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