2 * top - a top users display for Unix
4 * SYNOPSIS: For FreeBSD-2.x and later
7 * Originally written for BSD4.4 system by Christos Zoulas.
8 * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9 * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10 * by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
12 * This is the machine-dependent module for FreeBSD 2.2
14 * FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
18 * AUTHOR: Christos Zoulas <christos@ee.cornell.edu>
19 * Steven Wallace <swallace@freebsd.org>
20 * Wolfram Schneider <wosch@FreeBSD.org>
21 * Thomas Moestl <tmoestl@gmx.net>
26 #include <sys/param.h>
27 #include <sys/errno.h>
30 #include <sys/resource.h>
31 #include <sys/rtprio.h>
32 #include <sys/signal.h>
33 #include <sys/sysctl.h>
36 #include <sys/vmmeter.h>
57 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
58 #define SMPUNAMELEN 13
61 extern struct process_select ps;
62 extern char* printable(char *);
64 enum displaymodes displaymode;
65 #ifdef TOP_USERNAME_LEN
66 static int namelength = TOP_USERNAME_LEN;
68 static int namelength = 8;
70 static int cmdlengthdelta;
72 /* Prototypes for top internals */
75 /* get_process_info passes back a handle. This is what it looks like: */
78 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
79 int remaining; /* number of pointers remaining */
82 /* declarations for load_avg */
85 /* define what weighted cpu is. */
86 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
87 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
89 /* what we consider to be process size: */
90 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
92 #define RU(pp) (&(pp)->ki_rusage)
94 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
97 /* definitions for indices in the nlist array */
100 * These definitions control the format of the per-process area
103 static char io_header[] =
104 " PID%s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
106 #define io_Proc_format \
107 "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
109 static char smp_header_thr[] =
110 " PID%s %-*.*s THR PRI NICE SIZE RES STATE C TIME %7s COMMAND";
111 static char smp_header[] =
112 " PID%s %-*.*s " "PRI NICE SIZE RES STATE C TIME %7s COMMAND";
114 #define smp_Proc_format \
115 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %2d%7s %6.2f%% %.*s"
117 static char up_header_thr[] =
118 " PID%s %-*.*s THR PRI NICE SIZE RES STATE TIME %7s COMMAND";
119 static char up_header[] =
120 " PID%s %-*.*s " "PRI NICE SIZE RES STATE TIME %7s COMMAND";
122 #define up_Proc_format \
123 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %6.2f%% %.*s"
126 /* process state names for the "STATE" column of the display */
127 /* the extra nulls in the string "run" are for adding a slash and
128 the processor number when needed */
130 char *state_abbrev[] = {
131 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
137 /* values that we stash away in _init and use in later routines */
139 static double logcpu;
141 /* these are retrieved from the kernel in _init */
143 static load_avg ccpu;
145 /* these are used in the get_ functions */
149 /* these are for calculating cpu state percentages */
151 static long cp_time[CPUSTATES];
152 static long cp_old[CPUSTATES];
153 static long cp_diff[CPUSTATES];
155 /* these are for detailing the process states */
157 int process_states[8];
158 char *procstatenames[] = {
159 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
160 " zombie, ", " waiting, ", " lock, ",
164 /* these are for detailing the cpu states */
166 int cpu_states[CPUSTATES];
167 char *cpustatenames[] = {
168 "user", "nice", "system", "interrupt", "idle", NULL
171 /* these are for detailing the memory statistics */
174 char *memorynames[] = {
175 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
181 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
186 char *swapnames[] = {
187 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
192 /* these are for keeping track of the proc array */
195 static int onproc = -1;
197 static struct kinfo_proc *pbase;
198 static struct kinfo_proc **pref;
199 static struct kinfo_proc *previous_procs;
200 static struct kinfo_proc **previous_pref;
201 static int previous_proc_count = 0;
202 static int previous_proc_count_max = 0;
203 static int arc_enabled;
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 pageshift; /* log base 2 of the pagesize */
214 /* define pagetok in terms of pageshift */
216 #define pagetok(size) ((size) << pageshift)
218 /* useful externals */
223 * Sorting orders. The first element is the default.
225 char *ordernames[] = {
226 "cpu", "size", "res", "time", "pri", "threads",
227 "total", "read", "write", "fault", "vcsw", "ivcsw",
232 /* Per-cpu time states */
236 static u_long cpumask;
238 static long *pcpu_cp_time;
239 static long *pcpu_cp_old;
240 static long *pcpu_cp_diff;
241 static int *pcpu_cpu_states;
243 static int compare_jid(const void *a, const void *b);
244 static int compare_pid(const void *a, const void *b);
245 static int compare_tid(const void *a, const void *b);
246 static const char *format_nice(const struct kinfo_proc *pp);
247 static void getsysctl(const char *name, void *ptr, size_t len);
248 static int swapmode(int *retavail, int *retfree);
249 static void update_layout(void);
252 toggle_pcpustats(void)
260 /* Adjust display based on ncpus and the ARC state. */
267 y_swap = 4 + arc_enabled;
268 y_idlecursor = 5 + arc_enabled;
269 y_message = 5 + arc_enabled;
270 y_header = 6 + arc_enabled;
271 y_procs = 7 + arc_enabled;
272 Header_lines = 7 + arc_enabled;
278 y_idlecursor += ncpus - 1;
279 y_message += ncpus - 1;
280 y_header += ncpus - 1;
281 y_procs += ncpus - 1;
282 Header_lines += ncpus - 1;
287 machine_init(struct statics *statics, char do_unames)
289 int i, j, empty, pagesize;
294 size = sizeof(smpmode);
295 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
297 sysctlbyname("kern.smp.active", &smpmode, &size,
299 size != sizeof(smpmode))
302 size = sizeof(arc_size);
303 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
304 NULL, 0) == 0 && arc_size != 0)
308 while ((pw = getpwent()) != NULL) {
309 if (strlen(pw->pw_name) > namelength)
310 namelength = strlen(pw->pw_name);
313 if (smpmode && namelength > SMPUNAMELEN)
314 namelength = SMPUNAMELEN;
315 else if (namelength > UPUNAMELEN)
316 namelength = UPUNAMELEN;
318 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
322 GETSYSCTL("kern.ccpu", ccpu);
324 /* this is used in calculating WCPU -- calculate it ahead of time */
325 logcpu = log(loaddouble(ccpu));
332 /* get the page size and calculate pageshift from it */
333 pagesize = getpagesize();
335 while (pagesize > 1) {
340 /* we only need the amount of log(2)1024 for our conversion */
341 pageshift -= LOG1024;
343 /* fill in the statics information */
344 statics->procstate_names = procstatenames;
345 statics->cpustate_names = cpustatenames;
346 statics->memory_names = memorynames;
348 statics->arc_names = arcnames;
350 statics->arc_names = NULL;
351 statics->swap_names = swapnames;
353 statics->order_names = ordernames;
356 /* Allocate state for per-CPU stats. */
359 GETSYSCTL("kern.smp.maxcpus", maxcpu);
360 size = sizeof(long) * maxcpu * CPUSTATES;
361 times = malloc(size);
363 err(1, "malloc %zd bytes", size);
364 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
365 err(1, "sysctlbyname kern.cp_times");
366 pcpu_cp_time = calloc(1, size);
367 maxid = (size / CPUSTATES / sizeof(long)) - 1;
368 for (i = 0; i <= maxid; i++) {
370 for (j = 0; empty && j < CPUSTATES; j++) {
371 if (times[i * CPUSTATES + j] != 0)
375 cpumask |= (1ul << i);
379 size = sizeof(long) * ncpus * CPUSTATES;
380 pcpu_cp_old = calloc(1, size);
381 pcpu_cp_diff = calloc(1, size);
382 pcpu_cpu_states = calloc(1, size);
383 statics->ncpus = ncpus;
392 format_header(char *uname_field)
394 static char Header[128];
397 switch (displaymode) {
400 * The logic of picking the right header format seems reverse
401 * here because we only want to display a THR column when
402 * "thread mode" is off (and threads are not listed as
406 (ps.thread ? smp_header : smp_header_thr) :
407 (ps.thread ? up_header : up_header_thr);
408 snprintf(Header, sizeof(Header), prehead,
409 ps.jail ? " JID" : "",
410 namelength, namelength, uname_field,
411 ps.wcpu ? "WCPU" : "CPU");
415 snprintf(Header, sizeof(Header), prehead,
416 ps.jail ? " JID" : "",
417 namelength, namelength, uname_field);
420 cmdlengthdelta = strlen(Header) - 7;
424 static int swappgsin = -1;
425 static int swappgsout = -1;
426 extern struct timeval timeout;
430 get_system_info(struct system_info *si)
433 struct loadavg sysload;
435 struct timeval boottime;
436 uint64_t arc_stat, arc_stat2;
440 /* get the CPU stats */
441 size = (maxid + 1) * CPUSTATES * sizeof(long);
442 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
443 err(1, "sysctlbyname kern.cp_times");
444 GETSYSCTL("kern.cp_time", cp_time);
445 GETSYSCTL("vm.loadavg", sysload);
446 GETSYSCTL("kern.lastpid", lastpid);
448 /* convert load averages to doubles */
449 for (i = 0; i < 3; i++)
450 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
452 /* convert cp_time counts to percentages */
453 for (i = j = 0; i <= maxid; i++) {
454 if ((cpumask & (1ul << i)) == 0)
456 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
457 &pcpu_cp_time[j * CPUSTATES],
458 &pcpu_cp_old[j * CPUSTATES],
459 &pcpu_cp_diff[j * CPUSTATES]);
462 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
464 /* sum memory & swap statistics */
466 static unsigned int swap_delay = 0;
467 static int swapavail = 0;
468 static int swapfree = 0;
469 static long bufspace = 0;
470 static int nspgsin, nspgsout;
472 GETSYSCTL("vfs.bufspace", bufspace);
473 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
474 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
475 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
476 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
477 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
478 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
479 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
480 /* convert memory stats to Kbytes */
481 memory_stats[0] = pagetok(memory_stats[0]);
482 memory_stats[1] = pagetok(memory_stats[1]);
483 memory_stats[2] = pagetok(memory_stats[2]);
484 memory_stats[3] = pagetok(memory_stats[3]);
485 memory_stats[4] = bufspace / 1024;
486 memory_stats[5] = pagetok(memory_stats[5]);
487 memory_stats[6] = -1;
495 /* compute differences between old and new swap statistic */
497 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
498 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
502 swappgsout = nspgsout;
504 /* call CPU heavy swapmode() only for changes */
505 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
506 swap_stats[3] = swapmode(&swapavail, &swapfree);
507 swap_stats[0] = swapavail;
508 swap_stats[1] = swapavail - swapfree;
509 swap_stats[2] = swapfree;
516 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
517 arc_stats[0] = arc_stat >> 10;
518 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
519 arc_stats[1] = arc_stat >> 10;
520 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
521 arc_stats[2] = arc_stat >> 10;
522 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
523 arc_stats[3] = arc_stat >> 10;
524 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
525 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
526 arc_stats[4] = arc_stat + arc_stat2 >> 10;
527 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
528 arc_stats[5] = arc_stat >> 10;
532 /* set arrays and strings */
534 si->cpustates = pcpu_cpu_states;
537 si->cpustates = cpu_states;
540 si->memory = memory_stats;
541 si->swap = swap_stats;
545 si->last_pid = lastpid;
551 * Print how long system has been up.
552 * (Found by looking getting "boottime" from the kernel)
555 mib[1] = KERN_BOOTTIME;
556 size = sizeof(boottime);
557 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
558 boottime.tv_sec != 0) {
559 si->boottime = boottime;
561 si->boottime.tv_sec = -1;
565 #define NOPROC ((void *)-1)
568 * We need to compare data from the old process entry with the new
570 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
571 * structure to cache the mapping. We also use a negative cache pointer
572 * of NOPROC to avoid duplicate lookups.
573 * XXX: this could be done when the actual processes are fetched, we do
574 * it here out of laziness.
576 const struct kinfo_proc *
577 get_old_proc(struct kinfo_proc *pp)
579 struct kinfo_proc **oldpp, *oldp;
582 * If this is the first fetch of the kinfo_procs then we don't have
583 * any previous entries.
585 if (previous_proc_count == 0)
587 /* negative cache? */
588 if (pp->ki_udata == NOPROC)
591 if (pp->ki_udata != NULL)
592 return (pp->ki_udata);
595 * 1) look up based on pid.
596 * 2) compare process start.
597 * If we fail here, then setup a negative cache entry, otherwise
600 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
601 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
603 pp->ki_udata = NOPROC;
607 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
608 pp->ki_udata = NOPROC;
616 * Return the total amount of IO done in blocks in/out and faults.
617 * store the values individually in the pointers passed in.
620 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
621 long *vcsw, long *ivcsw)
623 const struct kinfo_proc *oldp;
624 static struct kinfo_proc dummy;
627 oldp = get_old_proc(pp);
629 bzero(&dummy, sizeof(dummy));
632 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
633 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
634 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
635 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
636 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
638 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
639 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
640 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
645 * Return the total number of block in/out and faults by a process.
648 get_io_total(struct kinfo_proc *pp)
652 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
655 static struct handle handle;
658 get_process_info(struct system_info *si, struct process_select *sel,
659 int (*compare)(const void *, const void *))
664 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
666 struct kinfo_proc **prefp;
667 struct kinfo_proc *pp;
669 /* these are copied out of sel for speed */
678 * Save the previous process info.
680 if (previous_proc_count_max < nproc) {
681 free(previous_procs);
682 previous_procs = malloc(nproc * sizeof(*previous_procs));
684 previous_pref = malloc(nproc * sizeof(*previous_pref));
685 if (previous_procs == NULL || previous_pref == NULL) {
686 (void) fprintf(stderr, "top: Out of memory.\n");
689 previous_proc_count_max = nproc;
692 for (i = 0; i < nproc; i++)
693 previous_pref[i] = &previous_procs[i];
694 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
695 qsort(previous_pref, nproc, sizeof(*previous_pref),
696 ps.thread ? compare_tid : compare_pid);
698 previous_proc_count = nproc;
700 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
703 pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
704 if (pref == NULL || pbase == NULL) {
705 (void) fprintf(stderr, "top: Out of memory.\n");
708 /* get a pointer to the states summary array */
709 si->procstates = process_states;
711 /* set up flags which define what we are going to select */
712 show_idle = sel->idle;
713 show_self = sel->self == -1;
714 show_system = sel->system;
715 show_uid = sel->uid != -1;
716 show_command = sel->command != NULL;
717 show_kidle = sel->kidle;
719 /* count up process states and get pointers to interesting procs */
725 memset((char *)process_states, 0, sizeof(process_states));
727 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
729 if (pp->ki_stat == 0)
733 if (!show_self && pp->ki_pid == sel->self)
737 if (!show_system && (pp->ki_flag & P_SYSTEM))
738 /* skip system process */
741 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
743 total_inblock += p_inblock;
744 total_oublock += p_oublock;
745 total_majflt += p_majflt;
747 process_states[pp->ki_stat]++;
749 if (pp->ki_stat == SZOMB)
753 if (!show_kidle && pp->ki_tdflags & TDF_IDLETD)
754 /* skip kernel idle process */
757 if (displaymode == DISP_CPU && !show_idle &&
758 (pp->ki_pctcpu == 0 ||
759 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
760 /* skip idle or non-running processes */
763 if (displaymode == DISP_IO && !show_idle && p_io == 0)
764 /* skip processes that aren't doing I/O */
767 if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
768 /* skip proc. that don't belong to the selected UID */
775 /* if requested, sort the "interesting" processes */
777 qsort(pref, active_procs, sizeof(*pref), compare);
779 /* remember active and total counts */
780 si->p_total = total_procs;
781 si->p_active = pref_len = active_procs;
783 /* pass back a handle */
784 handle.next_proc = pref;
785 handle.remaining = active_procs;
786 return ((caddr_t)&handle);
789 static char fmt[512]; /* static area where result is built */
792 format_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
794 struct kinfo_proc *pp;
795 const struct kinfo_proc *oldp;
801 struct rusage ru, *rup;
803 char *proc_fmt, thr_buf[6], jid_buf[6];
806 const int cmdlen = 128;
808 /* find and remember the next proc structure */
809 hp = (struct handle *)handle;
810 pp = *(hp->next_proc++);
813 /* get the process's command name */
814 if ((pp->ki_flag & P_INMEM) == 0) {
816 * Print swapped processes as <pname>
820 len = strlen(pp->ki_comm);
821 if (len > sizeof(pp->ki_comm) - 3)
822 len = sizeof(pp->ki_comm) - 3;
823 memmove(pp->ki_comm + 1, pp->ki_comm, len);
824 pp->ki_comm[0] = '<';
825 pp->ki_comm[len + 1] = '>';
826 pp->ki_comm[len + 2] = '\0';
830 * Convert the process's runtime from microseconds to seconds. This
831 * time includes the interrupt time although that is not wanted here.
832 * ps(1) is similarly sloppy.
834 cputime = (pp->ki_runtime + 500000) / 1000000;
836 /* calculate the base for cpu percentages */
837 pct = pctdouble(pp->ki_pctcpu);
839 /* generate "STATE" field */
840 switch (state = pp->ki_stat) {
842 if (smpmode && pp->ki_oncpu != 0xff)
843 sprintf(status, "CPU%d", pp->ki_oncpu);
845 strcpy(status, "RUN");
848 if (pp->ki_kiflag & KI_LOCKBLOCK) {
849 sprintf(status, "*%.6s", pp->ki_lockname);
854 if (pp->ki_wmesg != NULL) {
855 sprintf(status, "%.6s", pp->ki_wmesg);
862 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
863 sprintf(status, "%.6s", state_abbrev[state]);
865 sprintf(status, "?%5d", state);
869 cmdbuf = (char *)malloc(cmdlen + 1);
870 if (cmdbuf == NULL) {
871 warn("malloc(%d)", cmdlen + 1);
875 if (!(flags & FMT_SHOWARGS)) {
876 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
878 snprintf(cmdbuf, cmdlen, "%s{%s}", pp->ki_comm,
881 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
884 if (pp->ki_flag & P_SYSTEM ||
885 pp->ki_args == NULL ||
886 (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
888 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
890 snprintf(cmdbuf, cmdlen,
891 "[%s{%s}]", pp->ki_comm, pp->ki_tdname);
893 snprintf(cmdbuf, cmdlen,
894 "[%s]", pp->ki_comm);
897 char *src, *dst, *argbuf;
902 argbuflen = cmdlen * 4;
903 argbuf = (char *)malloc(argbuflen + 1);
904 if (argbuf == NULL) {
905 warn("malloc(%d)", argbuflen + 1);
912 /* Extract cmd name from argv */
913 cmd = strrchr(*args, '/');
919 for (; (src = *args++) != NULL; ) {
922 len = (argbuflen - (dst - argbuf) - 1) / 4;
924 strlen(src) < len ? strlen(src) : len,
925 VIS_NL | VIS_CSTYLE);
928 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
929 *dst++ = ' '; /* add delimiting space */
931 if (dst != argbuf && dst[-1] == ' ')
935 if (strcmp(cmd, pp->ki_comm) != 0) {
936 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
938 snprintf(cmdbuf, cmdlen,
939 "%s (%s){%s}", argbuf, pp->ki_comm,
942 snprintf(cmdbuf, cmdlen,
943 "%s (%s)", argbuf, pp->ki_comm);
945 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
947 snprintf(cmdbuf, cmdlen,
948 "%s{%s}", argbuf, pp->ki_tdname);
950 strlcpy(cmdbuf, argbuf, cmdlen);
959 snprintf(jid_buf, sizeof(jid_buf), " %*d",
960 sizeof(jid_buf) - 3, pp->ki_jid);
962 if (displaymode == DISP_IO) {
963 oldp = get_old_proc(pp);
965 ru.ru_inblock = RU(pp)->ru_inblock -
966 RU(oldp)->ru_inblock;
967 ru.ru_oublock = RU(pp)->ru_oublock -
968 RU(oldp)->ru_oublock;
969 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
970 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
971 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
976 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
977 s_tot = total_inblock + total_oublock + total_majflt;
979 snprintf(fmt, sizeof(fmt), io_Proc_format,
982 namelength, namelength, (*get_userid)(pp->ki_ruid),
989 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
990 screen_width > cmdlengthdelta ?
991 screen_width - cmdlengthdelta : 0,
999 /* format this entry */
1001 if (state == SRUN && pp->ki_oncpu != 0xff)
1004 cpu = pp->ki_lastcpu;
1007 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1011 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1012 sizeof(thr_buf) - 2, pp->ki_numthreads);
1014 snprintf(fmt, sizeof(fmt), proc_fmt,
1017 namelength, namelength, (*get_userid)(pp->ki_ruid),
1019 pp->ki_pri.pri_level - PZERO,
1021 format_k2(PROCSIZE(pp)),
1022 format_k2(pagetok(pp->ki_rssize)),
1025 format_time(cputime),
1026 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1027 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1032 /* return the result */
1037 getsysctl(const char *name, void *ptr, size_t len)
1041 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1042 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1047 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1048 name, (unsigned long)len, (unsigned long)nlen);
1054 format_nice(const struct kinfo_proc *pp)
1056 const char *fifo, *kthread;
1058 static char nicebuf[4 + 1];
1060 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1061 kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1062 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1067 * XXX: the kernel doesn't tell us the original rtprio and
1068 * doesn't really know what it was, so to recover it we
1069 * must be more chummy with the implementation than the
1070 * implementation is with itself. pri_user gives a
1071 * constant "base" priority, but is only initialized
1072 * properly for user threads. pri_native gives what the
1073 * kernel calls the "base" priority, but it isn't constant
1074 * since it is changed by priority propagation. pri_native
1075 * also isn't properly initialized for all threads, but it
1076 * is properly initialized for kernel realtime and idletime
1077 * threads. Thus we use pri_user for the base priority of
1078 * user threads (it is always correct) and pri_native for
1079 * the base priority of kernel realtime and idletime threads
1080 * (there is nothing better, and it is usually correct).
1082 * The field width and thus the buffer are too small for
1083 * values like "kr31F", but such values shouldn't occur,
1084 * and if they do then the tailing "F" is not displayed.
1086 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1087 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1088 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1089 kthread, rtpri, fifo);
1092 if (pp->ki_flag & P_KTHREAD)
1094 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1097 /* XXX: as above. */
1098 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1099 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1100 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1101 kthread, rtpri, fifo);
1109 /* comparison routines for qsort */
1112 compare_pid(const void *p1, const void *p2)
1114 const struct kinfo_proc * const *pp1 = p1;
1115 const struct kinfo_proc * const *pp2 = p2;
1117 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1120 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1124 compare_tid(const void *p1, const void *p2)
1126 const struct kinfo_proc * const *pp1 = p1;
1127 const struct kinfo_proc * const *pp2 = p2;
1129 if ((*pp2)->ki_tid < 0 || (*pp1)->ki_tid < 0)
1132 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1136 * proc_compare - comparison function for "qsort"
1137 * Compares the resource consumption of two processes using five
1138 * distinct keys. The keys (in descending order of importance) are:
1139 * percent cpu, cpu ticks, state, resident set size, total virtual
1140 * memory usage. The process states are ordered as follows (from least
1141 * to most important): WAIT, zombie, sleep, stop, start, run. The
1142 * array declaration below maps a process state index into a number
1143 * that reflects this ordering.
1146 static int sorted_state[] = {
1149 1, /* ABANDONED (WAIT) */
1157 #define ORDERKEY_PCTCPU(a, b) do { \
1160 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1162 floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1165 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1167 return (diff > 0 ? 1 : -1); \
1170 #define ORDERKEY_CPTICKS(a, b) do { \
1171 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1173 return (diff > 0 ? 1 : -1); \
1176 #define ORDERKEY_STATE(a, b) do { \
1177 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1179 return (diff > 0 ? 1 : -1); \
1182 #define ORDERKEY_PRIO(a, b) do { \
1183 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1185 return (diff > 0 ? 1 : -1); \
1188 #define ORDERKEY_THREADS(a, b) do { \
1189 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1191 return (diff > 0 ? 1 : -1); \
1194 #define ORDERKEY_RSSIZE(a, b) do { \
1195 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1197 return (diff > 0 ? 1 : -1); \
1200 #define ORDERKEY_MEM(a, b) do { \
1201 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1203 return (diff > 0 ? 1 : -1); \
1206 #define ORDERKEY_JID(a, b) do { \
1207 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1209 return (diff > 0 ? 1 : -1); \
1212 /* compare_cpu - the comparison function for sorting by cpu percentage */
1216 compare_cpu(void *arg1, void *arg2)
1218 proc_compare(void *arg1, void *arg2)
1221 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1222 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1224 ORDERKEY_PCTCPU(p1, p2);
1225 ORDERKEY_CPTICKS(p1, p2);
1226 ORDERKEY_STATE(p1, p2);
1227 ORDERKEY_PRIO(p1, p2);
1228 ORDERKEY_RSSIZE(p1, p2);
1229 ORDERKEY_MEM(p1, p2);
1235 /* "cpu" compare routines */
1236 int compare_size(), compare_res(), compare_time(), compare_prio(),
1240 * "io" compare routines. Context switches aren't i/o, but are displayed
1241 * on the "io" display.
1243 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1244 compare_vcsw(), compare_ivcsw();
1246 int (*compares[])() = {
1263 /* compare_size - the comparison function for sorting by total memory usage */
1266 compare_size(void *arg1, void *arg2)
1268 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1269 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1271 ORDERKEY_MEM(p1, p2);
1272 ORDERKEY_RSSIZE(p1, p2);
1273 ORDERKEY_PCTCPU(p1, p2);
1274 ORDERKEY_CPTICKS(p1, p2);
1275 ORDERKEY_STATE(p1, p2);
1276 ORDERKEY_PRIO(p1, p2);
1281 /* compare_res - the comparison function for sorting by resident set size */
1284 compare_res(void *arg1, void *arg2)
1286 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1287 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1289 ORDERKEY_RSSIZE(p1, p2);
1290 ORDERKEY_MEM(p1, p2);
1291 ORDERKEY_PCTCPU(p1, p2);
1292 ORDERKEY_CPTICKS(p1, p2);
1293 ORDERKEY_STATE(p1, p2);
1294 ORDERKEY_PRIO(p1, p2);
1299 /* compare_time - the comparison function for sorting by total cpu time */
1302 compare_time(void *arg1, void *arg2)
1304 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1305 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1307 ORDERKEY_CPTICKS(p1, p2);
1308 ORDERKEY_PCTCPU(p1, p2);
1309 ORDERKEY_STATE(p1, p2);
1310 ORDERKEY_PRIO(p1, p2);
1311 ORDERKEY_RSSIZE(p1, p2);
1312 ORDERKEY_MEM(p1, p2);
1317 /* compare_prio - the comparison function for sorting by priority */
1320 compare_prio(void *arg1, void *arg2)
1322 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1323 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1325 ORDERKEY_PRIO(p1, p2);
1326 ORDERKEY_CPTICKS(p1, p2);
1327 ORDERKEY_PCTCPU(p1, p2);
1328 ORDERKEY_STATE(p1, p2);
1329 ORDERKEY_RSSIZE(p1, p2);
1330 ORDERKEY_MEM(p1, p2);
1335 /* compare_threads - the comparison function for sorting by threads */
1337 compare_threads(void *arg1, void *arg2)
1339 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1340 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1342 ORDERKEY_THREADS(p1, p2);
1343 ORDERKEY_PCTCPU(p1, p2);
1344 ORDERKEY_CPTICKS(p1, p2);
1345 ORDERKEY_STATE(p1, p2);
1346 ORDERKEY_PRIO(p1, p2);
1347 ORDERKEY_RSSIZE(p1, p2);
1348 ORDERKEY_MEM(p1, p2);
1353 /* compare_jid - the comparison function for sorting by jid */
1355 compare_jid(const void *arg1, const void *arg2)
1357 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1358 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1360 ORDERKEY_JID(p1, p2);
1361 ORDERKEY_PCTCPU(p1, p2);
1362 ORDERKEY_CPTICKS(p1, p2);
1363 ORDERKEY_STATE(p1, p2);
1364 ORDERKEY_PRIO(p1, p2);
1365 ORDERKEY_RSSIZE(p1, p2);
1366 ORDERKEY_MEM(p1, p2);
1372 /* assorted comparison functions for sorting by i/o */
1376 compare_iototal(void *arg1, void *arg2)
1378 io_compare(void *arg1, void *arg2)
1381 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1382 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1384 return (get_io_total(p2) - get_io_total(p1));
1389 compare_ioread(void *arg1, void *arg2)
1391 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1392 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1393 long dummy, inp1, inp2;
1395 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1396 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1398 return (inp2 - inp1);
1402 compare_iowrite(void *arg1, void *arg2)
1404 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1405 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1406 long dummy, oup1, oup2;
1408 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1409 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1411 return (oup2 - oup1);
1415 compare_iofault(void *arg1, void *arg2)
1417 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1418 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1419 long dummy, flp1, flp2;
1421 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1422 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1424 return (flp2 - flp1);
1428 compare_vcsw(void *arg1, void *arg2)
1430 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1431 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1432 long dummy, flp1, flp2;
1434 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1435 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1437 return (flp2 - flp1);
1441 compare_ivcsw(void *arg1, void *arg2)
1443 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1444 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1445 long dummy, flp1, flp2;
1447 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1448 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1450 return (flp2 - flp1);
1455 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1456 * the process does not exist.
1457 * It is EXTREMELY IMPORTANT that this function work correctly.
1458 * If top runs setuid root (as in SVR4), then this function
1459 * is the only thing that stands in the way of a serious
1460 * security problem. It validates requests for the "kill"
1461 * and "renice" commands.
1468 struct kinfo_proc **prefp;
1469 struct kinfo_proc *pp;
1473 while (--cnt >= 0) {
1475 if (pp->ki_pid == (pid_t)pid)
1476 return ((int)pp->ki_ruid);
1482 swapmode(int *retavail, int *retfree)
1485 int pagesize = getpagesize();
1486 struct kvm_swap swapary[1];
1491 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1493 n = kvm_getswapinfo(kd, swapary, 1, 0);
1494 if (n < 0 || swapary[0].ksw_total == 0)
1497 *retavail = CONVERT(swapary[0].ksw_total);
1498 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1500 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);