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