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)];
155 /* these are for keeping track of the proc array */
158 static int onproc = -1;
160 static struct kinfo_proc *pbase;
161 static struct kinfo_proc **pref;
162 static struct kinfo_proc *previous_procs;
163 static struct kinfo_proc **previous_pref;
164 static int previous_proc_count = 0;
165 static int previous_proc_count_max = 0;
166 static int previous_thread;
168 /* data used for recalculating pctcpu */
170 static struct timespec proc_uptime;
171 static struct timeval proc_wall_time;
172 static struct timeval previous_wall_time;
173 static uint64_t previous_interval = 0;
175 /* total number of io operations */
176 static long total_inblock;
177 static long total_oublock;
178 static long total_majflt;
180 /* these are for getting the memory statistics */
182 static int arc_enabled;
183 static int carc_enabled;
184 static int pageshift; /* log base 2 of the pagesize */
186 /* define pagetok in terms of pageshift */
188 #define pagetok(size) ((size) << pageshift)
191 #define ki_swap(kip) \
192 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
195 * Sorting orders. The first element is the default.
197 static const char *ordernames[] = {
198 "cpu", "size", "res", "time", "pri", "threads",
199 "total", "read", "write", "fault", "vcsw", "ivcsw",
200 "jid", "swap", "pid", NULL
203 /* Per-cpu time states */
207 static unsigned long cpumask;
209 static long *pcpu_cp_time;
210 static long *pcpu_cp_old;
211 static long *pcpu_cp_diff;
212 static int *pcpu_cpu_states;
214 /* Battery units and states */
215 static int battery_units;
216 static int battery_life;
218 static int compare_swap(const void *a, const void *b);
219 static int compare_jid(const void *a, const void *b);
220 static int compare_pid(const void *a, const void *b);
221 static int compare_tid(const void *a, const void *b);
222 static const char *format_nice(const struct kinfo_proc *pp);
223 static void getsysctl(const char *name, void *ptr, size_t len);
224 static int swapmode(int *retavail, int *retfree);
225 static void update_layout(void);
226 static int find_uid(uid_t needle, int *haystack);
227 static int cmd_matches(struct kinfo_proc *, const char *);
230 find_uid(uid_t needle, int *haystack)
234 for (; i < TOP_MAX_UIDS; ++i)
235 if ((uid_t)haystack[i] == needle)
241 toggle_pcpustats(void)
249 /* Adjust display based on ncpus and the ARC state. */
257 y_swap = 3 + arc_enabled + carc_enabled + has_swap;
258 y_idlecursor = 4 + arc_enabled + carc_enabled + has_swap;
259 y_message = 4 + arc_enabled + carc_enabled + has_swap;
260 y_header = 5 + arc_enabled + carc_enabled + has_swap;
261 y_procs = 6 + arc_enabled + carc_enabled + has_swap;
262 Header_lines = 6 + arc_enabled + carc_enabled + has_swap;
269 y_idlecursor += ncpus - 1;
270 y_message += ncpus - 1;
271 y_header += ncpus - 1;
272 y_procs += ncpus - 1;
273 Header_lines += ncpus - 1;
278 machine_init(struct statics *statics)
280 int i, j, empty, pagesize;
282 int carc_en, nswapdev;
285 size = sizeof(smpmode);
286 if (sysctlbyname("kern.smp.active", &smpmode, &size, NULL, 0) != 0 ||
287 size != sizeof(smpmode))
290 size = sizeof(arc_size);
291 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
292 NULL, 0) == 0 && arc_size != 0)
294 size = sizeof(carc_en);
296 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
297 NULL, 0) == 0 && carc_en == 1)
300 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
304 size = sizeof(nswapdev);
305 if (sysctlbyname("vm.nswapdev", &nswapdev, &size, NULL,
306 0) == 0 && nswapdev != 0)
309 GETSYSCTL("kern.ccpu", ccpu);
311 /* this is used in calculating WCPU -- calculate it ahead of time */
312 logcpu = log(loaddouble(ccpu));
320 /* get the page size and calculate pageshift from it */
321 pagesize = getpagesize();
323 while (pagesize > 1) {
328 /* we only need the amount of log(2)1024 for our conversion */
329 pageshift -= LOG1024;
331 /* fill in the statics information */
332 statics->procstate_names = procstatenames;
333 statics->cpustate_names = cpustatenames;
334 statics->memory_names = memorynames;
336 statics->arc_names = arcnames;
338 statics->arc_names = NULL;
340 statics->carc_names = carcnames;
342 statics->carc_names = NULL;
344 statics->swap_names = swapnames;
346 statics->swap_names = NULL;
347 statics->order_names = ordernames;
349 /* Allocate state for per-CPU stats. */
352 GETSYSCTL("kern.smp.maxcpus", maxcpu);
353 times = calloc(maxcpu * CPUSTATES, sizeof(long));
355 err(1, "calloc for kern.smp.maxcpus");
356 size = sizeof(long) * maxcpu * CPUSTATES;
357 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
358 err(1, "sysctlbyname kern.cp_times");
359 pcpu_cp_time = calloc(1, size);
360 maxid = (size / CPUSTATES / sizeof(long)) - 1;
361 for (i = 0; i <= maxid; i++) {
363 for (j = 0; empty && j < CPUSTATES; j++) {
364 if (times[i * CPUSTATES + j] != 0)
368 cpumask |= (1ul << i);
373 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
374 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
375 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
376 statics->ncpus = ncpus;
378 /* Allocate state of battery units reported via ACPI. */
381 sysctlbyname("hw.acpi.battery.units", &battery_units, &size, NULL, 0);
382 statics->nbatteries = battery_units;
391 format_header(const char *uname_field)
393 static struct sbuf* header = NULL;
395 /* clean up from last time. */
396 if (header != NULL) {
399 header = sbuf_new_auto();
402 switch (displaymode) {
404 sbuf_printf(header, " %s", ps.thread_id ? " THR" : "PID");
405 sbuf_printf(header, "%*s", ps.jail ? TOP_JID_LEN : 0,
406 ps.jail ? " JID" : "");
407 sbuf_printf(header, " %-*.*s ", namelength, namelength, uname_field);
409 sbuf_cat(header, "THR ");
411 sbuf_cat(header, "PRI NICE SIZE RES ");
413 sbuf_printf(header, "%*s ", TOP_SWAP_LEN - 1, "SWAP");
415 sbuf_cat(header, "STATE ");
417 sbuf_cat(header, "C ");
419 sbuf_cat(header, "TIME ");
420 sbuf_printf(header, " %6s ", ps.wcpu ? "WCPU" : "CPU");
421 sbuf_cat(header, "COMMAND");
426 sbuf_printf(header, " %s%*s %-*.*s",
427 ps.thread_id ? " THR" : "PID",
428 ps.jail ? TOP_JID_LEN : 0, ps.jail ? " JID" : "",
429 namelength, namelength, uname_field);
430 sbuf_cat(header, " VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND");
435 assert("displaymode must not be set to DISP_MAX");
438 return sbuf_data(header);
441 static int swappgsin = -1;
442 static int swappgsout = -1;
446 get_system_info(struct system_info *si)
448 struct loadavg sysload;
450 struct timeval boottime;
451 uint64_t arc_stat, arc_stat2;
455 /* get the CPU stats */
456 size = (maxid + 1) * CPUSTATES * sizeof(long);
457 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
458 err(1, "sysctlbyname kern.cp_times");
459 GETSYSCTL("kern.cp_time", cp_time);
460 GETSYSCTL("vm.loadavg", sysload);
461 GETSYSCTL("kern.lastpid", lastpid);
463 /* convert load averages to doubles */
464 for (i = 0; i < 3; i++)
465 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
467 /* convert cp_time counts to percentages */
468 for (i = j = 0; i <= maxid; i++) {
469 if ((cpumask & (1ul << i)) == 0)
471 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
472 &pcpu_cp_time[j * CPUSTATES],
473 &pcpu_cp_old[j * CPUSTATES],
474 &pcpu_cp_diff[j * CPUSTATES]);
477 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
479 /* sum memory & swap statistics */
481 static unsigned int swap_delay = 0;
482 static int swapavail = 0;
483 static int swapfree = 0;
484 static long bufspace = 0;
485 static uint64_t nspgsin, nspgsout;
487 GETSYSCTL("vfs.bufspace", bufspace);
488 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
489 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
490 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
491 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
492 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
493 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
494 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
495 /* convert memory stats to Kbytes */
496 memory_stats[0] = pagetok(memory_stats[0]);
497 memory_stats[1] = pagetok(memory_stats[1]);
498 memory_stats[2] = pagetok(memory_stats[2]);
499 memory_stats[3] = pagetok(memory_stats[3]);
500 memory_stats[4] = bufspace / 1024;
501 memory_stats[5] = pagetok(memory_stats[5]);
502 memory_stats[6] = -1;
510 /* compute differences between old and new swap statistic */
512 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
513 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
517 swappgsout = nspgsout;
519 /* call CPU heavy swapmode() only for changes */
520 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
521 swap_stats[3] = swapmode(&swapavail, &swapfree);
522 swap_stats[0] = swapavail;
523 swap_stats[1] = swapavail - swapfree;
524 swap_stats[2] = swapfree;
531 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
532 arc_stats[0] = arc_stat >> 10;
533 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
534 arc_stats[1] = arc_stat >> 10;
535 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
536 arc_stats[2] = arc_stat >> 10;
537 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
538 arc_stats[3] = arc_stat >> 10;
539 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
540 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
541 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
542 GETSYSCTL("kstat.zfs.misc.arcstats.bonus_size", arc_stat);
543 arc_stats[5] = arc_stat >> 10;
544 GETSYSCTL("kstat.zfs.misc.arcstats.dnode_size", arc_stat);
545 arc_stats[5] += arc_stat >> 10;
546 GETSYSCTL("kstat.zfs.misc.arcstats.dbuf_size", arc_stat);
547 arc_stats[5] += arc_stat >> 10;
551 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
552 carc_stats[0] = arc_stat >> 10;
553 carc_stats[2] = arc_stat >> 10; /* For ratio */
554 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
555 carc_stats[1] = arc_stat >> 10;
556 si->carc = carc_stats;
559 /* set arrays and strings */
561 si->cpustates = pcpu_cpu_states;
564 si->cpustates = cpu_states;
567 si->memory = memory_stats;
568 si->swap = swap_stats;
572 si->last_pid = lastpid;
578 * Print how long system has been up.
579 * (Found by looking getting "boottime" from the kernel)
582 mib[1] = KERN_BOOTTIME;
583 size = sizeof(boottime);
584 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
585 boottime.tv_sec != 0) {
586 si->boottime = boottime;
588 si->boottime.tv_sec = -1;
592 if (battery_units > 0) {
593 GETSYSCTL("hw.acpi.battery.life", battery_life);
595 si->battery = battery_life;
598 #define NOPROC ((void *)-1)
601 * We need to compare data from the old process entry with the new
603 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
604 * structure to cache the mapping. We also use a negative cache pointer
605 * of NOPROC to avoid duplicate lookups.
606 * XXX: this could be done when the actual processes are fetched, we do
607 * it here out of laziness.
609 static const struct kinfo_proc *
610 get_old_proc(struct kinfo_proc *pp)
612 const struct kinfo_proc * const *oldpp, *oldp;
615 * If this is the first fetch of the kinfo_procs then we don't have
616 * any previous entries.
618 if (previous_proc_count == 0)
620 /* negative cache? */
621 if (pp->ki_udata == NOPROC)
624 if (pp->ki_udata != NULL)
625 return (pp->ki_udata);
628 * 1) look up based on pid.
629 * 2) compare process start.
630 * If we fail here, then setup a negative cache entry, otherwise
633 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
634 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
636 pp->ki_udata = NOPROC;
640 if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
641 pp->ki_udata = NOPROC;
644 pp->ki_udata = __DECONST(void *, oldp);
649 * Return the total amount of IO done in blocks in/out and faults.
650 * store the values individually in the pointers passed in.
653 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
654 long *vcsw, long *ivcsw)
656 const struct kinfo_proc *oldp;
657 static struct kinfo_proc dummy;
660 oldp = get_old_proc(__DECONST(struct kinfo_proc *, pp));
662 memset(&dummy, 0, sizeof(dummy));
665 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
666 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
667 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
668 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
669 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
671 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
672 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
673 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
678 * If there was a previous update, use the delta in ki_runtime over
679 * the previous interval to calculate pctcpu. Otherwise, fall back
680 * to using the kernel's ki_pctcpu.
683 proc_calc_pctcpu(struct kinfo_proc *pp)
685 const struct kinfo_proc *oldp;
687 if (previous_interval != 0) {
688 oldp = get_old_proc(pp);
690 return ((double)(pp->ki_runtime - oldp->ki_runtime)
691 / previous_interval);
694 * If this process/thread was created during the previous
695 * interval, charge it's total runtime to the previous
698 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
699 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
700 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
701 return ((double)pp->ki_runtime / previous_interval);
703 return (pctdouble(pp->ki_pctcpu));
707 * Return true if this process has used any CPU time since the
711 proc_used_cpu(struct kinfo_proc *pp)
713 const struct kinfo_proc *oldp;
715 oldp = get_old_proc(pp);
717 return (PCTCPU(pp) != 0);
718 return (pp->ki_runtime != oldp->ki_runtime ||
719 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
720 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
724 * Return the total number of block in/out and faults by a process.
727 get_io_total(const struct kinfo_proc *pp)
731 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
734 static struct handle handle;
737 get_process_info(struct system_info *si, struct process_select *sel,
738 int (*compare)(const void *, const void *))
743 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
746 struct kinfo_proc **prefp;
747 struct kinfo_proc *pp;
748 struct timespec previous_proc_uptime;
751 * If thread state was toggled, don't cache the previous processes.
753 if (previous_thread != sel->thread)
755 previous_thread = sel->thread;
758 * Save the previous process info.
760 if (previous_proc_count_max < nproc) {
761 free(previous_procs);
762 previous_procs = calloc(nproc, sizeof(*previous_procs));
764 previous_pref = calloc(nproc, sizeof(*previous_pref));
765 if (previous_procs == NULL || previous_pref == NULL) {
766 fprintf(stderr, "top: Out of memory.\n");
767 quit(TOP_EX_SYS_ERROR);
769 previous_proc_count_max = nproc;
772 for (i = 0; i < nproc; i++)
773 previous_pref[i] = &previous_procs[i];
774 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
775 qsort(previous_pref, nproc, sizeof(*previous_pref),
776 ps.thread ? compare_tid : compare_pid);
778 previous_proc_count = nproc;
779 previous_proc_uptime = proc_uptime;
780 previous_wall_time = proc_wall_time;
781 previous_interval = 0;
783 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
785 gettimeofday(&proc_wall_time, NULL);
786 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
787 memset(&proc_uptime, 0, sizeof(proc_uptime));
788 else if (previous_proc_uptime.tv_sec != 0 &&
789 previous_proc_uptime.tv_nsec != 0) {
790 previous_interval = (proc_uptime.tv_sec -
791 previous_proc_uptime.tv_sec) * 1000000;
792 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
794 previous_interval -= 1000000;
797 previous_interval += nsec / 1000;
799 if (nproc > onproc) {
800 pref = realloc(pref, sizeof(*pref) * nproc);
801 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
804 if (pref == NULL || pbase == NULL || pcpu == NULL) {
805 fprintf(stderr, "top: Out of memory.\n");
806 quit(TOP_EX_SYS_ERROR);
808 /* get a pointer to the states summary array */
809 si->procstates = process_states;
811 /* count up process states and get pointers to interesting procs */
817 memset(process_states, 0, sizeof(process_states));
819 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
821 if (pp->ki_stat == 0)
825 if (!sel->self && pp->ki_pid == mypid && sel->pid == -1)
829 if (!sel->system && (pp->ki_flag & P_SYSTEM) && sel->pid == -1)
830 /* skip system process */
833 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
835 total_inblock += p_inblock;
836 total_oublock += p_oublock;
837 total_majflt += p_majflt;
839 process_states[(unsigned char)pp->ki_stat]++;
841 if (pp->ki_stat == SZOMB)
845 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD && sel->pid == -1)
846 /* skip kernel idle process */
849 PCTCPU(pp) = proc_calc_pctcpu(pp);
850 if (sel->thread && PCTCPU(pp) > 1.0)
852 if (displaymode == DISP_CPU && !sel->idle &&
853 (!proc_used_cpu(pp) ||
854 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
855 /* skip idle or non-running processes */
858 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
859 /* skip processes that aren't doing I/O */
862 if (sel->jid != -1 && pp->ki_jid != sel->jid)
863 /* skip proc. that don't belong to the selected JID */
866 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
867 /* skip proc. that don't belong to the selected UID */
870 if (sel->pid != -1 && pp->ki_pid != sel->pid)
873 if (!cmd_matches(pp, sel->command))
874 /* skip proc. that doesn't match grep string */
881 /* if requested, sort the "interesting" processes */
883 qsort(pref, active_procs, sizeof(*pref), compare);
885 /* remember active and total counts */
886 si->p_total = total_procs;
887 si->p_pactive = pref_len = active_procs;
889 /* pass back a handle */
890 handle.next_proc = pref;
891 handle.remaining = active_procs;
896 cmd_matches(struct kinfo_proc *proc, const char *term)
901 /* No command filter set */
904 /* Filter set, does process name contain term? */
905 if (strstr(proc->ki_comm, term))
907 /* Search arguments only if arguments are displayed */
909 args = kvm_getargv(kd, proc, 1024);
911 /* Failed to get arguments so can't search them */
914 while (*args != NULL) {
915 if (strstr(*args, term))
925 format_next_process(struct handle * xhandle, char *(*get_userid)(int), int flags)
927 struct kinfo_proc *pp;
928 const struct kinfo_proc *oldp;
932 struct rusage ru, *rup;
936 static struct sbuf* procbuf = NULL;
938 /* clean up from last time. */
939 if (procbuf != NULL) {
942 procbuf = sbuf_new_auto();
946 /* find and remember the next proc structure */
947 pp = *(xhandle->next_proc++);
948 xhandle->remaining--;
950 /* get the process's command name */
951 if ((pp->ki_flag & P_INMEM) == 0) {
953 * Print swapped processes as <pname>
957 len = strlen(pp->ki_comm);
958 if (len > sizeof(pp->ki_comm) - 3)
959 len = sizeof(pp->ki_comm) - 3;
960 memmove(pp->ki_comm + 1, pp->ki_comm, len);
961 pp->ki_comm[0] = '<';
962 pp->ki_comm[len + 1] = '>';
963 pp->ki_comm[len + 2] = '\0';
967 * Convert the process's runtime from microseconds to seconds. This
968 * time includes the interrupt time although that is not wanted here.
969 * ps(1) is similarly sloppy.
971 cputime = (pp->ki_runtime + 500000) / 1000000;
973 /* generate "STATE" field */
974 switch (state = pp->ki_stat) {
976 if (smpmode && pp->ki_oncpu != NOCPU)
977 sprintf(status, "CPU%d", pp->ki_oncpu);
979 strcpy(status, "RUN");
982 if (pp->ki_kiflag & KI_LOCKBLOCK) {
983 sprintf(status, "*%.6s", pp->ki_lockname);
988 sprintf(status, "%.6s", pp->ki_wmesg);
992 if (state < nitems(state_abbrev)) {
993 sprintf(status, "%.6s", state_abbrev[state]);
995 sprintf(status, "?%5zu", state);
1000 cmdbuf = calloc(screen_width + 1, 1);
1001 if (cmdbuf == NULL) {
1002 warn("calloc(%d)", screen_width + 1);
1006 if (!(flags & FMT_SHOWARGS)) {
1007 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1009 snprintf(cmdbuf, screen_width, "%s{%s%s}", pp->ki_comm,
1010 pp->ki_tdname, pp->ki_moretdname);
1012 snprintf(cmdbuf, screen_width, "%s", pp->ki_comm);
1015 if (pp->ki_flag & P_SYSTEM ||
1016 (args = kvm_getargv(kd, pp, screen_width)) == NULL ||
1018 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1020 snprintf(cmdbuf, screen_width,
1021 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1024 snprintf(cmdbuf, screen_width,
1025 "[%s]", pp->ki_comm);
1034 argbuflen = screen_width * 4;
1035 argbuf = calloc(argbuflen + 1, 1);
1036 if (argbuf == NULL) {
1037 warn("calloc(%zu)", argbuflen + 1);
1044 /* Extract cmd name from argv */
1045 cmd = basename(*args);
1047 for (; (src = *args++) != NULL; ) {
1050 len = (argbuflen - (dst - argbuf) - 1) / 4;
1052 MIN(strlen(src), len),
1053 VIS_NL | VIS_TAB | VIS_CSTYLE | VIS_OCTAL);
1054 while (*dst != '\0')
1056 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1057 *dst++ = ' '; /* add delimiting space */
1059 if (dst != argbuf && dst[-1] == ' ')
1063 if (strcmp(cmd, pp->ki_comm) != 0) {
1064 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1066 snprintf(cmdbuf, screen_width,
1067 "%s (%s){%s%s}", argbuf,
1068 pp->ki_comm, pp->ki_tdname,
1071 snprintf(cmdbuf, screen_width,
1072 "%s (%s)", argbuf, pp->ki_comm);
1074 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1076 snprintf(cmdbuf, screen_width,
1077 "%s{%s%s}", argbuf, pp->ki_tdname,
1080 strlcpy(cmdbuf, argbuf, screen_width);
1086 if (displaymode == DISP_IO) {
1087 oldp = get_old_proc(pp);
1089 ru.ru_inblock = RU(pp)->ru_inblock -
1090 RU(oldp)->ru_inblock;
1091 ru.ru_oublock = RU(pp)->ru_oublock -
1092 RU(oldp)->ru_oublock;
1093 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1094 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1095 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1100 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1101 s_tot = total_inblock + total_oublock + total_majflt;
1103 sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1106 sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1108 sbuf_printf(procbuf, "%-*.*s", namelength, namelength, (*get_userid)(pp->ki_ruid));
1109 sbuf_printf(procbuf, "%6ld ", rup->ru_nvcsw);
1110 sbuf_printf(procbuf, "%6ld ", rup->ru_nivcsw);
1111 sbuf_printf(procbuf, "%6ld ", rup->ru_inblock);
1112 sbuf_printf(procbuf, "%6ld ", rup->ru_oublock);
1113 sbuf_printf(procbuf, "%6ld ", rup->ru_majflt);
1114 sbuf_printf(procbuf, "%6ld ", p_tot);
1115 sbuf_printf(procbuf, "%6.2f%% ", s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot));
1118 sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1120 sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1122 sbuf_printf(procbuf, "%-*.*s ", namelength, namelength, (*get_userid)(pp->ki_ruid));
1125 sbuf_printf(procbuf, "%4d ", pp->ki_numthreads);
1127 sbuf_printf(procbuf, " ");
1130 sbuf_printf(procbuf, "%3d ", pp->ki_pri.pri_level - PZERO);
1131 sbuf_printf(procbuf, "%4s", format_nice(pp));
1132 sbuf_printf(procbuf, "%7s ", format_k(PROCSIZE(pp)));
1133 sbuf_printf(procbuf, "%6s ", format_k(pagetok(pp->ki_rssize)));
1135 sbuf_printf(procbuf, "%*s ",
1137 format_k(pagetok(ki_swap(pp))));
1139 sbuf_printf(procbuf, "%-6.6s ", status);
1142 if (state == SRUN && pp->ki_oncpu != NOCPU) {
1145 cpu = pp->ki_lastcpu;
1147 sbuf_printf(procbuf, "%3d ", cpu);
1149 sbuf_printf(procbuf, "%6s ", format_time(cputime));
1150 sbuf_printf(procbuf, "%6.2f%% ", ps.wcpu ? 100.0 * weighted_cpu(PCTCPU(pp), pp) : 100.0 * PCTCPU(pp));
1152 sbuf_printf(procbuf, "%s", cmdbuf);
1154 return (sbuf_data(procbuf));
1158 getsysctl(const char *name, void *ptr, size_t len)
1162 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1163 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1165 quit(TOP_EX_SYS_ERROR);
1168 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1169 name, (unsigned long)len, (unsigned long)nlen);
1170 quit(TOP_EX_SYS_ERROR);
1175 format_nice(const struct kinfo_proc *pp)
1177 const char *fifo, *kproc;
1179 static char nicebuf[4 + 1];
1181 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1182 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1183 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1188 * XXX: the kernel doesn't tell us the original rtprio and
1189 * doesn't really know what it was, so to recover it we
1190 * must be more chummy with the implementation than the
1191 * implementation is with itself. pri_user gives a
1192 * constant "base" priority, but is only initialized
1193 * properly for user threads. pri_native gives what the
1194 * kernel calls the "base" priority, but it isn't constant
1195 * since it is changed by priority propagation. pri_native
1196 * also isn't properly initialized for all threads, but it
1197 * is properly initialized for kernel realtime and idletime
1198 * threads. Thus we use pri_user for the base priority of
1199 * user threads (it is always correct) and pri_native for
1200 * the base priority of kernel realtime and idletime threads
1201 * (there is nothing better, and it is usually correct).
1203 * The field width and thus the buffer are too small for
1204 * values like "kr31F", but such values shouldn't occur,
1205 * and if they do then the tailing "F" is not displayed.
1207 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1208 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1209 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1210 kproc, rtpri, fifo);
1213 if (pp->ki_flag & P_KPROC)
1215 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1218 /* XXX: as above. */
1219 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1220 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1221 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1222 kproc, rtpri, fifo);
1230 /* comparison routines for qsort */
1233 compare_pid(const void *p1, const void *p2)
1235 const struct kinfo_proc * const *pp1 = p1;
1236 const struct kinfo_proc * const *pp2 = p2;
1238 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1240 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1244 compare_tid(const void *p1, const void *p2)
1246 const struct kinfo_proc * const *pp1 = p1;
1247 const struct kinfo_proc * const *pp2 = p2;
1249 assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1251 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1255 * proc_compare - comparison function for "qsort"
1256 * Compares the resource consumption of two processes using five
1257 * distinct keys. The keys (in descending order of importance) are:
1258 * percent cpu, cpu ticks, state, resident set size, total virtual
1259 * memory usage. The process states are ordered as follows (from least
1260 * to most important): WAIT, zombie, sleep, stop, start, run. The
1261 * array declaration below maps a process state index into a number
1262 * that reflects this ordering.
1265 static int sorted_state[] = {
1268 1, /* ABANDONED (WAIT) */
1276 #define ORDERKEY_PCTCPU(a, b) do { \
1279 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1280 weighted_cpu(PCTCPU((a)), (a)); \
1282 diff = PCTCPU((b)) - PCTCPU((a)); \
1284 return (diff > 0 ? 1 : -1); \
1287 #define ORDERKEY_CPTICKS(a, b) do { \
1288 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1290 return (diff > 0 ? 1 : -1); \
1293 #define ORDERKEY_STATE(a, b) do { \
1294 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1296 return (diff > 0 ? 1 : -1); \
1299 #define ORDERKEY_PRIO(a, b) do { \
1300 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1302 return (diff > 0 ? 1 : -1); \
1305 #define ORDERKEY_THREADS(a, b) do { \
1306 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1308 return (diff > 0 ? 1 : -1); \
1311 #define ORDERKEY_RSSIZE(a, b) do { \
1312 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1314 return (diff > 0 ? 1 : -1); \
1317 #define ORDERKEY_MEM(a, b) do { \
1318 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1320 return (diff > 0 ? 1 : -1); \
1323 #define ORDERKEY_JID(a, b) do { \
1324 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1326 return (diff > 0 ? 1 : -1); \
1329 #define ORDERKEY_SWAP(a, b) do { \
1330 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1332 return (diff > 0 ? 1 : -1); \
1335 /* compare_cpu - the comparison function for sorting by cpu percentage */
1338 compare_cpu(const void *arg1, const void *arg2)
1340 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1341 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1343 ORDERKEY_PCTCPU(p1, p2);
1344 ORDERKEY_CPTICKS(p1, p2);
1345 ORDERKEY_STATE(p1, p2);
1346 ORDERKEY_PRIO(p1, p2);
1347 ORDERKEY_RSSIZE(p1, p2);
1348 ORDERKEY_MEM(p1, p2);
1353 /* compare_size - the comparison function for sorting by total memory usage */
1356 compare_size(const void *arg1, const void *arg2)
1358 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1359 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1361 ORDERKEY_MEM(p1, p2);
1362 ORDERKEY_RSSIZE(p1, p2);
1363 ORDERKEY_PCTCPU(p1, p2);
1364 ORDERKEY_CPTICKS(p1, p2);
1365 ORDERKEY_STATE(p1, p2);
1366 ORDERKEY_PRIO(p1, p2);
1371 /* compare_res - the comparison function for sorting by resident set size */
1374 compare_res(const void *arg1, const void *arg2)
1376 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1377 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1379 ORDERKEY_RSSIZE(p1, p2);
1380 ORDERKEY_MEM(p1, p2);
1381 ORDERKEY_PCTCPU(p1, p2);
1382 ORDERKEY_CPTICKS(p1, p2);
1383 ORDERKEY_STATE(p1, p2);
1384 ORDERKEY_PRIO(p1, p2);
1389 /* compare_time - the comparison function for sorting by total cpu time */
1392 compare_time(const void *arg1, const void *arg2)
1394 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1395 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1397 ORDERKEY_CPTICKS(p1, p2);
1398 ORDERKEY_PCTCPU(p1, p2);
1399 ORDERKEY_STATE(p1, p2);
1400 ORDERKEY_PRIO(p1, p2);
1401 ORDERKEY_RSSIZE(p1, p2);
1402 ORDERKEY_MEM(p1, p2);
1407 /* compare_prio - the comparison function for sorting by priority */
1410 compare_prio(const void *arg1, const void *arg2)
1412 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1413 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1415 ORDERKEY_PRIO(p1, p2);
1416 ORDERKEY_CPTICKS(p1, p2);
1417 ORDERKEY_PCTCPU(p1, p2);
1418 ORDERKEY_STATE(p1, p2);
1419 ORDERKEY_RSSIZE(p1, p2);
1420 ORDERKEY_MEM(p1, p2);
1425 /* compare_threads - the comparison function for sorting by threads */
1427 compare_threads(const void *arg1, const void *arg2)
1429 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1430 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1432 ORDERKEY_THREADS(p1, p2);
1433 ORDERKEY_PCTCPU(p1, p2);
1434 ORDERKEY_CPTICKS(p1, p2);
1435 ORDERKEY_STATE(p1, p2);
1436 ORDERKEY_PRIO(p1, p2);
1437 ORDERKEY_RSSIZE(p1, p2);
1438 ORDERKEY_MEM(p1, p2);
1443 /* compare_jid - the comparison function for sorting by jid */
1445 compare_jid(const void *arg1, const void *arg2)
1447 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1448 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1450 ORDERKEY_JID(p1, p2);
1451 ORDERKEY_PCTCPU(p1, p2);
1452 ORDERKEY_CPTICKS(p1, p2);
1453 ORDERKEY_STATE(p1, p2);
1454 ORDERKEY_PRIO(p1, p2);
1455 ORDERKEY_RSSIZE(p1, p2);
1456 ORDERKEY_MEM(p1, p2);
1461 /* compare_swap - the comparison function for sorting by swap */
1463 compare_swap(const void *arg1, const void *arg2)
1465 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1466 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1468 ORDERKEY_SWAP(p1, p2);
1469 ORDERKEY_PCTCPU(p1, p2);
1470 ORDERKEY_CPTICKS(p1, p2);
1471 ORDERKEY_STATE(p1, p2);
1472 ORDERKEY_PRIO(p1, p2);
1473 ORDERKEY_RSSIZE(p1, p2);
1474 ORDERKEY_MEM(p1, p2);
1479 /* assorted comparison functions for sorting by i/o */
1482 compare_iototal(const void *arg1, const void *arg2)
1484 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1485 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1487 return (get_io_total(p2) - get_io_total(p1));
1491 compare_ioread(const void *arg1, const void *arg2)
1493 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1494 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1495 long dummy, inp1, inp2;
1497 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1498 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1500 return (inp2 - inp1);
1504 compare_iowrite(const void *arg1, const void *arg2)
1506 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1507 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1508 long dummy, oup1, oup2;
1510 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1511 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1513 return (oup2 - oup1);
1517 compare_iofault(const void *arg1, const void *arg2)
1519 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1520 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1521 long dummy, flp1, flp2;
1523 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1524 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1526 return (flp2 - flp1);
1530 compare_vcsw(const void *arg1, const void *arg2)
1532 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1533 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1534 long dummy, flp1, flp2;
1536 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1537 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1539 return (flp2 - flp1);
1543 compare_ivcsw(const void *arg1, const void *arg2)
1545 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1546 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1547 long dummy, flp1, flp2;
1549 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1550 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1552 return (flp2 - flp1);
1555 int (*compares[])(const void *arg1, const void *arg2) = {
1575 swapmode(int *retavail, int *retfree)
1578 struct kvm_swap swapary[1];
1579 static int pagesize = 0;
1580 static unsigned long swap_maxpages = 0;
1585 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1587 n = kvm_getswapinfo(kd, swapary, 1, 0);
1588 if (n < 0 || swapary[0].ksw_total == 0)
1592 pagesize = getpagesize();
1593 if (swap_maxpages == 0)
1594 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1596 /* ksw_total contains the total size of swap all devices which may
1597 exceed the maximum swap size allocatable in the system */
1598 if ( swapary[0].ksw_total > swap_maxpages )
1599 swapary[0].ksw_total = swap_maxpages;
1601 *retavail = CONVERT(swapary[0].ksw_total);
1602 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1606 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);