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>
54 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
55 #define SMPUNAMELEN 13
58 extern struct process_select ps;
59 extern char* printable(char *);
61 enum displaymodes displaymode;
62 static int namelength = 8;
63 static int cmdlengthdelta;
65 /* Prototypes for top internals */
68 /* get_process_info passes back a handle. This is what it looks like: */
71 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
72 int remaining; /* number of pointers remaining */
75 /* declarations for load_avg */
78 /* define what weighted cpu is. */
79 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
80 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
82 /* what we consider to be process size: */
83 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
85 #define RU(pp) (&(pp)->ki_rusage)
87 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
90 /* definitions for indices in the nlist array */
93 * These definitions control the format of the per-process area
96 static char io_header[] =
97 " PID %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
99 #define io_Proc_format \
100 "%5d %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
102 static char smp_header_thr[] =
103 " PID %-*.*s THR PRI NICE SIZE RES STATE C TIME %6s COMMAND";
104 static char smp_header[] =
105 " PID %-*.*s " "PRI NICE SIZE RES STATE C TIME %6s COMMAND";
107 #define smp_Proc_format \
108 "%5d %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
110 static char up_header_thr[] =
111 " PID %-*.*s THR PRI NICE SIZE RES STATE TIME %6s COMMAND";
112 static char up_header[] =
113 " PID %-*.*s " "PRI NICE SIZE RES STATE TIME %6s COMMAND";
115 #define up_Proc_format \
116 "%5d %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
119 /* process state names for the "STATE" column of the display */
120 /* the extra nulls in the string "run" are for adding a slash and
121 the processor number when needed */
123 char *state_abbrev[] = {
124 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
130 /* values that we stash away in _init and use in later routines */
132 static double logcpu;
134 /* these are retrieved from the kernel in _init */
136 static load_avg ccpu;
138 /* these are used in the get_ functions */
142 /* these are for calculating cpu state percentages */
144 static long cp_time[CPUSTATES];
145 static long cp_old[CPUSTATES];
146 static long cp_diff[CPUSTATES];
148 /* these are for detailing the process states */
150 int process_states[8];
151 char *procstatenames[] = {
152 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
153 " zombie, ", " waiting, ", " lock, ",
157 /* these are for detailing the cpu states */
159 int cpu_states[CPUSTATES];
160 char *cpustatenames[] = {
161 "user", "nice", "system", "interrupt", "idle", NULL
164 /* these are for detailing the memory statistics */
167 char *memorynames[] = {
168 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
173 char *swapnames[] = {
174 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
179 /* these are for keeping track of the proc array */
182 static int onproc = -1;
184 static struct kinfo_proc *pbase;
185 static struct kinfo_proc **pref;
186 static struct kinfo_proc *previous_procs;
187 static struct kinfo_proc **previous_pref;
188 static int previous_proc_count = 0;
189 static int previous_proc_count_max = 0;
191 /* total number of io operations */
192 static long total_inblock;
193 static long total_oublock;
194 static long total_majflt;
196 /* these are for getting the memory statistics */
198 static int pageshift; /* log base 2 of the pagesize */
200 /* define pagetok in terms of pageshift */
202 #define pagetok(size) ((size) << pageshift)
204 /* useful externals */
209 * Sorting orders. The first element is the default.
211 char *ordernames[] = {
212 "cpu", "size", "res", "time", "pri", "threads",
213 "total", "read", "write", "fault", "vcsw", "ivcsw", NULL
217 static int compare_pid(const void *a, const void *b);
218 static const char *format_nice(const struct kinfo_proc *pp);
219 static void getsysctl(const char *name, void *ptr, size_t len);
220 static int swapmode(int *retavail, int *retfree);
223 machine_init(struct statics *statics)
229 modelen = sizeof(smpmode);
230 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
232 sysctlbyname("kern.smp.active", &smpmode, &modelen,
234 modelen != sizeof(smpmode))
237 while ((pw = getpwent()) != NULL) {
238 if (strlen(pw->pw_name) > namelength)
239 namelength = strlen(pw->pw_name);
241 if (smpmode && namelength > SMPUNAMELEN)
242 namelength = SMPUNAMELEN;
243 else if (namelength > UPUNAMELEN)
244 namelength = UPUNAMELEN;
246 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
250 GETSYSCTL("kern.ccpu", ccpu);
252 /* this is used in calculating WCPU -- calculate it ahead of time */
253 logcpu = log(loaddouble(ccpu));
260 /* get the page size and calculate pageshift from it */
261 pagesize = getpagesize();
263 while (pagesize > 1) {
268 /* we only need the amount of log(2)1024 for our conversion */
269 pageshift -= LOG1024;
271 /* fill in the statics information */
272 statics->procstate_names = procstatenames;
273 statics->cpustate_names = cpustatenames;
274 statics->memory_names = memorynames;
275 statics->swap_names = swapnames;
277 statics->order_names = ordernames;
285 format_header(char *uname_field)
287 static char Header[128];
290 switch (displaymode) {
293 * The logic of picking the right header format seems reverse
294 * here because we only want to display a THR column when
295 * "thread mode" is off (and threads are not listed as
299 (ps.thread ? smp_header : smp_header_thr) :
300 (ps.thread ? up_header : up_header_thr);
301 snprintf(Header, sizeof(Header), prehead,
302 namelength, namelength, uname_field,
303 ps.wcpu ? "WCPU" : "CPU");
307 snprintf(Header, sizeof(Header), prehead,
308 namelength, namelength, uname_field);
311 cmdlengthdelta = strlen(Header) - 7;
315 static int swappgsin = -1;
316 static int swappgsout = -1;
317 extern struct timeval timeout;
320 get_system_info(struct system_info *si)
323 struct loadavg sysload;
325 struct timeval boottime;
329 /* get the cp_time array */
330 GETSYSCTL("kern.cp_time", cp_time);
331 GETSYSCTL("vm.loadavg", sysload);
332 GETSYSCTL("kern.lastpid", lastpid);
334 /* convert load averages to doubles */
335 for (i = 0; i < 3; i++)
336 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
338 /* convert cp_time counts to percentages */
339 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
341 /* sum memory & swap statistics */
343 static unsigned int swap_delay = 0;
344 static int swapavail = 0;
345 static int swapfree = 0;
346 static int bufspace = 0;
347 static int nspgsin, nspgsout;
349 GETSYSCTL("vfs.bufspace", bufspace);
350 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
351 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
352 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
353 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
354 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
355 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
356 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
357 /* convert memory stats to Kbytes */
358 memory_stats[0] = pagetok(memory_stats[0]);
359 memory_stats[1] = pagetok(memory_stats[1]);
360 memory_stats[2] = pagetok(memory_stats[2]);
361 memory_stats[3] = pagetok(memory_stats[3]);
362 memory_stats[4] = bufspace / 1024;
363 memory_stats[5] = pagetok(memory_stats[5]);
364 memory_stats[6] = -1;
372 /* compute differences between old and new swap statistic */
374 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
375 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
379 swappgsout = nspgsout;
381 /* call CPU heavy swapmode() only for changes */
382 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
383 swap_stats[3] = swapmode(&swapavail, &swapfree);
384 swap_stats[0] = swapavail;
385 swap_stats[1] = swapavail - swapfree;
386 swap_stats[2] = swapfree;
392 /* set arrays and strings */
393 si->cpustates = cpu_states;
394 si->memory = memory_stats;
395 si->swap = swap_stats;
399 si->last_pid = lastpid;
405 * Print how long system has been up.
406 * (Found by looking getting "boottime" from the kernel)
409 mib[1] = KERN_BOOTTIME;
410 bt_size = sizeof(boottime);
411 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
412 boottime.tv_sec != 0) {
413 si->boottime = boottime;
415 si->boottime.tv_sec = -1;
419 #define NOPROC ((void *)-1)
422 * We need to compare data from the old process entry with the new
424 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
425 * structure to cache the mapping. We also use a negative cache pointer
426 * of NOPROC to avoid duplicate lookups.
427 * XXX: this could be done when the actual processes are fetched, we do
428 * it here out of laziness.
430 const struct kinfo_proc *
431 get_old_proc(struct kinfo_proc *pp)
433 struct kinfo_proc **oldpp, *oldp;
436 * If this is the first fetch of the kinfo_procs then we don't have
437 * any previous entries.
439 if (previous_proc_count == 0)
441 /* negative cache? */
442 if (pp->ki_udata == NOPROC)
445 if (pp->ki_udata != NULL)
446 return (pp->ki_udata);
449 * 1) look up based on pid.
450 * 2) compare process start.
451 * If we fail here, then setup a negative cache entry, otherwise
454 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
455 sizeof(*previous_pref), compare_pid);
457 pp->ki_udata = NOPROC;
461 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
462 pp->ki_udata = NOPROC;
470 * Return the total amount of IO done in blocks in/out and faults.
471 * store the values individually in the pointers passed in.
474 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
475 long *vcsw, long *ivcsw)
477 const struct kinfo_proc *oldp;
478 static struct kinfo_proc dummy;
481 oldp = get_old_proc(pp);
483 bzero(&dummy, sizeof(dummy));
486 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
487 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
488 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
489 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
490 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
492 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
493 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
494 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
499 * Return the total number of block in/out and faults by a process.
502 get_io_total(struct kinfo_proc *pp)
506 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
509 static struct handle handle;
512 get_process_info(struct system_info *si, struct process_select *sel,
513 int (*compare)(const void *, const void *))
518 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
520 struct kinfo_proc **prefp;
521 struct kinfo_proc *pp;
522 struct kinfo_proc *prev_pp = NULL;
524 /* these are copied out of sel for speed */
532 * Save the previous process info.
534 if (previous_proc_count_max < nproc) {
535 free(previous_procs);
536 previous_procs = malloc(nproc * sizeof(*previous_procs));
538 previous_pref = malloc(nproc * sizeof(*previous_pref));
539 if (previous_procs == NULL || previous_pref == NULL) {
540 (void) fprintf(stderr, "top: Out of memory.\n");
543 previous_proc_count_max = nproc;
546 for (i = 0; i < nproc; i++)
547 previous_pref[i] = &previous_procs[i];
548 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
549 qsort(previous_pref, nproc, sizeof(*previous_pref),
552 previous_proc_count = nproc;
554 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
556 pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
557 if (pref == NULL || pbase == NULL) {
558 (void) fprintf(stderr, "top: Out of memory.\n");
561 /* get a pointer to the states summary array */
562 si->procstates = process_states;
564 /* set up flags which define what we are going to select */
565 show_idle = sel->idle;
566 show_self = sel->self == -1;
567 show_system = sel->system;
568 show_uid = sel->uid != -1;
569 show_command = sel->command != NULL;
571 /* count up process states and get pointers to interesting procs */
577 memset((char *)process_states, 0, sizeof(process_states));
579 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
581 if (pp->ki_stat == 0)
585 if (!show_self && pp->ki_pid == sel->self)
589 if (!show_system && (pp->ki_flag & P_SYSTEM))
590 /* skip system process */
593 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
595 total_inblock += p_inblock;
596 total_oublock += p_oublock;
597 total_majflt += p_majflt;
599 process_states[pp->ki_stat]++;
601 if (pp->ki_stat == SZOMB)
605 if (displaymode == DISP_CPU && !show_idle &&
606 (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN))
607 /* skip idle or non-running processes */
610 if (displaymode == DISP_IO && !show_idle && p_io == 0)
611 /* skip processes that aren't doing I/O */
614 if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
615 /* skip proc. that don't belong to the selected UID */
619 * When not showing threads, take the first thread
620 * for output and add the fields that we can from
621 * the rest of the process's threads rather than
622 * using the system's mostly-broken KERN_PROC_PROC.
624 if (sel->thread || prev_pp == NULL ||
625 prev_pp->ki_pid != pp->ki_pid) {
630 prev_pp->ki_pctcpu += pp->ki_pctcpu;
634 /* if requested, sort the "interesting" processes */
636 qsort(pref, active_procs, sizeof(*pref), compare);
638 /* remember active and total counts */
639 si->p_total = total_procs;
640 si->p_active = pref_len = active_procs;
642 /* pass back a handle */
643 handle.next_proc = pref;
644 handle.remaining = active_procs;
645 return ((caddr_t)&handle);
648 static char fmt[128]; /* static area where result is built */
651 format_next_process(caddr_t handle, char *(*get_userid)(int))
653 struct kinfo_proc *pp;
654 const struct kinfo_proc *oldp;
660 struct rusage ru, *rup;
662 char *proc_fmt, thr_buf[6];
664 /* find and remember the next proc structure */
665 hp = (struct handle *)handle;
666 pp = *(hp->next_proc++);
669 /* get the process's command name */
670 if ((pp->ki_sflag & PS_INMEM) == 0) {
672 * Print swapped processes as <pname>
676 len = strlen(pp->ki_comm);
677 if (len > sizeof(pp->ki_comm) - 3)
678 len = sizeof(pp->ki_comm) - 3;
679 memmove(pp->ki_comm + 1, pp->ki_comm, len);
680 pp->ki_comm[0] = '<';
681 pp->ki_comm[len + 1] = '>';
682 pp->ki_comm[len + 2] = '\0';
686 * Convert the process's runtime from microseconds to seconds. This
687 * time includes the interrupt time although that is not wanted here.
688 * ps(1) is similarly sloppy.
690 cputime = (pp->ki_runtime + 500000) / 1000000;
692 /* calculate the base for cpu percentages */
693 pct = pctdouble(pp->ki_pctcpu);
695 /* generate "STATE" field */
696 switch (state = pp->ki_stat) {
698 if (smpmode && pp->ki_oncpu != 0xff)
699 sprintf(status, "CPU%d", pp->ki_oncpu);
701 strcpy(status, "RUN");
704 if (pp->ki_kiflag & KI_LOCKBLOCK) {
705 sprintf(status, "*%.6s", pp->ki_lockname);
710 if (pp->ki_wmesg != NULL) {
711 sprintf(status, "%.6s", pp->ki_wmesg);
718 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
719 sprintf(status, "%.6s", state_abbrev[state]);
721 sprintf(status, "?%5d", state);
725 if (displaymode == DISP_IO) {
726 oldp = get_old_proc(pp);
728 ru.ru_inblock = RU(pp)->ru_inblock -
729 RU(oldp)->ru_inblock;
730 ru.ru_oublock = RU(pp)->ru_oublock -
731 RU(oldp)->ru_oublock;
732 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
733 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
734 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
739 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
740 s_tot = total_inblock + total_oublock + total_majflt;
742 sprintf(fmt, io_Proc_format,
744 namelength, namelength, (*get_userid)(pp->ki_ruid),
751 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
752 screen_width > cmdlengthdelta ?
753 screen_width - cmdlengthdelta : 0,
754 printable(pp->ki_comm));
758 /* format this entry */
759 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
763 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
764 sizeof(thr_buf) - 2, pp->ki_numthreads);
766 sprintf(fmt, proc_fmt,
768 namelength, namelength, (*get_userid)(pp->ki_ruid),
770 pp->ki_pri.pri_level - PZERO,
772 format_k2(PROCSIZE(pp)),
773 format_k2(pagetok(pp->ki_rssize)),
775 smpmode ? pp->ki_lastcpu : 0,
776 format_time(cputime),
777 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
778 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
779 printable(pp->ki_comm));
781 /* return the result */
786 getsysctl(const char *name, void *ptr, size_t len)
790 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
791 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
796 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
797 name, (unsigned long)len, (unsigned long)nlen);
803 const char *format_nice(const struct kinfo_proc *pp)
805 static char nicebuf[5];
807 snprintf(nicebuf, sizeof(nicebuf), "%4d",
809 * normal time -> nice value -20 - +20
810 * real time 0 - 31 -> nice value -52 - -21
811 * idle time 0 - 31 -> nice value +21 - +52
813 (pp->ki_pri.pri_class == PRI_TIMESHARE ?
814 pp->ki_nice - NZERO :
815 (PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
816 (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
817 (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))));
821 /* comparison routines for qsort */
824 compare_pid(const void *p1, const void *p2)
826 const struct kinfo_proc * const *pp1 = p1;
827 const struct kinfo_proc * const *pp2 = p2;
829 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
832 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
836 * proc_compare - comparison function for "qsort"
837 * Compares the resource consumption of two processes using five
838 * distinct keys. The keys (in descending order of importance) are:
839 * percent cpu, cpu ticks, state, resident set size, total virtual
840 * memory usage. The process states are ordered as follows (from least
841 * to most important): WAIT, zombie, sleep, stop, start, run. The
842 * array declaration below maps a process state index into a number
843 * that reflects this ordering.
846 static int sorted_state[] = {
849 1, /* ABANDONED (WAIT) */
857 #define ORDERKEY_PCTCPU(a, b) do { \
860 diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
862 floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
865 diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
867 return (diff > 0 ? 1 : -1); \
870 #define ORDERKEY_CPTICKS(a, b) do { \
871 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
873 return (diff > 0 ? 1 : -1); \
876 #define ORDERKEY_STATE(a, b) do { \
877 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
879 return (diff > 0 ? 1 : -1); \
882 #define ORDERKEY_PRIO(a, b) do { \
883 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
885 return (diff > 0 ? 1 : -1); \
888 #define ORDERKEY_THREADS(a, b) do { \
889 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
891 return (diff > 0 ? 1 : -1); \
894 #define ORDERKEY_RSSIZE(a, b) do { \
895 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
897 return (diff > 0 ? 1 : -1); \
900 #define ORDERKEY_MEM(a, b) do { \
901 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
903 return (diff > 0 ? 1 : -1); \
906 /* compare_cpu - the comparison function for sorting by cpu percentage */
910 compare_cpu(void *arg1, void *arg2)
912 proc_compare(void *arg1, void *arg2)
915 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
916 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
918 ORDERKEY_PCTCPU(p1, p2);
919 ORDERKEY_CPTICKS(p1, p2);
920 ORDERKEY_STATE(p1, p2);
921 ORDERKEY_PRIO(p1, p2);
922 ORDERKEY_RSSIZE(p1, p2);
923 ORDERKEY_MEM(p1, p2);
929 /* "cpu" compare routines */
930 int compare_size(), compare_res(), compare_time(), compare_prio(),
934 * "io" compare routines. Context switches aren't i/o, but are displayed
935 * on the "io" display.
937 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
938 compare_vcsw(), compare_ivcsw();
940 int (*compares[])() = {
956 /* compare_size - the comparison function for sorting by total memory usage */
959 compare_size(void *arg1, void *arg2)
961 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
962 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
964 ORDERKEY_MEM(p1, p2);
965 ORDERKEY_RSSIZE(p1, p2);
966 ORDERKEY_PCTCPU(p1, p2);
967 ORDERKEY_CPTICKS(p1, p2);
968 ORDERKEY_STATE(p1, p2);
969 ORDERKEY_PRIO(p1, p2);
974 /* compare_res - the comparison function for sorting by resident set size */
977 compare_res(void *arg1, void *arg2)
979 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
980 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
982 ORDERKEY_RSSIZE(p1, p2);
983 ORDERKEY_MEM(p1, p2);
984 ORDERKEY_PCTCPU(p1, p2);
985 ORDERKEY_CPTICKS(p1, p2);
986 ORDERKEY_STATE(p1, p2);
987 ORDERKEY_PRIO(p1, p2);
992 /* compare_time - the comparison function for sorting by total cpu time */
995 compare_time(void *arg1, void *arg2)
997 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
998 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1000 ORDERKEY_CPTICKS(p1, p2);
1001 ORDERKEY_PCTCPU(p1, p2);
1002 ORDERKEY_STATE(p1, p2);
1003 ORDERKEY_PRIO(p1, p2);
1004 ORDERKEY_RSSIZE(p1, p2);
1005 ORDERKEY_MEM(p1, p2);
1010 /* compare_prio - the comparison function for sorting by priority */
1013 compare_prio(void *arg1, void *arg2)
1015 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1016 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1018 ORDERKEY_PRIO(p1, p2);
1019 ORDERKEY_CPTICKS(p1, p2);
1020 ORDERKEY_PCTCPU(p1, p2);
1021 ORDERKEY_STATE(p1, p2);
1022 ORDERKEY_RSSIZE(p1, p2);
1023 ORDERKEY_MEM(p1, p2);
1028 /* compare_threads - the comparison function for sorting by threads */
1030 compare_threads(void *arg1, void *arg2)
1032 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1033 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1035 ORDERKEY_THREADS(p1, p2);
1036 ORDERKEY_PCTCPU(p1, p2);
1037 ORDERKEY_CPTICKS(p1, p2);
1038 ORDERKEY_STATE(p1, p2);
1039 ORDERKEY_PRIO(p1, p2);
1040 ORDERKEY_RSSIZE(p1, p2);
1041 ORDERKEY_MEM(p1, p2);
1047 /* assorted comparison functions for sorting by i/o */
1051 compare_iototal(void *arg1, void *arg2)
1053 io_compare(void *arg1, void *arg2)
1056 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1057 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1059 return (get_io_total(p2) - get_io_total(p1));
1064 compare_ioread(void *arg1, void *arg2)
1066 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1067 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1068 long dummy, inp1, inp2;
1070 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1071 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1073 return (inp2 - inp1);
1077 compare_iowrite(void *arg1, void *arg2)
1079 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1080 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1081 long dummy, oup1, oup2;
1083 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1084 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1086 return (oup2 - oup1);
1090 compare_iofault(void *arg1, void *arg2)
1092 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1093 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1094 long dummy, flp1, flp2;
1096 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1097 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1099 return (flp2 - flp1);
1103 compare_vcsw(void *arg1, void *arg2)
1105 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1106 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1107 long dummy, flp1, flp2;
1109 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1110 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1112 return (flp2 - flp1);
1116 compare_ivcsw(void *arg1, void *arg2)
1118 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1119 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1120 long dummy, flp1, flp2;
1122 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1123 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1125 return (flp2 - flp1);
1130 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1131 * the process does not exist.
1132 * It is EXTREMLY IMPORTANT that this function work correctly.
1133 * If top runs setuid root (as in SVR4), then this function
1134 * is the only thing that stands in the way of a serious
1135 * security problem. It validates requests for the "kill"
1136 * and "renice" commands.
1143 struct kinfo_proc **prefp;
1144 struct kinfo_proc *pp;
1148 while (--cnt >= 0) {
1150 if (pp->ki_pid == (pid_t)pid)
1151 return ((int)pp->ki_ruid);
1157 swapmode(int *retavail, int *retfree)
1160 int pagesize = getpagesize();
1161 struct kvm_swap swapary[1];
1166 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1168 n = kvm_getswapinfo(kd, swapary, 1, 0);
1169 if (n < 0 || swapary[0].ksw_total == 0)
1172 *retavail = CONVERT(swapary[0].ksw_total);
1173 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1175 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);