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