machine.c revision 170774
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 170774 2007-06-15 12:03:07Z 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>
48168710Sstas#include <vis.h>
4924143Sjoerg
5024143Sjoerg#include "top.h"
5124143Sjoerg#include "machine.h"
5269375Sjhb#include "screen.h"
5372951Srwatson#include "utils.h"
5424143Sjoerg
5572951Srwatson#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
56146291Sobrien#define	SMPUNAMELEN	13
57146291Sobrien#define	UPUNAMELEN	15
5872951Srwatson
59145073Skeramidaextern struct process_select ps;
6092922Simpextern char* printable(char *);
6127340Speterstatic int smpmode;
62131402Salfredenum displaymodes displaymode;
63146291Sobrienstatic int namelength = 8;
6469375Sjhbstatic int cmdlengthdelta;
6524143Sjoerg
6672951Srwatson/* Prototypes for top internals */
6792922Simpvoid quit(int);
6824143Sjoerg
6924143Sjoerg/* get_process_info passes back a handle.  This is what it looks like: */
7024143Sjoerg
71158280Sbdestruct handle {
72131623Sdes	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
73131623Sdes	int remaining;			/* number of pointers remaining */
7424143Sjoerg};
7524143Sjoerg
7624143Sjoerg/* declarations for load_avg */
7724143Sjoerg#include "loadavg.h"
7824143Sjoerg
7924143Sjoerg/* define what weighted cpu is.  */
8069896Smckusick#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
8169896Smckusick			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
8224143Sjoerg
8324143Sjoerg/* what we consider to be process size: */
8469896Smckusick#define PROCSIZE(pp) ((pp)->ki_size / 1024)
8524143Sjoerg
86131402Salfred#define RU(pp)	(&(pp)->ki_rusage)
87131402Salfred#define RUTOT(pp) \
88131402Salfred	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
89131402Salfred
90131402Salfred
9124143Sjoerg/* definitions for indices in the nlist array */
9224143Sjoerg
9324143Sjoerg/*
9424143Sjoerg *  These definitions control the format of the per-process area
9524143Sjoerg */
9624143Sjoerg
97131402Salfredstatic char io_header[] =
98168799Srafan    "  PID%s %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
99131402Salfred
100131402Salfred#define io_Proc_format \
101168799Srafan    "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
102131402Salfred
103145073Skeramidastatic char smp_header_thr[] =
104168799Srafan    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
10527340Speterstatic char smp_header[] =
106168799Srafan    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
10724143Sjoerg
10827340Speter#define smp_Proc_format \
109168799Srafan    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
11024143Sjoerg
111145073Skeramidastatic char up_header_thr[] =
112168799Srafan    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
11327340Speterstatic char up_header[] =
114168799Srafan    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
11524143Sjoerg
11627340Speter#define up_Proc_format \
117168799Srafan    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
11824143Sjoerg
11924143Sjoerg
12024143Sjoerg/* process state names for the "STATE" column of the display */
12124143Sjoerg/* the extra nulls in the string "run" are for adding a slash and
12224143Sjoerg   the processor number when needed */
12324143Sjoerg
124158280Sbdechar *state_abbrev[] = {
125131623Sdes	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
12624143Sjoerg};
12724143Sjoerg
12824143Sjoerg
12924143Sjoergstatic kvm_t *kd;
13024143Sjoerg
13124143Sjoerg/* values that we stash away in _init and use in later routines */
13224143Sjoerg
13324143Sjoergstatic double logcpu;
13424143Sjoerg
13524143Sjoerg/* these are retrieved from the kernel in _init */
13624143Sjoerg
13724143Sjoergstatic load_avg  ccpu;
13824143Sjoerg
13972951Srwatson/* these are used in the get_ functions */
14024143Sjoerg
14172951Srwatsonstatic int lastpid;
14224143Sjoerg
14324143Sjoerg/* these are for calculating cpu state percentages */
14424143Sjoerg
14524143Sjoergstatic long cp_time[CPUSTATES];
14624143Sjoergstatic long cp_old[CPUSTATES];
14724143Sjoergstatic long cp_diff[CPUSTATES];
14824143Sjoerg
14924143Sjoerg/* these are for detailing the process states */
15024143Sjoerg
15165557Sjasoneint process_states[8];
15224143Sjoergchar *procstatenames[] = {
153131623Sdes	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
154131623Sdes	" zombie, ", " waiting, ", " lock, ",
155131623Sdes	NULL
15624143Sjoerg};
15724143Sjoerg
15824143Sjoerg/* these are for detailing the cpu states */
15924143Sjoerg
16024143Sjoergint cpu_states[CPUSTATES];
16124143Sjoergchar *cpustatenames[] = {
162131623Sdes	"user", "nice", "system", "interrupt", "idle", NULL
16324143Sjoerg};
16424143Sjoerg
16524143Sjoerg/* these are for detailing the memory statistics */
16624143Sjoerg
16724143Sjoergint memory_stats[7];
16824143Sjoergchar *memorynames[] = {
169158280Sbde	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
170158280Sbde	"K Free", NULL
17124143Sjoerg};
17224143Sjoerg
17324143Sjoergint swap_stats[7];
17424143Sjoergchar *swapnames[] = {
175131623Sdes	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
176131623Sdes	NULL
17724143Sjoerg};
17824143Sjoerg
17924143Sjoerg
18024143Sjoerg/* these are for keeping track of the proc array */
18124143Sjoerg
18224143Sjoergstatic int nproc;
18324143Sjoergstatic int onproc = -1;
18424143Sjoergstatic int pref_len;
18524143Sjoergstatic struct kinfo_proc *pbase;
18624143Sjoergstatic struct kinfo_proc **pref;
187131402Salfredstatic struct kinfo_proc *previous_procs;
188131402Salfredstatic struct kinfo_proc **previous_pref;
189131402Salfredstatic int previous_proc_count = 0;
190131402Salfredstatic int previous_proc_count_max = 0;
19124143Sjoerg
192131412Salfred/* total number of io operations */
193131412Salfredstatic long total_inblock;
194131412Salfredstatic long total_oublock;
195131412Salfredstatic long total_majflt;
196131412Salfred
19724143Sjoerg/* these are for getting the memory statistics */
19824143Sjoerg
19924143Sjoergstatic int pageshift;		/* log base 2 of the pagesize */
20024143Sjoerg
20124143Sjoerg/* define pagetok in terms of pageshift */
20224143Sjoerg
20324143Sjoerg#define pagetok(size) ((size) << pageshift)
20424143Sjoerg
20524143Sjoerg/* useful externals */
20624143Sjoerglong percentages();
20724143Sjoerg
20838278Swosch#ifdef ORDER
209131829Skeramida/*
210145073Skeramida * Sorting orders.  The first element is the default.
211131829Skeramida */
212133817Salfredchar *ordernames[] = {
213145073Skeramida	"cpu", "size", "res", "time", "pri", "threads",
214168799Srafan	"total", "read", "write", "fault", "vcsw", "ivcsw",
215168799Srafan	"jid", NULL
21638278Swosch};
21738278Swosch#endif
21838278Swosch
219168799Srafanstatic int compare_jid(const void *a, const void *b);
220158282Sbdestatic int compare_pid(const void *a, const void *b);
221158282Sbdestatic const char *format_nice(const struct kinfo_proc *pp);
222158282Sbdestatic void getsysctl(const char *name, void *ptr, size_t len);
223158282Sbdestatic int swapmode(int *retavail, int *retfree);
224158282Sbde
22524143Sjoergint
226131622Sdesmachine_init(struct statics *statics)
22724143Sjoerg{
228131623Sdes	int pagesize;
229131623Sdes	size_t modelen;
230131623Sdes	struct passwd *pw;
23124143Sjoerg
232131623Sdes	modelen = sizeof(smpmode);
233158280Sbde	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
234158280Sbde	    NULL, 0) != 0 &&
235158280Sbde	    sysctlbyname("kern.smp.active", &smpmode, &modelen,
236158280Sbde	    NULL, 0) != 0) ||
237131623Sdes	    modelen != sizeof(smpmode))
238131623Sdes		smpmode = 0;
23927340Speter
240131623Sdes	while ((pw = getpwent()) != NULL) {
241131623Sdes		if (strlen(pw->pw_name) > namelength)
242131623Sdes			namelength = strlen(pw->pw_name);
243131623Sdes	}
244146291Sobrien	if (smpmode && namelength > SMPUNAMELEN)
245146291Sobrien		namelength = SMPUNAMELEN;
246146291Sobrien	else if (namelength > UPUNAMELEN)
247146291Sobrien		namelength = UPUNAMELEN;
24827390Speter
249131626Sdes	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
250131626Sdes	if (kd == NULL)
251131626Sdes		return (-1);
25224143Sjoerg
253131623Sdes	GETSYSCTL("kern.ccpu", ccpu);
25424143Sjoerg
255131623Sdes	/* this is used in calculating WCPU -- calculate it ahead of time */
256131623Sdes	logcpu = log(loaddouble(ccpu));
25724143Sjoerg
258131623Sdes	pbase = NULL;
259131623Sdes	pref = NULL;
260131623Sdes	nproc = 0;
261131623Sdes	onproc = -1;
262158280Sbde
263158280Sbde	/* get the page size and calculate pageshift from it */
264131623Sdes	pagesize = getpagesize();
265131623Sdes	pageshift = 0;
266131626Sdes	while (pagesize > 1) {
267131623Sdes		pageshift++;
268131623Sdes		pagesize >>= 1;
269131623Sdes	}
27024143Sjoerg
271131623Sdes	/* we only need the amount of log(2)1024 for our conversion */
272131623Sdes	pageshift -= LOG1024;
27324143Sjoerg
274131623Sdes	/* fill in the statics information */
275131623Sdes	statics->procstate_names = procstatenames;
276131623Sdes	statics->cpustate_names = cpustatenames;
277131623Sdes	statics->memory_names = memorynames;
278131623Sdes	statics->swap_names = swapnames;
27938278Swosch#ifdef ORDER
280133817Salfred	statics->order_names = ordernames;
28138278Swosch#endif
28224143Sjoerg
283131623Sdes	/* all done! */
284131623Sdes	return (0);
28524143Sjoerg}
28624143Sjoerg
287131310Salfredchar *
288131622Sdesformat_header(char *uname_field)
28924143Sjoerg{
290131623Sdes	static char Header[128];
291131623Sdes	const char *prehead;
29224143Sjoerg
293131623Sdes	switch (displaymode) {
294131623Sdes	case DISP_CPU:
295145073Skeramida		/*
296145073Skeramida		 * The logic of picking the right header format seems reverse
297145073Skeramida		 * here because we only want to display a THR column when
298145073Skeramida		 * "thread mode" is off (and threads are not listed as
299145073Skeramida		 * separate lines).
300145073Skeramida		 */
301145073Skeramida		prehead = smpmode ?
302145073Skeramida		    (ps.thread ? smp_header : smp_header_thr) :
303145073Skeramida		    (ps.thread ? up_header : up_header_thr);
304146342Skeramida		snprintf(Header, sizeof(Header), prehead,
305168799Srafan		    ps.jail ? " JID" : "",
306146342Skeramida		    namelength, namelength, uname_field,
307146342Skeramida		    ps.wcpu ? "WCPU" : "CPU");
308131623Sdes		break;
309131623Sdes	case DISP_IO:
310131623Sdes		prehead = io_header;
311146342Skeramida		snprintf(Header, sizeof(Header), prehead,
312168799Srafan		    ps.jail ? " JID" : "",
313146342Skeramida		    namelength, namelength, uname_field);
314131623Sdes		break;
315131623Sdes	}
316131623Sdes	cmdlengthdelta = strlen(Header) - 7;
317131623Sdes	return (Header);
31824143Sjoerg}
31924143Sjoerg
32024143Sjoergstatic int swappgsin = -1;
32124143Sjoergstatic int swappgsout = -1;
32224143Sjoergextern struct timeval timeout;
32324143Sjoerg
32424143Sjoergvoid
325131622Sdesget_system_info(struct system_info *si)
32624143Sjoerg{
327131623Sdes	long total;
328131623Sdes	struct loadavg sysload;
329131623Sdes	int mib[2];
330131623Sdes	struct timeval boottime;
331131623Sdes	size_t bt_size;
332131626Sdes	int i;
33324143Sjoerg
334131623Sdes	/* get the cp_time array */
335131623Sdes	GETSYSCTL("kern.cp_time", cp_time);
336131623Sdes	GETSYSCTL("vm.loadavg", sysload);
337131623Sdes	GETSYSCTL("kern.lastpid", lastpid);
33824143Sjoerg
339131623Sdes	/* convert load averages to doubles */
340131626Sdes	for (i = 0; i < 3; i++)
341131626Sdes		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
34224143Sjoerg
343131623Sdes	/* convert cp_time counts to percentages */
344131623Sdes	total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
34524143Sjoerg
346131623Sdes	/* sum memory & swap statistics */
347131623Sdes	{
348131623Sdes		static unsigned int swap_delay = 0;
349131623Sdes		static int swapavail = 0;
350131623Sdes		static int swapfree = 0;
351131623Sdes		static int bufspace = 0;
352131623Sdes		static int nspgsin, nspgsout;
35324143Sjoerg
354131623Sdes		GETSYSCTL("vfs.bufspace", bufspace);
355131623Sdes		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
356131623Sdes		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
357131623Sdes		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
358131623Sdes		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
359131623Sdes		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
360131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
361131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
362131623Sdes		/* convert memory stats to Kbytes */
363131623Sdes		memory_stats[0] = pagetok(memory_stats[0]);
364131623Sdes		memory_stats[1] = pagetok(memory_stats[1]);
365131623Sdes		memory_stats[2] = pagetok(memory_stats[2]);
366131623Sdes		memory_stats[3] = pagetok(memory_stats[3]);
367131623Sdes		memory_stats[4] = bufspace / 1024;
368131623Sdes		memory_stats[5] = pagetok(memory_stats[5]);
369131623Sdes		memory_stats[6] = -1;
37024143Sjoerg
371131623Sdes		/* first interval */
372131623Sdes		if (swappgsin < 0) {
373131623Sdes			swap_stats[4] = 0;
374131623Sdes			swap_stats[5] = 0;
375131623Sdes		}
37624143Sjoerg
377131623Sdes		/* compute differences between old and new swap statistic */
378131623Sdes		else {
379131623Sdes			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
380131623Sdes			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
381131623Sdes		}
38224143Sjoerg
383131623Sdes		swappgsin = nspgsin;
384131623Sdes		swappgsout = nspgsout;
38524143Sjoerg
386131623Sdes		/* call CPU heavy swapmode() only for changes */
387131623Sdes		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
388131623Sdes			swap_stats[3] = swapmode(&swapavail, &swapfree);
389131623Sdes			swap_stats[0] = swapavail;
390131623Sdes			swap_stats[1] = swapavail - swapfree;
391131623Sdes			swap_stats[2] = swapfree;
392131623Sdes		}
393131623Sdes		swap_delay = 1;
394131623Sdes		swap_stats[6] = -1;
39524143Sjoerg	}
39624143Sjoerg
397131623Sdes	/* set arrays and strings */
398131623Sdes	si->cpustates = cpu_states;
399131623Sdes	si->memory = memory_stats;
400131623Sdes	si->swap = swap_stats;
40124143Sjoerg
40224143Sjoerg
403131623Sdes	if (lastpid > 0) {
404131623Sdes		si->last_pid = lastpid;
405131623Sdes	} else {
406131623Sdes		si->last_pid = -1;
407131623Sdes	}
40842447Sobrien
409131623Sdes	/*
410131623Sdes	 * Print how long system has been up.
411131623Sdes	 * (Found by looking getting "boottime" from the kernel)
412131623Sdes	 */
413131623Sdes	mib[0] = CTL_KERN;
414131623Sdes	mib[1] = KERN_BOOTTIME;
415131623Sdes	bt_size = sizeof(boottime);
416131623Sdes	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
417131623Sdes	    boottime.tv_sec != 0) {
418131623Sdes		si->boottime = boottime;
419131623Sdes	} else {
420131623Sdes		si->boottime.tv_sec = -1;
421131623Sdes	}
42224143Sjoerg}
42324143Sjoerg
424132015Salfred#define NOPROC	((void *)-1)
425132015Salfred
426132955Salfred/*
427132955Salfred * We need to compare data from the old process entry with the new
428132955Salfred * process entry.
429132955Salfred * To facilitate doing this quickly we stash a pointer in the kinfo_proc
430132955Salfred * structure to cache the mapping.  We also use a negative cache pointer
431132955Salfred * of NOPROC to avoid duplicate lookups.
432132955Salfred * XXX: this could be done when the actual processes are fetched, we do
433132955Salfred * it here out of laziness.
434132955Salfred */
435131402Salfredconst struct kinfo_proc *
436131402Salfredget_old_proc(struct kinfo_proc *pp)
437131402Salfred{
438131402Salfred	struct kinfo_proc **oldpp, *oldp;
439131402Salfred
440132955Salfred	/*
441132955Salfred	 * If this is the first fetch of the kinfo_procs then we don't have
442132955Salfred	 * any previous entries.
443132955Salfred	 */
444131402Salfred	if (previous_proc_count == 0)
445131402Salfred		return (NULL);
446132955Salfred	/* negative cache? */
447132015Salfred	if (pp->ki_udata == NOPROC)
448132015Salfred		return (NULL);
449132955Salfred	/* cached? */
450132015Salfred	if (pp->ki_udata != NULL)
451132015Salfred		return (pp->ki_udata);
452132955Salfred	/*
453132955Salfred	 * Not cached,
454132955Salfred	 * 1) look up based on pid.
455132955Salfred	 * 2) compare process start.
456132955Salfred	 * If we fail here, then setup a negative cache entry, otherwise
457132955Salfred	 * cache it.
458132955Salfred	 */
459131402Salfred	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
460131626Sdes	    sizeof(*previous_pref), compare_pid);
461132015Salfred	if (oldpp == NULL) {
462132015Salfred		pp->ki_udata = NOPROC;
463131402Salfred		return (NULL);
464132015Salfred	}
465131402Salfred	oldp = *oldpp;
466132015Salfred	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
467132015Salfred		pp->ki_udata = NOPROC;
468131402Salfred		return (NULL);
469132015Salfred	}
470132015Salfred	pp->ki_udata = oldp;
471131402Salfred	return (oldp);
472131402Salfred}
473131402Salfred
474132955Salfred/*
475132955Salfred * Return the total amount of IO done in blocks in/out and faults.
476132955Salfred * store the values individually in the pointers passed in.
477132955Salfred */
478131402Salfredlong
479158280Sbdeget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
480158280Sbde    long *vcsw, long *ivcsw)
481131402Salfred{
482131402Salfred	const struct kinfo_proc *oldp;
483131402Salfred	static struct kinfo_proc dummy;
484131402Salfred	long ret;
485131402Salfred
486131402Salfred	oldp = get_old_proc(pp);
487131402Salfred	if (oldp == NULL) {
488131402Salfred		bzero(&dummy, sizeof(dummy));
489131402Salfred		oldp = &dummy;
490131402Salfred	}
491131412Salfred	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
492131412Salfred	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
493131412Salfred	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
494133817Salfred	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
495133817Salfred	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
496131402Salfred	ret =
497131402Salfred	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
498131402Salfred	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
499131402Salfred	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
500131402Salfred	return (ret);
501131402Salfred}
502131402Salfred
503132955Salfred/*
504132955Salfred * Return the total number of block in/out and faults by a process.
505132955Salfred */
506131412Salfredlong
507131412Salfredget_io_total(struct kinfo_proc *pp)
508131412Salfred{
509131412Salfred	long dummy;
510131412Salfred
511133817Salfred	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
512131412Salfred}
513131412Salfred
51424143Sjoergstatic struct handle handle;
51524143Sjoerg
516131310Salfredcaddr_t
517131622Sdesget_process_info(struct system_info *si, struct process_select *sel,
518131626Sdes    int (*compare)(const void *, const void *))
51924143Sjoerg{
520131623Sdes	int i;
521131623Sdes	int total_procs;
522131623Sdes	long p_io;
523133817Salfred	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
524131623Sdes	int active_procs;
525131623Sdes	struct kinfo_proc **prefp;
526131623Sdes	struct kinfo_proc *pp;
527131623Sdes	struct kinfo_proc *prev_pp = NULL;
52824143Sjoerg
529131623Sdes	/* these are copied out of sel for speed */
530131623Sdes	int show_idle;
531131623Sdes	int show_self;
532131623Sdes	int show_system;
533131623Sdes	int show_uid;
534131623Sdes	int show_command;
53524143Sjoerg
536131623Sdes	/*
537131623Sdes	 * Save the previous process info.
538131623Sdes	 */
539131623Sdes	if (previous_proc_count_max < nproc) {
540131623Sdes		free(previous_procs);
541131626Sdes		previous_procs = malloc(nproc * sizeof(*previous_procs));
542131623Sdes		free(previous_pref);
543131626Sdes		previous_pref = malloc(nproc * sizeof(*previous_pref));
544131623Sdes		if (previous_procs == NULL || previous_pref == NULL) {
545131623Sdes			(void) fprintf(stderr, "top: Out of memory.\n");
546131623Sdes			quit(23);
547131623Sdes		}
548131623Sdes		previous_proc_count_max = nproc;
549131623Sdes	}
550131623Sdes	if (nproc) {
551131623Sdes		for (i = 0; i < nproc; i++)
552131623Sdes			previous_pref[i] = &previous_procs[i];
553131626Sdes		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
554158280Sbde		qsort(previous_pref, nproc, sizeof(*previous_pref),
555158280Sbde		    compare_pid);
556131623Sdes	}
557131623Sdes	previous_proc_count = nproc;
558131402Salfred
559131623Sdes	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
560131623Sdes	if (nproc > onproc)
561131626Sdes		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
562131623Sdes	if (pref == NULL || pbase == NULL) {
563131623Sdes		(void) fprintf(stderr, "top: Out of memory.\n");
564131623Sdes		quit(23);
565131623Sdes	}
566131623Sdes	/* get a pointer to the states summary array */
567131623Sdes	si->procstates = process_states;
56824143Sjoerg
569131623Sdes	/* set up flags which define what we are going to select */
570131623Sdes	show_idle = sel->idle;
571132024Sdes	show_self = sel->self == -1;
572131623Sdes	show_system = sel->system;
573131623Sdes	show_uid = sel->uid != -1;
574131623Sdes	show_command = sel->command != NULL;
57524143Sjoerg
576131623Sdes	/* count up process states and get pointers to interesting procs */
577131623Sdes	total_procs = 0;
578131623Sdes	active_procs = 0;
579131623Sdes	total_inblock = 0;
580131623Sdes	total_oublock = 0;
581131623Sdes	total_majflt = 0;
582131623Sdes	memset((char *)process_states, 0, sizeof(process_states));
583131623Sdes	prefp = pref;
584131626Sdes	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
585131619Sdes
586131623Sdes		if (pp->ki_stat == 0)
587132024Sdes			/* not in use */
588132024Sdes			continue;
589131619Sdes
590131623Sdes		if (!show_self && pp->ki_pid == sel->self)
591131623Sdes			/* skip self */
592131623Sdes			continue;
593131619Sdes
594131623Sdes		if (!show_system && (pp->ki_flag & P_SYSTEM))
595131623Sdes			/* skip system process */
596131623Sdes			continue;
597131619Sdes
598158280Sbde		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
599158280Sbde		    &p_vcsw, &p_ivcsw);
600131623Sdes		total_inblock += p_inblock;
601131623Sdes		total_oublock += p_oublock;
602131623Sdes		total_majflt += p_majflt;
603131623Sdes		total_procs++;
604131626Sdes		process_states[pp->ki_stat]++;
605131619Sdes
606131623Sdes		if (pp->ki_stat == SZOMB)
607131623Sdes			/* skip zombies */
608131623Sdes			continue;
609131619Sdes
610131623Sdes		if (displaymode == DISP_CPU && !show_idle &&
611159520Sse		    (pp->ki_pctcpu == 0 ||
612159520Sse		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
613131623Sdes			/* skip idle or non-running processes */
614131623Sdes			continue;
615131619Sdes
616131623Sdes		if (displaymode == DISP_IO && !show_idle && p_io == 0)
617131623Sdes			/* skip processes that aren't doing I/O */
618131623Sdes			continue;
619131619Sdes
620131623Sdes		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
621158280Sbde			/* skip proc. that don't belong to the selected UID */
622131623Sdes			continue;
623131619Sdes
624131623Sdes		/*
625131623Sdes		 * When not showing threads, take the first thread
626131623Sdes		 * for output and add the fields that we can from
627131623Sdes		 * the rest of the process's threads rather than
628131623Sdes		 * using the system's mostly-broken KERN_PROC_PROC.
629131623Sdes		 */
630131626Sdes		if (sel->thread || prev_pp == NULL ||
631131626Sdes		    prev_pp->ki_pid != pp->ki_pid) {
632131623Sdes			*prefp++ = pp;
633131623Sdes			active_procs++;
634131623Sdes			prev_pp = pp;
635131623Sdes		} else {
636131623Sdes			prev_pp->ki_pctcpu += pp->ki_pctcpu;
637131623Sdes		}
638131623Sdes	}
639131623Sdes
640131623Sdes	/* if requested, sort the "interesting" processes */
641131623Sdes	if (compare != NULL)
642131626Sdes		qsort(pref, active_procs, sizeof(*pref), compare);
64324143Sjoerg
644131623Sdes	/* remember active and total counts */
645131623Sdes	si->p_total = total_procs;
646131623Sdes	si->p_active = pref_len = active_procs;
64724143Sjoerg
648131623Sdes	/* pass back a handle */
649131623Sdes	handle.next_proc = pref;
650131623Sdes	handle.remaining = active_procs;
651131623Sdes	return ((caddr_t)&handle);
65224143Sjoerg}
65324143Sjoerg
654131626Sdesstatic char fmt[128];	/* static area where result is built */
65524143Sjoerg
656131310Salfredchar *
657168710Sstasformat_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
65824143Sjoerg{
659131623Sdes	struct kinfo_proc *pp;
660131623Sdes	const struct kinfo_proc *oldp;
661131623Sdes	long cputime;
662131623Sdes	double pct;
663131623Sdes	struct handle *hp;
664131623Sdes	char status[16];
665131623Sdes	int state;
666131623Sdes	struct rusage ru, *rup;
667131623Sdes	long p_tot, s_tot;
668168799Srafan	char *proc_fmt, thr_buf[6], jid_buf[6];
669168710Sstas	char *cmdbuf = NULL;
670168710Sstas	char **args;
67124143Sjoerg
672131623Sdes	/* find and remember the next proc structure */
673131623Sdes	hp = (struct handle *)handle;
674131623Sdes	pp = *(hp->next_proc++);
675131623Sdes	hp->remaining--;
676131620Sdes
677131623Sdes	/* get the process's command name */
678131623Sdes	if ((pp->ki_sflag & PS_INMEM) == 0) {
679131623Sdes		/*
680131623Sdes		 * Print swapped processes as <pname>
681131623Sdes		 */
682158280Sbde		size_t len;
683158280Sbde
684158280Sbde		len = strlen(pp->ki_comm);
685131626Sdes		if (len > sizeof(pp->ki_comm) - 3)
686131626Sdes			len = sizeof(pp->ki_comm) - 3;
687131626Sdes		memmove(pp->ki_comm + 1, pp->ki_comm, len);
688131626Sdes		pp->ki_comm[0] = '<';
689131626Sdes		pp->ki_comm[len + 1] = '>';
690131626Sdes		pp->ki_comm[len + 2] = '\0';
691131623Sdes	}
692131623Sdes
69324143Sjoerg	/*
694131623Sdes	 * Convert the process's runtime from microseconds to seconds.  This
695131623Sdes	 * time includes the interrupt time although that is not wanted here.
696131623Sdes	 * ps(1) is similarly sloppy.
69724143Sjoerg	 */
698131623Sdes	cputime = (pp->ki_runtime + 500000) / 1000000;
69924143Sjoerg
700131623Sdes	/* calculate the base for cpu percentages */
701131623Sdes	pct = pctdouble(pp->ki_pctcpu);
70224143Sjoerg
703131623Sdes	/* generate "STATE" field */
704131623Sdes	switch (state = pp->ki_stat) {
70524143Sjoerg	case SRUN:
706131623Sdes		if (smpmode && pp->ki_oncpu != 0xff)
707131623Sdes			sprintf(status, "CPU%d", pp->ki_oncpu);
708131623Sdes		else
709131623Sdes			strcpy(status, "RUN");
710131623Sdes		break;
711104388Sjhb	case SLOCK:
712131623Sdes		if (pp->ki_kiflag & KI_LOCKBLOCK) {
713131623Sdes			sprintf(status, "*%.6s", pp->ki_lockname);
714131623Sdes			break;
715131623Sdes		}
716131623Sdes		/* fall through */
71724143Sjoerg	case SSLEEP:
718131623Sdes		if (pp->ki_wmesg != NULL) {
719131623Sdes			sprintf(status, "%.6s", pp->ki_wmesg);
720131623Sdes			break;
721131623Sdes		}
722131623Sdes		/* FALLTHROUGH */
72324143Sjoerg	default:
72443720Sfenner
725131623Sdes		if (state >= 0 &&
726131623Sdes		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
727131626Sdes			sprintf(status, "%.6s", state_abbrev[state]);
728131623Sdes		else
729131623Sdes			sprintf(status, "?%5d", state);
730131623Sdes		break;
731131623Sdes	}
73224143Sjoerg
733168710Sstas	cmdbuf = (char *)malloc(cmdlengthdelta + 1);
734168710Sstas	if (cmdbuf == NULL) {
735168710Sstas		warn("malloc(%d)", cmdlengthdelta + 1);
736168710Sstas		return NULL;
737168710Sstas	}
738168710Sstas
739168710Sstas	if (!(flags & FMT_SHOWARGS)) {
740168710Sstas		snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
741168710Sstas	}
742168710Sstas	else if (pp->ki_args == NULL ||
743168710Sstas	    (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL || !(*args))
744168710Sstas		snprintf(cmdbuf, cmdlengthdelta, "[%s]", pp->ki_comm);
745168710Sstas	else {
746168710Sstas		char *src, *dst, *argbuf;
747168710Sstas		char *cmd;
748168710Sstas		size_t argbuflen;
749168710Sstas		size_t len;
750168710Sstas
751168710Sstas		argbuflen = cmdlengthdelta * 4;
752168710Sstas		argbuf = (char *)malloc(argbuflen + 1);
753168710Sstas		if (argbuf == NULL) {
754168710Sstas			warn("malloc(%d)", argbuflen + 1);
755168710Sstas			free(cmdbuf);
756168710Sstas			return NULL;
757168710Sstas		}
758168710Sstas
759168710Sstas		dst = argbuf;
760168710Sstas
761168710Sstas		/* Extract cmd name from argv */
762168710Sstas		cmd = strrchr(*args, '/');
763168710Sstas		if (cmd == NULL)
764168710Sstas			cmd = *args;
765168710Sstas		else
766168710Sstas			cmd++;
767168710Sstas
768168710Sstas		for (; (src = *args++) != NULL; ) {
769168710Sstas			if (*src == '\0')
770168710Sstas				continue;
771168710Sstas			len = (argbuflen - (dst - argbuf) - 1) / 4;
772168710Sstas			strvisx(dst, src, strlen(src) < len ? strlen(src) : len,
773168710Sstas			    VIS_NL | VIS_CSTYLE);
774168710Sstas			while (*dst != '\0')
775168710Sstas				dst++;
776168710Sstas			if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
777168710Sstas				*dst++ = ' '; /* add delimiting space */
778168710Sstas		}
779168710Sstas		if (dst != argbuf && dst[-1] == ' ')
780168710Sstas			dst--;
781168710Sstas		*dst = '\0';
782168710Sstas
783168710Sstas		if (strcmp(cmd, pp->ki_comm) != 0 )
784168710Sstas			snprintf(cmdbuf, cmdlengthdelta, "%s (%s)",argbuf, \
785168710Sstas				 pp->ki_comm);
786168710Sstas		else
787168710Sstas			strlcpy(cmdbuf, argbuf, cmdlengthdelta);
788168710Sstas
789168710Sstas		free(argbuf);
790168710Sstas	}
791168710Sstas
792168799Srafan	if (ps.jail == 0)
793168799Srafan		jid_buf[0] = '\0';
794168799Srafan	else
795168799Srafan		snprintf(jid_buf, sizeof(jid_buf), " %*d",
796168799Srafan		    sizeof(jid_buf) - 3, pp->ki_jid);
797168799Srafan
798131623Sdes	if (displaymode == DISP_IO) {
799131623Sdes		oldp = get_old_proc(pp);
800131623Sdes		if (oldp != NULL) {
801158280Sbde			ru.ru_inblock = RU(pp)->ru_inblock -
802158280Sbde			    RU(oldp)->ru_inblock;
803158280Sbde			ru.ru_oublock = RU(pp)->ru_oublock -
804158280Sbde			    RU(oldp)->ru_oublock;
805131623Sdes			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
806133817Salfred			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
807133817Salfred			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
808131623Sdes			rup = &ru;
809131623Sdes		} else {
810131623Sdes			rup = RU(pp);
811131623Sdes		}
812131623Sdes		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
813131623Sdes		s_tot = total_inblock + total_oublock + total_majflt;
814131402Salfred
815131623Sdes		sprintf(fmt, io_Proc_format,
816131623Sdes		    pp->ki_pid,
817168799Srafan		    jid_buf,
818158280Sbde		    namelength, namelength, (*get_userid)(pp->ki_ruid),
819133817Salfred		    rup->ru_nvcsw,
820133817Salfred		    rup->ru_nivcsw,
821131626Sdes		    rup->ru_inblock,
822131626Sdes		    rup->ru_oublock,
823131626Sdes		    rup->ru_majflt,
824131626Sdes		    p_tot,
825131626Sdes		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
826131623Sdes		    screen_width > cmdlengthdelta ?
827131623Sdes		    screen_width - cmdlengthdelta : 0,
828168710Sstas		    printable(cmdbuf));
829168710Sstas
830168710Sstas		free(cmdbuf);
831168710Sstas
832131623Sdes		return (fmt);
833131623Sdes	}
834145073Skeramida
835131623Sdes	/* format this entry */
836145073Skeramida	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
837145073Skeramida	if (ps.thread != 0)
838145073Skeramida		thr_buf[0] = '\0';
839145073Skeramida	else
840145073Skeramida		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
841145073Skeramida		    sizeof(thr_buf) - 2, pp->ki_numthreads);
842145073Skeramida
843145073Skeramida	sprintf(fmt, proc_fmt,
84469896Smckusick	    pp->ki_pid,
845168799Srafan	    jid_buf,
846158280Sbde	    namelength, namelength, (*get_userid)(pp->ki_ruid),
847145073Skeramida	    thr_buf,
84872377Sjake	    pp->ki_pri.pri_level - PZERO,
849158282Sbde	    format_nice(pp),
85037100Sdt	    format_k2(PROCSIZE(pp)),
85169896Smckusick	    format_k2(pagetok(pp->ki_rssize)),
85224143Sjoerg	    status,
85369896Smckusick	    smpmode ? pp->ki_lastcpu : 0,
85424143Sjoerg	    format_time(cputime),
855146342Skeramida	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
856158280Sbde	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
857168710Sstas	    printable(cmdbuf));
85824143Sjoerg
859168710Sstas	free(cmdbuf);
860168710Sstas
861131623Sdes	/* return the result */
862131623Sdes	return (fmt);
86324143Sjoerg}
86424143Sjoerg
865131310Salfredstatic void
866158282Sbdegetsysctl(const char *name, void *ptr, size_t len)
86724143Sjoerg{
868131623Sdes	size_t nlen = len;
869131310Salfred
870131623Sdes	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
871131623Sdes		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
872131623Sdes		    strerror(errno));
873131623Sdes		quit(23);
874131623Sdes	}
875131623Sdes	if (nlen != len) {
876158280Sbde		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
877158280Sbde		    name, (unsigned long)len, (unsigned long)nlen);
878131623Sdes		quit(23);
879131623Sdes	}
88024143Sjoerg}
88172951Srwatson
882164058Sbdestatic const char *
883164058Sbdeformat_nice(const struct kinfo_proc *pp)
884158282Sbde{
885164058Sbde	const char *fifo, *kthread;
886164058Sbde	int rtpri;
887164058Sbde	static char nicebuf[4 + 1];
888158282Sbde
889164058Sbde	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
890164058Sbde	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
891164058Sbde	switch (PRI_BASE(pp->ki_pri.pri_class)) {
892164058Sbde	case PRI_ITHD:
893164058Sbde		return ("-");
894164058Sbde	case PRI_REALTIME:
895170774Sbde		/*
896170774Sbde		 * XXX: the kernel doesn't tell us the original rtprio and
897170774Sbde		 * doesn't really know what it was, so to recover it we
898170774Sbde		 * must be more chummy with the implementation than the
899170774Sbde		 * implementation is with itself.  pri_user gives a
900170774Sbde		 * constant "base" priority, but is only initialized
901170774Sbde		 * properly for user threads.  pri_native gives what the
902170774Sbde		 * kernel calls the "base" priority, but it isn't constant
903170774Sbde		 * since it is changed by priority propagation.  pri_native
904170774Sbde		 * also isn't properly initialized for all threads, but it
905170774Sbde		 * is properly initialized for kernel realtime and idletime
906170774Sbde		 * threads.  Thus we use pri_user for the base priority of
907170774Sbde		 * user threads (it is always correct) and pri_native for
908170774Sbde		 * the base priority of kernel realtime and idletime threads
909170774Sbde		 * (there is nothing better, and it is usually correct).
910170774Sbde		 *
911170774Sbde		 * The field width and thus the buffer are too small for
912170774Sbde		 * values like "kr31F", but such values shouldn't occur,
913170774Sbde		 * and if they do then the tailing "F" is not displayed.
914170774Sbde		 */
915170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
916170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
917164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
918164058Sbde		    kthread, rtpri, fifo);
919164058Sbde		break;
920164058Sbde	case PRI_TIMESHARE:
921164058Sbde		if (pp->ki_flag & P_KTHREAD)
922164058Sbde			return ("-");
923164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
924164058Sbde		break;
925164058Sbde	case PRI_IDLE:
926170774Sbde		/* XXX: as above. */
927170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
928170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
929164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
930164058Sbde		    kthread, rtpri, fifo);
931164058Sbde		break;
932164058Sbde	default:
933164058Sbde		return ("?");
934164058Sbde	}
935158282Sbde	return (nicebuf);
936158282Sbde}
937158282Sbde
93838278Swosch/* comparison routines for qsort */
93924143Sjoerg
940158282Sbdestatic int
941131622Sdescompare_pid(const void *p1, const void *p2)
942131402Salfred{
943131623Sdes	const struct kinfo_proc * const *pp1 = p1;
944131623Sdes	const struct kinfo_proc * const *pp2 = p2;
945131402Salfred
946131623Sdes	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
947131623Sdes		abort();
948131402Salfred
949131623Sdes	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
950131402Salfred}
951131402Salfred
95224143Sjoerg/*
95324143Sjoerg *  proc_compare - comparison function for "qsort"
95424143Sjoerg *	Compares the resource consumption of two processes using five
955131620Sdes *	distinct keys.  The keys (in descending order of importance) are:
956131620Sdes *	percent cpu, cpu ticks, state, resident set size, total virtual
957131620Sdes *	memory usage.  The process states are ordered as follows (from least
958131620Sdes *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
959131620Sdes *	array declaration below maps a process state index into a number
960131620Sdes *	that reflects this ordering.
96124143Sjoerg */
96224143Sjoerg
963158280Sbdestatic int sorted_state[] = {
964131623Sdes	0,	/* not used		*/
965131623Sdes	3,	/* sleep		*/
966131623Sdes	1,	/* ABANDONED (WAIT)	*/
967131623Sdes	6,	/* run			*/
968131623Sdes	5,	/* start		*/
969131623Sdes	2,	/* zombie		*/
970131623Sdes	4	/* stop			*/
97124143Sjoerg};
97238278Swosch
973131620Sdes
974146343Skeramida#define ORDERKEY_PCTCPU(a, b) do { \
975146343Skeramida	long diff; \
976146343Skeramida	if (ps.wcpu) \
977158280Sbde		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
978158280Sbde		    (b))) - \
979158280Sbde		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
980158280Sbde		    (a))); \
981146343Skeramida	else \
982146343Skeramida		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
983146343Skeramida	if (diff != 0) \
984146343Skeramida		return (diff > 0 ? 1 : -1); \
985131626Sdes} while (0)
98638278Swosch
987131626Sdes#define ORDERKEY_CPTICKS(a, b) do { \
988131628Sdes	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
989131626Sdes	if (diff != 0) \
990131626Sdes		return (diff > 0 ? 1 : -1); \
991131626Sdes} while (0)
99238278Swosch
993131626Sdes#define ORDERKEY_STATE(a, b) do { \
994131626Sdes	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
995131626Sdes	if (diff != 0) \
996131626Sdes		return (diff > 0 ? 1 : -1); \
997131626Sdes} while (0)
99838278Swosch
999131626Sdes#define ORDERKEY_PRIO(a, b) do { \
1000131628Sdes	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1001131626Sdes	if (diff != 0) \
1002131626Sdes		return (diff > 0 ? 1 : -1); \
1003131626Sdes} while (0)
100438278Swosch
1005145073Skeramida#define	ORDERKEY_THREADS(a, b) do { \
1006145073Skeramida	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1007145073Skeramida	if (diff != 0) \
1008145073Skeramida		return (diff > 0 ? 1 : -1); \
1009145073Skeramida} while (0)
1010145073Skeramida
1011131626Sdes#define ORDERKEY_RSSIZE(a, b) do { \
1012131628Sdes	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1013131626Sdes	if (diff != 0) \
1014131626Sdes		return (diff > 0 ? 1 : -1); \
1015131626Sdes} while (0)
101638278Swosch
1017131626Sdes#define ORDERKEY_MEM(a, b) do { \
1018131628Sdes	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1019131626Sdes	if (diff != 0) \
1020131626Sdes		return (diff > 0 ? 1 : -1); \
1021131626Sdes} while (0)
102238278Swosch
1023168799Srafan#define ORDERKEY_JID(a, b) do { \
1024168799Srafan	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1025168799Srafan	if (diff != 0) \
1026168799Srafan		return (diff > 0 ? 1 : -1); \
1027168799Srafan} while (0)
1028168799Srafan
102938278Swosch/* compare_cpu - the comparison function for sorting by cpu percentage */
103038278Swosch
103124143Sjoergint
103238278Swosch#ifdef ORDER
1033131626Sdescompare_cpu(void *arg1, void *arg2)
103438278Swosch#else
1035131626Sdesproc_compare(void *arg1, void *arg2)
103638278Swosch#endif
103724143Sjoerg{
1038131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1039131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
104024143Sjoerg
1041131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1042131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1043131626Sdes	ORDERKEY_STATE(p1, p2);
1044131626Sdes	ORDERKEY_PRIO(p1, p2);
1045131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1046131626Sdes	ORDERKEY_MEM(p1, p2);
104724143Sjoerg
1048131626Sdes	return (0);
104924143Sjoerg}
105024143Sjoerg
105138278Swosch#ifdef ORDER
1052158280Sbde/* "cpu" compare routines */
1053158280Sbdeint compare_size(), compare_res(), compare_time(), compare_prio(),
1054158280Sbde    compare_threads();
105524143Sjoerg
1056158280Sbde/*
1057158280Sbde * "io" compare routines.  Context switches aren't i/o, but are displayed
1058158280Sbde * on the "io" display.
1059158280Sbde */
1060158280Sbdeint compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1061158280Sbde    compare_vcsw(), compare_ivcsw();
1062158280Sbde
1063133817Salfredint (*compares[])() = {
1064131623Sdes	compare_cpu,
1065131623Sdes	compare_size,
1066131623Sdes	compare_res,
1067131623Sdes	compare_time,
1068131623Sdes	compare_prio,
1069145073Skeramida	compare_threads,
1070133817Salfred	compare_iototal,
1071133817Salfred	compare_ioread,
1072133817Salfred	compare_iowrite,
1073133817Salfred	compare_iofault,
1074133817Salfred	compare_vcsw,
1075133817Salfred	compare_ivcsw,
1076168799Srafan	compare_jid,
1077131623Sdes	NULL
107838278Swosch};
107938278Swosch
108038278Swosch/* compare_size - the comparison function for sorting by total memory usage */
108138278Swosch
108238278Swoschint
1083131626Sdescompare_size(void *arg1, void *arg2)
108438278Swosch{
1085131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1086131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
108738278Swosch
1088131626Sdes	ORDERKEY_MEM(p1, p2);
1089131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1090131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1091131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1092131626Sdes	ORDERKEY_STATE(p1, p2);
1093131626Sdes	ORDERKEY_PRIO(p1, p2);
109438278Swosch
1095131626Sdes	return (0);
109638278Swosch}
109738278Swosch
109838278Swosch/* compare_res - the comparison function for sorting by resident set size */
109938278Swosch
110038278Swoschint
1101131626Sdescompare_res(void *arg1, void *arg2)
110238278Swosch{
1103131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1104131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
110538278Swosch
1106131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1107131626Sdes	ORDERKEY_MEM(p1, p2);
1108131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1109131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1110131626Sdes	ORDERKEY_STATE(p1, p2);
1111131626Sdes	ORDERKEY_PRIO(p1, p2);
111238278Swosch
1113131626Sdes	return (0);
111438278Swosch}
111538278Swosch
111638278Swosch/* compare_time - the comparison function for sorting by total cpu time */
111738278Swosch
111838278Swoschint
1119131626Sdescompare_time(void *arg1, void *arg2)
1120131310Salfred{
1121131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1122131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
112338278Swosch
1124131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1125131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1126131626Sdes	ORDERKEY_STATE(p1, p2);
1127131626Sdes	ORDERKEY_PRIO(p1, p2);
1128131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1129131626Sdes	ORDERKEY_MEM(p1, p2);
113038278Swosch
1131131626Sdes	return (0);
1132131623Sdes}
1133131310Salfred
1134131626Sdes/* compare_prio - the comparison function for sorting by priority */
113538278Swosch
113638278Swoschint
1137131626Sdescompare_prio(void *arg1, void *arg2)
113838278Swosch{
1139131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1140131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
114138278Swosch
1142131626Sdes	ORDERKEY_PRIO(p1, p2);
1143131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1144131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1145131626Sdes	ORDERKEY_STATE(p1, p2);
1146131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1147131626Sdes	ORDERKEY_MEM(p1, p2);
114838278Swosch
1149131626Sdes	return (0);
115038278Swosch}
1151145073Skeramida
1152145073Skeramida/* compare_threads - the comparison function for sorting by threads */
1153145073Skeramidaint
1154145073Skeramidacompare_threads(void *arg1, void *arg2)
1155145073Skeramida{
1156145073Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1157145073Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1158145073Skeramida
1159145073Skeramida	ORDERKEY_THREADS(p1, p2);
1160145073Skeramida	ORDERKEY_PCTCPU(p1, p2);
1161145073Skeramida	ORDERKEY_CPTICKS(p1, p2);
1162145073Skeramida	ORDERKEY_STATE(p1, p2);
1163145073Skeramida	ORDERKEY_PRIO(p1, p2);
1164145073Skeramida	ORDERKEY_RSSIZE(p1, p2);
1165145073Skeramida	ORDERKEY_MEM(p1, p2);
1166145073Skeramida
1167145073Skeramida	return (0);
1168145073Skeramida}
1169168799Srafan
1170168799Srafan/* compare_jid - the comparison function for sorting by jid */
1171168799Srafanstatic int
1172168799Srafancompare_jid(const void *arg1, const void *arg2)
1173168799Srafan{
1174168799Srafan	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1175168799Srafan	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1176168799Srafan
1177168799Srafan	ORDERKEY_JID(p1, p2);
1178168799Srafan	ORDERKEY_PCTCPU(p1, p2);
1179168799Srafan	ORDERKEY_CPTICKS(p1, p2);
1180168799Srafan	ORDERKEY_STATE(p1, p2);
1181168799Srafan	ORDERKEY_PRIO(p1, p2);
1182168799Srafan	ORDERKEY_RSSIZE(p1, p2);
1183168799Srafan	ORDERKEY_MEM(p1, p2);
1184168799Srafan
1185168799Srafan	return (0);
1186168799Srafan}
1187158280Sbde#endif /* ORDER */
118838278Swosch
1189158280Sbde/* assorted comparison functions for sorting by i/o */
1190131829Skeramida
1191131402Salfredint
1192131829Skeramida#ifdef ORDER
1193131829Skeramidacompare_iototal(void *arg1, void *arg2)
1194131829Skeramida#else
1195131626Sdesio_compare(void *arg1, void *arg2)
1196131829Skeramida#endif
1197131402Salfred{
1198131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1199131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1200131402Salfred
1201131626Sdes	return (get_io_total(p2) - get_io_total(p1));
1202131402Salfred}
1203131829Skeramida
1204131829Skeramida#ifdef ORDER
1205131829Skeramidaint
1206131829Skeramidacompare_ioread(void *arg1, void *arg2)
1207131829Skeramida{
1208131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1209131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1210131829Skeramida	long dummy, inp1, inp2;
1211131829Skeramida
1212133817Salfred	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1213133817Salfred	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1214131829Skeramida
1215131829Skeramida	return (inp2 - inp1);
1216131829Skeramida}
1217131829Skeramida
1218131829Skeramidaint
1219131829Skeramidacompare_iowrite(void *arg1, void *arg2)
1220131829Skeramida{
1221131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1222131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1223131829Skeramida	long dummy, oup1, oup2;
1224131829Skeramida
1225133817Salfred	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1226133817Salfred	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1227131829Skeramida
1228131829Skeramida	return (oup2 - oup1);
1229131829Skeramida}
1230131829Skeramida
1231131829Skeramidaint
1232131829Skeramidacompare_iofault(void *arg1, void *arg2)
1233131829Skeramida{
1234131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1235131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1236131829Skeramida	long dummy, flp1, flp2;
1237131829Skeramida
1238133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1239133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1240131829Skeramida
1241131829Skeramida	return (flp2 - flp1);
1242131829Skeramida}
1243131829Skeramida
1244133817Salfredint
1245133817Salfredcompare_vcsw(void *arg1, void *arg2)
1246133817Salfred{
1247133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1248133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1249133817Salfred	long dummy, flp1, flp2;
1250133817Salfred
1251133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1252133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1253133817Salfred
1254133817Salfred	return (flp2 - flp1);
1255133817Salfred}
1256133817Salfred
1257133817Salfredint
1258133817Salfredcompare_ivcsw(void *arg1, void *arg2)
1259133817Salfred{
1260133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1261133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1262133817Salfred	long dummy, flp1, flp2;
1263133817Salfred
1264133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1265133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1266133817Salfred
1267133817Salfred	return (flp2 - flp1);
1268133817Salfred}
1269131829Skeramida#endif /* ORDER */
1270131829Skeramida
127124143Sjoerg/*
127224143Sjoerg * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
127324143Sjoerg *		the process does not exist.
127424143Sjoerg *		It is EXTREMLY IMPORTANT that this function work correctly.
127524143Sjoerg *		If top runs setuid root (as in SVR4), then this function
127624143Sjoerg *		is the only thing that stands in the way of a serious
127724143Sjoerg *		security problem.  It validates requests for the "kill"
127824143Sjoerg *		and "renice" commands.
127924143Sjoerg */
128024143Sjoerg
1281131310Salfredint
1282131622Sdesproc_owner(int pid)
128324143Sjoerg{
1284131623Sdes	int cnt;
1285131623Sdes	struct kinfo_proc **prefp;
1286131623Sdes	struct kinfo_proc *pp;
128724143Sjoerg
1288131623Sdes	prefp = pref;
1289131623Sdes	cnt = pref_len;
1290131626Sdes	while (--cnt >= 0) {
1291131623Sdes		pp = *prefp++;
1292131623Sdes		if (pp->ki_pid == (pid_t)pid)
1293131623Sdes			return ((int)pp->ki_ruid);
129424143Sjoerg	}
1295131623Sdes	return (-1);
129624143Sjoerg}
129724143Sjoerg
1298158282Sbdestatic int
1299131622Sdesswapmode(int *retavail, int *retfree)
130024143Sjoerg{
130143053Sdillon	int n;
130243053Sdillon	int pagesize = getpagesize();
130343053Sdillon	struct kvm_swap swapary[1];
130424143Sjoerg
130543053Sdillon	*retavail = 0;
130643053Sdillon	*retfree = 0;
130724143Sjoerg
130843053Sdillon#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
130924143Sjoerg
131043053Sdillon	n = kvm_getswapinfo(kd, swapary, 1, 0);
131143697Sdillon	if (n < 0 || swapary[0].ksw_total == 0)
1312131623Sdes		return (0);
131324143Sjoerg
131443053Sdillon	*retavail = CONVERT(swapary[0].ksw_total);
131543053Sdillon	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
131624143Sjoerg
1317131626Sdes	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1318131623Sdes	return (n);
131943053Sdillon}
1320