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>
56 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
57 #define SMPUNAMELEN 13
60 extern struct process_select ps;
61 extern char* printable(char *);
63 enum displaymodes displaymode;
64 #ifdef TOP_USERNAME_LEN
65 static int namelength = TOP_USERNAME_LEN;
67 static int namelength = 8;
69 static int cmdlengthdelta;
71 /* Prototypes for top internals */
74 /* get_process_info passes back a handle. This is what it looks like: */
77 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
78 int remaining; /* number of pointers remaining */
81 /* declarations for load_avg */
84 /* define what weighted cpu is. */
85 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
86 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
88 /* what we consider to be process size: */
89 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
91 #define RU(pp) (&(pp)->ki_rusage)
93 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
96 /* definitions for indices in the nlist array */
99 * These definitions control the format of the per-process area
102 static char io_header[] =
103 " PID%s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
105 #define io_Proc_format \
106 "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
108 static char smp_header_thr[] =
109 " PID%s %-*.*s THR PRI NICE SIZE RES STATE C TIME %6s COMMAND";
110 static char smp_header[] =
111 " PID%s %-*.*s " "PRI NICE SIZE RES STATE C TIME %6s COMMAND";
113 #define smp_Proc_format \
114 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
116 static char up_header_thr[] =
117 " PID%s %-*.*s THR PRI NICE SIZE RES STATE TIME %6s COMMAND";
118 static char up_header[] =
119 " PID%s %-*.*s " "PRI NICE SIZE RES STATE TIME %6s COMMAND";
121 #define up_Proc_format \
122 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
125 /* process state names for the "STATE" column of the display */
126 /* the extra nulls in the string "run" are for adding a slash and
127 the processor number when needed */
129 char *state_abbrev[] = {
130 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
136 /* values that we stash away in _init and use in later routines */
138 static double logcpu;
140 /* these are retrieved from the kernel in _init */
142 static load_avg ccpu;
144 /* these are used in the get_ functions */
148 /* these are for calculating cpu state percentages */
150 static long cp_time[CPUSTATES];
151 static long cp_old[CPUSTATES];
152 static long cp_diff[CPUSTATES];
154 /* these are for detailing the process states */
156 int process_states[8];
157 char *procstatenames[] = {
158 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
159 " zombie, ", " waiting, ", " lock, ",
163 /* these are for detailing the cpu states */
165 int cpu_states[CPUSTATES];
166 char *cpustatenames[] = {
167 "user", "nice", "system", "interrupt", "idle", NULL
170 /* these are for detailing the memory statistics */
173 char *memorynames[] = {
174 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
179 char *swapnames[] = {
180 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
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;
197 /* total number of io operations */
198 static long total_inblock;
199 static long total_oublock;
200 static long total_majflt;
202 /* these are for getting the memory statistics */
204 static int pageshift; /* log base 2 of the pagesize */
206 /* define pagetok in terms of pageshift */
208 #define pagetok(size) ((size) << pageshift)
210 /* useful externals */
215 * Sorting orders. The first element is the default.
217 char *ordernames[] = {
218 "cpu", "size", "res", "time", "pri", "threads",
219 "total", "read", "write", "fault", "vcsw", "ivcsw",
224 /* Per-cpu time states */
228 static u_long cpumask;
230 static long *pcpu_cp_time;
231 static long *pcpu_cp_old;
232 static long *pcpu_cp_diff;
233 static int *pcpu_cpu_states;
235 static int compare_jid(const void *a, const void *b);
236 static int compare_pid(const void *a, const void *b);
237 static const char *format_nice(const struct kinfo_proc *pp);
238 static void getsysctl(const char *name, void *ptr, size_t len);
239 static int swapmode(int *retavail, int *retfree);
242 machine_init(struct statics *statics, char do_unames)
248 modelen = sizeof(smpmode);
249 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
251 sysctlbyname("kern.smp.active", &smpmode, &modelen,
253 modelen != sizeof(smpmode))
257 while ((pw = getpwent()) != NULL) {
258 if (strlen(pw->pw_name) > namelength)
259 namelength = strlen(pw->pw_name);
262 if (smpmode && namelength > SMPUNAMELEN)
263 namelength = SMPUNAMELEN;
264 else if (namelength > UPUNAMELEN)
265 namelength = UPUNAMELEN;
267 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
271 GETSYSCTL("kern.ccpu", ccpu);
273 /* this is used in calculating WCPU -- calculate it ahead of time */
274 logcpu = log(loaddouble(ccpu));
281 /* get the page size and calculate pageshift from it */
282 pagesize = getpagesize();
284 while (pagesize > 1) {
289 /* we only need the amount of log(2)1024 for our conversion */
290 pageshift -= LOG1024;
292 /* fill in the statics information */
293 statics->procstate_names = procstatenames;
294 statics->cpustate_names = cpustatenames;
295 statics->memory_names = memorynames;
296 statics->swap_names = swapnames;
298 statics->order_names = ordernames;
301 /* Adjust display based on ncpus */
308 GETSYSCTL("kern.smp.maxcpus", maxcpu);
309 size = sizeof(long) * maxcpu * CPUSTATES;
310 times = malloc(size);
312 err(1, "malloc %zd bytes", size);
313 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
314 err(1, "sysctlbyname kern.cp_times");
315 maxid = (size / CPUSTATES / sizeof(long)) - 1;
316 for (i = 0; i <= maxid; i++) {
318 for (j = 0; empty && j < CPUSTATES; j++) {
319 if (times[i * CPUSTATES + j] != 0)
323 cpumask |= (1ul << i);
329 y_mem += ncpus - 1; /* 3 */
330 y_swap += ncpus - 1; /* 4 */
331 y_idlecursor += ncpus - 1; /* 5 */
332 y_message += ncpus - 1; /* 5 */
333 y_header += ncpus - 1; /* 6 */
334 y_procs += ncpus - 1; /* 7 */
335 Header_lines += ncpus - 1; /* 7 */
337 size = sizeof(long) * ncpus * CPUSTATES;
338 pcpu_cp_time = calloc(1, size);
339 pcpu_cp_old = calloc(1, size);
340 pcpu_cp_diff = calloc(1, size);
341 pcpu_cpu_states = calloc(1, size);
342 statics->ncpus = ncpus;
352 format_header(char *uname_field)
354 static char Header[128];
357 switch (displaymode) {
360 * The logic of picking the right header format seems reverse
361 * here because we only want to display a THR column when
362 * "thread mode" is off (and threads are not listed as
366 (ps.thread ? smp_header : smp_header_thr) :
367 (ps.thread ? up_header : up_header_thr);
368 snprintf(Header, sizeof(Header), prehead,
369 ps.jail ? " JID" : "",
370 namelength, namelength, uname_field,
371 ps.wcpu ? "WCPU" : "CPU");
375 snprintf(Header, sizeof(Header), prehead,
376 ps.jail ? " JID" : "",
377 namelength, namelength, uname_field);
380 cmdlengthdelta = strlen(Header) - 7;
384 static int swappgsin = -1;
385 static int swappgsout = -1;
386 extern struct timeval timeout;
390 get_system_info(struct system_info *si)
393 struct loadavg sysload;
395 struct timeval boottime;
400 /* get the cp_time array */
402 size = (maxid + 1) * CPUSTATES * sizeof(long);
403 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
404 err(1, "sysctlbyname kern.cp_times");
406 GETSYSCTL("kern.cp_time", cp_time);
408 GETSYSCTL("vm.loadavg", sysload);
409 GETSYSCTL("kern.lastpid", lastpid);
411 /* convert load averages to doubles */
412 for (i = 0; i < 3; i++)
413 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
416 for (i = j = 0; i <= maxid; i++) {
417 if ((cpumask & (1ul << i)) == 0)
419 /* convert cp_time counts to percentages */
420 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
421 &pcpu_cp_time[j * CPUSTATES],
422 &pcpu_cp_old[j * CPUSTATES],
423 &pcpu_cp_diff[j * CPUSTATES]);
427 /* convert cp_time counts to percentages */
428 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
431 /* sum memory & swap statistics */
433 static unsigned int swap_delay = 0;
434 static int swapavail = 0;
435 static int swapfree = 0;
436 static int bufspace = 0;
437 static int nspgsin, nspgsout;
439 GETSYSCTL("vfs.bufspace", bufspace);
440 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
441 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
442 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
443 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
444 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
445 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
446 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
447 /* convert memory stats to Kbytes */
448 memory_stats[0] = pagetok(memory_stats[0]);
449 memory_stats[1] = pagetok(memory_stats[1]);
450 memory_stats[2] = pagetok(memory_stats[2]);
451 memory_stats[3] = pagetok(memory_stats[3]);
452 memory_stats[4] = bufspace / 1024;
453 memory_stats[5] = pagetok(memory_stats[5]);
454 memory_stats[6] = -1;
462 /* compute differences between old and new swap statistic */
464 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
465 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
469 swappgsout = nspgsout;
471 /* call CPU heavy swapmode() only for changes */
472 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
473 swap_stats[3] = swapmode(&swapavail, &swapfree);
474 swap_stats[0] = swapavail;
475 swap_stats[1] = swapavail - swapfree;
476 swap_stats[2] = swapfree;
482 /* set arrays and strings */
484 si->cpustates = pcpu_cpu_states;
485 si->cpumask = cpumask;
488 si->cpustates = cpu_states;
492 si->memory = memory_stats;
493 si->swap = swap_stats;
497 si->last_pid = lastpid;
503 * Print how long system has been up.
504 * (Found by looking getting "boottime" from the kernel)
507 mib[1] = KERN_BOOTTIME;
508 bt_size = sizeof(boottime);
509 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
510 boottime.tv_sec != 0) {
511 si->boottime = boottime;
513 si->boottime.tv_sec = -1;
517 #define NOPROC ((void *)-1)
520 * We need to compare data from the old process entry with the new
522 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
523 * structure to cache the mapping. We also use a negative cache pointer
524 * of NOPROC to avoid duplicate lookups.
525 * XXX: this could be done when the actual processes are fetched, we do
526 * it here out of laziness.
528 const struct kinfo_proc *
529 get_old_proc(struct kinfo_proc *pp)
531 struct kinfo_proc **oldpp, *oldp;
534 * If this is the first fetch of the kinfo_procs then we don't have
535 * any previous entries.
537 if (previous_proc_count == 0)
539 /* negative cache? */
540 if (pp->ki_udata == NOPROC)
543 if (pp->ki_udata != NULL)
544 return (pp->ki_udata);
547 * 1) look up based on pid.
548 * 2) compare process start.
549 * If we fail here, then setup a negative cache entry, otherwise
552 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
553 sizeof(*previous_pref), compare_pid);
555 pp->ki_udata = NOPROC;
559 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
560 pp->ki_udata = NOPROC;
568 * Return the total amount of IO done in blocks in/out and faults.
569 * store the values individually in the pointers passed in.
572 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
573 long *vcsw, long *ivcsw)
575 const struct kinfo_proc *oldp;
576 static struct kinfo_proc dummy;
579 oldp = get_old_proc(pp);
581 bzero(&dummy, sizeof(dummy));
584 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
585 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
586 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
587 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
588 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
590 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
591 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
592 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
597 * Return the total number of block in/out and faults by a process.
600 get_io_total(struct kinfo_proc *pp)
604 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
607 static struct handle handle;
610 get_process_info(struct system_info *si, struct process_select *sel,
611 int (*compare)(const void *, const void *))
616 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
618 struct kinfo_proc **prefp;
619 struct kinfo_proc *pp;
620 struct kinfo_proc *prev_pp = NULL;
622 /* these are copied out of sel for speed */
630 * Save the previous process info.
632 if (previous_proc_count_max < nproc) {
633 free(previous_procs);
634 previous_procs = malloc(nproc * sizeof(*previous_procs));
636 previous_pref = malloc(nproc * sizeof(*previous_pref));
637 if (previous_procs == NULL || previous_pref == NULL) {
638 (void) fprintf(stderr, "top: Out of memory.\n");
641 previous_proc_count_max = nproc;
644 for (i = 0; i < nproc; i++)
645 previous_pref[i] = &previous_procs[i];
646 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
647 qsort(previous_pref, nproc, sizeof(*previous_pref),
650 previous_proc_count = nproc;
652 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
654 pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
655 if (pref == NULL || pbase == NULL) {
656 (void) fprintf(stderr, "top: Out of memory.\n");
659 /* get a pointer to the states summary array */
660 si->procstates = process_states;
662 /* set up flags which define what we are going to select */
663 show_idle = sel->idle;
664 show_self = sel->self == -1;
665 show_system = sel->system;
666 show_uid = sel->uid != -1;
667 show_command = sel->command != NULL;
669 /* count up process states and get pointers to interesting procs */
675 memset((char *)process_states, 0, sizeof(process_states));
677 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
679 if (pp->ki_stat == 0)
683 if (!show_self && pp->ki_pid == sel->self)
687 if (!show_system && (pp->ki_flag & P_SYSTEM))
688 /* skip system process */
691 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
693 total_inblock += p_inblock;
694 total_oublock += p_oublock;
695 total_majflt += p_majflt;
697 process_states[pp->ki_stat]++;
699 if (pp->ki_stat == SZOMB)
703 if (displaymode == DISP_CPU && !show_idle &&
704 (pp->ki_pctcpu == 0 ||
705 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
706 /* skip idle or non-running processes */
709 if (displaymode == DISP_IO && !show_idle && p_io == 0)
710 /* skip processes that aren't doing I/O */
713 if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
714 /* skip proc. that don't belong to the selected UID */
718 * When not showing threads, take the first thread
719 * for output and add the fields that we can from
720 * the rest of the process's threads rather than
721 * using the system's mostly-broken KERN_PROC_PROC.
723 if (sel->thread || prev_pp == NULL ||
724 prev_pp->ki_pid != pp->ki_pid) {
729 prev_pp->ki_pctcpu += pp->ki_pctcpu;
733 /* if requested, sort the "interesting" processes */
735 qsort(pref, active_procs, sizeof(*pref), compare);
737 /* remember active and total counts */
738 si->p_total = total_procs;
739 si->p_active = pref_len = active_procs;
741 /* pass back a handle */
742 handle.next_proc = pref;
743 handle.remaining = active_procs;
744 return ((caddr_t)&handle);
747 static char fmt[128]; /* static area where result is built */
750 format_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
752 struct kinfo_proc *pp;
753 const struct kinfo_proc *oldp;
759 struct rusage ru, *rup;
761 char *proc_fmt, thr_buf[6], jid_buf[6];
765 /* find and remember the next proc structure */
766 hp = (struct handle *)handle;
767 pp = *(hp->next_proc++);
770 /* get the process's command name */
771 if ((pp->ki_flag & P_INMEM) == 0) {
773 * Print swapped processes as <pname>
777 len = strlen(pp->ki_comm);
778 if (len > sizeof(pp->ki_comm) - 3)
779 len = sizeof(pp->ki_comm) - 3;
780 memmove(pp->ki_comm + 1, pp->ki_comm, len);
781 pp->ki_comm[0] = '<';
782 pp->ki_comm[len + 1] = '>';
783 pp->ki_comm[len + 2] = '\0';
787 * Convert the process's runtime from microseconds to seconds. This
788 * time includes the interrupt time although that is not wanted here.
789 * ps(1) is similarly sloppy.
791 cputime = (pp->ki_runtime + 500000) / 1000000;
793 /* calculate the base for cpu percentages */
794 pct = pctdouble(pp->ki_pctcpu);
796 /* generate "STATE" field */
797 switch (state = pp->ki_stat) {
799 if (smpmode && pp->ki_oncpu != 0xff)
800 sprintf(status, "CPU%d", pp->ki_oncpu);
802 strcpy(status, "RUN");
805 if (pp->ki_kiflag & KI_LOCKBLOCK) {
806 sprintf(status, "*%.6s", pp->ki_lockname);
811 if (pp->ki_wmesg != NULL) {
812 sprintf(status, "%.6s", pp->ki_wmesg);
819 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
820 sprintf(status, "%.6s", state_abbrev[state]);
822 sprintf(status, "?%5d", state);
826 cmdbuf = (char *)malloc(cmdlengthdelta + 1);
827 if (cmdbuf == NULL) {
828 warn("malloc(%d)", cmdlengthdelta + 1);
832 if (!(flags & FMT_SHOWARGS)) {
833 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
835 snprintf(cmdbuf, cmdlengthdelta, "{%s}", pp->ki_ocomm);
837 snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
840 if (pp->ki_flag & P_SYSTEM ||
841 pp->ki_args == NULL ||
842 (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
844 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
846 snprintf(cmdbuf, cmdlengthdelta,
847 "{%s}", pp->ki_ocomm);
849 snprintf(cmdbuf, cmdlengthdelta,
850 "[%s]", pp->ki_comm);
853 char *src, *dst, *argbuf;
858 argbuflen = cmdlengthdelta * 4;
859 argbuf = (char *)malloc(argbuflen + 1);
860 if (argbuf == NULL) {
861 warn("malloc(%d)", argbuflen + 1);
868 /* Extract cmd name from argv */
869 cmd = strrchr(*args, '/');
875 for (; (src = *args++) != NULL; ) {
878 len = (argbuflen - (dst - argbuf) - 1) / 4;
880 strlen(src) < len ? strlen(src) : len,
881 VIS_NL | VIS_CSTYLE);
884 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
885 *dst++ = ' '; /* add delimiting space */
887 if (dst != argbuf && dst[-1] == ' ')
891 if (strcmp(cmd, pp->ki_comm) != 0 )
892 snprintf(cmdbuf, cmdlengthdelta,
893 "%s (%s)",argbuf, pp->ki_comm);
895 strlcpy(cmdbuf, argbuf, cmdlengthdelta);
904 snprintf(jid_buf, sizeof(jid_buf), " %*d",
905 sizeof(jid_buf) - 3, pp->ki_jid);
907 if (displaymode == DISP_IO) {
908 oldp = get_old_proc(pp);
910 ru.ru_inblock = RU(pp)->ru_inblock -
911 RU(oldp)->ru_inblock;
912 ru.ru_oublock = RU(pp)->ru_oublock -
913 RU(oldp)->ru_oublock;
914 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
915 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
916 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
921 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
922 s_tot = total_inblock + total_oublock + total_majflt;
924 sprintf(fmt, io_Proc_format,
927 namelength, namelength, (*get_userid)(pp->ki_ruid),
934 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
935 screen_width > cmdlengthdelta ?
936 screen_width - cmdlengthdelta : 0,
944 /* format this entry */
945 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
949 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
950 sizeof(thr_buf) - 2, pp->ki_numthreads);
952 sprintf(fmt, proc_fmt,
955 namelength, namelength, (*get_userid)(pp->ki_ruid),
957 pp->ki_pri.pri_level - PZERO,
959 format_k2(PROCSIZE(pp)),
960 format_k2(pagetok(pp->ki_rssize)),
962 smpmode ? pp->ki_lastcpu : 0,
963 format_time(cputime),
964 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
965 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
970 /* return the result */
975 getsysctl(const char *name, void *ptr, size_t len)
979 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
980 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
985 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
986 name, (unsigned long)len, (unsigned long)nlen);
992 format_nice(const struct kinfo_proc *pp)
994 const char *fifo, *kthread;
996 static char nicebuf[4 + 1];
998 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
999 kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1000 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1005 * XXX: the kernel doesn't tell us the original rtprio and
1006 * doesn't really know what it was, so to recover it we
1007 * must be more chummy with the implementation than the
1008 * implementation is with itself. pri_user gives a
1009 * constant "base" priority, but is only initialized
1010 * properly for user threads. pri_native gives what the
1011 * kernel calls the "base" priority, but it isn't constant
1012 * since it is changed by priority propagation. pri_native
1013 * also isn't properly initialized for all threads, but it
1014 * is properly initialized for kernel realtime and idletime
1015 * threads. Thus we use pri_user for the base priority of
1016 * user threads (it is always correct) and pri_native for
1017 * the base priority of kernel realtime and idletime threads
1018 * (there is nothing better, and it is usually correct).
1020 * The field width and thus the buffer are too small for
1021 * values like "kr31F", but such values shouldn't occur,
1022 * and if they do then the tailing "F" is not displayed.
1024 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1025 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1026 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1027 kthread, rtpri, fifo);
1030 if (pp->ki_flag & P_KTHREAD)
1032 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1035 /* XXX: as above. */
1036 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1037 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1038 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1039 kthread, rtpri, fifo);
1047 /* comparison routines for qsort */
1050 compare_pid(const void *p1, const void *p2)
1052 const struct kinfo_proc * const *pp1 = p1;
1053 const struct kinfo_proc * const *pp2 = p2;
1055 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1058 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1062 * proc_compare - comparison function for "qsort"
1063 * Compares the resource consumption of two processes using five
1064 * distinct keys. The keys (in descending order of importance) are:
1065 * percent cpu, cpu ticks, state, resident set size, total virtual
1066 * memory usage. The process states are ordered as follows (from least
1067 * to most important): WAIT, zombie, sleep, stop, start, run. The
1068 * array declaration below maps a process state index into a number
1069 * that reflects this ordering.
1072 static int sorted_state[] = {
1075 1, /* ABANDONED (WAIT) */
1083 #define ORDERKEY_PCTCPU(a, b) do { \
1086 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1088 floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1091 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1093 return (diff > 0 ? 1 : -1); \
1096 #define ORDERKEY_CPTICKS(a, b) do { \
1097 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1099 return (diff > 0 ? 1 : -1); \
1102 #define ORDERKEY_STATE(a, b) do { \
1103 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1105 return (diff > 0 ? 1 : -1); \
1108 #define ORDERKEY_PRIO(a, b) do { \
1109 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1111 return (diff > 0 ? 1 : -1); \
1114 #define ORDERKEY_THREADS(a, b) do { \
1115 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1117 return (diff > 0 ? 1 : -1); \
1120 #define ORDERKEY_RSSIZE(a, b) do { \
1121 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1123 return (diff > 0 ? 1 : -1); \
1126 #define ORDERKEY_MEM(a, b) do { \
1127 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1129 return (diff > 0 ? 1 : -1); \
1132 #define ORDERKEY_JID(a, b) do { \
1133 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1135 return (diff > 0 ? 1 : -1); \
1138 /* compare_cpu - the comparison function for sorting by cpu percentage */
1142 compare_cpu(void *arg1, void *arg2)
1144 proc_compare(void *arg1, void *arg2)
1147 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1148 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1150 ORDERKEY_PCTCPU(p1, p2);
1151 ORDERKEY_CPTICKS(p1, p2);
1152 ORDERKEY_STATE(p1, p2);
1153 ORDERKEY_PRIO(p1, p2);
1154 ORDERKEY_RSSIZE(p1, p2);
1155 ORDERKEY_MEM(p1, p2);
1161 /* "cpu" compare routines */
1162 int compare_size(), compare_res(), compare_time(), compare_prio(),
1166 * "io" compare routines. Context switches aren't i/o, but are displayed
1167 * on the "io" display.
1169 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1170 compare_vcsw(), compare_ivcsw();
1172 int (*compares[])() = {
1189 /* compare_size - the comparison function for sorting by total memory usage */
1192 compare_size(void *arg1, void *arg2)
1194 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1195 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1197 ORDERKEY_MEM(p1, p2);
1198 ORDERKEY_RSSIZE(p1, p2);
1199 ORDERKEY_PCTCPU(p1, p2);
1200 ORDERKEY_CPTICKS(p1, p2);
1201 ORDERKEY_STATE(p1, p2);
1202 ORDERKEY_PRIO(p1, p2);
1207 /* compare_res - the comparison function for sorting by resident set size */
1210 compare_res(void *arg1, void *arg2)
1212 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1213 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1215 ORDERKEY_RSSIZE(p1, p2);
1216 ORDERKEY_MEM(p1, p2);
1217 ORDERKEY_PCTCPU(p1, p2);
1218 ORDERKEY_CPTICKS(p1, p2);
1219 ORDERKEY_STATE(p1, p2);
1220 ORDERKEY_PRIO(p1, p2);
1225 /* compare_time - the comparison function for sorting by total cpu time */
1228 compare_time(void *arg1, void *arg2)
1230 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1231 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1233 ORDERKEY_CPTICKS(p1, p2);
1234 ORDERKEY_PCTCPU(p1, p2);
1235 ORDERKEY_STATE(p1, p2);
1236 ORDERKEY_PRIO(p1, p2);
1237 ORDERKEY_RSSIZE(p1, p2);
1238 ORDERKEY_MEM(p1, p2);
1243 /* compare_prio - the comparison function for sorting by priority */
1246 compare_prio(void *arg1, void *arg2)
1248 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1249 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1251 ORDERKEY_PRIO(p1, p2);
1252 ORDERKEY_CPTICKS(p1, p2);
1253 ORDERKEY_PCTCPU(p1, p2);
1254 ORDERKEY_STATE(p1, p2);
1255 ORDERKEY_RSSIZE(p1, p2);
1256 ORDERKEY_MEM(p1, p2);
1261 /* compare_threads - the comparison function for sorting by threads */
1263 compare_threads(void *arg1, void *arg2)
1265 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1266 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1268 ORDERKEY_THREADS(p1, p2);
1269 ORDERKEY_PCTCPU(p1, p2);
1270 ORDERKEY_CPTICKS(p1, p2);
1271 ORDERKEY_STATE(p1, p2);
1272 ORDERKEY_PRIO(p1, p2);
1273 ORDERKEY_RSSIZE(p1, p2);
1274 ORDERKEY_MEM(p1, p2);
1279 /* compare_jid - the comparison function for sorting by jid */
1281 compare_jid(const void *arg1, const void *arg2)
1283 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1284 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1286 ORDERKEY_JID(p1, p2);
1287 ORDERKEY_PCTCPU(p1, p2);
1288 ORDERKEY_CPTICKS(p1, p2);
1289 ORDERKEY_STATE(p1, p2);
1290 ORDERKEY_PRIO(p1, p2);
1291 ORDERKEY_RSSIZE(p1, p2);
1292 ORDERKEY_MEM(p1, p2);
1298 /* assorted comparison functions for sorting by i/o */
1302 compare_iototal(void *arg1, void *arg2)
1304 io_compare(void *arg1, void *arg2)
1307 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1308 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1310 return (get_io_total(p2) - get_io_total(p1));
1315 compare_ioread(void *arg1, void *arg2)
1317 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1318 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1319 long dummy, inp1, inp2;
1321 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1322 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1324 return (inp2 - inp1);
1328 compare_iowrite(void *arg1, void *arg2)
1330 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1331 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1332 long dummy, oup1, oup2;
1334 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1335 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1337 return (oup2 - oup1);
1341 compare_iofault(void *arg1, void *arg2)
1343 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1344 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1345 long dummy, flp1, flp2;
1347 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1348 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1350 return (flp2 - flp1);
1354 compare_vcsw(void *arg1, void *arg2)
1356 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1357 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1358 long dummy, flp1, flp2;
1360 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1361 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1363 return (flp2 - flp1);
1367 compare_ivcsw(void *arg1, void *arg2)
1369 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1370 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1371 long dummy, flp1, flp2;
1373 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1374 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1376 return (flp2 - flp1);
1381 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1382 * the process does not exist.
1383 * It is EXTREMLY IMPORTANT that this function work correctly.
1384 * If top runs setuid root (as in SVR4), then this function
1385 * is the only thing that stands in the way of a serious
1386 * security problem. It validates requests for the "kill"
1387 * and "renice" commands.
1394 struct kinfo_proc **prefp;
1395 struct kinfo_proc *pp;
1399 while (--cnt >= 0) {
1401 if (pp->ki_pid == (pid_t)pid)
1402 return ((int)pp->ki_ruid);
1408 swapmode(int *retavail, int *retfree)
1411 int pagesize = getpagesize();
1412 struct kvm_swap swapary[1];
1417 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1419 n = kvm_getswapinfo(kd, swapary, 1, 0);
1420 if (n < 0 || swapary[0].ksw_total == 0)
1423 *retavail = CONVERT(swapary[0].ksw_total);
1424 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1426 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);