2 * top - a top users display for Unix
5 * Originally written for BSD4.4 system by Christos Zoulas.
6 * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
7 * Order support hacked in from top-3.5beta6/machine/m_aix41.c
8 * by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
10 * AUTHOR: Christos Zoulas <christos@ee.cornell.edu>
11 * Steven Wallace <swallace@FreeBSD.org>
12 * Wolfram Schneider <wosch@FreeBSD.org>
13 * Thomas Moestl <tmoestl@gmx.net>
14 * Eitan Adler <eadler@FreeBSD.org>
19 #include <sys/errno.h>
20 #include <sys/fcntl.h>
21 #include <sys/param.h>
22 #include <sys/priority.h>
24 #include <sys/resource.h>
26 #include <sys/sysctl.h>
53 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
55 extern struct timeval timeout;
57 enum displaymodes displaymode;
58 static const int namelength = 10;
59 /* TOP_JID_LEN based on max of 999999 */
61 #define TOP_SWAP_LEN 5
63 /* get_process_info passes back a handle. This is what it looks like: */
66 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
67 int remaining; /* number of pointers remaining */
71 /* define what weighted cpu is. */
72 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
73 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
75 /* what we consider to be process size: */
76 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
78 #define RU(pp) (&(pp)->ki_rusage)
80 #define PCTCPU(pp) (pcpu[pp - pbase])
82 /* process state names for the "STATE" column of the display */
83 /* the extra nulls in the string "run" are for adding a slash and
84 the processor number when needed */
86 static const char *state_abbrev[] = {
87 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
93 /* values that we stash away in _init and use in later routines */
97 /* these are retrieved from the kernel in _init */
101 /* these are used in the get_ functions */
105 /* these are for calculating cpu state percentages */
107 static long cp_time[CPUSTATES];
108 static long cp_old[CPUSTATES];
109 static long cp_diff[CPUSTATES];
111 /* these are for detailing the process states */
113 static const char *procstatenames[] = {
114 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
115 " zombie, ", " waiting, ", " lock, ",
118 static int process_states[nitems(procstatenames)];
120 /* these are for detailing the cpu states */
122 static int cpu_states[CPUSTATES];
123 static const char *cpustatenames[] = {
124 "user", "nice", "system", "interrupt", "idle", NULL
127 /* these are for detailing the memory statistics */
129 static const char *memorynames[] = {
130 "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
133 static int memory_stats[nitems(memorynames)];
135 static const char *arcnames[] = {
136 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
139 static int arc_stats[nitems(arcnames)];
141 static const char *carcnames[] = {
142 "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
145 static int carc_stats[nitems(carcnames)];
147 static const char *swapnames[] = {
148 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
151 static int swap_stats[nitems(swapnames)];
154 /* these are for keeping track of the proc array */
157 static int onproc = -1;
159 static struct kinfo_proc *pbase;
160 static struct kinfo_proc **pref;
161 static struct kinfo_proc *previous_procs;
162 static struct kinfo_proc **previous_pref;
163 static int previous_proc_count = 0;
164 static int previous_proc_count_max = 0;
165 static int previous_thread;
167 /* data used for recalculating pctcpu */
169 static struct timespec proc_uptime;
170 static struct timeval proc_wall_time;
171 static struct timeval previous_wall_time;
172 static uint64_t previous_interval = 0;
174 /* total number of io operations */
175 static long total_inblock;
176 static long total_oublock;
177 static long total_majflt;
179 /* these are for getting the memory statistics */
181 static int arc_enabled;
182 static int carc_enabled;
183 static int pageshift; /* log base 2 of the pagesize */
185 /* define pagetok in terms of pageshift */
187 #define pagetok(size) ((size) << pageshift)
190 #define ki_swap(kip) \
191 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
194 * Sorting orders. The first element is the default.
196 static const char *ordernames[] = {
197 "cpu", "size", "res", "time", "pri", "threads",
198 "total", "read", "write", "fault", "vcsw", "ivcsw",
199 "jid", "swap", "pid", NULL
202 /* Per-cpu time states */
206 static unsigned long cpumask;
208 static long *pcpu_cp_time;
209 static long *pcpu_cp_old;
210 static long *pcpu_cp_diff;
211 static int *pcpu_cpu_states;
213 static int compare_swap(const void *a, const void *b);
214 static int compare_jid(const void *a, const void *b);
215 static int compare_pid(const void *a, const void *b);
216 static int compare_tid(const void *a, const void *b);
217 static const char *format_nice(const struct kinfo_proc *pp);
218 static void getsysctl(const char *name, void *ptr, size_t len);
219 static int swapmode(int *retavail, int *retfree);
220 static void update_layout(void);
221 static int find_uid(uid_t needle, int *haystack);
224 find_uid(uid_t needle, int *haystack)
228 for (; i < TOP_MAX_UIDS; ++i)
229 if ((uid_t)haystack[i] == needle)
235 toggle_pcpustats(void)
243 /* Adjust display based on ncpus and the ARC state. */
251 y_swap = 4 + arc_enabled + carc_enabled;
252 y_idlecursor = 5 + arc_enabled + carc_enabled;
253 y_message = 5 + arc_enabled + carc_enabled;
254 y_header = 6 + arc_enabled + carc_enabled;
255 y_procs = 7 + arc_enabled + carc_enabled;
256 Header_lines = 7 + arc_enabled + carc_enabled;
263 y_idlecursor += ncpus - 1;
264 y_message += ncpus - 1;
265 y_header += ncpus - 1;
266 y_procs += ncpus - 1;
267 Header_lines += ncpus - 1;
272 machine_init(struct statics *statics)
274 int i, j, empty, pagesize;
279 size = sizeof(smpmode);
280 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
282 sysctlbyname("kern.smp.active", &smpmode, &size,
284 size != sizeof(smpmode))
287 size = sizeof(arc_size);
288 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
289 NULL, 0) == 0 && arc_size != 0)
291 size = sizeof(carc_en);
293 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
294 NULL, 0) == 0 && carc_en == 1)
297 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
301 GETSYSCTL("kern.ccpu", ccpu);
303 /* this is used in calculating WCPU -- calculate it ahead of time */
304 logcpu = log(loaddouble(ccpu));
312 /* get the page size and calculate pageshift from it */
313 pagesize = getpagesize();
315 while (pagesize > 1) {
320 /* we only need the amount of log(2)1024 for our conversion */
321 pageshift -= LOG1024;
323 /* fill in the statics information */
324 statics->procstate_names = procstatenames;
325 statics->cpustate_names = cpustatenames;
326 statics->memory_names = memorynames;
328 statics->arc_names = arcnames;
330 statics->arc_names = NULL;
332 statics->carc_names = carcnames;
334 statics->carc_names = NULL;
335 statics->swap_names = swapnames;
336 statics->order_names = ordernames;
338 /* Allocate state for per-CPU stats. */
341 GETSYSCTL("kern.smp.maxcpus", maxcpu);
342 times = calloc(maxcpu * CPUSTATES, sizeof(long));
344 err(1, "calloc for kern.smp.maxcpus");
345 size = sizeof(long) * maxcpu * CPUSTATES;
346 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
347 err(1, "sysctlbyname kern.cp_times");
348 pcpu_cp_time = calloc(1, size);
349 maxid = (size / CPUSTATES / sizeof(long)) - 1;
350 for (i = 0; i <= maxid; i++) {
352 for (j = 0; empty && j < CPUSTATES; j++) {
353 if (times[i * CPUSTATES + j] != 0)
357 cpumask |= (1ul << i);
362 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
363 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
364 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
365 statics->ncpus = ncpus;
374 format_header(const char *uname_field)
376 static struct sbuf* header = NULL;
378 /* clean up from last time. */
379 if (header != NULL) {
382 header = sbuf_new_auto();
385 switch (displaymode) {
387 sbuf_printf(header, " %s", ps.thread_id ? " THR" : "PID");
388 sbuf_printf(header, "%*s", ps.jail ? TOP_JID_LEN : 0,
389 ps.jail ? " JID" : "");
390 sbuf_printf(header, " %-*.*s ", namelength, namelength, uname_field);
392 sbuf_cat(header, "THR ");
394 sbuf_cat(header, "PRI NICE SIZE RES ");
396 sbuf_printf(header, "%*s ", TOP_SWAP_LEN - 1, "SWAP");
398 sbuf_cat(header, "STATE ");
400 sbuf_cat(header, "C ");
402 sbuf_cat(header, "TIME ");
403 sbuf_printf(header, " %6s ", ps.wcpu ? "WCPU" : "CPU");
404 sbuf_cat(header, "COMMAND");
409 sbuf_printf(header, " %s%*s %-*.*s",
410 ps.thread_id ? " THR" : "PID",
411 ps.jail ? TOP_JID_LEN : 0, ps.jail ? " JID" : "",
412 namelength, namelength, uname_field);
413 sbuf_cat(header, " VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND");
418 assert("displaymode must not be set to DISP_MAX");
421 return sbuf_data(header);
424 static int swappgsin = -1;
425 static int swappgsout = -1;
429 get_system_info(struct system_info *si)
431 struct loadavg sysload;
433 struct timeval boottime;
434 uint64_t arc_stat, arc_stat2;
438 /* get the CPU stats */
439 size = (maxid + 1) * CPUSTATES * sizeof(long);
440 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
441 err(1, "sysctlbyname kern.cp_times");
442 GETSYSCTL("kern.cp_time", cp_time);
443 GETSYSCTL("vm.loadavg", sysload);
444 GETSYSCTL("kern.lastpid", lastpid);
446 /* convert load averages to doubles */
447 for (i = 0; i < 3; i++)
448 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
450 /* convert cp_time counts to percentages */
451 for (i = j = 0; i <= maxid; i++) {
452 if ((cpumask & (1ul << i)) == 0)
454 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
455 &pcpu_cp_time[j * CPUSTATES],
456 &pcpu_cp_old[j * CPUSTATES],
457 &pcpu_cp_diff[j * CPUSTATES]);
460 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
462 /* sum memory & swap statistics */
464 static unsigned int swap_delay = 0;
465 static int swapavail = 0;
466 static int swapfree = 0;
467 static long bufspace = 0;
468 static uint64_t nspgsin, nspgsout;
470 GETSYSCTL("vfs.bufspace", bufspace);
471 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
472 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
473 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
474 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
475 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
476 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
477 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
478 /* convert memory stats to Kbytes */
479 memory_stats[0] = pagetok(memory_stats[0]);
480 memory_stats[1] = pagetok(memory_stats[1]);
481 memory_stats[2] = pagetok(memory_stats[2]);
482 memory_stats[3] = pagetok(memory_stats[3]);
483 memory_stats[4] = bufspace / 1024;
484 memory_stats[5] = pagetok(memory_stats[5]);
485 memory_stats[6] = -1;
493 /* compute differences between old and new swap statistic */
495 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
496 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
500 swappgsout = nspgsout;
502 /* call CPU heavy swapmode() only for changes */
503 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
504 swap_stats[3] = swapmode(&swapavail, &swapfree);
505 swap_stats[0] = swapavail;
506 swap_stats[1] = swapavail - swapfree;
507 swap_stats[2] = swapfree;
514 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
515 arc_stats[0] = arc_stat >> 10;
516 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
517 arc_stats[1] = arc_stat >> 10;
518 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
519 arc_stats[2] = arc_stat >> 10;
520 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
521 arc_stats[3] = arc_stat >> 10;
522 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
523 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
524 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
525 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
526 arc_stats[5] = arc_stat >> 10;
530 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
531 carc_stats[0] = arc_stat >> 10;
532 carc_stats[2] = arc_stat >> 10; /* For ratio */
533 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
534 carc_stats[1] = arc_stat >> 10;
535 si->carc = carc_stats;
538 /* set arrays and strings */
540 si->cpustates = pcpu_cpu_states;
543 si->cpustates = cpu_states;
546 si->memory = memory_stats;
547 si->swap = swap_stats;
551 si->last_pid = lastpid;
557 * Print how long system has been up.
558 * (Found by looking getting "boottime" from the kernel)
561 mib[1] = KERN_BOOTTIME;
562 size = sizeof(boottime);
563 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
564 boottime.tv_sec != 0) {
565 si->boottime = boottime;
567 si->boottime.tv_sec = -1;
571 #define NOPROC ((void *)-1)
574 * We need to compare data from the old process entry with the new
576 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
577 * structure to cache the mapping. We also use a negative cache pointer
578 * of NOPROC to avoid duplicate lookups.
579 * XXX: this could be done when the actual processes are fetched, we do
580 * it here out of laziness.
582 static const struct kinfo_proc *
583 get_old_proc(struct kinfo_proc *pp)
585 const struct kinfo_proc * const *oldpp, *oldp;
588 * If this is the first fetch of the kinfo_procs then we don't have
589 * any previous entries.
591 if (previous_proc_count == 0)
593 /* negative cache? */
594 if (pp->ki_udata == NOPROC)
597 if (pp->ki_udata != NULL)
598 return (pp->ki_udata);
601 * 1) look up based on pid.
602 * 2) compare process start.
603 * If we fail here, then setup a negative cache entry, otherwise
606 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
607 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
609 pp->ki_udata = NOPROC;
613 if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
614 pp->ki_udata = NOPROC;
622 * Return the total amount of IO done in blocks in/out and faults.
623 * store the values individually in the pointers passed in.
626 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
627 long *vcsw, long *ivcsw)
629 const struct kinfo_proc *oldp;
630 static struct kinfo_proc dummy;
633 oldp = get_old_proc(pp);
635 memset(&dummy, 0, sizeof(dummy));
638 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
639 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
640 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
641 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
642 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
644 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
645 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
646 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
651 * If there was a previous update, use the delta in ki_runtime over
652 * the previous interval to calculate pctcpu. Otherwise, fall back
653 * to using the kernel's ki_pctcpu.
656 proc_calc_pctcpu(struct kinfo_proc *pp)
658 const struct kinfo_proc *oldp;
660 if (previous_interval != 0) {
661 oldp = get_old_proc(pp);
663 return ((double)(pp->ki_runtime - oldp->ki_runtime)
664 / previous_interval);
667 * If this process/thread was created during the previous
668 * interval, charge it's total runtime to the previous
671 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
672 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
673 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
674 return ((double)pp->ki_runtime / previous_interval);
676 return (pctdouble(pp->ki_pctcpu));
680 * Return true if this process has used any CPU time since the
684 proc_used_cpu(struct kinfo_proc *pp)
686 const struct kinfo_proc *oldp;
688 oldp = get_old_proc(pp);
690 return (PCTCPU(pp) != 0);
691 return (pp->ki_runtime != oldp->ki_runtime ||
692 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
693 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
697 * Return the total number of block in/out and faults by a process.
700 get_io_total(const struct kinfo_proc *pp)
704 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
707 static struct handle handle;
710 get_process_info(struct system_info *si, struct process_select *sel,
711 int (*compare)(const void *, const void *))
716 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
719 struct kinfo_proc **prefp;
720 struct kinfo_proc *pp;
721 struct timespec previous_proc_uptime;
724 * If thread state was toggled, don't cache the previous processes.
726 if (previous_thread != sel->thread)
728 previous_thread = sel->thread;
731 * Save the previous process info.
733 if (previous_proc_count_max < nproc) {
734 free(previous_procs);
735 previous_procs = calloc(nproc, sizeof(*previous_procs));
737 previous_pref = calloc(nproc, sizeof(*previous_pref));
738 if (previous_procs == NULL || previous_pref == NULL) {
739 fprintf(stderr, "top: Out of memory.\n");
740 quit(TOP_EX_SYS_ERROR);
742 previous_proc_count_max = nproc;
745 for (i = 0; i < nproc; i++)
746 previous_pref[i] = &previous_procs[i];
747 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
748 qsort(previous_pref, nproc, sizeof(*previous_pref),
749 ps.thread ? compare_tid : compare_pid);
751 previous_proc_count = nproc;
752 previous_proc_uptime = proc_uptime;
753 previous_wall_time = proc_wall_time;
754 previous_interval = 0;
756 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
758 gettimeofday(&proc_wall_time, NULL);
759 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
760 memset(&proc_uptime, 0, sizeof(proc_uptime));
761 else if (previous_proc_uptime.tv_sec != 0 &&
762 previous_proc_uptime.tv_nsec != 0) {
763 previous_interval = (proc_uptime.tv_sec -
764 previous_proc_uptime.tv_sec) * 1000000;
765 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
767 previous_interval -= 1000000;
770 previous_interval += nsec / 1000;
772 if (nproc > onproc) {
773 pref = realloc(pref, sizeof(*pref) * nproc);
774 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
777 if (pref == NULL || pbase == NULL || pcpu == NULL) {
778 fprintf(stderr, "top: Out of memory.\n");
779 quit(TOP_EX_SYS_ERROR);
781 /* get a pointer to the states summary array */
782 si->procstates = process_states;
784 /* count up process states and get pointers to interesting procs */
790 memset(process_states, 0, sizeof(process_states));
792 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
794 if (pp->ki_stat == 0)
798 if (!sel->self && pp->ki_pid == mypid && sel->pid == -1)
802 if (!sel->system && (pp->ki_flag & P_SYSTEM) && sel->pid == -1)
803 /* skip system process */
806 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
808 total_inblock += p_inblock;
809 total_oublock += p_oublock;
810 total_majflt += p_majflt;
812 process_states[(unsigned char)pp->ki_stat]++;
814 if (pp->ki_stat == SZOMB)
818 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD && sel->pid == -1)
819 /* skip kernel idle process */
822 PCTCPU(pp) = proc_calc_pctcpu(pp);
823 if (sel->thread && PCTCPU(pp) > 1.0)
825 if (displaymode == DISP_CPU && !sel->idle &&
826 (!proc_used_cpu(pp) ||
827 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
828 /* skip idle or non-running processes */
831 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
832 /* skip processes that aren't doing I/O */
835 if (sel->jid != -1 && pp->ki_jid != sel->jid)
836 /* skip proc. that don't belong to the selected JID */
839 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
840 /* skip proc. that don't belong to the selected UID */
843 if (sel->pid != -1 && pp->ki_pid != sel->pid)
850 /* if requested, sort the "interesting" processes */
852 qsort(pref, active_procs, sizeof(*pref), compare);
854 /* remember active and total counts */
855 si->p_total = total_procs;
856 si->p_pactive = pref_len = active_procs;
858 /* pass back a handle */
859 handle.next_proc = pref;
860 handle.remaining = active_procs;
865 format_next_process(struct handle * xhandle, char *(*get_userid)(int), int flags)
867 struct kinfo_proc *pp;
868 const struct kinfo_proc *oldp;
872 struct rusage ru, *rup;
876 static struct sbuf* procbuf = NULL;
878 /* clean up from last time. */
879 if (procbuf != NULL) {
882 procbuf = sbuf_new_auto();
886 /* find and remember the next proc structure */
887 pp = *(xhandle->next_proc++);
888 xhandle->remaining--;
890 /* get the process's command name */
891 if ((pp->ki_flag & P_INMEM) == 0) {
893 * Print swapped processes as <pname>
897 len = strlen(pp->ki_comm);
898 if (len > sizeof(pp->ki_comm) - 3)
899 len = sizeof(pp->ki_comm) - 3;
900 memmove(pp->ki_comm + 1, pp->ki_comm, len);
901 pp->ki_comm[0] = '<';
902 pp->ki_comm[len + 1] = '>';
903 pp->ki_comm[len + 2] = '\0';
907 * Convert the process's runtime from microseconds to seconds. This
908 * time includes the interrupt time although that is not wanted here.
909 * ps(1) is similarly sloppy.
911 cputime = (pp->ki_runtime + 500000) / 1000000;
913 /* generate "STATE" field */
914 switch (state = pp->ki_stat) {
916 if (smpmode && pp->ki_oncpu != NOCPU)
917 sprintf(status, "CPU%d", pp->ki_oncpu);
919 strcpy(status, "RUN");
922 if (pp->ki_kiflag & KI_LOCKBLOCK) {
923 sprintf(status, "*%.6s", pp->ki_lockname);
928 sprintf(status, "%.6s", pp->ki_wmesg);
932 if (state < nitems(state_abbrev)) {
933 sprintf(status, "%.6s", state_abbrev[state]);
935 sprintf(status, "?%5zu", state);
940 cmdbuf = calloc(screen_width + 1, 1);
941 if (cmdbuf == NULL) {
942 warn("calloc(%d)", screen_width + 1);
946 if (!(flags & FMT_SHOWARGS)) {
947 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
949 snprintf(cmdbuf, screen_width, "%s{%s%s}", pp->ki_comm,
950 pp->ki_tdname, pp->ki_moretdname);
952 snprintf(cmdbuf, screen_width, "%s", pp->ki_comm);
955 if (pp->ki_flag & P_SYSTEM ||
956 (args = kvm_getargv(kd, pp, screen_width)) == NULL ||
958 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
960 snprintf(cmdbuf, screen_width,
961 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
964 snprintf(cmdbuf, screen_width,
965 "[%s]", pp->ki_comm);
974 argbuflen = screen_width * 4;
975 argbuf = calloc(argbuflen + 1, 1);
976 if (argbuf == NULL) {
977 warn("calloc(%zu)", argbuflen + 1);
984 /* Extract cmd name from argv */
985 cmd = basename(*args);
987 for (; (src = *args++) != NULL; ) {
990 len = (argbuflen - (dst - argbuf) - 1) / 4;
992 MIN(strlen(src), len),
993 VIS_NL | VIS_CSTYLE);
996 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
997 *dst++ = ' '; /* add delimiting space */
999 if (dst != argbuf && dst[-1] == ' ')
1003 if (strcmp(cmd, pp->ki_comm) != 0) {
1004 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1006 snprintf(cmdbuf, screen_width,
1007 "%s (%s){%s%s}", argbuf,
1008 pp->ki_comm, pp->ki_tdname,
1011 snprintf(cmdbuf, screen_width,
1012 "%s (%s)", argbuf, pp->ki_comm);
1014 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1016 snprintf(cmdbuf, screen_width,
1017 "%s{%s%s}", argbuf, pp->ki_tdname,
1020 strlcpy(cmdbuf, argbuf, screen_width);
1026 if (displaymode == DISP_IO) {
1027 oldp = get_old_proc(pp);
1029 ru.ru_inblock = RU(pp)->ru_inblock -
1030 RU(oldp)->ru_inblock;
1031 ru.ru_oublock = RU(pp)->ru_oublock -
1032 RU(oldp)->ru_oublock;
1033 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1034 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1035 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1040 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1041 s_tot = total_inblock + total_oublock + total_majflt;
1043 sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1046 sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1048 sbuf_printf(procbuf, "%-*.*s", namelength, namelength, (*get_userid)(pp->ki_ruid));
1049 sbuf_printf(procbuf, "%6ld ", rup->ru_nvcsw);
1050 sbuf_printf(procbuf, "%6ld ", rup->ru_nivcsw);
1051 sbuf_printf(procbuf, "%6ld ", rup->ru_inblock);
1052 sbuf_printf(procbuf, "%6ld ", rup->ru_oublock);
1053 sbuf_printf(procbuf, "%6ld ", rup->ru_majflt);
1054 sbuf_printf(procbuf, "%6ld ", p_tot);
1055 sbuf_printf(procbuf, "%6.2f%% ", s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot));
1058 sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1060 sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1062 sbuf_printf(procbuf, "%-*.*s ", namelength, namelength, (*get_userid)(pp->ki_ruid));
1065 sbuf_printf(procbuf, "%4d ", pp->ki_numthreads);
1068 sbuf_printf(procbuf, "%3d ", pp->ki_pri.pri_level - PZERO);
1069 sbuf_printf(procbuf, "%4s", format_nice(pp));
1070 sbuf_printf(procbuf, "%7s ", format_k(PROCSIZE(pp)));
1071 sbuf_printf(procbuf, "%6s ", format_k(pagetok(pp->ki_rssize)));
1073 sbuf_printf(procbuf, "%*s ",
1075 format_k(pagetok(ki_swap(pp))));
1077 sbuf_printf(procbuf, "%-6.6s ", status);
1080 if (state == SRUN && pp->ki_oncpu != NOCPU) {
1083 cpu = pp->ki_lastcpu;
1085 sbuf_printf(procbuf, "%3d ", cpu);
1087 sbuf_printf(procbuf, "%6s ", format_time(cputime));
1088 sbuf_printf(procbuf, "%6.2f%% ", ps.wcpu ? 100.0 * weighted_cpu(PCTCPU(pp), pp) : 100.0 * PCTCPU(pp));
1090 sbuf_printf(procbuf, "%s", printable(cmdbuf));
1092 return (sbuf_data(procbuf));
1096 getsysctl(const char *name, void *ptr, size_t len)
1100 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1101 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1103 quit(TOP_EX_SYS_ERROR);
1106 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1107 name, (unsigned long)len, (unsigned long)nlen);
1108 quit(TOP_EX_SYS_ERROR);
1113 format_nice(const struct kinfo_proc *pp)
1115 const char *fifo, *kproc;
1117 static char nicebuf[4 + 1];
1119 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1120 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1121 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1126 * XXX: the kernel doesn't tell us the original rtprio and
1127 * doesn't really know what it was, so to recover it we
1128 * must be more chummy with the implementation than the
1129 * implementation is with itself. pri_user gives a
1130 * constant "base" priority, but is only initialized
1131 * properly for user threads. pri_native gives what the
1132 * kernel calls the "base" priority, but it isn't constant
1133 * since it is changed by priority propagation. pri_native
1134 * also isn't properly initialized for all threads, but it
1135 * is properly initialized for kernel realtime and idletime
1136 * threads. Thus we use pri_user for the base priority of
1137 * user threads (it is always correct) and pri_native for
1138 * the base priority of kernel realtime and idletime threads
1139 * (there is nothing better, and it is usually correct).
1141 * The field width and thus the buffer are too small for
1142 * values like "kr31F", but such values shouldn't occur,
1143 * and if they do then the tailing "F" is not displayed.
1145 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1146 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1147 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1148 kproc, rtpri, fifo);
1151 if (pp->ki_flag & P_KPROC)
1153 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1156 /* XXX: as above. */
1157 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1158 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1159 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1160 kproc, rtpri, fifo);
1168 /* comparison routines for qsort */
1171 compare_pid(const void *p1, const void *p2)
1173 const struct kinfo_proc * const *pp1 = p1;
1174 const struct kinfo_proc * const *pp2 = p2;
1176 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1178 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1182 compare_tid(const void *p1, const void *p2)
1184 const struct kinfo_proc * const *pp1 = p1;
1185 const struct kinfo_proc * const *pp2 = p2;
1187 assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1189 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1193 * proc_compare - comparison function for "qsort"
1194 * Compares the resource consumption of two processes using five
1195 * distinct keys. The keys (in descending order of importance) are:
1196 * percent cpu, cpu ticks, state, resident set size, total virtual
1197 * memory usage. The process states are ordered as follows (from least
1198 * to most important): WAIT, zombie, sleep, stop, start, run. The
1199 * array declaration below maps a process state index into a number
1200 * that reflects this ordering.
1203 static int sorted_state[] = {
1206 1, /* ABANDONED (WAIT) */
1214 #define ORDERKEY_PCTCPU(a, b) do { \
1217 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1218 weighted_cpu(PCTCPU((a)), (a)); \
1220 diff = PCTCPU((b)) - PCTCPU((a)); \
1222 return (diff > 0 ? 1 : -1); \
1225 #define ORDERKEY_CPTICKS(a, b) do { \
1226 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1228 return (diff > 0 ? 1 : -1); \
1231 #define ORDERKEY_STATE(a, b) do { \
1232 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1234 return (diff > 0 ? 1 : -1); \
1237 #define ORDERKEY_PRIO(a, b) do { \
1238 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1240 return (diff > 0 ? 1 : -1); \
1243 #define ORDERKEY_THREADS(a, b) do { \
1244 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1246 return (diff > 0 ? 1 : -1); \
1249 #define ORDERKEY_RSSIZE(a, b) do { \
1250 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1252 return (diff > 0 ? 1 : -1); \
1255 #define ORDERKEY_MEM(a, b) do { \
1256 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1258 return (diff > 0 ? 1 : -1); \
1261 #define ORDERKEY_JID(a, b) do { \
1262 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1264 return (diff > 0 ? 1 : -1); \
1267 #define ORDERKEY_SWAP(a, b) do { \
1268 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1270 return (diff > 0 ? 1 : -1); \
1273 /* compare_cpu - the comparison function for sorting by cpu percentage */
1276 compare_cpu(const void *arg1, const void *arg2)
1278 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1279 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1281 ORDERKEY_PCTCPU(p1, p2);
1282 ORDERKEY_CPTICKS(p1, p2);
1283 ORDERKEY_STATE(p1, p2);
1284 ORDERKEY_PRIO(p1, p2);
1285 ORDERKEY_RSSIZE(p1, p2);
1286 ORDERKEY_MEM(p1, p2);
1291 /* compare_size - the comparison function for sorting by total memory usage */
1294 compare_size(const void *arg1, const void *arg2)
1296 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1297 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1299 ORDERKEY_MEM(p1, p2);
1300 ORDERKEY_RSSIZE(p1, p2);
1301 ORDERKEY_PCTCPU(p1, p2);
1302 ORDERKEY_CPTICKS(p1, p2);
1303 ORDERKEY_STATE(p1, p2);
1304 ORDERKEY_PRIO(p1, p2);
1309 /* compare_res - the comparison function for sorting by resident set size */
1312 compare_res(const void *arg1, const void *arg2)
1314 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1315 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1317 ORDERKEY_RSSIZE(p1, p2);
1318 ORDERKEY_MEM(p1, p2);
1319 ORDERKEY_PCTCPU(p1, p2);
1320 ORDERKEY_CPTICKS(p1, p2);
1321 ORDERKEY_STATE(p1, p2);
1322 ORDERKEY_PRIO(p1, p2);
1327 /* compare_time - the comparison function for sorting by total cpu time */
1330 compare_time(const void *arg1, const void *arg2)
1332 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1333 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1335 ORDERKEY_CPTICKS(p1, p2);
1336 ORDERKEY_PCTCPU(p1, p2);
1337 ORDERKEY_STATE(p1, p2);
1338 ORDERKEY_PRIO(p1, p2);
1339 ORDERKEY_RSSIZE(p1, p2);
1340 ORDERKEY_MEM(p1, p2);
1345 /* compare_prio - the comparison function for sorting by priority */
1348 compare_prio(const void *arg1, const void *arg2)
1350 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1351 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1353 ORDERKEY_PRIO(p1, p2);
1354 ORDERKEY_CPTICKS(p1, p2);
1355 ORDERKEY_PCTCPU(p1, p2);
1356 ORDERKEY_STATE(p1, p2);
1357 ORDERKEY_RSSIZE(p1, p2);
1358 ORDERKEY_MEM(p1, p2);
1363 /* compare_threads - the comparison function for sorting by threads */
1365 compare_threads(const void *arg1, const void *arg2)
1367 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1368 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1370 ORDERKEY_THREADS(p1, p2);
1371 ORDERKEY_PCTCPU(p1, p2);
1372 ORDERKEY_CPTICKS(p1, p2);
1373 ORDERKEY_STATE(p1, p2);
1374 ORDERKEY_PRIO(p1, p2);
1375 ORDERKEY_RSSIZE(p1, p2);
1376 ORDERKEY_MEM(p1, p2);
1381 /* compare_jid - the comparison function for sorting by jid */
1383 compare_jid(const void *arg1, const void *arg2)
1385 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1386 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1388 ORDERKEY_JID(p1, p2);
1389 ORDERKEY_PCTCPU(p1, p2);
1390 ORDERKEY_CPTICKS(p1, p2);
1391 ORDERKEY_STATE(p1, p2);
1392 ORDERKEY_PRIO(p1, p2);
1393 ORDERKEY_RSSIZE(p1, p2);
1394 ORDERKEY_MEM(p1, p2);
1399 /* compare_swap - the comparison function for sorting by swap */
1401 compare_swap(const void *arg1, const void *arg2)
1403 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1404 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1406 ORDERKEY_SWAP(p1, p2);
1407 ORDERKEY_PCTCPU(p1, p2);
1408 ORDERKEY_CPTICKS(p1, p2);
1409 ORDERKEY_STATE(p1, p2);
1410 ORDERKEY_PRIO(p1, p2);
1411 ORDERKEY_RSSIZE(p1, p2);
1412 ORDERKEY_MEM(p1, p2);
1417 /* assorted comparison functions for sorting by i/o */
1420 compare_iototal(const void *arg1, const void *arg2)
1422 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1423 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1425 return (get_io_total(p2) - get_io_total(p1));
1429 compare_ioread(const void *arg1, const void *arg2)
1431 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1432 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1433 long dummy, inp1, inp2;
1435 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1436 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1438 return (inp2 - inp1);
1442 compare_iowrite(const void *arg1, const void *arg2)
1444 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1445 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1446 long dummy, oup1, oup2;
1448 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1449 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1451 return (oup2 - oup1);
1455 compare_iofault(const void *arg1, const void *arg2)
1457 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1458 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1459 long dummy, flp1, flp2;
1461 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1462 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1464 return (flp2 - flp1);
1468 compare_vcsw(const void *arg1, const void *arg2)
1470 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1471 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1472 long dummy, flp1, flp2;
1474 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1475 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1477 return (flp2 - flp1);
1481 compare_ivcsw(const void *arg1, const void *arg2)
1483 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1484 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1485 long dummy, flp1, flp2;
1487 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1488 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1490 return (flp2 - flp1);
1493 int (*compares[])(const void *arg1, const void *arg2) = {
1513 swapmode(int *retavail, int *retfree)
1516 struct kvm_swap swapary[1];
1517 static int pagesize = 0;
1518 static unsigned long swap_maxpages = 0;
1523 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1525 n = kvm_getswapinfo(kd, swapary, 1, 0);
1526 if (n < 0 || swapary[0].ksw_total == 0)
1530 pagesize = getpagesize();
1531 if (swap_maxpages == 0)
1532 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1534 /* ksw_total contains the total size of swap all devices which may
1535 exceed the maximum swap size allocatable in the system */
1536 if ( swapary[0].ksw_total > swap_maxpages )
1537 swapary[0].ksw_total = swap_maxpages;
1539 *retavail = CONVERT(swapary[0].ksw_total);
1540 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1544 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);