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