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