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>
25 #include <sys/sysctl.h>
51 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
52 #define SMPUNAMELEN 13
55 extern struct timeval timeout;
57 enum displaymodes displaymode;
58 static int namelength = 8;
59 /* TOP_JID_LEN based on max of 999999 */
61 #define TOP_SWAP_LEN 6
63 static int swaplength;
64 static int cmdlengthdelta;
66 /* get_process_info passes back a handle. This is what it looks like: */
69 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
70 int remaining; /* number of pointers remaining */
74 /* define what weighted cpu is. */
75 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
76 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
78 /* what we consider to be process size: */
79 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
81 #define RU(pp) (&(pp)->ki_rusage)
83 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
85 #define PCTCPU(pp) (pcpu[pp - pbase])
88 * These definitions control the format of the per-process area
91 static const char io_header[] =
92 " PID%*s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
94 static const char io_Proc_format[] =
95 "%5d%*s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s";
97 static const char smp_header_thr_and_pid[] =
98 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
99 static const char smp_header_tid_only[] =
100 " THR%*s %-*.*s " "PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
101 static const char smp_Proc_format[] =
102 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s %2d%7s %6.2f%% %.*s";
104 static char up_header_thr_and_pid[] =
105 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
106 static char up_header_tid_only[] =
107 " THR%*s %-*.*s " "PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
108 static char up_Proc_format[] =
109 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s%.0d%7s %6.2f%% %.*s";
112 /* process state names for the "STATE" column of the display */
113 /* the extra nulls in the string "run" are for adding a slash and
114 the processor number when needed */
116 static const char *state_abbrev[] = {
117 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
123 /* values that we stash away in _init and use in later routines */
125 static double logcpu;
127 /* these are retrieved from the kernel in _init */
129 static load_avg ccpu;
131 /* these are used in the get_ functions */
135 /* these are for calculating cpu state percentages */
137 static long cp_time[CPUSTATES];
138 static long cp_old[CPUSTATES];
139 static long cp_diff[CPUSTATES];
141 /* these are for detailing the process states */
143 static const char *procstatenames[] = {
144 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
145 " zombie, ", " waiting, ", " lock, ",
148 static int process_states[nitems(procstatenames)];
150 /* these are for detailing the cpu states */
152 static int cpu_states[CPUSTATES];
153 static const char *cpustatenames[] = {
154 "user", "nice", "system", "interrupt", "idle", NULL
157 /* these are for detailing the memory statistics */
159 static const char *memorynames[] = {
160 "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
163 static int memory_stats[nitems(memorynames)];
165 static const char *arcnames[] = {
166 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
169 static int arc_stats[nitems(arcnames)];
171 static const char *carcnames[] = {
172 "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
175 static int carc_stats[nitems(carcnames)];
177 static const char *swapnames[] = {
178 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
181 static int swap_stats[nitems(swapnames)];
184 /* these are for keeping track of the proc array */
187 static int onproc = -1;
189 static struct kinfo_proc *pbase;
190 static struct kinfo_proc **pref;
191 static struct kinfo_proc *previous_procs;
192 static struct kinfo_proc **previous_pref;
193 static int previous_proc_count = 0;
194 static int previous_proc_count_max = 0;
195 static int previous_thread;
197 /* data used for recalculating pctcpu */
199 static struct timespec proc_uptime;
200 static struct timeval proc_wall_time;
201 static struct timeval previous_wall_time;
202 static uint64_t previous_interval = 0;
204 /* total number of io operations */
205 static long total_inblock;
206 static long total_oublock;
207 static long total_majflt;
209 /* these are for getting the memory statistics */
211 static int arc_enabled;
212 static int carc_enabled;
213 static int pageshift; /* log base 2 of the pagesize */
215 /* define pagetok in terms of pageshift */
217 #define pagetok(size) ((size) << pageshift)
220 #define ki_swap(kip) \
221 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
224 * Sorting orders. The first element is the default.
226 static const char *ordernames[] = {
227 "cpu", "size", "res", "time", "pri", "threads",
228 "total", "read", "write", "fault", "vcsw", "ivcsw",
229 "jid", "swap", "pid", NULL
232 /* Per-cpu time states */
236 static unsigned long cpumask;
238 static long *pcpu_cp_time;
239 static long *pcpu_cp_old;
240 static long *pcpu_cp_diff;
241 static int *pcpu_cpu_states;
243 static int compare_swap(const void *a, const void *b);
244 static int compare_jid(const void *a, const void *b);
245 static int compare_pid(const void *a, const void *b);
246 static int compare_tid(const void *a, const void *b);
247 static const char *format_nice(const struct kinfo_proc *pp);
248 static void getsysctl(const char *name, void *ptr, size_t len);
249 static int swapmode(int *retavail, int *retfree);
250 static void update_layout(void);
251 static int find_uid(uid_t needle, int *haystack);
254 find_uid(uid_t needle, int *haystack)
258 for (; i < TOP_MAX_UIDS; ++i)
259 if ((uid_t)haystack[i] == needle)
265 toggle_pcpustats(void)
273 /* Adjust display based on ncpus and the ARC state. */
281 y_swap = 4 + arc_enabled + carc_enabled;
282 y_idlecursor = 5 + arc_enabled + carc_enabled;
283 y_message = 5 + arc_enabled + carc_enabled;
284 y_header = 6 + arc_enabled + carc_enabled;
285 y_procs = 7 + arc_enabled + carc_enabled;
286 Header_lines = 7 + arc_enabled + carc_enabled;
293 y_idlecursor += ncpus - 1;
294 y_message += ncpus - 1;
295 y_header += ncpus - 1;
296 y_procs += ncpus - 1;
297 Header_lines += ncpus - 1;
302 machine_init(struct statics *statics)
304 int i, j, empty, pagesize;
309 size = sizeof(smpmode);
310 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
312 sysctlbyname("kern.smp.active", &smpmode, &size,
314 size != sizeof(smpmode))
317 size = sizeof(arc_size);
318 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
319 NULL, 0) == 0 && arc_size != 0)
321 size = sizeof(carc_en);
323 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
324 NULL, 0) == 0 && carc_en == 1)
327 namelength = MAXLOGNAME;
328 if (smpmode && namelength > SMPUNAMELEN)
329 namelength = SMPUNAMELEN;
330 else if (namelength > UPUNAMELEN)
331 namelength = UPUNAMELEN;
333 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
337 GETSYSCTL("kern.ccpu", ccpu);
339 /* this is used in calculating WCPU -- calculate it ahead of time */
340 logcpu = log(loaddouble(ccpu));
348 /* get the page size and calculate pageshift from it */
349 pagesize = getpagesize();
351 while (pagesize > 1) {
356 /* we only need the amount of log(2)1024 for our conversion */
357 pageshift -= LOG1024;
359 /* fill in the statics information */
360 statics->procstate_names = procstatenames;
361 statics->cpustate_names = cpustatenames;
362 statics->memory_names = memorynames;
364 statics->arc_names = arcnames;
366 statics->arc_names = NULL;
368 statics->carc_names = carcnames;
370 statics->carc_names = NULL;
371 statics->swap_names = swapnames;
372 statics->order_names = ordernames;
374 /* Allocate state for per-CPU stats. */
377 GETSYSCTL("kern.smp.maxcpus", maxcpu);
378 times = calloc(maxcpu * CPUSTATES, sizeof(long));
380 err(1, "calloc for kern.smp.maxcpus");
381 size = sizeof(long) * maxcpu * CPUSTATES;
382 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
383 err(1, "sysctlbyname kern.cp_times");
384 pcpu_cp_time = calloc(1, size);
385 maxid = (size / CPUSTATES / sizeof(long)) - 1;
386 for (i = 0; i <= maxid; i++) {
388 for (j = 0; empty && j < CPUSTATES; j++) {
389 if (times[i * CPUSTATES + j] != 0)
393 cpumask |= (1ul << i);
398 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
399 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
400 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
401 statics->ncpus = ncpus;
410 format_header(const char *uname_field)
412 static char Header[128];
416 jidlength = TOP_JID_LEN + 1; /* +1 for extra left space. */
421 swaplength = TOP_SWAP_LEN + 1; /* +1 for extra left space */
425 switch (displaymode) {
428 * The logic of picking the right header format seems reverse
429 * here because we only want to display a THR column when
430 * "thread mode" is off (and threads are not listed as
434 (ps.thread_id ? smp_header_tid_only : smp_header_thr_and_pid) :
435 (ps.thread_id ? up_header_tid_only : up_header_thr_and_pid);
436 snprintf(Header, sizeof(Header), prehead,
437 jidlength, ps.jail ? " JID" : "",
438 namelength, namelength, uname_field,
439 swaplength, ps.swap ? " SWAP" : "",
440 ps.wcpu ? "WCPU" : "CPU");
444 snprintf(Header, sizeof(Header), prehead,
445 jidlength, ps.jail ? " JID" : "",
446 namelength, namelength, uname_field);
449 assert("displaymode must not be set to DISP_MAX");
451 cmdlengthdelta = strlen(Header) - 7;
455 static int swappgsin = -1;
456 static int swappgsout = -1;
460 get_system_info(struct system_info *si)
462 struct loadavg sysload;
464 struct timeval boottime;
465 uint64_t arc_stat, arc_stat2;
469 /* get the CPU stats */
470 size = (maxid + 1) * CPUSTATES * sizeof(long);
471 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
472 err(1, "sysctlbyname kern.cp_times");
473 GETSYSCTL("kern.cp_time", cp_time);
474 GETSYSCTL("vm.loadavg", sysload);
475 GETSYSCTL("kern.lastpid", lastpid);
477 /* convert load averages to doubles */
478 for (i = 0; i < 3; i++)
479 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
481 /* convert cp_time counts to percentages */
482 for (i = j = 0; i <= maxid; i++) {
483 if ((cpumask & (1ul << i)) == 0)
485 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
486 &pcpu_cp_time[j * CPUSTATES],
487 &pcpu_cp_old[j * CPUSTATES],
488 &pcpu_cp_diff[j * CPUSTATES]);
491 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
493 /* sum memory & swap statistics */
495 static unsigned int swap_delay = 0;
496 static int swapavail = 0;
497 static int swapfree = 0;
498 static long bufspace = 0;
499 static uint64_t nspgsin, nspgsout;
501 GETSYSCTL("vfs.bufspace", bufspace);
502 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
503 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
504 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
505 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
506 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
507 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
508 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
509 /* convert memory stats to Kbytes */
510 memory_stats[0] = pagetok(memory_stats[0]);
511 memory_stats[1] = pagetok(memory_stats[1]);
512 memory_stats[2] = pagetok(memory_stats[2]);
513 memory_stats[3] = pagetok(memory_stats[3]);
514 memory_stats[4] = bufspace / 1024;
515 memory_stats[5] = pagetok(memory_stats[5]);
516 memory_stats[6] = -1;
524 /* compute differences between old and new swap statistic */
526 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
527 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
531 swappgsout = nspgsout;
533 /* call CPU heavy swapmode() only for changes */
534 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
535 swap_stats[3] = swapmode(&swapavail, &swapfree);
536 swap_stats[0] = swapavail;
537 swap_stats[1] = swapavail - swapfree;
538 swap_stats[2] = swapfree;
545 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
546 arc_stats[0] = arc_stat >> 10;
547 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
548 arc_stats[1] = arc_stat >> 10;
549 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
550 arc_stats[2] = arc_stat >> 10;
551 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
552 arc_stats[3] = arc_stat >> 10;
553 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
554 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
555 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
556 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
557 arc_stats[5] = arc_stat >> 10;
561 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
562 carc_stats[0] = arc_stat >> 10;
563 carc_stats[2] = arc_stat >> 10; /* For ratio */
564 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
565 carc_stats[1] = arc_stat >> 10;
566 si->carc = carc_stats;
569 /* set arrays and strings */
571 si->cpustates = pcpu_cpu_states;
574 si->cpustates = cpu_states;
577 si->memory = memory_stats;
578 si->swap = swap_stats;
582 si->last_pid = lastpid;
588 * Print how long system has been up.
589 * (Found by looking getting "boottime" from the kernel)
592 mib[1] = KERN_BOOTTIME;
593 size = sizeof(boottime);
594 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
595 boottime.tv_sec != 0) {
596 si->boottime = boottime;
598 si->boottime.tv_sec = -1;
602 #define NOPROC ((void *)-1)
605 * We need to compare data from the old process entry with the new
607 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
608 * structure to cache the mapping. We also use a negative cache pointer
609 * of NOPROC to avoid duplicate lookups.
610 * XXX: this could be done when the actual processes are fetched, we do
611 * it here out of laziness.
613 static const struct kinfo_proc *
614 get_old_proc(struct kinfo_proc *pp)
616 const struct kinfo_proc * const *oldpp, *oldp;
619 * If this is the first fetch of the kinfo_procs then we don't have
620 * any previous entries.
622 if (previous_proc_count == 0)
624 /* negative cache? */
625 if (pp->ki_udata == NOPROC)
628 if (pp->ki_udata != NULL)
629 return (pp->ki_udata);
632 * 1) look up based on pid.
633 * 2) compare process start.
634 * If we fail here, then setup a negative cache entry, otherwise
637 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
638 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
640 pp->ki_udata = NOPROC;
644 if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
645 pp->ki_udata = NOPROC;
653 * Return the total amount of IO done in blocks in/out and faults.
654 * store the values individually in the pointers passed in.
657 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
658 long *vcsw, long *ivcsw)
660 const struct kinfo_proc *oldp;
661 static struct kinfo_proc dummy;
664 oldp = get_old_proc(pp);
666 memset(&dummy, 0, sizeof(dummy));
669 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
670 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
671 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
672 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
673 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
675 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
676 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
677 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
682 * If there was a previous update, use the delta in ki_runtime over
683 * the previous interval to calculate pctcpu. Otherwise, fall back
684 * to using the kernel's ki_pctcpu.
687 proc_calc_pctcpu(struct kinfo_proc *pp)
689 const struct kinfo_proc *oldp;
691 if (previous_interval != 0) {
692 oldp = get_old_proc(pp);
694 return ((double)(pp->ki_runtime - oldp->ki_runtime)
695 / previous_interval);
698 * If this process/thread was created during the previous
699 * interval, charge it's total runtime to the previous
702 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
703 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
704 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
705 return ((double)pp->ki_runtime / previous_interval);
707 return (pctdouble(pp->ki_pctcpu));
711 * Return true if this process has used any CPU time since the
715 proc_used_cpu(struct kinfo_proc *pp)
717 const struct kinfo_proc *oldp;
719 oldp = get_old_proc(pp);
721 return (PCTCPU(pp) != 0);
722 return (pp->ki_runtime != oldp->ki_runtime ||
723 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
724 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
728 * Return the total number of block in/out and faults by a process.
731 get_io_total(const struct kinfo_proc *pp)
735 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
738 static struct handle handle;
741 get_process_info(struct system_info *si, struct process_select *sel,
742 int (*compare)(const void *, const void *))
747 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
750 struct kinfo_proc **prefp;
751 struct kinfo_proc *pp;
752 struct timespec previous_proc_uptime;
755 * If thread state was toggled, don't cache the previous processes.
757 if (previous_thread != sel->thread)
759 previous_thread = sel->thread;
762 * Save the previous process info.
764 if (previous_proc_count_max < nproc) {
765 free(previous_procs);
766 previous_procs = calloc(nproc, sizeof(*previous_procs));
768 previous_pref = calloc(nproc, sizeof(*previous_pref));
769 if (previous_procs == NULL || previous_pref == NULL) {
770 fprintf(stderr, "top: Out of memory.\n");
771 quit(TOP_EX_SYS_ERROR);
773 previous_proc_count_max = nproc;
776 for (i = 0; i < nproc; i++)
777 previous_pref[i] = &previous_procs[i];
778 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
779 qsort(previous_pref, nproc, sizeof(*previous_pref),
780 ps.thread ? compare_tid : compare_pid);
782 previous_proc_count = nproc;
783 previous_proc_uptime = proc_uptime;
784 previous_wall_time = proc_wall_time;
785 previous_interval = 0;
787 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
789 gettimeofday(&proc_wall_time, NULL);
790 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
791 memset(&proc_uptime, 0, sizeof(proc_uptime));
792 else if (previous_proc_uptime.tv_sec != 0 &&
793 previous_proc_uptime.tv_nsec != 0) {
794 previous_interval = (proc_uptime.tv_sec -
795 previous_proc_uptime.tv_sec) * 1000000;
796 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
798 previous_interval -= 1000000;
801 previous_interval += nsec / 1000;
803 if (nproc > onproc) {
804 pref = realloc(pref, sizeof(*pref) * nproc);
805 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
808 if (pref == NULL || pbase == NULL || pcpu == NULL) {
809 fprintf(stderr, "top: Out of memory.\n");
810 quit(TOP_EX_SYS_ERROR);
812 /* get a pointer to the states summary array */
813 si->procstates = process_states;
815 /* count up process states and get pointers to interesting procs */
821 memset(process_states, 0, sizeof(process_states));
823 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
825 if (pp->ki_stat == 0)
829 if (!sel->self && pp->ki_pid == mypid)
833 if (!sel->system && (pp->ki_flag & P_SYSTEM))
834 /* skip system process */
837 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
839 total_inblock += p_inblock;
840 total_oublock += p_oublock;
841 total_majflt += p_majflt;
843 process_states[(unsigned char)pp->ki_stat]++;
845 if (pp->ki_stat == SZOMB)
849 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD)
850 /* skip kernel idle process */
853 PCTCPU(pp) = proc_calc_pctcpu(pp);
854 if (sel->thread && PCTCPU(pp) > 1.0)
856 if (displaymode == DISP_CPU && !sel->idle &&
857 (!proc_used_cpu(pp) ||
858 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
859 /* skip idle or non-running processes */
862 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
863 /* skip processes that aren't doing I/O */
866 if (sel->jid != -1 && pp->ki_jid != sel->jid)
867 /* skip proc. that don't belong to the selected JID */
870 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
871 /* skip proc. that don't belong to the selected UID */
874 if (sel->pid != -1 && pp->ki_pid != sel->pid)
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;
895 static char fmt[512]; /* static area where result is built */
898 format_next_process(void* xhandle, char *(*get_userid)(int), int flags)
900 struct kinfo_proc *pp;
901 const struct kinfo_proc *oldp;
908 struct rusage ru, *rup;
910 const char *proc_fmt;
912 char jid_buf[TOP_JID_LEN + 1], swap_buf[TOP_SWAP_LEN + 1];
915 const int cmdlen = 128;
917 /* find and remember the next proc structure */
918 hp = (struct handle *)xhandle;
919 pp = *(hp->next_proc++);
922 /* get the process's command name */
923 if ((pp->ki_flag & P_INMEM) == 0) {
925 * Print swapped processes as <pname>
929 len = strlen(pp->ki_comm);
930 if (len > sizeof(pp->ki_comm) - 3)
931 len = sizeof(pp->ki_comm) - 3;
932 memmove(pp->ki_comm + 1, pp->ki_comm, len);
933 pp->ki_comm[0] = '<';
934 pp->ki_comm[len + 1] = '>';
935 pp->ki_comm[len + 2] = '\0';
939 * Convert the process's runtime from microseconds to seconds. This
940 * time includes the interrupt time although that is not wanted here.
941 * ps(1) is similarly sloppy.
943 cputime = (pp->ki_runtime + 500000) / 1000000;
945 /* calculate the base for cpu percentages */
948 /* generate "STATE" field */
949 switch (state = pp->ki_stat) {
951 if (smpmode && pp->ki_oncpu != NOCPU)
952 sprintf(status, "CPU%d", pp->ki_oncpu);
954 strcpy(status, "RUN");
957 if (pp->ki_kiflag & KI_LOCKBLOCK) {
958 sprintf(status, "*%.6s", pp->ki_lockname);
963 sprintf(status, "%.6s", pp->ki_wmesg);
967 if (state < nitems(state_abbrev)) {
968 sprintf(status, "%.6s", state_abbrev[state]);
970 sprintf(status, "?%5zu", state);
975 cmdbuf = calloc(cmdlen + 1, 1);
976 if (cmdbuf == NULL) {
977 warn("calloc(%d)", cmdlen + 1);
981 if (!(flags & FMT_SHOWARGS)) {
982 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
984 snprintf(cmdbuf, cmdlen, "%s{%s%s}", pp->ki_comm,
985 pp->ki_tdname, pp->ki_moretdname);
987 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
990 if (pp->ki_flag & P_SYSTEM ||
991 pp->ki_args == NULL ||
992 (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
994 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
996 snprintf(cmdbuf, cmdlen,
997 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1000 snprintf(cmdbuf, cmdlen,
1001 "[%s]", pp->ki_comm);
1010 argbuflen = cmdlen * 4;
1011 argbuf = calloc(argbuflen + 1, 1);
1012 if (argbuf == NULL) {
1013 warn("calloc(%zu)", argbuflen + 1);
1020 /* Extract cmd name from argv */
1021 cmd = strrchr(*args, '/');
1027 for (; (src = *args++) != NULL; ) {
1030 len = (argbuflen - (dst - argbuf) - 1) / 4;
1032 MIN(strlen(src), len),
1033 VIS_NL | VIS_CSTYLE);
1034 while (*dst != '\0')
1036 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1037 *dst++ = ' '; /* add delimiting space */
1039 if (dst != argbuf && dst[-1] == ' ')
1043 if (strcmp(cmd, pp->ki_comm) != 0) {
1044 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1046 snprintf(cmdbuf, cmdlen,
1047 "%s (%s){%s%s}", argbuf,
1048 pp->ki_comm, pp->ki_tdname,
1051 snprintf(cmdbuf, cmdlen,
1052 "%s (%s)", argbuf, pp->ki_comm);
1054 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1056 snprintf(cmdbuf, cmdlen,
1057 "%s{%s%s}", argbuf, pp->ki_tdname,
1060 strlcpy(cmdbuf, argbuf, cmdlen);
1069 snprintf(jid_buf, sizeof(jid_buf), "%*d",
1070 jidlength - 1, pp->ki_jid);
1075 snprintf(swap_buf, sizeof(swap_buf), "%*s",
1077 format_k2(pagetok(ki_swap(pp)))); /* XXX */
1079 if (displaymode == DISP_IO) {
1080 oldp = get_old_proc(pp);
1082 ru.ru_inblock = RU(pp)->ru_inblock -
1083 RU(oldp)->ru_inblock;
1084 ru.ru_oublock = RU(pp)->ru_oublock -
1085 RU(oldp)->ru_oublock;
1086 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1087 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1088 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1093 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1094 s_tot = total_inblock + total_oublock + total_majflt;
1096 snprintf(fmt, sizeof(fmt), io_Proc_format,
1099 namelength, namelength, (*get_userid)(pp->ki_ruid),
1106 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
1107 screen_width > cmdlengthdelta ?
1108 screen_width - cmdlengthdelta : 0,
1116 /* format this entry */
1118 if (state == SRUN && pp->ki_oncpu != NOCPU)
1121 cpu = pp->ki_lastcpu;
1124 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1128 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1129 (int)(sizeof(thr_buf) - 2), pp->ki_numthreads);
1131 snprintf(fmt, sizeof(fmt), proc_fmt,
1132 (ps.thread_id) ? pp->ki_tid : pp->ki_pid,
1134 namelength, namelength, (*get_userid)(pp->ki_ruid),
1136 pp->ki_pri.pri_level - PZERO,
1138 format_k2(PROCSIZE(pp)),
1139 format_k2(pagetok(pp->ki_rssize)),
1140 swaplength, swaplength, swap_buf,
1143 format_time(cputime),
1144 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1145 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1150 /* return the result */
1155 getsysctl(const char *name, void *ptr, size_t len)
1159 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1160 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1162 quit(TOP_EX_SYS_ERROR);
1165 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1166 name, (unsigned long)len, (unsigned long)nlen);
1167 quit(TOP_EX_SYS_ERROR);
1172 format_nice(const struct kinfo_proc *pp)
1174 const char *fifo, *kproc;
1176 static char nicebuf[4 + 1];
1178 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1179 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1180 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1185 * XXX: the kernel doesn't tell us the original rtprio and
1186 * doesn't really know what it was, so to recover it we
1187 * must be more chummy with the implementation than the
1188 * implementation is with itself. pri_user gives a
1189 * constant "base" priority, but is only initialized
1190 * properly for user threads. pri_native gives what the
1191 * kernel calls the "base" priority, but it isn't constant
1192 * since it is changed by priority propagation. pri_native
1193 * also isn't properly initialized for all threads, but it
1194 * is properly initialized for kernel realtime and idletime
1195 * threads. Thus we use pri_user for the base priority of
1196 * user threads (it is always correct) and pri_native for
1197 * the base priority of kernel realtime and idletime threads
1198 * (there is nothing better, and it is usually correct).
1200 * The field width and thus the buffer are too small for
1201 * values like "kr31F", but such values shouldn't occur,
1202 * and if they do then the tailing "F" is not displayed.
1204 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1205 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1206 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1207 kproc, rtpri, fifo);
1210 if (pp->ki_flag & P_KPROC)
1212 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1215 /* XXX: as above. */
1216 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1217 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1218 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1219 kproc, rtpri, fifo);
1227 /* comparison routines for qsort */
1230 compare_pid(const void *p1, const void *p2)
1232 const struct kinfo_proc * const *pp1 = p1;
1233 const struct kinfo_proc * const *pp2 = p2;
1235 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1237 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1241 compare_tid(const void *p1, const void *p2)
1243 const struct kinfo_proc * const *pp1 = p1;
1244 const struct kinfo_proc * const *pp2 = p2;
1246 assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1248 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1252 * proc_compare - comparison function for "qsort"
1253 * Compares the resource consumption of two processes using five
1254 * distinct keys. The keys (in descending order of importance) are:
1255 * percent cpu, cpu ticks, state, resident set size, total virtual
1256 * memory usage. The process states are ordered as follows (from least
1257 * to most important): WAIT, zombie, sleep, stop, start, run. The
1258 * array declaration below maps a process state index into a number
1259 * that reflects this ordering.
1262 static int sorted_state[] = {
1265 1, /* ABANDONED (WAIT) */
1273 #define ORDERKEY_PCTCPU(a, b) do { \
1276 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1277 weighted_cpu(PCTCPU((a)), (a)); \
1279 diff = PCTCPU((b)) - PCTCPU((a)); \
1281 return (diff > 0 ? 1 : -1); \
1284 #define ORDERKEY_CPTICKS(a, b) do { \
1285 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1287 return (diff > 0 ? 1 : -1); \
1290 #define ORDERKEY_STATE(a, b) do { \
1291 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1293 return (diff > 0 ? 1 : -1); \
1296 #define ORDERKEY_PRIO(a, b) do { \
1297 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1299 return (diff > 0 ? 1 : -1); \
1302 #define ORDERKEY_THREADS(a, b) do { \
1303 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1305 return (diff > 0 ? 1 : -1); \
1308 #define ORDERKEY_RSSIZE(a, b) do { \
1309 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1311 return (diff > 0 ? 1 : -1); \
1314 #define ORDERKEY_MEM(a, b) do { \
1315 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1317 return (diff > 0 ? 1 : -1); \
1320 #define ORDERKEY_JID(a, b) do { \
1321 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1323 return (diff > 0 ? 1 : -1); \
1326 #define ORDERKEY_SWAP(a, b) do { \
1327 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1329 return (diff > 0 ? 1 : -1); \
1332 /* compare_cpu - the comparison function for sorting by cpu percentage */
1335 compare_cpu(const void *arg1, const void *arg2)
1337 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1338 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1340 ORDERKEY_PCTCPU(p1, p2);
1341 ORDERKEY_CPTICKS(p1, p2);
1342 ORDERKEY_STATE(p1, p2);
1343 ORDERKEY_PRIO(p1, p2);
1344 ORDERKEY_RSSIZE(p1, p2);
1345 ORDERKEY_MEM(p1, p2);
1350 /* compare_size - the comparison function for sorting by total memory usage */
1353 compare_size(const void *arg1, const void *arg2)
1355 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1356 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1358 ORDERKEY_MEM(p1, p2);
1359 ORDERKEY_RSSIZE(p1, p2);
1360 ORDERKEY_PCTCPU(p1, p2);
1361 ORDERKEY_CPTICKS(p1, p2);
1362 ORDERKEY_STATE(p1, p2);
1363 ORDERKEY_PRIO(p1, p2);
1368 /* compare_res - the comparison function for sorting by resident set size */
1371 compare_res(const void *arg1, const void *arg2)
1373 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1374 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1376 ORDERKEY_RSSIZE(p1, p2);
1377 ORDERKEY_MEM(p1, p2);
1378 ORDERKEY_PCTCPU(p1, p2);
1379 ORDERKEY_CPTICKS(p1, p2);
1380 ORDERKEY_STATE(p1, p2);
1381 ORDERKEY_PRIO(p1, p2);
1386 /* compare_time - the comparison function for sorting by total cpu time */
1389 compare_time(const void *arg1, const void *arg2)
1391 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1392 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1394 ORDERKEY_CPTICKS(p1, p2);
1395 ORDERKEY_PCTCPU(p1, p2);
1396 ORDERKEY_STATE(p1, p2);
1397 ORDERKEY_PRIO(p1, p2);
1398 ORDERKEY_RSSIZE(p1, p2);
1399 ORDERKEY_MEM(p1, p2);
1404 /* compare_prio - the comparison function for sorting by priority */
1407 compare_prio(const void *arg1, const void *arg2)
1409 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1410 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1412 ORDERKEY_PRIO(p1, p2);
1413 ORDERKEY_CPTICKS(p1, p2);
1414 ORDERKEY_PCTCPU(p1, p2);
1415 ORDERKEY_STATE(p1, p2);
1416 ORDERKEY_RSSIZE(p1, p2);
1417 ORDERKEY_MEM(p1, p2);
1422 /* compare_threads - the comparison function for sorting by threads */
1424 compare_threads(const void *arg1, const void *arg2)
1426 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1427 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1429 ORDERKEY_THREADS(p1, p2);
1430 ORDERKEY_PCTCPU(p1, p2);
1431 ORDERKEY_CPTICKS(p1, p2);
1432 ORDERKEY_STATE(p1, p2);
1433 ORDERKEY_PRIO(p1, p2);
1434 ORDERKEY_RSSIZE(p1, p2);
1435 ORDERKEY_MEM(p1, p2);
1440 /* compare_jid - the comparison function for sorting by jid */
1442 compare_jid(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;
1447 ORDERKEY_JID(p1, p2);
1448 ORDERKEY_PCTCPU(p1, p2);
1449 ORDERKEY_CPTICKS(p1, p2);
1450 ORDERKEY_STATE(p1, p2);
1451 ORDERKEY_PRIO(p1, p2);
1452 ORDERKEY_RSSIZE(p1, p2);
1453 ORDERKEY_MEM(p1, p2);
1458 /* compare_swap - the comparison function for sorting by swap */
1460 compare_swap(const void *arg1, const void *arg2)
1462 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1463 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1465 ORDERKEY_SWAP(p1, p2);
1466 ORDERKEY_PCTCPU(p1, p2);
1467 ORDERKEY_CPTICKS(p1, p2);
1468 ORDERKEY_STATE(p1, p2);
1469 ORDERKEY_PRIO(p1, p2);
1470 ORDERKEY_RSSIZE(p1, p2);
1471 ORDERKEY_MEM(p1, p2);
1476 /* assorted comparison functions for sorting by i/o */
1479 compare_iototal(const void *arg1, const void *arg2)
1481 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1482 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1484 return (get_io_total(p2) - get_io_total(p1));
1488 compare_ioread(const void *arg1, const void *arg2)
1490 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1491 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1492 long dummy, inp1, inp2;
1494 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1495 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1497 return (inp2 - inp1);
1501 compare_iowrite(const void *arg1, const void *arg2)
1503 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1504 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1505 long dummy, oup1, oup2;
1507 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1508 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1510 return (oup2 - oup1);
1514 compare_iofault(const void *arg1, const void *arg2)
1516 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1517 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1518 long dummy, flp1, flp2;
1520 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1521 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1523 return (flp2 - flp1);
1527 compare_vcsw(const void *arg1, const void *arg2)
1529 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1530 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1531 long dummy, flp1, flp2;
1533 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1534 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1536 return (flp2 - flp1);
1540 compare_ivcsw(const void *arg1, const void *arg2)
1542 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1543 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1544 long dummy, flp1, flp2;
1546 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1547 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1549 return (flp2 - flp1);
1552 int (*compares[])(const void *arg1, const void *arg2) = {
1572 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1573 * the process does not exist.
1580 struct kinfo_proc **prefp;
1581 struct kinfo_proc *pp;
1585 while (--cnt >= 0) {
1587 if (pp->ki_pid == (pid_t)pid)
1588 return ((int)pp->ki_ruid);
1594 swapmode(int *retavail, int *retfree)
1597 struct kvm_swap swapary[1];
1598 static int pagesize = 0;
1599 static unsigned long swap_maxpages = 0;
1604 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1606 n = kvm_getswapinfo(kd, swapary, 1, 0);
1607 if (n < 0 || swapary[0].ksw_total == 0)
1611 pagesize = getpagesize();
1612 if (swap_maxpages == 0)
1613 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1615 /* ksw_total contains the total size of swap all devices which may
1616 exceed the maximum swap size allocatable in the system */
1617 if ( swapary[0].ksw_total > swap_maxpages )
1618 swapary[0].ksw_total = swap_maxpages;
1620 *retavail = CONVERT(swapary[0].ksw_total);
1621 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1623 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);