machine.c revision 158280
1126756Smlaier/*
2163621Sdelphij * top - a top users display for Unix
3126756Smlaier *
4126756Smlaier * SYNOPSIS:  For FreeBSD-2.x and later
5126756Smlaier *
6126756Smlaier * DESCRIPTION:
7126756Smlaier * Originally written for BSD4.4 system by Christos Zoulas.
8126756Smlaier * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9126756Smlaier * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10126756Smlaier *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
11126756Smlaier *
12126756Smlaier * This is the machine-dependent module for FreeBSD 2.2
13126756Smlaier * Works for:
14126756Smlaier *	FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
15126756Smlaier *
16126756Smlaier * LIBS: -lkvm
17126756Smlaier *
18126756Smlaier * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
19126756Smlaier *          Steven Wallace  <swallace@freebsd.org>
20126756Smlaier *          Wolfram Schneider <wosch@FreeBSD.org>
21126756Smlaier *          Thomas Moestl <tmoestl@gmx.net>
22126756Smlaier *
23126756Smlaier * $FreeBSD: head/usr.bin/top/machine.c 158280 2006-05-04 03:00:13Z bde $
24126756Smlaier */
25135183Smlaier
26135183Smlaier#include <sys/param.h>
27126756Smlaier#include <sys/errno.h>
28126756Smlaier#include <sys/file.h>
29126756Smlaier#include <sys/proc.h>
30126756Smlaier#include <sys/resource.h>
31126756Smlaier#include <sys/rtprio.h>
32126756Smlaier#include <sys/signal.h>
33126756Smlaier#include <sys/sysctl.h>
34126756Smlaier#include <sys/time.h>
35126756Smlaier#include <sys/user.h>
36126756Smlaier#include <sys/vmmeter.h>
37126756Smlaier
38126756Smlaier#include <kvm.h>
39126756Smlaier#include <math.h>
40126756Smlaier#include <nlist.h>
41126756Smlaier#include <paths.h>
42126756Smlaier#include <pwd.h>
43126756Smlaier#include <stdio.h>
44126756Smlaier#include <stdlib.h>
45126756Smlaier#include <string.h>
46126756Smlaier#include <strings.h>
47126756Smlaier#include <unistd.h>
48126756Smlaier
49126756Smlaier#include "top.h"
50126756Smlaier#include "machine.h"
51126756Smlaier#include "screen.h"
52126756Smlaier#include "utils.h"
53126756Smlaier
54126756Smlaierstatic void getsysctl(char *, void *, size_t);
55126756Smlaier
56126756Smlaier#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
57126756Smlaier#define	SMPUNAMELEN	13
58126756Smlaier#define	UPUNAMELEN	15
59126756Smlaier
60126756Smlaierextern struct process_select ps;
61126756Smlaierextern char* printable(char *);
62126756Smlaierint swapmode(int *retavail, int *retfree);
63126756Smlaierstatic int smpmode;
64126756Smlaierenum displaymodes displaymode;
65126756Smlaierstatic int namelength = 8;
66126756Smlaierstatic int cmdlengthdelta;
67126756Smlaier
68126756Smlaier/* Prototypes for top internals */
69126756Smlaiervoid quit(int);
70126756Smlaierint compare_pid(const void *a, const void *b);
71126756Smlaier
72126756Smlaier/* get_process_info passes back a handle.  This is what it looks like: */
73126756Smlaier
74126756Smlaierstruct handle {
75126756Smlaier	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
76126756Smlaier	int remaining;			/* number of pointers remaining */
77126756Smlaier};
78126756Smlaier
79126756Smlaier/* declarations for load_avg */
80126756Smlaier#include "loadavg.h"
81126756Smlaier
82126756Smlaier/* define what weighted cpu is.  */
83126756Smlaier#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
84126756Smlaier			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
85126756Smlaier
86126756Smlaier/* what we consider to be process size: */
87126756Smlaier#define PROCSIZE(pp) ((pp)->ki_size / 1024)
88126756Smlaier
89126756Smlaier#define RU(pp)	(&(pp)->ki_rusage)
90126756Smlaier#define RUTOT(pp) \
91126756Smlaier	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
92126756Smlaier
93126756Smlaier
94126756Smlaier/* definitions for indices in the nlist array */
95126756Smlaier
96126756Smlaier/*
97126756Smlaier *  These definitions control the format of the per-process area
98126756Smlaier */
99126756Smlaier
100126756Smlaierstatic char io_header[] =
101126756Smlaier    "  PID %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
102126756Smlaier
103126756Smlaier#define io_Proc_format \
104126756Smlaier    "%5d %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
105126756Smlaier
106126756Smlaierstatic char smp_header_thr[] =
107126756Smlaier    "  PID %-*.*s  THR PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
108126756Smlaierstatic char smp_header[] =
109126756Smlaier    "  PID %-*.*s "   "PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
110126756Smlaier
111126756Smlaier#define smp_Proc_format \
112126756Smlaier    "%5d %-*.*s %s%3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
113126756Smlaier
114126756Smlaierstatic char up_header_thr[] =
115126756Smlaier    "  PID %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
116126756Smlaierstatic char up_header[] =
117126756Smlaier    "  PID %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
118126756Smlaier
119126756Smlaier#define up_Proc_format \
120126756Smlaier    "%5d %-*.*s %s%3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
121126756Smlaier
122126756Smlaier
123126756Smlaier/* process state names for the "STATE" column of the display */
124126756Smlaier/* the extra nulls in the string "run" are for adding a slash and
125126756Smlaier   the processor number when needed */
126126756Smlaier
127126756Smlaierchar *state_abbrev[] = {
128126756Smlaier	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
129126756Smlaier};
130126756Smlaier
131126756Smlaier
132126756Smlaierstatic kvm_t *kd;
133126756Smlaier
134126756Smlaier/* values that we stash away in _init and use in later routines */
135126756Smlaier
136126756Smlaierstatic double logcpu;
137126756Smlaier
138126756Smlaier/* these are retrieved from the kernel in _init */
139126756Smlaier
140126756Smlaierstatic load_avg  ccpu;
141126756Smlaier
142126756Smlaier/* these are used in the get_ functions */
143126756Smlaier
144126756Smlaierstatic int lastpid;
145135183Smlaier
146135183Smlaier/* these are for calculating cpu state percentages */
147126756Smlaier
148126756Smlaierstatic long cp_time[CPUSTATES];
149126756Smlaierstatic long cp_old[CPUSTATES];
150126756Smlaierstatic long cp_diff[CPUSTATES];
151126756Smlaier
152126756Smlaier/* these are for detailing the process states */
153126756Smlaier
154126756Smlaierint process_states[8];
155135183Smlaierchar *procstatenames[] = {
156135183Smlaier	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
157135183Smlaier	" zombie, ", " waiting, ", " lock, ",
158135183Smlaier	NULL
159126756Smlaier};
160126756Smlaier
161126756Smlaier/* these are for detailing the cpu states */
162126756Smlaier
163126756Smlaierint cpu_states[CPUSTATES];
164126756Smlaierchar *cpustatenames[] = {
165126756Smlaier	"user", "nice", "system", "interrupt", "idle", NULL
166126756Smlaier};
167126756Smlaier
168126756Smlaier/* these are for detailing the memory statistics */
169126756Smlaier
170126756Smlaierint memory_stats[7];
171126756Smlaierchar *memorynames[] = {
172126756Smlaier	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
173126756Smlaier	"K Free", NULL
174126756Smlaier};
175126756Smlaier
176126756Smlaierint swap_stats[7];
177126756Smlaierchar *swapnames[] = {
178126756Smlaier	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
179126756Smlaier	NULL
180126756Smlaier};
181126756Smlaier
182126756Smlaier
183126756Smlaier/* these are for keeping track of the proc array */
184126756Smlaier
185126756Smlaierstatic int nproc;
186126756Smlaierstatic int onproc = -1;
187126756Smlaierstatic int pref_len;
188126756Smlaierstatic struct kinfo_proc *pbase;
189126756Smlaierstatic struct kinfo_proc **pref;
190126756Smlaierstatic struct kinfo_proc *previous_procs;
191126756Smlaierstatic struct kinfo_proc **previous_pref;
192126756Smlaierstatic int previous_proc_count = 0;
193126756Smlaierstatic int previous_proc_count_max = 0;
194126756Smlaier
195126756Smlaier/* total number of io operations */
196126756Smlaierstatic long total_inblock;
197126756Smlaierstatic long total_oublock;
198126756Smlaierstatic long total_majflt;
199126756Smlaier
200126756Smlaier/* these are for getting the memory statistics */
201135183Smlaier
202126756Smlaierstatic int pageshift;		/* log base 2 of the pagesize */
203126756Smlaier
204126756Smlaier/* define pagetok in terms of pageshift */
205126756Smlaier
206126756Smlaier#define pagetok(size) ((size) << pageshift)
207126756Smlaier
208126756Smlaier/* useful externals */
209126756Smlaierlong percentages();
210126756Smlaier
211126756Smlaier#ifdef ORDER
212126756Smlaier/*
213126756Smlaier * Sorting orders.  The first element is the default.
214135183Smlaier */
215126756Smlaierchar *ordernames[] = {
216126756Smlaier	"cpu", "size", "res", "time", "pri", "threads",
217126756Smlaier	"total", "read", "write", "fault", "vcsw", "ivcsw", NULL
218126756Smlaier};
219126756Smlaier#endif
220126756Smlaier
221126756Smlaierint
222126756Smlaiermachine_init(struct statics *statics)
223126756Smlaier{
224126756Smlaier	int pagesize;
225126756Smlaier	size_t modelen;
226163621Sdelphij	struct passwd *pw;
227163621Sdelphij
228163621Sdelphij	modelen = sizeof(smpmode);
229163621Sdelphij	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
230126756Smlaier	    NULL, 0) != 0 &&
231135183Smlaier	    sysctlbyname("kern.smp.active", &smpmode, &modelen,
232126756Smlaier	    NULL, 0) != 0) ||
233135183Smlaier	    modelen != sizeof(smpmode))
234135183Smlaier		smpmode = 0;
235126756Smlaier
236126756Smlaier	while ((pw = getpwent()) != NULL) {
237126756Smlaier		if (strlen(pw->pw_name) > namelength)
238126756Smlaier			namelength = strlen(pw->pw_name);
239126756Smlaier	}
240126756Smlaier	if (smpmode && namelength > SMPUNAMELEN)
241126756Smlaier		namelength = SMPUNAMELEN;
242126756Smlaier	else if (namelength > UPUNAMELEN)
243126756Smlaier		namelength = UPUNAMELEN;
244126756Smlaier
245126756Smlaier	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
246126756Smlaier	if (kd == NULL)
247126756Smlaier		return (-1);
248126756Smlaier
249126756Smlaier	GETSYSCTL("kern.ccpu", ccpu);
250126756Smlaier
251126756Smlaier	/* this is used in calculating WCPU -- calculate it ahead of time */
252126756Smlaier	logcpu = log(loaddouble(ccpu));
253126756Smlaier
254126756Smlaier	pbase = NULL;
255126756Smlaier	pref = NULL;
256126756Smlaier	nproc = 0;
257126756Smlaier	onproc = -1;
258126756Smlaier
259126756Smlaier	/* get the page size and calculate pageshift from it */
260126756Smlaier	pagesize = getpagesize();
261126756Smlaier	pageshift = 0;
262126756Smlaier	while (pagesize > 1) {
263126756Smlaier		pageshift++;
264163621Sdelphij		pagesize >>= 1;
265163621Sdelphij	}
266163621Sdelphij
267126756Smlaier	/* we only need the amount of log(2)1024 for our conversion */
268126756Smlaier	pageshift -= LOG1024;
269126756Smlaier
270126756Smlaier	/* fill in the statics information */
271126756Smlaier	statics->procstate_names = procstatenames;
272163621Sdelphij	statics->cpustate_names = cpustatenames;
273126756Smlaier	statics->memory_names = memorynames;
274163621Sdelphij	statics->swap_names = swapnames;
275126756Smlaier#ifdef ORDER
276163621Sdelphij	statics->order_names = ordernames;
277163621Sdelphij#endif
278163621Sdelphij
279163621Sdelphij	/* all done! */
280126756Smlaier	return (0);
281135183Smlaier}
282163621Sdelphij
283163621Sdelphijchar *
284163621Sdelphijformat_header(char *uname_field)
285163621Sdelphij{
286135183Smlaier	static char Header[128];
287126756Smlaier	const char *prehead;
288126756Smlaier
289126756Smlaier	switch (displaymode) {
290126756Smlaier	case DISP_CPU:
291135183Smlaier		/*
292126756Smlaier		 * The logic of picking the right header format seems reverse
293126756Smlaier		 * here because we only want to display a THR column when
294126756Smlaier		 * "thread mode" is off (and threads are not listed as
295126756Smlaier		 * separate lines).
296135183Smlaier		 */
297135183Smlaier		prehead = smpmode ?
298126756Smlaier		    (ps.thread ? smp_header : smp_header_thr) :
299126756Smlaier		    (ps.thread ? up_header : up_header_thr);
300126756Smlaier		snprintf(Header, sizeof(Header), prehead,
301126756Smlaier		    namelength, namelength, uname_field,
302163621Sdelphij		    ps.wcpu ? "WCPU" : "CPU");
303163621Sdelphij		break;
304163621Sdelphij	case DISP_IO:
305163621Sdelphij		prehead = io_header;
306126756Smlaier		snprintf(Header, sizeof(Header), prehead,
307163621Sdelphij		    namelength, namelength, uname_field);
308126756Smlaier		break;
309126756Smlaier	}
310126756Smlaier	cmdlengthdelta = strlen(Header) - 7;
311126756Smlaier	return (Header);
312126756Smlaier}
313126756Smlaier
314126756Smlaierstatic int swappgsin = -1;
315126756Smlaierstatic int swappgsout = -1;
316126756Smlaierextern struct timeval timeout;
317126756Smlaier
318126756Smlaiervoid
319126756Smlaierget_system_info(struct system_info *si)
320135183Smlaier{
321135183Smlaier	long total;
322163621Sdelphij	struct loadavg sysload;
323163621Sdelphij	int mib[2];
324135183Smlaier	struct timeval boottime;
325126756Smlaier	size_t bt_size;
326126756Smlaier	int i;
327126756Smlaier
328126756Smlaier	/* get the cp_time array */
329126756Smlaier	GETSYSCTL("kern.cp_time", cp_time);
330126756Smlaier	GETSYSCTL("vm.loadavg", sysload);
331126756Smlaier	GETSYSCTL("kern.lastpid", lastpid);
332126756Smlaier
333126756Smlaier	/* convert load averages to doubles */
334126756Smlaier	for (i = 0; i < 3; i++)
335163621Sdelphij		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
336163621Sdelphij
337163621Sdelphij	/* convert cp_time counts to percentages */
338126756Smlaier	total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
339126756Smlaier
340135183Smlaier	/* sum memory & swap statistics */
341126756Smlaier	{
342126756Smlaier		static unsigned int swap_delay = 0;
343126756Smlaier		static int swapavail = 0;
344126756Smlaier		static int swapfree = 0;
345126756Smlaier		static int bufspace = 0;
346126756Smlaier		static int nspgsin, nspgsout;
347126756Smlaier
348126756Smlaier		GETSYSCTL("vfs.bufspace", bufspace);
349126756Smlaier		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
350126756Smlaier		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
351135183Smlaier		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
352135183Smlaier		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
353135183Smlaier		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
354135183Smlaier		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
355126756Smlaier		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
356126756Smlaier		/* convert memory stats to Kbytes */
357135183Smlaier		memory_stats[0] = pagetok(memory_stats[0]);
358135183Smlaier		memory_stats[1] = pagetok(memory_stats[1]);
359135183Smlaier		memory_stats[2] = pagetok(memory_stats[2]);
360126756Smlaier		memory_stats[3] = pagetok(memory_stats[3]);
361135183Smlaier		memory_stats[4] = bufspace / 1024;
362126756Smlaier		memory_stats[5] = pagetok(memory_stats[5]);
363126756Smlaier		memory_stats[6] = -1;
364135183Smlaier
365135183Smlaier		/* first interval */
366135183Smlaier		if (swappgsin < 0) {
367135183Smlaier			swap_stats[4] = 0;
368135183Smlaier			swap_stats[5] = 0;
369135183Smlaier		}
370126756Smlaier
371135183Smlaier		/* compute differences between old and new swap statistic */
372135183Smlaier		else {
373135183Smlaier			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
374126756Smlaier			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
375135183Smlaier		}
376135183Smlaier
377135183Smlaier		swappgsin = nspgsin;
378135183Smlaier		swappgsout = nspgsout;
379126756Smlaier
380135183Smlaier		/* call CPU heavy swapmode() only for changes */
381135183Smlaier		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
382135183Smlaier			swap_stats[3] = swapmode(&swapavail, &swapfree);
383135183Smlaier			swap_stats[0] = swapavail;
384126756Smlaier			swap_stats[1] = swapavail - swapfree;
385126756Smlaier			swap_stats[2] = swapfree;
386126756Smlaier		}
387135183Smlaier		swap_delay = 1;
388126756Smlaier		swap_stats[6] = -1;
389126756Smlaier	}
390126756Smlaier
391135183Smlaier	/* set arrays and strings */
392126756Smlaier	si->cpustates = cpu_states;
393126756Smlaier	si->memory = memory_stats;
394126756Smlaier	si->swap = swap_stats;
395126756Smlaier
396126756Smlaier
397126756Smlaier	if (lastpid > 0) {
398126756Smlaier		si->last_pid = lastpid;
399126756Smlaier	} else {
400135183Smlaier		si->last_pid = -1;
401135183Smlaier	}
402126756Smlaier
403126756Smlaier	/*
404130151Sschweikh	 * Print how long system has been up.
405126756Smlaier	 * (Found by looking getting "boottime" from the kernel)
406126756Smlaier	 */
407126756Smlaier	mib[0] = CTL_KERN;
408126756Smlaier	mib[1] = KERN_BOOTTIME;
409126756Smlaier	bt_size = sizeof(boottime);
410126756Smlaier	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
411135183Smlaier	    boottime.tv_sec != 0) {
412135183Smlaier		si->boottime = boottime;
413135183Smlaier	} else {
414135183Smlaier		si->boottime.tv_sec = -1;
415135183Smlaier	}
416135183Smlaier}
417135183Smlaier
418126756Smlaier#define NOPROC	((void *)-1)
419135183Smlaier
420135183Smlaier/*
421135183Smlaier * We need to compare data from the old process entry with the new
422135183Smlaier * process entry.
423135183Smlaier * To facilitate doing this quickly we stash a pointer in the kinfo_proc
424135183Smlaier * structure to cache the mapping.  We also use a negative cache pointer
425135183Smlaier * of NOPROC to avoid duplicate lookups.
426135183Smlaier * XXX: this could be done when the actual processes are fetched, we do
427135183Smlaier * it here out of laziness.
428135183Smlaier */
429126756Smlaierconst struct kinfo_proc *
430126756Smlaierget_old_proc(struct kinfo_proc *pp)
431135183Smlaier{
432135183Smlaier	struct kinfo_proc **oldpp, *oldp;
433135183Smlaier
434135183Smlaier	/*
435135183Smlaier	 * If this is the first fetch of the kinfo_procs then we don't have
436126756Smlaier	 * any previous entries.
437163621Sdelphij	 */
438163621Sdelphij	if (previous_proc_count == 0)
439163621Sdelphij		return (NULL);
440163621Sdelphij	/* negative cache? */
441163621Sdelphij	if (pp->ki_udata == NOPROC)
442135183Smlaier		return (NULL);
443135183Smlaier	/* cached? */
444135183Smlaier	if (pp->ki_udata != NULL)
445126756Smlaier		return (pp->ki_udata);
446126756Smlaier	/*
447126756Smlaier	 * Not cached,
448126756Smlaier	 * 1) look up based on pid.
449126756Smlaier	 * 2) compare process start.
450126756Smlaier	 * If we fail here, then setup a negative cache entry, otherwise
451126756Smlaier	 * cache it.
452126756Smlaier	 */
453126756Smlaier	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
454126756Smlaier	    sizeof(*previous_pref), compare_pid);
455126756Smlaier	if (oldpp == NULL) {
456126756Smlaier		pp->ki_udata = NOPROC;
457126756Smlaier		return (NULL);
458126756Smlaier	}
459126756Smlaier	oldp = *oldpp;
460135183Smlaier	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
461126756Smlaier		pp->ki_udata = NOPROC;
462135183Smlaier		return (NULL);
463135183Smlaier	}
464135183Smlaier	pp->ki_udata = oldp;
465135183Smlaier	return (oldp);
466163621Sdelphij}
467126756Smlaier
468126756Smlaier/*
469126756Smlaier * Return the total amount of IO done in blocks in/out and faults.
470126756Smlaier * store the values individually in the pointers passed in.
471126756Smlaier */
472126756Smlaierlong
473126756Smlaierget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
474126756Smlaier    long *vcsw, long *ivcsw)
475126756Smlaier{
476126756Smlaier	const struct kinfo_proc *oldp;
477126756Smlaier	static struct kinfo_proc dummy;
478126756Smlaier	long ret;
479126756Smlaier
480163621Sdelphij	oldp = get_old_proc(pp);
481126756Smlaier	if (oldp == NULL) {
482126756Smlaier		bzero(&dummy, sizeof(dummy));
483126756Smlaier		oldp = &dummy;
484126756Smlaier	}
485126756Smlaier	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
486126756Smlaier	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
487126756Smlaier	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
488126756Smlaier	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
489126756Smlaier	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
490126756Smlaier	ret =
491126756Smlaier	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
492126756Smlaier	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
493126756Smlaier	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
494135183Smlaier	return (ret);
495135183Smlaier}
496126756Smlaier
497126756Smlaier/*
498126756Smlaier * Return the total number of block in/out and faults by a process.
499126756Smlaier */
500126756Smlaierlong
501126756Smlaierget_io_total(struct kinfo_proc *pp)
502126756Smlaier{
503126756Smlaier	long dummy;
504126756Smlaier
505126756Smlaier	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
506126756Smlaier}
507126756Smlaier
508126756Smlaierstatic struct handle handle;
509135183Smlaier
510126756Smlaiercaddr_t
511135183Smlaierget_process_info(struct system_info *si, struct process_select *sel,
512135183Smlaier    int (*compare)(const void *, const void *))
513135183Smlaier{
514126756Smlaier	int i;
515135183Smlaier	int total_procs;
516163621Sdelphij	long p_io;
517135183Smlaier	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
518126756Smlaier	int active_procs;
519126756Smlaier	struct kinfo_proc **prefp;
520126756Smlaier	struct kinfo_proc *pp;
521126756Smlaier	struct kinfo_proc *prev_pp = NULL;
522163621Sdelphij
523126756Smlaier	/* these are copied out of sel for speed */
524135183Smlaier	int show_idle;
525135183Smlaier	int show_self;
526135183Smlaier	int show_system;
527163621Sdelphij	int show_uid;
528135183Smlaier	int show_command;
529135183Smlaier
530135183Smlaier	/*
531135183Smlaier	 * Save the previous process info.
532135183Smlaier	 */
533135183Smlaier	if (previous_proc_count_max < nproc) {
534135183Smlaier		free(previous_procs);
535163621Sdelphij		previous_procs = malloc(nproc * sizeof(*previous_procs));
536163621Sdelphij		free(previous_pref);
537163621Sdelphij		previous_pref = malloc(nproc * sizeof(*previous_pref));
538163621Sdelphij		if (previous_procs == NULL || previous_pref == NULL) {
539135183Smlaier			(void) fprintf(stderr, "top: Out of memory.\n");
540135183Smlaier			quit(23);
541135183Smlaier		}
542135183Smlaier		previous_proc_count_max = nproc;
543135183Smlaier	}
544135183Smlaier	if (nproc) {
545135183Smlaier		for (i = 0; i < nproc; i++)
546135183Smlaier			previous_pref[i] = &previous_procs[i];
547135183Smlaier		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
548135183Smlaier		qsort(previous_pref, nproc, sizeof(*previous_pref),
549135183Smlaier		    compare_pid);
550135183Smlaier	}
551135183Smlaier	previous_proc_count = nproc;
552126756Smlaier
553126756Smlaier	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
554126756Smlaier	if (nproc > onproc)
555126756Smlaier		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
556126756Smlaier	if (pref == NULL || pbase == NULL) {
557126756Smlaier		(void) fprintf(stderr, "top: Out of memory.\n");
558126756Smlaier		quit(23);
559126756Smlaier	}
560126756Smlaier	/* get a pointer to the states summary array */
561126756Smlaier	si->procstates = process_states;
562135183Smlaier
563135183Smlaier	/* set up flags which define what we are going to select */
564135183Smlaier	show_idle = sel->idle;
565135183Smlaier	show_self = sel->self == -1;
566135183Smlaier	show_system = sel->system;
567135183Smlaier	show_uid = sel->uid != -1;
568135183Smlaier	show_command = sel->command != NULL;
569135183Smlaier
570163621Sdelphij	/* count up process states and get pointers to interesting procs */
571135183Smlaier	total_procs = 0;
572163621Sdelphij	active_procs = 0;
573163621Sdelphij	total_inblock = 0;
574126756Smlaier	total_oublock = 0;
575126756Smlaier	total_majflt = 0;
576126756Smlaier	memset((char *)process_states, 0, sizeof(process_states));
577126756Smlaier	prefp = pref;
578126756Smlaier	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
579126756Smlaier
580126756Smlaier		if (pp->ki_stat == 0)
581126756Smlaier			/* not in use */
582126756Smlaier			continue;
583126756Smlaier
584126756Smlaier		if (!show_self && pp->ki_pid == sel->self)
585126756Smlaier			/* skip self */
586126756Smlaier			continue;
587126756Smlaier
588135183Smlaier		if (!show_system && (pp->ki_flag & P_SYSTEM))
589126756Smlaier			/* skip system process */
590126756Smlaier			continue;
591135183Smlaier
592126756Smlaier		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
593135183Smlaier		    &p_vcsw, &p_ivcsw);
594135183Smlaier		total_inblock += p_inblock;
595135183Smlaier		total_oublock += p_oublock;
596126756Smlaier		total_majflt += p_majflt;
597126756Smlaier		total_procs++;
598126756Smlaier		process_states[pp->ki_stat]++;
599126756Smlaier
600126756Smlaier		if (pp->ki_stat == SZOMB)
601126756Smlaier			/* skip zombies */
602126756Smlaier			continue;
603126756Smlaier
604126756Smlaier		if (displaymode == DISP_CPU && !show_idle &&
605163621Sdelphij		    (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN))
606163621Sdelphij			/* skip idle or non-running processes */
607163621Sdelphij			continue;
608163621Sdelphij
609126756Smlaier		if (displaymode == DISP_IO && !show_idle && p_io == 0)
610126756Smlaier			/* skip processes that aren't doing I/O */
611126756Smlaier			continue;
612126756Smlaier
613126756Smlaier		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
614126756Smlaier			/* skip proc. that don't belong to the selected UID */
615126756Smlaier			continue;
616135183Smlaier
617163621Sdelphij		/*
618163621Sdelphij		 * When not showing threads, take the first thread
619126756Smlaier		 * for output and add the fields that we can from
620126756Smlaier		 * the rest of the process's threads rather than
621126756Smlaier		 * using the system's mostly-broken KERN_PROC_PROC.
622163621Sdelphij		 */
623163621Sdelphij		if (sel->thread || prev_pp == NULL ||
624163621Sdelphij		    prev_pp->ki_pid != pp->ki_pid) {
625163621Sdelphij			*prefp++ = pp;
626126756Smlaier			active_procs++;
627163621Sdelphij			prev_pp = pp;
628126756Smlaier		} else {
629126756Smlaier			prev_pp->ki_pctcpu += pp->ki_pctcpu;
630126756Smlaier		}
631126756Smlaier	}
632126756Smlaier
633126756Smlaier	/* if requested, sort the "interesting" processes */
634126756Smlaier	if (compare != NULL)
635126756Smlaier		qsort(pref, active_procs, sizeof(*pref), compare);
636135183Smlaier
637135183Smlaier	/* remember active and total counts */
638126756Smlaier	si->p_total = total_procs;
639126756Smlaier	si->p_active = pref_len = active_procs;
640126756Smlaier
641163621Sdelphij	/* pass back a handle */
642126756Smlaier	handle.next_proc = pref;
643126756Smlaier	handle.remaining = active_procs;
644126756Smlaier	return ((caddr_t)&handle);
645126756Smlaier}
646126756Smlaier
647126756Smlaierstatic char fmt[128];	/* static area where result is built */
648126756Smlaier
649126756Smlaierchar *
650126756Smlaierformat_next_process(caddr_t handle, char *(*get_userid)(int))
651126756Smlaier{
652163621Sdelphij	struct kinfo_proc *pp;
653163621Sdelphij	const struct kinfo_proc *oldp;
654163621Sdelphij	long cputime;
655163621Sdelphij	double pct;
656163621Sdelphij	struct handle *hp;
657163621Sdelphij	char status[16];
658126756Smlaier	int state;
659126756Smlaier	struct rusage ru, *rup;
660126756Smlaier	long p_tot, s_tot;
661126756Smlaier	char *proc_fmt, thr_buf[6];
662126756Smlaier
663163621Sdelphij	/* find and remember the next proc structure */
664163621Sdelphij	hp = (struct handle *)handle;
665163621Sdelphij	pp = *(hp->next_proc++);
666163621Sdelphij	hp->remaining--;
667163621Sdelphij
668163621Sdelphij	/* get the process's command name */
669126756Smlaier	if ((pp->ki_sflag & PS_INMEM) == 0) {
670126756Smlaier		/*
671126756Smlaier		 * Print swapped processes as <pname>
672126756Smlaier		 */
673126756Smlaier		size_t len;
674126756Smlaier
675126756Smlaier		len = strlen(pp->ki_comm);
676126756Smlaier		if (len > sizeof(pp->ki_comm) - 3)
677126756Smlaier			len = sizeof(pp->ki_comm) - 3;
678163621Sdelphij		memmove(pp->ki_comm + 1, pp->ki_comm, len);
679163621Sdelphij		pp->ki_comm[0] = '<';
680126756Smlaier		pp->ki_comm[len + 1] = '>';
681126756Smlaier		pp->ki_comm[len + 2] = '\0';
682126756Smlaier	}
683135183Smlaier
684126756Smlaier	/*
685126756Smlaier	 * Convert the process's runtime from microseconds to seconds.  This
686135183Smlaier	 * time includes the interrupt time although that is not wanted here.
687135183Smlaier	 * ps(1) is similarly sloppy.
688	 */
689	cputime = (pp->ki_runtime + 500000) / 1000000;
690
691	/* calculate the base for cpu percentages */
692	pct = pctdouble(pp->ki_pctcpu);
693
694	/* generate "STATE" field */
695	switch (state = pp->ki_stat) {
696	case SRUN:
697		if (smpmode && pp->ki_oncpu != 0xff)
698			sprintf(status, "CPU%d", pp->ki_oncpu);
699		else
700			strcpy(status, "RUN");
701		break;
702	case SLOCK:
703		if (pp->ki_kiflag & KI_LOCKBLOCK) {
704			sprintf(status, "*%.6s", pp->ki_lockname);
705			break;
706		}
707		/* fall through */
708	case SSLEEP:
709		if (pp->ki_wmesg != NULL) {
710			sprintf(status, "%.6s", pp->ki_wmesg);
711			break;
712		}
713		/* FALLTHROUGH */
714	default:
715
716		if (state >= 0 &&
717		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
718			sprintf(status, "%.6s", state_abbrev[state]);
719		else
720			sprintf(status, "?%5d", state);
721		break;
722	}
723
724	if (displaymode == DISP_IO) {
725		oldp = get_old_proc(pp);
726		if (oldp != NULL) {
727			ru.ru_inblock = RU(pp)->ru_inblock -
728			    RU(oldp)->ru_inblock;
729			ru.ru_oublock = RU(pp)->ru_oublock -
730			    RU(oldp)->ru_oublock;
731			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
732			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
733			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
734			rup = &ru;
735		} else {
736			rup = RU(pp);
737		}
738		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
739		s_tot = total_inblock + total_oublock + total_majflt;
740
741		sprintf(fmt, io_Proc_format,
742		    pp->ki_pid,
743		    namelength, namelength, (*get_userid)(pp->ki_ruid),
744		    rup->ru_nvcsw,
745		    rup->ru_nivcsw,
746		    rup->ru_inblock,
747		    rup->ru_oublock,
748		    rup->ru_majflt,
749		    p_tot,
750		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
751		    screen_width > cmdlengthdelta ?
752		    screen_width - cmdlengthdelta : 0,
753		    printable(pp->ki_comm));
754		return (fmt);
755	}
756
757	/* format this entry */
758	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
759	if (ps.thread != 0)
760		thr_buf[0] = '\0';
761	else
762		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
763		    sizeof(thr_buf) - 2, pp->ki_numthreads);
764
765	sprintf(fmt, proc_fmt,
766	    pp->ki_pid,
767	    namelength, namelength, (*get_userid)(pp->ki_ruid),
768	    thr_buf,
769	    pp->ki_pri.pri_level - PZERO,
770
771	    /*
772	     * normal time      -> nice value -20 - +20
773	     * real time 0 - 31 -> nice value -52 - -21
774	     * idle time 0 - 31 -> nice value +21 - +52
775	     */
776	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
777		pp->ki_nice - NZERO :
778		(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
779		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
780		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
781	    format_k2(PROCSIZE(pp)),
782	    format_k2(pagetok(pp->ki_rssize)),
783	    status,
784	    smpmode ? pp->ki_lastcpu : 0,
785	    format_time(cputime),
786	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
787	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
788	    printable(pp->ki_comm));
789
790	/* return the result */
791	return (fmt);
792}
793
794static void
795getsysctl(char *name, void *ptr, size_t len)
796{
797	size_t nlen = len;
798
799	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
800		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
801		    strerror(errno));
802		quit(23);
803	}
804	if (nlen != len) {
805		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
806		    name, (unsigned long)len, (unsigned long)nlen);
807		quit(23);
808	}
809}
810
811/* comparison routines for qsort */
812
813int
814compare_pid(const void *p1, const void *p2)
815{
816	const struct kinfo_proc * const *pp1 = p1;
817	const struct kinfo_proc * const *pp2 = p2;
818
819	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
820		abort();
821
822	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
823}
824
825/*
826 *  proc_compare - comparison function for "qsort"
827 *	Compares the resource consumption of two processes using five
828 *	distinct keys.  The keys (in descending order of importance) are:
829 *	percent cpu, cpu ticks, state, resident set size, total virtual
830 *	memory usage.  The process states are ordered as follows (from least
831 *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
832 *	array declaration below maps a process state index into a number
833 *	that reflects this ordering.
834 */
835
836static int sorted_state[] = {
837	0,	/* not used		*/
838	3,	/* sleep		*/
839	1,	/* ABANDONED (WAIT)	*/
840	6,	/* run			*/
841	5,	/* start		*/
842	2,	/* zombie		*/
843	4	/* stop			*/
844};
845
846
847#define ORDERKEY_PCTCPU(a, b) do { \
848	long diff; \
849	if (ps.wcpu) \
850		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
851		    (b))) - \
852		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
853		    (a))); \
854	else \
855		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
856	if (diff != 0) \
857		return (diff > 0 ? 1 : -1); \
858} while (0)
859
860#define ORDERKEY_CPTICKS(a, b) do { \
861	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
862	if (diff != 0) \
863		return (diff > 0 ? 1 : -1); \
864} while (0)
865
866#define ORDERKEY_STATE(a, b) do { \
867	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
868	if (diff != 0) \
869		return (diff > 0 ? 1 : -1); \
870} while (0)
871
872#define ORDERKEY_PRIO(a, b) do { \
873	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
874	if (diff != 0) \
875		return (diff > 0 ? 1 : -1); \
876} while (0)
877
878#define	ORDERKEY_THREADS(a, b) do { \
879	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
880	if (diff != 0) \
881		return (diff > 0 ? 1 : -1); \
882} while (0)
883
884#define ORDERKEY_RSSIZE(a, b) do { \
885	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
886	if (diff != 0) \
887		return (diff > 0 ? 1 : -1); \
888} while (0)
889
890#define ORDERKEY_MEM(a, b) do { \
891	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
892	if (diff != 0) \
893		return (diff > 0 ? 1 : -1); \
894} while (0)
895
896/* compare_cpu - the comparison function for sorting by cpu percentage */
897
898int
899#ifdef ORDER
900compare_cpu(void *arg1, void *arg2)
901#else
902proc_compare(void *arg1, void *arg2)
903#endif
904{
905	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
906	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
907
908	ORDERKEY_PCTCPU(p1, p2);
909	ORDERKEY_CPTICKS(p1, p2);
910	ORDERKEY_STATE(p1, p2);
911	ORDERKEY_PRIO(p1, p2);
912	ORDERKEY_RSSIZE(p1, p2);
913	ORDERKEY_MEM(p1, p2);
914
915	return (0);
916}
917
918#ifdef ORDER
919/* "cpu" compare routines */
920int compare_size(), compare_res(), compare_time(), compare_prio(),
921    compare_threads();
922
923/*
924 * "io" compare routines.  Context switches aren't i/o, but are displayed
925 * on the "io" display.
926 */
927int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
928    compare_vcsw(), compare_ivcsw();
929
930int (*compares[])() = {
931	compare_cpu,
932	compare_size,
933	compare_res,
934	compare_time,
935	compare_prio,
936	compare_threads,
937	compare_iototal,
938	compare_ioread,
939	compare_iowrite,
940	compare_iofault,
941	compare_vcsw,
942	compare_ivcsw,
943	NULL
944};
945
946/* compare_size - the comparison function for sorting by total memory usage */
947
948int
949compare_size(void *arg1, void *arg2)
950{
951	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
952	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
953
954	ORDERKEY_MEM(p1, p2);
955	ORDERKEY_RSSIZE(p1, p2);
956	ORDERKEY_PCTCPU(p1, p2);
957	ORDERKEY_CPTICKS(p1, p2);
958	ORDERKEY_STATE(p1, p2);
959	ORDERKEY_PRIO(p1, p2);
960
961	return (0);
962}
963
964/* compare_res - the comparison function for sorting by resident set size */
965
966int
967compare_res(void *arg1, void *arg2)
968{
969	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
970	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
971
972	ORDERKEY_RSSIZE(p1, p2);
973	ORDERKEY_MEM(p1, p2);
974	ORDERKEY_PCTCPU(p1, p2);
975	ORDERKEY_CPTICKS(p1, p2);
976	ORDERKEY_STATE(p1, p2);
977	ORDERKEY_PRIO(p1, p2);
978
979	return (0);
980}
981
982/* compare_time - the comparison function for sorting by total cpu time */
983
984int
985compare_time(void *arg1, void *arg2)
986{
987	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
988	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
989
990	ORDERKEY_CPTICKS(p1, p2);
991	ORDERKEY_PCTCPU(p1, p2);
992	ORDERKEY_STATE(p1, p2);
993	ORDERKEY_PRIO(p1, p2);
994	ORDERKEY_RSSIZE(p1, p2);
995	ORDERKEY_MEM(p1, p2);
996
997	return (0);
998}
999
1000/* compare_prio - the comparison function for sorting by priority */
1001
1002int
1003compare_prio(void *arg1, void *arg2)
1004{
1005	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1006	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1007
1008	ORDERKEY_PRIO(p1, p2);
1009	ORDERKEY_CPTICKS(p1, p2);
1010	ORDERKEY_PCTCPU(p1, p2);
1011	ORDERKEY_STATE(p1, p2);
1012	ORDERKEY_RSSIZE(p1, p2);
1013	ORDERKEY_MEM(p1, p2);
1014
1015	return (0);
1016}
1017
1018/* compare_threads - the comparison function for sorting by threads */
1019int
1020compare_threads(void *arg1, void *arg2)
1021{
1022	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1023	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1024
1025	ORDERKEY_THREADS(p1, p2);
1026	ORDERKEY_PCTCPU(p1, p2);
1027	ORDERKEY_CPTICKS(p1, p2);
1028	ORDERKEY_STATE(p1, p2);
1029	ORDERKEY_PRIO(p1, p2);
1030	ORDERKEY_RSSIZE(p1, p2);
1031	ORDERKEY_MEM(p1, p2);
1032
1033	return (0);
1034}
1035#endif /* ORDER */
1036
1037/* assorted comparison functions for sorting by i/o */
1038
1039int
1040#ifdef ORDER
1041compare_iototal(void *arg1, void *arg2)
1042#else
1043io_compare(void *arg1, void *arg2)
1044#endif
1045{
1046	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1047	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1048
1049	return (get_io_total(p2) - get_io_total(p1));
1050}
1051
1052#ifdef ORDER
1053int
1054compare_ioread(void *arg1, void *arg2)
1055{
1056	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1057	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1058	long dummy, inp1, inp2;
1059
1060	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1061	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1062
1063	return (inp2 - inp1);
1064}
1065
1066int
1067compare_iowrite(void *arg1, void *arg2)
1068{
1069	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1070	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1071	long dummy, oup1, oup2;
1072
1073	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1074	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1075
1076	return (oup2 - oup1);
1077}
1078
1079int
1080compare_iofault(void *arg1, void *arg2)
1081{
1082	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1083	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1084	long dummy, flp1, flp2;
1085
1086	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1087	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1088
1089	return (flp2 - flp1);
1090}
1091
1092int
1093compare_vcsw(void *arg1, void *arg2)
1094{
1095	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1096	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1097	long dummy, flp1, flp2;
1098
1099	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1100	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1101
1102	return (flp2 - flp1);
1103}
1104
1105int
1106compare_ivcsw(void *arg1, void *arg2)
1107{
1108	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1109	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1110	long dummy, flp1, flp2;
1111
1112	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1113	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1114
1115	return (flp2 - flp1);
1116}
1117#endif /* ORDER */
1118
1119/*
1120 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1121 *		the process does not exist.
1122 *		It is EXTREMLY IMPORTANT that this function work correctly.
1123 *		If top runs setuid root (as in SVR4), then this function
1124 *		is the only thing that stands in the way of a serious
1125 *		security problem.  It validates requests for the "kill"
1126 *		and "renice" commands.
1127 */
1128
1129int
1130proc_owner(int pid)
1131{
1132	int cnt;
1133	struct kinfo_proc **prefp;
1134	struct kinfo_proc *pp;
1135
1136	prefp = pref;
1137	cnt = pref_len;
1138	while (--cnt >= 0) {
1139		pp = *prefp++;
1140		if (pp->ki_pid == (pid_t)pid)
1141			return ((int)pp->ki_ruid);
1142	}
1143	return (-1);
1144}
1145
1146int
1147swapmode(int *retavail, int *retfree)
1148{
1149	int n;
1150	int pagesize = getpagesize();
1151	struct kvm_swap swapary[1];
1152
1153	*retavail = 0;
1154	*retfree = 0;
1155
1156#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1157
1158	n = kvm_getswapinfo(kd, swapary, 1, 0);
1159	if (n < 0 || swapary[0].ksw_total == 0)
1160		return (0);
1161
1162	*retavail = CONVERT(swapary[0].ksw_total);
1163	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1164
1165	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1166	return (n);
1167}
1168