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