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>
18 #include <sys/errno.h>
20 #include <sys/param.h>
22 #include <sys/resource.h>
23 #include <sys/rtprio.h>
24 #include <sys/signal.h>
25 #include <sys/sysctl.h>
28 #include <sys/vmmeter.h>
53 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
54 #define SMPUNAMELEN 13
57 extern struct timeval timeout;
59 enum displaymodes displaymode;
60 static int namelength = 8;
61 /* TOP_JID_LEN based on max of 999999 */
63 #define TOP_SWAP_LEN 6
65 static int swaplength;
66 static int cmdlengthdelta;
68 /* get_process_info passes back a handle. This is what it looks like: */
71 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
72 int remaining; /* number of pointers remaining */
76 /* define what weighted cpu is. */
77 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
78 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
80 /* what we consider to be process size: */
81 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
83 #define RU(pp) (&(pp)->ki_rusage)
85 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
87 #define PCTCPU(pp) (pcpu[pp - pbase])
89 /* definitions for indices in the nlist array */
92 * These definitions control the format of the per-process area
95 static const char io_header[] =
96 " PID%*s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
98 static const char io_Proc_format[] =
99 "%5d%*s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s";
101 static const char smp_header_thr_and_pid[] =
102 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
103 static const char smp_header_tid_only[] =
104 " THR%*s %-*.*s " "PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
106 static const char smp_Proc_format[] =
107 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s %2d%7s %6.2f%% %.*s";
109 static char up_header_thr_and_pid[] =
110 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
111 static char up_header_tid_only[] =
112 " THR%*s %-*.*s " "PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
114 static char up_Proc_format[] =
115 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s%.0d%7s %6.2f%% %.*s";
118 /* process state names for the "STATE" column of the display */
119 /* the extra nulls in the string "run" are for adding a slash and
120 the processor number when needed */
122 static const char *state_abbrev[] = {
123 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
129 /* values that we stash away in _init and use in later routines */
131 static double logcpu;
133 /* these are retrieved from the kernel in _init */
135 static load_avg ccpu;
137 /* these are used in the get_ functions */
141 /* these are for calculating cpu state percentages */
143 static long cp_time[CPUSTATES];
144 static long cp_old[CPUSTATES];
145 static long cp_diff[CPUSTATES];
147 /* these are for detailing the process states */
149 static const char *procstatenames[] = {
150 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
151 " zombie, ", " waiting, ", " lock, ",
154 static int process_states[nitems(procstatenames)];
156 /* these are for detailing the cpu states */
158 static int cpu_states[CPUSTATES];
159 static const char *cpustatenames[] = {
160 "user", "nice", "system", "interrupt", "idle", NULL
163 /* these are for detailing the memory statistics */
165 static const char *memorynames[] = {
166 "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
169 static int memory_stats[nitems(memorynames)];
171 static const char *arcnames[] = {
172 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
175 static int arc_stats[nitems(arcnames)];
177 static const char *carcnames[] = {
178 "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
181 static int carc_stats[nitems(carcnames)];
183 static const char *swapnames[] = {
184 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
187 static int swap_stats[nitems(swapnames)];
190 /* these are for keeping track of the proc array */
193 static int onproc = -1;
195 static struct kinfo_proc *pbase;
196 static struct kinfo_proc **pref;
197 static struct kinfo_proc *previous_procs;
198 static struct kinfo_proc **previous_pref;
199 static int previous_proc_count = 0;
200 static int previous_proc_count_max = 0;
201 static int previous_thread;
203 /* data used for recalculating pctcpu */
205 static struct timespec proc_uptime;
206 static struct timeval proc_wall_time;
207 static struct timeval previous_wall_time;
208 static uint64_t previous_interval = 0;
210 /* total number of io operations */
211 static long total_inblock;
212 static long total_oublock;
213 static long total_majflt;
215 /* these are for getting the memory statistics */
217 static int arc_enabled;
218 static int carc_enabled;
219 static int pageshift; /* log base 2 of the pagesize */
221 /* define pagetok in terms of pageshift */
223 #define pagetok(size) ((size) << pageshift)
226 #define ki_swap(kip) \
227 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
230 * Sorting orders. The first element is the default.
232 static const char *ordernames[] = {
233 "cpu", "size", "res", "time", "pri", "threads",
234 "total", "read", "write", "fault", "vcsw", "ivcsw",
235 "jid", "swap", "pid", NULL
238 /* Per-cpu time states */
242 static u_long cpumask;
244 static long *pcpu_cp_time;
245 static long *pcpu_cp_old;
246 static long *pcpu_cp_diff;
247 static int *pcpu_cpu_states;
249 static int compare_swap(const void *a, const void *b);
250 static int compare_jid(const void *a, const void *b);
251 static int compare_pid(const void *a, const void *b);
252 static int compare_tid(const void *a, const void *b);
253 static const char *format_nice(const struct kinfo_proc *pp);
254 static void getsysctl(const char *name, void *ptr, size_t len);
255 static int swapmode(int *retavail, int *retfree);
256 static void update_layout(void);
257 static int find_uid(uid_t needle, int *haystack);
260 find_uid(uid_t needle, int *haystack)
264 for (; i < TOP_MAX_UIDS; ++i)
265 if ((uid_t)haystack[i] == needle)
271 toggle_pcpustats(void)
279 /* Adjust display based on ncpus and the ARC state. */
287 y_swap = 4 + arc_enabled + carc_enabled;
288 y_idlecursor = 5 + arc_enabled + carc_enabled;
289 y_message = 5 + arc_enabled + carc_enabled;
290 y_header = 6 + arc_enabled + carc_enabled;
291 y_procs = 7 + arc_enabled + carc_enabled;
292 Header_lines = 7 + arc_enabled + carc_enabled;
299 y_idlecursor += ncpus - 1;
300 y_message += ncpus - 1;
301 y_header += ncpus - 1;
302 y_procs += ncpus - 1;
303 Header_lines += ncpus - 1;
308 machine_init(struct statics *statics)
310 int i, j, empty, pagesize;
315 size = sizeof(smpmode);
316 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
318 sysctlbyname("kern.smp.active", &smpmode, &size,
320 size != sizeof(smpmode))
323 size = sizeof(arc_size);
324 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
325 NULL, 0) == 0 && arc_size != 0)
327 size = sizeof(carc_en);
329 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
330 NULL, 0) == 0 && carc_en == 1)
333 namelength = MAXLOGNAME;
334 if (smpmode && namelength > SMPUNAMELEN)
335 namelength = SMPUNAMELEN;
336 else if (namelength > UPUNAMELEN)
337 namelength = UPUNAMELEN;
339 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
343 GETSYSCTL("kern.ccpu", ccpu);
345 /* this is used in calculating WCPU -- calculate it ahead of time */
346 logcpu = log(loaddouble(ccpu));
354 /* get the page size and calculate pageshift from it */
355 pagesize = getpagesize();
357 while (pagesize > 1) {
362 /* we only need the amount of log(2)1024 for our conversion */
363 pageshift -= LOG1024;
365 /* fill in the statics information */
366 statics->procstate_names = procstatenames;
367 statics->cpustate_names = cpustatenames;
368 statics->memory_names = memorynames;
370 statics->arc_names = arcnames;
372 statics->arc_names = NULL;
374 statics->carc_names = carcnames;
376 statics->carc_names = NULL;
377 statics->swap_names = swapnames;
378 statics->order_names = ordernames;
380 /* Allocate state for per-CPU stats. */
383 GETSYSCTL("kern.smp.maxcpus", maxcpu);
384 times = calloc(maxcpu * CPUSTATES, sizeof(long));
386 err(1, "calloc %zu bytes", size);
387 size = sizeof(long) * maxcpu * CPUSTATES;
388 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
389 err(1, "sysctlbyname kern.cp_times");
390 pcpu_cp_time = calloc(1, size);
391 maxid = (size / CPUSTATES / sizeof(long)) - 1;
392 for (i = 0; i <= maxid; i++) {
394 for (j = 0; empty && j < CPUSTATES; j++) {
395 if (times[i * CPUSTATES + j] != 0)
399 cpumask |= (1ul << i);
404 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
405 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
406 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
407 statics->ncpus = ncpus;
416 format_header(const char *uname_field)
418 static char Header[128];
422 jidlength = TOP_JID_LEN + 1; /* +1 for extra left space. */
427 swaplength = TOP_SWAP_LEN + 1; /* +1 for extra left space */
431 switch (displaymode) {
434 * The logic of picking the right header format seems reverse
435 * here because we only want to display a THR column when
436 * "thread mode" is off (and threads are not listed as
440 (ps.thread ? smp_header_tid_only : smp_header_thr_and_pid) :
441 (ps.thread ? up_header_tid_only : up_header_thr_and_pid);
442 snprintf(Header, sizeof(Header), prehead,
443 jidlength, ps.jail ? " JID" : "",
444 namelength, namelength, uname_field,
445 swaplength, ps.swap ? " SWAP" : "",
446 ps.wcpu ? "WCPU" : "CPU");
450 snprintf(Header, sizeof(Header), prehead,
451 jidlength, ps.jail ? " JID" : "",
452 namelength, namelength, uname_field);
455 assert("displaymode must not be set to DISP_MAX");
457 cmdlengthdelta = strlen(Header) - 7;
461 static int swappgsin = -1;
462 static int swappgsout = -1;
466 get_system_info(struct system_info *si)
468 struct loadavg sysload;
470 struct timeval boottime;
471 uint64_t arc_stat, arc_stat2;
475 /* get the CPU stats */
476 size = (maxid + 1) * CPUSTATES * sizeof(long);
477 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
478 err(1, "sysctlbyname kern.cp_times");
479 GETSYSCTL("kern.cp_time", cp_time);
480 GETSYSCTL("vm.loadavg", sysload);
481 GETSYSCTL("kern.lastpid", lastpid);
483 /* convert load averages to doubles */
484 for (i = 0; i < 3; i++)
485 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
487 /* convert cp_time counts to percentages */
488 for (i = j = 0; i <= maxid; i++) {
489 if ((cpumask & (1ul << i)) == 0)
491 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
492 &pcpu_cp_time[j * CPUSTATES],
493 &pcpu_cp_old[j * CPUSTATES],
494 &pcpu_cp_diff[j * CPUSTATES]);
497 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
499 /* sum memory & swap statistics */
501 static unsigned int swap_delay = 0;
502 static int swapavail = 0;
503 static int swapfree = 0;
504 static long bufspace = 0;
505 static uint64_t nspgsin, nspgsout;
507 GETSYSCTL("vfs.bufspace", bufspace);
508 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
509 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
510 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
511 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
512 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
513 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
514 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
515 /* convert memory stats to Kbytes */
516 memory_stats[0] = pagetok(memory_stats[0]);
517 memory_stats[1] = pagetok(memory_stats[1]);
518 memory_stats[2] = pagetok(memory_stats[2]);
519 memory_stats[3] = pagetok(memory_stats[3]);
520 memory_stats[4] = bufspace / 1024;
521 memory_stats[5] = pagetok(memory_stats[5]);
522 memory_stats[6] = -1;
530 /* compute differences between old and new swap statistic */
532 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
533 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
537 swappgsout = nspgsout;
539 /* call CPU heavy swapmode() only for changes */
540 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
541 swap_stats[3] = swapmode(&swapavail, &swapfree);
542 swap_stats[0] = swapavail;
543 swap_stats[1] = swapavail - swapfree;
544 swap_stats[2] = swapfree;
551 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
552 arc_stats[0] = arc_stat >> 10;
553 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
554 arc_stats[1] = arc_stat >> 10;
555 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
556 arc_stats[2] = arc_stat >> 10;
557 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
558 arc_stats[3] = arc_stat >> 10;
559 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
560 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
561 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
562 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
563 arc_stats[5] = arc_stat >> 10;
567 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
568 carc_stats[0] = arc_stat >> 10;
569 carc_stats[2] = arc_stat >> 10; /* For ratio */
570 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
571 carc_stats[1] = arc_stat >> 10;
572 si->carc = carc_stats;
575 /* set arrays and strings */
577 si->cpustates = pcpu_cpu_states;
580 si->cpustates = cpu_states;
583 si->memory = memory_stats;
584 si->swap = swap_stats;
588 si->last_pid = lastpid;
594 * Print how long system has been up.
595 * (Found by looking getting "boottime" from the kernel)
598 mib[1] = KERN_BOOTTIME;
599 size = sizeof(boottime);
600 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
601 boottime.tv_sec != 0) {
602 si->boottime = boottime;
604 si->boottime.tv_sec = -1;
608 #define NOPROC ((void *)-1)
611 * We need to compare data from the old process entry with the new
613 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
614 * structure to cache the mapping. We also use a negative cache pointer
615 * of NOPROC to avoid duplicate lookups.
616 * XXX: this could be done when the actual processes are fetched, we do
617 * it here out of laziness.
619 static const struct kinfo_proc *
620 get_old_proc(struct kinfo_proc *pp)
622 struct kinfo_proc **oldpp, *oldp;
625 * If this is the first fetch of the kinfo_procs then we don't have
626 * any previous entries.
628 if (previous_proc_count == 0)
630 /* negative cache? */
631 if (pp->ki_udata == NOPROC)
634 if (pp->ki_udata != NULL)
635 return (pp->ki_udata);
638 * 1) look up based on pid.
639 * 2) compare process start.
640 * If we fail here, then setup a negative cache entry, otherwise
643 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
644 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
646 pp->ki_udata = NOPROC;
650 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
651 pp->ki_udata = NOPROC;
659 * Return the total amount of IO done in blocks in/out and faults.
660 * store the values individually in the pointers passed in.
663 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
664 long *vcsw, long *ivcsw)
666 const struct kinfo_proc *oldp;
667 static struct kinfo_proc dummy;
670 oldp = get_old_proc(pp);
672 bzero(&dummy, sizeof(dummy));
675 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
676 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
677 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
678 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
679 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
681 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
682 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
683 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
688 * If there was a previous update, use the delta in ki_runtime over
689 * the previous interval to calculate pctcpu. Otherwise, fall back
690 * to using the kernel's ki_pctcpu.
693 proc_calc_pctcpu(struct kinfo_proc *pp)
695 const struct kinfo_proc *oldp;
697 if (previous_interval != 0) {
698 oldp = get_old_proc(pp);
700 return ((double)(pp->ki_runtime - oldp->ki_runtime)
701 / previous_interval);
704 * If this process/thread was created during the previous
705 * interval, charge it's total runtime to the previous
708 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
709 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
710 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
711 return ((double)pp->ki_runtime / previous_interval);
713 return (pctdouble(pp->ki_pctcpu));
717 * Return true if this process has used any CPU time since the
721 proc_used_cpu(struct kinfo_proc *pp)
723 const struct kinfo_proc *oldp;
725 oldp = get_old_proc(pp);
727 return (PCTCPU(pp) != 0);
728 return (pp->ki_runtime != oldp->ki_runtime ||
729 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
730 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
734 * Return the total number of block in/out and faults by a process.
737 get_io_total(const struct kinfo_proc *pp)
741 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
744 static struct handle handle;
747 get_process_info(struct system_info *si, struct process_select *sel,
748 int (*compare)(const void *, const void *))
753 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
756 struct kinfo_proc **prefp;
757 struct kinfo_proc *pp;
758 struct timespec previous_proc_uptime;
760 /* these are copied out of sel for speed */
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 (void)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 (void) 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 /* set up flags which define what we are going to select */
831 show_idle = sel->idle;
832 show_jid = sel->jid != -1;
833 show_self = sel->self == -1;
834 show_system = sel->system;
835 show_uid = sel->uid[0] != -1;
836 show_pid = sel->pid != -1;
837 show_kidle = sel->kidle;
839 /* count up process states and get pointers to interesting procs */
845 memset(process_states, 0, sizeof(process_states));
847 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
849 if (pp->ki_stat == 0)
853 if (!show_self && pp->ki_pid == sel->self)
857 if (!show_system && (pp->ki_flag & P_SYSTEM))
858 /* skip system process */
861 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
863 total_inblock += p_inblock;
864 total_oublock += p_oublock;
865 total_majflt += p_majflt;
867 process_states[(unsigned char)pp->ki_stat]++;
869 if (pp->ki_stat == SZOMB)
873 if (!show_kidle && pp->ki_tdflags & TDF_IDLETD)
874 /* skip kernel idle process */
877 PCTCPU(pp) = proc_calc_pctcpu(pp);
878 if (sel->thread && PCTCPU(pp) > 1.0)
880 if (displaymode == DISP_CPU && !show_idle &&
881 (!proc_used_cpu(pp) ||
882 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
883 /* skip idle or non-running processes */
886 if (displaymode == DISP_IO && !show_idle && p_io == 0)
887 /* skip processes that aren't doing I/O */
890 if (show_jid && pp->ki_jid != sel->jid)
891 /* skip proc. that don't belong to the selected JID */
894 if (show_uid && !find_uid(pp->ki_ruid, sel->uid))
895 /* skip proc. that don't belong to the selected UID */
898 if (show_pid && pp->ki_pid != sel->pid)
905 /* if requested, sort the "interesting" processes */
907 qsort(pref, active_procs, sizeof(*pref), compare);
909 /* remember active and total counts */
910 si->p_total = total_procs;
911 si->p_pactive = pref_len = active_procs;
913 /* pass back a handle */
914 handle.next_proc = pref;
915 handle.remaining = active_procs;
916 return ((void*)&handle);
919 static char fmt[512]; /* static area where result is built */
922 format_next_process(void* xhandle, char *(*get_userid)(int), int flags)
924 struct kinfo_proc *pp;
925 const struct kinfo_proc *oldp;
932 struct rusage ru, *rup;
934 const char *proc_fmt;
936 char jid_buf[TOP_JID_LEN + 1], swap_buf[TOP_SWAP_LEN + 1];
939 const int cmdlen = 128;
941 /* find and remember the next proc structure */
942 hp = (struct handle *)xhandle;
943 pp = *(hp->next_proc++);
946 /* get the process's command name */
947 if ((pp->ki_flag & P_INMEM) == 0) {
949 * Print swapped processes as <pname>
953 len = strlen(pp->ki_comm);
954 if (len > sizeof(pp->ki_comm) - 3)
955 len = sizeof(pp->ki_comm) - 3;
956 memmove(pp->ki_comm + 1, pp->ki_comm, len);
957 pp->ki_comm[0] = '<';
958 pp->ki_comm[len + 1] = '>';
959 pp->ki_comm[len + 2] = '\0';
963 * Convert the process's runtime from microseconds to seconds. This
964 * time includes the interrupt time although that is not wanted here.
965 * ps(1) is similarly sloppy.
967 cputime = (pp->ki_runtime + 500000) / 1000000;
969 /* calculate the base for cpu percentages */
972 /* generate "STATE" field */
973 switch (state = pp->ki_stat) {
975 if (smpmode && pp->ki_oncpu != NOCPU)
976 sprintf(status, "CPU%d", pp->ki_oncpu);
978 strcpy(status, "RUN");
981 if (pp->ki_kiflag & KI_LOCKBLOCK) {
982 sprintf(status, "*%.6s", pp->ki_lockname);
987 sprintf(status, "%.6s", pp->ki_wmesg);
991 if (state < nitems(state_abbrev)) {
992 sprintf(status, "%.6s", state_abbrev[state]);
994 sprintf(status, "?%5zu", state);
999 cmdbuf = calloc(cmdlen + 1, 1);
1000 if (cmdbuf == NULL) {
1001 warn("calloc(%d)", cmdlen + 1);
1005 if (!(flags & FMT_SHOWARGS)) {
1006 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1008 snprintf(cmdbuf, cmdlen, "%s{%s%s}", pp->ki_comm,
1009 pp->ki_tdname, pp->ki_moretdname);
1011 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
1014 if (pp->ki_flag & P_SYSTEM ||
1015 pp->ki_args == NULL ||
1016 (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
1018 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1020 snprintf(cmdbuf, cmdlen,
1021 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1024 snprintf(cmdbuf, cmdlen,
1025 "[%s]", pp->ki_comm);
1034 argbuflen = cmdlen * 4;
1035 argbuf = calloc(argbuflen + 1, 1);
1036 if (argbuf == NULL) {
1037 warn("calloc(%zu)", argbuflen + 1);
1044 /* Extract cmd name from argv */
1045 cmd = strrchr(*args, '/');
1051 for (; (src = *args++) != NULL; ) {
1054 len = (argbuflen - (dst - argbuf) - 1) / 4;
1056 MIN(strlen(src), len),
1057 VIS_NL | VIS_CSTYLE);
1058 while (*dst != '\0')
1060 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1061 *dst++ = ' '; /* add delimiting space */
1063 if (dst != argbuf && dst[-1] == ' ')
1067 if (strcmp(cmd, pp->ki_comm) != 0) {
1068 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1070 snprintf(cmdbuf, cmdlen,
1071 "%s (%s){%s%s}", argbuf,
1072 pp->ki_comm, pp->ki_tdname,
1075 snprintf(cmdbuf, cmdlen,
1076 "%s (%s)", argbuf, pp->ki_comm);
1078 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1080 snprintf(cmdbuf, cmdlen,
1081 "%s{%s%s}", argbuf, pp->ki_tdname,
1084 strlcpy(cmdbuf, argbuf, cmdlen);
1093 snprintf(jid_buf, sizeof(jid_buf), "%*d",
1094 jidlength - 1, pp->ki_jid);
1099 snprintf(swap_buf, sizeof(swap_buf), "%*s",
1101 format_k2(pagetok(ki_swap(pp)))); /* XXX */
1103 if (displaymode == DISP_IO) {
1104 oldp = get_old_proc(pp);
1106 ru.ru_inblock = RU(pp)->ru_inblock -
1107 RU(oldp)->ru_inblock;
1108 ru.ru_oublock = RU(pp)->ru_oublock -
1109 RU(oldp)->ru_oublock;
1110 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1111 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1112 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1117 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1118 s_tot = total_inblock + total_oublock + total_majflt;
1120 snprintf(fmt, sizeof(fmt), io_Proc_format,
1123 namelength, namelength, (*get_userid)(pp->ki_ruid),
1130 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
1131 screen_width > cmdlengthdelta ?
1132 screen_width - cmdlengthdelta : 0,
1140 /* format this entry */
1142 if (state == SRUN && pp->ki_oncpu != NOCPU)
1145 cpu = pp->ki_lastcpu;
1148 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1152 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1153 (int)(sizeof(thr_buf) - 2), pp->ki_numthreads);
1155 snprintf(fmt, sizeof(fmt), proc_fmt,
1156 (ps.thread) ? pp->ki_tid : pp->ki_pid,
1158 namelength, namelength, (*get_userid)(pp->ki_ruid),
1160 pp->ki_pri.pri_level - PZERO,
1162 format_k2(PROCSIZE(pp)),
1163 format_k2(pagetok(pp->ki_rssize)),
1164 swaplength, swaplength, swap_buf,
1167 format_time(cputime),
1168 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1169 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1174 /* return the result */
1179 getsysctl(const char *name, void *ptr, size_t len)
1183 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1184 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1186 quit(TOP_EX_SYS_ERROR);
1189 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1190 name, (unsigned long)len, (unsigned long)nlen);
1191 quit(TOP_EX_SYS_ERROR);
1196 format_nice(const struct kinfo_proc *pp)
1198 const char *fifo, *kproc;
1200 static char nicebuf[4 + 1];
1202 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1203 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1204 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1209 * XXX: the kernel doesn't tell us the original rtprio and
1210 * doesn't really know what it was, so to recover it we
1211 * must be more chummy with the implementation than the
1212 * implementation is with itself. pri_user gives a
1213 * constant "base" priority, but is only initialized
1214 * properly for user threads. pri_native gives what the
1215 * kernel calls the "base" priority, but it isn't constant
1216 * since it is changed by priority propagation. pri_native
1217 * also isn't properly initialized for all threads, but it
1218 * is properly initialized for kernel realtime and idletime
1219 * threads. Thus we use pri_user for the base priority of
1220 * user threads (it is always correct) and pri_native for
1221 * the base priority of kernel realtime and idletime threads
1222 * (there is nothing better, and it is usually correct).
1224 * The field width and thus the buffer are too small for
1225 * values like "kr31F", but such values shouldn't occur,
1226 * and if they do then the tailing "F" is not displayed.
1228 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1229 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1230 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1231 kproc, rtpri, fifo);
1234 if (pp->ki_flag & P_KPROC)
1236 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1239 /* XXX: as above. */
1240 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1241 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1242 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1243 kproc, rtpri, fifo);
1251 /* comparison routines for qsort */
1254 compare_pid(const void *p1, const void *p2)
1256 const struct kinfo_proc * const *pp1 = p1;
1257 const struct kinfo_proc * const *pp2 = p2;
1259 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1261 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1265 compare_tid(const void *p1, const void *p2)
1267 const struct kinfo_proc * const *pp1 = p1;
1268 const struct kinfo_proc * const *pp2 = p2;
1270 assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1272 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1276 * proc_compare - comparison function for "qsort"
1277 * Compares the resource consumption of two processes using five
1278 * distinct keys. The keys (in descending order of importance) are:
1279 * percent cpu, cpu ticks, state, resident set size, total virtual
1280 * memory usage. The process states are ordered as follows (from least
1281 * to most important): WAIT, zombie, sleep, stop, start, run. The
1282 * array declaration below maps a process state index into a number
1283 * that reflects this ordering.
1286 static int sorted_state[] = {
1289 1, /* ABANDONED (WAIT) */
1297 #define ORDERKEY_PCTCPU(a, b) do { \
1300 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1301 weighted_cpu(PCTCPU((a)), (a)); \
1303 diff = PCTCPU((b)) - PCTCPU((a)); \
1305 return (diff > 0 ? 1 : -1); \
1308 #define ORDERKEY_CPTICKS(a, b) do { \
1309 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1311 return (diff > 0 ? 1 : -1); \
1314 #define ORDERKEY_STATE(a, b) do { \
1315 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1317 return (diff > 0 ? 1 : -1); \
1320 #define ORDERKEY_PRIO(a, b) do { \
1321 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1323 return (diff > 0 ? 1 : -1); \
1326 #define ORDERKEY_THREADS(a, b) do { \
1327 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1329 return (diff > 0 ? 1 : -1); \
1332 #define ORDERKEY_RSSIZE(a, b) do { \
1333 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1335 return (diff > 0 ? 1 : -1); \
1338 #define ORDERKEY_MEM(a, b) do { \
1339 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1341 return (diff > 0 ? 1 : -1); \
1344 #define ORDERKEY_JID(a, b) do { \
1345 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1347 return (diff > 0 ? 1 : -1); \
1350 #define ORDERKEY_SWAP(a, b) do { \
1351 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1353 return (diff > 0 ? 1 : -1); \
1356 /* compare_cpu - the comparison function for sorting by cpu percentage */
1359 compare_cpu(const void *arg1, const void *arg2)
1361 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1362 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1364 ORDERKEY_PCTCPU(p1, p2);
1365 ORDERKEY_CPTICKS(p1, p2);
1366 ORDERKEY_STATE(p1, p2);
1367 ORDERKEY_PRIO(p1, p2);
1368 ORDERKEY_RSSIZE(p1, p2);
1369 ORDERKEY_MEM(p1, p2);
1374 /* compare_size - the comparison function for sorting by total memory usage */
1377 compare_size(const void *arg1, const void *arg2)
1379 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1380 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1382 ORDERKEY_MEM(p1, p2);
1383 ORDERKEY_RSSIZE(p1, p2);
1384 ORDERKEY_PCTCPU(p1, p2);
1385 ORDERKEY_CPTICKS(p1, p2);
1386 ORDERKEY_STATE(p1, p2);
1387 ORDERKEY_PRIO(p1, p2);
1392 /* compare_res - the comparison function for sorting by resident set size */
1395 compare_res(const void *arg1, const void *arg2)
1397 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1398 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1400 ORDERKEY_RSSIZE(p1, p2);
1401 ORDERKEY_MEM(p1, p2);
1402 ORDERKEY_PCTCPU(p1, p2);
1403 ORDERKEY_CPTICKS(p1, p2);
1404 ORDERKEY_STATE(p1, p2);
1405 ORDERKEY_PRIO(p1, p2);
1410 /* compare_time - the comparison function for sorting by total cpu time */
1413 compare_time(const void *arg1, const void *arg2)
1415 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1416 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1418 ORDERKEY_CPTICKS(p1, p2);
1419 ORDERKEY_PCTCPU(p1, p2);
1420 ORDERKEY_STATE(p1, p2);
1421 ORDERKEY_PRIO(p1, p2);
1422 ORDERKEY_RSSIZE(p1, p2);
1423 ORDERKEY_MEM(p1, p2);
1428 /* compare_prio - the comparison function for sorting by priority */
1431 compare_prio(const void *arg1, const void *arg2)
1433 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1434 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1436 ORDERKEY_PRIO(p1, p2);
1437 ORDERKEY_CPTICKS(p1, p2);
1438 ORDERKEY_PCTCPU(p1, p2);
1439 ORDERKEY_STATE(p1, p2);
1440 ORDERKEY_RSSIZE(p1, p2);
1441 ORDERKEY_MEM(p1, p2);
1446 /* compare_threads - the comparison function for sorting by threads */
1448 compare_threads(const void *arg1, const void *arg2)
1450 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1451 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1453 ORDERKEY_THREADS(p1, p2);
1454 ORDERKEY_PCTCPU(p1, p2);
1455 ORDERKEY_CPTICKS(p1, p2);
1456 ORDERKEY_STATE(p1, p2);
1457 ORDERKEY_PRIO(p1, p2);
1458 ORDERKEY_RSSIZE(p1, p2);
1459 ORDERKEY_MEM(p1, p2);
1464 /* compare_jid - the comparison function for sorting by jid */
1466 compare_jid(const void *arg1, const void *arg2)
1468 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1469 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1471 ORDERKEY_JID(p1, p2);
1472 ORDERKEY_PCTCPU(p1, p2);
1473 ORDERKEY_CPTICKS(p1, p2);
1474 ORDERKEY_STATE(p1, p2);
1475 ORDERKEY_PRIO(p1, p2);
1476 ORDERKEY_RSSIZE(p1, p2);
1477 ORDERKEY_MEM(p1, p2);
1482 /* compare_swap - the comparison function for sorting by swap */
1484 compare_swap(const void *arg1, const void *arg2)
1486 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1487 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1489 ORDERKEY_SWAP(p1, p2);
1490 ORDERKEY_PCTCPU(p1, p2);
1491 ORDERKEY_CPTICKS(p1, p2);
1492 ORDERKEY_STATE(p1, p2);
1493 ORDERKEY_PRIO(p1, p2);
1494 ORDERKEY_RSSIZE(p1, p2);
1495 ORDERKEY_MEM(p1, p2);
1500 /* assorted comparison functions for sorting by i/o */
1503 compare_iototal(const void *arg1, const void *arg2)
1505 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1506 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1508 return (get_io_total(p2) - get_io_total(p1));
1512 compare_ioread(const void *arg1, const void *arg2)
1514 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1515 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1516 long dummy, inp1, inp2;
1518 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1519 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1521 return (inp2 - inp1);
1525 compare_iowrite(const void *arg1, const void *arg2)
1527 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1528 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1529 long dummy, oup1, oup2;
1531 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1532 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1534 return (oup2 - oup1);
1538 compare_iofault(const void *arg1, const void *arg2)
1540 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1541 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1542 long dummy, flp1, flp2;
1544 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1545 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1547 return (flp2 - flp1);
1551 compare_vcsw(const void *arg1, const void *arg2)
1553 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1554 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1555 long dummy, flp1, flp2;
1557 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1558 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1560 return (flp2 - flp1);
1564 compare_ivcsw(const void *arg1, const void *arg2)
1566 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1567 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1568 long dummy, flp1, flp2;
1570 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1571 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1573 return (flp2 - flp1);
1576 int (*compares[])(const void *arg1, const void *arg2) = {
1596 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1597 * the process does not exist.
1604 struct kinfo_proc **prefp;
1605 struct kinfo_proc *pp;
1609 while (--cnt >= 0) {
1611 if (pp->ki_pid == (pid_t)pid)
1612 return ((int)pp->ki_ruid);
1618 swapmode(int *retavail, int *retfree)
1621 struct kvm_swap swapary[1];
1622 static int pagesize = 0;
1623 static u_long swap_maxpages = 0;
1628 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1630 n = kvm_getswapinfo(kd, swapary, 1, 0);
1631 if (n < 0 || swapary[0].ksw_total == 0)
1635 pagesize = getpagesize();
1636 if (swap_maxpages == 0)
1637 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1639 /* ksw_total contains the total size of swap all devices which may
1640 exceed the maximum swap size allocatable in the system */
1641 if ( swapary[0].ksw_total > swap_maxpages )
1642 swapary[0].ksw_total = swap_maxpages;
1644 *retavail = CONVERT(swapary[0].ksw_total);
1645 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1647 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);