machine.c revision 234416
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 234416 2012-04-18 10:23:42Z kib $
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
38222136Spluknet#include <err.h>
39131621Sdes#include <kvm.h>
40131621Sdes#include <math.h>
41131621Sdes#include <nlist.h>
42131626Sdes#include <paths.h>
43131621Sdes#include <pwd.h>
44131621Sdes#include <stdio.h>
4524143Sjoerg#include <stdlib.h>
46144636Sstefanf#include <string.h>
47144636Sstefanf#include <strings.h>
4872951Srwatson#include <unistd.h>
49168710Sstas#include <vis.h>
5024143Sjoerg
5124143Sjoerg#include "top.h"
5224143Sjoerg#include "machine.h"
5369375Sjhb#include "screen.h"
5472951Srwatson#include "utils.h"
55175420Speter#include "layout.h"
5624143Sjoerg
5772951Srwatson#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
58146291Sobrien#define	SMPUNAMELEN	13
59146291Sobrien#define	UPUNAMELEN	15
6072951Srwatson
61145073Skeramidaextern struct process_select ps;
6292922Simpextern char* printable(char *);
6327340Speterstatic int smpmode;
64131402Salfredenum displaymodes displaymode;
65175195Sobrien#ifdef TOP_USERNAME_LEN
66175195Sobrienstatic int namelength = TOP_USERNAME_LEN;
67175195Sobrien#else
68146291Sobrienstatic int namelength = 8;
69175195Sobrien#endif
7069375Sjhbstatic int cmdlengthdelta;
7124143Sjoerg
7272951Srwatson/* Prototypes for top internals */
7392922Simpvoid quit(int);
7424143Sjoerg
7524143Sjoerg/* get_process_info passes back a handle.  This is what it looks like: */
7624143Sjoerg
77158280Sbdestruct handle {
78131623Sdes	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
79131623Sdes	int remaining;			/* number of pointers remaining */
8024143Sjoerg};
8124143Sjoerg
8224143Sjoerg/* declarations for load_avg */
8324143Sjoerg#include "loadavg.h"
8424143Sjoerg
8524143Sjoerg/* define what weighted cpu is.  */
8669896Smckusick#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
8769896Smckusick			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
8824143Sjoerg
8924143Sjoerg/* what we consider to be process size: */
9069896Smckusick#define PROCSIZE(pp) ((pp)->ki_size / 1024)
9124143Sjoerg
92131402Salfred#define RU(pp)	(&(pp)->ki_rusage)
93131402Salfred#define RUTOT(pp) \
94131402Salfred	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
95131402Salfred
96131402Salfred
9724143Sjoerg/* definitions for indices in the nlist array */
9824143Sjoerg
9924143Sjoerg/*
10024143Sjoerg *  These definitions control the format of the per-process area
10124143Sjoerg */
10224143Sjoerg
103131402Salfredstatic char io_header[] =
104168799Srafan    "  PID%s %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
105131402Salfred
106131402Salfred#define io_Proc_format \
107168799Srafan    "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
108131402Salfred
109145073Skeramidastatic char smp_header_thr[] =
110186499Srpaulo    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE   C   TIME %6s COMMAND";
11127340Speterstatic char smp_header[] =
112186499Srpaulo    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE   C   TIME %6s COMMAND";
11324143Sjoerg
11427340Speter#define smp_Proc_format \
115183526Sjhb    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %2d%7s %5.2f%% %.*s"
11624143Sjoerg
117145073Skeramidastatic char up_header_thr[] =
118168799Srafan    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
11927340Speterstatic char up_header[] =
120168799Srafan    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
12124143Sjoerg
12227340Speter#define up_Proc_format \
123168799Srafan    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
12424143Sjoerg
12524143Sjoerg
12624143Sjoerg/* process state names for the "STATE" column of the display */
12724143Sjoerg/* the extra nulls in the string "run" are for adding a slash and
12824143Sjoerg   the processor number when needed */
12924143Sjoerg
130158280Sbdechar *state_abbrev[] = {
131131623Sdes	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
13224143Sjoerg};
13324143Sjoerg
13424143Sjoerg
13524143Sjoergstatic kvm_t *kd;
13624143Sjoerg
13724143Sjoerg/* values that we stash away in _init and use in later routines */
13824143Sjoerg
13924143Sjoergstatic double logcpu;
14024143Sjoerg
14124143Sjoerg/* these are retrieved from the kernel in _init */
14224143Sjoerg
14324143Sjoergstatic load_avg  ccpu;
14424143Sjoerg
14572951Srwatson/* these are used in the get_ functions */
14624143Sjoerg
14772951Srwatsonstatic int lastpid;
14824143Sjoerg
14924143Sjoerg/* these are for calculating cpu state percentages */
15024143Sjoerg
15124143Sjoergstatic long cp_time[CPUSTATES];
15224143Sjoergstatic long cp_old[CPUSTATES];
15324143Sjoergstatic long cp_diff[CPUSTATES];
15424143Sjoerg
15524143Sjoerg/* these are for detailing the process states */
15624143Sjoerg
15765557Sjasoneint process_states[8];
15824143Sjoergchar *procstatenames[] = {
159131623Sdes	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
160131623Sdes	" zombie, ", " waiting, ", " lock, ",
161131623Sdes	NULL
16224143Sjoerg};
16324143Sjoerg
16424143Sjoerg/* these are for detailing the cpu states */
16524143Sjoerg
16624143Sjoergint cpu_states[CPUSTATES];
16724143Sjoergchar *cpustatenames[] = {
168131623Sdes	"user", "nice", "system", "interrupt", "idle", NULL
16924143Sjoerg};
17024143Sjoerg
17124143Sjoerg/* these are for detailing the memory statistics */
17224143Sjoerg
17324143Sjoergint memory_stats[7];
17424143Sjoergchar *memorynames[] = {
175158280Sbde	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
176158280Sbde	"K Free", NULL
17724143Sjoerg};
17824143Sjoerg
17924143Sjoergint swap_stats[7];
18024143Sjoergchar *swapnames[] = {
181131623Sdes	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
182131623Sdes	NULL
18324143Sjoerg};
18424143Sjoerg
18524143Sjoerg
18624143Sjoerg/* these are for keeping track of the proc array */
18724143Sjoerg
18824143Sjoergstatic int nproc;
18924143Sjoergstatic int onproc = -1;
19024143Sjoergstatic int pref_len;
19124143Sjoergstatic struct kinfo_proc *pbase;
19224143Sjoergstatic struct kinfo_proc **pref;
193131402Salfredstatic struct kinfo_proc *previous_procs;
194131402Salfredstatic struct kinfo_proc **previous_pref;
195131402Salfredstatic int previous_proc_count = 0;
196131402Salfredstatic int previous_proc_count_max = 0;
19724143Sjoerg
198131412Salfred/* total number of io operations */
199131412Salfredstatic long total_inblock;
200131412Salfredstatic long total_oublock;
201131412Salfredstatic long total_majflt;
202131412Salfred
20324143Sjoerg/* these are for getting the memory statistics */
20424143Sjoerg
20524143Sjoergstatic int pageshift;		/* log base 2 of the pagesize */
20624143Sjoerg
20724143Sjoerg/* define pagetok in terms of pageshift */
20824143Sjoerg
20924143Sjoerg#define pagetok(size) ((size) << pageshift)
21024143Sjoerg
21124143Sjoerg/* useful externals */
21224143Sjoerglong percentages();
21324143Sjoerg
21438278Swosch#ifdef ORDER
215131829Skeramida/*
216145073Skeramida * Sorting orders.  The first element is the default.
217131829Skeramida */
218133817Salfredchar *ordernames[] = {
219145073Skeramida	"cpu", "size", "res", "time", "pri", "threads",
220168799Srafan	"total", "read", "write", "fault", "vcsw", "ivcsw",
221168799Srafan	"jid", NULL
22238278Swosch};
22338278Swosch#endif
22438278Swosch
225175420Speter/* Per-cpu time states */
226175420Speterstatic int maxcpu;
227175420Speterstatic int maxid;
228175420Speterstatic int ncpus;
229175420Speterstatic u_long cpumask;
230175420Speterstatic long *times;
231175420Speterstatic long *pcpu_cp_time;
232175420Speterstatic long *pcpu_cp_old;
233175420Speterstatic long *pcpu_cp_diff;
234175420Speterstatic int *pcpu_cpu_states;
235175420Speter
236168799Srafanstatic int compare_jid(const void *a, const void *b);
237158282Sbdestatic int compare_pid(const void *a, const void *b);
238224188Sjhbstatic int compare_tid(const void *a, const void *b);
239158282Sbdestatic const char *format_nice(const struct kinfo_proc *pp);
240158282Sbdestatic void getsysctl(const char *name, void *ptr, size_t len);
241158282Sbdestatic int swapmode(int *retavail, int *retfree);
242158282Sbde
243223936Sjhbvoid
244224205Sjhbtoggle_pcpustats(void)
245223936Sjhb{
246223936Sjhb
247223936Sjhb	if (ncpus == 1)
248223936Sjhb		return;
249223936Sjhb
250223936Sjhb	/* Adjust display based on ncpus */
251223936Sjhb	if (pcpu_stats) {
252223936Sjhb		y_mem += ncpus - 1;	/* 3 */
253223936Sjhb		y_swap += ncpus - 1;	/* 4 */
254223936Sjhb		y_idlecursor += ncpus - 1; /* 5 */
255223936Sjhb		y_message += ncpus - 1;	/* 5 */
256223936Sjhb		y_header += ncpus - 1;	/* 6 */
257223936Sjhb		y_procs += ncpus - 1;	/* 7 */
258223936Sjhb		Header_lines += ncpus - 1; /* 7 */
259223936Sjhb	} else {
260223936Sjhb		y_mem = 3;
261223936Sjhb		y_swap = 4;
262223936Sjhb		y_idlecursor = 5;
263223936Sjhb		y_message = 5;
264223936Sjhb		y_header = 6;
265223936Sjhb		y_procs = 7;
266223936Sjhb		Header_lines = 7;
267223936Sjhb	}
268223936Sjhb}
269223936Sjhb
27024143Sjoergint
271175195Sobrienmachine_init(struct statics *statics, char do_unames)
27224143Sjoerg{
273223936Sjhb	int i, j, empty, pagesize;
274223936Sjhb	size_t size;
275131623Sdes	struct passwd *pw;
27624143Sjoerg
277223936Sjhb	size = sizeof(smpmode);
278223936Sjhb	if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
279158280Sbde	    NULL, 0) != 0 &&
280223936Sjhb	    sysctlbyname("kern.smp.active", &smpmode, &size,
281158280Sbde	    NULL, 0) != 0) ||
282223936Sjhb	    size != sizeof(smpmode))
283131623Sdes		smpmode = 0;
28427340Speter
285175195Sobrien	if (do_unames) {
286175195Sobrien	    while ((pw = getpwent()) != NULL) {
287131623Sdes		if (strlen(pw->pw_name) > namelength)
288131623Sdes			namelength = strlen(pw->pw_name);
289175195Sobrien	    }
290131623Sdes	}
291146291Sobrien	if (smpmode && namelength > SMPUNAMELEN)
292146291Sobrien		namelength = SMPUNAMELEN;
293146291Sobrien	else if (namelength > UPUNAMELEN)
294146291Sobrien		namelength = UPUNAMELEN;
29527390Speter
296131626Sdes	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
297131626Sdes	if (kd == NULL)
298131626Sdes		return (-1);
29924143Sjoerg
300131623Sdes	GETSYSCTL("kern.ccpu", ccpu);
30124143Sjoerg
302131623Sdes	/* this is used in calculating WCPU -- calculate it ahead of time */
303131623Sdes	logcpu = log(loaddouble(ccpu));
30424143Sjoerg
305131623Sdes	pbase = NULL;
306131623Sdes	pref = NULL;
307131623Sdes	nproc = 0;
308131623Sdes	onproc = -1;
309158280Sbde
310158280Sbde	/* get the page size and calculate pageshift from it */
311131623Sdes	pagesize = getpagesize();
312131623Sdes	pageshift = 0;
313131626Sdes	while (pagesize > 1) {
314131623Sdes		pageshift++;
315131623Sdes		pagesize >>= 1;
316131623Sdes	}
31724143Sjoerg
318131623Sdes	/* we only need the amount of log(2)1024 for our conversion */
319131623Sdes	pageshift -= LOG1024;
32024143Sjoerg
321131623Sdes	/* fill in the statics information */
322131623Sdes	statics->procstate_names = procstatenames;
323131623Sdes	statics->cpustate_names = cpustatenames;
324131623Sdes	statics->memory_names = memorynames;
325131623Sdes	statics->swap_names = swapnames;
32638278Swosch#ifdef ORDER
327133817Salfred	statics->order_names = ordernames;
32838278Swosch#endif
32924143Sjoerg
330223936Sjhb	/* Allocate state for per-CPU stats. */
331223936Sjhb	cpumask = 0;
332223936Sjhb	ncpus = 0;
333223936Sjhb	GETSYSCTL("kern.smp.maxcpus", maxcpu);
334223936Sjhb	size = sizeof(long) * maxcpu * CPUSTATES;
335223936Sjhb	times = malloc(size);
336223936Sjhb	if (times == NULL)
337223936Sjhb		err(1, "malloc %zd bytes", size);
338223936Sjhb	if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
339223936Sjhb		err(1, "sysctlbyname kern.cp_times");
340223936Sjhb	pcpu_cp_time = calloc(1, size);
341223936Sjhb	maxid = (size / CPUSTATES / sizeof(long)) - 1;
342223936Sjhb	for (i = 0; i <= maxid; i++) {
343223936Sjhb		empty = 1;
344223936Sjhb		for (j = 0; empty && j < CPUSTATES; j++) {
345223936Sjhb			if (times[i * CPUSTATES + j] != 0)
346223936Sjhb				empty = 0;
347175420Speter		}
348223936Sjhb		if (!empty) {
349223936Sjhb			cpumask |= (1ul << i);
350223936Sjhb			ncpus++;
351175420Speter		}
352175420Speter	}
353223936Sjhb	size = sizeof(long) * ncpus * CPUSTATES;
354223936Sjhb	pcpu_cp_old = calloc(1, size);
355223936Sjhb	pcpu_cp_diff = calloc(1, size);
356223936Sjhb	pcpu_cpu_states = calloc(1, size);
357224205Sjhb	statics->ncpus = ncpus;
358175420Speter
359223936Sjhb	if (pcpu_stats)
360224205Sjhb		toggle_pcpustats();
361223936Sjhb
362131623Sdes	/* all done! */
363131623Sdes	return (0);
36424143Sjoerg}
36524143Sjoerg
366131310Salfredchar *
367131622Sdesformat_header(char *uname_field)
36824143Sjoerg{
369131623Sdes	static char Header[128];
370131623Sdes	const char *prehead;
37124143Sjoerg
372131623Sdes	switch (displaymode) {
373131623Sdes	case DISP_CPU:
374145073Skeramida		/*
375145073Skeramida		 * The logic of picking the right header format seems reverse
376145073Skeramida		 * here because we only want to display a THR column when
377145073Skeramida		 * "thread mode" is off (and threads are not listed as
378145073Skeramida		 * separate lines).
379145073Skeramida		 */
380145073Skeramida		prehead = smpmode ?
381145073Skeramida		    (ps.thread ? smp_header : smp_header_thr) :
382145073Skeramida		    (ps.thread ? up_header : up_header_thr);
383146342Skeramida		snprintf(Header, sizeof(Header), prehead,
384168799Srafan		    ps.jail ? " JID" : "",
385146342Skeramida		    namelength, namelength, uname_field,
386146342Skeramida		    ps.wcpu ? "WCPU" : "CPU");
387131623Sdes		break;
388131623Sdes	case DISP_IO:
389131623Sdes		prehead = io_header;
390146342Skeramida		snprintf(Header, sizeof(Header), prehead,
391168799Srafan		    ps.jail ? " JID" : "",
392146342Skeramida		    namelength, namelength, uname_field);
393131623Sdes		break;
394131623Sdes	}
395131623Sdes	cmdlengthdelta = strlen(Header) - 7;
396131623Sdes	return (Header);
39724143Sjoerg}
39824143Sjoerg
39924143Sjoergstatic int swappgsin = -1;
40024143Sjoergstatic int swappgsout = -1;
40124143Sjoergextern struct timeval timeout;
40224143Sjoerg
403175420Speter
40424143Sjoergvoid
405131622Sdesget_system_info(struct system_info *si)
40624143Sjoerg{
407131623Sdes	long total;
408131623Sdes	struct loadavg sysload;
409131623Sdes	int mib[2];
410131623Sdes	struct timeval boottime;
411131623Sdes	size_t bt_size;
412175420Speter	int i, j;
413175420Speter	size_t size;
41424143Sjoerg
415223936Sjhb	/* get the CPU stats */
416223936Sjhb	size = (maxid + 1) * CPUSTATES * sizeof(long);
417223936Sjhb	if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
418223936Sjhb		err(1, "sysctlbyname kern.cp_times");
419223936Sjhb	GETSYSCTL("kern.cp_time", cp_time);
420131623Sdes	GETSYSCTL("vm.loadavg", sysload);
421131623Sdes	GETSYSCTL("kern.lastpid", lastpid);
42224143Sjoerg
423131623Sdes	/* convert load averages to doubles */
424131626Sdes	for (i = 0; i < 3; i++)
425131626Sdes		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
42624143Sjoerg
427223936Sjhb	/* convert cp_time counts to percentages */
428223936Sjhb	for (i = j = 0; i <= maxid; i++) {
429223936Sjhb		if ((cpumask & (1ul << i)) == 0)
430223936Sjhb			continue;
431223936Sjhb		percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
432223936Sjhb		    &pcpu_cp_time[j * CPUSTATES],
433223936Sjhb		    &pcpu_cp_old[j * CPUSTATES],
434223936Sjhb		    &pcpu_cp_diff[j * CPUSTATES]);
435223936Sjhb		j++;
436175420Speter	}
437223936Sjhb	percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
43824143Sjoerg
439131623Sdes	/* sum memory & swap statistics */
440131623Sdes	{
441131623Sdes		static unsigned int swap_delay = 0;
442131623Sdes		static int swapavail = 0;
443131623Sdes		static int swapfree = 0;
444189626Sjhb		static long bufspace = 0;
445131623Sdes		static int nspgsin, nspgsout;
44624143Sjoerg
447131623Sdes		GETSYSCTL("vfs.bufspace", bufspace);
448131623Sdes		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
449131623Sdes		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
450131623Sdes		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
451131623Sdes		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
452131623Sdes		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
453131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
454131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
455131623Sdes		/* convert memory stats to Kbytes */
456131623Sdes		memory_stats[0] = pagetok(memory_stats[0]);
457131623Sdes		memory_stats[1] = pagetok(memory_stats[1]);
458131623Sdes		memory_stats[2] = pagetok(memory_stats[2]);
459131623Sdes		memory_stats[3] = pagetok(memory_stats[3]);
460131623Sdes		memory_stats[4] = bufspace / 1024;
461131623Sdes		memory_stats[5] = pagetok(memory_stats[5]);
462131623Sdes		memory_stats[6] = -1;
46324143Sjoerg
464131623Sdes		/* first interval */
465131623Sdes		if (swappgsin < 0) {
466131623Sdes			swap_stats[4] = 0;
467131623Sdes			swap_stats[5] = 0;
468131623Sdes		}
46924143Sjoerg
470131623Sdes		/* compute differences between old and new swap statistic */
471131623Sdes		else {
472131623Sdes			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
473131623Sdes			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
474131623Sdes		}
47524143Sjoerg
476131623Sdes		swappgsin = nspgsin;
477131623Sdes		swappgsout = nspgsout;
47824143Sjoerg
479131623Sdes		/* call CPU heavy swapmode() only for changes */
480131623Sdes		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
481131623Sdes			swap_stats[3] = swapmode(&swapavail, &swapfree);
482131623Sdes			swap_stats[0] = swapavail;
483131623Sdes			swap_stats[1] = swapavail - swapfree;
484131623Sdes			swap_stats[2] = swapfree;
485131623Sdes		}
486131623Sdes		swap_delay = 1;
487131623Sdes		swap_stats[6] = -1;
48824143Sjoerg	}
48924143Sjoerg
490131623Sdes	/* set arrays and strings */
491175420Speter	if (pcpu_stats) {
492175420Speter		si->cpustates = pcpu_cpu_states;
493175420Speter		si->ncpus = ncpus;
494175420Speter	} else {
495175420Speter		si->cpustates = cpu_states;
496175420Speter		si->ncpus = 1;
497175420Speter	}
498131623Sdes	si->memory = memory_stats;
499131623Sdes	si->swap = swap_stats;
50024143Sjoerg
50124143Sjoerg
502131623Sdes	if (lastpid > 0) {
503131623Sdes		si->last_pid = lastpid;
504131623Sdes	} else {
505131623Sdes		si->last_pid = -1;
506131623Sdes	}
50742447Sobrien
508131623Sdes	/*
509131623Sdes	 * Print how long system has been up.
510131623Sdes	 * (Found by looking getting "boottime" from the kernel)
511131623Sdes	 */
512131623Sdes	mib[0] = CTL_KERN;
513131623Sdes	mib[1] = KERN_BOOTTIME;
514131623Sdes	bt_size = sizeof(boottime);
515131623Sdes	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
516131623Sdes	    boottime.tv_sec != 0) {
517131623Sdes		si->boottime = boottime;
518131623Sdes	} else {
519131623Sdes		si->boottime.tv_sec = -1;
520131623Sdes	}
52124143Sjoerg}
52224143Sjoerg
523132015Salfred#define NOPROC	((void *)-1)
524132015Salfred
525132955Salfred/*
526132955Salfred * We need to compare data from the old process entry with the new
527132955Salfred * process entry.
528132955Salfred * To facilitate doing this quickly we stash a pointer in the kinfo_proc
529132955Salfred * structure to cache the mapping.  We also use a negative cache pointer
530132955Salfred * of NOPROC to avoid duplicate lookups.
531132955Salfred * XXX: this could be done when the actual processes are fetched, we do
532132955Salfred * it here out of laziness.
533132955Salfred */
534131402Salfredconst struct kinfo_proc *
535131402Salfredget_old_proc(struct kinfo_proc *pp)
536131402Salfred{
537131402Salfred	struct kinfo_proc **oldpp, *oldp;
538131402Salfred
539132955Salfred	/*
540132955Salfred	 * If this is the first fetch of the kinfo_procs then we don't have
541132955Salfred	 * any previous entries.
542132955Salfred	 */
543131402Salfred	if (previous_proc_count == 0)
544131402Salfred		return (NULL);
545132955Salfred	/* negative cache? */
546132015Salfred	if (pp->ki_udata == NOPROC)
547132015Salfred		return (NULL);
548132955Salfred	/* cached? */
549132015Salfred	if (pp->ki_udata != NULL)
550132015Salfred		return (pp->ki_udata);
551132955Salfred	/*
552132955Salfred	 * Not cached,
553132955Salfred	 * 1) look up based on pid.
554132955Salfred	 * 2) compare process start.
555132955Salfred	 * If we fail here, then setup a negative cache entry, otherwise
556132955Salfred	 * cache it.
557132955Salfred	 */
558131402Salfred	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
559224188Sjhb	    sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
560132015Salfred	if (oldpp == NULL) {
561132015Salfred		pp->ki_udata = NOPROC;
562131402Salfred		return (NULL);
563132015Salfred	}
564131402Salfred	oldp = *oldpp;
565132015Salfred	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
566132015Salfred		pp->ki_udata = NOPROC;
567131402Salfred		return (NULL);
568132015Salfred	}
569132015Salfred	pp->ki_udata = oldp;
570131402Salfred	return (oldp);
571131402Salfred}
572131402Salfred
573132955Salfred/*
574132955Salfred * Return the total amount of IO done in blocks in/out and faults.
575132955Salfred * store the values individually in the pointers passed in.
576132955Salfred */
577131402Salfredlong
578158280Sbdeget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
579158280Sbde    long *vcsw, long *ivcsw)
580131402Salfred{
581131402Salfred	const struct kinfo_proc *oldp;
582131402Salfred	static struct kinfo_proc dummy;
583131402Salfred	long ret;
584131402Salfred
585131402Salfred	oldp = get_old_proc(pp);
586131402Salfred	if (oldp == NULL) {
587131402Salfred		bzero(&dummy, sizeof(dummy));
588131402Salfred		oldp = &dummy;
589131402Salfred	}
590131412Salfred	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
591131412Salfred	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
592131412Salfred	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
593133817Salfred	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
594133817Salfred	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
595131402Salfred	ret =
596131402Salfred	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
597131402Salfred	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
598131402Salfred	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
599131402Salfred	return (ret);
600131402Salfred}
601131402Salfred
602132955Salfred/*
603132955Salfred * Return the total number of block in/out and faults by a process.
604132955Salfred */
605131412Salfredlong
606131412Salfredget_io_total(struct kinfo_proc *pp)
607131412Salfred{
608131412Salfred	long dummy;
609131412Salfred
610133817Salfred	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
611131412Salfred}
612131412Salfred
61324143Sjoergstatic struct handle handle;
61424143Sjoerg
615131310Salfredcaddr_t
616131622Sdesget_process_info(struct system_info *si, struct process_select *sel,
617131626Sdes    int (*compare)(const void *, const void *))
61824143Sjoerg{
619131623Sdes	int i;
620131623Sdes	int total_procs;
621131623Sdes	long p_io;
622133817Salfred	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
623131623Sdes	int active_procs;
624131623Sdes	struct kinfo_proc **prefp;
625131623Sdes	struct kinfo_proc *pp;
62624143Sjoerg
627131623Sdes	/* these are copied out of sel for speed */
628131623Sdes	int show_idle;
629131623Sdes	int show_self;
630131623Sdes	int show_system;
631131623Sdes	int show_uid;
632131623Sdes	int show_command;
633222530Sjhb	int show_kidle;
63424143Sjoerg
635131623Sdes	/*
636131623Sdes	 * Save the previous process info.
637131623Sdes	 */
638131623Sdes	if (previous_proc_count_max < nproc) {
639131623Sdes		free(previous_procs);
640131626Sdes		previous_procs = malloc(nproc * sizeof(*previous_procs));
641131623Sdes		free(previous_pref);
642131626Sdes		previous_pref = malloc(nproc * sizeof(*previous_pref));
643131623Sdes		if (previous_procs == NULL || previous_pref == NULL) {
644131623Sdes			(void) fprintf(stderr, "top: Out of memory.\n");
645131623Sdes			quit(23);
646131623Sdes		}
647131623Sdes		previous_proc_count_max = nproc;
648131623Sdes	}
649131623Sdes	if (nproc) {
650131623Sdes		for (i = 0; i < nproc; i++)
651131623Sdes			previous_pref[i] = &previous_procs[i];
652131626Sdes		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
653158280Sbde		qsort(previous_pref, nproc, sizeof(*previous_pref),
654224188Sjhb		    ps.thread ? compare_tid : compare_pid);
655131623Sdes	}
656131623Sdes	previous_proc_count = nproc;
657131402Salfred
658224062Sjhb	pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
659224062Sjhb	    0, &nproc);
660131623Sdes	if (nproc > onproc)
661131626Sdes		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
662131623Sdes	if (pref == NULL || pbase == NULL) {
663131623Sdes		(void) fprintf(stderr, "top: Out of memory.\n");
664131623Sdes		quit(23);
665131623Sdes	}
666131623Sdes	/* get a pointer to the states summary array */
667131623Sdes	si->procstates = process_states;
66824143Sjoerg
669131623Sdes	/* set up flags which define what we are going to select */
670131623Sdes	show_idle = sel->idle;
671132024Sdes	show_self = sel->self == -1;
672131623Sdes	show_system = sel->system;
673131623Sdes	show_uid = sel->uid != -1;
674131623Sdes	show_command = sel->command != NULL;
675222530Sjhb	show_kidle = sel->kidle;
67624143Sjoerg
677131623Sdes	/* count up process states and get pointers to interesting procs */
678131623Sdes	total_procs = 0;
679131623Sdes	active_procs = 0;
680131623Sdes	total_inblock = 0;
681131623Sdes	total_oublock = 0;
682131623Sdes	total_majflt = 0;
683131623Sdes	memset((char *)process_states, 0, sizeof(process_states));
684131623Sdes	prefp = pref;
685131626Sdes	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
686131619Sdes
687131623Sdes		if (pp->ki_stat == 0)
688132024Sdes			/* not in use */
689132024Sdes			continue;
690131619Sdes
691131623Sdes		if (!show_self && pp->ki_pid == sel->self)
692131623Sdes			/* skip self */
693131623Sdes			continue;
694131619Sdes
695131623Sdes		if (!show_system && (pp->ki_flag & P_SYSTEM))
696131623Sdes			/* skip system process */
697131623Sdes			continue;
698131619Sdes
699158280Sbde		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
700158280Sbde		    &p_vcsw, &p_ivcsw);
701131623Sdes		total_inblock += p_inblock;
702131623Sdes		total_oublock += p_oublock;
703131623Sdes		total_majflt += p_majflt;
704131623Sdes		total_procs++;
705131626Sdes		process_states[pp->ki_stat]++;
706131619Sdes
707131623Sdes		if (pp->ki_stat == SZOMB)
708131623Sdes			/* skip zombies */
709131623Sdes			continue;
710131619Sdes
711223841Sjhb		if (!show_kidle && pp->ki_tdflags & TDF_IDLETD)
712223841Sjhb			/* skip kernel idle process */
713223841Sjhb			continue;
714223841Sjhb
715131623Sdes		if (displaymode == DISP_CPU && !show_idle &&
716159520Sse		    (pp->ki_pctcpu == 0 ||
717159520Sse		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
718131623Sdes			/* skip idle or non-running processes */
719131623Sdes			continue;
720131619Sdes
721131623Sdes		if (displaymode == DISP_IO && !show_idle && p_io == 0)
722131623Sdes			/* skip processes that aren't doing I/O */
723131623Sdes			continue;
724131619Sdes
725131623Sdes		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
726158280Sbde			/* skip proc. that don't belong to the selected UID */
727131623Sdes			continue;
728131619Sdes
729224062Sjhb		*prefp++ = pp;
730224062Sjhb		active_procs++;
731131623Sdes	}
732131623Sdes
733131623Sdes	/* if requested, sort the "interesting" processes */
734131623Sdes	if (compare != NULL)
735131626Sdes		qsort(pref, active_procs, sizeof(*pref), compare);
73624143Sjoerg
737131623Sdes	/* remember active and total counts */
738131623Sdes	si->p_total = total_procs;
739131623Sdes	si->p_active = pref_len = active_procs;
74024143Sjoerg
741131623Sdes	/* pass back a handle */
742131623Sdes	handle.next_proc = pref;
743131623Sdes	handle.remaining = active_procs;
744131623Sdes	return ((caddr_t)&handle);
74524143Sjoerg}
74624143Sjoerg
747131626Sdesstatic char fmt[128];	/* static area where result is built */
74824143Sjoerg
749131310Salfredchar *
750168710Sstasformat_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
75124143Sjoerg{
752131623Sdes	struct kinfo_proc *pp;
753131623Sdes	const struct kinfo_proc *oldp;
754131623Sdes	long cputime;
755131623Sdes	double pct;
756131623Sdes	struct handle *hp;
757131623Sdes	char status[16];
758131623Sdes	int state;
759131623Sdes	struct rusage ru, *rup;
760131623Sdes	long p_tot, s_tot;
761168799Srafan	char *proc_fmt, thr_buf[6], jid_buf[6];
762168710Sstas	char *cmdbuf = NULL;
763168710Sstas	char **args;
76424143Sjoerg
765131623Sdes	/* find and remember the next proc structure */
766131623Sdes	hp = (struct handle *)handle;
767131623Sdes	pp = *(hp->next_proc++);
768131623Sdes	hp->remaining--;
769131620Sdes
770131623Sdes	/* get the process's command name */
771172207Sjeff	if ((pp->ki_flag & P_INMEM) == 0) {
772131623Sdes		/*
773131623Sdes		 * Print swapped processes as <pname>
774131623Sdes		 */
775158280Sbde		size_t len;
776158280Sbde
777158280Sbde		len = strlen(pp->ki_comm);
778131626Sdes		if (len > sizeof(pp->ki_comm) - 3)
779131626Sdes			len = sizeof(pp->ki_comm) - 3;
780131626Sdes		memmove(pp->ki_comm + 1, pp->ki_comm, len);
781131626Sdes		pp->ki_comm[0] = '<';
782131626Sdes		pp->ki_comm[len + 1] = '>';
783131626Sdes		pp->ki_comm[len + 2] = '\0';
784131623Sdes	}
785131623Sdes
78624143Sjoerg	/*
787131623Sdes	 * Convert the process's runtime from microseconds to seconds.  This
788131623Sdes	 * time includes the interrupt time although that is not wanted here.
789131623Sdes	 * ps(1) is similarly sloppy.
79024143Sjoerg	 */
791131623Sdes	cputime = (pp->ki_runtime + 500000) / 1000000;
79224143Sjoerg
793131623Sdes	/* calculate the base for cpu percentages */
794131623Sdes	pct = pctdouble(pp->ki_pctcpu);
79524143Sjoerg
796131623Sdes	/* generate "STATE" field */
797131623Sdes	switch (state = pp->ki_stat) {
79824143Sjoerg	case SRUN:
799131623Sdes		if (smpmode && pp->ki_oncpu != 0xff)
800131623Sdes			sprintf(status, "CPU%d", pp->ki_oncpu);
801131623Sdes		else
802131623Sdes			strcpy(status, "RUN");
803131623Sdes		break;
804104388Sjhb	case SLOCK:
805131623Sdes		if (pp->ki_kiflag & KI_LOCKBLOCK) {
806131623Sdes			sprintf(status, "*%.6s", pp->ki_lockname);
807131623Sdes			break;
808131623Sdes		}
809131623Sdes		/* fall through */
81024143Sjoerg	case SSLEEP:
811131623Sdes		if (pp->ki_wmesg != NULL) {
812131623Sdes			sprintf(status, "%.6s", pp->ki_wmesg);
813131623Sdes			break;
814131623Sdes		}
815131623Sdes		/* FALLTHROUGH */
81624143Sjoerg	default:
81743720Sfenner
818131623Sdes		if (state >= 0 &&
819131623Sdes		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
820131626Sdes			sprintf(status, "%.6s", state_abbrev[state]);
821131623Sdes		else
822131623Sdes			sprintf(status, "?%5d", state);
823131623Sdes		break;
824131623Sdes	}
82524143Sjoerg
826168710Sstas	cmdbuf = (char *)malloc(cmdlengthdelta + 1);
827168710Sstas	if (cmdbuf == NULL) {
828168710Sstas		warn("malloc(%d)", cmdlengthdelta + 1);
829168710Sstas		return NULL;
830168710Sstas	}
831168710Sstas
832168710Sstas	if (!(flags & FMT_SHOWARGS)) {
833173004Sjulian		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
834224199Sbz		    pp->ki_tdname[0]) {
835224202Sbz			snprintf(cmdbuf, cmdlengthdelta, "%s{%s}", pp->ki_comm,
836224202Sbz			    pp->ki_tdname);
837173004Sjulian		} else {
838173004Sjulian			snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
839168710Sstas		}
840173004Sjulian	} else {
841173004Sjulian		if (pp->ki_flag & P_SYSTEM ||
842173004Sjulian		    pp->ki_args == NULL ||
843173004Sjulian		    (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
844173004Sjulian		    !(*args)) {
845173004Sjulian			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
846224199Sbz		    	    pp->ki_tdname[0]) {
847173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
848224202Sbz				    "[%s{%s}]", pp->ki_comm, pp->ki_tdname);
849173004Sjulian			} else {
850173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
851173004Sjulian				    "[%s]", pp->ki_comm);
852173004Sjulian			}
853173004Sjulian		} else {
854173004Sjulian			char *src, *dst, *argbuf;
855173004Sjulian			char *cmd;
856173004Sjulian			size_t argbuflen;
857173004Sjulian			size_t len;
858168710Sstas
859173004Sjulian			argbuflen = cmdlengthdelta * 4;
860173004Sjulian			argbuf = (char *)malloc(argbuflen + 1);
861173004Sjulian			if (argbuf == NULL) {
862173004Sjulian				warn("malloc(%d)", argbuflen + 1);
863173004Sjulian				free(cmdbuf);
864173004Sjulian				return NULL;
865173004Sjulian			}
866168710Sstas
867173004Sjulian			dst = argbuf;
868168710Sstas
869173004Sjulian			/* Extract cmd name from argv */
870173004Sjulian			cmd = strrchr(*args, '/');
871173004Sjulian			if (cmd == NULL)
872173004Sjulian				cmd = *args;
873173004Sjulian			else
874173004Sjulian				cmd++;
875168710Sstas
876173004Sjulian			for (; (src = *args++) != NULL; ) {
877173004Sjulian				if (*src == '\0')
878173004Sjulian					continue;
879173004Sjulian				len = (argbuflen - (dst - argbuf) - 1) / 4;
880173004Sjulian				strvisx(dst, src,
881173004Sjulian				    strlen(src) < len ? strlen(src) : len,
882173004Sjulian				    VIS_NL | VIS_CSTYLE);
883173004Sjulian				while (*dst != '\0')
884173004Sjulian					dst++;
885173004Sjulian				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
886173004Sjulian					*dst++ = ' '; /* add delimiting space */
887173004Sjulian			}
888173004Sjulian			if (dst != argbuf && dst[-1] == ' ')
889173004Sjulian				dst--;
890173004Sjulian			*dst = '\0';
891168710Sstas
892224202Sbz			if (strcmp(cmd, pp->ki_comm) != 0 ) {
893224202Sbz				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
894224202Sbz				    pp->ki_tdname[0])
895224202Sbz					snprintf(cmdbuf, cmdlengthdelta,
896224202Sbz					    "%s (%s){%s}", argbuf, pp->ki_comm,
897224202Sbz					    pp->ki_tdname);
898224202Sbz				else
899224202Sbz					snprintf(cmdbuf, cmdlengthdelta,
900224202Sbz					    "%s (%s)", argbuf, pp->ki_comm);
901224202Sbz			} else {
902224202Sbz				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
903224202Sbz				    pp->ki_tdname[0])
904224202Sbz					snprintf(cmdbuf, cmdlengthdelta,
905224202Sbz					    "%s{%s}", argbuf, pp->ki_tdname);
906224202Sbz				else
907224202Sbz					strlcpy(cmdbuf, argbuf, cmdlengthdelta);
908224202Sbz			}
909173004Sjulian			free(argbuf);
910173004Sjulian		}
911168710Sstas	}
912168710Sstas
913168799Srafan	if (ps.jail == 0)
914168799Srafan		jid_buf[0] = '\0';
915168799Srafan	else
916168799Srafan		snprintf(jid_buf, sizeof(jid_buf), " %*d",
917168799Srafan		    sizeof(jid_buf) - 3, pp->ki_jid);
918168799Srafan
919131623Sdes	if (displaymode == DISP_IO) {
920131623Sdes		oldp = get_old_proc(pp);
921131623Sdes		if (oldp != NULL) {
922158280Sbde			ru.ru_inblock = RU(pp)->ru_inblock -
923158280Sbde			    RU(oldp)->ru_inblock;
924158280Sbde			ru.ru_oublock = RU(pp)->ru_oublock -
925158280Sbde			    RU(oldp)->ru_oublock;
926131623Sdes			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
927133817Salfred			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
928133817Salfred			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
929131623Sdes			rup = &ru;
930131623Sdes		} else {
931131623Sdes			rup = RU(pp);
932131623Sdes		}
933131623Sdes		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
934131623Sdes		s_tot = total_inblock + total_oublock + total_majflt;
935131402Salfred
936234416Skib		snprintf(fmt, sizeof(fmt), io_Proc_format,
937131623Sdes		    pp->ki_pid,
938168799Srafan		    jid_buf,
939158280Sbde		    namelength, namelength, (*get_userid)(pp->ki_ruid),
940133817Salfred		    rup->ru_nvcsw,
941133817Salfred		    rup->ru_nivcsw,
942131626Sdes		    rup->ru_inblock,
943131626Sdes		    rup->ru_oublock,
944131626Sdes		    rup->ru_majflt,
945131626Sdes		    p_tot,
946131626Sdes		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
947131623Sdes		    screen_width > cmdlengthdelta ?
948131623Sdes		    screen_width - cmdlengthdelta : 0,
949168710Sstas		    printable(cmdbuf));
950168710Sstas
951168710Sstas		free(cmdbuf);
952168710Sstas
953131623Sdes		return (fmt);
954131623Sdes	}
955145073Skeramida
956131623Sdes	/* format this entry */
957145073Skeramida	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
958145073Skeramida	if (ps.thread != 0)
959145073Skeramida		thr_buf[0] = '\0';
960145073Skeramida	else
961145073Skeramida		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
962145073Skeramida		    sizeof(thr_buf) - 2, pp->ki_numthreads);
963145073Skeramida
964234416Skib	snprintf(fmt, sizeof(fmt), proc_fmt,
96569896Smckusick	    pp->ki_pid,
966168799Srafan	    jid_buf,
967158280Sbde	    namelength, namelength, (*get_userid)(pp->ki_ruid),
968145073Skeramida	    thr_buf,
96972377Sjake	    pp->ki_pri.pri_level - PZERO,
970158282Sbde	    format_nice(pp),
97137100Sdt	    format_k2(PROCSIZE(pp)),
97269896Smckusick	    format_k2(pagetok(pp->ki_rssize)),
97324143Sjoerg	    status,
97469896Smckusick	    smpmode ? pp->ki_lastcpu : 0,
97524143Sjoerg	    format_time(cputime),
976146342Skeramida	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
977158280Sbde	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
978168710Sstas	    printable(cmdbuf));
97924143Sjoerg
980168710Sstas	free(cmdbuf);
981168710Sstas
982131623Sdes	/* return the result */
983131623Sdes	return (fmt);
98424143Sjoerg}
98524143Sjoerg
986131310Salfredstatic void
987158282Sbdegetsysctl(const char *name, void *ptr, size_t len)
98824143Sjoerg{
989131623Sdes	size_t nlen = len;
990131310Salfred
991131623Sdes	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
992131623Sdes		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
993131623Sdes		    strerror(errno));
994131623Sdes		quit(23);
995131623Sdes	}
996131623Sdes	if (nlen != len) {
997158280Sbde		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
998158280Sbde		    name, (unsigned long)len, (unsigned long)nlen);
999131623Sdes		quit(23);
1000131623Sdes	}
100124143Sjoerg}
100272951Srwatson
1003164058Sbdestatic const char *
1004164058Sbdeformat_nice(const struct kinfo_proc *pp)
1005158282Sbde{
1006164058Sbde	const char *fifo, *kthread;
1007164058Sbde	int rtpri;
1008164058Sbde	static char nicebuf[4 + 1];
1009158282Sbde
1010164058Sbde	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1011164058Sbde	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1012164058Sbde	switch (PRI_BASE(pp->ki_pri.pri_class)) {
1013164058Sbde	case PRI_ITHD:
1014164058Sbde		return ("-");
1015164058Sbde	case PRI_REALTIME:
1016170774Sbde		/*
1017170774Sbde		 * XXX: the kernel doesn't tell us the original rtprio and
1018170774Sbde		 * doesn't really know what it was, so to recover it we
1019170774Sbde		 * must be more chummy with the implementation than the
1020170774Sbde		 * implementation is with itself.  pri_user gives a
1021170774Sbde		 * constant "base" priority, but is only initialized
1022170774Sbde		 * properly for user threads.  pri_native gives what the
1023170774Sbde		 * kernel calls the "base" priority, but it isn't constant
1024170774Sbde		 * since it is changed by priority propagation.  pri_native
1025170774Sbde		 * also isn't properly initialized for all threads, but it
1026170774Sbde		 * is properly initialized for kernel realtime and idletime
1027170774Sbde		 * threads.  Thus we use pri_user for the base priority of
1028170774Sbde		 * user threads (it is always correct) and pri_native for
1029170774Sbde		 * the base priority of kernel realtime and idletime threads
1030170774Sbde		 * (there is nothing better, and it is usually correct).
1031170774Sbde		 *
1032170774Sbde		 * The field width and thus the buffer are too small for
1033170774Sbde		 * values like "kr31F", but such values shouldn't occur,
1034170774Sbde		 * and if they do then the tailing "F" is not displayed.
1035170774Sbde		 */
1036170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1037170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1038164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1039164058Sbde		    kthread, rtpri, fifo);
1040164058Sbde		break;
1041164058Sbde	case PRI_TIMESHARE:
1042164058Sbde		if (pp->ki_flag & P_KTHREAD)
1043164058Sbde			return ("-");
1044164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1045164058Sbde		break;
1046164058Sbde	case PRI_IDLE:
1047170774Sbde		/* XXX: as above. */
1048170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1049170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1050164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1051164058Sbde		    kthread, rtpri, fifo);
1052164058Sbde		break;
1053164058Sbde	default:
1054164058Sbde		return ("?");
1055164058Sbde	}
1056158282Sbde	return (nicebuf);
1057158282Sbde}
1058158282Sbde
105938278Swosch/* comparison routines for qsort */
106024143Sjoerg
1061158282Sbdestatic int
1062131622Sdescompare_pid(const void *p1, const void *p2)
1063131402Salfred{
1064131623Sdes	const struct kinfo_proc * const *pp1 = p1;
1065131623Sdes	const struct kinfo_proc * const *pp2 = p2;
1066131402Salfred
1067131623Sdes	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1068131623Sdes		abort();
1069131402Salfred
1070131623Sdes	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1071131402Salfred}
1072131402Salfred
1073224188Sjhbstatic int
1074224188Sjhbcompare_tid(const void *p1, const void *p2)
1075224188Sjhb{
1076224188Sjhb	const struct kinfo_proc * const *pp1 = p1;
1077224188Sjhb	const struct kinfo_proc * const *pp2 = p2;
1078224188Sjhb
1079224188Sjhb	if ((*pp2)->ki_tid < 0 || (*pp1)->ki_tid < 0)
1080224188Sjhb		abort();
1081224188Sjhb
1082224188Sjhb	return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1083224188Sjhb}
1084224188Sjhb
108524143Sjoerg/*
108624143Sjoerg *  proc_compare - comparison function for "qsort"
108724143Sjoerg *	Compares the resource consumption of two processes using five
1088131620Sdes *	distinct keys.  The keys (in descending order of importance) are:
1089131620Sdes *	percent cpu, cpu ticks, state, resident set size, total virtual
1090131620Sdes *	memory usage.  The process states are ordered as follows (from least
1091131620Sdes *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
1092131620Sdes *	array declaration below maps a process state index into a number
1093131620Sdes *	that reflects this ordering.
109424143Sjoerg */
109524143Sjoerg
1096158280Sbdestatic int sorted_state[] = {
1097131623Sdes	0,	/* not used		*/
1098131623Sdes	3,	/* sleep		*/
1099131623Sdes	1,	/* ABANDONED (WAIT)	*/
1100131623Sdes	6,	/* run			*/
1101131623Sdes	5,	/* start		*/
1102131623Sdes	2,	/* zombie		*/
1103131623Sdes	4	/* stop			*/
110424143Sjoerg};
110538278Swosch
1106131620Sdes
1107146343Skeramida#define ORDERKEY_PCTCPU(a, b) do { \
1108146343Skeramida	long diff; \
1109146343Skeramida	if (ps.wcpu) \
1110158280Sbde		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1111158280Sbde		    (b))) - \
1112158280Sbde		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1113158280Sbde		    (a))); \
1114146343Skeramida	else \
1115146343Skeramida		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1116146343Skeramida	if (diff != 0) \
1117146343Skeramida		return (diff > 0 ? 1 : -1); \
1118131626Sdes} while (0)
111938278Swosch
1120131626Sdes#define ORDERKEY_CPTICKS(a, b) do { \
1121131628Sdes	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1122131626Sdes	if (diff != 0) \
1123131626Sdes		return (diff > 0 ? 1 : -1); \
1124131626Sdes} while (0)
112538278Swosch
1126131626Sdes#define ORDERKEY_STATE(a, b) do { \
1127131626Sdes	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1128131626Sdes	if (diff != 0) \
1129131626Sdes		return (diff > 0 ? 1 : -1); \
1130131626Sdes} while (0)
113138278Swosch
1132131626Sdes#define ORDERKEY_PRIO(a, b) do { \
1133131628Sdes	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1134131626Sdes	if (diff != 0) \
1135131626Sdes		return (diff > 0 ? 1 : -1); \
1136131626Sdes} while (0)
113738278Swosch
1138145073Skeramida#define	ORDERKEY_THREADS(a, b) do { \
1139145073Skeramida	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1140145073Skeramida	if (diff != 0) \
1141145073Skeramida		return (diff > 0 ? 1 : -1); \
1142145073Skeramida} while (0)
1143145073Skeramida
1144131626Sdes#define ORDERKEY_RSSIZE(a, b) do { \
1145131628Sdes	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1146131626Sdes	if (diff != 0) \
1147131626Sdes		return (diff > 0 ? 1 : -1); \
1148131626Sdes} while (0)
114938278Swosch
1150131626Sdes#define ORDERKEY_MEM(a, b) do { \
1151131628Sdes	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1152131626Sdes	if (diff != 0) \
1153131626Sdes		return (diff > 0 ? 1 : -1); \
1154131626Sdes} while (0)
115538278Swosch
1156168799Srafan#define ORDERKEY_JID(a, b) do { \
1157168799Srafan	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1158168799Srafan	if (diff != 0) \
1159168799Srafan		return (diff > 0 ? 1 : -1); \
1160168799Srafan} while (0)
1161168799Srafan
116238278Swosch/* compare_cpu - the comparison function for sorting by cpu percentage */
116338278Swosch
116424143Sjoergint
116538278Swosch#ifdef ORDER
1166131626Sdescompare_cpu(void *arg1, void *arg2)
116738278Swosch#else
1168131626Sdesproc_compare(void *arg1, void *arg2)
116938278Swosch#endif
117024143Sjoerg{
1171131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1172131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
117324143Sjoerg
1174131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1175131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1176131626Sdes	ORDERKEY_STATE(p1, p2);
1177131626Sdes	ORDERKEY_PRIO(p1, p2);
1178131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1179131626Sdes	ORDERKEY_MEM(p1, p2);
118024143Sjoerg
1181131626Sdes	return (0);
118224143Sjoerg}
118324143Sjoerg
118438278Swosch#ifdef ORDER
1185158280Sbde/* "cpu" compare routines */
1186158280Sbdeint compare_size(), compare_res(), compare_time(), compare_prio(),
1187158280Sbde    compare_threads();
118824143Sjoerg
1189158280Sbde/*
1190158280Sbde * "io" compare routines.  Context switches aren't i/o, but are displayed
1191158280Sbde * on the "io" display.
1192158280Sbde */
1193158280Sbdeint compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1194158280Sbde    compare_vcsw(), compare_ivcsw();
1195158280Sbde
1196133817Salfredint (*compares[])() = {
1197131623Sdes	compare_cpu,
1198131623Sdes	compare_size,
1199131623Sdes	compare_res,
1200131623Sdes	compare_time,
1201131623Sdes	compare_prio,
1202145073Skeramida	compare_threads,
1203133817Salfred	compare_iototal,
1204133817Salfred	compare_ioread,
1205133817Salfred	compare_iowrite,
1206133817Salfred	compare_iofault,
1207133817Salfred	compare_vcsw,
1208133817Salfred	compare_ivcsw,
1209168799Srafan	compare_jid,
1210131623Sdes	NULL
121138278Swosch};
121238278Swosch
121338278Swosch/* compare_size - the comparison function for sorting by total memory usage */
121438278Swosch
121538278Swoschint
1216131626Sdescompare_size(void *arg1, void *arg2)
121738278Swosch{
1218131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1219131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
122038278Swosch
1221131626Sdes	ORDERKEY_MEM(p1, p2);
1222131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1223131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1224131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1225131626Sdes	ORDERKEY_STATE(p1, p2);
1226131626Sdes	ORDERKEY_PRIO(p1, p2);
122738278Swosch
1228131626Sdes	return (0);
122938278Swosch}
123038278Swosch
123138278Swosch/* compare_res - the comparison function for sorting by resident set size */
123238278Swosch
123338278Swoschint
1234131626Sdescompare_res(void *arg1, void *arg2)
123538278Swosch{
1236131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1237131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
123838278Swosch
1239131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1240131626Sdes	ORDERKEY_MEM(p1, p2);
1241131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1242131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1243131626Sdes	ORDERKEY_STATE(p1, p2);
1244131626Sdes	ORDERKEY_PRIO(p1, p2);
124538278Swosch
1246131626Sdes	return (0);
124738278Swosch}
124838278Swosch
124938278Swosch/* compare_time - the comparison function for sorting by total cpu time */
125038278Swosch
125138278Swoschint
1252131626Sdescompare_time(void *arg1, void *arg2)
1253131310Salfred{
1254131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1255131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
125638278Swosch
1257131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1258131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1259131626Sdes	ORDERKEY_STATE(p1, p2);
1260131626Sdes	ORDERKEY_PRIO(p1, p2);
1261131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1262131626Sdes	ORDERKEY_MEM(p1, p2);
126338278Swosch
1264131626Sdes	return (0);
1265131623Sdes}
1266131310Salfred
1267131626Sdes/* compare_prio - the comparison function for sorting by priority */
126838278Swosch
126938278Swoschint
1270131626Sdescompare_prio(void *arg1, void *arg2)
127138278Swosch{
1272131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1273131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
127438278Swosch
1275131626Sdes	ORDERKEY_PRIO(p1, p2);
1276131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1277131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1278131626Sdes	ORDERKEY_STATE(p1, p2);
1279131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1280131626Sdes	ORDERKEY_MEM(p1, p2);
128138278Swosch
1282131626Sdes	return (0);
128338278Swosch}
1284145073Skeramida
1285145073Skeramida/* compare_threads - the comparison function for sorting by threads */
1286145073Skeramidaint
1287145073Skeramidacompare_threads(void *arg1, void *arg2)
1288145073Skeramida{
1289145073Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1290145073Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1291145073Skeramida
1292145073Skeramida	ORDERKEY_THREADS(p1, p2);
1293145073Skeramida	ORDERKEY_PCTCPU(p1, p2);
1294145073Skeramida	ORDERKEY_CPTICKS(p1, p2);
1295145073Skeramida	ORDERKEY_STATE(p1, p2);
1296145073Skeramida	ORDERKEY_PRIO(p1, p2);
1297145073Skeramida	ORDERKEY_RSSIZE(p1, p2);
1298145073Skeramida	ORDERKEY_MEM(p1, p2);
1299145073Skeramida
1300145073Skeramida	return (0);
1301145073Skeramida}
1302168799Srafan
1303168799Srafan/* compare_jid - the comparison function for sorting by jid */
1304168799Srafanstatic int
1305168799Srafancompare_jid(const void *arg1, const void *arg2)
1306168799Srafan{
1307168799Srafan	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1308168799Srafan	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1309168799Srafan
1310168799Srafan	ORDERKEY_JID(p1, p2);
1311168799Srafan	ORDERKEY_PCTCPU(p1, p2);
1312168799Srafan	ORDERKEY_CPTICKS(p1, p2);
1313168799Srafan	ORDERKEY_STATE(p1, p2);
1314168799Srafan	ORDERKEY_PRIO(p1, p2);
1315168799Srafan	ORDERKEY_RSSIZE(p1, p2);
1316168799Srafan	ORDERKEY_MEM(p1, p2);
1317168799Srafan
1318168799Srafan	return (0);
1319168799Srafan}
1320158280Sbde#endif /* ORDER */
132138278Swosch
1322158280Sbde/* assorted comparison functions for sorting by i/o */
1323131829Skeramida
1324131402Salfredint
1325131829Skeramida#ifdef ORDER
1326131829Skeramidacompare_iototal(void *arg1, void *arg2)
1327131829Skeramida#else
1328131626Sdesio_compare(void *arg1, void *arg2)
1329131829Skeramida#endif
1330131402Salfred{
1331131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1332131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1333131402Salfred
1334131626Sdes	return (get_io_total(p2) - get_io_total(p1));
1335131402Salfred}
1336131829Skeramida
1337131829Skeramida#ifdef ORDER
1338131829Skeramidaint
1339131829Skeramidacompare_ioread(void *arg1, void *arg2)
1340131829Skeramida{
1341131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1342131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1343131829Skeramida	long dummy, inp1, inp2;
1344131829Skeramida
1345133817Salfred	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1346133817Salfred	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1347131829Skeramida
1348131829Skeramida	return (inp2 - inp1);
1349131829Skeramida}
1350131829Skeramida
1351131829Skeramidaint
1352131829Skeramidacompare_iowrite(void *arg1, void *arg2)
1353131829Skeramida{
1354131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1355131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1356131829Skeramida	long dummy, oup1, oup2;
1357131829Skeramida
1358133817Salfred	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1359133817Salfred	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1360131829Skeramida
1361131829Skeramida	return (oup2 - oup1);
1362131829Skeramida}
1363131829Skeramida
1364131829Skeramidaint
1365131829Skeramidacompare_iofault(void *arg1, void *arg2)
1366131829Skeramida{
1367131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1368131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1369131829Skeramida	long dummy, flp1, flp2;
1370131829Skeramida
1371133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1372133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1373131829Skeramida
1374131829Skeramida	return (flp2 - flp1);
1375131829Skeramida}
1376131829Skeramida
1377133817Salfredint
1378133817Salfredcompare_vcsw(void *arg1, void *arg2)
1379133817Salfred{
1380133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1381133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1382133817Salfred	long dummy, flp1, flp2;
1383133817Salfred
1384133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1385133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1386133817Salfred
1387133817Salfred	return (flp2 - flp1);
1388133817Salfred}
1389133817Salfred
1390133817Salfredint
1391133817Salfredcompare_ivcsw(void *arg1, void *arg2)
1392133817Salfred{
1393133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1394133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1395133817Salfred	long dummy, flp1, flp2;
1396133817Salfred
1397133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1398133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1399133817Salfred
1400133817Salfred	return (flp2 - flp1);
1401133817Salfred}
1402131829Skeramida#endif /* ORDER */
1403131829Skeramida
140424143Sjoerg/*
140524143Sjoerg * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
140624143Sjoerg *		the process does not exist.
1407228992Suqs *		It is EXTREMELY IMPORTANT that this function work correctly.
140824143Sjoerg *		If top runs setuid root (as in SVR4), then this function
140924143Sjoerg *		is the only thing that stands in the way of a serious
141024143Sjoerg *		security problem.  It validates requests for the "kill"
141124143Sjoerg *		and "renice" commands.
141224143Sjoerg */
141324143Sjoerg
1414131310Salfredint
1415131622Sdesproc_owner(int pid)
141624143Sjoerg{
1417131623Sdes	int cnt;
1418131623Sdes	struct kinfo_proc **prefp;
1419131623Sdes	struct kinfo_proc *pp;
142024143Sjoerg
1421131623Sdes	prefp = pref;
1422131623Sdes	cnt = pref_len;
1423131626Sdes	while (--cnt >= 0) {
1424131623Sdes		pp = *prefp++;
1425131623Sdes		if (pp->ki_pid == (pid_t)pid)
1426131623Sdes			return ((int)pp->ki_ruid);
142724143Sjoerg	}
1428131623Sdes	return (-1);
142924143Sjoerg}
143024143Sjoerg
1431158282Sbdestatic int
1432131622Sdesswapmode(int *retavail, int *retfree)
143324143Sjoerg{
143443053Sdillon	int n;
143543053Sdillon	int pagesize = getpagesize();
143643053Sdillon	struct kvm_swap swapary[1];
143724143Sjoerg
143843053Sdillon	*retavail = 0;
143943053Sdillon	*retfree = 0;
144024143Sjoerg
144143053Sdillon#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
144224143Sjoerg
144343053Sdillon	n = kvm_getswapinfo(kd, swapary, 1, 0);
144443697Sdillon	if (n < 0 || swapary[0].ksw_total == 0)
1445131623Sdes		return (0);
144624143Sjoerg
144743053Sdillon	*retavail = CONVERT(swapary[0].ksw_total);
144843053Sdillon	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
144924143Sjoerg
1450131626Sdes	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1451131623Sdes	return (n);
145243053Sdillon}
1453