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