]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/top/machine.c
top(1): use a different command to toggle tid vs pid
[FreeBSD/FreeBSD.git] / usr.bin / top / machine.c
1 /*
2  * top - a top users display for Unix
3  *
4  * DESCRIPTION:
5  * Originally written for BSD4.4 system by Christos Zoulas.
6  * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
7  * Order support hacked in from top-3.5beta6/machine/m_aix41.c
8  *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
9  *
10  * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
11  *          Steven Wallace  <swallace@FreeBSD.org>
12  *          Wolfram Schneider <wosch@FreeBSD.org>
13  *          Thomas Moestl <tmoestl@gmx.net>
14  *          Eitan Adler <eadler@FreeBSD.org>
15  *
16  * $FreeBSD$
17  */
18
19 #include <sys/errno.h>
20 #include <sys/fcntl.h>
21 #include <sys/param.h>
22 #include <sys/priority.h>
23 #include <sys/proc.h>
24 #include <sys/resource.h>
25 #include <sys/sysctl.h>
26 #include <sys/time.h>
27 #include <sys/user.h>
28
29 #include <assert.h>
30 #include <err.h>
31 #include <kvm.h>
32 #include <math.h>
33 #include <paths.h>
34 #include <stdio.h>
35 #include <stdbool.h>
36 #include <stdint.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <time.h>
40 #include <unistd.h>
41 #include <vis.h>
42
43 #include "top.h"
44 #include "display.h"
45 #include "machine.h"
46 #include "loadavg.h"
47 #include "screen.h"
48 #include "utils.h"
49 #include "layout.h"
50
51 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
52 #define SMPUNAMELEN     13
53 #define UPUNAMELEN      15
54
55 extern struct timeval timeout;
56 static int smpmode;
57 enum displaymodes displaymode;
58 static int namelength = 8;
59 /* TOP_JID_LEN based on max of 999999 */
60 #define TOP_JID_LEN 7
61 #define TOP_SWAP_LEN 6
62 static int jidlength;
63 static int swaplength;
64 static int cmdlengthdelta;
65
66 /* get_process_info passes back a handle.  This is what it looks like: */
67
68 struct handle {
69         struct kinfo_proc **next_proc;  /* points to next valid proc pointer */
70         int remaining;                  /* number of pointers remaining */
71 };
72
73
74 /* define what weighted cpu is.  */
75 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
76                          ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
77
78 /* what we consider to be process size: */
79 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
80
81 #define RU(pp)  (&(pp)->ki_rusage)
82 #define RUTOT(pp) \
83         (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
84
85 #define PCTCPU(pp) (pcpu[pp - pbase])
86
87 /*
88  *  These definitions control the format of the per-process area
89  */
90
91 static const char io_header[] =
92     "  PID%*s %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
93
94 static const char io_Proc_format[] =
95     "%5d%*s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s";
96
97 static const char smp_header_thr_and_pid[] =
98     "  PID%*s %-*.*s  THR PRI NICE   SIZE    RES%*s STATE   C   TIME %7s COMMAND";
99 static const char smp_header_tid_only[] =
100     "  THR%*s %-*.*s "   "PRI NICE   SIZE    RES%*s STATE   C   TIME %7s COMMAND";
101
102 static const char smp_Proc_format[] =
103     "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s %2d%7s %6.2f%% %.*s";
104
105 static char up_header_thr_and_pid[] =
106     "  PID%*s %-*.*s  THR PRI NICE   SIZE    RES%*s STATE    TIME %7s COMMAND";
107 static char up_header_tid_only[] =
108     "  THR%*s %-*.*s "   "PRI NICE   SIZE    RES%*s STATE    TIME %7s COMMAND";
109
110 static char up_Proc_format[] =
111     "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s%.0d%7s %6.2f%% %.*s";
112
113
114 /* process state names for the "STATE" column of the display */
115 /* the extra nulls in the string "run" are for adding a slash and
116    the processor number when needed */
117
118 static const char *state_abbrev[] = {
119         "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
120 };
121
122
123 static kvm_t *kd;
124
125 /* values that we stash away in _init and use in later routines */
126
127 static double logcpu;
128
129 /* these are retrieved from the kernel in _init */
130
131 static load_avg  ccpu;
132
133 /* these are used in the get_ functions */
134
135 static int lastpid;
136
137 /* these are for calculating cpu state percentages */
138
139 static long cp_time[CPUSTATES];
140 static long cp_old[CPUSTATES];
141 static long cp_diff[CPUSTATES];
142
143 /* these are for detailing the process states */
144
145 static const char *procstatenames[] = {
146         "", " starting, ", " running, ", " sleeping, ", " stopped, ",
147         " zombie, ", " waiting, ", " lock, ",
148         NULL
149 };
150 static int process_states[nitems(procstatenames)];
151
152 /* these are for detailing the cpu states */
153
154 static int cpu_states[CPUSTATES];
155 static const char *cpustatenames[] = {
156         "user", "nice", "system", "interrupt", "idle", NULL
157 };
158
159 /* these are for detailing the memory statistics */
160
161 static const char *memorynames[] = {
162         "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
163         "K Free", NULL
164 };
165 static int memory_stats[nitems(memorynames)];
166
167 static const char *arcnames[] = {
168         "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
169         NULL
170 };
171 static int arc_stats[nitems(arcnames)];
172
173 static const char *carcnames[] = {
174         "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
175         NULL
176 };
177 static int carc_stats[nitems(carcnames)];
178
179 static const char *swapnames[] = {
180         "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
181         NULL
182 };
183 static int swap_stats[nitems(swapnames)];
184
185
186 /* these are for keeping track of the proc array */
187
188 static int nproc;
189 static int onproc = -1;
190 static int pref_len;
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;
197 static int previous_thread;
198
199 /* data used for recalculating pctcpu */
200 static double *pcpu;
201 static struct timespec proc_uptime;
202 static struct timeval proc_wall_time;
203 static struct timeval previous_wall_time;
204 static uint64_t previous_interval = 0;
205
206 /* total number of io operations */
207 static long total_inblock;
208 static long total_oublock;
209 static long total_majflt;
210
211 /* these are for getting the memory statistics */
212
213 static int arc_enabled;
214 static int carc_enabled;
215 static int pageshift;           /* log base 2 of the pagesize */
216
217 /* define pagetok in terms of pageshift */
218
219 #define pagetok(size) ((size) << pageshift)
220
221 /* swap usage */
222 #define ki_swap(kip) \
223     ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
224
225 /*
226  * Sorting orders.  The first element is the default.
227  */
228 static const char *ordernames[] = {
229         "cpu", "size", "res", "time", "pri", "threads",
230         "total", "read", "write", "fault", "vcsw", "ivcsw",
231         "jid", "swap", "pid", NULL
232 };
233
234 /* Per-cpu time states */
235 static int maxcpu;
236 static int maxid;
237 static int ncpus;
238 static unsigned long cpumask;
239 static long *times;
240 static long *pcpu_cp_time;
241 static long *pcpu_cp_old;
242 static long *pcpu_cp_diff;
243 static int *pcpu_cpu_states;
244
245 static int compare_swap(const void *a, const void *b);
246 static int compare_jid(const void *a, const void *b);
247 static int compare_pid(const void *a, const void *b);
248 static int compare_tid(const void *a, const void *b);
249 static const char *format_nice(const struct kinfo_proc *pp);
250 static void getsysctl(const char *name, void *ptr, size_t len);
251 static int swapmode(int *retavail, int *retfree);
252 static void update_layout(void);
253 static int find_uid(uid_t needle, int *haystack);
254
255 static int
256 find_uid(uid_t needle, int *haystack)
257 {
258         size_t i = 0;
259
260         for (; i < TOP_MAX_UIDS; ++i)
261                 if ((uid_t)haystack[i] == needle)
262                         return 1;
263         return (0);
264 }
265
266 void
267 toggle_pcpustats(void)
268 {
269
270         if (ncpus == 1)
271                 return;
272         update_layout();
273 }
274
275 /* Adjust display based on ncpus and the ARC state. */
276 static void
277 update_layout(void)
278 {
279
280         y_mem = 3;
281         y_arc = 4;
282         y_carc = 5;
283         y_swap = 4 + arc_enabled + carc_enabled;
284         y_idlecursor = 5 + arc_enabled + carc_enabled;
285         y_message = 5 + arc_enabled + carc_enabled;
286         y_header = 6 + arc_enabled + carc_enabled;
287         y_procs = 7 + arc_enabled + carc_enabled;
288         Header_lines = 7 + arc_enabled + carc_enabled;
289
290         if (pcpu_stats) {
291                 y_mem += ncpus - 1;
292                 y_arc += ncpus - 1;
293                 y_carc += ncpus - 1;
294                 y_swap += ncpus - 1;
295                 y_idlecursor += ncpus - 1;
296                 y_message += ncpus - 1;
297                 y_header += ncpus - 1;
298                 y_procs += ncpus - 1;
299                 Header_lines += ncpus - 1;
300         }
301 }
302
303 int
304 machine_init(struct statics *statics)
305 {
306         int i, j, empty, pagesize;
307         uint64_t arc_size;
308         bool carc_en;
309         size_t size;
310
311         size = sizeof(smpmode);
312         if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
313             NULL, 0) != 0 &&
314             sysctlbyname("kern.smp.active", &smpmode, &size,
315             NULL, 0) != 0) ||
316             size != sizeof(smpmode))
317                 smpmode = 0;
318
319         size = sizeof(arc_size);
320         if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
321             NULL, 0) == 0 && arc_size != 0)
322                 arc_enabled = 1;
323         size = sizeof(carc_en);
324         if (arc_enabled &&
325             sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
326             NULL, 0) == 0 && carc_en == 1)
327                 carc_enabled = 1;
328
329         namelength = MAXLOGNAME;
330         if (smpmode && namelength > SMPUNAMELEN)
331                 namelength = SMPUNAMELEN;
332         else if (namelength > UPUNAMELEN)
333                 namelength = UPUNAMELEN;
334
335         kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
336         if (kd == NULL)
337                 return (-1);
338
339         GETSYSCTL("kern.ccpu", ccpu);
340
341         /* this is used in calculating WCPU -- calculate it ahead of time */
342         logcpu = log(loaddouble(ccpu));
343
344         pbase = NULL;
345         pref = NULL;
346         pcpu = NULL;
347         nproc = 0;
348         onproc = -1;
349
350         /* get the page size and calculate pageshift from it */
351         pagesize = getpagesize();
352         pageshift = 0;
353         while (pagesize > 1) {
354                 pageshift++;
355                 pagesize >>= 1;
356         }
357
358         /* we only need the amount of log(2)1024 for our conversion */
359         pageshift -= LOG1024;
360
361         /* fill in the statics information */
362         statics->procstate_names = procstatenames;
363         statics->cpustate_names = cpustatenames;
364         statics->memory_names = memorynames;
365         if (arc_enabled)
366                 statics->arc_names = arcnames;
367         else
368                 statics->arc_names = NULL;
369         if (carc_enabled)
370                 statics->carc_names = carcnames;
371         else
372                 statics->carc_names = NULL;
373         statics->swap_names = swapnames;
374         statics->order_names = ordernames;
375
376         /* Allocate state for per-CPU stats. */
377         cpumask = 0;
378         ncpus = 0;
379         GETSYSCTL("kern.smp.maxcpus", maxcpu);
380         times = calloc(maxcpu * CPUSTATES, sizeof(long));
381         if (times == NULL)
382                 err(1, "calloc for kern.smp.maxcpus");
383         size = sizeof(long) * maxcpu * CPUSTATES;
384         if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
385                 err(1, "sysctlbyname kern.cp_times");
386         pcpu_cp_time = calloc(1, size);
387         maxid = (size / CPUSTATES / sizeof(long)) - 1;
388         for (i = 0; i <= maxid; i++) {
389                 empty = 1;
390                 for (j = 0; empty && j < CPUSTATES; j++) {
391                         if (times[i * CPUSTATES + j] != 0)
392                                 empty = 0;
393                 }
394                 if (!empty) {
395                         cpumask |= (1ul << i);
396                         ncpus++;
397                 }
398         }
399         assert(ncpus > 0);
400         pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
401         pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
402         pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
403         statics->ncpus = ncpus;
404
405         update_layout();
406
407         /* all done! */
408         return (0);
409 }
410
411 const char *
412 format_header(const char *uname_field)
413 {
414         static char Header[128];
415         const char *prehead;
416
417         if (ps.jail)
418                 jidlength = TOP_JID_LEN + 1;    /* +1 for extra left space. */
419         else
420                 jidlength = 0;
421
422         if (ps.swap)
423                 swaplength = TOP_SWAP_LEN + 1;  /* +1 for extra left space */
424         else
425                 swaplength = 0;
426
427         switch (displaymode) {
428         case DISP_CPU:
429                 /*
430                  * The logic of picking the right header format seems reverse
431                  * here because we only want to display a THR column when
432                  * "thread mode" is off (and threads are not listed as
433                  * separate lines).
434                  */
435                 prehead = smpmode ?
436                     (ps.thread_id ? smp_header_tid_only : smp_header_thr_and_pid) :
437                     (ps.thread_id ? up_header_tid_only : up_header_thr_and_pid);
438                 snprintf(Header, sizeof(Header), prehead,
439                     jidlength, ps.jail ? " JID" : "",
440                     namelength, namelength, uname_field,
441                     swaplength, ps.swap ? " SWAP" : "",
442                     ps.wcpu ? "WCPU" : "CPU");
443                 break;
444         case DISP_IO:
445                 prehead = io_header;
446                 snprintf(Header, sizeof(Header), prehead,
447                     jidlength, ps.jail ? " JID" : "",
448                     namelength, namelength, uname_field);
449                 break;
450         case DISP_MAX:
451                 assert("displaymode must not be set to DISP_MAX");
452         }
453         cmdlengthdelta = strlen(Header) - 7;
454         return (Header);
455 }
456
457 static int swappgsin = -1;
458 static int swappgsout = -1;
459
460
461 void
462 get_system_info(struct system_info *si)
463 {
464         struct loadavg sysload;
465         int mib[2];
466         struct timeval boottime;
467         uint64_t arc_stat, arc_stat2;
468         int i, j;
469         size_t size;
470
471         /* get the CPU stats */
472         size = (maxid + 1) * CPUSTATES * sizeof(long);
473         if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
474                 err(1, "sysctlbyname kern.cp_times");
475         GETSYSCTL("kern.cp_time", cp_time);
476         GETSYSCTL("vm.loadavg", sysload);
477         GETSYSCTL("kern.lastpid", lastpid);
478
479         /* convert load averages to doubles */
480         for (i = 0; i < 3; i++)
481                 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
482
483         /* convert cp_time counts to percentages */
484         for (i = j = 0; i <= maxid; i++) {
485                 if ((cpumask & (1ul << i)) == 0)
486                         continue;
487                 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
488                     &pcpu_cp_time[j * CPUSTATES],
489                     &pcpu_cp_old[j * CPUSTATES],
490                     &pcpu_cp_diff[j * CPUSTATES]);
491                 j++;
492         }
493         percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
494
495         /* sum memory & swap statistics */
496         {
497                 static unsigned int swap_delay = 0;
498                 static int swapavail = 0;
499                 static int swapfree = 0;
500                 static long bufspace = 0;
501                 static uint64_t nspgsin, nspgsout;
502
503                 GETSYSCTL("vfs.bufspace", bufspace);
504                 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
505                 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
506                 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
507                 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
508                 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
509                 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
510                 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
511                 /* convert memory stats to Kbytes */
512                 memory_stats[0] = pagetok(memory_stats[0]);
513                 memory_stats[1] = pagetok(memory_stats[1]);
514                 memory_stats[2] = pagetok(memory_stats[2]);
515                 memory_stats[3] = pagetok(memory_stats[3]);
516                 memory_stats[4] = bufspace / 1024;
517                 memory_stats[5] = pagetok(memory_stats[5]);
518                 memory_stats[6] = -1;
519
520                 /* first interval */
521                 if (swappgsin < 0) {
522                         swap_stats[4] = 0;
523                         swap_stats[5] = 0;
524                 }
525
526                 /* compute differences between old and new swap statistic */
527                 else {
528                         swap_stats[4] = pagetok(((nspgsin - swappgsin)));
529                         swap_stats[5] = pagetok(((nspgsout - swappgsout)));
530                 }
531
532                 swappgsin = nspgsin;
533                 swappgsout = nspgsout;
534
535                 /* call CPU heavy swapmode() only for changes */
536                 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
537                         swap_stats[3] = swapmode(&swapavail, &swapfree);
538                         swap_stats[0] = swapavail;
539                         swap_stats[1] = swapavail - swapfree;
540                         swap_stats[2] = swapfree;
541                 }
542                 swap_delay = 1;
543                 swap_stats[6] = -1;
544         }
545
546         if (arc_enabled) {
547                 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
548                 arc_stats[0] = arc_stat >> 10;
549                 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
550                 arc_stats[1] = arc_stat >> 10;
551                 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
552                 arc_stats[2] = arc_stat >> 10;
553                 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
554                 arc_stats[3] = arc_stat >> 10;
555                 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
556                 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
557                 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
558                 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
559                 arc_stats[5] = arc_stat >> 10;
560                 si->arc = arc_stats;
561         }
562         if (carc_enabled) {
563                 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
564                 carc_stats[0] = arc_stat >> 10;
565                 carc_stats[2] = arc_stat >> 10; /* For ratio */
566                 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
567                 carc_stats[1] = arc_stat >> 10;
568                 si->carc = carc_stats;
569         }
570
571         /* set arrays and strings */
572         if (pcpu_stats) {
573                 si->cpustates = pcpu_cpu_states;
574                 si->ncpus = ncpus;
575         } else {
576                 si->cpustates = cpu_states;
577                 si->ncpus = 1;
578         }
579         si->memory = memory_stats;
580         si->swap = swap_stats;
581
582
583         if (lastpid > 0) {
584                 si->last_pid = lastpid;
585         } else {
586                 si->last_pid = -1;
587         }
588
589         /*
590          * Print how long system has been up.
591          * (Found by looking getting "boottime" from the kernel)
592          */
593         mib[0] = CTL_KERN;
594         mib[1] = KERN_BOOTTIME;
595         size = sizeof(boottime);
596         if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
597             boottime.tv_sec != 0) {
598                 si->boottime = boottime;
599         } else {
600                 si->boottime.tv_sec = -1;
601         }
602 }
603
604 #define NOPROC  ((void *)-1)
605
606 /*
607  * We need to compare data from the old process entry with the new
608  * process entry.
609  * To facilitate doing this quickly we stash a pointer in the kinfo_proc
610  * structure to cache the mapping.  We also use a negative cache pointer
611  * of NOPROC to avoid duplicate lookups.
612  * XXX: this could be done when the actual processes are fetched, we do
613  * it here out of laziness.
614  */
615 static const struct kinfo_proc *
616 get_old_proc(struct kinfo_proc *pp)
617 {
618         const struct kinfo_proc * const *oldpp, *oldp;
619
620         /*
621          * If this is the first fetch of the kinfo_procs then we don't have
622          * any previous entries.
623          */
624         if (previous_proc_count == 0)
625                 return (NULL);
626         /* negative cache? */
627         if (pp->ki_udata == NOPROC)
628                 return (NULL);
629         /* cached? */
630         if (pp->ki_udata != NULL)
631                 return (pp->ki_udata);
632         /*
633          * Not cached,
634          * 1) look up based on pid.
635          * 2) compare process start.
636          * If we fail here, then setup a negative cache entry, otherwise
637          * cache it.
638          */
639         oldpp = bsearch(&pp, previous_pref, previous_proc_count,
640             sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
641         if (oldpp == NULL) {
642                 pp->ki_udata = NOPROC;
643                 return (NULL);
644         }
645         oldp = *oldpp;
646         if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
647                 pp->ki_udata = NOPROC;
648                 return (NULL);
649         }
650         pp->ki_udata = oldp;
651         return (oldp);
652 }
653
654 /*
655  * Return the total amount of IO done in blocks in/out and faults.
656  * store the values individually in the pointers passed in.
657  */
658 static long
659 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
660     long *vcsw, long *ivcsw)
661 {
662         const struct kinfo_proc *oldp;
663         static struct kinfo_proc dummy;
664         long ret;
665
666         oldp = get_old_proc(pp);
667         if (oldp == NULL) {
668                 memset(&dummy, 0, sizeof(dummy));
669                 oldp = &dummy;
670         }
671         *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
672         *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
673         *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
674         *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
675         *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
676         ret =
677             (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
678             (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
679             (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
680         return (ret);
681 }
682
683 /*
684  * If there was a previous update, use the delta in ki_runtime over
685  * the previous interval to calculate pctcpu.  Otherwise, fall back
686  * to using the kernel's ki_pctcpu.
687  */
688 static double
689 proc_calc_pctcpu(struct kinfo_proc *pp)
690 {
691         const struct kinfo_proc *oldp;
692
693         if (previous_interval != 0) {
694                 oldp = get_old_proc(pp);
695                 if (oldp != NULL)
696                         return ((double)(pp->ki_runtime - oldp->ki_runtime)
697                             / previous_interval);
698
699                 /*
700                  * If this process/thread was created during the previous
701                  * interval, charge it's total runtime to the previous
702                  * interval.
703                  */
704                 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
705                     (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
706                     pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
707                         return ((double)pp->ki_runtime / previous_interval);
708         }
709         return (pctdouble(pp->ki_pctcpu));
710 }
711
712 /*
713  * Return true if this process has used any CPU time since the
714  * previous update.
715  */
716 static int
717 proc_used_cpu(struct kinfo_proc *pp)
718 {
719         const struct kinfo_proc *oldp;
720
721         oldp = get_old_proc(pp);
722         if (oldp == NULL)
723                 return (PCTCPU(pp) != 0);
724         return (pp->ki_runtime != oldp->ki_runtime ||
725             RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
726             RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
727 }
728
729 /*
730  * Return the total number of block in/out and faults by a process.
731  */
732 static long
733 get_io_total(const struct kinfo_proc *pp)
734 {
735         long dummy;
736
737         return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
738 }
739
740 static struct handle handle;
741
742 void *
743 get_process_info(struct system_info *si, struct process_select *sel,
744     int (*compare)(const void *, const void *))
745 {
746         int i;
747         int total_procs;
748         long p_io;
749         long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
750         long nsec;
751         int active_procs;
752         struct kinfo_proc **prefp;
753         struct kinfo_proc *pp;
754         struct timespec previous_proc_uptime;
755
756         /*
757          * If thread state was toggled, don't cache the previous processes.
758          */
759         if (previous_thread != sel->thread)
760                 nproc = 0;
761         previous_thread = sel->thread;
762
763         /*
764          * Save the previous process info.
765          */
766         if (previous_proc_count_max < nproc) {
767                 free(previous_procs);
768                 previous_procs = calloc(nproc, sizeof(*previous_procs));
769                 free(previous_pref);
770                 previous_pref = calloc(nproc, sizeof(*previous_pref));
771                 if (previous_procs == NULL || previous_pref == NULL) {
772                         fprintf(stderr, "top: Out of memory.\n");
773                         quit(TOP_EX_SYS_ERROR);
774                 }
775                 previous_proc_count_max = nproc;
776         }
777         if (nproc) {
778                 for (i = 0; i < nproc; i++)
779                         previous_pref[i] = &previous_procs[i];
780                 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
781                 qsort(previous_pref, nproc, sizeof(*previous_pref),
782                     ps.thread ? compare_tid : compare_pid);
783         }
784         previous_proc_count = nproc;
785         previous_proc_uptime = proc_uptime;
786         previous_wall_time = proc_wall_time;
787         previous_interval = 0;
788
789         pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
790             0, &nproc);
791         gettimeofday(&proc_wall_time, NULL);
792         if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
793                 memset(&proc_uptime, 0, sizeof(proc_uptime));
794         else if (previous_proc_uptime.tv_sec != 0 &&
795             previous_proc_uptime.tv_nsec != 0) {
796                 previous_interval = (proc_uptime.tv_sec -
797                     previous_proc_uptime.tv_sec) * 1000000;
798                 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
799                 if (nsec < 0) {
800                         previous_interval -= 1000000;
801                         nsec += 1000000000;
802                 }
803                 previous_interval += nsec / 1000;
804         }
805         if (nproc > onproc) {
806                 pref = realloc(pref, sizeof(*pref) * nproc);
807                 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
808                 onproc = nproc;
809         }
810         if (pref == NULL || pbase == NULL || pcpu == NULL) {
811                 fprintf(stderr, "top: Out of memory.\n");
812                 quit(TOP_EX_SYS_ERROR);
813         }
814         /* get a pointer to the states summary array */
815         si->procstates = process_states;
816
817         /* count up process states and get pointers to interesting procs */
818         total_procs = 0;
819         active_procs = 0;
820         total_inblock = 0;
821         total_oublock = 0;
822         total_majflt = 0;
823         memset(process_states, 0, sizeof(process_states));
824         prefp = pref;
825         for (pp = pbase, i = 0; i < nproc; pp++, i++) {
826
827                 if (pp->ki_stat == 0)
828                         /* not in use */
829                         continue;
830
831                 if (!sel->self && pp->ki_pid == mypid)
832                         /* skip self */
833                         continue;
834
835                 if (!sel->system && (pp->ki_flag & P_SYSTEM))
836                         /* skip system process */
837                         continue;
838
839                 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
840                     &p_vcsw, &p_ivcsw);
841                 total_inblock += p_inblock;
842                 total_oublock += p_oublock;
843                 total_majflt += p_majflt;
844                 total_procs++;
845                 process_states[(unsigned char)pp->ki_stat]++;
846
847                 if (pp->ki_stat == SZOMB)
848                         /* skip zombies */
849                         continue;
850
851                 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD)
852                         /* skip kernel idle process */
853                         continue;
854
855                 PCTCPU(pp) = proc_calc_pctcpu(pp);
856                 if (sel->thread && PCTCPU(pp) > 1.0)
857                         PCTCPU(pp) = 1.0;
858                 if (displaymode == DISP_CPU && !sel->idle &&
859                     (!proc_used_cpu(pp) ||
860                      pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
861                         /* skip idle or non-running processes */
862                         continue;
863
864                 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
865                         /* skip processes that aren't doing I/O */
866                         continue;
867
868                 if (sel->jid != -1 && pp->ki_jid != sel->jid)
869                         /* skip proc. that don't belong to the selected JID */
870                         continue;
871
872                 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
873                         /* skip proc. that don't belong to the selected UID */
874                         continue;
875
876                 if (sel->pid != -1 && pp->ki_pid != sel->pid)
877                         continue;
878
879                 *prefp++ = pp;
880                 active_procs++;
881         }
882
883         /* if requested, sort the "interesting" processes */
884         if (compare != NULL)
885                 qsort(pref, active_procs, sizeof(*pref), compare);
886
887         /* remember active and total counts */
888         si->p_total = total_procs;
889         si->p_pactive = pref_len = active_procs;
890
891         /* pass back a handle */
892         handle.next_proc = pref;
893         handle.remaining = active_procs;
894         return (&handle);
895 }
896
897 static char fmt[512];   /* static area where result is built */
898
899 char *
900 format_next_process(void* xhandle, char *(*get_userid)(int), int flags)
901 {
902         struct kinfo_proc *pp;
903         const struct kinfo_proc *oldp;
904         long cputime;
905         double pct;
906         struct handle *hp;
907         char status[22];
908         int cpu;
909         size_t state;
910         struct rusage ru, *rup;
911         long p_tot, s_tot;
912         const char *proc_fmt;
913         char thr_buf[6];
914         char jid_buf[TOP_JID_LEN + 1], swap_buf[TOP_SWAP_LEN + 1];
915         char *cmdbuf = NULL;
916         char **args;
917         const int cmdlen = 128;
918
919         /* find and remember the next proc structure */
920         hp = (struct handle *)xhandle;
921         pp = *(hp->next_proc++);
922         hp->remaining--;
923
924         /* get the process's command name */
925         if ((pp->ki_flag & P_INMEM) == 0) {
926                 /*
927                  * Print swapped processes as <pname>
928                  */
929                 size_t len;
930
931                 len = strlen(pp->ki_comm);
932                 if (len > sizeof(pp->ki_comm) - 3)
933                         len = sizeof(pp->ki_comm) - 3;
934                 memmove(pp->ki_comm + 1, pp->ki_comm, len);
935                 pp->ki_comm[0] = '<';
936                 pp->ki_comm[len + 1] = '>';
937                 pp->ki_comm[len + 2] = '\0';
938         }
939
940         /*
941          * Convert the process's runtime from microseconds to seconds.  This
942          * time includes the interrupt time although that is not wanted here.
943          * ps(1) is similarly sloppy.
944          */
945         cputime = (pp->ki_runtime + 500000) / 1000000;
946
947         /* calculate the base for cpu percentages */
948         pct = PCTCPU(pp);
949
950         /* generate "STATE" field */
951         switch (state = pp->ki_stat) {
952         case SRUN:
953                 if (smpmode && pp->ki_oncpu != NOCPU)
954                         sprintf(status, "CPU%d", pp->ki_oncpu);
955                 else
956                         strcpy(status, "RUN");
957                 break;
958         case SLOCK:
959                 if (pp->ki_kiflag & KI_LOCKBLOCK) {
960                         sprintf(status, "*%.6s", pp->ki_lockname);
961                         break;
962                 }
963                 /* fall through */
964         case SSLEEP:
965                 sprintf(status, "%.6s", pp->ki_wmesg);
966                 break;
967         default:
968
969                 if (state < nitems(state_abbrev)) {
970                         sprintf(status, "%.6s", state_abbrev[state]);
971                 } else {
972                         sprintf(status, "?%5zu", state);
973                 }
974                 break;
975         }
976
977         cmdbuf = calloc(cmdlen + 1, 1);
978         if (cmdbuf == NULL) {
979                 warn("calloc(%d)", cmdlen + 1);
980                 return NULL;
981         }
982
983         if (!(flags & FMT_SHOWARGS)) {
984                 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
985                     pp->ki_tdname[0]) {
986                         snprintf(cmdbuf, cmdlen, "%s{%s%s}", pp->ki_comm,
987                             pp->ki_tdname, pp->ki_moretdname);
988                 } else {
989                         snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
990                 }
991         } else {
992                 if (pp->ki_flag & P_SYSTEM ||
993                     pp->ki_args == NULL ||
994                     (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
995                     !(*args)) {
996                         if (ps.thread && pp->ki_flag & P_HADTHREADS &&
997                             pp->ki_tdname[0]) {
998                                 snprintf(cmdbuf, cmdlen,
999                                     "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1000                                     pp->ki_moretdname);
1001                         } else {
1002                                 snprintf(cmdbuf, cmdlen,
1003                                     "[%s]", pp->ki_comm);
1004                         }
1005                 } else {
1006                         const char *src;
1007                         char *dst, *argbuf;
1008                         const char *cmd;
1009                         size_t argbuflen;
1010                         size_t len;
1011
1012                         argbuflen = cmdlen * 4;
1013                         argbuf = calloc(argbuflen + 1, 1);
1014                         if (argbuf == NULL) {
1015                                 warn("calloc(%zu)", argbuflen + 1);
1016                                 free(cmdbuf);
1017                                 return NULL;
1018                         }
1019
1020                         dst = argbuf;
1021
1022                         /* Extract cmd name from argv */
1023                         cmd = strrchr(*args, '/');
1024                         if (cmd == NULL)
1025                                 cmd = *args;
1026                         else
1027                                 cmd++;
1028
1029                         for (; (src = *args++) != NULL; ) {
1030                                 if (*src == '\0')
1031                                         continue;
1032                                 len = (argbuflen - (dst - argbuf) - 1) / 4;
1033                                 strvisx(dst, src,
1034                                     MIN(strlen(src), len),
1035                                     VIS_NL | VIS_CSTYLE);
1036                                 while (*dst != '\0')
1037                                         dst++;
1038                                 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1039                                         *dst++ = ' '; /* add delimiting space */
1040                         }
1041                         if (dst != argbuf && dst[-1] == ' ')
1042                                 dst--;
1043                         *dst = '\0';
1044
1045                         if (strcmp(cmd, pp->ki_comm) != 0) {
1046                                 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1047                                     pp->ki_tdname[0])
1048                                         snprintf(cmdbuf, cmdlen,
1049                                             "%s (%s){%s%s}", argbuf,
1050                                             pp->ki_comm, pp->ki_tdname,
1051                                             pp->ki_moretdname);
1052                                 else
1053                                         snprintf(cmdbuf, cmdlen,
1054                                             "%s (%s)", argbuf, pp->ki_comm);
1055                         } else {
1056                                 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1057                                     pp->ki_tdname[0])
1058                                         snprintf(cmdbuf, cmdlen,
1059                                             "%s{%s%s}", argbuf, pp->ki_tdname,
1060                                             pp->ki_moretdname);
1061                                 else
1062                                         strlcpy(cmdbuf, argbuf, cmdlen);
1063                         }
1064                         free(argbuf);
1065                 }
1066         }
1067
1068         if (ps.jail == 0)
1069                 jid_buf[0] = '\0';
1070         else
1071                 snprintf(jid_buf, sizeof(jid_buf), "%*d",
1072                     jidlength - 1, pp->ki_jid);
1073
1074         if (ps.swap == 0)
1075                 swap_buf[0] = '\0';
1076         else
1077                 snprintf(swap_buf, sizeof(swap_buf), "%*s",
1078                     swaplength - 1,
1079                     format_k2(pagetok(ki_swap(pp)))); /* XXX */
1080
1081         if (displaymode == DISP_IO) {
1082                 oldp = get_old_proc(pp);
1083                 if (oldp != NULL) {
1084                         ru.ru_inblock = RU(pp)->ru_inblock -
1085                             RU(oldp)->ru_inblock;
1086                         ru.ru_oublock = RU(pp)->ru_oublock -
1087                             RU(oldp)->ru_oublock;
1088                         ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1089                         ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1090                         ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1091                         rup = &ru;
1092                 } else {
1093                         rup = RU(pp);
1094                 }
1095                 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1096                 s_tot = total_inblock + total_oublock + total_majflt;
1097
1098                 snprintf(fmt, sizeof(fmt), io_Proc_format,
1099                     pp->ki_pid,
1100                     jidlength, jid_buf,
1101                     namelength, namelength, (*get_userid)(pp->ki_ruid),
1102                     rup->ru_nvcsw,
1103                     rup->ru_nivcsw,
1104                     rup->ru_inblock,
1105                     rup->ru_oublock,
1106                     rup->ru_majflt,
1107                     p_tot,
1108                     s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
1109                     screen_width > cmdlengthdelta ?
1110                     screen_width - cmdlengthdelta : 0,
1111                     printable(cmdbuf));
1112
1113                 free(cmdbuf);
1114
1115                 return (fmt);
1116         }
1117
1118         /* format this entry */
1119         if (smpmode) {
1120                 if (state == SRUN && pp->ki_oncpu != NOCPU)
1121                         cpu = pp->ki_oncpu;
1122                 else
1123                         cpu = pp->ki_lastcpu;
1124         } else
1125                 cpu = 0;
1126         proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1127         if (ps.thread != 0)
1128                 thr_buf[0] = '\0';
1129         else
1130                 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1131                     (int)(sizeof(thr_buf) - 2), pp->ki_numthreads);
1132
1133         snprintf(fmt, sizeof(fmt), proc_fmt,
1134             (ps.thread) ? pp->ki_tid : pp->ki_pid,
1135             jidlength, jid_buf,
1136             namelength, namelength, (*get_userid)(pp->ki_ruid),
1137             thr_buf,
1138             pp->ki_pri.pri_level - PZERO,
1139             format_nice(pp),
1140             format_k2(PROCSIZE(pp)),
1141             format_k2(pagetok(pp->ki_rssize)),
1142             swaplength, swaplength, swap_buf,
1143             status,
1144             cpu,
1145             format_time(cputime),
1146             ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1147             screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1148             printable(cmdbuf));
1149
1150         free(cmdbuf);
1151
1152         /* return the result */
1153         return (fmt);
1154 }
1155
1156 static void
1157 getsysctl(const char *name, void *ptr, size_t len)
1158 {
1159         size_t nlen = len;
1160
1161         if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1162                 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1163                     strerror(errno));
1164                 quit(TOP_EX_SYS_ERROR);
1165         }
1166         if (nlen != len) {
1167                 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1168                     name, (unsigned long)len, (unsigned long)nlen);
1169                 quit(TOP_EX_SYS_ERROR);
1170         }
1171 }
1172
1173 static const char *
1174 format_nice(const struct kinfo_proc *pp)
1175 {
1176         const char *fifo, *kproc;
1177         int rtpri;
1178         static char nicebuf[4 + 1];
1179
1180         fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1181         kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1182         switch (PRI_BASE(pp->ki_pri.pri_class)) {
1183         case PRI_ITHD:
1184                 return ("-");
1185         case PRI_REALTIME:
1186                 /*
1187                  * XXX: the kernel doesn't tell us the original rtprio and
1188                  * doesn't really know what it was, so to recover it we
1189                  * must be more chummy with the implementation than the
1190                  * implementation is with itself.  pri_user gives a
1191                  * constant "base" priority, but is only initialized
1192                  * properly for user threads.  pri_native gives what the
1193                  * kernel calls the "base" priority, but it isn't constant
1194                  * since it is changed by priority propagation.  pri_native
1195                  * also isn't properly initialized for all threads, but it
1196                  * is properly initialized for kernel realtime and idletime
1197                  * threads.  Thus we use pri_user for the base priority of
1198                  * user threads (it is always correct) and pri_native for
1199                  * the base priority of kernel realtime and idletime threads
1200                  * (there is nothing better, and it is usually correct).
1201                  *
1202                  * The field width and thus the buffer are too small for
1203                  * values like "kr31F", but such values shouldn't occur,
1204                  * and if they do then the tailing "F" is not displayed.
1205                  */
1206                 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1207                     pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1208                 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1209                     kproc, rtpri, fifo);
1210                 break;
1211         case PRI_TIMESHARE:
1212                 if (pp->ki_flag & P_KPROC)
1213                         return ("-");
1214                 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1215                 break;
1216         case PRI_IDLE:
1217                 /* XXX: as above. */
1218                 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1219                     pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1220                 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1221                     kproc, rtpri, fifo);
1222                 break;
1223         default:
1224                 return ("?");
1225         }
1226         return (nicebuf);
1227 }
1228
1229 /* comparison routines for qsort */
1230
1231 static int
1232 compare_pid(const void *p1, const void *p2)
1233 {
1234         const struct kinfo_proc * const *pp1 = p1;
1235         const struct kinfo_proc * const *pp2 = p2;
1236
1237         assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1238
1239         return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1240 }
1241
1242 static int
1243 compare_tid(const void *p1, const void *p2)
1244 {
1245         const struct kinfo_proc * const *pp1 = p1;
1246         const struct kinfo_proc * const *pp2 = p2;
1247
1248         assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1249
1250         return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1251 }
1252
1253 /*
1254  *  proc_compare - comparison function for "qsort"
1255  *      Compares the resource consumption of two processes using five
1256  *      distinct keys.  The keys (in descending order of importance) are:
1257  *      percent cpu, cpu ticks, state, resident set size, total virtual
1258  *      memory usage.  The process states are ordered as follows (from least
1259  *      to most important):  WAIT, zombie, sleep, stop, start, run.  The
1260  *      array declaration below maps a process state index into a number
1261  *      that reflects this ordering.
1262  */
1263
1264 static int sorted_state[] = {
1265         0,      /* not used             */
1266         3,      /* sleep                */
1267         1,      /* ABANDONED (WAIT)     */
1268         6,      /* run                  */
1269         5,      /* start                */
1270         2,      /* zombie               */
1271         4       /* stop                 */
1272 };
1273
1274
1275 #define ORDERKEY_PCTCPU(a, b) do { \
1276         double diff; \
1277         if (ps.wcpu) \
1278                 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1279                     weighted_cpu(PCTCPU((a)), (a)); \
1280         else \
1281                 diff = PCTCPU((b)) - PCTCPU((a)); \
1282         if (diff != 0) \
1283                 return (diff > 0 ? 1 : -1); \
1284 } while (0)
1285
1286 #define ORDERKEY_CPTICKS(a, b) do { \
1287         int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1288         if (diff != 0) \
1289                 return (diff > 0 ? 1 : -1); \
1290 } while (0)
1291
1292 #define ORDERKEY_STATE(a, b) do { \
1293         int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1294         if (diff != 0) \
1295                 return (diff > 0 ? 1 : -1); \
1296 } while (0)
1297
1298 #define ORDERKEY_PRIO(a, b) do { \
1299         int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1300         if (diff != 0) \
1301                 return (diff > 0 ? 1 : -1); \
1302 } while (0)
1303
1304 #define ORDERKEY_THREADS(a, b) do { \
1305         int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1306         if (diff != 0) \
1307                 return (diff > 0 ? 1 : -1); \
1308 } while (0)
1309
1310 #define ORDERKEY_RSSIZE(a, b) do { \
1311         long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1312         if (diff != 0) \
1313                 return (diff > 0 ? 1 : -1); \
1314 } while (0)
1315
1316 #define ORDERKEY_MEM(a, b) do { \
1317         long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1318         if (diff != 0) \
1319                 return (diff > 0 ? 1 : -1); \
1320 } while (0)
1321
1322 #define ORDERKEY_JID(a, b) do { \
1323         int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1324         if (diff != 0) \
1325                 return (diff > 0 ? 1 : -1); \
1326 } while (0)
1327
1328 #define ORDERKEY_SWAP(a, b) do { \
1329         int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1330         if (diff != 0) \
1331                 return (diff > 0 ? 1 : -1); \
1332 } while (0)
1333
1334 /* compare_cpu - the comparison function for sorting by cpu percentage */
1335
1336 static int
1337 compare_cpu(const void *arg1, const void *arg2)
1338 {
1339         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1340         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1341
1342         ORDERKEY_PCTCPU(p1, p2);
1343         ORDERKEY_CPTICKS(p1, p2);
1344         ORDERKEY_STATE(p1, p2);
1345         ORDERKEY_PRIO(p1, p2);
1346         ORDERKEY_RSSIZE(p1, p2);
1347         ORDERKEY_MEM(p1, p2);
1348
1349         return (0);
1350 }
1351
1352 /* compare_size - the comparison function for sorting by total memory usage */
1353
1354 static int
1355 compare_size(const void *arg1, const void *arg2)
1356 {
1357         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1358         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1359
1360         ORDERKEY_MEM(p1, p2);
1361         ORDERKEY_RSSIZE(p1, p2);
1362         ORDERKEY_PCTCPU(p1, p2);
1363         ORDERKEY_CPTICKS(p1, p2);
1364         ORDERKEY_STATE(p1, p2);
1365         ORDERKEY_PRIO(p1, p2);
1366
1367         return (0);
1368 }
1369
1370 /* compare_res - the comparison function for sorting by resident set size */
1371
1372 static int
1373 compare_res(const void *arg1, const void *arg2)
1374 {
1375         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1376         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1377
1378         ORDERKEY_RSSIZE(p1, p2);
1379         ORDERKEY_MEM(p1, p2);
1380         ORDERKEY_PCTCPU(p1, p2);
1381         ORDERKEY_CPTICKS(p1, p2);
1382         ORDERKEY_STATE(p1, p2);
1383         ORDERKEY_PRIO(p1, p2);
1384
1385         return (0);
1386 }
1387
1388 /* compare_time - the comparison function for sorting by total cpu time */
1389
1390 static int
1391 compare_time(const void *arg1, const void *arg2)
1392 {
1393         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const  *)arg1;
1394         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1395
1396         ORDERKEY_CPTICKS(p1, p2);
1397         ORDERKEY_PCTCPU(p1, p2);
1398         ORDERKEY_STATE(p1, p2);
1399         ORDERKEY_PRIO(p1, p2);
1400         ORDERKEY_RSSIZE(p1, p2);
1401         ORDERKEY_MEM(p1, p2);
1402
1403         return (0);
1404 }
1405
1406 /* compare_prio - the comparison function for sorting by priority */
1407
1408 static int
1409 compare_prio(const void *arg1, const void *arg2)
1410 {
1411         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1412         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1413
1414         ORDERKEY_PRIO(p1, p2);
1415         ORDERKEY_CPTICKS(p1, p2);
1416         ORDERKEY_PCTCPU(p1, p2);
1417         ORDERKEY_STATE(p1, p2);
1418         ORDERKEY_RSSIZE(p1, p2);
1419         ORDERKEY_MEM(p1, p2);
1420
1421         return (0);
1422 }
1423
1424 /* compare_threads - the comparison function for sorting by threads */
1425 static int
1426 compare_threads(const void *arg1, const void *arg2)
1427 {
1428         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1429         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1430
1431         ORDERKEY_THREADS(p1, p2);
1432         ORDERKEY_PCTCPU(p1, p2);
1433         ORDERKEY_CPTICKS(p1, p2);
1434         ORDERKEY_STATE(p1, p2);
1435         ORDERKEY_PRIO(p1, p2);
1436         ORDERKEY_RSSIZE(p1, p2);
1437         ORDERKEY_MEM(p1, p2);
1438
1439         return (0);
1440 }
1441
1442 /* compare_jid - the comparison function for sorting by jid */
1443 static int
1444 compare_jid(const void *arg1, const void *arg2)
1445 {
1446         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1447         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1448
1449         ORDERKEY_JID(p1, p2);
1450         ORDERKEY_PCTCPU(p1, p2);
1451         ORDERKEY_CPTICKS(p1, p2);
1452         ORDERKEY_STATE(p1, p2);
1453         ORDERKEY_PRIO(p1, p2);
1454         ORDERKEY_RSSIZE(p1, p2);
1455         ORDERKEY_MEM(p1, p2);
1456
1457         return (0);
1458 }
1459
1460 /* compare_swap - the comparison function for sorting by swap */
1461 static int
1462 compare_swap(const void *arg1, const void *arg2)
1463 {
1464         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1465         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1466
1467         ORDERKEY_SWAP(p1, p2);
1468         ORDERKEY_PCTCPU(p1, p2);
1469         ORDERKEY_CPTICKS(p1, p2);
1470         ORDERKEY_STATE(p1, p2);
1471         ORDERKEY_PRIO(p1, p2);
1472         ORDERKEY_RSSIZE(p1, p2);
1473         ORDERKEY_MEM(p1, p2);
1474
1475         return (0);
1476 }
1477
1478 /* assorted comparison functions for sorting by i/o */
1479
1480 static int
1481 compare_iototal(const void *arg1, const void *arg2)
1482 {
1483         const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1484         const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1485
1486         return (get_io_total(p2) - get_io_total(p1));
1487 }
1488
1489 static int
1490 compare_ioread(const void *arg1, const void *arg2)
1491 {
1492         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1493         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1494         long dummy, inp1, inp2;
1495
1496         (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1497         (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1498
1499         return (inp2 - inp1);
1500 }
1501
1502 static int
1503 compare_iowrite(const void *arg1, const void *arg2)
1504 {
1505         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1506         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1507         long dummy, oup1, oup2;
1508
1509         (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1510         (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1511
1512         return (oup2 - oup1);
1513 }
1514
1515 static int
1516 compare_iofault(const void *arg1, const void *arg2)
1517 {
1518         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1519         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1520         long dummy, flp1, flp2;
1521
1522         (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1523         (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1524
1525         return (flp2 - flp1);
1526 }
1527
1528 static int
1529 compare_vcsw(const void *arg1, const void *arg2)
1530 {
1531         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1532         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1533         long dummy, flp1, flp2;
1534
1535         (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1536         (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1537
1538         return (flp2 - flp1);
1539 }
1540
1541 static int
1542 compare_ivcsw(const void *arg1, const void *arg2)
1543 {
1544         const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1545         const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1546         long dummy, flp1, flp2;
1547
1548         (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1549         (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1550
1551         return (flp2 - flp1);
1552 }
1553
1554 int (*compares[])(const void *arg1, const void *arg2) = {
1555         compare_cpu,
1556         compare_size,
1557         compare_res,
1558         compare_time,
1559         compare_prio,
1560         compare_threads,
1561         compare_iototal,
1562         compare_ioread,
1563         compare_iowrite,
1564         compare_iofault,
1565         compare_vcsw,
1566         compare_ivcsw,
1567         compare_jid,
1568         compare_swap,
1569         NULL
1570 };
1571
1572
1573 /*
1574  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1575  *              the process does not exist.
1576  */
1577
1578 int
1579 proc_owner(int pid)
1580 {
1581         int cnt;
1582         struct kinfo_proc **prefp;
1583         struct kinfo_proc *pp;
1584
1585         prefp = pref;
1586         cnt = pref_len;
1587         while (--cnt >= 0) {
1588                 pp = *prefp++;
1589                 if (pp->ki_pid == (pid_t)pid)
1590                         return ((int)pp->ki_ruid);
1591         }
1592         return (-1);
1593 }
1594
1595 static int
1596 swapmode(int *retavail, int *retfree)
1597 {
1598         int n;
1599         struct kvm_swap swapary[1];
1600         static int pagesize = 0;
1601         static unsigned long swap_maxpages = 0;
1602
1603         *retavail = 0;
1604         *retfree = 0;
1605
1606 #define CONVERT(v)      ((quad_t)(v) * pagesize / 1024)
1607
1608         n = kvm_getswapinfo(kd, swapary, 1, 0);
1609         if (n < 0 || swapary[0].ksw_total == 0)
1610                 return (0);
1611
1612         if (pagesize == 0)
1613                 pagesize = getpagesize();
1614         if (swap_maxpages == 0)
1615                 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1616
1617         /* ksw_total contains the total size of swap all devices which may
1618            exceed the maximum swap size allocatable in the system */
1619         if ( swapary[0].ksw_total > swap_maxpages )
1620                 swapary[0].ksw_total = swap_maxpages;
1621
1622         *retavail = CONVERT(swapary[0].ksw_total);
1623         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1624
1625         n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1626         return (n);
1627 }