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 static void getsysctl(char *, void *, size_t);
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 *);
63 int swapmode(int *retavail, int *retfree);
65 enum displaymodes displaymode;
66 static int namelength = 8;
67 static int cmdlengthdelta;
69 /* Per-cpu time states */
73 static u_long cpumask;
75 static long *pcpu_cp_time;
76 static long *pcpu_cp_old;
77 static long *pcpu_cp_diff;
78 static int *pcpu_cpu_states;
80 /* Prototypes for top internals */
82 int compare_jid(const void *a, const void *b);
83 int compare_pid(const void *a, const void *b);
85 /* get_process_info passes back a handle. This is what it looks like: */
89 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
90 int remaining; /* number of pointers remaining */
93 /* declarations for load_avg */
96 /* define what weighted cpu is. */
97 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
98 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
100 /* what we consider to be process size: */
101 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
103 #define RU(pp) (&(pp)->ki_rusage)
105 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
108 /* definitions for indices in the nlist array */
111 * These definitions control the format of the per-process area
114 static char io_header[] =
115 " PID%s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
117 #define io_Proc_format \
118 "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
120 static char smp_header_thr[] =
121 " PID%s %-*.*s THR PRI NICE SIZE RES STATE C TIME %6s COMMAND";
122 static char smp_header[] =
123 " PID%s %-*.*s " "PRI NICE SIZE RES STATE C TIME %6s COMMAND";
125 #define smp_Proc_format \
126 "%5d%s %-*.*s %s%3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
128 static char up_header_thr[] =
129 " PID%s %-*.*s THR PRI NICE SIZE RES STATE TIME %6s COMMAND";
130 static char up_header[] =
131 " PID%s %-*.*s " "PRI NICE SIZE RES STATE TIME %6s COMMAND";
133 #define up_Proc_format \
134 "%5d%s %-*.*s %s%3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
137 /* process state names for the "STATE" column of the display */
138 /* the extra nulls in the string "run" are for adding a slash and
139 the processor number when needed */
141 char *state_abbrev[] =
143 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
149 /* values that we stash away in _init and use in later routines */
151 static double logcpu;
153 /* these are retrieved from the kernel in _init */
155 static load_avg ccpu;
157 /* these are used in the get_ functions */
161 /* these are for calculating cpu state percentages */
163 static long cp_time[CPUSTATES];
164 static long cp_old[CPUSTATES];
165 static long cp_diff[CPUSTATES];
167 /* these are for detailing the process states */
169 int process_states[8];
170 char *procstatenames[] = {
171 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
172 " zombie, ", " waiting, ", " lock, ",
176 /* these are for detailing the cpu states */
178 int cpu_states[CPUSTATES];
179 char *cpustatenames[] = {
180 "user", "nice", "system", "interrupt", "idle", NULL
183 /* these are for detailing the memory statistics */
186 char *memorynames[] = {
188 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
193 char *swapnames[] = {
195 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
200 /* these are for keeping track of the proc array */
203 static int onproc = -1;
205 static struct kinfo_proc *pbase;
206 static struct kinfo_proc **pref;
207 static struct kinfo_proc *previous_procs;
208 static struct kinfo_proc **previous_pref;
209 static int previous_proc_count = 0;
210 static int previous_proc_count_max = 0;
212 /* total number of io operations */
213 static long total_inblock;
214 static long total_oublock;
215 static long total_majflt;
217 /* these are for getting the memory statistics */
219 static int pageshift; /* log base 2 of the pagesize */
221 /* define pagetok in terms of pageshift */
223 #define pagetok(size) ((size) << pageshift)
225 /* useful externals */
230 * Sorting orders. The first element is the default.
232 char *ordernames[] = {
233 "cpu", "size", "res", "time", "pri", "threads",
234 "total", "read", "write", "fault", "vcsw", "ivcsw",
240 machine_init(struct statics *statics)
246 modelen = sizeof(smpmode);
247 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
248 sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
249 modelen != sizeof(smpmode))
252 while ((pw = getpwent()) != NULL) {
253 if (strlen(pw->pw_name) > namelength)
254 namelength = strlen(pw->pw_name);
256 if (smpmode && namelength > SMPUNAMELEN)
257 namelength = SMPUNAMELEN;
258 else if (namelength > UPUNAMELEN)
259 namelength = UPUNAMELEN;
261 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
265 GETSYSCTL("kern.ccpu", ccpu);
267 /* this is used in calculating WCPU -- calculate it ahead of time */
268 logcpu = log(loaddouble(ccpu));
274 /* get the page size with "getpagesize" and calculate pageshift from it */
275 pagesize = getpagesize();
277 while (pagesize > 1) {
282 /* we only need the amount of log(2)1024 for our conversion */
283 pageshift -= LOG1024;
285 /* fill in the statics information */
286 statics->procstate_names = procstatenames;
287 statics->cpustate_names = cpustatenames;
288 statics->memory_names = memorynames;
289 statics->swap_names = swapnames;
291 statics->order_names = ordernames;
294 /* Adjust display based on ncpus */
301 GETSYSCTL("kern.smp.maxcpus", maxcpu);
302 size = sizeof(long) * maxcpu * CPUSTATES;
303 times = malloc(size);
305 err(1, "malloc %zd bytes", size);
306 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
307 err(1, "sysctlbyname kern.cp_times");
308 maxid = (size / CPUSTATES / sizeof(long)) - 1;
309 for (i = 0; i <= maxid; i++) {
311 for (j = 0; empty && j < CPUSTATES; j++) {
312 if (times[i * CPUSTATES + j] != 0)
316 cpumask |= (1ul << i);
322 y_mem += ncpus - 1; /* 3 */
323 y_swap += ncpus - 1; /* 4 */
324 y_idlecursor += ncpus - 1; /* 5 */
325 y_message += ncpus - 1; /* 5 */
326 y_header += ncpus - 1; /* 6 */
327 y_procs += ncpus - 1; /* 7 */
328 Header_lines += ncpus - 1; /* 7 */
330 size = sizeof(long) * ncpus * CPUSTATES;
331 pcpu_cp_time = malloc(size);
332 pcpu_cp_old = malloc(size);
333 pcpu_cp_diff = malloc(size);
334 pcpu_cpu_states = malloc(size);
335 bzero(pcpu_cp_time, size);
336 bzero(pcpu_cp_old, size);
337 bzero(pcpu_cp_diff, size);
338 bzero(pcpu_cpu_states, size);
339 statics->ncpus = ncpus;
349 format_header(char *uname_field)
351 static char Header[128];
354 switch (displaymode) {
357 * The logic of picking the right header format seems reverse
358 * here because we only want to display a THR column when
359 * "thread mode" is off (and threads are not listed as
363 (ps.thread ? smp_header : smp_header_thr) :
364 (ps.thread ? up_header : up_header_thr);
365 snprintf(Header, sizeof(Header), prehead,
366 ps.jail ? " JID" : "",
367 namelength, namelength, uname_field,
368 ps.wcpu ? "WCPU" : "CPU");
372 snprintf(Header, sizeof(Header), prehead,
373 ps.jail ? " JID" : "",
374 namelength, namelength, uname_field);
377 cmdlengthdelta = strlen(Header) - 7;
381 static int swappgsin = -1;
382 static int swappgsout = -1;
383 extern struct timeval timeout;
387 get_system_info(struct system_info *si)
390 struct loadavg sysload;
392 struct timeval boottime;
397 /* get the cp_time array */
399 size = (maxid + 1) * CPUSTATES * sizeof(long);
400 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
401 err(1, "sysctlbyname kern.cp_times");
403 GETSYSCTL("kern.cp_time", cp_time);
405 GETSYSCTL("vm.loadavg", sysload);
406 GETSYSCTL("kern.lastpid", lastpid);
408 /* convert load averages to doubles */
409 for (i = 0; i < 3; i++)
410 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
413 for (i = j = 0; i <= maxid; i++, j++) {
414 if (cpumask && (1ul << i) == 0)
416 /* convert cp_time counts to percentages */
417 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
418 &pcpu_cp_time[j * CPUSTATES],
419 &pcpu_cp_old[j * CPUSTATES],
420 &pcpu_cp_diff[j * CPUSTATES]);
423 /* convert cp_time counts to percentages */
424 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
427 /* sum memory & swap statistics */
429 static unsigned int swap_delay = 0;
430 static int swapavail = 0;
431 static int swapfree = 0;
432 static int bufspace = 0;
433 static int nspgsin, nspgsout;
435 GETSYSCTL("vfs.bufspace", bufspace);
436 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
437 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
438 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
439 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
440 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
441 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
442 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
443 /* convert memory stats to Kbytes */
444 memory_stats[0] = pagetok(memory_stats[0]);
445 memory_stats[1] = pagetok(memory_stats[1]);
446 memory_stats[2] = pagetok(memory_stats[2]);
447 memory_stats[3] = pagetok(memory_stats[3]);
448 memory_stats[4] = bufspace / 1024;
449 memory_stats[5] = pagetok(memory_stats[5]);
450 memory_stats[6] = -1;
458 /* compute differences between old and new swap statistic */
460 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
461 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
465 swappgsout = nspgsout;
467 /* call CPU heavy swapmode() only for changes */
468 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
469 swap_stats[3] = swapmode(&swapavail, &swapfree);
470 swap_stats[0] = swapavail;
471 swap_stats[1] = swapavail - swapfree;
472 swap_stats[2] = swapfree;
478 /* set arrays and strings */
480 si->cpustates = pcpu_cpu_states;
481 si->cpumask = cpumask;
484 si->cpustates = cpu_states;
488 si->memory = memory_stats;
489 si->swap = swap_stats;
493 si->last_pid = lastpid;
499 * Print how long system has been up.
500 * (Found by looking getting "boottime" from the kernel)
503 mib[1] = KERN_BOOTTIME;
504 bt_size = sizeof(boottime);
505 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
506 boottime.tv_sec != 0) {
507 si->boottime = boottime;
509 si->boottime.tv_sec = -1;
513 #define NOPROC ((void *)-1)
516 * We need to compare data from the old process entry with the new
518 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
519 * structure to cache the mapping. We also use a negative cache pointer
520 * of NOPROC to avoid duplicate lookups.
521 * XXX: this could be done when the actual processes are fetched, we do
522 * it here out of laziness.
524 const struct kinfo_proc *
525 get_old_proc(struct kinfo_proc *pp)
527 struct kinfo_proc **oldpp, *oldp;
530 * If this is the first fetch of the kinfo_procs then we don't have
531 * any previous entries.
533 if (previous_proc_count == 0)
535 /* negative cache? */
536 if (pp->ki_udata == NOPROC)
539 if (pp->ki_udata != NULL)
540 return (pp->ki_udata);
543 * 1) look up based on pid.
544 * 2) compare process start.
545 * If we fail here, then setup a negative cache entry, otherwise
548 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
549 sizeof(*previous_pref), compare_pid);
551 pp->ki_udata = NOPROC;
555 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
556 pp->ki_udata = NOPROC;
564 * Return the total amount of IO done in blocks in/out and faults.
565 * store the values individually in the pointers passed in.
568 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp, long *vcsw, long *ivcsw)
570 const struct kinfo_proc *oldp;
571 static struct kinfo_proc dummy;
574 oldp = get_old_proc(pp);
576 bzero(&dummy, sizeof(dummy));
580 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
581 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
582 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
583 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
584 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
586 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
587 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
588 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
593 * Return the total number of block in/out and faults by a process.
596 get_io_total(struct kinfo_proc *pp)
600 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
603 static struct handle handle;
606 get_process_info(struct system_info *si, struct process_select *sel,
607 int (*compare)(const void *, const void *))
612 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
614 struct kinfo_proc **prefp;
615 struct kinfo_proc *pp;
616 struct kinfo_proc *prev_pp = NULL;
618 /* these are copied out of sel for speed */
626 * Save the previous process info.
628 if (previous_proc_count_max < nproc) {
629 free(previous_procs);
630 previous_procs = malloc(nproc * sizeof(*previous_procs));
632 previous_pref = malloc(nproc * sizeof(*previous_pref));
633 if (previous_procs == NULL || previous_pref == NULL) {
634 (void) fprintf(stderr, "top: Out of memory.\n");
637 previous_proc_count_max = nproc;
640 for (i = 0; i < nproc; i++)
641 previous_pref[i] = &previous_procs[i];
642 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
643 qsort(previous_pref, nproc, sizeof(*previous_pref), compare_pid);
645 previous_proc_count = nproc;
647 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
649 pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
650 if (pref == NULL || pbase == NULL) {
651 (void) fprintf(stderr, "top: Out of memory.\n");
654 /* get a pointer to the states summary array */
655 si->procstates = process_states;
657 /* set up flags which define what we are going to select */
658 show_idle = sel->idle;
659 show_self = sel->self == -1;
660 show_system = sel->system;
661 show_uid = sel->uid != -1;
662 show_command = sel->command != NULL;
664 /* count up process states and get pointers to interesting procs */
670 memset((char *)process_states, 0, sizeof(process_states));
672 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
674 if (pp->ki_stat == 0)
678 if (!show_self && pp->ki_pid == sel->self)
682 if (!show_system && (pp->ki_flag & P_SYSTEM))
683 /* skip system process */
686 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt, &p_vcsw, &p_ivcsw);
687 total_inblock += p_inblock;
688 total_oublock += p_oublock;
689 total_majflt += p_majflt;
691 process_states[pp->ki_stat]++;
693 if (pp->ki_stat == SZOMB)
697 if (displaymode == DISP_CPU && !show_idle &&
698 (pp->ki_pctcpu == 0 ||
699 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
700 /* skip idle or non-running processes */
703 if (displaymode == DISP_IO && !show_idle && p_io == 0)
704 /* skip processes that aren't doing I/O */
707 if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
708 /* skip processes which don't belong to the selected UID */
712 * When not showing threads, take the first thread
713 * for output and add the fields that we can from
714 * the rest of the process's threads rather than
715 * using the system's mostly-broken KERN_PROC_PROC.
717 if (sel->thread || prev_pp == NULL ||
718 prev_pp->ki_pid != pp->ki_pid) {
723 prev_pp->ki_pctcpu += pp->ki_pctcpu;
727 /* if requested, sort the "interesting" processes */
729 qsort(pref, active_procs, sizeof(*pref), compare);
731 /* remember active and total counts */
732 si->p_total = total_procs;
733 si->p_active = pref_len = active_procs;
735 /* pass back a handle */
736 handle.next_proc = pref;
737 handle.remaining = active_procs;
738 return ((caddr_t)&handle);
741 static char fmt[128]; /* static area where result is built */
744 format_next_process(caddr_t handle, char *(*get_userid)(int))
746 struct kinfo_proc *pp;
747 const struct kinfo_proc *oldp;
753 struct rusage ru, *rup;
755 char *proc_fmt, thr_buf[6], jid_buf[6];
757 /* find and remember the next proc structure */
758 hp = (struct handle *)handle;
759 pp = *(hp->next_proc++);
762 /* get the process's command name */
763 if ((pp->ki_sflag & PS_INMEM) == 0) {
765 * Print swapped processes as <pname>
767 size_t len = strlen(pp->ki_comm);
768 if (len > sizeof(pp->ki_comm) - 3)
769 len = sizeof(pp->ki_comm) - 3;
770 memmove(pp->ki_comm + 1, pp->ki_comm, len);
771 pp->ki_comm[0] = '<';
772 pp->ki_comm[len + 1] = '>';
773 pp->ki_comm[len + 2] = '\0';
777 * Convert the process's runtime from microseconds to seconds. This
778 * time includes the interrupt time although that is not wanted here.
779 * ps(1) is similarly sloppy.
781 cputime = (pp->ki_runtime + 500000) / 1000000;
783 /* calculate the base for cpu percentages */
784 pct = pctdouble(pp->ki_pctcpu);
786 /* generate "STATE" field */
787 switch (state = pp->ki_stat) {
789 if (smpmode && pp->ki_oncpu != 0xff)
790 sprintf(status, "CPU%d", pp->ki_oncpu);
792 strcpy(status, "RUN");
795 if (pp->ki_kiflag & KI_LOCKBLOCK) {
796 sprintf(status, "*%.6s", pp->ki_lockname);
801 if (pp->ki_wmesg != NULL) {
802 sprintf(status, "%.6s", pp->ki_wmesg);
809 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
810 sprintf(status, "%.6s", state_abbrev[state]);
812 sprintf(status, "?%5d", state);
819 snprintf(jid_buf, sizeof(jid_buf), " %*d",
820 sizeof(jid_buf) - 3, pp->ki_jid);
822 if (displaymode == DISP_IO) {
823 oldp = get_old_proc(pp);
825 ru.ru_inblock = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
826 ru.ru_oublock = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
827 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
828 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
829 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
834 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
835 s_tot = total_inblock + total_oublock + total_majflt;
837 sprintf(fmt, io_Proc_format,
840 namelength, namelength,
841 (*get_userid)(pp->ki_ruid),
848 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
849 screen_width > cmdlengthdelta ?
850 screen_width - cmdlengthdelta : 0,
851 printable(pp->ki_comm));
855 /* format this entry */
856 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
860 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
861 sizeof(thr_buf) - 2, pp->ki_numthreads);
863 sprintf(fmt, proc_fmt,
866 namelength, namelength,
867 (*get_userid)(pp->ki_ruid),
869 pp->ki_pri.pri_level - PZERO,
872 * normal time -> nice value -20 - +20
873 * real time 0 - 31 -> nice value -52 - -21
874 * idle time 0 - 31 -> nice value +21 - +52
876 (pp->ki_pri.pri_class == PRI_TIMESHARE ?
877 pp->ki_nice - NZERO :
878 (PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
879 (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
880 (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
881 format_k2(PROCSIZE(pp)),
882 format_k2(pagetok(pp->ki_rssize)),
884 smpmode ? pp->ki_lastcpu : 0,
885 format_time(cputime),
886 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
887 screen_width > cmdlengthdelta ?
888 screen_width - cmdlengthdelta :
890 printable(pp->ki_comm));
892 /* return the result */
897 getsysctl(char *name, void *ptr, size_t len)
901 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
902 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
907 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
908 (unsigned long)len, (unsigned long)nlen);
913 /* comparison routines for qsort */
916 compare_pid(const void *p1, const void *p2)
918 const struct kinfo_proc * const *pp1 = p1;
919 const struct kinfo_proc * const *pp2 = p2;
921 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
924 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
928 * proc_compare - comparison function for "qsort"
929 * Compares the resource consumption of two processes using five
930 * distinct keys. The keys (in descending order of importance) are:
931 * percent cpu, cpu ticks, state, resident set size, total virtual
932 * memory usage. The process states are ordered as follows (from least
933 * to most important): WAIT, zombie, sleep, stop, start, run. The
934 * array declaration below maps a process state index into a number
935 * that reflects this ordering.
938 static int sorted_state[] =
942 1, /* ABANDONED (WAIT) */
950 #define ORDERKEY_PCTCPU(a, b) do { \
953 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), (b))) - \
954 floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), (a))); \
956 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
958 return (diff > 0 ? 1 : -1); \
961 #define ORDERKEY_CPTICKS(a, b) do { \
962 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
964 return (diff > 0 ? 1 : -1); \
967 #define ORDERKEY_STATE(a, b) do { \
968 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
970 return (diff > 0 ? 1 : -1); \
973 #define ORDERKEY_PRIO(a, b) do { \
974 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
976 return (diff > 0 ? 1 : -1); \
979 #define ORDERKEY_THREADS(a, b) do { \
980 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
982 return (diff > 0 ? 1 : -1); \
985 #define ORDERKEY_RSSIZE(a, b) do { \
986 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
988 return (diff > 0 ? 1 : -1); \
991 #define ORDERKEY_MEM(a, b) do { \
992 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
994 return (diff > 0 ? 1 : -1); \
997 #define ORDERKEY_JID(a, b) do { \
998 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1000 return (diff > 0 ? 1 : -1); \
1003 /* compare_cpu - the comparison function for sorting by cpu percentage */
1007 compare_cpu(void *arg1, void *arg2)
1009 proc_compare(void *arg1, void *arg2)
1012 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1013 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1015 ORDERKEY_PCTCPU(p1, p2);
1016 ORDERKEY_CPTICKS(p1, p2);
1017 ORDERKEY_STATE(p1, p2);
1018 ORDERKEY_PRIO(p1, p2);
1019 ORDERKEY_RSSIZE(p1, p2);
1020 ORDERKEY_MEM(p1, p2);
1026 /* compare routines */
1027 int compare_size(), compare_res(), compare_time(), compare_prio(), compare_threads();
1028 /* io compare routines */
1029 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(), compare_vcsw(), compare_ivcsw();
1031 int (*compares[])() = {
1048 /* compare_size - the comparison function for sorting by total memory usage */
1051 compare_size(void *arg1, void *arg2)
1053 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1054 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1056 ORDERKEY_MEM(p1, p2);
1057 ORDERKEY_RSSIZE(p1, p2);
1058 ORDERKEY_PCTCPU(p1, p2);
1059 ORDERKEY_CPTICKS(p1, p2);
1060 ORDERKEY_STATE(p1, p2);
1061 ORDERKEY_PRIO(p1, p2);
1066 /* compare_res - the comparison function for sorting by resident set size */
1069 compare_res(void *arg1, void *arg2)
1071 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1072 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1074 ORDERKEY_RSSIZE(p1, p2);
1075 ORDERKEY_MEM(p1, p2);
1076 ORDERKEY_PCTCPU(p1, p2);
1077 ORDERKEY_CPTICKS(p1, p2);
1078 ORDERKEY_STATE(p1, p2);
1079 ORDERKEY_PRIO(p1, p2);
1084 /* compare_time - the comparison function for sorting by total cpu time */
1087 compare_time(void *arg1, void *arg2)
1089 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1090 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1092 ORDERKEY_CPTICKS(p1, p2);
1093 ORDERKEY_PCTCPU(p1, p2);
1094 ORDERKEY_STATE(p1, p2);
1095 ORDERKEY_PRIO(p1, p2);
1096 ORDERKEY_RSSIZE(p1, p2);
1097 ORDERKEY_MEM(p1, p2);
1102 /* compare_prio - the comparison function for sorting by priority */
1105 compare_prio(void *arg1, void *arg2)
1107 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1108 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1110 ORDERKEY_PRIO(p1, p2);
1111 ORDERKEY_CPTICKS(p1, p2);
1112 ORDERKEY_PCTCPU(p1, p2);
1113 ORDERKEY_STATE(p1, p2);
1114 ORDERKEY_RSSIZE(p1, p2);
1115 ORDERKEY_MEM(p1, p2);
1120 /* compare_threads - the comparison function for sorting by threads */
1122 compare_threads(void *arg1, void *arg2)
1124 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1125 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1127 ORDERKEY_THREADS(p1, p2);
1128 ORDERKEY_PCTCPU(p1, p2);
1129 ORDERKEY_CPTICKS(p1, p2);
1130 ORDERKEY_STATE(p1, p2);
1131 ORDERKEY_PRIO(p1, p2);
1132 ORDERKEY_RSSIZE(p1, p2);
1133 ORDERKEY_MEM(p1, p2);
1139 /* compare_jid - the comparison function for sorting by jid */
1142 compare_jid(const void *arg1, const void *arg2)
1144 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1145 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1147 ORDERKEY_JID(p1, p2);
1148 ORDERKEY_PCTCPU(p1, p2);
1149 ORDERKEY_CPTICKS(p1, p2);
1150 ORDERKEY_STATE(p1, p2);
1151 ORDERKEY_PRIO(p1, p2);
1152 ORDERKEY_RSSIZE(p1, p2);
1153 ORDERKEY_MEM(p1, p2);
1158 /* compare_io - the comparison function for sorting by total io */
1162 compare_iototal(void *arg1, void *arg2)
1164 io_compare(void *arg1, void *arg2)
1167 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1168 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1170 return (get_io_total(p2) - get_io_total(p1));
1176 compare_ioread(void *arg1, void *arg2)
1178 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1179 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1180 long dummy, inp1, inp2;
1182 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1183 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1185 return (inp2 - inp1);
1189 compare_iowrite(void *arg1, void *arg2)
1191 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1192 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1193 long dummy, oup1, oup2;
1195 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1196 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1198 return (oup2 - oup1);
1202 compare_iofault(void *arg1, void *arg2)
1204 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1205 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1206 long dummy, flp1, flp2;
1208 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1209 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1211 return (flp2 - flp1);
1215 compare_vcsw(void *arg1, void *arg2)
1217 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1218 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1219 long dummy, flp1, flp2;
1221 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1222 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1224 return (flp2 - flp1);
1228 compare_ivcsw(void *arg1, void *arg2)
1230 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1231 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1232 long dummy, flp1, flp2;
1234 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1235 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1237 return (flp2 - flp1);
1243 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1244 * the process does not exist.
1245 * It is EXTREMLY IMPORTANT that this function work correctly.
1246 * If top runs setuid root (as in SVR4), then this function
1247 * is the only thing that stands in the way of a serious
1248 * security problem. It validates requests for the "kill"
1249 * and "renice" commands.
1256 struct kinfo_proc **prefp;
1257 struct kinfo_proc *pp;
1261 while (--cnt >= 0) {
1263 if (pp->ki_pid == (pid_t)pid)
1264 return ((int)pp->ki_ruid);
1270 swapmode(int *retavail, int *retfree)
1273 int pagesize = getpagesize();
1274 struct kvm_swap swapary[1];
1279 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1281 n = kvm_getswapinfo(kd, swapary, 1, 0);
1282 if (n < 0 || swapary[0].ksw_total == 0)
1285 *retavail = CONVERT(swapary[0].ksw_total);
1286 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1288 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);