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