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