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 #define PCTCPU(pp) (pcpu[pp - pbase])
86 * These definitions control the format of the per-process area
89 static const char io_header[] =
90 " PID%*s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
92 static const char io_Proc_format[] =
93 "%5d%*s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s";
95 /* XXX: build up header instead of statically defining them.
96 * This will also allow for a "format string" to be supplied
97 * as an argument to top(1) instead of having predefined options */
98 static const char smp_header_thr_and_pid[] =
99 " %s%*s %-*.*s THR PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
100 static const char smp_header_id_only[] =
101 " %s%*s %-*.*s PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
102 static const char smp_Proc_format[] =
103 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s %2d%7s %6.2f%% %.*s";
105 static char up_header_thr_and_pid[] =
106 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
107 static char up_header_id_only[] =
108 " %s%*s %-*.*s PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
109 static char up_Proc_format[] =
110 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s%.0d%7s %6.2f%% %.*s";
113 /* process state names for the "STATE" column of the display */
114 /* the extra nulls in the string "run" are for adding a slash and
115 the processor number when needed */
117 static const char *state_abbrev[] = {
118 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
124 /* values that we stash away in _init and use in later routines */
126 static double logcpu;
128 /* these are retrieved from the kernel in _init */
130 static load_avg ccpu;
132 /* these are used in the get_ functions */
136 /* these are for calculating cpu state percentages */
138 static long cp_time[CPUSTATES];
139 static long cp_old[CPUSTATES];
140 static long cp_diff[CPUSTATES];
142 /* these are for detailing the process states */
144 static const char *procstatenames[] = {
145 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
146 " zombie, ", " waiting, ", " lock, ",
149 static int process_states[nitems(procstatenames)];
151 /* these are for detailing the cpu states */
153 static int cpu_states[CPUSTATES];
154 static const char *cpustatenames[] = {
155 "user", "nice", "system", "interrupt", "idle", NULL
158 /* these are for detailing the memory statistics */
160 static const char *memorynames[] = {
161 "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
164 static int memory_stats[nitems(memorynames)];
166 static const char *arcnames[] = {
167 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
170 static int arc_stats[nitems(arcnames)];
172 static const char *carcnames[] = {
173 "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
176 static int carc_stats[nitems(carcnames)];
178 static const char *swapnames[] = {
179 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
182 static int swap_stats[nitems(swapnames)];
185 /* these are for keeping track of the proc array */
188 static int onproc = -1;
190 static struct kinfo_proc *pbase;
191 static struct kinfo_proc **pref;
192 static struct kinfo_proc *previous_procs;
193 static struct kinfo_proc **previous_pref;
194 static int previous_proc_count = 0;
195 static int previous_proc_count_max = 0;
196 static int previous_thread;
198 /* data used for recalculating pctcpu */
200 static struct timespec proc_uptime;
201 static struct timeval proc_wall_time;
202 static struct timeval previous_wall_time;
203 static uint64_t previous_interval = 0;
205 /* total number of io operations */
206 static long total_inblock;
207 static long total_oublock;
208 static long total_majflt;
210 /* these are for getting the memory statistics */
212 static int arc_enabled;
213 static int carc_enabled;
214 static int pageshift; /* log base 2 of the pagesize */
216 /* define pagetok in terms of pageshift */
218 #define pagetok(size) ((size) << pageshift)
221 #define ki_swap(kip) \
222 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
225 * Sorting orders. The first element is the default.
227 static const char *ordernames[] = {
228 "cpu", "size", "res", "time", "pri", "threads",
229 "total", "read", "write", "fault", "vcsw", "ivcsw",
230 "jid", "swap", "pid", NULL
233 /* Per-cpu time states */
237 static unsigned long cpumask;
239 static long *pcpu_cp_time;
240 static long *pcpu_cp_old;
241 static long *pcpu_cp_diff;
242 static int *pcpu_cpu_states;
244 static int compare_swap(const void *a, const void *b);
245 static int compare_jid(const void *a, const void *b);
246 static int compare_pid(const void *a, const void *b);
247 static int compare_tid(const void *a, const void *b);
248 static const char *format_nice(const struct kinfo_proc *pp);
249 static void getsysctl(const char *name, void *ptr, size_t len);
250 static int swapmode(int *retavail, int *retfree);
251 static void update_layout(void);
252 static int find_uid(uid_t needle, int *haystack);
255 find_uid(uid_t needle, int *haystack)
259 for (; i < TOP_MAX_UIDS; ++i)
260 if ((uid_t)haystack[i] == needle)
266 toggle_pcpustats(void)
274 /* Adjust display based on ncpus and the ARC state. */
282 y_swap = 4 + arc_enabled + carc_enabled;
283 y_idlecursor = 5 + arc_enabled + carc_enabled;
284 y_message = 5 + arc_enabled + carc_enabled;
285 y_header = 6 + arc_enabled + carc_enabled;
286 y_procs = 7 + arc_enabled + carc_enabled;
287 Header_lines = 7 + arc_enabled + carc_enabled;
294 y_idlecursor += ncpus - 1;
295 y_message += ncpus - 1;
296 y_header += ncpus - 1;
297 y_procs += ncpus - 1;
298 Header_lines += ncpus - 1;
303 machine_init(struct statics *statics)
305 int i, j, empty, pagesize;
310 size = sizeof(smpmode);
311 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
313 sysctlbyname("kern.smp.active", &smpmode, &size,
315 size != sizeof(smpmode))
318 size = sizeof(arc_size);
319 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
320 NULL, 0) == 0 && arc_size != 0)
322 size = sizeof(carc_en);
324 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
325 NULL, 0) == 0 && carc_en == 1)
328 namelength = MAXLOGNAME;
329 if (smpmode && namelength > SMPUNAMELEN)
330 namelength = SMPUNAMELEN;
331 else if (namelength > UPUNAMELEN)
332 namelength = UPUNAMELEN;
334 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
338 GETSYSCTL("kern.ccpu", ccpu);
340 /* this is used in calculating WCPU -- calculate it ahead of time */
341 logcpu = log(loaddouble(ccpu));
349 /* get the page size and calculate pageshift from it */
350 pagesize = getpagesize();
352 while (pagesize > 1) {
357 /* we only need the amount of log(2)1024 for our conversion */
358 pageshift -= LOG1024;
360 /* fill in the statics information */
361 statics->procstate_names = procstatenames;
362 statics->cpustate_names = cpustatenames;
363 statics->memory_names = memorynames;
365 statics->arc_names = arcnames;
367 statics->arc_names = NULL;
369 statics->carc_names = carcnames;
371 statics->carc_names = NULL;
372 statics->swap_names = swapnames;
373 statics->order_names = ordernames;
375 /* Allocate state for per-CPU stats. */
378 GETSYSCTL("kern.smp.maxcpus", maxcpu);
379 times = calloc(maxcpu * CPUSTATES, sizeof(long));
381 err(1, "calloc for kern.smp.maxcpus");
382 size = sizeof(long) * maxcpu * CPUSTATES;
383 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
384 err(1, "sysctlbyname kern.cp_times");
385 pcpu_cp_time = calloc(1, size);
386 maxid = (size / CPUSTATES / sizeof(long)) - 1;
387 for (i = 0; i <= maxid; i++) {
389 for (j = 0; empty && j < CPUSTATES; j++) {
390 if (times[i * CPUSTATES + j] != 0)
394 cpumask |= (1ul << i);
399 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
400 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
401 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
402 statics->ncpus = ncpus;
411 format_header(const char *uname_field)
413 static char Header[128];
417 jidlength = TOP_JID_LEN + 1; /* +1 for extra left space. */
422 swaplength = TOP_SWAP_LEN + 1; /* +1 for extra left space */
426 switch (displaymode) {
429 * The logic of picking the right header is confusing, and
430 * depends on too much. We should instead have a struct of
431 * "header name", and "header format" which we build up.
432 * This would also fix the duplicate of effort into up vs smp
436 prehead = ps.thread ?
437 smp_header_id_only : smp_header_thr_and_pid;
438 snprintf(Header, sizeof(Header), prehead,
439 ps.thread_id ? " THR" : "PID",
440 jidlength, ps.jail ? " JID" : "",
441 namelength, namelength, uname_field,
442 swaplength, ps.swap ? " SWAP" : "",
443 ps.wcpu ? "WCPU" : "CPU");
445 prehead = ps.thread ?
446 up_header_id_only : up_header_thr_and_pid;
447 snprintf(Header, sizeof(Header), prehead,
448 ps.thread_id ? " THR" : "PID",
449 jidlength, ps.jail ? " JID" : "",
450 namelength, namelength, uname_field,
451 swaplength, ps.swap ? " SWAP" : "",
452 ps.wcpu ? "WCPU" : "CPU");
457 snprintf(Header, sizeof(Header), prehead,
458 jidlength, ps.jail ? " JID" : "",
459 namelength, namelength, uname_field);
462 assert("displaymode must not be set to DISP_MAX");
464 cmdlengthdelta = strlen(Header) - 7;
468 static int swappgsin = -1;
469 static int swappgsout = -1;
473 get_system_info(struct system_info *si)
475 struct loadavg sysload;
477 struct timeval boottime;
478 uint64_t arc_stat, arc_stat2;
482 /* get the CPU stats */
483 size = (maxid + 1) * CPUSTATES * sizeof(long);
484 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
485 err(1, "sysctlbyname kern.cp_times");
486 GETSYSCTL("kern.cp_time", cp_time);
487 GETSYSCTL("vm.loadavg", sysload);
488 GETSYSCTL("kern.lastpid", lastpid);
490 /* convert load averages to doubles */
491 for (i = 0; i < 3; i++)
492 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
494 /* convert cp_time counts to percentages */
495 for (i = j = 0; i <= maxid; i++) {
496 if ((cpumask & (1ul << i)) == 0)
498 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
499 &pcpu_cp_time[j * CPUSTATES],
500 &pcpu_cp_old[j * CPUSTATES],
501 &pcpu_cp_diff[j * CPUSTATES]);
504 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
506 /* sum memory & swap statistics */
508 static unsigned int swap_delay = 0;
509 static int swapavail = 0;
510 static int swapfree = 0;
511 static long bufspace = 0;
512 static uint64_t nspgsin, nspgsout;
514 GETSYSCTL("vfs.bufspace", bufspace);
515 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
516 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
517 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
518 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
519 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
520 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
521 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
522 /* convert memory stats to Kbytes */
523 memory_stats[0] = pagetok(memory_stats[0]);
524 memory_stats[1] = pagetok(memory_stats[1]);
525 memory_stats[2] = pagetok(memory_stats[2]);
526 memory_stats[3] = pagetok(memory_stats[3]);
527 memory_stats[4] = bufspace / 1024;
528 memory_stats[5] = pagetok(memory_stats[5]);
529 memory_stats[6] = -1;
537 /* compute differences between old and new swap statistic */
539 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
540 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
544 swappgsout = nspgsout;
546 /* call CPU heavy swapmode() only for changes */
547 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
548 swap_stats[3] = swapmode(&swapavail, &swapfree);
549 swap_stats[0] = swapavail;
550 swap_stats[1] = swapavail - swapfree;
551 swap_stats[2] = swapfree;
558 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
559 arc_stats[0] = arc_stat >> 10;
560 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
561 arc_stats[1] = arc_stat >> 10;
562 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
563 arc_stats[2] = arc_stat >> 10;
564 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
565 arc_stats[3] = arc_stat >> 10;
566 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
567 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
568 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
569 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
570 arc_stats[5] = arc_stat >> 10;
574 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
575 carc_stats[0] = arc_stat >> 10;
576 carc_stats[2] = arc_stat >> 10; /* For ratio */
577 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
578 carc_stats[1] = arc_stat >> 10;
579 si->carc = carc_stats;
582 /* set arrays and strings */
584 si->cpustates = pcpu_cpu_states;
587 si->cpustates = cpu_states;
590 si->memory = memory_stats;
591 si->swap = swap_stats;
595 si->last_pid = lastpid;
601 * Print how long system has been up.
602 * (Found by looking getting "boottime" from the kernel)
605 mib[1] = KERN_BOOTTIME;
606 size = sizeof(boottime);
607 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
608 boottime.tv_sec != 0) {
609 si->boottime = boottime;
611 si->boottime.tv_sec = -1;
615 #define NOPROC ((void *)-1)
618 * We need to compare data from the old process entry with the new
620 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
621 * structure to cache the mapping. We also use a negative cache pointer
622 * of NOPROC to avoid duplicate lookups.
623 * XXX: this could be done when the actual processes are fetched, we do
624 * it here out of laziness.
626 static const struct kinfo_proc *
627 get_old_proc(struct kinfo_proc *pp)
629 const struct kinfo_proc * const *oldpp, *oldp;
632 * If this is the first fetch of the kinfo_procs then we don't have
633 * any previous entries.
635 if (previous_proc_count == 0)
637 /* negative cache? */
638 if (pp->ki_udata == NOPROC)
641 if (pp->ki_udata != NULL)
642 return (pp->ki_udata);
645 * 1) look up based on pid.
646 * 2) compare process start.
647 * If we fail here, then setup a negative cache entry, otherwise
650 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
651 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
653 pp->ki_udata = NOPROC;
657 if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
658 pp->ki_udata = NOPROC;
666 * Return the total amount of IO done in blocks in/out and faults.
667 * store the values individually in the pointers passed in.
670 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
671 long *vcsw, long *ivcsw)
673 const struct kinfo_proc *oldp;
674 static struct kinfo_proc dummy;
677 oldp = get_old_proc(pp);
679 memset(&dummy, 0, sizeof(dummy));
682 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
683 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
684 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
685 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
686 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
688 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
689 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
690 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
695 * If there was a previous update, use the delta in ki_runtime over
696 * the previous interval to calculate pctcpu. Otherwise, fall back
697 * to using the kernel's ki_pctcpu.
700 proc_calc_pctcpu(struct kinfo_proc *pp)
702 const struct kinfo_proc *oldp;
704 if (previous_interval != 0) {
705 oldp = get_old_proc(pp);
707 return ((double)(pp->ki_runtime - oldp->ki_runtime)
708 / previous_interval);
711 * If this process/thread was created during the previous
712 * interval, charge it's total runtime to the previous
715 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
716 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
717 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
718 return ((double)pp->ki_runtime / previous_interval);
720 return (pctdouble(pp->ki_pctcpu));
724 * Return true if this process has used any CPU time since the
728 proc_used_cpu(struct kinfo_proc *pp)
730 const struct kinfo_proc *oldp;
732 oldp = get_old_proc(pp);
734 return (PCTCPU(pp) != 0);
735 return (pp->ki_runtime != oldp->ki_runtime ||
736 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
737 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
741 * Return the total number of block in/out and faults by a process.
744 get_io_total(const struct kinfo_proc *pp)
748 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
751 static struct handle handle;
754 get_process_info(struct system_info *si, struct process_select *sel,
755 int (*compare)(const void *, const void *))
760 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
763 struct kinfo_proc **prefp;
764 struct kinfo_proc *pp;
765 struct timespec previous_proc_uptime;
768 * If thread state was toggled, don't cache the previous processes.
770 if (previous_thread != sel->thread)
772 previous_thread = sel->thread;
775 * Save the previous process info.
777 if (previous_proc_count_max < nproc) {
778 free(previous_procs);
779 previous_procs = calloc(nproc, sizeof(*previous_procs));
781 previous_pref = calloc(nproc, sizeof(*previous_pref));
782 if (previous_procs == NULL || previous_pref == NULL) {
783 fprintf(stderr, "top: Out of memory.\n");
784 quit(TOP_EX_SYS_ERROR);
786 previous_proc_count_max = nproc;
789 for (i = 0; i < nproc; i++)
790 previous_pref[i] = &previous_procs[i];
791 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
792 qsort(previous_pref, nproc, sizeof(*previous_pref),
793 ps.thread ? compare_tid : compare_pid);
795 previous_proc_count = nproc;
796 previous_proc_uptime = proc_uptime;
797 previous_wall_time = proc_wall_time;
798 previous_interval = 0;
800 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
802 gettimeofday(&proc_wall_time, NULL);
803 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
804 memset(&proc_uptime, 0, sizeof(proc_uptime));
805 else if (previous_proc_uptime.tv_sec != 0 &&
806 previous_proc_uptime.tv_nsec != 0) {
807 previous_interval = (proc_uptime.tv_sec -
808 previous_proc_uptime.tv_sec) * 1000000;
809 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
811 previous_interval -= 1000000;
814 previous_interval += nsec / 1000;
816 if (nproc > onproc) {
817 pref = realloc(pref, sizeof(*pref) * nproc);
818 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
821 if (pref == NULL || pbase == NULL || pcpu == NULL) {
822 fprintf(stderr, "top: Out of memory.\n");
823 quit(TOP_EX_SYS_ERROR);
825 /* get a pointer to the states summary array */
826 si->procstates = process_states;
828 /* count up process states and get pointers to interesting procs */
834 memset(process_states, 0, sizeof(process_states));
836 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
838 if (pp->ki_stat == 0)
842 if (!sel->self && pp->ki_pid == mypid && sel->pid == -1)
846 if (!sel->system && (pp->ki_flag & P_SYSTEM) && sel->pid == -1)
847 /* skip system process */
850 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
852 total_inblock += p_inblock;
853 total_oublock += p_oublock;
854 total_majflt += p_majflt;
856 process_states[(unsigned char)pp->ki_stat]++;
858 if (pp->ki_stat == SZOMB)
862 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD && sel->pid == -1)
863 /* skip kernel idle process */
866 PCTCPU(pp) = proc_calc_pctcpu(pp);
867 if (sel->thread && PCTCPU(pp) > 1.0)
869 if (displaymode == DISP_CPU && !sel->idle &&
870 (!proc_used_cpu(pp) ||
871 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
872 /* skip idle or non-running processes */
875 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
876 /* skip processes that aren't doing I/O */
879 if (sel->jid != -1 && pp->ki_jid != sel->jid)
880 /* skip proc. that don't belong to the selected JID */
883 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
884 /* skip proc. that don't belong to the selected UID */
887 if (sel->pid != -1 && pp->ki_pid != sel->pid)
894 /* if requested, sort the "interesting" processes */
896 qsort(pref, active_procs, sizeof(*pref), compare);
898 /* remember active and total counts */
899 si->p_total = total_procs;
900 si->p_pactive = pref_len = active_procs;
902 /* pass back a handle */
903 handle.next_proc = pref;
904 handle.remaining = active_procs;
908 static char fmt[512]; /* static area where result is built */
911 format_next_process(void* xhandle, char *(*get_userid)(int), int flags)
913 struct kinfo_proc *pp;
914 const struct kinfo_proc *oldp;
921 struct rusage ru, *rup;
923 const char *proc_fmt;
925 char jid_buf[TOP_JID_LEN + 1], swap_buf[TOP_SWAP_LEN + 1];
928 const int cmdlen = 128;
930 /* find and remember the next proc structure */
931 hp = (struct handle *)xhandle;
932 pp = *(hp->next_proc++);
935 /* get the process's command name */
936 if ((pp->ki_flag & P_INMEM) == 0) {
938 * Print swapped processes as <pname>
942 len = strlen(pp->ki_comm);
943 if (len > sizeof(pp->ki_comm) - 3)
944 len = sizeof(pp->ki_comm) - 3;
945 memmove(pp->ki_comm + 1, pp->ki_comm, len);
946 pp->ki_comm[0] = '<';
947 pp->ki_comm[len + 1] = '>';
948 pp->ki_comm[len + 2] = '\0';
952 * Convert the process's runtime from microseconds to seconds. This
953 * time includes the interrupt time although that is not wanted here.
954 * ps(1) is similarly sloppy.
956 cputime = (pp->ki_runtime + 500000) / 1000000;
958 /* calculate the base for cpu percentages */
961 /* generate "STATE" field */
962 switch (state = pp->ki_stat) {
964 if (smpmode && pp->ki_oncpu != NOCPU)
965 sprintf(status, "CPU%d", pp->ki_oncpu);
967 strcpy(status, "RUN");
970 if (pp->ki_kiflag & KI_LOCKBLOCK) {
971 sprintf(status, "*%.6s", pp->ki_lockname);
976 sprintf(status, "%.6s", pp->ki_wmesg);
980 if (state < nitems(state_abbrev)) {
981 sprintf(status, "%.6s", state_abbrev[state]);
983 sprintf(status, "?%5zu", state);
988 cmdbuf = calloc(cmdlen + 1, 1);
989 if (cmdbuf == NULL) {
990 warn("calloc(%d)", cmdlen + 1);
994 if (!(flags & FMT_SHOWARGS)) {
995 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
997 snprintf(cmdbuf, cmdlen, "%s{%s%s}", pp->ki_comm,
998 pp->ki_tdname, pp->ki_moretdname);
1000 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
1003 if (pp->ki_flag & P_SYSTEM ||
1004 pp->ki_args == NULL ||
1005 (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
1007 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1009 snprintf(cmdbuf, cmdlen,
1010 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1013 snprintf(cmdbuf, cmdlen,
1014 "[%s]", pp->ki_comm);
1023 argbuflen = cmdlen * 4;
1024 argbuf = calloc(argbuflen + 1, 1);
1025 if (argbuf == NULL) {
1026 warn("calloc(%zu)", argbuflen + 1);
1033 /* Extract cmd name from argv */
1034 cmd = strrchr(*args, '/');
1040 for (; (src = *args++) != NULL; ) {
1043 len = (argbuflen - (dst - argbuf) - 1) / 4;
1045 MIN(strlen(src), len),
1046 VIS_NL | VIS_CSTYLE);
1047 while (*dst != '\0')
1049 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1050 *dst++ = ' '; /* add delimiting space */
1052 if (dst != argbuf && dst[-1] == ' ')
1056 if (strcmp(cmd, pp->ki_comm) != 0) {
1057 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1059 snprintf(cmdbuf, cmdlen,
1060 "%s (%s){%s%s}", argbuf,
1061 pp->ki_comm, pp->ki_tdname,
1064 snprintf(cmdbuf, cmdlen,
1065 "%s (%s)", argbuf, pp->ki_comm);
1067 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1069 snprintf(cmdbuf, cmdlen,
1070 "%s{%s%s}", argbuf, pp->ki_tdname,
1073 strlcpy(cmdbuf, argbuf, cmdlen);
1082 snprintf(jid_buf, sizeof(jid_buf), "%*d",
1083 jidlength - 1, pp->ki_jid);
1088 snprintf(swap_buf, sizeof(swap_buf), "%*s",
1090 format_k2(pagetok(ki_swap(pp)))); /* XXX */
1092 if (displaymode == DISP_IO) {
1093 oldp = get_old_proc(pp);
1095 ru.ru_inblock = RU(pp)->ru_inblock -
1096 RU(oldp)->ru_inblock;
1097 ru.ru_oublock = RU(pp)->ru_oublock -
1098 RU(oldp)->ru_oublock;
1099 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1100 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1101 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1106 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1107 s_tot = total_inblock + total_oublock + total_majflt;
1109 snprintf(fmt, sizeof(fmt), io_Proc_format,
1112 namelength, namelength, (*get_userid)(pp->ki_ruid),
1119 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
1120 screen_width > cmdlengthdelta ?
1121 screen_width - cmdlengthdelta : 0,
1129 /* format this entry */
1131 if (state == SRUN && pp->ki_oncpu != NOCPU)
1134 cpu = pp->ki_lastcpu;
1137 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1141 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1142 (int)(sizeof(thr_buf) - 2), pp->ki_numthreads);
1144 snprintf(fmt, sizeof(fmt), proc_fmt,
1145 (ps.thread_id) ? pp->ki_tid : pp->ki_pid,
1147 namelength, namelength, (*get_userid)(pp->ki_ruid),
1149 pp->ki_pri.pri_level - PZERO,
1151 format_k2(PROCSIZE(pp)),
1152 format_k2(pagetok(pp->ki_rssize)),
1153 swaplength, swaplength, swap_buf,
1156 format_time(cputime),
1157 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1158 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1163 /* return the result */
1168 getsysctl(const char *name, void *ptr, size_t len)
1172 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1173 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1175 quit(TOP_EX_SYS_ERROR);
1178 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1179 name, (unsigned long)len, (unsigned long)nlen);
1180 quit(TOP_EX_SYS_ERROR);
1185 format_nice(const struct kinfo_proc *pp)
1187 const char *fifo, *kproc;
1189 static char nicebuf[4 + 1];
1191 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1192 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1193 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1198 * XXX: the kernel doesn't tell us the original rtprio and
1199 * doesn't really know what it was, so to recover it we
1200 * must be more chummy with the implementation than the
1201 * implementation is with itself. pri_user gives a
1202 * constant "base" priority, but is only initialized
1203 * properly for user threads. pri_native gives what the
1204 * kernel calls the "base" priority, but it isn't constant
1205 * since it is changed by priority propagation. pri_native
1206 * also isn't properly initialized for all threads, but it
1207 * is properly initialized for kernel realtime and idletime
1208 * threads. Thus we use pri_user for the base priority of
1209 * user threads (it is always correct) and pri_native for
1210 * the base priority of kernel realtime and idletime threads
1211 * (there is nothing better, and it is usually correct).
1213 * The field width and thus the buffer are too small for
1214 * values like "kr31F", but such values shouldn't occur,
1215 * and if they do then the tailing "F" is not displayed.
1217 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1218 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1219 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1220 kproc, rtpri, fifo);
1223 if (pp->ki_flag & P_KPROC)
1225 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1228 /* XXX: as above. */
1229 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1230 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1231 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1232 kproc, rtpri, fifo);
1240 /* comparison routines for qsort */
1243 compare_pid(const void *p1, const void *p2)
1245 const struct kinfo_proc * const *pp1 = p1;
1246 const struct kinfo_proc * const *pp2 = p2;
1248 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1250 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1254 compare_tid(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_tid >= 0 && (*pp1)->ki_tid >= 0);
1261 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1265 * proc_compare - comparison function for "qsort"
1266 * Compares the resource consumption of two processes using five
1267 * distinct keys. The keys (in descending order of importance) are:
1268 * percent cpu, cpu ticks, state, resident set size, total virtual
1269 * memory usage. The process states are ordered as follows (from least
1270 * to most important): WAIT, zombie, sleep, stop, start, run. The
1271 * array declaration below maps a process state index into a number
1272 * that reflects this ordering.
1275 static int sorted_state[] = {
1278 1, /* ABANDONED (WAIT) */
1286 #define ORDERKEY_PCTCPU(a, b) do { \
1289 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1290 weighted_cpu(PCTCPU((a)), (a)); \
1292 diff = PCTCPU((b)) - PCTCPU((a)); \
1294 return (diff > 0 ? 1 : -1); \
1297 #define ORDERKEY_CPTICKS(a, b) do { \
1298 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1300 return (diff > 0 ? 1 : -1); \
1303 #define ORDERKEY_STATE(a, b) do { \
1304 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1306 return (diff > 0 ? 1 : -1); \
1309 #define ORDERKEY_PRIO(a, b) do { \
1310 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1312 return (diff > 0 ? 1 : -1); \
1315 #define ORDERKEY_THREADS(a, b) do { \
1316 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1318 return (diff > 0 ? 1 : -1); \
1321 #define ORDERKEY_RSSIZE(a, b) do { \
1322 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1324 return (diff > 0 ? 1 : -1); \
1327 #define ORDERKEY_MEM(a, b) do { \
1328 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1330 return (diff > 0 ? 1 : -1); \
1333 #define ORDERKEY_JID(a, b) do { \
1334 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1336 return (diff > 0 ? 1 : -1); \
1339 #define ORDERKEY_SWAP(a, b) do { \
1340 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1342 return (diff > 0 ? 1 : -1); \
1345 /* compare_cpu - the comparison function for sorting by cpu percentage */
1348 compare_cpu(const void *arg1, const void *arg2)
1350 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1351 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1353 ORDERKEY_PCTCPU(p1, p2);
1354 ORDERKEY_CPTICKS(p1, p2);
1355 ORDERKEY_STATE(p1, p2);
1356 ORDERKEY_PRIO(p1, p2);
1357 ORDERKEY_RSSIZE(p1, p2);
1358 ORDERKEY_MEM(p1, p2);
1363 /* compare_size - the comparison function for sorting by total memory usage */
1366 compare_size(const void *arg1, const void *arg2)
1368 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1369 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1371 ORDERKEY_MEM(p1, p2);
1372 ORDERKEY_RSSIZE(p1, p2);
1373 ORDERKEY_PCTCPU(p1, p2);
1374 ORDERKEY_CPTICKS(p1, p2);
1375 ORDERKEY_STATE(p1, p2);
1376 ORDERKEY_PRIO(p1, p2);
1381 /* compare_res - the comparison function for sorting by resident set size */
1384 compare_res(const void *arg1, const void *arg2)
1386 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1387 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1389 ORDERKEY_RSSIZE(p1, p2);
1390 ORDERKEY_MEM(p1, p2);
1391 ORDERKEY_PCTCPU(p1, p2);
1392 ORDERKEY_CPTICKS(p1, p2);
1393 ORDERKEY_STATE(p1, p2);
1394 ORDERKEY_PRIO(p1, p2);
1399 /* compare_time - the comparison function for sorting by total cpu time */
1402 compare_time(const void *arg1, const void *arg2)
1404 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1405 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1407 ORDERKEY_CPTICKS(p1, p2);
1408 ORDERKEY_PCTCPU(p1, p2);
1409 ORDERKEY_STATE(p1, p2);
1410 ORDERKEY_PRIO(p1, p2);
1411 ORDERKEY_RSSIZE(p1, p2);
1412 ORDERKEY_MEM(p1, p2);
1417 /* compare_prio - the comparison function for sorting by priority */
1420 compare_prio(const void *arg1, const void *arg2)
1422 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1423 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1425 ORDERKEY_PRIO(p1, p2);
1426 ORDERKEY_CPTICKS(p1, p2);
1427 ORDERKEY_PCTCPU(p1, p2);
1428 ORDERKEY_STATE(p1, p2);
1429 ORDERKEY_RSSIZE(p1, p2);
1430 ORDERKEY_MEM(p1, p2);
1435 /* compare_threads - the comparison function for sorting by threads */
1437 compare_threads(const void *arg1, const void *arg2)
1439 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1440 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1442 ORDERKEY_THREADS(p1, p2);
1443 ORDERKEY_PCTCPU(p1, p2);
1444 ORDERKEY_CPTICKS(p1, p2);
1445 ORDERKEY_STATE(p1, p2);
1446 ORDERKEY_PRIO(p1, p2);
1447 ORDERKEY_RSSIZE(p1, p2);
1448 ORDERKEY_MEM(p1, p2);
1453 /* compare_jid - the comparison function for sorting by jid */
1455 compare_jid(const void *arg1, const void *arg2)
1457 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1458 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1460 ORDERKEY_JID(p1, p2);
1461 ORDERKEY_PCTCPU(p1, p2);
1462 ORDERKEY_CPTICKS(p1, p2);
1463 ORDERKEY_STATE(p1, p2);
1464 ORDERKEY_PRIO(p1, p2);
1465 ORDERKEY_RSSIZE(p1, p2);
1466 ORDERKEY_MEM(p1, p2);
1471 /* compare_swap - the comparison function for sorting by swap */
1473 compare_swap(const void *arg1, const void *arg2)
1475 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1476 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1478 ORDERKEY_SWAP(p1, p2);
1479 ORDERKEY_PCTCPU(p1, p2);
1480 ORDERKEY_CPTICKS(p1, p2);
1481 ORDERKEY_STATE(p1, p2);
1482 ORDERKEY_PRIO(p1, p2);
1483 ORDERKEY_RSSIZE(p1, p2);
1484 ORDERKEY_MEM(p1, p2);
1489 /* assorted comparison functions for sorting by i/o */
1492 compare_iototal(const void *arg1, const void *arg2)
1494 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1495 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1497 return (get_io_total(p2) - get_io_total(p1));
1501 compare_ioread(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, inp1, inp2;
1507 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1508 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1510 return (inp2 - inp1);
1514 compare_iowrite(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, oup1, oup2;
1520 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1521 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1523 return (oup2 - oup1);
1527 compare_iofault(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, &flp1, &dummy, &dummy);
1534 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1536 return (flp2 - flp1);
1540 compare_vcsw(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, &flp1, &dummy);
1547 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1549 return (flp2 - flp1);
1553 compare_ivcsw(const void *arg1, const void *arg2)
1555 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1556 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1557 long dummy, flp1, flp2;
1559 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1560 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1562 return (flp2 - flp1);
1565 int (*compares[])(const void *arg1, const void *arg2) = {
1585 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1586 * the process does not exist.
1593 struct kinfo_proc **prefp;
1594 struct kinfo_proc *pp;
1598 while (--cnt >= 0) {
1600 if (pp->ki_pid == (pid_t)pid)
1601 return ((int)pp->ki_ruid);
1607 swapmode(int *retavail, int *retfree)
1610 struct kvm_swap swapary[1];
1611 static int pagesize = 0;
1612 static unsigned long swap_maxpages = 0;
1617 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1619 n = kvm_getswapinfo(kd, swapary, 1, 0);
1620 if (n < 0 || swapary[0].ksw_total == 0)
1624 pagesize = getpagesize();
1625 if (swap_maxpages == 0)
1626 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1628 /* ksw_total contains the total size of swap all devices which may
1629 exceed the maximum swap size allocatable in the system */
1630 if ( swapary[0].ksw_total > swap_maxpages )
1631 swapary[0].ksw_total = swap_maxpages;
1633 *retavail = CONVERT(swapary[0].ksw_total);
1634 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1636 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);