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);
229 find_uid(uid_t needle, int *haystack)
233 for (; i < TOP_MAX_UIDS; ++i)
234 if ((uid_t)haystack[i] == needle)
240 toggle_pcpustats(void)
248 /* Adjust display based on ncpus and the ARC state. */
256 y_swap = 3 + arc_enabled + carc_enabled + has_swap;
257 y_idlecursor = 4 + arc_enabled + carc_enabled + has_swap;
258 y_message = 4 + arc_enabled + carc_enabled + has_swap;
259 y_header = 5 + arc_enabled + carc_enabled + has_swap;
260 y_procs = 6 + arc_enabled + carc_enabled + has_swap;
261 Header_lines = 6 + arc_enabled + carc_enabled + has_swap;
268 y_idlecursor += ncpus - 1;
269 y_message += ncpus - 1;
270 y_header += ncpus - 1;
271 y_procs += ncpus - 1;
272 Header_lines += ncpus - 1;
277 machine_init(struct statics *statics)
279 int i, j, empty, pagesize;
281 int carc_en, nswapdev;
284 size = sizeof(smpmode);
285 if (sysctlbyname("kern.smp.active", &smpmode, &size, NULL, 0) != 0 ||
286 size != sizeof(smpmode))
289 size = sizeof(arc_size);
290 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
291 NULL, 0) == 0 && arc_size != 0)
293 size = sizeof(carc_en);
295 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
296 NULL, 0) == 0 && carc_en == 1)
299 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
303 size = sizeof(nswapdev);
304 if (sysctlbyname("vm.nswapdev", &nswapdev, &size, NULL,
305 0) == 0 && nswapdev != 0)
308 GETSYSCTL("kern.ccpu", ccpu);
310 /* this is used in calculating WCPU -- calculate it ahead of time */
311 logcpu = log(loaddouble(ccpu));
319 /* get the page size and calculate pageshift from it */
320 pagesize = getpagesize();
322 while (pagesize > 1) {
327 /* we only need the amount of log(2)1024 for our conversion */
328 pageshift -= LOG1024;
330 /* fill in the statics information */
331 statics->procstate_names = procstatenames;
332 statics->cpustate_names = cpustatenames;
333 statics->memory_names = memorynames;
335 statics->arc_names = arcnames;
337 statics->arc_names = NULL;
339 statics->carc_names = carcnames;
341 statics->carc_names = NULL;
343 statics->swap_names = swapnames;
345 statics->swap_names = NULL;
346 statics->order_names = ordernames;
348 /* Allocate state for per-CPU stats. */
351 GETSYSCTL("kern.smp.maxcpus", maxcpu);
352 times = calloc(maxcpu * CPUSTATES, sizeof(long));
354 err(1, "calloc for kern.smp.maxcpus");
355 size = sizeof(long) * maxcpu * CPUSTATES;
356 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
357 err(1, "sysctlbyname kern.cp_times");
358 pcpu_cp_time = calloc(1, size);
359 maxid = (size / CPUSTATES / sizeof(long)) - 1;
360 for (i = 0; i <= maxid; i++) {
362 for (j = 0; empty && j < CPUSTATES; j++) {
363 if (times[i * CPUSTATES + j] != 0)
367 cpumask |= (1ul << i);
372 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
373 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
374 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
375 statics->ncpus = ncpus;
377 /* Allocate state of battery units reported via ACPI. */
380 sysctlbyname("hw.acpi.battery.units", &battery_units, &size, NULL, 0);
381 statics->nbatteries = battery_units;
390 format_header(const char *uname_field)
392 static struct sbuf* header = NULL;
394 /* clean up from last time. */
395 if (header != NULL) {
398 header = sbuf_new_auto();
401 switch (displaymode) {
403 sbuf_printf(header, " %s", ps.thread_id ? " THR" : "PID");
404 sbuf_printf(header, "%*s", ps.jail ? TOP_JID_LEN : 0,
405 ps.jail ? " JID" : "");
406 sbuf_printf(header, " %-*.*s ", namelength, namelength, uname_field);
408 sbuf_cat(header, "THR ");
410 sbuf_cat(header, "PRI NICE SIZE RES ");
412 sbuf_printf(header, "%*s ", TOP_SWAP_LEN - 1, "SWAP");
414 sbuf_cat(header, "STATE ");
416 sbuf_cat(header, "C ");
418 sbuf_cat(header, "TIME ");
419 sbuf_printf(header, " %6s ", ps.wcpu ? "WCPU" : "CPU");
420 sbuf_cat(header, "COMMAND");
425 sbuf_printf(header, " %s%*s %-*.*s",
426 ps.thread_id ? " THR" : "PID",
427 ps.jail ? TOP_JID_LEN : 0, ps.jail ? " JID" : "",
428 namelength, namelength, uname_field);
429 sbuf_cat(header, " VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND");
434 assert("displaymode must not be set to DISP_MAX");
437 return sbuf_data(header);
440 static int swappgsin = -1;
441 static int swappgsout = -1;
445 get_system_info(struct system_info *si)
447 struct loadavg sysload;
449 struct timeval boottime;
450 uint64_t arc_stat, arc_stat2;
454 /* get the CPU stats */
455 size = (maxid + 1) * CPUSTATES * sizeof(long);
456 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
457 err(1, "sysctlbyname kern.cp_times");
458 GETSYSCTL("kern.cp_time", cp_time);
459 GETSYSCTL("vm.loadavg", sysload);
460 GETSYSCTL("kern.lastpid", lastpid);
462 /* convert load averages to doubles */
463 for (i = 0; i < 3; i++)
464 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
466 /* convert cp_time counts to percentages */
467 for (i = j = 0; i <= maxid; i++) {
468 if ((cpumask & (1ul << i)) == 0)
470 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
471 &pcpu_cp_time[j * CPUSTATES],
472 &pcpu_cp_old[j * CPUSTATES],
473 &pcpu_cp_diff[j * CPUSTATES]);
476 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
478 /* sum memory & swap statistics */
480 static unsigned int swap_delay = 0;
481 static int swapavail = 0;
482 static int swapfree = 0;
483 static long bufspace = 0;
484 static uint64_t nspgsin, nspgsout;
486 GETSYSCTL("vfs.bufspace", bufspace);
487 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
488 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
489 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
490 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
491 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
492 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
493 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
494 /* convert memory stats to Kbytes */
495 memory_stats[0] = pagetok(memory_stats[0]);
496 memory_stats[1] = pagetok(memory_stats[1]);
497 memory_stats[2] = pagetok(memory_stats[2]);
498 memory_stats[3] = pagetok(memory_stats[3]);
499 memory_stats[4] = bufspace / 1024;
500 memory_stats[5] = pagetok(memory_stats[5]);
501 memory_stats[6] = -1;
509 /* compute differences between old and new swap statistic */
511 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
512 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
516 swappgsout = nspgsout;
518 /* call CPU heavy swapmode() only for changes */
519 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
520 swap_stats[3] = swapmode(&swapavail, &swapfree);
521 swap_stats[0] = swapavail;
522 swap_stats[1] = swapavail - swapfree;
523 swap_stats[2] = swapfree;
530 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
531 arc_stats[0] = arc_stat >> 10;
532 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
533 arc_stats[1] = arc_stat >> 10;
534 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
535 arc_stats[2] = arc_stat >> 10;
536 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
537 arc_stats[3] = arc_stat >> 10;
538 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
539 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
540 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
541 GETSYSCTL("kstat.zfs.misc.arcstats.bonus_size", arc_stat);
542 arc_stats[5] = arc_stat >> 10;
543 GETSYSCTL("kstat.zfs.misc.arcstats.dnode_size", arc_stat);
544 arc_stats[5] += arc_stat >> 10;
545 GETSYSCTL("kstat.zfs.misc.arcstats.dbuf_size", arc_stat);
546 arc_stats[5] += arc_stat >> 10;
550 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
551 carc_stats[0] = arc_stat >> 10;
552 carc_stats[2] = arc_stat >> 10; /* For ratio */
553 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
554 carc_stats[1] = arc_stat >> 10;
555 si->carc = carc_stats;
558 /* set arrays and strings */
560 si->cpustates = pcpu_cpu_states;
563 si->cpustates = cpu_states;
566 si->memory = memory_stats;
567 si->swap = swap_stats;
571 si->last_pid = lastpid;
577 * Print how long system has been up.
578 * (Found by looking getting "boottime" from the kernel)
581 mib[1] = KERN_BOOTTIME;
582 size = sizeof(boottime);
583 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
584 boottime.tv_sec != 0) {
585 si->boottime = boottime;
587 si->boottime.tv_sec = -1;
591 if (battery_units > 0) {
592 GETSYSCTL("hw.acpi.battery.life", battery_life);
594 si->battery = battery_life;
597 #define NOPROC ((void *)-1)
600 * We need to compare data from the old process entry with the new
602 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
603 * structure to cache the mapping. We also use a negative cache pointer
604 * of NOPROC to avoid duplicate lookups.
605 * XXX: this could be done when the actual processes are fetched, we do
606 * it here out of laziness.
608 static const struct kinfo_proc *
609 get_old_proc(struct kinfo_proc *pp)
611 const struct kinfo_proc * const *oldpp, *oldp;
614 * If this is the first fetch of the kinfo_procs then we don't have
615 * any previous entries.
617 if (previous_proc_count == 0)
619 /* negative cache? */
620 if (pp->ki_udata == NOPROC)
623 if (pp->ki_udata != NULL)
624 return (pp->ki_udata);
627 * 1) look up based on pid.
628 * 2) compare process start.
629 * If we fail here, then setup a negative cache entry, otherwise
632 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
633 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
635 pp->ki_udata = NOPROC;
639 if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
640 pp->ki_udata = NOPROC;
643 pp->ki_udata = __DECONST(void *, oldp);
648 * Return the total amount of IO done in blocks in/out and faults.
649 * store the values individually in the pointers passed in.
652 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
653 long *vcsw, long *ivcsw)
655 const struct kinfo_proc *oldp;
656 static struct kinfo_proc dummy;
659 oldp = get_old_proc(__DECONST(struct kinfo_proc *, pp));
661 memset(&dummy, 0, sizeof(dummy));
664 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
665 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
666 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
667 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
668 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
670 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
671 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
672 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
677 * If there was a previous update, use the delta in ki_runtime over
678 * the previous interval to calculate pctcpu. Otherwise, fall back
679 * to using the kernel's ki_pctcpu.
682 proc_calc_pctcpu(struct kinfo_proc *pp)
684 const struct kinfo_proc *oldp;
686 if (previous_interval != 0) {
687 oldp = get_old_proc(pp);
689 return ((double)(pp->ki_runtime - oldp->ki_runtime)
690 / previous_interval);
693 * If this process/thread was created during the previous
694 * interval, charge it's total runtime to the previous
697 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
698 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
699 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
700 return ((double)pp->ki_runtime / previous_interval);
702 return (pctdouble(pp->ki_pctcpu));
706 * Return true if this process has used any CPU time since the
710 proc_used_cpu(struct kinfo_proc *pp)
712 const struct kinfo_proc *oldp;
714 oldp = get_old_proc(pp);
716 return (PCTCPU(pp) != 0);
717 return (pp->ki_runtime != oldp->ki_runtime ||
718 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
719 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
723 * Return the total number of block in/out and faults by a process.
726 get_io_total(const struct kinfo_proc *pp)
730 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
733 static struct handle handle;
736 get_process_info(struct system_info *si, struct process_select *sel,
737 int (*compare)(const void *, const void *))
742 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
745 struct kinfo_proc **prefp;
746 struct kinfo_proc *pp;
747 struct timespec previous_proc_uptime;
750 * If thread state was toggled, don't cache the previous processes.
752 if (previous_thread != sel->thread)
754 previous_thread = sel->thread;
757 * Save the previous process info.
759 if (previous_proc_count_max < nproc) {
760 free(previous_procs);
761 previous_procs = calloc(nproc, sizeof(*previous_procs));
763 previous_pref = calloc(nproc, sizeof(*previous_pref));
764 if (previous_procs == NULL || previous_pref == NULL) {
765 fprintf(stderr, "top: Out of memory.\n");
766 quit(TOP_EX_SYS_ERROR);
768 previous_proc_count_max = nproc;
771 for (i = 0; i < nproc; i++)
772 previous_pref[i] = &previous_procs[i];
773 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
774 qsort(previous_pref, nproc, sizeof(*previous_pref),
775 ps.thread ? compare_tid : compare_pid);
777 previous_proc_count = nproc;
778 previous_proc_uptime = proc_uptime;
779 previous_wall_time = proc_wall_time;
780 previous_interval = 0;
782 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
784 gettimeofday(&proc_wall_time, NULL);
785 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
786 memset(&proc_uptime, 0, sizeof(proc_uptime));
787 else if (previous_proc_uptime.tv_sec != 0 &&
788 previous_proc_uptime.tv_nsec != 0) {
789 previous_interval = (proc_uptime.tv_sec -
790 previous_proc_uptime.tv_sec) * 1000000;
791 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
793 previous_interval -= 1000000;
796 previous_interval += nsec / 1000;
798 if (nproc > onproc) {
799 pref = realloc(pref, sizeof(*pref) * nproc);
800 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
803 if (pref == NULL || pbase == NULL || pcpu == NULL) {
804 fprintf(stderr, "top: Out of memory.\n");
805 quit(TOP_EX_SYS_ERROR);
807 /* get a pointer to the states summary array */
808 si->procstates = process_states;
810 /* count up process states and get pointers to interesting procs */
816 memset(process_states, 0, sizeof(process_states));
818 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
820 if (pp->ki_stat == 0)
824 if (!sel->self && pp->ki_pid == mypid && sel->pid == -1)
828 if (!sel->system && (pp->ki_flag & P_SYSTEM) && sel->pid == -1)
829 /* skip system process */
832 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
834 total_inblock += p_inblock;
835 total_oublock += p_oublock;
836 total_majflt += p_majflt;
838 process_states[(unsigned char)pp->ki_stat]++;
840 if (pp->ki_stat == SZOMB)
844 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD && sel->pid == -1)
845 /* skip kernel idle process */
848 PCTCPU(pp) = proc_calc_pctcpu(pp);
849 if (sel->thread && PCTCPU(pp) > 1.0)
851 if (displaymode == DISP_CPU && !sel->idle &&
852 (!proc_used_cpu(pp) ||
853 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
854 /* skip idle or non-running processes */
857 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
858 /* skip processes that aren't doing I/O */
861 if (sel->jid != -1 && pp->ki_jid != sel->jid)
862 /* skip proc. that don't belong to the selected JID */
865 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
866 /* skip proc. that don't belong to the selected UID */
869 if (sel->pid != -1 && pp->ki_pid != sel->pid)
876 /* if requested, sort the "interesting" processes */
878 qsort(pref, active_procs, sizeof(*pref), compare);
880 /* remember active and total counts */
881 si->p_total = total_procs;
882 si->p_pactive = pref_len = active_procs;
884 /* pass back a handle */
885 handle.next_proc = pref;
886 handle.remaining = active_procs;
891 format_next_process(struct handle * xhandle, char *(*get_userid)(int), int flags)
893 struct kinfo_proc *pp;
894 const struct kinfo_proc *oldp;
898 struct rusage ru, *rup;
902 static struct sbuf* procbuf = NULL;
904 /* clean up from last time. */
905 if (procbuf != NULL) {
908 procbuf = sbuf_new_auto();
912 /* find and remember the next proc structure */
913 pp = *(xhandle->next_proc++);
914 xhandle->remaining--;
916 /* get the process's command name */
917 if ((pp->ki_flag & P_INMEM) == 0) {
919 * Print swapped processes as <pname>
923 len = strlen(pp->ki_comm);
924 if (len > sizeof(pp->ki_comm) - 3)
925 len = sizeof(pp->ki_comm) - 3;
926 memmove(pp->ki_comm + 1, pp->ki_comm, len);
927 pp->ki_comm[0] = '<';
928 pp->ki_comm[len + 1] = '>';
929 pp->ki_comm[len + 2] = '\0';
933 * Convert the process's runtime from microseconds to seconds. This
934 * time includes the interrupt time although that is not wanted here.
935 * ps(1) is similarly sloppy.
937 cputime = (pp->ki_runtime + 500000) / 1000000;
939 /* generate "STATE" field */
940 switch (state = pp->ki_stat) {
942 if (smpmode && pp->ki_oncpu != NOCPU)
943 sprintf(status, "CPU%d", pp->ki_oncpu);
945 strcpy(status, "RUN");
948 if (pp->ki_kiflag & KI_LOCKBLOCK) {
949 sprintf(status, "*%.6s", pp->ki_lockname);
954 sprintf(status, "%.6s", pp->ki_wmesg);
958 if (state < nitems(state_abbrev)) {
959 sprintf(status, "%.6s", state_abbrev[state]);
961 sprintf(status, "?%5zu", state);
966 cmdbuf = calloc(screen_width + 1, 1);
967 if (cmdbuf == NULL) {
968 warn("calloc(%d)", screen_width + 1);
972 if (!(flags & FMT_SHOWARGS)) {
973 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
975 snprintf(cmdbuf, screen_width, "%s{%s%s}", pp->ki_comm,
976 pp->ki_tdname, pp->ki_moretdname);
978 snprintf(cmdbuf, screen_width, "%s", pp->ki_comm);
981 if (pp->ki_flag & P_SYSTEM ||
982 (args = kvm_getargv(kd, pp, screen_width)) == NULL ||
984 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
986 snprintf(cmdbuf, screen_width,
987 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
990 snprintf(cmdbuf, screen_width,
991 "[%s]", pp->ki_comm);
1000 argbuflen = screen_width * 4;
1001 argbuf = calloc(argbuflen + 1, 1);
1002 if (argbuf == NULL) {
1003 warn("calloc(%zu)", argbuflen + 1);
1010 /* Extract cmd name from argv */
1011 cmd = basename(*args);
1013 for (; (src = *args++) != NULL; ) {
1016 len = (argbuflen - (dst - argbuf) - 1) / 4;
1018 MIN(strlen(src), len),
1019 VIS_NL | VIS_TAB | VIS_CSTYLE | VIS_OCTAL);
1020 while (*dst != '\0')
1022 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1023 *dst++ = ' '; /* add delimiting space */
1025 if (dst != argbuf && dst[-1] == ' ')
1029 if (strcmp(cmd, pp->ki_comm) != 0) {
1030 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1032 snprintf(cmdbuf, screen_width,
1033 "%s (%s){%s%s}", argbuf,
1034 pp->ki_comm, pp->ki_tdname,
1037 snprintf(cmdbuf, screen_width,
1038 "%s (%s)", argbuf, pp->ki_comm);
1040 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1042 snprintf(cmdbuf, screen_width,
1043 "%s{%s%s}", argbuf, pp->ki_tdname,
1046 strlcpy(cmdbuf, argbuf, screen_width);
1052 if (displaymode == DISP_IO) {
1053 oldp = get_old_proc(pp);
1055 ru.ru_inblock = RU(pp)->ru_inblock -
1056 RU(oldp)->ru_inblock;
1057 ru.ru_oublock = RU(pp)->ru_oublock -
1058 RU(oldp)->ru_oublock;
1059 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1060 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1061 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1066 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1067 s_tot = total_inblock + total_oublock + total_majflt;
1069 sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1072 sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1074 sbuf_printf(procbuf, "%-*.*s", namelength, namelength, (*get_userid)(pp->ki_ruid));
1075 sbuf_printf(procbuf, "%6ld ", rup->ru_nvcsw);
1076 sbuf_printf(procbuf, "%6ld ", rup->ru_nivcsw);
1077 sbuf_printf(procbuf, "%6ld ", rup->ru_inblock);
1078 sbuf_printf(procbuf, "%6ld ", rup->ru_oublock);
1079 sbuf_printf(procbuf, "%6ld ", rup->ru_majflt);
1080 sbuf_printf(procbuf, "%6ld ", p_tot);
1081 sbuf_printf(procbuf, "%6.2f%% ", s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot));
1084 sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1086 sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1088 sbuf_printf(procbuf, "%-*.*s ", namelength, namelength, (*get_userid)(pp->ki_ruid));
1091 sbuf_printf(procbuf, "%4d ", pp->ki_numthreads);
1093 sbuf_printf(procbuf, " ");
1096 sbuf_printf(procbuf, "%3d ", pp->ki_pri.pri_level - PZERO);
1097 sbuf_printf(procbuf, "%4s", format_nice(pp));
1098 sbuf_printf(procbuf, "%7s ", format_k(PROCSIZE(pp)));
1099 sbuf_printf(procbuf, "%6s ", format_k(pagetok(pp->ki_rssize)));
1101 sbuf_printf(procbuf, "%*s ",
1103 format_k(pagetok(ki_swap(pp))));
1105 sbuf_printf(procbuf, "%-6.6s ", status);
1108 if (state == SRUN && pp->ki_oncpu != NOCPU) {
1111 cpu = pp->ki_lastcpu;
1113 sbuf_printf(procbuf, "%3d ", cpu);
1115 sbuf_printf(procbuf, "%6s ", format_time(cputime));
1116 sbuf_printf(procbuf, "%6.2f%% ", ps.wcpu ? 100.0 * weighted_cpu(PCTCPU(pp), pp) : 100.0 * PCTCPU(pp));
1118 sbuf_printf(procbuf, "%s", cmdbuf);
1120 return (sbuf_data(procbuf));
1124 getsysctl(const char *name, void *ptr, size_t len)
1128 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1129 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1131 quit(TOP_EX_SYS_ERROR);
1134 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1135 name, (unsigned long)len, (unsigned long)nlen);
1136 quit(TOP_EX_SYS_ERROR);
1141 format_nice(const struct kinfo_proc *pp)
1143 const char *fifo, *kproc;
1145 static char nicebuf[4 + 1];
1147 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1148 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1149 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1154 * XXX: the kernel doesn't tell us the original rtprio and
1155 * doesn't really know what it was, so to recover it we
1156 * must be more chummy with the implementation than the
1157 * implementation is with itself. pri_user gives a
1158 * constant "base" priority, but is only initialized
1159 * properly for user threads. pri_native gives what the
1160 * kernel calls the "base" priority, but it isn't constant
1161 * since it is changed by priority propagation. pri_native
1162 * also isn't properly initialized for all threads, but it
1163 * is properly initialized for kernel realtime and idletime
1164 * threads. Thus we use pri_user for the base priority of
1165 * user threads (it is always correct) and pri_native for
1166 * the base priority of kernel realtime and idletime threads
1167 * (there is nothing better, and it is usually correct).
1169 * The field width and thus the buffer are too small for
1170 * values like "kr31F", but such values shouldn't occur,
1171 * and if they do then the tailing "F" is not displayed.
1173 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1174 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1175 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1176 kproc, rtpri, fifo);
1179 if (pp->ki_flag & P_KPROC)
1181 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1184 /* XXX: as above. */
1185 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1186 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1187 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1188 kproc, rtpri, fifo);
1196 /* comparison routines for qsort */
1199 compare_pid(const void *p1, const void *p2)
1201 const struct kinfo_proc * const *pp1 = p1;
1202 const struct kinfo_proc * const *pp2 = p2;
1204 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1206 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1210 compare_tid(const void *p1, const void *p2)
1212 const struct kinfo_proc * const *pp1 = p1;
1213 const struct kinfo_proc * const *pp2 = p2;
1215 assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1217 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1221 * proc_compare - comparison function for "qsort"
1222 * Compares the resource consumption of two processes using five
1223 * distinct keys. The keys (in descending order of importance) are:
1224 * percent cpu, cpu ticks, state, resident set size, total virtual
1225 * memory usage. The process states are ordered as follows (from least
1226 * to most important): WAIT, zombie, sleep, stop, start, run. The
1227 * array declaration below maps a process state index into a number
1228 * that reflects this ordering.
1231 static int sorted_state[] = {
1234 1, /* ABANDONED (WAIT) */
1242 #define ORDERKEY_PCTCPU(a, b) do { \
1245 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1246 weighted_cpu(PCTCPU((a)), (a)); \
1248 diff = PCTCPU((b)) - PCTCPU((a)); \
1250 return (diff > 0 ? 1 : -1); \
1253 #define ORDERKEY_CPTICKS(a, b) do { \
1254 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1256 return (diff > 0 ? 1 : -1); \
1259 #define ORDERKEY_STATE(a, b) do { \
1260 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1262 return (diff > 0 ? 1 : -1); \
1265 #define ORDERKEY_PRIO(a, b) do { \
1266 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1268 return (diff > 0 ? 1 : -1); \
1271 #define ORDERKEY_THREADS(a, b) do { \
1272 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1274 return (diff > 0 ? 1 : -1); \
1277 #define ORDERKEY_RSSIZE(a, b) do { \
1278 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1280 return (diff > 0 ? 1 : -1); \
1283 #define ORDERKEY_MEM(a, b) do { \
1284 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1286 return (diff > 0 ? 1 : -1); \
1289 #define ORDERKEY_JID(a, b) do { \
1290 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1292 return (diff > 0 ? 1 : -1); \
1295 #define ORDERKEY_SWAP(a, b) do { \
1296 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1298 return (diff > 0 ? 1 : -1); \
1301 /* compare_cpu - the comparison function for sorting by cpu percentage */
1304 compare_cpu(const void *arg1, const void *arg2)
1306 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1307 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1309 ORDERKEY_PCTCPU(p1, p2);
1310 ORDERKEY_CPTICKS(p1, p2);
1311 ORDERKEY_STATE(p1, p2);
1312 ORDERKEY_PRIO(p1, p2);
1313 ORDERKEY_RSSIZE(p1, p2);
1314 ORDERKEY_MEM(p1, p2);
1319 /* compare_size - the comparison function for sorting by total memory usage */
1322 compare_size(const void *arg1, const void *arg2)
1324 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1325 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1327 ORDERKEY_MEM(p1, p2);
1328 ORDERKEY_RSSIZE(p1, p2);
1329 ORDERKEY_PCTCPU(p1, p2);
1330 ORDERKEY_CPTICKS(p1, p2);
1331 ORDERKEY_STATE(p1, p2);
1332 ORDERKEY_PRIO(p1, p2);
1337 /* compare_res - the comparison function for sorting by resident set size */
1340 compare_res(const void *arg1, const void *arg2)
1342 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1343 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1345 ORDERKEY_RSSIZE(p1, p2);
1346 ORDERKEY_MEM(p1, p2);
1347 ORDERKEY_PCTCPU(p1, p2);
1348 ORDERKEY_CPTICKS(p1, p2);
1349 ORDERKEY_STATE(p1, p2);
1350 ORDERKEY_PRIO(p1, p2);
1355 /* compare_time - the comparison function for sorting by total cpu time */
1358 compare_time(const void *arg1, const void *arg2)
1360 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1361 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1363 ORDERKEY_CPTICKS(p1, p2);
1364 ORDERKEY_PCTCPU(p1, p2);
1365 ORDERKEY_STATE(p1, p2);
1366 ORDERKEY_PRIO(p1, p2);
1367 ORDERKEY_RSSIZE(p1, p2);
1368 ORDERKEY_MEM(p1, p2);
1373 /* compare_prio - the comparison function for sorting by priority */
1376 compare_prio(const void *arg1, const void *arg2)
1378 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1379 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1381 ORDERKEY_PRIO(p1, p2);
1382 ORDERKEY_CPTICKS(p1, p2);
1383 ORDERKEY_PCTCPU(p1, p2);
1384 ORDERKEY_STATE(p1, p2);
1385 ORDERKEY_RSSIZE(p1, p2);
1386 ORDERKEY_MEM(p1, p2);
1391 /* compare_threads - the comparison function for sorting by threads */
1393 compare_threads(const void *arg1, const void *arg2)
1395 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1396 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1398 ORDERKEY_THREADS(p1, p2);
1399 ORDERKEY_PCTCPU(p1, p2);
1400 ORDERKEY_CPTICKS(p1, p2);
1401 ORDERKEY_STATE(p1, p2);
1402 ORDERKEY_PRIO(p1, p2);
1403 ORDERKEY_RSSIZE(p1, p2);
1404 ORDERKEY_MEM(p1, p2);
1409 /* compare_jid - the comparison function for sorting by jid */
1411 compare_jid(const void *arg1, const void *arg2)
1413 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1414 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1416 ORDERKEY_JID(p1, p2);
1417 ORDERKEY_PCTCPU(p1, p2);
1418 ORDERKEY_CPTICKS(p1, p2);
1419 ORDERKEY_STATE(p1, p2);
1420 ORDERKEY_PRIO(p1, p2);
1421 ORDERKEY_RSSIZE(p1, p2);
1422 ORDERKEY_MEM(p1, p2);
1427 /* compare_swap - the comparison function for sorting by swap */
1429 compare_swap(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;
1434 ORDERKEY_SWAP(p1, p2);
1435 ORDERKEY_PCTCPU(p1, p2);
1436 ORDERKEY_CPTICKS(p1, p2);
1437 ORDERKEY_STATE(p1, p2);
1438 ORDERKEY_PRIO(p1, p2);
1439 ORDERKEY_RSSIZE(p1, p2);
1440 ORDERKEY_MEM(p1, p2);
1445 /* assorted comparison functions for sorting by i/o */
1448 compare_iototal(const void *arg1, const void *arg2)
1450 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1451 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1453 return (get_io_total(p2) - get_io_total(p1));
1457 compare_ioread(const void *arg1, const void *arg2)
1459 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1460 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1461 long dummy, inp1, inp2;
1463 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1464 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1466 return (inp2 - inp1);
1470 compare_iowrite(const void *arg1, const void *arg2)
1472 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1473 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1474 long dummy, oup1, oup2;
1476 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1477 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1479 return (oup2 - oup1);
1483 compare_iofault(const void *arg1, const void *arg2)
1485 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1486 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1487 long dummy, flp1, flp2;
1489 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1490 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1492 return (flp2 - flp1);
1496 compare_vcsw(const void *arg1, const void *arg2)
1498 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1499 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1500 long dummy, flp1, flp2;
1502 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1503 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1505 return (flp2 - flp1);
1509 compare_ivcsw(const void *arg1, const void *arg2)
1511 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1512 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1513 long dummy, flp1, flp2;
1515 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1516 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1518 return (flp2 - flp1);
1521 int (*compares[])(const void *arg1, const void *arg2) = {
1541 swapmode(int *retavail, int *retfree)
1544 struct kvm_swap swapary[1];
1545 static int pagesize = 0;
1546 static unsigned long swap_maxpages = 0;
1551 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1553 n = kvm_getswapinfo(kd, swapary, 1, 0);
1554 if (n < 0 || swapary[0].ksw_total == 0)
1558 pagesize = getpagesize();
1559 if (swap_maxpages == 0)
1560 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1562 /* ksw_total contains the total size of swap all devices which may
1563 exceed the maximum swap size allocatable in the system */
1564 if ( swapary[0].ksw_total > swap_maxpages )
1565 swapary[0].ksw_total = swap_maxpages;
1567 *retavail = CONVERT(swapary[0].ksw_total);
1568 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1572 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);