xref: /freebsd/usr.bin/top/machine.c (revision 5c8e8e82aeaf3aa788acdd6cfca30ef09094230d)
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 	extern int show_args;
899 	char **args = NULL;
900 
901 	if (!term) {
902 		/* No command filter set */
903 		return 1;
904 	} else {
905 		/* Filter set, does process name contain term? */
906 		if (strstr(proc->ki_comm, term))
907 			return 1;
908 		/* Search arguments only if arguments are displayed */
909 		if (show_args) {
910 			args = kvm_getargv(kd, proc, 1024);
911 			if (args == NULL) {
912 				/* Failed to get arguments so can't search them */
913 				return 0;
914 			}
915 			while (*args != NULL) {
916 				if (strstr(*args, term))
917 					return 1;
918 				args++;
919 			}
920 		}
921 	}
922 	return 0;
923 }
924 
925 char *
926 format_next_process(struct handle * xhandle, char *(*get_userid)(int), int flags)
927 {
928 	struct kinfo_proc *pp;
929 	const struct kinfo_proc *oldp;
930 	long cputime;
931 	char status[22];
932 	size_t state;
933 	struct rusage ru, *rup;
934 	long p_tot, s_tot;
935 	char *cmdbuf = NULL;
936 	char **args;
937 	static struct sbuf* procbuf = NULL;
938 
939 	/* clean up from last time. */
940 	if (procbuf != NULL) {
941 		sbuf_clear(procbuf);
942 	} else {
943 		procbuf = sbuf_new_auto();
944 	}
945 
946 
947 	/* find and remember the next proc structure */
948 	pp = *(xhandle->next_proc++);
949 	xhandle->remaining--;
950 
951 	/* get the process's command name */
952 	if ((pp->ki_flag & P_INMEM) == 0) {
953 		/*
954 		 * Print swapped processes as <pname>
955 		 */
956 		size_t len;
957 
958 		len = strlen(pp->ki_comm);
959 		if (len > sizeof(pp->ki_comm) - 3)
960 			len = sizeof(pp->ki_comm) - 3;
961 		memmove(pp->ki_comm + 1, pp->ki_comm, len);
962 		pp->ki_comm[0] = '<';
963 		pp->ki_comm[len + 1] = '>';
964 		pp->ki_comm[len + 2] = '\0';
965 	}
966 
967 	/*
968 	 * Convert the process's runtime from microseconds to seconds.  This
969 	 * time includes the interrupt time although that is not wanted here.
970 	 * ps(1) is similarly sloppy.
971 	 */
972 	cputime = (pp->ki_runtime + 500000) / 1000000;
973 
974 	/* generate "STATE" field */
975 	switch (state = pp->ki_stat) {
976 	case SRUN:
977 		if (smpmode && pp->ki_oncpu != NOCPU)
978 			sprintf(status, "CPU%d", pp->ki_oncpu);
979 		else
980 			strcpy(status, "RUN");
981 		break;
982 	case SLOCK:
983 		if (pp->ki_kiflag & KI_LOCKBLOCK) {
984 			sprintf(status, "*%.6s", pp->ki_lockname);
985 			break;
986 		}
987 		/* fall through */
988 	case SSLEEP:
989 		sprintf(status, "%.6s", pp->ki_wmesg);
990 		break;
991 	default:
992 
993 		if (state < nitems(state_abbrev)) {
994 			sprintf(status, "%.6s", state_abbrev[state]);
995 		} else {
996 			sprintf(status, "?%5zu", state);
997 		}
998 		break;
999 	}
1000 
1001 	cmdbuf = calloc(screen_width + 1, 1);
1002 	if (cmdbuf == NULL) {
1003 		warn("calloc(%d)", screen_width + 1);
1004 		return NULL;
1005 	}
1006 
1007 	if (!(flags & FMT_SHOWARGS)) {
1008 		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1009 		    pp->ki_tdname[0]) {
1010 			snprintf(cmdbuf, screen_width, "%s{%s%s}", pp->ki_comm,
1011 			    pp->ki_tdname, pp->ki_moretdname);
1012 		} else {
1013 			snprintf(cmdbuf, screen_width, "%s", pp->ki_comm);
1014 		}
1015 	} else {
1016 		if (pp->ki_flag & P_SYSTEM ||
1017 		    (args = kvm_getargv(kd, pp, screen_width)) == NULL ||
1018 		    !(*args)) {
1019 			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1020 		    	    pp->ki_tdname[0]) {
1021 				snprintf(cmdbuf, screen_width,
1022 				    "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1023 				    pp->ki_moretdname);
1024 			} else {
1025 				snprintf(cmdbuf, screen_width,
1026 				    "[%s]", pp->ki_comm);
1027 			}
1028 		} else {
1029 			const char *src;
1030 			char *dst, *argbuf;
1031 			const char *cmd;
1032 			size_t argbuflen;
1033 			size_t len;
1034 
1035 			argbuflen = screen_width * 4;
1036 			argbuf = calloc(argbuflen + 1, 1);
1037 			if (argbuf == NULL) {
1038 				warn("calloc(%zu)", argbuflen + 1);
1039 				free(cmdbuf);
1040 				return NULL;
1041 			}
1042 
1043 			dst = argbuf;
1044 
1045 			/* Extract cmd name from argv */
1046 			cmd = basename(*args);
1047 
1048 			for (; (src = *args++) != NULL; ) {
1049 				if (*src == '\0')
1050 					continue;
1051 				len = (argbuflen - (dst - argbuf) - 1) / 4;
1052 				strvisx(dst, src,
1053 				    MIN(strlen(src), len),
1054 				    VIS_NL | VIS_TAB | VIS_CSTYLE | VIS_OCTAL);
1055 				while (*dst != '\0')
1056 					dst++;
1057 				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1058 					*dst++ = ' '; /* add delimiting space */
1059 			}
1060 			if (dst != argbuf && dst[-1] == ' ')
1061 				dst--;
1062 			*dst = '\0';
1063 
1064 			if (strcmp(cmd, pp->ki_comm) != 0) {
1065 				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1066 				    pp->ki_tdname[0])
1067 					snprintf(cmdbuf, screen_width,
1068 					    "%s (%s){%s%s}", argbuf,
1069 					    pp->ki_comm, pp->ki_tdname,
1070 					    pp->ki_moretdname);
1071 				else
1072 					snprintf(cmdbuf, screen_width,
1073 					    "%s (%s)", argbuf, pp->ki_comm);
1074 			} else {
1075 				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1076 				    pp->ki_tdname[0])
1077 					snprintf(cmdbuf, screen_width,
1078 					    "%s{%s%s}", argbuf, pp->ki_tdname,
1079 					    pp->ki_moretdname);
1080 				else
1081 					strlcpy(cmdbuf, argbuf, screen_width);
1082 			}
1083 			free(argbuf);
1084 		}
1085 	}
1086 
1087 	if (displaymode == DISP_IO) {
1088 		oldp = get_old_proc(pp);
1089 		if (oldp != NULL) {
1090 			ru.ru_inblock = RU(pp)->ru_inblock -
1091 			    RU(oldp)->ru_inblock;
1092 			ru.ru_oublock = RU(pp)->ru_oublock -
1093 			    RU(oldp)->ru_oublock;
1094 			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1095 			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1096 			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1097 			rup = &ru;
1098 		} else {
1099 			rup = RU(pp);
1100 		}
1101 		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1102 		s_tot = total_inblock + total_oublock + total_majflt;
1103 
1104 		sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1105 
1106 		if (ps.jail) {
1107 			sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1108 		}
1109 		sbuf_printf(procbuf, "%-*.*s", namelength, namelength, (*get_userid)(pp->ki_ruid));
1110 		sbuf_printf(procbuf, "%6ld ", rup->ru_nvcsw);
1111 		sbuf_printf(procbuf, "%6ld ", rup->ru_nivcsw);
1112 		sbuf_printf(procbuf, "%6ld ", rup->ru_inblock);
1113 		sbuf_printf(procbuf, "%6ld ", rup->ru_oublock);
1114 		sbuf_printf(procbuf, "%6ld ", rup->ru_majflt);
1115 		sbuf_printf(procbuf, "%6ld ", p_tot);
1116 		sbuf_printf(procbuf, "%6.2f%% ", s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot));
1117 
1118 	} else {
1119 		sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1120 		if (ps.jail) {
1121 			sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1122 		}
1123 		sbuf_printf(procbuf, "%-*.*s ", namelength, namelength, (*get_userid)(pp->ki_ruid));
1124 
1125 		if (!ps.thread) {
1126 			sbuf_printf(procbuf, "%4d ", pp->ki_numthreads);
1127 		} else {
1128 			sbuf_printf(procbuf, " ");
1129 		}
1130 
1131 		sbuf_printf(procbuf, "%3d ", pp->ki_pri.pri_level - PZERO);
1132 		sbuf_printf(procbuf, "%4s", format_nice(pp));
1133 		sbuf_printf(procbuf, "%7s ", format_k(PROCSIZE(pp)));
1134 		sbuf_printf(procbuf, "%6s ", format_k(pagetok(pp->ki_rssize)));
1135 		if (ps.swap) {
1136 			sbuf_printf(procbuf, "%*s ",
1137 				TOP_SWAP_LEN - 1,
1138 				format_k(pagetok(ki_swap(pp))));
1139 		}
1140 		sbuf_printf(procbuf, "%-6.6s ", status);
1141 		if (smpmode) {
1142 			int cpu;
1143 			if (state == SRUN && pp->ki_oncpu != NOCPU) {
1144 				cpu = pp->ki_oncpu;
1145 			} else {
1146 				cpu = pp->ki_lastcpu;
1147 			}
1148 			sbuf_printf(procbuf, "%3d ", cpu);
1149 		}
1150 		sbuf_printf(procbuf, "%6s ", format_time(cputime));
1151 		sbuf_printf(procbuf, "%6.2f%% ", ps.wcpu ? 100.0 * weighted_cpu(PCTCPU(pp), pp) : 100.0 * PCTCPU(pp));
1152 	}
1153 	sbuf_printf(procbuf, "%s", cmdbuf);
1154 	free(cmdbuf);
1155 	return (sbuf_data(procbuf));
1156 }
1157 
1158 static void
1159 getsysctl(const char *name, void *ptr, size_t len)
1160 {
1161 	size_t nlen = len;
1162 
1163 	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1164 		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1165 		    strerror(errno));
1166 		quit(TOP_EX_SYS_ERROR);
1167 	}
1168 	if (nlen != len) {
1169 		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1170 		    name, (unsigned long)len, (unsigned long)nlen);
1171 		quit(TOP_EX_SYS_ERROR);
1172 	}
1173 }
1174 
1175 static const char *
1176 format_nice(const struct kinfo_proc *pp)
1177 {
1178 	const char *fifo, *kproc;
1179 	int rtpri;
1180 	static char nicebuf[4 + 1];
1181 
1182 	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1183 	kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1184 	switch (PRI_BASE(pp->ki_pri.pri_class)) {
1185 	case PRI_ITHD:
1186 		return ("-");
1187 	case PRI_REALTIME:
1188 		/*
1189 		 * XXX: the kernel doesn't tell us the original rtprio and
1190 		 * doesn't really know what it was, so to recover it we
1191 		 * must be more chummy with the implementation than the
1192 		 * implementation is with itself.  pri_user gives a
1193 		 * constant "base" priority, but is only initialized
1194 		 * properly for user threads.  pri_native gives what the
1195 		 * kernel calls the "base" priority, but it isn't constant
1196 		 * since it is changed by priority propagation.  pri_native
1197 		 * also isn't properly initialized for all threads, but it
1198 		 * is properly initialized for kernel realtime and idletime
1199 		 * threads.  Thus we use pri_user for the base priority of
1200 		 * user threads (it is always correct) and pri_native for
1201 		 * the base priority of kernel realtime and idletime threads
1202 		 * (there is nothing better, and it is usually correct).
1203 		 *
1204 		 * The field width and thus the buffer are too small for
1205 		 * values like "kr31F", but such values shouldn't occur,
1206 		 * and if they do then the tailing "F" is not displayed.
1207 		 */
1208 		rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1209 		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1210 		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1211 		    kproc, rtpri, fifo);
1212 		break;
1213 	case PRI_TIMESHARE:
1214 		if (pp->ki_flag & P_KPROC)
1215 			return ("-");
1216 		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1217 		break;
1218 	case PRI_IDLE:
1219 		/* XXX: as above. */
1220 		rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1221 		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1222 		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1223 		    kproc, rtpri, fifo);
1224 		break;
1225 	default:
1226 		return ("?");
1227 	}
1228 	return (nicebuf);
1229 }
1230 
1231 /* comparison routines for qsort */
1232 
1233 static int
1234 compare_pid(const void *p1, const void *p2)
1235 {
1236 	const struct kinfo_proc * const *pp1 = p1;
1237 	const struct kinfo_proc * const *pp2 = p2;
1238 
1239 	assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1240 
1241 	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1242 }
1243 
1244 static int
1245 compare_tid(const void *p1, const void *p2)
1246 {
1247 	const struct kinfo_proc * const *pp1 = p1;
1248 	const struct kinfo_proc * const *pp2 = p2;
1249 
1250 	assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1251 
1252 	return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1253 }
1254 
1255 /*
1256  *  proc_compare - comparison function for "qsort"
1257  *	Compares the resource consumption of two processes using five
1258  *	distinct keys.  The keys (in descending order of importance) are:
1259  *	percent cpu, cpu ticks, state, resident set size, total virtual
1260  *	memory usage.  The process states are ordered as follows (from least
1261  *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
1262  *	array declaration below maps a process state index into a number
1263  *	that reflects this ordering.
1264  */
1265 
1266 static int sorted_state[] = {
1267 	0,	/* not used		*/
1268 	3,	/* sleep		*/
1269 	1,	/* ABANDONED (WAIT)	*/
1270 	6,	/* run			*/
1271 	5,	/* start		*/
1272 	2,	/* zombie		*/
1273 	4	/* stop			*/
1274 };
1275 
1276 
1277 #define ORDERKEY_PCTCPU(a, b) do { \
1278 	double diff; \
1279 	if (ps.wcpu) \
1280 		diff = weighted_cpu(PCTCPU((b)), (b)) - \
1281 		    weighted_cpu(PCTCPU((a)), (a)); \
1282 	else \
1283 		diff = PCTCPU((b)) - PCTCPU((a)); \
1284 	if (diff != 0) \
1285 		return (diff > 0 ? 1 : -1); \
1286 } while (0)
1287 
1288 #define ORDERKEY_CPTICKS(a, b) do { \
1289 	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1290 	if (diff != 0) \
1291 		return (diff > 0 ? 1 : -1); \
1292 } while (0)
1293 
1294 #define ORDERKEY_STATE(a, b) do { \
1295 	int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1296 	if (diff != 0) \
1297 		return (diff > 0 ? 1 : -1); \
1298 } while (0)
1299 
1300 #define ORDERKEY_PRIO(a, b) do { \
1301 	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1302 	if (diff != 0) \
1303 		return (diff > 0 ? 1 : -1); \
1304 } while (0)
1305 
1306 #define	ORDERKEY_THREADS(a, b) do { \
1307 	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1308 	if (diff != 0) \
1309 		return (diff > 0 ? 1 : -1); \
1310 } while (0)
1311 
1312 #define ORDERKEY_RSSIZE(a, b) do { \
1313 	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1314 	if (diff != 0) \
1315 		return (diff > 0 ? 1 : -1); \
1316 } while (0)
1317 
1318 #define ORDERKEY_MEM(a, b) do { \
1319 	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1320 	if (diff != 0) \
1321 		return (diff > 0 ? 1 : -1); \
1322 } while (0)
1323 
1324 #define ORDERKEY_JID(a, b) do { \
1325 	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1326 	if (diff != 0) \
1327 		return (diff > 0 ? 1 : -1); \
1328 } while (0)
1329 
1330 #define ORDERKEY_SWAP(a, b) do { \
1331 	int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1332 	if (diff != 0) \
1333 		return (diff > 0 ? 1 : -1); \
1334 } while (0)
1335 
1336 /* compare_cpu - the comparison function for sorting by cpu percentage */
1337 
1338 static int
1339 compare_cpu(const void *arg1, const void *arg2)
1340 {
1341 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1342 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1343 
1344 	ORDERKEY_PCTCPU(p1, p2);
1345 	ORDERKEY_CPTICKS(p1, p2);
1346 	ORDERKEY_STATE(p1, p2);
1347 	ORDERKEY_PRIO(p1, p2);
1348 	ORDERKEY_RSSIZE(p1, p2);
1349 	ORDERKEY_MEM(p1, p2);
1350 
1351 	return (0);
1352 }
1353 
1354 /* compare_size - the comparison function for sorting by total memory usage */
1355 
1356 static int
1357 compare_size(const void *arg1, const void *arg2)
1358 {
1359 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1360 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1361 
1362 	ORDERKEY_MEM(p1, p2);
1363 	ORDERKEY_RSSIZE(p1, p2);
1364 	ORDERKEY_PCTCPU(p1, p2);
1365 	ORDERKEY_CPTICKS(p1, p2);
1366 	ORDERKEY_STATE(p1, p2);
1367 	ORDERKEY_PRIO(p1, p2);
1368 
1369 	return (0);
1370 }
1371 
1372 /* compare_res - the comparison function for sorting by resident set size */
1373 
1374 static int
1375 compare_res(const void *arg1, const void *arg2)
1376 {
1377 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1378 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1379 
1380 	ORDERKEY_RSSIZE(p1, p2);
1381 	ORDERKEY_MEM(p1, p2);
1382 	ORDERKEY_PCTCPU(p1, p2);
1383 	ORDERKEY_CPTICKS(p1, p2);
1384 	ORDERKEY_STATE(p1, p2);
1385 	ORDERKEY_PRIO(p1, p2);
1386 
1387 	return (0);
1388 }
1389 
1390 /* compare_time - the comparison function for sorting by total cpu time */
1391 
1392 static int
1393 compare_time(const void *arg1, const void *arg2)
1394 {
1395 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const  *)arg1;
1396 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1397 
1398 	ORDERKEY_CPTICKS(p1, p2);
1399 	ORDERKEY_PCTCPU(p1, p2);
1400 	ORDERKEY_STATE(p1, p2);
1401 	ORDERKEY_PRIO(p1, p2);
1402 	ORDERKEY_RSSIZE(p1, p2);
1403 	ORDERKEY_MEM(p1, p2);
1404 
1405 	return (0);
1406 }
1407 
1408 /* compare_prio - the comparison function for sorting by priority */
1409 
1410 static int
1411 compare_prio(const void *arg1, const void *arg2)
1412 {
1413 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1414 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1415 
1416 	ORDERKEY_PRIO(p1, p2);
1417 	ORDERKEY_CPTICKS(p1, p2);
1418 	ORDERKEY_PCTCPU(p1, p2);
1419 	ORDERKEY_STATE(p1, p2);
1420 	ORDERKEY_RSSIZE(p1, p2);
1421 	ORDERKEY_MEM(p1, p2);
1422 
1423 	return (0);
1424 }
1425 
1426 /* compare_threads - the comparison function for sorting by threads */
1427 static int
1428 compare_threads(const void *arg1, const void *arg2)
1429 {
1430 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1431 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1432 
1433 	ORDERKEY_THREADS(p1, p2);
1434 	ORDERKEY_PCTCPU(p1, p2);
1435 	ORDERKEY_CPTICKS(p1, p2);
1436 	ORDERKEY_STATE(p1, p2);
1437 	ORDERKEY_PRIO(p1, p2);
1438 	ORDERKEY_RSSIZE(p1, p2);
1439 	ORDERKEY_MEM(p1, p2);
1440 
1441 	return (0);
1442 }
1443 
1444 /* compare_jid - the comparison function for sorting by jid */
1445 static int
1446 compare_jid(const void *arg1, const void *arg2)
1447 {
1448 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1449 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1450 
1451 	ORDERKEY_JID(p1, p2);
1452 	ORDERKEY_PCTCPU(p1, p2);
1453 	ORDERKEY_CPTICKS(p1, p2);
1454 	ORDERKEY_STATE(p1, p2);
1455 	ORDERKEY_PRIO(p1, p2);
1456 	ORDERKEY_RSSIZE(p1, p2);
1457 	ORDERKEY_MEM(p1, p2);
1458 
1459 	return (0);
1460 }
1461 
1462 /* compare_swap - the comparison function for sorting by swap */
1463 static int
1464 compare_swap(const void *arg1, const void *arg2)
1465 {
1466 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1467 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1468 
1469 	ORDERKEY_SWAP(p1, p2);
1470 	ORDERKEY_PCTCPU(p1, p2);
1471 	ORDERKEY_CPTICKS(p1, p2);
1472 	ORDERKEY_STATE(p1, p2);
1473 	ORDERKEY_PRIO(p1, p2);
1474 	ORDERKEY_RSSIZE(p1, p2);
1475 	ORDERKEY_MEM(p1, p2);
1476 
1477 	return (0);
1478 }
1479 
1480 /* assorted comparison functions for sorting by i/o */
1481 
1482 static int
1483 compare_iototal(const void *arg1, const void *arg2)
1484 {
1485 	const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1486 	const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1487 
1488 	return (get_io_total(p2) - get_io_total(p1));
1489 }
1490 
1491 static int
1492 compare_ioread(const void *arg1, const void *arg2)
1493 {
1494 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1495 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1496 	long dummy, inp1, inp2;
1497 
1498 	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1499 	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1500 
1501 	return (inp2 - inp1);
1502 }
1503 
1504 static int
1505 compare_iowrite(const void *arg1, const void *arg2)
1506 {
1507 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1508 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1509 	long dummy, oup1, oup2;
1510 
1511 	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1512 	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1513 
1514 	return (oup2 - oup1);
1515 }
1516 
1517 static int
1518 compare_iofault(const void *arg1, const void *arg2)
1519 {
1520 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1521 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1522 	long dummy, flp1, flp2;
1523 
1524 	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1525 	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1526 
1527 	return (flp2 - flp1);
1528 }
1529 
1530 static int
1531 compare_vcsw(const void *arg1, const void *arg2)
1532 {
1533 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1534 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1535 	long dummy, flp1, flp2;
1536 
1537 	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1538 	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1539 
1540 	return (flp2 - flp1);
1541 }
1542 
1543 static int
1544 compare_ivcsw(const void *arg1, const void *arg2)
1545 {
1546 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1547 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1548 	long dummy, flp1, flp2;
1549 
1550 	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1551 	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1552 
1553 	return (flp2 - flp1);
1554 }
1555 
1556 int (*compares[])(const void *arg1, const void *arg2) = {
1557 	compare_cpu,
1558 	compare_size,
1559 	compare_res,
1560 	compare_time,
1561 	compare_prio,
1562 	compare_threads,
1563 	compare_iototal,
1564 	compare_ioread,
1565 	compare_iowrite,
1566 	compare_iofault,
1567 	compare_vcsw,
1568 	compare_ivcsw,
1569 	compare_jid,
1570 	compare_swap,
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