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