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