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