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