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