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