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 /* XXX: build up header instead of statically defining them.
98 * This will also allow for a "format string" to be supplied
99 * as an argument to top(1) instead of having predefined options */
100 static const char smp_header_thr_and_pid[] =
101 " %s%*s %-*.*s THR PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
102 static const char smp_header_id_only[] =
103 " %s%*s %-*.*s PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
104 static const char smp_Proc_format[] =
105 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s %2d%7s %6.2f%% %.*s";
107 static char up_header_thr_and_pid[] =
108 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
109 static char up_header_id_only[] =
110 " %s%*s %-*.*s PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
111 static char up_Proc_format[] =
112 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s%.0d%7s %6.2f%% %.*s";
115 /* process state names for the "STATE" column of the display */
116 /* the extra nulls in the string "run" are for adding a slash and
117 the processor number when needed */
119 static const char *state_abbrev[] = {
120 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
126 /* values that we stash away in _init and use in later routines */
128 static double logcpu;
130 /* these are retrieved from the kernel in _init */
132 static load_avg ccpu;
134 /* these are used in the get_ functions */
138 /* these are for calculating cpu state percentages */
140 static long cp_time[CPUSTATES];
141 static long cp_old[CPUSTATES];
142 static long cp_diff[CPUSTATES];
144 /* these are for detailing the process states */
146 static const char *procstatenames[] = {
147 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
148 " zombie, ", " waiting, ", " lock, ",
151 static int process_states[nitems(procstatenames)];
153 /* these are for detailing the cpu states */
155 static int cpu_states[CPUSTATES];
156 static const char *cpustatenames[] = {
157 "user", "nice", "system", "interrupt", "idle", NULL
160 /* these are for detailing the memory statistics */
162 static const char *memorynames[] = {
163 "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
166 static int memory_stats[nitems(memorynames)];
168 static const char *arcnames[] = {
169 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
172 static int arc_stats[nitems(arcnames)];
174 static const char *carcnames[] = {
175 "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
178 static int carc_stats[nitems(carcnames)];
180 static const char *swapnames[] = {
181 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
184 static int swap_stats[nitems(swapnames)];
187 /* these are for keeping track of the proc array */
190 static int onproc = -1;
192 static struct kinfo_proc *pbase;
193 static struct kinfo_proc **pref;
194 static struct kinfo_proc *previous_procs;
195 static struct kinfo_proc **previous_pref;
196 static int previous_proc_count = 0;
197 static int previous_proc_count_max = 0;
198 static int previous_thread;
200 /* data used for recalculating pctcpu */
202 static struct timespec proc_uptime;
203 static struct timeval proc_wall_time;
204 static struct timeval previous_wall_time;
205 static uint64_t previous_interval = 0;
207 /* total number of io operations */
208 static long total_inblock;
209 static long total_oublock;
210 static long total_majflt;
212 /* these are for getting the memory statistics */
214 static int arc_enabled;
215 static int carc_enabled;
216 static int pageshift; /* log base 2 of the pagesize */
218 /* define pagetok in terms of pageshift */
220 #define pagetok(size) ((size) << pageshift)
223 #define ki_swap(kip) \
224 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
227 * Sorting orders. The first element is the default.
229 static const char *ordernames[] = {
230 "cpu", "size", "res", "time", "pri", "threads",
231 "total", "read", "write", "fault", "vcsw", "ivcsw",
232 "jid", "swap", "pid", NULL
235 /* Per-cpu time states */
239 static unsigned long cpumask;
241 static long *pcpu_cp_time;
242 static long *pcpu_cp_old;
243 static long *pcpu_cp_diff;
244 static int *pcpu_cpu_states;
246 static int compare_swap(const void *a, const void *b);
247 static int compare_jid(const void *a, const void *b);
248 static int compare_pid(const void *a, const void *b);
249 static int compare_tid(const void *a, const void *b);
250 static const char *format_nice(const struct kinfo_proc *pp);
251 static void getsysctl(const char *name, void *ptr, size_t len);
252 static int swapmode(int *retavail, int *retfree);
253 static void update_layout(void);
254 static int find_uid(uid_t needle, int *haystack);
257 find_uid(uid_t needle, int *haystack)
261 for (; i < TOP_MAX_UIDS; ++i)
262 if ((uid_t)haystack[i] == needle)
268 toggle_pcpustats(void)
276 /* Adjust display based on ncpus and the ARC state. */
284 y_swap = 4 + arc_enabled + carc_enabled;
285 y_idlecursor = 5 + arc_enabled + carc_enabled;
286 y_message = 5 + arc_enabled + carc_enabled;
287 y_header = 6 + arc_enabled + carc_enabled;
288 y_procs = 7 + arc_enabled + carc_enabled;
289 Header_lines = 7 + arc_enabled + carc_enabled;
296 y_idlecursor += ncpus - 1;
297 y_message += ncpus - 1;
298 y_header += ncpus - 1;
299 y_procs += ncpus - 1;
300 Header_lines += ncpus - 1;
305 machine_init(struct statics *statics)
307 int i, j, empty, pagesize;
312 size = sizeof(smpmode);
313 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
315 sysctlbyname("kern.smp.active", &smpmode, &size,
317 size != sizeof(smpmode))
320 size = sizeof(arc_size);
321 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
322 NULL, 0) == 0 && arc_size != 0)
324 size = sizeof(carc_en);
326 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
327 NULL, 0) == 0 && carc_en == 1)
330 namelength = MAXLOGNAME;
331 if (smpmode && namelength > SMPUNAMELEN)
332 namelength = SMPUNAMELEN;
333 else if (namelength > UPUNAMELEN)
334 namelength = UPUNAMELEN;
336 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
340 GETSYSCTL("kern.ccpu", ccpu);
342 /* this is used in calculating WCPU -- calculate it ahead of time */
343 logcpu = log(loaddouble(ccpu));
351 /* get the page size and calculate pageshift from it */
352 pagesize = getpagesize();
354 while (pagesize > 1) {
359 /* we only need the amount of log(2)1024 for our conversion */
360 pageshift -= LOG1024;
362 /* fill in the statics information */
363 statics->procstate_names = procstatenames;
364 statics->cpustate_names = cpustatenames;
365 statics->memory_names = memorynames;
367 statics->arc_names = arcnames;
369 statics->arc_names = NULL;
371 statics->carc_names = carcnames;
373 statics->carc_names = NULL;
374 statics->swap_names = swapnames;
375 statics->order_names = ordernames;
377 /* Allocate state for per-CPU stats. */
380 GETSYSCTL("kern.smp.maxcpus", maxcpu);
381 times = calloc(maxcpu * CPUSTATES, sizeof(long));
383 err(1, "calloc for kern.smp.maxcpus");
384 size = sizeof(long) * maxcpu * CPUSTATES;
385 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
386 err(1, "sysctlbyname kern.cp_times");
387 pcpu_cp_time = calloc(1, size);
388 maxid = (size / CPUSTATES / sizeof(long)) - 1;
389 for (i = 0; i <= maxid; i++) {
391 for (j = 0; empty && j < CPUSTATES; j++) {
392 if (times[i * CPUSTATES + j] != 0)
396 cpumask |= (1ul << i);
401 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
402 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
403 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
404 statics->ncpus = ncpus;
413 format_header(const char *uname_field)
415 static char Header[128];
419 jidlength = TOP_JID_LEN + 1; /* +1 for extra left space. */
424 swaplength = TOP_SWAP_LEN + 1; /* +1 for extra left space */
428 switch (displaymode) {
431 * The logic of picking the right header is confusing, and
432 * depends on too much. We should instead have a struct of
433 * "header name", and "header format" which we build up.
434 * This would also fix the duplicate of effort into up vs smp
438 prehead = ps.thread ?
439 smp_header_id_only : smp_header_thr_and_pid;
440 snprintf(Header, sizeof(Header), prehead,
441 ps.thread_id ? " THR" : "PID",
442 jidlength, ps.jail ? " JID" : "",
443 namelength, namelength, uname_field,
444 swaplength, ps.swap ? " SWAP" : "",
445 ps.wcpu ? "WCPU" : "CPU");
447 prehead = ps.thread ?
448 up_header_id_only : up_header_thr_and_pid;
449 snprintf(Header, sizeof(Header), prehead,
450 ps.thread_id ? " THR" : "PID",
451 jidlength, ps.jail ? " JID" : "",
452 namelength, namelength, uname_field,
453 swaplength, ps.swap ? " SWAP" : "",
454 ps.wcpu ? "WCPU" : "CPU");
459 snprintf(Header, sizeof(Header), prehead,
460 jidlength, ps.jail ? " JID" : "",
461 namelength, namelength, uname_field);
464 assert("displaymode must not be set to DISP_MAX");
466 cmdlengthdelta = strlen(Header) - 7;
470 static int swappgsin = -1;
471 static int swappgsout = -1;
475 get_system_info(struct system_info *si)
477 struct loadavg sysload;
479 struct timeval boottime;
480 uint64_t arc_stat, arc_stat2;
484 /* get the CPU stats */
485 size = (maxid + 1) * CPUSTATES * sizeof(long);
486 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
487 err(1, "sysctlbyname kern.cp_times");
488 GETSYSCTL("kern.cp_time", cp_time);
489 GETSYSCTL("vm.loadavg", sysload);
490 GETSYSCTL("kern.lastpid", lastpid);
492 /* convert load averages to doubles */
493 for (i = 0; i < 3; i++)
494 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
496 /* convert cp_time counts to percentages */
497 for (i = j = 0; i <= maxid; i++) {
498 if ((cpumask & (1ul << i)) == 0)
500 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
501 &pcpu_cp_time[j * CPUSTATES],
502 &pcpu_cp_old[j * CPUSTATES],
503 &pcpu_cp_diff[j * CPUSTATES]);
506 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
508 /* sum memory & swap statistics */
510 static unsigned int swap_delay = 0;
511 static int swapavail = 0;
512 static int swapfree = 0;
513 static long bufspace = 0;
514 static uint64_t nspgsin, nspgsout;
516 GETSYSCTL("vfs.bufspace", bufspace);
517 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
518 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
519 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
520 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
521 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
522 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
523 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
524 /* convert memory stats to Kbytes */
525 memory_stats[0] = pagetok(memory_stats[0]);
526 memory_stats[1] = pagetok(memory_stats[1]);
527 memory_stats[2] = pagetok(memory_stats[2]);
528 memory_stats[3] = pagetok(memory_stats[3]);
529 memory_stats[4] = bufspace / 1024;
530 memory_stats[5] = pagetok(memory_stats[5]);
531 memory_stats[6] = -1;
539 /* compute differences between old and new swap statistic */
541 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
542 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
546 swappgsout = nspgsout;
548 /* call CPU heavy swapmode() only for changes */
549 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
550 swap_stats[3] = swapmode(&swapavail, &swapfree);
551 swap_stats[0] = swapavail;
552 swap_stats[1] = swapavail - swapfree;
553 swap_stats[2] = swapfree;
560 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
561 arc_stats[0] = arc_stat >> 10;
562 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
563 arc_stats[1] = arc_stat >> 10;
564 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
565 arc_stats[2] = arc_stat >> 10;
566 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
567 arc_stats[3] = arc_stat >> 10;
568 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
569 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
570 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
571 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
572 arc_stats[5] = arc_stat >> 10;
576 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
577 carc_stats[0] = arc_stat >> 10;
578 carc_stats[2] = arc_stat >> 10; /* For ratio */
579 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
580 carc_stats[1] = arc_stat >> 10;
581 si->carc = carc_stats;
584 /* set arrays and strings */
586 si->cpustates = pcpu_cpu_states;
589 si->cpustates = cpu_states;
592 si->memory = memory_stats;
593 si->swap = swap_stats;
597 si->last_pid = lastpid;
603 * Print how long system has been up.
604 * (Found by looking getting "boottime" from the kernel)
607 mib[1] = KERN_BOOTTIME;
608 size = sizeof(boottime);
609 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
610 boottime.tv_sec != 0) {
611 si->boottime = boottime;
613 si->boottime.tv_sec = -1;
617 #define NOPROC ((void *)-1)
620 * We need to compare data from the old process entry with the new
622 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
623 * structure to cache the mapping. We also use a negative cache pointer
624 * of NOPROC to avoid duplicate lookups.
625 * XXX: this could be done when the actual processes are fetched, we do
626 * it here out of laziness.
628 static const struct kinfo_proc *
629 get_old_proc(struct kinfo_proc *pp)
631 const struct kinfo_proc * const *oldpp, *oldp;
634 * If this is the first fetch of the kinfo_procs then we don't have
635 * any previous entries.
637 if (previous_proc_count == 0)
639 /* negative cache? */
640 if (pp->ki_udata == NOPROC)
643 if (pp->ki_udata != NULL)
644 return (pp->ki_udata);
647 * 1) look up based on pid.
648 * 2) compare process start.
649 * If we fail here, then setup a negative cache entry, otherwise
652 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
653 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
655 pp->ki_udata = NOPROC;
659 if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
660 pp->ki_udata = NOPROC;
668 * Return the total amount of IO done in blocks in/out and faults.
669 * store the values individually in the pointers passed in.
672 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
673 long *vcsw, long *ivcsw)
675 const struct kinfo_proc *oldp;
676 static struct kinfo_proc dummy;
679 oldp = get_old_proc(pp);
681 memset(&dummy, 0, sizeof(dummy));
684 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
685 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
686 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
687 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
688 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
690 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
691 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
692 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
697 * If there was a previous update, use the delta in ki_runtime over
698 * the previous interval to calculate pctcpu. Otherwise, fall back
699 * to using the kernel's ki_pctcpu.
702 proc_calc_pctcpu(struct kinfo_proc *pp)
704 const struct kinfo_proc *oldp;
706 if (previous_interval != 0) {
707 oldp = get_old_proc(pp);
709 return ((double)(pp->ki_runtime - oldp->ki_runtime)
710 / previous_interval);
713 * If this process/thread was created during the previous
714 * interval, charge it's total runtime to the previous
717 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
718 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
719 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
720 return ((double)pp->ki_runtime / previous_interval);
722 return (pctdouble(pp->ki_pctcpu));
726 * Return true if this process has used any CPU time since the
730 proc_used_cpu(struct kinfo_proc *pp)
732 const struct kinfo_proc *oldp;
734 oldp = get_old_proc(pp);
736 return (PCTCPU(pp) != 0);
737 return (pp->ki_runtime != oldp->ki_runtime ||
738 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
739 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
743 * Return the total number of block in/out and faults by a process.
746 get_io_total(const struct kinfo_proc *pp)
750 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
753 static struct handle handle;
756 get_process_info(struct system_info *si, struct process_select *sel,
757 int (*compare)(const void *, const void *))
762 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
765 struct kinfo_proc **prefp;
766 struct kinfo_proc *pp;
767 struct timespec previous_proc_uptime;
770 * If thread state was toggled, don't cache the previous processes.
772 if (previous_thread != sel->thread)
774 previous_thread = sel->thread;
777 * Save the previous process info.
779 if (previous_proc_count_max < nproc) {
780 free(previous_procs);
781 previous_procs = calloc(nproc, sizeof(*previous_procs));
783 previous_pref = calloc(nproc, sizeof(*previous_pref));
784 if (previous_procs == NULL || previous_pref == NULL) {
785 fprintf(stderr, "top: Out of memory.\n");
786 quit(TOP_EX_SYS_ERROR);
788 previous_proc_count_max = nproc;
791 for (i = 0; i < nproc; i++)
792 previous_pref[i] = &previous_procs[i];
793 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
794 qsort(previous_pref, nproc, sizeof(*previous_pref),
795 ps.thread ? compare_tid : compare_pid);
797 previous_proc_count = nproc;
798 previous_proc_uptime = proc_uptime;
799 previous_wall_time = proc_wall_time;
800 previous_interval = 0;
802 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
804 gettimeofday(&proc_wall_time, NULL);
805 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
806 memset(&proc_uptime, 0, sizeof(proc_uptime));
807 else if (previous_proc_uptime.tv_sec != 0 &&
808 previous_proc_uptime.tv_nsec != 0) {
809 previous_interval = (proc_uptime.tv_sec -
810 previous_proc_uptime.tv_sec) * 1000000;
811 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
813 previous_interval -= 1000000;
816 previous_interval += nsec / 1000;
818 if (nproc > onproc) {
819 pref = realloc(pref, sizeof(*pref) * nproc);
820 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
823 if (pref == NULL || pbase == NULL || pcpu == NULL) {
824 fprintf(stderr, "top: Out of memory.\n");
825 quit(TOP_EX_SYS_ERROR);
827 /* get a pointer to the states summary array */
828 si->procstates = process_states;
830 /* count up process states and get pointers to interesting procs */
836 memset(process_states, 0, sizeof(process_states));
838 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
840 if (pp->ki_stat == 0)
844 if (!sel->self && pp->ki_pid == mypid && sel->pid == -1)
848 if (!sel->system && (pp->ki_flag & P_SYSTEM) && sel->pid == -1)
849 /* skip system process */
852 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
854 total_inblock += p_inblock;
855 total_oublock += p_oublock;
856 total_majflt += p_majflt;
858 process_states[(unsigned char)pp->ki_stat]++;
860 if (pp->ki_stat == SZOMB)
864 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD && sel->pid == -1)
865 /* skip kernel idle process */
868 PCTCPU(pp) = proc_calc_pctcpu(pp);
869 if (sel->thread && PCTCPU(pp) > 1.0)
871 if (displaymode == DISP_CPU && !sel->idle &&
872 (!proc_used_cpu(pp) ||
873 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
874 /* skip idle or non-running processes */
877 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
878 /* skip processes that aren't doing I/O */
881 if (sel->jid != -1 && pp->ki_jid != sel->jid)
882 /* skip proc. that don't belong to the selected JID */
885 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
886 /* skip proc. that don't belong to the selected UID */
889 if (sel->pid != -1 && pp->ki_pid != sel->pid)
896 /* if requested, sort the "interesting" processes */
898 qsort(pref, active_procs, sizeof(*pref), compare);
900 /* remember active and total counts */
901 si->p_total = total_procs;
902 si->p_pactive = pref_len = active_procs;
904 /* pass back a handle */
905 handle.next_proc = pref;
906 handle.remaining = active_procs;
910 static char fmt[512]; /* static area where result is built */
913 format_next_process(void* xhandle, char *(*get_userid)(int), int flags)
915 struct kinfo_proc *pp;
916 const struct kinfo_proc *oldp;
923 struct rusage ru, *rup;
925 const char *proc_fmt;
927 char jid_buf[TOP_JID_LEN + 1], swap_buf[TOP_SWAP_LEN + 1];
930 const int cmdlen = 128;
932 /* find and remember the next proc structure */
933 hp = (struct handle *)xhandle;
934 pp = *(hp->next_proc++);
937 /* get the process's command name */
938 if ((pp->ki_flag & P_INMEM) == 0) {
940 * Print swapped processes as <pname>
944 len = strlen(pp->ki_comm);
945 if (len > sizeof(pp->ki_comm) - 3)
946 len = sizeof(pp->ki_comm) - 3;
947 memmove(pp->ki_comm + 1, pp->ki_comm, len);
948 pp->ki_comm[0] = '<';
949 pp->ki_comm[len + 1] = '>';
950 pp->ki_comm[len + 2] = '\0';
954 * Convert the process's runtime from microseconds to seconds. This
955 * time includes the interrupt time although that is not wanted here.
956 * ps(1) is similarly sloppy.
958 cputime = (pp->ki_runtime + 500000) / 1000000;
960 /* calculate the base for cpu percentages */
963 /* generate "STATE" field */
964 switch (state = pp->ki_stat) {
966 if (smpmode && pp->ki_oncpu != NOCPU)
967 sprintf(status, "CPU%d", pp->ki_oncpu);
969 strcpy(status, "RUN");
972 if (pp->ki_kiflag & KI_LOCKBLOCK) {
973 sprintf(status, "*%.6s", pp->ki_lockname);
978 sprintf(status, "%.6s", pp->ki_wmesg);
982 if (state < nitems(state_abbrev)) {
983 sprintf(status, "%.6s", state_abbrev[state]);
985 sprintf(status, "?%5zu", state);
990 cmdbuf = calloc(cmdlen + 1, 1);
991 if (cmdbuf == NULL) {
992 warn("calloc(%d)", cmdlen + 1);
996 if (!(flags & FMT_SHOWARGS)) {
997 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
999 snprintf(cmdbuf, cmdlen, "%s{%s%s}", pp->ki_comm,
1000 pp->ki_tdname, pp->ki_moretdname);
1002 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
1005 if (pp->ki_flag & P_SYSTEM ||
1006 pp->ki_args == NULL ||
1007 (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
1009 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1011 snprintf(cmdbuf, cmdlen,
1012 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1015 snprintf(cmdbuf, cmdlen,
1016 "[%s]", pp->ki_comm);
1025 argbuflen = cmdlen * 4;
1026 argbuf = calloc(argbuflen + 1, 1);
1027 if (argbuf == NULL) {
1028 warn("calloc(%zu)", argbuflen + 1);
1035 /* Extract cmd name from argv */
1036 cmd = strrchr(*args, '/');
1042 for (; (src = *args++) != NULL; ) {
1045 len = (argbuflen - (dst - argbuf) - 1) / 4;
1047 MIN(strlen(src), len),
1048 VIS_NL | VIS_CSTYLE);
1049 while (*dst != '\0')
1051 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1052 *dst++ = ' '; /* add delimiting space */
1054 if (dst != argbuf && dst[-1] == ' ')
1058 if (strcmp(cmd, pp->ki_comm) != 0) {
1059 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1061 snprintf(cmdbuf, cmdlen,
1062 "%s (%s){%s%s}", argbuf,
1063 pp->ki_comm, pp->ki_tdname,
1066 snprintf(cmdbuf, cmdlen,
1067 "%s (%s)", argbuf, pp->ki_comm);
1069 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1071 snprintf(cmdbuf, cmdlen,
1072 "%s{%s%s}", argbuf, pp->ki_tdname,
1075 strlcpy(cmdbuf, argbuf, cmdlen);
1084 snprintf(jid_buf, sizeof(jid_buf), "%*d",
1085 jidlength - 1, pp->ki_jid);
1090 snprintf(swap_buf, sizeof(swap_buf), "%*s",
1092 format_k2(pagetok(ki_swap(pp)))); /* XXX */
1094 if (displaymode == DISP_IO) {
1095 oldp = get_old_proc(pp);
1097 ru.ru_inblock = RU(pp)->ru_inblock -
1098 RU(oldp)->ru_inblock;
1099 ru.ru_oublock = RU(pp)->ru_oublock -
1100 RU(oldp)->ru_oublock;
1101 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1102 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1103 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1108 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1109 s_tot = total_inblock + total_oublock + total_majflt;
1111 snprintf(fmt, sizeof(fmt), io_Proc_format,
1114 namelength, namelength, (*get_userid)(pp->ki_ruid),
1121 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
1122 screen_width > cmdlengthdelta ?
1123 screen_width - cmdlengthdelta : 0,
1131 /* format this entry */
1133 if (state == SRUN && pp->ki_oncpu != NOCPU)
1136 cpu = pp->ki_lastcpu;
1139 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1143 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1144 (int)(sizeof(thr_buf) - 2), pp->ki_numthreads);
1146 snprintf(fmt, sizeof(fmt), proc_fmt,
1147 (ps.thread_id) ? pp->ki_tid : pp->ki_pid,
1149 namelength, namelength, (*get_userid)(pp->ki_ruid),
1151 pp->ki_pri.pri_level - PZERO,
1153 format_k2(PROCSIZE(pp)),
1154 format_k2(pagetok(pp->ki_rssize)),
1155 swaplength, swaplength, swap_buf,
1158 format_time(cputime),
1159 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1160 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1165 /* return the result */
1170 getsysctl(const char *name, void *ptr, size_t len)
1174 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1175 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1177 quit(TOP_EX_SYS_ERROR);
1180 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1181 name, (unsigned long)len, (unsigned long)nlen);
1182 quit(TOP_EX_SYS_ERROR);
1187 format_nice(const struct kinfo_proc *pp)
1189 const char *fifo, *kproc;
1191 static char nicebuf[4 + 1];
1193 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1194 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1195 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1200 * XXX: the kernel doesn't tell us the original rtprio and
1201 * doesn't really know what it was, so to recover it we
1202 * must be more chummy with the implementation than the
1203 * implementation is with itself. pri_user gives a
1204 * constant "base" priority, but is only initialized
1205 * properly for user threads. pri_native gives what the
1206 * kernel calls the "base" priority, but it isn't constant
1207 * since it is changed by priority propagation. pri_native
1208 * also isn't properly initialized for all threads, but it
1209 * is properly initialized for kernel realtime and idletime
1210 * threads. Thus we use pri_user for the base priority of
1211 * user threads (it is always correct) and pri_native for
1212 * the base priority of kernel realtime and idletime threads
1213 * (there is nothing better, and it is usually correct).
1215 * The field width and thus the buffer are too small for
1216 * values like "kr31F", but such values shouldn't occur,
1217 * and if they do then the tailing "F" is not displayed.
1219 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1220 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1221 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1222 kproc, rtpri, fifo);
1225 if (pp->ki_flag & P_KPROC)
1227 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1230 /* XXX: as above. */
1231 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1232 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1233 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1234 kproc, rtpri, fifo);
1242 /* comparison routines for qsort */
1245 compare_pid(const void *p1, const void *p2)
1247 const struct kinfo_proc * const *pp1 = p1;
1248 const struct kinfo_proc * const *pp2 = p2;
1250 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1252 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1256 compare_tid(const void *p1, const void *p2)
1258 const struct kinfo_proc * const *pp1 = p1;
1259 const struct kinfo_proc * const *pp2 = p2;
1261 assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1263 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1267 * proc_compare - comparison function for "qsort"
1268 * Compares the resource consumption of two processes using five
1269 * distinct keys. The keys (in descending order of importance) are:
1270 * percent cpu, cpu ticks, state, resident set size, total virtual
1271 * memory usage. The process states are ordered as follows (from least
1272 * to most important): WAIT, zombie, sleep, stop, start, run. The
1273 * array declaration below maps a process state index into a number
1274 * that reflects this ordering.
1277 static int sorted_state[] = {
1280 1, /* ABANDONED (WAIT) */
1288 #define ORDERKEY_PCTCPU(a, b) do { \
1291 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1292 weighted_cpu(PCTCPU((a)), (a)); \
1294 diff = PCTCPU((b)) - PCTCPU((a)); \
1296 return (diff > 0 ? 1 : -1); \
1299 #define ORDERKEY_CPTICKS(a, b) do { \
1300 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1302 return (diff > 0 ? 1 : -1); \
1305 #define ORDERKEY_STATE(a, b) do { \
1306 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1308 return (diff > 0 ? 1 : -1); \
1311 #define ORDERKEY_PRIO(a, b) do { \
1312 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1314 return (diff > 0 ? 1 : -1); \
1317 #define ORDERKEY_THREADS(a, b) do { \
1318 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1320 return (diff > 0 ? 1 : -1); \
1323 #define ORDERKEY_RSSIZE(a, b) do { \
1324 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1326 return (diff > 0 ? 1 : -1); \
1329 #define ORDERKEY_MEM(a, b) do { \
1330 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1332 return (diff > 0 ? 1 : -1); \
1335 #define ORDERKEY_JID(a, b) do { \
1336 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1338 return (diff > 0 ? 1 : -1); \
1341 #define ORDERKEY_SWAP(a, b) do { \
1342 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1344 return (diff > 0 ? 1 : -1); \
1347 /* compare_cpu - the comparison function for sorting by cpu percentage */
1350 compare_cpu(const void *arg1, const void *arg2)
1352 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1353 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1355 ORDERKEY_PCTCPU(p1, p2);
1356 ORDERKEY_CPTICKS(p1, p2);
1357 ORDERKEY_STATE(p1, p2);
1358 ORDERKEY_PRIO(p1, p2);
1359 ORDERKEY_RSSIZE(p1, p2);
1360 ORDERKEY_MEM(p1, p2);
1365 /* compare_size - the comparison function for sorting by total memory usage */
1368 compare_size(const void *arg1, const void *arg2)
1370 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1371 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1373 ORDERKEY_MEM(p1, p2);
1374 ORDERKEY_RSSIZE(p1, p2);
1375 ORDERKEY_PCTCPU(p1, p2);
1376 ORDERKEY_CPTICKS(p1, p2);
1377 ORDERKEY_STATE(p1, p2);
1378 ORDERKEY_PRIO(p1, p2);
1383 /* compare_res - the comparison function for sorting by resident set size */
1386 compare_res(const void *arg1, const void *arg2)
1388 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1389 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1391 ORDERKEY_RSSIZE(p1, p2);
1392 ORDERKEY_MEM(p1, p2);
1393 ORDERKEY_PCTCPU(p1, p2);
1394 ORDERKEY_CPTICKS(p1, p2);
1395 ORDERKEY_STATE(p1, p2);
1396 ORDERKEY_PRIO(p1, p2);
1401 /* compare_time - the comparison function for sorting by total cpu time */
1404 compare_time(const void *arg1, const void *arg2)
1406 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1407 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1409 ORDERKEY_CPTICKS(p1, p2);
1410 ORDERKEY_PCTCPU(p1, p2);
1411 ORDERKEY_STATE(p1, p2);
1412 ORDERKEY_PRIO(p1, p2);
1413 ORDERKEY_RSSIZE(p1, p2);
1414 ORDERKEY_MEM(p1, p2);
1419 /* compare_prio - the comparison function for sorting by priority */
1422 compare_prio(const void *arg1, const void *arg2)
1424 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1425 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1427 ORDERKEY_PRIO(p1, p2);
1428 ORDERKEY_CPTICKS(p1, p2);
1429 ORDERKEY_PCTCPU(p1, p2);
1430 ORDERKEY_STATE(p1, p2);
1431 ORDERKEY_RSSIZE(p1, p2);
1432 ORDERKEY_MEM(p1, p2);
1437 /* compare_threads - the comparison function for sorting by threads */
1439 compare_threads(const void *arg1, const void *arg2)
1441 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1442 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1444 ORDERKEY_THREADS(p1, p2);
1445 ORDERKEY_PCTCPU(p1, p2);
1446 ORDERKEY_CPTICKS(p1, p2);
1447 ORDERKEY_STATE(p1, p2);
1448 ORDERKEY_PRIO(p1, p2);
1449 ORDERKEY_RSSIZE(p1, p2);
1450 ORDERKEY_MEM(p1, p2);
1455 /* compare_jid - the comparison function for sorting by jid */
1457 compare_jid(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;
1462 ORDERKEY_JID(p1, p2);
1463 ORDERKEY_PCTCPU(p1, p2);
1464 ORDERKEY_CPTICKS(p1, p2);
1465 ORDERKEY_STATE(p1, p2);
1466 ORDERKEY_PRIO(p1, p2);
1467 ORDERKEY_RSSIZE(p1, p2);
1468 ORDERKEY_MEM(p1, p2);
1473 /* compare_swap - the comparison function for sorting by swap */
1475 compare_swap(const void *arg1, const void *arg2)
1477 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1478 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1480 ORDERKEY_SWAP(p1, p2);
1481 ORDERKEY_PCTCPU(p1, p2);
1482 ORDERKEY_CPTICKS(p1, p2);
1483 ORDERKEY_STATE(p1, p2);
1484 ORDERKEY_PRIO(p1, p2);
1485 ORDERKEY_RSSIZE(p1, p2);
1486 ORDERKEY_MEM(p1, p2);
1491 /* assorted comparison functions for sorting by i/o */
1494 compare_iototal(const void *arg1, const void *arg2)
1496 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1497 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1499 return (get_io_total(p2) - get_io_total(p1));
1503 compare_ioread(const void *arg1, const void *arg2)
1505 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1506 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1507 long dummy, inp1, inp2;
1509 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1510 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1512 return (inp2 - inp1);
1516 compare_iowrite(const void *arg1, const void *arg2)
1518 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1519 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1520 long dummy, oup1, oup2;
1522 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1523 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1525 return (oup2 - oup1);
1529 compare_iofault(const void *arg1, const void *arg2)
1531 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1532 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1533 long dummy, flp1, flp2;
1535 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1536 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1538 return (flp2 - flp1);
1542 compare_vcsw(const void *arg1, const void *arg2)
1544 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1545 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1546 long dummy, flp1, flp2;
1548 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1549 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1551 return (flp2 - flp1);
1555 compare_ivcsw(const void *arg1, const void *arg2)
1557 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1558 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1559 long dummy, flp1, flp2;
1561 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1562 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1564 return (flp2 - flp1);
1567 int (*compares[])(const void *arg1, const void *arg2) = {
1587 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1588 * the process does not exist.
1595 struct kinfo_proc **prefp;
1596 struct kinfo_proc *pp;
1600 while (--cnt >= 0) {
1602 if (pp->ki_pid == (pid_t)pid)
1603 return ((int)pp->ki_ruid);
1609 swapmode(int *retavail, int *retfree)
1612 struct kvm_swap swapary[1];
1613 static int pagesize = 0;
1614 static unsigned long swap_maxpages = 0;
1619 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1621 n = kvm_getswapinfo(kd, swapary, 1, 0);
1622 if (n < 0 || swapary[0].ksw_total == 0)
1626 pagesize = getpagesize();
1627 if (swap_maxpages == 0)
1628 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1630 /* ksw_total contains the total size of swap all devices which may
1631 exceed the maximum swap size allocatable in the system */
1632 if ( swapary[0].ksw_total > swap_maxpages )
1633 swapary[0].ksw_total = swap_maxpages;
1635 *retavail = CONVERT(swapary[0].ksw_total);
1636 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1638 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);