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