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