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>
55 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
56 #define SMPUNAMELEN 13
59 extern struct process_select ps;
60 extern char* printable(char *);
62 enum displaymodes displaymode;
63 static int namelength = 8;
64 static int cmdlengthdelta;
66 /* Prototypes for top internals */
69 /* get_process_info passes back a handle. This is what it looks like: */
72 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
73 int remaining; /* number of pointers remaining */
76 /* declarations for load_avg */
79 /* define what weighted cpu is. */
80 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
81 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
83 /* what we consider to be process size: */
84 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
86 #define RU(pp) (&(pp)->ki_rusage)
88 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
91 /* definitions for indices in the nlist array */
94 * These definitions control the format of the per-process area
97 static char io_header[] =
98 " PID%s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
100 #define io_Proc_format \
101 "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
103 static char smp_header_thr[] =
104 " PID%s %-*.*s THR PRI NICE SIZE RES STATE C TIME %6s COMMAND";
105 static char smp_header[] =
106 " PID%s %-*.*s " "PRI NICE SIZE RES STATE C TIME %6s COMMAND";
108 #define smp_Proc_format \
109 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
111 static char up_header_thr[] =
112 " PID%s %-*.*s THR PRI NICE SIZE RES STATE TIME %6s COMMAND";
113 static char up_header[] =
114 " PID%s %-*.*s " "PRI NICE SIZE RES STATE TIME %6s COMMAND";
116 #define up_Proc_format \
117 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
120 /* process state names for the "STATE" column of the display */
121 /* the extra nulls in the string "run" are for adding a slash and
122 the processor number when needed */
124 char *state_abbrev[] = {
125 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
131 /* values that we stash away in _init and use in later routines */
133 static double logcpu;
135 /* these are retrieved from the kernel in _init */
137 static load_avg ccpu;
139 /* these are used in the get_ functions */
143 /* these are for calculating cpu state percentages */
145 static long cp_time[CPUSTATES];
146 static long cp_old[CPUSTATES];
147 static long cp_diff[CPUSTATES];
149 /* these are for detailing the process states */
151 int process_states[8];
152 char *procstatenames[] = {
153 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
154 " zombie, ", " waiting, ", " lock, ",
158 /* these are for detailing the cpu states */
160 int cpu_states[CPUSTATES];
161 char *cpustatenames[] = {
162 "user", "nice", "system", "interrupt", "idle", NULL
165 /* these are for detailing the memory statistics */
168 char *memorynames[] = {
169 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
174 char *swapnames[] = {
175 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
180 /* these are for keeping track of the proc array */
183 static int onproc = -1;
185 static struct kinfo_proc *pbase;
186 static struct kinfo_proc **pref;
187 static struct kinfo_proc *previous_procs;
188 static struct kinfo_proc **previous_pref;
189 static int previous_proc_count = 0;
190 static int previous_proc_count_max = 0;
192 /* total number of io operations */
193 static long total_inblock;
194 static long total_oublock;
195 static long total_majflt;
197 /* these are for getting the memory statistics */
199 static int pageshift; /* log base 2 of the pagesize */
201 /* define pagetok in terms of pageshift */
203 #define pagetok(size) ((size) << pageshift)
205 /* useful externals */
210 * Sorting orders. The first element is the default.
212 char *ordernames[] = {
213 "cpu", "size", "res", "time", "pri", "threads",
214 "total", "read", "write", "fault", "vcsw", "ivcsw",
219 static int compare_jid(const void *a, const void *b);
220 static int compare_pid(const void *a, const void *b);
221 static const char *format_nice(const struct kinfo_proc *pp);
222 static void getsysctl(const char *name, void *ptr, size_t len);
223 static int swapmode(int *retavail, int *retfree);
226 machine_init(struct statics *statics)
232 modelen = sizeof(smpmode);
233 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
235 sysctlbyname("kern.smp.active", &smpmode, &modelen,
237 modelen != sizeof(smpmode))
240 while ((pw = getpwent()) != NULL) {
241 if (strlen(pw->pw_name) > namelength)
242 namelength = strlen(pw->pw_name);
244 if (smpmode && namelength > SMPUNAMELEN)
245 namelength = SMPUNAMELEN;
246 else if (namelength > UPUNAMELEN)
247 namelength = UPUNAMELEN;
249 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
253 GETSYSCTL("kern.ccpu", ccpu);
255 /* this is used in calculating WCPU -- calculate it ahead of time */
256 logcpu = log(loaddouble(ccpu));
263 /* get the page size and calculate pageshift from it */
264 pagesize = getpagesize();
266 while (pagesize > 1) {
271 /* we only need the amount of log(2)1024 for our conversion */
272 pageshift -= LOG1024;
274 /* fill in the statics information */
275 statics->procstate_names = procstatenames;
276 statics->cpustate_names = cpustatenames;
277 statics->memory_names = memorynames;
278 statics->swap_names = swapnames;
280 statics->order_names = ordernames;
288 format_header(char *uname_field)
290 static char Header[128];
293 switch (displaymode) {
296 * The logic of picking the right header format seems reverse
297 * here because we only want to display a THR column when
298 * "thread mode" is off (and threads are not listed as
302 (ps.thread ? smp_header : smp_header_thr) :
303 (ps.thread ? up_header : up_header_thr);
304 snprintf(Header, sizeof(Header), prehead,
305 ps.jail ? " JID" : "",
306 namelength, namelength, uname_field,
307 ps.wcpu ? "WCPU" : "CPU");
311 snprintf(Header, sizeof(Header), prehead,
312 ps.jail ? " JID" : "",
313 namelength, namelength, uname_field);
316 cmdlengthdelta = strlen(Header) - 7;
320 static int swappgsin = -1;
321 static int swappgsout = -1;
322 extern struct timeval timeout;
325 get_system_info(struct system_info *si)
328 struct loadavg sysload;
330 struct timeval boottime;
334 /* get the cp_time array */
335 GETSYSCTL("kern.cp_time", cp_time);
336 GETSYSCTL("vm.loadavg", sysload);
337 GETSYSCTL("kern.lastpid", lastpid);
339 /* convert load averages to doubles */
340 for (i = 0; i < 3; i++)
341 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
343 /* convert cp_time counts to percentages */
344 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
346 /* sum memory & swap statistics */
348 static unsigned int swap_delay = 0;
349 static int swapavail = 0;
350 static int swapfree = 0;
351 static int bufspace = 0;
352 static int nspgsin, nspgsout;
354 GETSYSCTL("vfs.bufspace", bufspace);
355 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
356 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
357 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
358 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
359 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
360 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
361 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
362 /* convert memory stats to Kbytes */
363 memory_stats[0] = pagetok(memory_stats[0]);
364 memory_stats[1] = pagetok(memory_stats[1]);
365 memory_stats[2] = pagetok(memory_stats[2]);
366 memory_stats[3] = pagetok(memory_stats[3]);
367 memory_stats[4] = bufspace / 1024;
368 memory_stats[5] = pagetok(memory_stats[5]);
369 memory_stats[6] = -1;
377 /* compute differences between old and new swap statistic */
379 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
380 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
384 swappgsout = nspgsout;
386 /* call CPU heavy swapmode() only for changes */
387 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
388 swap_stats[3] = swapmode(&swapavail, &swapfree);
389 swap_stats[0] = swapavail;
390 swap_stats[1] = swapavail - swapfree;
391 swap_stats[2] = swapfree;
397 /* set arrays and strings */
398 si->cpustates = cpu_states;
399 si->memory = memory_stats;
400 si->swap = swap_stats;
404 si->last_pid = lastpid;
410 * Print how long system has been up.
411 * (Found by looking getting "boottime" from the kernel)
414 mib[1] = KERN_BOOTTIME;
415 bt_size = sizeof(boottime);
416 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
417 boottime.tv_sec != 0) {
418 si->boottime = boottime;
420 si->boottime.tv_sec = -1;
424 #define NOPROC ((void *)-1)
427 * We need to compare data from the old process entry with the new
429 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
430 * structure to cache the mapping. We also use a negative cache pointer
431 * of NOPROC to avoid duplicate lookups.
432 * XXX: this could be done when the actual processes are fetched, we do
433 * it here out of laziness.
435 const struct kinfo_proc *
436 get_old_proc(struct kinfo_proc *pp)
438 struct kinfo_proc **oldpp, *oldp;
441 * If this is the first fetch of the kinfo_procs then we don't have
442 * any previous entries.
444 if (previous_proc_count == 0)
446 /* negative cache? */
447 if (pp->ki_udata == NOPROC)
450 if (pp->ki_udata != NULL)
451 return (pp->ki_udata);
454 * 1) look up based on pid.
455 * 2) compare process start.
456 * If we fail here, then setup a negative cache entry, otherwise
459 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
460 sizeof(*previous_pref), compare_pid);
462 pp->ki_udata = NOPROC;
466 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
467 pp->ki_udata = NOPROC;
475 * Return the total amount of IO done in blocks in/out and faults.
476 * store the values individually in the pointers passed in.
479 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
480 long *vcsw, long *ivcsw)
482 const struct kinfo_proc *oldp;
483 static struct kinfo_proc dummy;
486 oldp = get_old_proc(pp);
488 bzero(&dummy, sizeof(dummy));
491 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
492 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
493 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
494 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
495 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
497 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
498 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
499 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
504 * Return the total number of block in/out and faults by a process.
507 get_io_total(struct kinfo_proc *pp)
511 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
514 static struct handle handle;
517 get_process_info(struct system_info *si, struct process_select *sel,
518 int (*compare)(const void *, const void *))
523 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
525 struct kinfo_proc **prefp;
526 struct kinfo_proc *pp;
527 struct kinfo_proc *prev_pp = NULL;
529 /* these are copied out of sel for speed */
537 * Save the previous process info.
539 if (previous_proc_count_max < nproc) {
540 free(previous_procs);
541 previous_procs = malloc(nproc * sizeof(*previous_procs));
543 previous_pref = malloc(nproc * sizeof(*previous_pref));
544 if (previous_procs == NULL || previous_pref == NULL) {
545 (void) fprintf(stderr, "top: Out of memory.\n");
548 previous_proc_count_max = nproc;
551 for (i = 0; i < nproc; i++)
552 previous_pref[i] = &previous_procs[i];
553 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
554 qsort(previous_pref, nproc, sizeof(*previous_pref),
557 previous_proc_count = nproc;
559 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
561 pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
562 if (pref == NULL || pbase == NULL) {
563 (void) fprintf(stderr, "top: Out of memory.\n");
566 /* get a pointer to the states summary array */
567 si->procstates = process_states;
569 /* set up flags which define what we are going to select */
570 show_idle = sel->idle;
571 show_self = sel->self == -1;
572 show_system = sel->system;
573 show_uid = sel->uid != -1;
574 show_command = sel->command != NULL;
576 /* count up process states and get pointers to interesting procs */
582 memset((char *)process_states, 0, sizeof(process_states));
584 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
586 if (pp->ki_stat == 0)
590 if (!show_self && pp->ki_pid == sel->self)
594 if (!show_system && (pp->ki_flag & P_SYSTEM))
595 /* skip system process */
598 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
600 total_inblock += p_inblock;
601 total_oublock += p_oublock;
602 total_majflt += p_majflt;
604 process_states[pp->ki_stat]++;
606 if (pp->ki_stat == SZOMB)
610 if (displaymode == DISP_CPU && !show_idle &&
611 (pp->ki_pctcpu == 0 ||
612 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
613 /* skip idle or non-running processes */
616 if (displaymode == DISP_IO && !show_idle && p_io == 0)
617 /* skip processes that aren't doing I/O */
620 if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
621 /* skip proc. that don't belong to the selected UID */
625 * When not showing threads, take the first thread
626 * for output and add the fields that we can from
627 * the rest of the process's threads rather than
628 * using the system's mostly-broken KERN_PROC_PROC.
630 if (sel->thread || prev_pp == NULL ||
631 prev_pp->ki_pid != pp->ki_pid) {
636 prev_pp->ki_pctcpu += pp->ki_pctcpu;
640 /* if requested, sort the "interesting" processes */
642 qsort(pref, active_procs, sizeof(*pref), compare);
644 /* remember active and total counts */
645 si->p_total = total_procs;
646 si->p_active = pref_len = active_procs;
648 /* pass back a handle */
649 handle.next_proc = pref;
650 handle.remaining = active_procs;
651 return ((caddr_t)&handle);
654 static char fmt[128]; /* static area where result is built */
657 format_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
659 struct kinfo_proc *pp;
660 const struct kinfo_proc *oldp;
666 struct rusage ru, *rup;
668 char *proc_fmt, thr_buf[6], jid_buf[6];
672 /* find and remember the next proc structure */
673 hp = (struct handle *)handle;
674 pp = *(hp->next_proc++);
677 /* get the process's command name */
678 if ((pp->ki_sflag & PS_INMEM) == 0) {
680 * Print swapped processes as <pname>
684 len = strlen(pp->ki_comm);
685 if (len > sizeof(pp->ki_comm) - 3)
686 len = sizeof(pp->ki_comm) - 3;
687 memmove(pp->ki_comm + 1, pp->ki_comm, len);
688 pp->ki_comm[0] = '<';
689 pp->ki_comm[len + 1] = '>';
690 pp->ki_comm[len + 2] = '\0';
694 * Convert the process's runtime from microseconds to seconds. This
695 * time includes the interrupt time although that is not wanted here.
696 * ps(1) is similarly sloppy.
698 cputime = (pp->ki_runtime + 500000) / 1000000;
700 /* calculate the base for cpu percentages */
701 pct = pctdouble(pp->ki_pctcpu);
703 /* generate "STATE" field */
704 switch (state = pp->ki_stat) {
706 if (smpmode && pp->ki_oncpu != 0xff)
707 sprintf(status, "CPU%d", pp->ki_oncpu);
709 strcpy(status, "RUN");
712 if (pp->ki_kiflag & KI_LOCKBLOCK) {
713 sprintf(status, "*%.6s", pp->ki_lockname);
718 if (pp->ki_wmesg != NULL) {
719 sprintf(status, "%.6s", pp->ki_wmesg);
726 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
727 sprintf(status, "%.6s", state_abbrev[state]);
729 sprintf(status, "?%5d", state);
733 cmdbuf = (char *)malloc(cmdlengthdelta + 1);
734 if (cmdbuf == NULL) {
735 warn("malloc(%d)", cmdlengthdelta + 1);
739 if (!(flags & FMT_SHOWARGS)) {
740 snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
742 else if (pp->ki_args == NULL ||
743 (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL || !(*args))
744 snprintf(cmdbuf, cmdlengthdelta, "[%s]", pp->ki_comm);
746 char *src, *dst, *argbuf;
751 argbuflen = cmdlengthdelta * 4;
752 argbuf = (char *)malloc(argbuflen + 1);
753 if (argbuf == NULL) {
754 warn("malloc(%d)", argbuflen + 1);
761 /* Extract cmd name from argv */
762 cmd = strrchr(*args, '/');
768 for (; (src = *args++) != NULL; ) {
771 len = (argbuflen - (dst - argbuf) - 1) / 4;
772 strvisx(dst, src, strlen(src) < len ? strlen(src) : len,
773 VIS_NL | VIS_CSTYLE);
776 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
777 *dst++ = ' '; /* add delimiting space */
779 if (dst != argbuf && dst[-1] == ' ')
783 if (strcmp(cmd, pp->ki_comm) != 0 )
784 snprintf(cmdbuf, cmdlengthdelta, "%s (%s)",argbuf, \
787 strlcpy(cmdbuf, argbuf, cmdlengthdelta);
795 snprintf(jid_buf, sizeof(jid_buf), " %*d",
796 sizeof(jid_buf) - 3, pp->ki_jid);
798 if (displaymode == DISP_IO) {
799 oldp = get_old_proc(pp);
801 ru.ru_inblock = RU(pp)->ru_inblock -
802 RU(oldp)->ru_inblock;
803 ru.ru_oublock = RU(pp)->ru_oublock -
804 RU(oldp)->ru_oublock;
805 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
806 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
807 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
812 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
813 s_tot = total_inblock + total_oublock + total_majflt;
815 sprintf(fmt, io_Proc_format,
818 namelength, namelength, (*get_userid)(pp->ki_ruid),
825 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
826 screen_width > cmdlengthdelta ?
827 screen_width - cmdlengthdelta : 0,
835 /* format this entry */
836 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
840 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
841 sizeof(thr_buf) - 2, pp->ki_numthreads);
843 sprintf(fmt, proc_fmt,
846 namelength, namelength, (*get_userid)(pp->ki_ruid),
848 pp->ki_pri.pri_level - PZERO,
850 format_k2(PROCSIZE(pp)),
851 format_k2(pagetok(pp->ki_rssize)),
853 smpmode ? pp->ki_lastcpu : 0,
854 format_time(cputime),
855 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
856 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
861 /* return the result */
866 getsysctl(const char *name, void *ptr, size_t len)
870 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
871 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
876 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
877 name, (unsigned long)len, (unsigned long)nlen);
883 format_nice(const struct kinfo_proc *pp)
885 const char *fifo, *kthread;
887 static char nicebuf[4 + 1];
889 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
890 kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
891 switch (PRI_BASE(pp->ki_pri.pri_class)) {
896 * XXX: the kernel doesn't tell us the original rtprio and
897 * doesn't really know what it was, so to recover it we
898 * must be more chummy with the implementation than the
899 * implementation is with itself. pri_user gives a
900 * constant "base" priority, but is only initialized
901 * properly for user threads. pri_native gives what the
902 * kernel calls the "base" priority, but it isn't constant
903 * since it is changed by priority propagation. pri_native
904 * also isn't properly initialized for all threads, but it
905 * is properly initialized for kernel realtime and idletime
906 * threads. Thus we use pri_user for the base priority of
907 * user threads (it is always correct) and pri_native for
908 * the base priority of kernel realtime and idletime threads
909 * (there is nothing better, and it is usually correct).
911 * The field width and thus the buffer are too small for
912 * values like "kr31F", but such values shouldn't occur,
913 * and if they do then the tailing "F" is not displayed.
915 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
916 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
917 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
918 kthread, rtpri, fifo);
921 if (pp->ki_flag & P_KTHREAD)
923 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
927 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
928 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
929 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
930 kthread, rtpri, fifo);
938 /* comparison routines for qsort */
941 compare_pid(const void *p1, const void *p2)
943 const struct kinfo_proc * const *pp1 = p1;
944 const struct kinfo_proc * const *pp2 = p2;
946 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
949 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
953 * proc_compare - comparison function for "qsort"
954 * Compares the resource consumption of two processes using five
955 * distinct keys. The keys (in descending order of importance) are:
956 * percent cpu, cpu ticks, state, resident set size, total virtual
957 * memory usage. The process states are ordered as follows (from least
958 * to most important): WAIT, zombie, sleep, stop, start, run. The
959 * array declaration below maps a process state index into a number
960 * that reflects this ordering.
963 static int sorted_state[] = {
966 1, /* ABANDONED (WAIT) */
974 #define ORDERKEY_PCTCPU(a, b) do { \
977 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
979 floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
982 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
984 return (diff > 0 ? 1 : -1); \
987 #define ORDERKEY_CPTICKS(a, b) do { \
988 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
990 return (diff > 0 ? 1 : -1); \
993 #define ORDERKEY_STATE(a, b) do { \
994 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
996 return (diff > 0 ? 1 : -1); \
999 #define ORDERKEY_PRIO(a, b) do { \
1000 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1002 return (diff > 0 ? 1 : -1); \
1005 #define ORDERKEY_THREADS(a, b) do { \
1006 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1008 return (diff > 0 ? 1 : -1); \
1011 #define ORDERKEY_RSSIZE(a, b) do { \
1012 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1014 return (diff > 0 ? 1 : -1); \
1017 #define ORDERKEY_MEM(a, b) do { \
1018 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1020 return (diff > 0 ? 1 : -1); \
1023 #define ORDERKEY_JID(a, b) do { \
1024 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1026 return (diff > 0 ? 1 : -1); \
1029 /* compare_cpu - the comparison function for sorting by cpu percentage */
1033 compare_cpu(void *arg1, void *arg2)
1035 proc_compare(void *arg1, void *arg2)
1038 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1039 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1041 ORDERKEY_PCTCPU(p1, p2);
1042 ORDERKEY_CPTICKS(p1, p2);
1043 ORDERKEY_STATE(p1, p2);
1044 ORDERKEY_PRIO(p1, p2);
1045 ORDERKEY_RSSIZE(p1, p2);
1046 ORDERKEY_MEM(p1, p2);
1052 /* "cpu" compare routines */
1053 int compare_size(), compare_res(), compare_time(), compare_prio(),
1057 * "io" compare routines. Context switches aren't i/o, but are displayed
1058 * on the "io" display.
1060 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1061 compare_vcsw(), compare_ivcsw();
1063 int (*compares[])() = {
1080 /* compare_size - the comparison function for sorting by total memory usage */
1083 compare_size(void *arg1, void *arg2)
1085 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1086 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1088 ORDERKEY_MEM(p1, p2);
1089 ORDERKEY_RSSIZE(p1, p2);
1090 ORDERKEY_PCTCPU(p1, p2);
1091 ORDERKEY_CPTICKS(p1, p2);
1092 ORDERKEY_STATE(p1, p2);
1093 ORDERKEY_PRIO(p1, p2);
1098 /* compare_res - the comparison function for sorting by resident set size */
1101 compare_res(void *arg1, void *arg2)
1103 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1104 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1106 ORDERKEY_RSSIZE(p1, p2);
1107 ORDERKEY_MEM(p1, p2);
1108 ORDERKEY_PCTCPU(p1, p2);
1109 ORDERKEY_CPTICKS(p1, p2);
1110 ORDERKEY_STATE(p1, p2);
1111 ORDERKEY_PRIO(p1, p2);
1116 /* compare_time - the comparison function for sorting by total cpu time */
1119 compare_time(void *arg1, void *arg2)
1121 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1122 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1124 ORDERKEY_CPTICKS(p1, p2);
1125 ORDERKEY_PCTCPU(p1, p2);
1126 ORDERKEY_STATE(p1, p2);
1127 ORDERKEY_PRIO(p1, p2);
1128 ORDERKEY_RSSIZE(p1, p2);
1129 ORDERKEY_MEM(p1, p2);
1134 /* compare_prio - the comparison function for sorting by priority */
1137 compare_prio(void *arg1, void *arg2)
1139 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1140 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1142 ORDERKEY_PRIO(p1, p2);
1143 ORDERKEY_CPTICKS(p1, p2);
1144 ORDERKEY_PCTCPU(p1, p2);
1145 ORDERKEY_STATE(p1, p2);
1146 ORDERKEY_RSSIZE(p1, p2);
1147 ORDERKEY_MEM(p1, p2);
1152 /* compare_threads - the comparison function for sorting by threads */
1154 compare_threads(void *arg1, void *arg2)
1156 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1157 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1159 ORDERKEY_THREADS(p1, p2);
1160 ORDERKEY_PCTCPU(p1, p2);
1161 ORDERKEY_CPTICKS(p1, p2);
1162 ORDERKEY_STATE(p1, p2);
1163 ORDERKEY_PRIO(p1, p2);
1164 ORDERKEY_RSSIZE(p1, p2);
1165 ORDERKEY_MEM(p1, p2);
1170 /* compare_jid - the comparison function for sorting by jid */
1172 compare_jid(const void *arg1, const void *arg2)
1174 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1175 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1177 ORDERKEY_JID(p1, p2);
1178 ORDERKEY_PCTCPU(p1, p2);
1179 ORDERKEY_CPTICKS(p1, p2);
1180 ORDERKEY_STATE(p1, p2);
1181 ORDERKEY_PRIO(p1, p2);
1182 ORDERKEY_RSSIZE(p1, p2);
1183 ORDERKEY_MEM(p1, p2);
1189 /* assorted comparison functions for sorting by i/o */
1193 compare_iototal(void *arg1, void *arg2)
1195 io_compare(void *arg1, void *arg2)
1198 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1199 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1201 return (get_io_total(p2) - get_io_total(p1));
1206 compare_ioread(void *arg1, void *arg2)
1208 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1209 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1210 long dummy, inp1, inp2;
1212 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1213 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1215 return (inp2 - inp1);
1219 compare_iowrite(void *arg1, void *arg2)
1221 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1222 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1223 long dummy, oup1, oup2;
1225 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1226 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1228 return (oup2 - oup1);
1232 compare_iofault(void *arg1, void *arg2)
1234 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1235 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1236 long dummy, flp1, flp2;
1238 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1239 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1241 return (flp2 - flp1);
1245 compare_vcsw(void *arg1, void *arg2)
1247 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1248 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1249 long dummy, flp1, flp2;
1251 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1252 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1254 return (flp2 - flp1);
1258 compare_ivcsw(void *arg1, void *arg2)
1260 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1261 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1262 long dummy, flp1, flp2;
1264 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1265 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1267 return (flp2 - flp1);
1272 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1273 * the process does not exist.
1274 * It is EXTREMLY IMPORTANT that this function work correctly.
1275 * If top runs setuid root (as in SVR4), then this function
1276 * is the only thing that stands in the way of a serious
1277 * security problem. It validates requests for the "kill"
1278 * and "renice" commands.
1285 struct kinfo_proc **prefp;
1286 struct kinfo_proc *pp;
1290 while (--cnt >= 0) {
1292 if (pp->ki_pid == (pid_t)pid)
1293 return ((int)pp->ki_ruid);
1299 swapmode(int *retavail, int *retfree)
1302 int pagesize = getpagesize();
1303 struct kvm_swap swapary[1];
1308 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1310 n = kvm_getswapinfo(kd, swapary, 1, 0);
1311 if (n < 0 || swapary[0].ksw_total == 0)
1314 *retavail = CONVERT(swapary[0].ksw_total);
1315 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1317 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);