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