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