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 %6s COMMAND";
111 static char smp_header[] =
112 " PID%s %-*.*s " "PRI NICE SIZE RES STATE C TIME %6s COMMAND";
114 #define smp_Proc_format \
115 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %2d%7s %5.2f%% %.*s"
117 static char up_header_thr[] =
118 " PID%s %-*.*s THR PRI NICE SIZE RES STATE TIME %6s COMMAND";
119 static char up_header[] =
120 " PID%s %-*.*s " "PRI NICE SIZE RES STATE TIME %6s COMMAND";
122 #define up_Proc_format \
123 "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.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, ",
180 char *swapnames[] = {
181 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
186 /* these are for keeping track of the proc array */
189 static int onproc = -1;
191 static struct kinfo_proc *pbase;
192 static struct kinfo_proc **pref;
193 static struct kinfo_proc *previous_procs;
194 static struct kinfo_proc **previous_pref;
195 static int previous_proc_count = 0;
196 static int previous_proc_count_max = 0;
198 /* total number of io operations */
199 static long total_inblock;
200 static long total_oublock;
201 static long total_majflt;
203 /* these are for getting the memory statistics */
205 static int pageshift; /* log base 2 of the pagesize */
207 /* define pagetok in terms of pageshift */
209 #define pagetok(size) ((size) << pageshift)
211 /* useful externals */
216 * Sorting orders. The first element is the default.
218 char *ordernames[] = {
219 "cpu", "size", "res", "time", "pri", "threads",
220 "total", "read", "write", "fault", "vcsw", "ivcsw",
225 /* Per-cpu time states */
229 static u_long cpumask;
231 static long *pcpu_cp_time;
232 static long *pcpu_cp_old;
233 static long *pcpu_cp_diff;
234 static int *pcpu_cpu_states;
236 static int compare_jid(const void *a, const void *b);
237 static int compare_pid(const void *a, const void *b);
238 static const char *format_nice(const struct kinfo_proc *pp);
239 static void getsysctl(const char *name, void *ptr, size_t len);
240 static int swapmode(int *retavail, int *retfree);
243 machine_init(struct statics *statics, char do_unames)
249 modelen = sizeof(smpmode);
250 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
252 sysctlbyname("kern.smp.active", &smpmode, &modelen,
254 modelen != sizeof(smpmode))
258 while ((pw = getpwent()) != NULL) {
259 if (strlen(pw->pw_name) > namelength)
260 namelength = strlen(pw->pw_name);
263 if (smpmode && namelength > SMPUNAMELEN)
264 namelength = SMPUNAMELEN;
265 else if (namelength > UPUNAMELEN)
266 namelength = UPUNAMELEN;
268 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
272 GETSYSCTL("kern.ccpu", ccpu);
274 /* this is used in calculating WCPU -- calculate it ahead of time */
275 logcpu = log(loaddouble(ccpu));
282 /* get the page size and calculate pageshift from it */
283 pagesize = getpagesize();
285 while (pagesize > 1) {
290 /* we only need the amount of log(2)1024 for our conversion */
291 pageshift -= LOG1024;
293 /* fill in the statics information */
294 statics->procstate_names = procstatenames;
295 statics->cpustate_names = cpustatenames;
296 statics->memory_names = memorynames;
297 statics->swap_names = swapnames;
299 statics->order_names = ordernames;
302 /* Adjust display based on ncpus */
309 GETSYSCTL("kern.smp.maxcpus", maxcpu);
310 size = sizeof(long) * maxcpu * CPUSTATES;
311 times = malloc(size);
313 err(1, "malloc %zd bytes", size);
314 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
315 err(1, "sysctlbyname kern.cp_times");
316 pcpu_cp_time = calloc(1, size);
317 maxid = (size / CPUSTATES / sizeof(long)) - 1;
318 for (i = 0; i <= maxid; i++) {
320 for (j = 0; empty && j < CPUSTATES; j++) {
321 if (times[i * CPUSTATES + j] != 0)
325 cpumask |= (1ul << i);
331 y_mem += ncpus - 1; /* 3 */
332 y_swap += ncpus - 1; /* 4 */
333 y_idlecursor += ncpus - 1; /* 5 */
334 y_message += ncpus - 1; /* 5 */
335 y_header += ncpus - 1; /* 6 */
336 y_procs += ncpus - 1; /* 7 */
337 Header_lines += ncpus - 1; /* 7 */
339 size = sizeof(long) * ncpus * CPUSTATES;
340 pcpu_cp_old = calloc(1, size);
341 pcpu_cp_diff = calloc(1, size);
342 pcpu_cpu_states = calloc(1, size);
343 statics->ncpus = ncpus;
353 format_header(char *uname_field)
355 static char Header[128];
358 switch (displaymode) {
361 * The logic of picking the right header format seems reverse
362 * here because we only want to display a THR column when
363 * "thread mode" is off (and threads are not listed as
367 (ps.thread ? smp_header : smp_header_thr) :
368 (ps.thread ? up_header : up_header_thr);
369 snprintf(Header, sizeof(Header), prehead,
370 ps.jail ? " JID" : "",
371 namelength, namelength, uname_field,
372 ps.wcpu ? "WCPU" : "CPU");
376 snprintf(Header, sizeof(Header), prehead,
377 ps.jail ? " JID" : "",
378 namelength, namelength, uname_field);
381 cmdlengthdelta = strlen(Header) - 7;
385 static int swappgsin = -1;
386 static int swappgsout = -1;
387 extern struct timeval timeout;
391 get_system_info(struct system_info *si)
394 struct loadavg sysload;
396 struct timeval boottime;
401 /* get the cp_time array */
403 size = (maxid + 1) * CPUSTATES * sizeof(long);
404 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
405 err(1, "sysctlbyname kern.cp_times");
407 GETSYSCTL("kern.cp_time", cp_time);
409 GETSYSCTL("vm.loadavg", sysload);
410 GETSYSCTL("kern.lastpid", lastpid);
412 /* convert load averages to doubles */
413 for (i = 0; i < 3; i++)
414 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
417 for (i = j = 0; i <= maxid; i++) {
418 if ((cpumask & (1ul << i)) == 0)
420 /* convert cp_time counts to percentages */
421 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
422 &pcpu_cp_time[j * CPUSTATES],
423 &pcpu_cp_old[j * CPUSTATES],
424 &pcpu_cp_diff[j * CPUSTATES]);
428 /* convert cp_time counts to percentages */
429 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
432 /* sum memory & swap statistics */
434 static unsigned int swap_delay = 0;
435 static int swapavail = 0;
436 static int swapfree = 0;
437 static long bufspace = 0;
438 static int nspgsin, nspgsout;
440 GETSYSCTL("vfs.bufspace", bufspace);
441 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
442 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
443 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
444 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
445 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
446 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
447 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
448 /* convert memory stats to Kbytes */
449 memory_stats[0] = pagetok(memory_stats[0]);
450 memory_stats[1] = pagetok(memory_stats[1]);
451 memory_stats[2] = pagetok(memory_stats[2]);
452 memory_stats[3] = pagetok(memory_stats[3]);
453 memory_stats[4] = bufspace / 1024;
454 memory_stats[5] = pagetok(memory_stats[5]);
455 memory_stats[6] = -1;
463 /* compute differences between old and new swap statistic */
465 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
466 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
470 swappgsout = nspgsout;
472 /* call CPU heavy swapmode() only for changes */
473 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
474 swap_stats[3] = swapmode(&swapavail, &swapfree);
475 swap_stats[0] = swapavail;
476 swap_stats[1] = swapavail - swapfree;
477 swap_stats[2] = swapfree;
483 /* set arrays and strings */
485 si->cpustates = pcpu_cpu_states;
488 si->cpustates = cpu_states;
491 si->memory = memory_stats;
492 si->swap = swap_stats;
496 si->last_pid = lastpid;
502 * Print how long system has been up.
503 * (Found by looking getting "boottime" from the kernel)
506 mib[1] = KERN_BOOTTIME;
507 bt_size = sizeof(boottime);
508 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
509 boottime.tv_sec != 0) {
510 si->boottime = boottime;
512 si->boottime.tv_sec = -1;
516 #define NOPROC ((void *)-1)
519 * We need to compare data from the old process entry with the new
521 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
522 * structure to cache the mapping. We also use a negative cache pointer
523 * of NOPROC to avoid duplicate lookups.
524 * XXX: this could be done when the actual processes are fetched, we do
525 * it here out of laziness.
527 const struct kinfo_proc *
528 get_old_proc(struct kinfo_proc *pp)
530 struct kinfo_proc **oldpp, *oldp;
533 * If this is the first fetch of the kinfo_procs then we don't have
534 * any previous entries.
536 if (previous_proc_count == 0)
538 /* negative cache? */
539 if (pp->ki_udata == NOPROC)
542 if (pp->ki_udata != NULL)
543 return (pp->ki_udata);
546 * 1) look up based on pid.
547 * 2) compare process start.
548 * If we fail here, then setup a negative cache entry, otherwise
551 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
552 sizeof(*previous_pref), compare_pid);
554 pp->ki_udata = NOPROC;
558 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
559 pp->ki_udata = NOPROC;
567 * Return the total amount of IO done in blocks in/out and faults.
568 * store the values individually in the pointers passed in.
571 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
572 long *vcsw, long *ivcsw)
574 const struct kinfo_proc *oldp;
575 static struct kinfo_proc dummy;
578 oldp = get_old_proc(pp);
580 bzero(&dummy, sizeof(dummy));
583 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
584 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
585 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
586 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
587 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
589 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
590 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
591 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
596 * Return the total number of block in/out and faults by a process.
599 get_io_total(struct kinfo_proc *pp)
603 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
606 static struct handle handle;
609 get_process_info(struct system_info *si, struct process_select *sel,
610 int (*compare)(const void *, const void *))
615 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
617 struct kinfo_proc **prefp;
618 struct kinfo_proc *pp;
619 struct kinfo_proc *prev_pp = NULL;
621 /* 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;
668 show_kidle = sel->kidle;
670 /* count up process states and get pointers to interesting procs */
676 memset((char *)process_states, 0, sizeof(process_states));
678 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
680 if (pp->ki_stat == 0)
684 if (!show_self && pp->ki_pid == sel->self)
688 if (!show_system && (pp->ki_flag & P_SYSTEM))
689 /* skip system process */
692 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
694 total_inblock += p_inblock;
695 total_oublock += p_oublock;
696 total_majflt += p_majflt;
698 process_states[pp->ki_stat]++;
700 if (pp->ki_stat == SZOMB)
704 if (displaymode == DISP_CPU && !show_idle &&
705 (pp->ki_pctcpu == 0 ||
706 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
707 /* skip idle or non-running processes */
710 if (displaymode == DISP_CPU && !show_kidle &&
711 pp->ki_tdflags & TDF_IDLETD)
712 /* skip kernel idle process */
715 if (displaymode == DISP_IO && !show_idle && p_io == 0)
716 /* skip processes that aren't doing I/O */
719 if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
720 /* skip proc. that don't belong to the selected UID */
724 * When not showing threads, take the first thread
725 * for output and add the fields that we can from
726 * the rest of the process's threads rather than
727 * using the system's mostly-broken KERN_PROC_PROC.
729 if (sel->thread || prev_pp == NULL ||
730 prev_pp->ki_pid != pp->ki_pid) {
735 prev_pp->ki_pctcpu += pp->ki_pctcpu;
736 prev_pp->ki_runtime += pp->ki_runtime;
740 /* if requested, sort the "interesting" processes */
742 qsort(pref, active_procs, sizeof(*pref), compare);
744 /* remember active and total counts */
745 si->p_total = total_procs;
746 si->p_active = pref_len = active_procs;
748 /* pass back a handle */
749 handle.next_proc = pref;
750 handle.remaining = active_procs;
751 return ((caddr_t)&handle);
754 static char fmt[128]; /* static area where result is built */
757 format_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
759 struct kinfo_proc *pp;
760 const struct kinfo_proc *oldp;
766 struct rusage ru, *rup;
768 char *proc_fmt, thr_buf[6], jid_buf[6];
772 /* find and remember the next proc structure */
773 hp = (struct handle *)handle;
774 pp = *(hp->next_proc++);
777 /* get the process's command name */
778 if ((pp->ki_flag & P_INMEM) == 0) {
780 * Print swapped processes as <pname>
784 len = strlen(pp->ki_comm);
785 if (len > sizeof(pp->ki_comm) - 3)
786 len = sizeof(pp->ki_comm) - 3;
787 memmove(pp->ki_comm + 1, pp->ki_comm, len);
788 pp->ki_comm[0] = '<';
789 pp->ki_comm[len + 1] = '>';
790 pp->ki_comm[len + 2] = '\0';
794 * Convert the process's runtime from microseconds to seconds. This
795 * time includes the interrupt time although that is not wanted here.
796 * ps(1) is similarly sloppy.
798 cputime = (pp->ki_runtime + 500000) / 1000000;
800 /* calculate the base for cpu percentages */
801 pct = pctdouble(pp->ki_pctcpu);
803 /* generate "STATE" field */
804 switch (state = pp->ki_stat) {
806 if (smpmode && pp->ki_oncpu != 0xff)
807 sprintf(status, "CPU%d", pp->ki_oncpu);
809 strcpy(status, "RUN");
812 if (pp->ki_kiflag & KI_LOCKBLOCK) {
813 sprintf(status, "*%.6s", pp->ki_lockname);
818 if (pp->ki_wmesg != NULL) {
819 sprintf(status, "%.6s", pp->ki_wmesg);
826 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
827 sprintf(status, "%.6s", state_abbrev[state]);
829 sprintf(status, "?%5d", state);
833 cmdbuf = (char *)malloc(cmdlengthdelta + 1);
834 if (cmdbuf == NULL) {
835 warn("malloc(%d)", cmdlengthdelta + 1);
839 if (!(flags & FMT_SHOWARGS)) {
840 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
842 snprintf(cmdbuf, cmdlengthdelta, "{%s}", pp->ki_ocomm);
844 snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
847 if (pp->ki_flag & P_SYSTEM ||
848 pp->ki_args == NULL ||
849 (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
851 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
853 snprintf(cmdbuf, cmdlengthdelta,
854 "{%s}", pp->ki_ocomm);
856 snprintf(cmdbuf, cmdlengthdelta,
857 "[%s]", pp->ki_comm);
860 char *src, *dst, *argbuf;
865 argbuflen = cmdlengthdelta * 4;
866 argbuf = (char *)malloc(argbuflen + 1);
867 if (argbuf == NULL) {
868 warn("malloc(%d)", argbuflen + 1);
875 /* Extract cmd name from argv */
876 cmd = strrchr(*args, '/');
882 for (; (src = *args++) != NULL; ) {
885 len = (argbuflen - (dst - argbuf) - 1) / 4;
887 strlen(src) < len ? strlen(src) : len,
888 VIS_NL | VIS_CSTYLE);
891 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
892 *dst++ = ' '; /* add delimiting space */
894 if (dst != argbuf && dst[-1] == ' ')
898 if (strcmp(cmd, pp->ki_comm) != 0 )
899 snprintf(cmdbuf, cmdlengthdelta,
900 "%s (%s)",argbuf, pp->ki_comm);
902 strlcpy(cmdbuf, argbuf, cmdlengthdelta);
911 snprintf(jid_buf, sizeof(jid_buf), " %*d",
912 sizeof(jid_buf) - 3, pp->ki_jid);
914 if (displaymode == DISP_IO) {
915 oldp = get_old_proc(pp);
917 ru.ru_inblock = RU(pp)->ru_inblock -
918 RU(oldp)->ru_inblock;
919 ru.ru_oublock = RU(pp)->ru_oublock -
920 RU(oldp)->ru_oublock;
921 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
922 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
923 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
928 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
929 s_tot = total_inblock + total_oublock + total_majflt;
931 sprintf(fmt, io_Proc_format,
934 namelength, namelength, (*get_userid)(pp->ki_ruid),
941 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
942 screen_width > cmdlengthdelta ?
943 screen_width - cmdlengthdelta : 0,
951 /* format this entry */
952 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
956 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
957 sizeof(thr_buf) - 2, pp->ki_numthreads);
959 sprintf(fmt, proc_fmt,
962 namelength, namelength, (*get_userid)(pp->ki_ruid),
964 pp->ki_pri.pri_level - PZERO,
966 format_k2(PROCSIZE(pp)),
967 format_k2(pagetok(pp->ki_rssize)),
969 smpmode ? pp->ki_lastcpu : 0,
970 format_time(cputime),
971 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
972 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
977 /* return the result */
982 getsysctl(const char *name, void *ptr, size_t len)
986 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
987 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
992 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
993 name, (unsigned long)len, (unsigned long)nlen);
999 format_nice(const struct kinfo_proc *pp)
1001 const char *fifo, *kthread;
1003 static char nicebuf[4 + 1];
1005 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1006 kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1007 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1012 * XXX: the kernel doesn't tell us the original rtprio and
1013 * doesn't really know what it was, so to recover it we
1014 * must be more chummy with the implementation than the
1015 * implementation is with itself. pri_user gives a
1016 * constant "base" priority, but is only initialized
1017 * properly for user threads. pri_native gives what the
1018 * kernel calls the "base" priority, but it isn't constant
1019 * since it is changed by priority propagation. pri_native
1020 * also isn't properly initialized for all threads, but it
1021 * is properly initialized for kernel realtime and idletime
1022 * threads. Thus we use pri_user for the base priority of
1023 * user threads (it is always correct) and pri_native for
1024 * the base priority of kernel realtime and idletime threads
1025 * (there is nothing better, and it is usually correct).
1027 * The field width and thus the buffer are too small for
1028 * values like "kr31F", but such values shouldn't occur,
1029 * and if they do then the tailing "F" is not displayed.
1031 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1032 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1033 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1034 kthread, rtpri, fifo);
1037 if (pp->ki_flag & P_KTHREAD)
1039 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1042 /* XXX: as above. */
1043 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1044 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1045 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1046 kthread, rtpri, fifo);
1054 /* comparison routines for qsort */
1057 compare_pid(const void *p1, const void *p2)
1059 const struct kinfo_proc * const *pp1 = p1;
1060 const struct kinfo_proc * const *pp2 = p2;
1062 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1065 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1069 * proc_compare - comparison function for "qsort"
1070 * Compares the resource consumption of two processes using five
1071 * distinct keys. The keys (in descending order of importance) are:
1072 * percent cpu, cpu ticks, state, resident set size, total virtual
1073 * memory usage. The process states are ordered as follows (from least
1074 * to most important): WAIT, zombie, sleep, stop, start, run. The
1075 * array declaration below maps a process state index into a number
1076 * that reflects this ordering.
1079 static int sorted_state[] = {
1082 1, /* ABANDONED (WAIT) */
1090 #define ORDERKEY_PCTCPU(a, b) do { \
1093 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1095 floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1098 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1100 return (diff > 0 ? 1 : -1); \
1103 #define ORDERKEY_CPTICKS(a, b) do { \
1104 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1106 return (diff > 0 ? 1 : -1); \
1109 #define ORDERKEY_STATE(a, b) do { \
1110 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1112 return (diff > 0 ? 1 : -1); \
1115 #define ORDERKEY_PRIO(a, b) do { \
1116 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1118 return (diff > 0 ? 1 : -1); \
1121 #define ORDERKEY_THREADS(a, b) do { \
1122 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1124 return (diff > 0 ? 1 : -1); \
1127 #define ORDERKEY_RSSIZE(a, b) do { \
1128 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1130 return (diff > 0 ? 1 : -1); \
1133 #define ORDERKEY_MEM(a, b) do { \
1134 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1136 return (diff > 0 ? 1 : -1); \
1139 #define ORDERKEY_JID(a, b) do { \
1140 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1142 return (diff > 0 ? 1 : -1); \
1145 /* compare_cpu - the comparison function for sorting by cpu percentage */
1149 compare_cpu(void *arg1, void *arg2)
1151 proc_compare(void *arg1, void *arg2)
1154 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1155 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1157 ORDERKEY_PCTCPU(p1, p2);
1158 ORDERKEY_CPTICKS(p1, p2);
1159 ORDERKEY_STATE(p1, p2);
1160 ORDERKEY_PRIO(p1, p2);
1161 ORDERKEY_RSSIZE(p1, p2);
1162 ORDERKEY_MEM(p1, p2);
1168 /* "cpu" compare routines */
1169 int compare_size(), compare_res(), compare_time(), compare_prio(),
1173 * "io" compare routines. Context switches aren't i/o, but are displayed
1174 * on the "io" display.
1176 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1177 compare_vcsw(), compare_ivcsw();
1179 int (*compares[])() = {
1196 /* compare_size - the comparison function for sorting by total memory usage */
1199 compare_size(void *arg1, void *arg2)
1201 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1202 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1204 ORDERKEY_MEM(p1, p2);
1205 ORDERKEY_RSSIZE(p1, p2);
1206 ORDERKEY_PCTCPU(p1, p2);
1207 ORDERKEY_CPTICKS(p1, p2);
1208 ORDERKEY_STATE(p1, p2);
1209 ORDERKEY_PRIO(p1, p2);
1214 /* compare_res - the comparison function for sorting by resident set size */
1217 compare_res(void *arg1, void *arg2)
1219 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1220 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1222 ORDERKEY_RSSIZE(p1, p2);
1223 ORDERKEY_MEM(p1, p2);
1224 ORDERKEY_PCTCPU(p1, p2);
1225 ORDERKEY_CPTICKS(p1, p2);
1226 ORDERKEY_STATE(p1, p2);
1227 ORDERKEY_PRIO(p1, p2);
1232 /* compare_time - the comparison function for sorting by total cpu time */
1235 compare_time(void *arg1, void *arg2)
1237 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1238 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1240 ORDERKEY_CPTICKS(p1, p2);
1241 ORDERKEY_PCTCPU(p1, p2);
1242 ORDERKEY_STATE(p1, p2);
1243 ORDERKEY_PRIO(p1, p2);
1244 ORDERKEY_RSSIZE(p1, p2);
1245 ORDERKEY_MEM(p1, p2);
1250 /* compare_prio - the comparison function for sorting by priority */
1253 compare_prio(void *arg1, void *arg2)
1255 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1256 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1258 ORDERKEY_PRIO(p1, p2);
1259 ORDERKEY_CPTICKS(p1, p2);
1260 ORDERKEY_PCTCPU(p1, p2);
1261 ORDERKEY_STATE(p1, p2);
1262 ORDERKEY_RSSIZE(p1, p2);
1263 ORDERKEY_MEM(p1, p2);
1268 /* compare_threads - the comparison function for sorting by threads */
1270 compare_threads(void *arg1, void *arg2)
1272 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1273 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1275 ORDERKEY_THREADS(p1, p2);
1276 ORDERKEY_PCTCPU(p1, p2);
1277 ORDERKEY_CPTICKS(p1, p2);
1278 ORDERKEY_STATE(p1, p2);
1279 ORDERKEY_PRIO(p1, p2);
1280 ORDERKEY_RSSIZE(p1, p2);
1281 ORDERKEY_MEM(p1, p2);
1286 /* compare_jid - the comparison function for sorting by jid */
1288 compare_jid(const void *arg1, const void *arg2)
1290 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1291 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1293 ORDERKEY_JID(p1, p2);
1294 ORDERKEY_PCTCPU(p1, p2);
1295 ORDERKEY_CPTICKS(p1, p2);
1296 ORDERKEY_STATE(p1, p2);
1297 ORDERKEY_PRIO(p1, p2);
1298 ORDERKEY_RSSIZE(p1, p2);
1299 ORDERKEY_MEM(p1, p2);
1305 /* assorted comparison functions for sorting by i/o */
1309 compare_iototal(void *arg1, void *arg2)
1311 io_compare(void *arg1, void *arg2)
1314 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1315 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1317 return (get_io_total(p2) - get_io_total(p1));
1322 compare_ioread(void *arg1, void *arg2)
1324 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1325 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1326 long dummy, inp1, inp2;
1328 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1329 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1331 return (inp2 - inp1);
1335 compare_iowrite(void *arg1, void *arg2)
1337 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1338 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1339 long dummy, oup1, oup2;
1341 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1342 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1344 return (oup2 - oup1);
1348 compare_iofault(void *arg1, void *arg2)
1350 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1351 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1352 long dummy, flp1, flp2;
1354 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1355 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1357 return (flp2 - flp1);
1361 compare_vcsw(void *arg1, void *arg2)
1363 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1364 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1365 long dummy, flp1, flp2;
1367 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1368 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1370 return (flp2 - flp1);
1374 compare_ivcsw(void *arg1, void *arg2)
1376 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1377 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1378 long dummy, flp1, flp2;
1380 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1381 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1383 return (flp2 - flp1);
1388 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1389 * the process does not exist.
1390 * It is EXTREMLY IMPORTANT that this function work correctly.
1391 * If top runs setuid root (as in SVR4), then this function
1392 * is the only thing that stands in the way of a serious
1393 * security problem. It validates requests for the "kill"
1394 * and "renice" commands.
1401 struct kinfo_proc **prefp;
1402 struct kinfo_proc *pp;
1406 while (--cnt >= 0) {
1408 if (pp->ki_pid == (pid_t)pid)
1409 return ((int)pp->ki_ruid);
1415 swapmode(int *retavail, int *retfree)
1418 int pagesize = getpagesize();
1419 struct kvm_swap swapary[1];
1424 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1426 n = kvm_getswapinfo(kd, swapary, 1, 0);
1427 if (n < 0 || swapary[0].ksw_total == 0)
1430 *retavail = CONVERT(swapary[0].ksw_total);
1431 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1433 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);