machine.c revision 164058
124143Sjoerg/*
224143Sjoerg * top - a top users display for Unix
324143Sjoerg *
447901Sn_hibma * SYNOPSIS:  For FreeBSD-2.x and later
524143Sjoerg *
624143Sjoerg * DESCRIPTION:
724143Sjoerg * Originally written for BSD4.4 system by Christos Zoulas.
824143Sjoerg * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
938278Swosch * Order support hacked in from top-3.5beta6/machine/m_aix41.c
1038278Swosch *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
1124143Sjoerg *
1224143Sjoerg * This is the machine-dependent module for FreeBSD 2.2
1324143Sjoerg * Works for:
1447901Sn_hibma *	FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
1524143Sjoerg *
1624143Sjoerg * LIBS: -lkvm
1724143Sjoerg *
1824143Sjoerg * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
1924143Sjoerg *          Steven Wallace  <swallace@freebsd.org>
2024143Sjoerg *          Wolfram Schneider <wosch@FreeBSD.org>
2172951Srwatson *          Thomas Moestl <tmoestl@gmx.net>
2224143Sjoerg *
2350477Speter * $FreeBSD: head/usr.bin/top/machine.c 164058 2006-11-07 10:03:10Z bde $
2424143Sjoerg */
2524143Sjoerg
2624143Sjoerg#include <sys/param.h>
2724143Sjoerg#include <sys/errno.h>
28131621Sdes#include <sys/file.h>
29131621Sdes#include <sys/proc.h>
30131621Sdes#include <sys/resource.h>
31131621Sdes#include <sys/rtprio.h>
32131621Sdes#include <sys/signal.h>
3324143Sjoerg#include <sys/sysctl.h>
3424143Sjoerg#include <sys/time.h>
3524143Sjoerg#include <sys/user.h>
3624143Sjoerg#include <sys/vmmeter.h>
3724143Sjoerg
38131621Sdes#include <kvm.h>
39131621Sdes#include <math.h>
40131621Sdes#include <nlist.h>
41131626Sdes#include <paths.h>
42131621Sdes#include <pwd.h>
43131621Sdes#include <stdio.h>
4424143Sjoerg#include <stdlib.h>
45144636Sstefanf#include <string.h>
46144636Sstefanf#include <strings.h>
4772951Srwatson#include <unistd.h>
4824143Sjoerg
4924143Sjoerg#include "top.h"
5024143Sjoerg#include "machine.h"
5169375Sjhb#include "screen.h"
5272951Srwatson#include "utils.h"
5324143Sjoerg
5472951Srwatson#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
55146291Sobrien#define	SMPUNAMELEN	13
56146291Sobrien#define	UPUNAMELEN	15
5772951Srwatson
58145073Skeramidaextern struct process_select ps;
5992922Simpextern char* printable(char *);
6027340Speterstatic int smpmode;
61131402Salfredenum displaymodes displaymode;
62146291Sobrienstatic int namelength = 8;
6369375Sjhbstatic int cmdlengthdelta;
6424143Sjoerg
6572951Srwatson/* Prototypes for top internals */
6692922Simpvoid quit(int);
6724143Sjoerg
6824143Sjoerg/* get_process_info passes back a handle.  This is what it looks like: */
6924143Sjoerg
70158280Sbdestruct handle {
71131623Sdes	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
72131623Sdes	int remaining;			/* number of pointers remaining */
7324143Sjoerg};
7424143Sjoerg
7524143Sjoerg/* declarations for load_avg */
7624143Sjoerg#include "loadavg.h"
7724143Sjoerg
7824143Sjoerg/* define what weighted cpu is.  */
7969896Smckusick#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
8069896Smckusick			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
8124143Sjoerg
8224143Sjoerg/* what we consider to be process size: */
8369896Smckusick#define PROCSIZE(pp) ((pp)->ki_size / 1024)
8424143Sjoerg
85131402Salfred#define RU(pp)	(&(pp)->ki_rusage)
86131402Salfred#define RUTOT(pp) \
87131402Salfred	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
88131402Salfred
89131402Salfred
9024143Sjoerg/* definitions for indices in the nlist array */
9124143Sjoerg
9224143Sjoerg/*
9324143Sjoerg *  These definitions control the format of the per-process area
9424143Sjoerg */
9524143Sjoerg
96131402Salfredstatic char io_header[] =
97158280Sbde    "  PID %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
98131402Salfred
99131402Salfred#define io_Proc_format \
100158280Sbde    "%5d %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
101131402Salfred
102145073Skeramidastatic char smp_header_thr[] =
103158280Sbde    "  PID %-*.*s  THR PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
10427340Speterstatic char smp_header[] =
105158280Sbde    "  PID %-*.*s "   "PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
10624143Sjoerg
10727340Speter#define smp_Proc_format \
108158282Sbde    "%5d %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
10924143Sjoerg
110145073Skeramidastatic char up_header_thr[] =
111158280Sbde    "  PID %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
11227340Speterstatic char up_header[] =
113158280Sbde    "  PID %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
11424143Sjoerg
11527340Speter#define up_Proc_format \
116158282Sbde    "%5d %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
11724143Sjoerg
11824143Sjoerg
11924143Sjoerg/* process state names for the "STATE" column of the display */
12024143Sjoerg/* the extra nulls in the string "run" are for adding a slash and
12124143Sjoerg   the processor number when needed */
12224143Sjoerg
123158280Sbdechar *state_abbrev[] = {
124131623Sdes	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
12524143Sjoerg};
12624143Sjoerg
12724143Sjoerg
12824143Sjoergstatic kvm_t *kd;
12924143Sjoerg
13024143Sjoerg/* values that we stash away in _init and use in later routines */
13124143Sjoerg
13224143Sjoergstatic double logcpu;
13324143Sjoerg
13424143Sjoerg/* these are retrieved from the kernel in _init */
13524143Sjoerg
13624143Sjoergstatic load_avg  ccpu;
13724143Sjoerg
13872951Srwatson/* these are used in the get_ functions */
13924143Sjoerg
14072951Srwatsonstatic int lastpid;
14124143Sjoerg
14224143Sjoerg/* these are for calculating cpu state percentages */
14324143Sjoerg
14424143Sjoergstatic long cp_time[CPUSTATES];
14524143Sjoergstatic long cp_old[CPUSTATES];
14624143Sjoergstatic long cp_diff[CPUSTATES];
14724143Sjoerg
14824143Sjoerg/* these are for detailing the process states */
14924143Sjoerg
15065557Sjasoneint process_states[8];
15124143Sjoergchar *procstatenames[] = {
152131623Sdes	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
153131623Sdes	" zombie, ", " waiting, ", " lock, ",
154131623Sdes	NULL
15524143Sjoerg};
15624143Sjoerg
15724143Sjoerg/* these are for detailing the cpu states */
15824143Sjoerg
15924143Sjoergint cpu_states[CPUSTATES];
16024143Sjoergchar *cpustatenames[] = {
161131623Sdes	"user", "nice", "system", "interrupt", "idle", NULL
16224143Sjoerg};
16324143Sjoerg
16424143Sjoerg/* these are for detailing the memory statistics */
16524143Sjoerg
16624143Sjoergint memory_stats[7];
16724143Sjoergchar *memorynames[] = {
168158280Sbde	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
169158280Sbde	"K Free", NULL
17024143Sjoerg};
17124143Sjoerg
17224143Sjoergint swap_stats[7];
17324143Sjoergchar *swapnames[] = {
174131623Sdes	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
175131623Sdes	NULL
17624143Sjoerg};
17724143Sjoerg
17824143Sjoerg
17924143Sjoerg/* these are for keeping track of the proc array */
18024143Sjoerg
18124143Sjoergstatic int nproc;
18224143Sjoergstatic int onproc = -1;
18324143Sjoergstatic int pref_len;
18424143Sjoergstatic struct kinfo_proc *pbase;
18524143Sjoergstatic struct kinfo_proc **pref;
186131402Salfredstatic struct kinfo_proc *previous_procs;
187131402Salfredstatic struct kinfo_proc **previous_pref;
188131402Salfredstatic int previous_proc_count = 0;
189131402Salfredstatic int previous_proc_count_max = 0;
19024143Sjoerg
191131412Salfred/* total number of io operations */
192131412Salfredstatic long total_inblock;
193131412Salfredstatic long total_oublock;
194131412Salfredstatic long total_majflt;
195131412Salfred
19624143Sjoerg/* these are for getting the memory statistics */
19724143Sjoerg
19824143Sjoergstatic int pageshift;		/* log base 2 of the pagesize */
19924143Sjoerg
20024143Sjoerg/* define pagetok in terms of pageshift */
20124143Sjoerg
20224143Sjoerg#define pagetok(size) ((size) << pageshift)
20324143Sjoerg
20424143Sjoerg/* useful externals */
20524143Sjoerglong percentages();
20624143Sjoerg
20738278Swosch#ifdef ORDER
208131829Skeramida/*
209145073Skeramida * Sorting orders.  The first element is the default.
210131829Skeramida */
211133817Salfredchar *ordernames[] = {
212145073Skeramida	"cpu", "size", "res", "time", "pri", "threads",
213133817Salfred	"total", "read", "write", "fault", "vcsw", "ivcsw", NULL
21438278Swosch};
21538278Swosch#endif
21638278Swosch
217158282Sbdestatic int compare_pid(const void *a, const void *b);
218158282Sbdestatic const char *format_nice(const struct kinfo_proc *pp);
219158282Sbdestatic void getsysctl(const char *name, void *ptr, size_t len);
220158282Sbdestatic int swapmode(int *retavail, int *retfree);
221158282Sbde
22224143Sjoergint
223131622Sdesmachine_init(struct statics *statics)
22424143Sjoerg{
225131623Sdes	int pagesize;
226131623Sdes	size_t modelen;
227131623Sdes	struct passwd *pw;
22824143Sjoerg
229131623Sdes	modelen = sizeof(smpmode);
230158280Sbde	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
231158280Sbde	    NULL, 0) != 0 &&
232158280Sbde	    sysctlbyname("kern.smp.active", &smpmode, &modelen,
233158280Sbde	    NULL, 0) != 0) ||
234131623Sdes	    modelen != sizeof(smpmode))
235131623Sdes		smpmode = 0;
23627340Speter
237131623Sdes	while ((pw = getpwent()) != NULL) {
238131623Sdes		if (strlen(pw->pw_name) > namelength)
239131623Sdes			namelength = strlen(pw->pw_name);
240131623Sdes	}
241146291Sobrien	if (smpmode && namelength > SMPUNAMELEN)
242146291Sobrien		namelength = SMPUNAMELEN;
243146291Sobrien	else if (namelength > UPUNAMELEN)
244146291Sobrien		namelength = UPUNAMELEN;
24527390Speter
246131626Sdes	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
247131626Sdes	if (kd == NULL)
248131626Sdes		return (-1);
24924143Sjoerg
250131623Sdes	GETSYSCTL("kern.ccpu", ccpu);
25124143Sjoerg
252131623Sdes	/* this is used in calculating WCPU -- calculate it ahead of time */
253131623Sdes	logcpu = log(loaddouble(ccpu));
25424143Sjoerg
255131623Sdes	pbase = NULL;
256131623Sdes	pref = NULL;
257131623Sdes	nproc = 0;
258131623Sdes	onproc = -1;
259158280Sbde
260158280Sbde	/* get the page size and calculate pageshift from it */
261131623Sdes	pagesize = getpagesize();
262131623Sdes	pageshift = 0;
263131626Sdes	while (pagesize > 1) {
264131623Sdes		pageshift++;
265131623Sdes		pagesize >>= 1;
266131623Sdes	}
26724143Sjoerg
268131623Sdes	/* we only need the amount of log(2)1024 for our conversion */
269131623Sdes	pageshift -= LOG1024;
27024143Sjoerg
271131623Sdes	/* fill in the statics information */
272131623Sdes	statics->procstate_names = procstatenames;
273131623Sdes	statics->cpustate_names = cpustatenames;
274131623Sdes	statics->memory_names = memorynames;
275131623Sdes	statics->swap_names = swapnames;
27638278Swosch#ifdef ORDER
277133817Salfred	statics->order_names = ordernames;
27838278Swosch#endif
27924143Sjoerg
280131623Sdes	/* all done! */
281131623Sdes	return (0);
28224143Sjoerg}
28324143Sjoerg
284131310Salfredchar *
285131622Sdesformat_header(char *uname_field)
28624143Sjoerg{
287131623Sdes	static char Header[128];
288131623Sdes	const char *prehead;
28924143Sjoerg
290131623Sdes	switch (displaymode) {
291131623Sdes	case DISP_CPU:
292145073Skeramida		/*
293145073Skeramida		 * The logic of picking the right header format seems reverse
294145073Skeramida		 * here because we only want to display a THR column when
295145073Skeramida		 * "thread mode" is off (and threads are not listed as
296145073Skeramida		 * separate lines).
297145073Skeramida		 */
298145073Skeramida		prehead = smpmode ?
299145073Skeramida		    (ps.thread ? smp_header : smp_header_thr) :
300145073Skeramida		    (ps.thread ? up_header : up_header_thr);
301146342Skeramida		snprintf(Header, sizeof(Header), prehead,
302146342Skeramida		    namelength, namelength, uname_field,
303146342Skeramida		    ps.wcpu ? "WCPU" : "CPU");
304131623Sdes		break;
305131623Sdes	case DISP_IO:
306131623Sdes		prehead = io_header;
307146342Skeramida		snprintf(Header, sizeof(Header), prehead,
308146342Skeramida		    namelength, namelength, uname_field);
309131623Sdes		break;
310131623Sdes	}
311131623Sdes	cmdlengthdelta = strlen(Header) - 7;
312131623Sdes	return (Header);
31324143Sjoerg}
31424143Sjoerg
31524143Sjoergstatic int swappgsin = -1;
31624143Sjoergstatic int swappgsout = -1;
31724143Sjoergextern struct timeval timeout;
31824143Sjoerg
31924143Sjoergvoid
320131622Sdesget_system_info(struct system_info *si)
32124143Sjoerg{
322131623Sdes	long total;
323131623Sdes	struct loadavg sysload;
324131623Sdes	int mib[2];
325131623Sdes	struct timeval boottime;
326131623Sdes	size_t bt_size;
327131626Sdes	int i;
32824143Sjoerg
329131623Sdes	/* get the cp_time array */
330131623Sdes	GETSYSCTL("kern.cp_time", cp_time);
331131623Sdes	GETSYSCTL("vm.loadavg", sysload);
332131623Sdes	GETSYSCTL("kern.lastpid", lastpid);
33324143Sjoerg
334131623Sdes	/* convert load averages to doubles */
335131626Sdes	for (i = 0; i < 3; i++)
336131626Sdes		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
33724143Sjoerg
338131623Sdes	/* convert cp_time counts to percentages */
339131623Sdes	total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
34024143Sjoerg
341131623Sdes	/* sum memory & swap statistics */
342131623Sdes	{
343131623Sdes		static unsigned int swap_delay = 0;
344131623Sdes		static int swapavail = 0;
345131623Sdes		static int swapfree = 0;
346131623Sdes		static int bufspace = 0;
347131623Sdes		static int nspgsin, nspgsout;
34824143Sjoerg
349131623Sdes		GETSYSCTL("vfs.bufspace", bufspace);
350131623Sdes		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
351131623Sdes		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
352131623Sdes		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
353131623Sdes		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
354131623Sdes		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
355131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
356131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
357131623Sdes		/* convert memory stats to Kbytes */
358131623Sdes		memory_stats[0] = pagetok(memory_stats[0]);
359131623Sdes		memory_stats[1] = pagetok(memory_stats[1]);
360131623Sdes		memory_stats[2] = pagetok(memory_stats[2]);
361131623Sdes		memory_stats[3] = pagetok(memory_stats[3]);
362131623Sdes		memory_stats[4] = bufspace / 1024;
363131623Sdes		memory_stats[5] = pagetok(memory_stats[5]);
364131623Sdes		memory_stats[6] = -1;
36524143Sjoerg
366131623Sdes		/* first interval */
367131623Sdes		if (swappgsin < 0) {
368131623Sdes			swap_stats[4] = 0;
369131623Sdes			swap_stats[5] = 0;
370131623Sdes		}
37124143Sjoerg
372131623Sdes		/* compute differences between old and new swap statistic */
373131623Sdes		else {
374131623Sdes			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
375131623Sdes			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
376131623Sdes		}
37724143Sjoerg
378131623Sdes		swappgsin = nspgsin;
379131623Sdes		swappgsout = nspgsout;
38024143Sjoerg
381131623Sdes		/* call CPU heavy swapmode() only for changes */
382131623Sdes		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
383131623Sdes			swap_stats[3] = swapmode(&swapavail, &swapfree);
384131623Sdes			swap_stats[0] = swapavail;
385131623Sdes			swap_stats[1] = swapavail - swapfree;
386131623Sdes			swap_stats[2] = swapfree;
387131623Sdes		}
388131623Sdes		swap_delay = 1;
389131623Sdes		swap_stats[6] = -1;
39024143Sjoerg	}
39124143Sjoerg
392131623Sdes	/* set arrays and strings */
393131623Sdes	si->cpustates = cpu_states;
394131623Sdes	si->memory = memory_stats;
395131623Sdes	si->swap = swap_stats;
39624143Sjoerg
39724143Sjoerg
398131623Sdes	if (lastpid > 0) {
399131623Sdes		si->last_pid = lastpid;
400131623Sdes	} else {
401131623Sdes		si->last_pid = -1;
402131623Sdes	}
40342447Sobrien
404131623Sdes	/*
405131623Sdes	 * Print how long system has been up.
406131623Sdes	 * (Found by looking getting "boottime" from the kernel)
407131623Sdes	 */
408131623Sdes	mib[0] = CTL_KERN;
409131623Sdes	mib[1] = KERN_BOOTTIME;
410131623Sdes	bt_size = sizeof(boottime);
411131623Sdes	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
412131623Sdes	    boottime.tv_sec != 0) {
413131623Sdes		si->boottime = boottime;
414131623Sdes	} else {
415131623Sdes		si->boottime.tv_sec = -1;
416131623Sdes	}
41724143Sjoerg}
41824143Sjoerg
419132015Salfred#define NOPROC	((void *)-1)
420132015Salfred
421132955Salfred/*
422132955Salfred * We need to compare data from the old process entry with the new
423132955Salfred * process entry.
424132955Salfred * To facilitate doing this quickly we stash a pointer in the kinfo_proc
425132955Salfred * structure to cache the mapping.  We also use a negative cache pointer
426132955Salfred * of NOPROC to avoid duplicate lookups.
427132955Salfred * XXX: this could be done when the actual processes are fetched, we do
428132955Salfred * it here out of laziness.
429132955Salfred */
430131402Salfredconst struct kinfo_proc *
431131402Salfredget_old_proc(struct kinfo_proc *pp)
432131402Salfred{
433131402Salfred	struct kinfo_proc **oldpp, *oldp;
434131402Salfred
435132955Salfred	/*
436132955Salfred	 * If this is the first fetch of the kinfo_procs then we don't have
437132955Salfred	 * any previous entries.
438132955Salfred	 */
439131402Salfred	if (previous_proc_count == 0)
440131402Salfred		return (NULL);
441132955Salfred	/* negative cache? */
442132015Salfred	if (pp->ki_udata == NOPROC)
443132015Salfred		return (NULL);
444132955Salfred	/* cached? */
445132015Salfred	if (pp->ki_udata != NULL)
446132015Salfred		return (pp->ki_udata);
447132955Salfred	/*
448132955Salfred	 * Not cached,
449132955Salfred	 * 1) look up based on pid.
450132955Salfred	 * 2) compare process start.
451132955Salfred	 * If we fail here, then setup a negative cache entry, otherwise
452132955Salfred	 * cache it.
453132955Salfred	 */
454131402Salfred	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
455131626Sdes	    sizeof(*previous_pref), compare_pid);
456132015Salfred	if (oldpp == NULL) {
457132015Salfred		pp->ki_udata = NOPROC;
458131402Salfred		return (NULL);
459132015Salfred	}
460131402Salfred	oldp = *oldpp;
461132015Salfred	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
462132015Salfred		pp->ki_udata = NOPROC;
463131402Salfred		return (NULL);
464132015Salfred	}
465132015Salfred	pp->ki_udata = oldp;
466131402Salfred	return (oldp);
467131402Salfred}
468131402Salfred
469132955Salfred/*
470132955Salfred * Return the total amount of IO done in blocks in/out and faults.
471132955Salfred * store the values individually in the pointers passed in.
472132955Salfred */
473131402Salfredlong
474158280Sbdeget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
475158280Sbde    long *vcsw, long *ivcsw)
476131402Salfred{
477131402Salfred	const struct kinfo_proc *oldp;
478131402Salfred	static struct kinfo_proc dummy;
479131402Salfred	long ret;
480131402Salfred
481131402Salfred	oldp = get_old_proc(pp);
482131402Salfred	if (oldp == NULL) {
483131402Salfred		bzero(&dummy, sizeof(dummy));
484131402Salfred		oldp = &dummy;
485131402Salfred	}
486131412Salfred	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
487131412Salfred	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
488131412Salfred	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
489133817Salfred	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
490133817Salfred	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
491131402Salfred	ret =
492131402Salfred	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
493131402Salfred	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
494131402Salfred	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
495131402Salfred	return (ret);
496131402Salfred}
497131402Salfred
498132955Salfred/*
499132955Salfred * Return the total number of block in/out and faults by a process.
500132955Salfred */
501131412Salfredlong
502131412Salfredget_io_total(struct kinfo_proc *pp)
503131412Salfred{
504131412Salfred	long dummy;
505131412Salfred
506133817Salfred	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
507131412Salfred}
508131412Salfred
50924143Sjoergstatic struct handle handle;
51024143Sjoerg
511131310Salfredcaddr_t
512131622Sdesget_process_info(struct system_info *si, struct process_select *sel,
513131626Sdes    int (*compare)(const void *, const void *))
51424143Sjoerg{
515131623Sdes	int i;
516131623Sdes	int total_procs;
517131623Sdes	long p_io;
518133817Salfred	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
519131623Sdes	int active_procs;
520131623Sdes	struct kinfo_proc **prefp;
521131623Sdes	struct kinfo_proc *pp;
522131623Sdes	struct kinfo_proc *prev_pp = NULL;
52324143Sjoerg
524131623Sdes	/* these are copied out of sel for speed */
525131623Sdes	int show_idle;
526131623Sdes	int show_self;
527131623Sdes	int show_system;
528131623Sdes	int show_uid;
529131623Sdes	int show_command;
53024143Sjoerg
531131623Sdes	/*
532131623Sdes	 * Save the previous process info.
533131623Sdes	 */
534131623Sdes	if (previous_proc_count_max < nproc) {
535131623Sdes		free(previous_procs);
536131626Sdes		previous_procs = malloc(nproc * sizeof(*previous_procs));
537131623Sdes		free(previous_pref);
538131626Sdes		previous_pref = malloc(nproc * sizeof(*previous_pref));
539131623Sdes		if (previous_procs == NULL || previous_pref == NULL) {
540131623Sdes			(void) fprintf(stderr, "top: Out of memory.\n");
541131623Sdes			quit(23);
542131623Sdes		}
543131623Sdes		previous_proc_count_max = nproc;
544131623Sdes	}
545131623Sdes	if (nproc) {
546131623Sdes		for (i = 0; i < nproc; i++)
547131623Sdes			previous_pref[i] = &previous_procs[i];
548131626Sdes		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
549158280Sbde		qsort(previous_pref, nproc, sizeof(*previous_pref),
550158280Sbde		    compare_pid);
551131623Sdes	}
552131623Sdes	previous_proc_count = nproc;
553131402Salfred
554131623Sdes	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
555131623Sdes	if (nproc > onproc)
556131626Sdes		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
557131623Sdes	if (pref == NULL || pbase == NULL) {
558131623Sdes		(void) fprintf(stderr, "top: Out of memory.\n");
559131623Sdes		quit(23);
560131623Sdes	}
561131623Sdes	/* get a pointer to the states summary array */
562131623Sdes	si->procstates = process_states;
56324143Sjoerg
564131623Sdes	/* set up flags which define what we are going to select */
565131623Sdes	show_idle = sel->idle;
566132024Sdes	show_self = sel->self == -1;
567131623Sdes	show_system = sel->system;
568131623Sdes	show_uid = sel->uid != -1;
569131623Sdes	show_command = sel->command != NULL;
57024143Sjoerg
571131623Sdes	/* count up process states and get pointers to interesting procs */
572131623Sdes	total_procs = 0;
573131623Sdes	active_procs = 0;
574131623Sdes	total_inblock = 0;
575131623Sdes	total_oublock = 0;
576131623Sdes	total_majflt = 0;
577131623Sdes	memset((char *)process_states, 0, sizeof(process_states));
578131623Sdes	prefp = pref;
579131626Sdes	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
580131619Sdes
581131623Sdes		if (pp->ki_stat == 0)
582132024Sdes			/* not in use */
583132024Sdes			continue;
584131619Sdes
585131623Sdes		if (!show_self && pp->ki_pid == sel->self)
586131623Sdes			/* skip self */
587131623Sdes			continue;
588131619Sdes
589131623Sdes		if (!show_system && (pp->ki_flag & P_SYSTEM))
590131623Sdes			/* skip system process */
591131623Sdes			continue;
592131619Sdes
593158280Sbde		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
594158280Sbde		    &p_vcsw, &p_ivcsw);
595131623Sdes		total_inblock += p_inblock;
596131623Sdes		total_oublock += p_oublock;
597131623Sdes		total_majflt += p_majflt;
598131623Sdes		total_procs++;
599131626Sdes		process_states[pp->ki_stat]++;
600131619Sdes
601131623Sdes		if (pp->ki_stat == SZOMB)
602131623Sdes			/* skip zombies */
603131623Sdes			continue;
604131619Sdes
605131623Sdes		if (displaymode == DISP_CPU && !show_idle &&
606159520Sse		    (pp->ki_pctcpu == 0 ||
607159520Sse		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
608131623Sdes			/* skip idle or non-running processes */
609131623Sdes			continue;
610131619Sdes
611131623Sdes		if (displaymode == DISP_IO && !show_idle && p_io == 0)
612131623Sdes			/* skip processes that aren't doing I/O */
613131623Sdes			continue;
614131619Sdes
615131623Sdes		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
616158280Sbde			/* skip proc. that don't belong to the selected UID */
617131623Sdes			continue;
618131619Sdes
619131623Sdes		/*
620131623Sdes		 * When not showing threads, take the first thread
621131623Sdes		 * for output and add the fields that we can from
622131623Sdes		 * the rest of the process's threads rather than
623131623Sdes		 * using the system's mostly-broken KERN_PROC_PROC.
624131623Sdes		 */
625131626Sdes		if (sel->thread || prev_pp == NULL ||
626131626Sdes		    prev_pp->ki_pid != pp->ki_pid) {
627131623Sdes			*prefp++ = pp;
628131623Sdes			active_procs++;
629131623Sdes			prev_pp = pp;
630131623Sdes		} else {
631131623Sdes			prev_pp->ki_pctcpu += pp->ki_pctcpu;
632131623Sdes		}
633131623Sdes	}
634131623Sdes
635131623Sdes	/* if requested, sort the "interesting" processes */
636131623Sdes	if (compare != NULL)
637131626Sdes		qsort(pref, active_procs, sizeof(*pref), compare);
63824143Sjoerg
639131623Sdes	/* remember active and total counts */
640131623Sdes	si->p_total = total_procs;
641131623Sdes	si->p_active = pref_len = active_procs;
64224143Sjoerg
643131623Sdes	/* pass back a handle */
644131623Sdes	handle.next_proc = pref;
645131623Sdes	handle.remaining = active_procs;
646131623Sdes	return ((caddr_t)&handle);
64724143Sjoerg}
64824143Sjoerg
649131626Sdesstatic char fmt[128];	/* static area where result is built */
65024143Sjoerg
651131310Salfredchar *
652131626Sdesformat_next_process(caddr_t handle, char *(*get_userid)(int))
65324143Sjoerg{
654131623Sdes	struct kinfo_proc *pp;
655131623Sdes	const struct kinfo_proc *oldp;
656131623Sdes	long cputime;
657131623Sdes	double pct;
658131623Sdes	struct handle *hp;
659131623Sdes	char status[16];
660131623Sdes	int state;
661131623Sdes	struct rusage ru, *rup;
662131623Sdes	long p_tot, s_tot;
663145155Skeramida	char *proc_fmt, thr_buf[6];
66424143Sjoerg
665131623Sdes	/* find and remember the next proc structure */
666131623Sdes	hp = (struct handle *)handle;
667131623Sdes	pp = *(hp->next_proc++);
668131623Sdes	hp->remaining--;
669131620Sdes
670131623Sdes	/* get the process's command name */
671131623Sdes	if ((pp->ki_sflag & PS_INMEM) == 0) {
672131623Sdes		/*
673131623Sdes		 * Print swapped processes as <pname>
674131623Sdes		 */
675158280Sbde		size_t len;
676158280Sbde
677158280Sbde		len = strlen(pp->ki_comm);
678131626Sdes		if (len > sizeof(pp->ki_comm) - 3)
679131626Sdes			len = sizeof(pp->ki_comm) - 3;
680131626Sdes		memmove(pp->ki_comm + 1, pp->ki_comm, len);
681131626Sdes		pp->ki_comm[0] = '<';
682131626Sdes		pp->ki_comm[len + 1] = '>';
683131626Sdes		pp->ki_comm[len + 2] = '\0';
684131623Sdes	}
685131623Sdes
68624143Sjoerg	/*
687131623Sdes	 * Convert the process's runtime from microseconds to seconds.  This
688131623Sdes	 * time includes the interrupt time although that is not wanted here.
689131623Sdes	 * ps(1) is similarly sloppy.
69024143Sjoerg	 */
691131623Sdes	cputime = (pp->ki_runtime + 500000) / 1000000;
69224143Sjoerg
693131623Sdes	/* calculate the base for cpu percentages */
694131623Sdes	pct = pctdouble(pp->ki_pctcpu);
69524143Sjoerg
696131623Sdes	/* generate "STATE" field */
697131623Sdes	switch (state = pp->ki_stat) {
69824143Sjoerg	case SRUN:
699131623Sdes		if (smpmode && pp->ki_oncpu != 0xff)
700131623Sdes			sprintf(status, "CPU%d", pp->ki_oncpu);
701131623Sdes		else
702131623Sdes			strcpy(status, "RUN");
703131623Sdes		break;
704104388Sjhb	case SLOCK:
705131623Sdes		if (pp->ki_kiflag & KI_LOCKBLOCK) {
706131623Sdes			sprintf(status, "*%.6s", pp->ki_lockname);
707131623Sdes			break;
708131623Sdes		}
709131623Sdes		/* fall through */
71024143Sjoerg	case SSLEEP:
711131623Sdes		if (pp->ki_wmesg != NULL) {
712131623Sdes			sprintf(status, "%.6s", pp->ki_wmesg);
713131623Sdes			break;
714131623Sdes		}
715131623Sdes		/* FALLTHROUGH */
71624143Sjoerg	default:
71743720Sfenner
718131623Sdes		if (state >= 0 &&
719131623Sdes		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
720131626Sdes			sprintf(status, "%.6s", state_abbrev[state]);
721131623Sdes		else
722131623Sdes			sprintf(status, "?%5d", state);
723131623Sdes		break;
724131623Sdes	}
72524143Sjoerg
726131623Sdes	if (displaymode == DISP_IO) {
727131623Sdes		oldp = get_old_proc(pp);
728131623Sdes		if (oldp != NULL) {
729158280Sbde			ru.ru_inblock = RU(pp)->ru_inblock -
730158280Sbde			    RU(oldp)->ru_inblock;
731158280Sbde			ru.ru_oublock = RU(pp)->ru_oublock -
732158280Sbde			    RU(oldp)->ru_oublock;
733131623Sdes			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
734133817Salfred			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
735133817Salfred			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
736131623Sdes			rup = &ru;
737131623Sdes		} else {
738131623Sdes			rup = RU(pp);
739131623Sdes		}
740131623Sdes		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
741131623Sdes		s_tot = total_inblock + total_oublock + total_majflt;
742131402Salfred
743131623Sdes		sprintf(fmt, io_Proc_format,
744131623Sdes		    pp->ki_pid,
745158280Sbde		    namelength, namelength, (*get_userid)(pp->ki_ruid),
746133817Salfred		    rup->ru_nvcsw,
747133817Salfred		    rup->ru_nivcsw,
748131626Sdes		    rup->ru_inblock,
749131626Sdes		    rup->ru_oublock,
750131626Sdes		    rup->ru_majflt,
751131626Sdes		    p_tot,
752131626Sdes		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
753131623Sdes		    screen_width > cmdlengthdelta ?
754131623Sdes		    screen_width - cmdlengthdelta : 0,
755131623Sdes		    printable(pp->ki_comm));
756131623Sdes		return (fmt);
757131623Sdes	}
758145073Skeramida
759131623Sdes	/* format this entry */
760145073Skeramida	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
761145073Skeramida	if (ps.thread != 0)
762145073Skeramida		thr_buf[0] = '\0';
763145073Skeramida	else
764145073Skeramida		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
765145073Skeramida		    sizeof(thr_buf) - 2, pp->ki_numthreads);
766145073Skeramida
767145073Skeramida	sprintf(fmt, proc_fmt,
76869896Smckusick	    pp->ki_pid,
769158280Sbde	    namelength, namelength, (*get_userid)(pp->ki_ruid),
770145073Skeramida	    thr_buf,
77172377Sjake	    pp->ki_pri.pri_level - PZERO,
772158282Sbde	    format_nice(pp),
77337100Sdt	    format_k2(PROCSIZE(pp)),
77469896Smckusick	    format_k2(pagetok(pp->ki_rssize)),
77524143Sjoerg	    status,
77669896Smckusick	    smpmode ? pp->ki_lastcpu : 0,
77724143Sjoerg	    format_time(cputime),
778146342Skeramida	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
779158280Sbde	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
78069896Smckusick	    printable(pp->ki_comm));
78124143Sjoerg
782131623Sdes	/* return the result */
783131623Sdes	return (fmt);
78424143Sjoerg}
78524143Sjoerg
786131310Salfredstatic void
787158282Sbdegetsysctl(const char *name, void *ptr, size_t len)
78824143Sjoerg{
789131623Sdes	size_t nlen = len;
790131310Salfred
791131623Sdes	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
792131623Sdes		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
793131623Sdes		    strerror(errno));
794131623Sdes		quit(23);
795131623Sdes	}
796131623Sdes	if (nlen != len) {
797158280Sbde		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
798158280Sbde		    name, (unsigned long)len, (unsigned long)nlen);
799131623Sdes		quit(23);
800131623Sdes	}
80124143Sjoerg}
80272951Srwatson
803164058Sbdestatic const char *
804164058Sbdeformat_nice(const struct kinfo_proc *pp)
805158282Sbde{
806164058Sbde	const char *fifo, *kthread;
807164058Sbde	int rtpri;
808164058Sbde	static char nicebuf[4 + 1];
809158282Sbde
810164058Sbde	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
811164058Sbde	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
812164058Sbde	switch (PRI_BASE(pp->ki_pri.pri_class)) {
813164058Sbde	case PRI_ITHD:
814164058Sbde		return ("-");
815164058Sbde	case PRI_REALTIME:
816164058Sbde		rtpri = pp->ki_pri.pri_level - PRI_MIN_REALTIME;
817164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
818164058Sbde		    kthread, rtpri, fifo);
819164058Sbde		break;
820164058Sbde	case PRI_TIMESHARE:
821164058Sbde		if (pp->ki_flag & P_KTHREAD)
822164058Sbde			return ("-");
823164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
824164058Sbde		break;
825164058Sbde	case PRI_IDLE:
826164058Sbde		rtpri = pp->ki_pri.pri_level - PRI_MIN_IDLE;
827164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
828164058Sbde		    kthread, rtpri, fifo);
829164058Sbde		break;
830164058Sbde	default:
831164058Sbde		return ("?");
832164058Sbde	}
833158282Sbde	return (nicebuf);
834158282Sbde}
835158282Sbde
83638278Swosch/* comparison routines for qsort */
83724143Sjoerg
838158282Sbdestatic int
839131622Sdescompare_pid(const void *p1, const void *p2)
840131402Salfred{
841131623Sdes	const struct kinfo_proc * const *pp1 = p1;
842131623Sdes	const struct kinfo_proc * const *pp2 = p2;
843131402Salfred
844131623Sdes	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
845131623Sdes		abort();
846131402Salfred
847131623Sdes	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
848131402Salfred}
849131402Salfred
85024143Sjoerg/*
85124143Sjoerg *  proc_compare - comparison function for "qsort"
85224143Sjoerg *	Compares the resource consumption of two processes using five
853131620Sdes *	distinct keys.  The keys (in descending order of importance) are:
854131620Sdes *	percent cpu, cpu ticks, state, resident set size, total virtual
855131620Sdes *	memory usage.  The process states are ordered as follows (from least
856131620Sdes *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
857131620Sdes *	array declaration below maps a process state index into a number
858131620Sdes *	that reflects this ordering.
85924143Sjoerg */
86024143Sjoerg
861158280Sbdestatic int sorted_state[] = {
862131623Sdes	0,	/* not used		*/
863131623Sdes	3,	/* sleep		*/
864131623Sdes	1,	/* ABANDONED (WAIT)	*/
865131623Sdes	6,	/* run			*/
866131623Sdes	5,	/* start		*/
867131623Sdes	2,	/* zombie		*/
868131623Sdes	4	/* stop			*/
86924143Sjoerg};
87038278Swosch
871131620Sdes
872146343Skeramida#define ORDERKEY_PCTCPU(a, b) do { \
873146343Skeramida	long diff; \
874146343Skeramida	if (ps.wcpu) \
875158280Sbde		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
876158280Sbde		    (b))) - \
877158280Sbde		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
878158280Sbde		    (a))); \
879146343Skeramida	else \
880146343Skeramida		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
881146343Skeramida	if (diff != 0) \
882146343Skeramida		return (diff > 0 ? 1 : -1); \
883131626Sdes} while (0)
88438278Swosch
885131626Sdes#define ORDERKEY_CPTICKS(a, b) do { \
886131628Sdes	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
887131626Sdes	if (diff != 0) \
888131626Sdes		return (diff > 0 ? 1 : -1); \
889131626Sdes} while (0)
89038278Swosch
891131626Sdes#define ORDERKEY_STATE(a, b) do { \
892131626Sdes	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
893131626Sdes	if (diff != 0) \
894131626Sdes		return (diff > 0 ? 1 : -1); \
895131626Sdes} while (0)
89638278Swosch
897131626Sdes#define ORDERKEY_PRIO(a, b) do { \
898131628Sdes	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
899131626Sdes	if (diff != 0) \
900131626Sdes		return (diff > 0 ? 1 : -1); \
901131626Sdes} while (0)
90238278Swosch
903145073Skeramida#define	ORDERKEY_THREADS(a, b) do { \
904145073Skeramida	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
905145073Skeramida	if (diff != 0) \
906145073Skeramida		return (diff > 0 ? 1 : -1); \
907145073Skeramida} while (0)
908145073Skeramida
909131626Sdes#define ORDERKEY_RSSIZE(a, b) do { \
910131628Sdes	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
911131626Sdes	if (diff != 0) \
912131626Sdes		return (diff > 0 ? 1 : -1); \
913131626Sdes} while (0)
91438278Swosch
915131626Sdes#define ORDERKEY_MEM(a, b) do { \
916131628Sdes	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
917131626Sdes	if (diff != 0) \
918131626Sdes		return (diff > 0 ? 1 : -1); \
919131626Sdes} while (0)
92038278Swosch
92138278Swosch/* compare_cpu - the comparison function for sorting by cpu percentage */
92238278Swosch
92324143Sjoergint
92438278Swosch#ifdef ORDER
925131626Sdescompare_cpu(void *arg1, void *arg2)
92638278Swosch#else
927131626Sdesproc_compare(void *arg1, void *arg2)
92838278Swosch#endif
92924143Sjoerg{
930131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
931131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
93224143Sjoerg
933131626Sdes	ORDERKEY_PCTCPU(p1, p2);
934131626Sdes	ORDERKEY_CPTICKS(p1, p2);
935131626Sdes	ORDERKEY_STATE(p1, p2);
936131626Sdes	ORDERKEY_PRIO(p1, p2);
937131626Sdes	ORDERKEY_RSSIZE(p1, p2);
938131626Sdes	ORDERKEY_MEM(p1, p2);
93924143Sjoerg
940131626Sdes	return (0);
94124143Sjoerg}
94224143Sjoerg
94338278Swosch#ifdef ORDER
944158280Sbde/* "cpu" compare routines */
945158280Sbdeint compare_size(), compare_res(), compare_time(), compare_prio(),
946158280Sbde    compare_threads();
94724143Sjoerg
948158280Sbde/*
949158280Sbde * "io" compare routines.  Context switches aren't i/o, but are displayed
950158280Sbde * on the "io" display.
951158280Sbde */
952158280Sbdeint compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
953158280Sbde    compare_vcsw(), compare_ivcsw();
954158280Sbde
955133817Salfredint (*compares[])() = {
956131623Sdes	compare_cpu,
957131623Sdes	compare_size,
958131623Sdes	compare_res,
959131623Sdes	compare_time,
960131623Sdes	compare_prio,
961145073Skeramida	compare_threads,
962133817Salfred	compare_iototal,
963133817Salfred	compare_ioread,
964133817Salfred	compare_iowrite,
965133817Salfred	compare_iofault,
966133817Salfred	compare_vcsw,
967133817Salfred	compare_ivcsw,
968131623Sdes	NULL
96938278Swosch};
97038278Swosch
97138278Swosch/* compare_size - the comparison function for sorting by total memory usage */
97238278Swosch
97338278Swoschint
974131626Sdescompare_size(void *arg1, void *arg2)
97538278Swosch{
976131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
977131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
97838278Swosch
979131626Sdes	ORDERKEY_MEM(p1, p2);
980131626Sdes	ORDERKEY_RSSIZE(p1, p2);
981131626Sdes	ORDERKEY_PCTCPU(p1, p2);
982131626Sdes	ORDERKEY_CPTICKS(p1, p2);
983131626Sdes	ORDERKEY_STATE(p1, p2);
984131626Sdes	ORDERKEY_PRIO(p1, p2);
98538278Swosch
986131626Sdes	return (0);
98738278Swosch}
98838278Swosch
98938278Swosch/* compare_res - the comparison function for sorting by resident set size */
99038278Swosch
99138278Swoschint
992131626Sdescompare_res(void *arg1, void *arg2)
99338278Swosch{
994131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
995131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
99638278Swosch
997131626Sdes	ORDERKEY_RSSIZE(p1, p2);
998131626Sdes	ORDERKEY_MEM(p1, p2);
999131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1000131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1001131626Sdes	ORDERKEY_STATE(p1, p2);
1002131626Sdes	ORDERKEY_PRIO(p1, p2);
100338278Swosch
1004131626Sdes	return (0);
100538278Swosch}
100638278Swosch
100738278Swosch/* compare_time - the comparison function for sorting by total cpu time */
100838278Swosch
100938278Swoschint
1010131626Sdescompare_time(void *arg1, void *arg2)
1011131310Salfred{
1012131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1013131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
101438278Swosch
1015131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1016131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1017131626Sdes	ORDERKEY_STATE(p1, p2);
1018131626Sdes	ORDERKEY_PRIO(p1, p2);
1019131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1020131626Sdes	ORDERKEY_MEM(p1, p2);
102138278Swosch
1022131626Sdes	return (0);
1023131623Sdes}
1024131310Salfred
1025131626Sdes/* compare_prio - the comparison function for sorting by priority */
102638278Swosch
102738278Swoschint
1028131626Sdescompare_prio(void *arg1, void *arg2)
102938278Swosch{
1030131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1031131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
103238278Swosch
1033131626Sdes	ORDERKEY_PRIO(p1, p2);
1034131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1035131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1036131626Sdes	ORDERKEY_STATE(p1, p2);
1037131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1038131626Sdes	ORDERKEY_MEM(p1, p2);
103938278Swosch
1040131626Sdes	return (0);
104138278Swosch}
1042145073Skeramida
1043145073Skeramida/* compare_threads - the comparison function for sorting by threads */
1044145073Skeramidaint
1045145073Skeramidacompare_threads(void *arg1, void *arg2)
1046145073Skeramida{
1047145073Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1048145073Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1049145073Skeramida
1050145073Skeramida	ORDERKEY_THREADS(p1, p2);
1051145073Skeramida	ORDERKEY_PCTCPU(p1, p2);
1052145073Skeramida	ORDERKEY_CPTICKS(p1, p2);
1053145073Skeramida	ORDERKEY_STATE(p1, p2);
1054145073Skeramida	ORDERKEY_PRIO(p1, p2);
1055145073Skeramida	ORDERKEY_RSSIZE(p1, p2);
1056145073Skeramida	ORDERKEY_MEM(p1, p2);
1057145073Skeramida
1058145073Skeramida	return (0);
1059145073Skeramida}
1060158280Sbde#endif /* ORDER */
106138278Swosch
1062158280Sbde/* assorted comparison functions for sorting by i/o */
1063131829Skeramida
1064131402Salfredint
1065131829Skeramida#ifdef ORDER
1066131829Skeramidacompare_iototal(void *arg1, void *arg2)
1067131829Skeramida#else
1068131626Sdesio_compare(void *arg1, void *arg2)
1069131829Skeramida#endif
1070131402Salfred{
1071131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1072131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1073131402Salfred
1074131626Sdes	return (get_io_total(p2) - get_io_total(p1));
1075131402Salfred}
1076131829Skeramida
1077131829Skeramida#ifdef ORDER
1078131829Skeramidaint
1079131829Skeramidacompare_ioread(void *arg1, void *arg2)
1080131829Skeramida{
1081131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1082131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1083131829Skeramida	long dummy, inp1, inp2;
1084131829Skeramida
1085133817Salfred	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1086133817Salfred	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1087131829Skeramida
1088131829Skeramida	return (inp2 - inp1);
1089131829Skeramida}
1090131829Skeramida
1091131829Skeramidaint
1092131829Skeramidacompare_iowrite(void *arg1, void *arg2)
1093131829Skeramida{
1094131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1095131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1096131829Skeramida	long dummy, oup1, oup2;
1097131829Skeramida
1098133817Salfred	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1099133817Salfred	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1100131829Skeramida
1101131829Skeramida	return (oup2 - oup1);
1102131829Skeramida}
1103131829Skeramida
1104131829Skeramidaint
1105131829Skeramidacompare_iofault(void *arg1, void *arg2)
1106131829Skeramida{
1107131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1108131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1109131829Skeramida	long dummy, flp1, flp2;
1110131829Skeramida
1111133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1112133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1113131829Skeramida
1114131829Skeramida	return (flp2 - flp1);
1115131829Skeramida}
1116131829Skeramida
1117133817Salfredint
1118133817Salfredcompare_vcsw(void *arg1, void *arg2)
1119133817Salfred{
1120133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1121133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1122133817Salfred	long dummy, flp1, flp2;
1123133817Salfred
1124133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1125133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1126133817Salfred
1127133817Salfred	return (flp2 - flp1);
1128133817Salfred}
1129133817Salfred
1130133817Salfredint
1131133817Salfredcompare_ivcsw(void *arg1, void *arg2)
1132133817Salfred{
1133133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1134133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1135133817Salfred	long dummy, flp1, flp2;
1136133817Salfred
1137133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1138133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1139133817Salfred
1140133817Salfred	return (flp2 - flp1);
1141133817Salfred}
1142131829Skeramida#endif /* ORDER */
1143131829Skeramida
114424143Sjoerg/*
114524143Sjoerg * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
114624143Sjoerg *		the process does not exist.
114724143Sjoerg *		It is EXTREMLY IMPORTANT that this function work correctly.
114824143Sjoerg *		If top runs setuid root (as in SVR4), then this function
114924143Sjoerg *		is the only thing that stands in the way of a serious
115024143Sjoerg *		security problem.  It validates requests for the "kill"
115124143Sjoerg *		and "renice" commands.
115224143Sjoerg */
115324143Sjoerg
1154131310Salfredint
1155131622Sdesproc_owner(int pid)
115624143Sjoerg{
1157131623Sdes	int cnt;
1158131623Sdes	struct kinfo_proc **prefp;
1159131623Sdes	struct kinfo_proc *pp;
116024143Sjoerg
1161131623Sdes	prefp = pref;
1162131623Sdes	cnt = pref_len;
1163131626Sdes	while (--cnt >= 0) {
1164131623Sdes		pp = *prefp++;
1165131623Sdes		if (pp->ki_pid == (pid_t)pid)
1166131623Sdes			return ((int)pp->ki_ruid);
116724143Sjoerg	}
1168131623Sdes	return (-1);
116924143Sjoerg}
117024143Sjoerg
1171158282Sbdestatic int
1172131622Sdesswapmode(int *retavail, int *retfree)
117324143Sjoerg{
117443053Sdillon	int n;
117543053Sdillon	int pagesize = getpagesize();
117643053Sdillon	struct kvm_swap swapary[1];
117724143Sjoerg
117843053Sdillon	*retavail = 0;
117943053Sdillon	*retfree = 0;
118024143Sjoerg
118143053Sdillon#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
118224143Sjoerg
118343053Sdillon	n = kvm_getswapinfo(kd, swapary, 1, 0);
118443697Sdillon	if (n < 0 || swapary[0].ksw_total == 0)
1185131623Sdes		return (0);
118624143Sjoerg
118743053Sdillon	*retavail = CONVERT(swapary[0].ksw_total);
118843053Sdillon	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
118924143Sjoerg
1190131626Sdes	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1191131623Sdes	return (n);
119243053Sdillon}
1193