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