machine.c revision 145073
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 145073 2005-04-14 15:02:03Z keramida $
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
5492922Simpstatic void getsysctl(char *, void *, size_t);
5572951Srwatson
5672951Srwatson#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
5772951Srwatson
58145073Skeramidaextern struct process_select ps;
5992922Simpextern char* printable(char *);
6092922Simpint swapmode(int *retavail, int *retfree);
6127340Speterstatic int smpmode;
62131402Salfredenum displaymodes displaymode;
6327390Speterstatic int namelength;
6469375Sjhbstatic int cmdlengthdelta;
6524143Sjoerg
6672951Srwatson/* Prototypes for top internals */
6792922Simpvoid quit(int);
68131402Salfredint compare_pid(const void *a, const void *b);
6924143Sjoerg
7024143Sjoerg/* get_process_info passes back a handle.  This is what it looks like: */
7124143Sjoerg
7224143Sjoergstruct handle
7324143Sjoerg{
74131623Sdes	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
75131623Sdes	int remaining;			/* number of pointers remaining */
7624143Sjoerg};
7724143Sjoerg
7824143Sjoerg/* declarations for load_avg */
7924143Sjoerg#include "loadavg.h"
8024143Sjoerg
8124143Sjoerg/* define what weighted cpu is.  */
8269896Smckusick#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
8369896Smckusick			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
8424143Sjoerg
8524143Sjoerg/* what we consider to be process size: */
8669896Smckusick#define PROCSIZE(pp) ((pp)->ki_size / 1024)
8724143Sjoerg
88131402Salfred#define RU(pp)	(&(pp)->ki_rusage)
89131402Salfred#define RUTOT(pp) \
90131402Salfred	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
91131402Salfred
92131402Salfred
9324143Sjoerg/* definitions for indices in the nlist array */
9424143Sjoerg
9524143Sjoerg/*
9624143Sjoerg *  These definitions control the format of the per-process area
9724143Sjoerg */
9824143Sjoerg
99131402Salfredstatic char io_header[] =
100133817Salfred	"  PID %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
101131402Salfred
102131402Salfred#define io_Proc_format \
103133817Salfred	"%5d %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
104131402Salfred
105145073Skeramidastatic char smp_header_thr[] =
106145073Skeramida	"  PID %-*.*s   THR PRI NICE   SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
10727340Speterstatic char smp_header[] =
108145073Skeramida	"  PID %-*.*s "    "PRI NICE   SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
10924143Sjoerg
11027340Speter#define smp_Proc_format \
111145073Skeramida	"%5d %-*.*s %s%3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
11224143Sjoerg
113145073Skeramidastatic char up_header_thr[] =
114145073Skeramida	"  PID %-*.*s   THR PRI NICE   SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
11527340Speterstatic char up_header[] =
116145073Skeramida	"  PID %-*.*s "    "PRI NICE   SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
11724143Sjoerg
11827340Speter#define up_Proc_format \
119145073Skeramida	"%5d %-*.*s %s%3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
12024143Sjoerg
12124143Sjoerg
12224143Sjoerg/* process state names for the "STATE" column of the display */
12324143Sjoerg/* the extra nulls in the string "run" are for adding a slash and
12424143Sjoerg   the processor number when needed */
12524143Sjoerg
12624143Sjoergchar *state_abbrev[] =
12724143Sjoerg{
128131623Sdes	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
12924143Sjoerg};
13024143Sjoerg
13124143Sjoerg
13224143Sjoergstatic kvm_t *kd;
13324143Sjoerg
13424143Sjoerg/* values that we stash away in _init and use in later routines */
13524143Sjoerg
13624143Sjoergstatic double logcpu;
13724143Sjoerg
13824143Sjoerg/* these are retrieved from the kernel in _init */
13924143Sjoerg
14024143Sjoergstatic load_avg  ccpu;
14124143Sjoerg
14272951Srwatson/* these are used in the get_ functions */
14324143Sjoerg
14472951Srwatsonstatic int lastpid;
14524143Sjoerg
14624143Sjoerg/* these are for calculating cpu state percentages */
14724143Sjoerg
14824143Sjoergstatic long cp_time[CPUSTATES];
14924143Sjoergstatic long cp_old[CPUSTATES];
15024143Sjoergstatic long cp_diff[CPUSTATES];
15124143Sjoerg
15224143Sjoerg/* these are for detailing the process states */
15324143Sjoerg
15465557Sjasoneint process_states[8];
15524143Sjoergchar *procstatenames[] = {
156131623Sdes	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
157131623Sdes	" zombie, ", " waiting, ", " lock, ",
158131623Sdes	NULL
15924143Sjoerg};
16024143Sjoerg
16124143Sjoerg/* these are for detailing the cpu states */
16224143Sjoerg
16324143Sjoergint cpu_states[CPUSTATES];
16424143Sjoergchar *cpustatenames[] = {
165131623Sdes	"user", "nice", "system", "interrupt", "idle", NULL
16624143Sjoerg};
16724143Sjoerg
16824143Sjoerg/* these are for detailing the memory statistics */
16924143Sjoerg
17024143Sjoergint memory_stats[7];
17124143Sjoergchar *memorynames[] = {
172131623Sdes	/* 0             1            2            3            4          5 */
173131623Sdes	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
174131623Sdes	NULL
17524143Sjoerg};
17624143Sjoerg
17724143Sjoergint swap_stats[7];
17824143Sjoergchar *swapnames[] = {
179131623Sdes	/* 0            1           2           3            4         5 */
180131623Sdes	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
181131623Sdes	NULL
18224143Sjoerg};
18324143Sjoerg
18424143Sjoerg
18524143Sjoerg/* these are for keeping track of the proc array */
18624143Sjoerg
18724143Sjoergstatic int nproc;
18824143Sjoergstatic int onproc = -1;
18924143Sjoergstatic int pref_len;
19024143Sjoergstatic struct kinfo_proc *pbase;
19124143Sjoergstatic struct kinfo_proc **pref;
192131402Salfredstatic struct kinfo_proc *previous_procs;
193131402Salfredstatic struct kinfo_proc **previous_pref;
194131402Salfredstatic int previous_proc_count = 0;
195131402Salfredstatic int previous_proc_count_max = 0;
19624143Sjoerg
197131412Salfred/* total number of io operations */
198131412Salfredstatic long total_inblock;
199131412Salfredstatic long total_oublock;
200131412Salfredstatic long total_majflt;
201131412Salfred
20224143Sjoerg/* these are for getting the memory statistics */
20324143Sjoerg
20424143Sjoergstatic int pageshift;		/* log base 2 of the pagesize */
20524143Sjoerg
20624143Sjoerg/* define pagetok in terms of pageshift */
20724143Sjoerg
20824143Sjoerg#define pagetok(size) ((size) << pageshift)
20924143Sjoerg
21024143Sjoerg/* useful externals */
21124143Sjoerglong percentages();
21224143Sjoerg
21338278Swosch#ifdef ORDER
214131829Skeramida/*
215145073Skeramida * Sorting orders.  The first element is the default.
216131829Skeramida */
217133817Salfredchar *ordernames[] = {
218145073Skeramida	"cpu", "size", "res", "time", "pri", "threads",
219133817Salfred	"total", "read", "write", "fault", "vcsw", "ivcsw", NULL
22038278Swosch};
22138278Swosch#endif
22238278Swosch
22324143Sjoergint
224131622Sdesmachine_init(struct statics *statics)
22524143Sjoerg{
226131623Sdes	int pagesize;
227131623Sdes	size_t modelen;
228131623Sdes	struct passwd *pw;
22924143Sjoerg
230131623Sdes	modelen = sizeof(smpmode);
231131623Sdes	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
232131623Sdes		sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
233131623Sdes	    modelen != sizeof(smpmode))
234131623Sdes		smpmode = 0;
23527340Speter
236131623Sdes	while ((pw = getpwent()) != NULL) {
237131623Sdes		if (strlen(pw->pw_name) > namelength)
238131623Sdes			namelength = strlen(pw->pw_name);
239131623Sdes	}
240131623Sdes	if (namelength < 8)
241131623Sdes		namelength = 8;
242131623Sdes	if (smpmode && namelength > 13)
243131623Sdes		namelength = 13;
244131623Sdes	else if (namelength > 15)
245131623Sdes		namelength = 15;
24627390Speter
247131626Sdes	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
248131626Sdes	if (kd == NULL)
249131626Sdes		return (-1);
25024143Sjoerg
251131623Sdes	GETSYSCTL("kern.ccpu", ccpu);
25224143Sjoerg
253131623Sdes	/* this is used in calculating WCPU -- calculate it ahead of time */
254131623Sdes	logcpu = log(loaddouble(ccpu));
25524143Sjoerg
256131623Sdes	pbase = NULL;
257131623Sdes	pref = NULL;
258131623Sdes	nproc = 0;
259131623Sdes	onproc = -1;
260131623Sdes	/* get the page size with "getpagesize" 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);
301131623Sdes		break;
302131623Sdes	case DISP_IO:
303131623Sdes		prehead = io_header;
304131623Sdes		break;
305131623Sdes	}
306131402Salfred
307131623Sdes	snprintf(Header, sizeof(Header), prehead,
308131623Sdes	    namelength, namelength, uname_field);
30927340Speter
310131623Sdes	cmdlengthdelta = strlen(Header) - 7;
31124143Sjoerg
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
474133817Salfredget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp, long *vcsw, long *ivcsw)
475131402Salfred{
476131402Salfred	const struct kinfo_proc *oldp;
477131402Salfred	static struct kinfo_proc dummy;
478131402Salfred	long ret;
479131402Salfred
480131402Salfred	oldp = get_old_proc(pp);
481131402Salfred	if (oldp == NULL) {
482131402Salfred		bzero(&dummy, sizeof(dummy));
483131402Salfred		oldp = &dummy;
484131402Salfred	}
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));
549131626Sdes		qsort(previous_pref, nproc, sizeof(*previous_pref), compare_pid);
550131623Sdes	}
551131623Sdes	previous_proc_count = nproc;
552131402Salfred
553131623Sdes	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
554131623Sdes	if (nproc > onproc)
555131626Sdes		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
556131623Sdes	if (pref == NULL || pbase == NULL) {
557131623Sdes		(void) fprintf(stderr, "top: Out of memory.\n");
558131623Sdes		quit(23);
559131623Sdes	}
560131623Sdes	/* get a pointer to the states summary array */
561131623Sdes	si->procstates = process_states;
56224143Sjoerg
563131623Sdes	/* set up flags which define what we are going to select */
564131623Sdes	show_idle = sel->idle;
565132024Sdes	show_self = sel->self == -1;
566131623Sdes	show_system = sel->system;
567131623Sdes	show_uid = sel->uid != -1;
568131623Sdes	show_command = sel->command != NULL;
56924143Sjoerg
570131623Sdes	/* count up process states and get pointers to interesting procs */
571131623Sdes	total_procs = 0;
572131623Sdes	active_procs = 0;
573131623Sdes	total_inblock = 0;
574131623Sdes	total_oublock = 0;
575131623Sdes	total_majflt = 0;
576131623Sdes	memset((char *)process_states, 0, sizeof(process_states));
577131623Sdes	prefp = pref;
578131626Sdes	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
579131619Sdes
580131623Sdes		if (pp->ki_stat == 0)
581132024Sdes			/* not in use */
582132024Sdes			continue;
583131619Sdes
584131623Sdes		if (!show_self && pp->ki_pid == sel->self)
585131623Sdes			/* skip self */
586131623Sdes			continue;
587131619Sdes
588131623Sdes		if (!show_system && (pp->ki_flag & P_SYSTEM))
589131623Sdes			/* skip system process */
590131623Sdes			continue;
591131619Sdes
592133817Salfred		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt, &p_vcsw, &p_ivcsw);
593131623Sdes		total_inblock += p_inblock;
594131623Sdes		total_oublock += p_oublock;
595131623Sdes		total_majflt += p_majflt;
596131623Sdes		total_procs++;
597131626Sdes		process_states[pp->ki_stat]++;
598131619Sdes
599131623Sdes		if (pp->ki_stat == SZOMB)
600131623Sdes			/* skip zombies */
601131623Sdes			continue;
602131619Sdes
603131623Sdes		if (displaymode == DISP_CPU && !show_idle &&
604131623Sdes		    (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN))
605131623Sdes			/* skip idle or non-running processes */
606131623Sdes			continue;
607131619Sdes
608131623Sdes		if (displaymode == DISP_IO && !show_idle && p_io == 0)
609131623Sdes			/* skip processes that aren't doing I/O */
610131623Sdes			continue;
611131619Sdes
612131623Sdes		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
613131623Sdes			/* skip processes which don't belong to the selected UID */
614131623Sdes			continue;
615131619Sdes
616131623Sdes		/*
617131623Sdes		 * When not showing threads, take the first thread
618131623Sdes		 * for output and add the fields that we can from
619131623Sdes		 * the rest of the process's threads rather than
620131623Sdes		 * using the system's mostly-broken KERN_PROC_PROC.
621131623Sdes		 */
622131626Sdes		if (sel->thread || prev_pp == NULL ||
623131626Sdes		    prev_pp->ki_pid != pp->ki_pid) {
624131623Sdes			*prefp++ = pp;
625131623Sdes			active_procs++;
626131623Sdes			prev_pp = pp;
627131623Sdes		} else {
628131623Sdes			prev_pp->ki_pctcpu += pp->ki_pctcpu;
629131623Sdes		}
630131623Sdes	}
631131623Sdes
632131623Sdes	/* if requested, sort the "interesting" processes */
633131623Sdes	if (compare != NULL)
634131626Sdes		qsort(pref, active_procs, sizeof(*pref), compare);
63524143Sjoerg
636131623Sdes	/* remember active and total counts */
637131623Sdes	si->p_total = total_procs;
638131623Sdes	si->p_active = pref_len = active_procs;
63924143Sjoerg
640131623Sdes	/* pass back a handle */
641131623Sdes	handle.next_proc = pref;
642131623Sdes	handle.remaining = active_procs;
643131623Sdes	return ((caddr_t)&handle);
64424143Sjoerg}
64524143Sjoerg
646131626Sdesstatic char fmt[128];	/* static area where result is built */
64724143Sjoerg
648131310Salfredchar *
649131626Sdesformat_next_process(caddr_t handle, char *(*get_userid)(int))
65024143Sjoerg{
651131623Sdes	struct kinfo_proc *pp;
652131623Sdes	const struct kinfo_proc *oldp;
653131623Sdes	long cputime;
654131623Sdes	double pct;
655131623Sdes	struct handle *hp;
656131623Sdes	char status[16];
657131623Sdes	int state;
658131623Sdes	struct rusage ru, *rup;
659131623Sdes	long p_tot, s_tot;
660145073Skeramida	char *proc_fmt, thr_buf[7];
66124143Sjoerg
662131623Sdes	/* find and remember the next proc structure */
663131623Sdes	hp = (struct handle *)handle;
664131623Sdes	pp = *(hp->next_proc++);
665131623Sdes	hp->remaining--;
666131620Sdes
667131623Sdes	/* get the process's command name */
668131623Sdes	if ((pp->ki_sflag & PS_INMEM) == 0) {
669131623Sdes		/*
670131623Sdes		 * Print swapped processes as <pname>
671131623Sdes		 */
672131626Sdes		size_t len = strlen(pp->ki_comm);
673131626Sdes		if (len > sizeof(pp->ki_comm) - 3)
674131626Sdes			len = sizeof(pp->ki_comm) - 3;
675131626Sdes		memmove(pp->ki_comm + 1, pp->ki_comm, len);
676131626Sdes		pp->ki_comm[0] = '<';
677131626Sdes		pp->ki_comm[len + 1] = '>';
678131626Sdes		pp->ki_comm[len + 2] = '\0';
679131623Sdes	}
680131623Sdes
68124143Sjoerg	/*
682131623Sdes	 * Convert the process's runtime from microseconds to seconds.  This
683131623Sdes	 * time includes the interrupt time although that is not wanted here.
684131623Sdes	 * ps(1) is similarly sloppy.
68524143Sjoerg	 */
686131623Sdes	cputime = (pp->ki_runtime + 500000) / 1000000;
68724143Sjoerg
688131623Sdes	/* calculate the base for cpu percentages */
689131623Sdes	pct = pctdouble(pp->ki_pctcpu);
69024143Sjoerg
691131623Sdes	/* generate "STATE" field */
692131623Sdes	switch (state = pp->ki_stat) {
69324143Sjoerg	case SRUN:
694131623Sdes		if (smpmode && pp->ki_oncpu != 0xff)
695131623Sdes			sprintf(status, "CPU%d", pp->ki_oncpu);
696131623Sdes		else
697131623Sdes			strcpy(status, "RUN");
698131623Sdes		break;
699104388Sjhb	case SLOCK:
700131623Sdes		if (pp->ki_kiflag & KI_LOCKBLOCK) {
701131623Sdes			sprintf(status, "*%.6s", pp->ki_lockname);
702131623Sdes			break;
703131623Sdes		}
704131623Sdes		/* fall through */
70524143Sjoerg	case SSLEEP:
706131623Sdes		if (pp->ki_wmesg != NULL) {
707131623Sdes			sprintf(status, "%.6s", pp->ki_wmesg);
708131623Sdes			break;
709131623Sdes		}
710131623Sdes		/* FALLTHROUGH */
71124143Sjoerg	default:
71243720Sfenner
713131623Sdes		if (state >= 0 &&
714131623Sdes		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
715131626Sdes			sprintf(status, "%.6s", state_abbrev[state]);
716131623Sdes		else
717131623Sdes			sprintf(status, "?%5d", state);
718131623Sdes		break;
719131623Sdes	}
72024143Sjoerg
721131623Sdes	if (displaymode == DISP_IO) {
722131623Sdes		oldp = get_old_proc(pp);
723131623Sdes		if (oldp != NULL) {
724131623Sdes			ru.ru_inblock = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
725131623Sdes			ru.ru_oublock = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
726131623Sdes			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
727133817Salfred			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
728133817Salfred			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
729131623Sdes			rup = &ru;
730131623Sdes		} else {
731131623Sdes			rup = RU(pp);
732131623Sdes		}
733131623Sdes		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
734131623Sdes		s_tot = total_inblock + total_oublock + total_majflt;
735131402Salfred
736131623Sdes		sprintf(fmt, io_Proc_format,
737131623Sdes		    pp->ki_pid,
738131623Sdes		    namelength, namelength,
739131623Sdes		    (*get_userid)(pp->ki_ruid),
740133817Salfred		    rup->ru_nvcsw,
741133817Salfred		    rup->ru_nivcsw,
742131626Sdes		    rup->ru_inblock,
743131626Sdes		    rup->ru_oublock,
744131626Sdes		    rup->ru_majflt,
745131626Sdes		    p_tot,
746131626Sdes		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
747131623Sdes		    screen_width > cmdlengthdelta ?
748131623Sdes		    screen_width - cmdlengthdelta : 0,
749131623Sdes		    printable(pp->ki_comm));
750131623Sdes		return (fmt);
751131623Sdes	}
752145073Skeramida
753131623Sdes	/* format this entry */
754145073Skeramida	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
755145073Skeramida	if (ps.thread != 0)
756145073Skeramida		thr_buf[0] = '\0';
757145073Skeramida	else
758145073Skeramida		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
759145073Skeramida		    sizeof(thr_buf) - 2, pp->ki_numthreads);
760145073Skeramida
761145073Skeramida	sprintf(fmt, proc_fmt,
76269896Smckusick	    pp->ki_pid,
76327390Speter	    namelength, namelength,
76469896Smckusick	    (*get_userid)(pp->ki_ruid),
765145073Skeramida	    thr_buf,
76672377Sjake	    pp->ki_pri.pri_level - PZERO,
76729904Speter
76829904Speter	    /*
769131620Sdes	     * normal time      -> nice value -20 - +20
77029904Speter	     * real time 0 - 31 -> nice value -52 - -21
77129904Speter	     * idle time 0 - 31 -> nice value +21 - +52
77229904Speter	     */
773131620Sdes	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
774131620Sdes		pp->ki_nice - NZERO :
775131620Sdes		(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
77672377Sjake		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
777131620Sdes		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
77837100Sdt	    format_k2(PROCSIZE(pp)),
77969896Smckusick	    format_k2(pagetok(pp->ki_rssize)),
78024143Sjoerg	    status,
78169896Smckusick	    smpmode ? pp->ki_lastcpu : 0,
78224143Sjoerg	    format_time(cputime),
78341325Sdfr	    100.0 * weighted_cpu(pct, pp),
78441325Sdfr	    100.0 * pct,
78569375Sjhb	    screen_width > cmdlengthdelta ?
786131623Sdes	    screen_width - cmdlengthdelta :
787131623Sdes	    0,
78869896Smckusick	    printable(pp->ki_comm));
78924143Sjoerg
790131623Sdes	/* return the result */
791131623Sdes	return (fmt);
79224143Sjoerg}
79324143Sjoerg
794131310Salfredstatic void
795131622Sdesgetsysctl(char *name, void *ptr, size_t len)
79624143Sjoerg{
797131623Sdes	size_t nlen = len;
798131310Salfred
799131623Sdes	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
800131623Sdes		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
801131623Sdes		    strerror(errno));
802131623Sdes		quit(23);
803131623Sdes	}
804131623Sdes	if (nlen != len) {
805131623Sdes		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
806131623Sdes		    (unsigned long)len, (unsigned long)nlen);
807131623Sdes		quit(23);
808131623Sdes	}
80924143Sjoerg}
81072951Srwatson
81138278Swosch/* comparison routines for qsort */
81224143Sjoerg
813131402Salfredint
814131622Sdescompare_pid(const void *p1, const void *p2)
815131402Salfred{
816131623Sdes	const struct kinfo_proc * const *pp1 = p1;
817131623Sdes	const struct kinfo_proc * const *pp2 = p2;
818131402Salfred
819131623Sdes	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
820131623Sdes		abort();
821131402Salfred
822131623Sdes	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
823131402Salfred}
824131402Salfred
82524143Sjoerg/*
82624143Sjoerg *  proc_compare - comparison function for "qsort"
82724143Sjoerg *	Compares the resource consumption of two processes using five
828131620Sdes *	distinct keys.  The keys (in descending order of importance) are:
829131620Sdes *	percent cpu, cpu ticks, state, resident set size, total virtual
830131620Sdes *	memory usage.  The process states are ordered as follows (from least
831131620Sdes *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
832131620Sdes *	array declaration below maps a process state index into a number
833131620Sdes *	that reflects this ordering.
83424143Sjoerg */
83524143Sjoerg
836131626Sdesstatic int sorted_state[] =
83724143Sjoerg{
838131623Sdes	0,	/* not used		*/
839131623Sdes	3,	/* sleep		*/
840131623Sdes	1,	/* ABANDONED (WAIT)	*/
841131623Sdes	6,	/* run			*/
842131623Sdes	5,	/* start		*/
843131623Sdes	2,	/* zombie		*/
844131623Sdes	4	/* stop			*/
84524143Sjoerg};
84638278Swosch
847131620Sdes
848131626Sdes#define ORDERKEY_PCTCPU(a, b) do { \
849131627Sdes	long diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
850131626Sdes	if (diff != 0) \
851131626Sdes		return (diff > 0 ? 1 : -1); \
852131626Sdes} while (0)
85338278Swosch
854131626Sdes#define ORDERKEY_CPTICKS(a, b) do { \
855131628Sdes	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
856131626Sdes	if (diff != 0) \
857131626Sdes		return (diff > 0 ? 1 : -1); \
858131626Sdes} while (0)
85938278Swosch
860131626Sdes#define ORDERKEY_STATE(a, b) do { \
861131626Sdes	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
862131626Sdes	if (diff != 0) \
863131626Sdes		return (diff > 0 ? 1 : -1); \
864131626Sdes} while (0)
86538278Swosch
866131626Sdes#define ORDERKEY_PRIO(a, b) do { \
867131628Sdes	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
868131626Sdes	if (diff != 0) \
869131626Sdes		return (diff > 0 ? 1 : -1); \
870131626Sdes} while (0)
87138278Swosch
872145073Skeramida#define	ORDERKEY_THREADS(a, b) do { \
873145073Skeramida	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
874145073Skeramida	if (diff != 0) \
875145073Skeramida		return (diff > 0 ? 1 : -1); \
876145073Skeramida} while (0)
877145073Skeramida
878131626Sdes#define ORDERKEY_RSSIZE(a, b) do { \
879131628Sdes	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
880131626Sdes	if (diff != 0) \
881131626Sdes		return (diff > 0 ? 1 : -1); \
882131626Sdes} while (0)
88338278Swosch
884131626Sdes#define ORDERKEY_MEM(a, b) do { \
885131628Sdes	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
886131626Sdes	if (diff != 0) \
887131626Sdes		return (diff > 0 ? 1 : -1); \
888131626Sdes} while (0)
88938278Swosch
89038278Swosch/* compare_cpu - the comparison function for sorting by cpu percentage */
89138278Swosch
89224143Sjoergint
89338278Swosch#ifdef ORDER
894131626Sdescompare_cpu(void *arg1, void *arg2)
89538278Swosch#else
896131626Sdesproc_compare(void *arg1, void *arg2)
89738278Swosch#endif
89824143Sjoerg{
899131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
900131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
90124143Sjoerg
902131626Sdes	ORDERKEY_PCTCPU(p1, p2);
903131626Sdes	ORDERKEY_CPTICKS(p1, p2);
904131626Sdes	ORDERKEY_STATE(p1, p2);
905131626Sdes	ORDERKEY_PRIO(p1, p2);
906131626Sdes	ORDERKEY_RSSIZE(p1, p2);
907131626Sdes	ORDERKEY_MEM(p1, p2);
90824143Sjoerg
909131626Sdes	return (0);
91024143Sjoerg}
91124143Sjoerg
91238278Swosch#ifdef ORDER
91338278Swosch/* compare routines */
914145073Skeramidaint compare_size(), compare_res(), compare_time(), compare_prio(), compare_threads();
915133817Salfred/* io compare routines */
916133817Salfredint compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(), compare_vcsw(), compare_ivcsw();
91724143Sjoerg
918133817Salfredint (*compares[])() = {
919131623Sdes	compare_cpu,
920131623Sdes	compare_size,
921131623Sdes	compare_res,
922131623Sdes	compare_time,
923131623Sdes	compare_prio,
924145073Skeramida	compare_threads,
925133817Salfred	compare_iototal,
926133817Salfred	compare_ioread,
927133817Salfred	compare_iowrite,
928133817Salfred	compare_iofault,
929133817Salfred	compare_vcsw,
930133817Salfred	compare_ivcsw,
931131623Sdes	NULL
93238278Swosch};
93338278Swosch
93438278Swosch/* compare_size - the comparison function for sorting by total memory usage */
93538278Swosch
93638278Swoschint
937131626Sdescompare_size(void *arg1, void *arg2)
93838278Swosch{
939131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
940131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
94138278Swosch
942131626Sdes	ORDERKEY_MEM(p1, p2);
943131626Sdes	ORDERKEY_RSSIZE(p1, p2);
944131626Sdes	ORDERKEY_PCTCPU(p1, p2);
945131626Sdes	ORDERKEY_CPTICKS(p1, p2);
946131626Sdes	ORDERKEY_STATE(p1, p2);
947131626Sdes	ORDERKEY_PRIO(p1, p2);
94838278Swosch
949131626Sdes	return (0);
95038278Swosch}
95138278Swosch
95238278Swosch/* compare_res - the comparison function for sorting by resident set size */
95338278Swosch
95438278Swoschint
955131626Sdescompare_res(void *arg1, void *arg2)
95638278Swosch{
957131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
958131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
95938278Swosch
960131626Sdes	ORDERKEY_RSSIZE(p1, p2);
961131626Sdes	ORDERKEY_MEM(p1, p2);
962131626Sdes	ORDERKEY_PCTCPU(p1, p2);
963131626Sdes	ORDERKEY_CPTICKS(p1, p2);
964131626Sdes	ORDERKEY_STATE(p1, p2);
965131626Sdes	ORDERKEY_PRIO(p1, p2);
96638278Swosch
967131626Sdes	return (0);
96838278Swosch}
96938278Swosch
97038278Swosch/* compare_time - the comparison function for sorting by total cpu time */
97138278Swosch
97238278Swoschint
973131626Sdescompare_time(void *arg1, void *arg2)
974131310Salfred{
975131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
976131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
97738278Swosch
978131626Sdes	ORDERKEY_CPTICKS(p1, p2);
979131626Sdes	ORDERKEY_PCTCPU(p1, p2);
980131626Sdes	ORDERKEY_STATE(p1, p2);
981131626Sdes	ORDERKEY_PRIO(p1, p2);
982131626Sdes	ORDERKEY_RSSIZE(p1, p2);
983131626Sdes	ORDERKEY_MEM(p1, p2);
98438278Swosch
985131626Sdes	return (0);
986131623Sdes}
987131310Salfred
988131626Sdes/* compare_prio - the comparison function for sorting by priority */
98938278Swosch
99038278Swoschint
991131626Sdescompare_prio(void *arg1, void *arg2)
99238278Swosch{
993131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
994131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
99538278Swosch
996131626Sdes	ORDERKEY_PRIO(p1, p2);
997131626Sdes	ORDERKEY_CPTICKS(p1, p2);
998131626Sdes	ORDERKEY_PCTCPU(p1, p2);
999131626Sdes	ORDERKEY_STATE(p1, p2);
1000131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1001131626Sdes	ORDERKEY_MEM(p1, p2);
100238278Swosch
1003131626Sdes	return (0);
100438278Swosch}
1005145073Skeramida
1006145073Skeramida/* compare_threads - the comparison function for sorting by threads */
1007145073Skeramidaint
1008145073Skeramidacompare_threads(void *arg1, void *arg2)
1009145073Skeramida{
1010145073Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1011145073Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1012145073Skeramida
1013145073Skeramida	ORDERKEY_THREADS(p1, p2);
1014145073Skeramida	ORDERKEY_PCTCPU(p1, p2);
1015145073Skeramida	ORDERKEY_CPTICKS(p1, p2);
1016145073Skeramida	ORDERKEY_STATE(p1, p2);
1017145073Skeramida	ORDERKEY_PRIO(p1, p2);
1018145073Skeramida	ORDERKEY_RSSIZE(p1, p2);
1019145073Skeramida	ORDERKEY_MEM(p1, p2);
1020145073Skeramida
1021145073Skeramida	return (0);
1022145073Skeramida}
102338278Swosch#endif
102438278Swosch
1025131829Skeramida/* compare_io - the comparison function for sorting by total io */
1026131829Skeramida
1027131402Salfredint
1028131829Skeramida#ifdef ORDER
1029131829Skeramidacompare_iototal(void *arg1, void *arg2)
1030131829Skeramida#else
1031131626Sdesio_compare(void *arg1, void *arg2)
1032131829Skeramida#endif
1033131402Salfred{
1034131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1035131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1036131402Salfred
1037131626Sdes	return (get_io_total(p2) - get_io_total(p1));
1038131402Salfred}
1039131829Skeramida
1040131829Skeramida#ifdef ORDER
1041131829Skeramida
1042131829Skeramidaint
1043131829Skeramidacompare_ioread(void *arg1, void *arg2)
1044131829Skeramida{
1045131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1046131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1047131829Skeramida	long dummy, inp1, inp2;
1048131829Skeramida
1049133817Salfred	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1050133817Salfred	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1051131829Skeramida
1052131829Skeramida	return (inp2 - inp1);
1053131829Skeramida}
1054131829Skeramida
1055131829Skeramidaint
1056131829Skeramidacompare_iowrite(void *arg1, void *arg2)
1057131829Skeramida{
1058131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1059131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1060131829Skeramida	long dummy, oup1, oup2;
1061131829Skeramida
1062133817Salfred	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1063133817Salfred	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1064131829Skeramida
1065131829Skeramida	return (oup2 - oup1);
1066131829Skeramida}
1067131829Skeramida
1068131829Skeramidaint
1069131829Skeramidacompare_iofault(void *arg1, void *arg2)
1070131829Skeramida{
1071131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1072131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1073131829Skeramida	long dummy, flp1, flp2;
1074131829Skeramida
1075133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1076133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1077131829Skeramida
1078131829Skeramida	return (flp2 - flp1);
1079131829Skeramida}
1080131829Skeramida
1081133817Salfredint
1082133817Salfredcompare_vcsw(void *arg1, void *arg2)
1083133817Salfred{
1084133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1085133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1086133817Salfred	long dummy, flp1, flp2;
1087133817Salfred
1088133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1089133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1090133817Salfred
1091133817Salfred	return (flp2 - flp1);
1092133817Salfred}
1093133817Salfred
1094133817Salfredint
1095133817Salfredcompare_ivcsw(void *arg1, void *arg2)
1096133817Salfred{
1097133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1098133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1099133817Salfred	long dummy, flp1, flp2;
1100133817Salfred
1101133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1102133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1103133817Salfred
1104133817Salfred	return (flp2 - flp1);
1105133817Salfred}
1106133817Salfred
1107131829Skeramida#endif /* ORDER */
1108131829Skeramida
110924143Sjoerg/*
111024143Sjoerg * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
111124143Sjoerg *		the process does not exist.
111224143Sjoerg *		It is EXTREMLY IMPORTANT that this function work correctly.
111324143Sjoerg *		If top runs setuid root (as in SVR4), then this function
111424143Sjoerg *		is the only thing that stands in the way of a serious
111524143Sjoerg *		security problem.  It validates requests for the "kill"
111624143Sjoerg *		and "renice" commands.
111724143Sjoerg */
111824143Sjoerg
1119131310Salfredint
1120131622Sdesproc_owner(int pid)
112124143Sjoerg{
1122131623Sdes	int cnt;
1123131623Sdes	struct kinfo_proc **prefp;
1124131623Sdes	struct kinfo_proc *pp;
112524143Sjoerg
1126131623Sdes	prefp = pref;
1127131623Sdes	cnt = pref_len;
1128131626Sdes	while (--cnt >= 0) {
1129131623Sdes		pp = *prefp++;
1130131623Sdes		if (pp->ki_pid == (pid_t)pid)
1131131623Sdes			return ((int)pp->ki_ruid);
113224143Sjoerg	}
1133131623Sdes	return (-1);
113424143Sjoerg}
113524143Sjoerg
113624143Sjoergint
1137131622Sdesswapmode(int *retavail, int *retfree)
113824143Sjoerg{
113943053Sdillon	int n;
114043053Sdillon	int pagesize = getpagesize();
114143053Sdillon	struct kvm_swap swapary[1];
114224143Sjoerg
114343053Sdillon	*retavail = 0;
114443053Sdillon	*retfree = 0;
114524143Sjoerg
114643053Sdillon#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
114724143Sjoerg
114843053Sdillon	n = kvm_getswapinfo(kd, swapary, 1, 0);
114943697Sdillon	if (n < 0 || swapary[0].ksw_total == 0)
1150131623Sdes		return (0);
115124143Sjoerg
115243053Sdillon	*retavail = CONVERT(swapary[0].ksw_total);
115343053Sdillon	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
115424143Sjoerg
1155131626Sdes	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1156131623Sdes	return (n);
115743053Sdillon}
1158