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