machine.c revision 224199
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 224199 2011-07-18 20:06:15Z bz $
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
244223936Sjhbtoggle_pcpustats(struct statics *statics)
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		statics->ncpus = ncpus;
260223936Sjhb	} else {
261223936Sjhb		y_mem = 3;
262223936Sjhb		y_swap = 4;
263223936Sjhb		y_idlecursor = 5;
264223936Sjhb		y_message = 5;
265223936Sjhb		y_header = 6;
266223936Sjhb		y_procs = 7;
267223936Sjhb		Header_lines = 7;
268223936Sjhb		statics->ncpus = 1;
269223936Sjhb	}
270223936Sjhb}
271223936Sjhb
27224143Sjoergint
273175195Sobrienmachine_init(struct statics *statics, char do_unames)
27424143Sjoerg{
275223936Sjhb	int i, j, empty, pagesize;
276223936Sjhb	size_t size;
277131623Sdes	struct passwd *pw;
27824143Sjoerg
279223936Sjhb	size = sizeof(smpmode);
280223936Sjhb	if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
281158280Sbde	    NULL, 0) != 0 &&
282223936Sjhb	    sysctlbyname("kern.smp.active", &smpmode, &size,
283158280Sbde	    NULL, 0) != 0) ||
284223936Sjhb	    size != sizeof(smpmode))
285131623Sdes		smpmode = 0;
28627340Speter
287175195Sobrien	if (do_unames) {
288175195Sobrien	    while ((pw = getpwent()) != NULL) {
289131623Sdes		if (strlen(pw->pw_name) > namelength)
290131623Sdes			namelength = strlen(pw->pw_name);
291175195Sobrien	    }
292131623Sdes	}
293146291Sobrien	if (smpmode && namelength > SMPUNAMELEN)
294146291Sobrien		namelength = SMPUNAMELEN;
295146291Sobrien	else if (namelength > UPUNAMELEN)
296146291Sobrien		namelength = UPUNAMELEN;
29727390Speter
298131626Sdes	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
299131626Sdes	if (kd == NULL)
300131626Sdes		return (-1);
30124143Sjoerg
302131623Sdes	GETSYSCTL("kern.ccpu", ccpu);
30324143Sjoerg
304131623Sdes	/* this is used in calculating WCPU -- calculate it ahead of time */
305131623Sdes	logcpu = log(loaddouble(ccpu));
30624143Sjoerg
307131623Sdes	pbase = NULL;
308131623Sdes	pref = NULL;
309131623Sdes	nproc = 0;
310131623Sdes	onproc = -1;
311158280Sbde
312158280Sbde	/* get the page size and calculate pageshift from it */
313131623Sdes	pagesize = getpagesize();
314131623Sdes	pageshift = 0;
315131626Sdes	while (pagesize > 1) {
316131623Sdes		pageshift++;
317131623Sdes		pagesize >>= 1;
318131623Sdes	}
31924143Sjoerg
320131623Sdes	/* we only need the amount of log(2)1024 for our conversion */
321131623Sdes	pageshift -= LOG1024;
32224143Sjoerg
323131623Sdes	/* fill in the statics information */
324131623Sdes	statics->procstate_names = procstatenames;
325131623Sdes	statics->cpustate_names = cpustatenames;
326131623Sdes	statics->memory_names = memorynames;
327131623Sdes	statics->swap_names = swapnames;
32838278Swosch#ifdef ORDER
329133817Salfred	statics->order_names = ordernames;
33038278Swosch#endif
33124143Sjoerg
332223936Sjhb	/* Allocate state for per-CPU stats. */
333223936Sjhb	cpumask = 0;
334223936Sjhb	ncpus = 0;
335223936Sjhb	GETSYSCTL("kern.smp.maxcpus", maxcpu);
336223936Sjhb	size = sizeof(long) * maxcpu * CPUSTATES;
337223936Sjhb	times = malloc(size);
338223936Sjhb	if (times == NULL)
339223936Sjhb		err(1, "malloc %zd bytes", size);
340223936Sjhb	if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
341223936Sjhb		err(1, "sysctlbyname kern.cp_times");
342223936Sjhb	pcpu_cp_time = calloc(1, size);
343223936Sjhb	maxid = (size / CPUSTATES / sizeof(long)) - 1;
344223936Sjhb	for (i = 0; i <= maxid; i++) {
345223936Sjhb		empty = 1;
346223936Sjhb		for (j = 0; empty && j < CPUSTATES; j++) {
347223936Sjhb			if (times[i * CPUSTATES + j] != 0)
348223936Sjhb				empty = 0;
349175420Speter		}
350223936Sjhb		if (!empty) {
351223936Sjhb			cpumask |= (1ul << i);
352223936Sjhb			ncpus++;
353175420Speter		}
354175420Speter	}
355223936Sjhb	size = sizeof(long) * ncpus * CPUSTATES;
356223936Sjhb	pcpu_cp_old = calloc(1, size);
357223936Sjhb	pcpu_cp_diff = calloc(1, size);
358223936Sjhb	pcpu_cpu_states = calloc(1, size);
359223936Sjhb	statics->ncpus = 1;
360175420Speter
361223936Sjhb	if (pcpu_stats)
362223936Sjhb		toggle_pcpustats(statics);
363223936Sjhb
364131623Sdes	/* all done! */
365131623Sdes	return (0);
36624143Sjoerg}
36724143Sjoerg
368131310Salfredchar *
369131622Sdesformat_header(char *uname_field)
37024143Sjoerg{
371131623Sdes	static char Header[128];
372131623Sdes	const char *prehead;
37324143Sjoerg
374131623Sdes	switch (displaymode) {
375131623Sdes	case DISP_CPU:
376145073Skeramida		/*
377145073Skeramida		 * The logic of picking the right header format seems reverse
378145073Skeramida		 * here because we only want to display a THR column when
379145073Skeramida		 * "thread mode" is off (and threads are not listed as
380145073Skeramida		 * separate lines).
381145073Skeramida		 */
382145073Skeramida		prehead = smpmode ?
383145073Skeramida		    (ps.thread ? smp_header : smp_header_thr) :
384145073Skeramida		    (ps.thread ? up_header : up_header_thr);
385146342Skeramida		snprintf(Header, sizeof(Header), prehead,
386168799Srafan		    ps.jail ? " JID" : "",
387146342Skeramida		    namelength, namelength, uname_field,
388146342Skeramida		    ps.wcpu ? "WCPU" : "CPU");
389131623Sdes		break;
390131623Sdes	case DISP_IO:
391131623Sdes		prehead = io_header;
392146342Skeramida		snprintf(Header, sizeof(Header), prehead,
393168799Srafan		    ps.jail ? " JID" : "",
394146342Skeramida		    namelength, namelength, uname_field);
395131623Sdes		break;
396131623Sdes	}
397131623Sdes	cmdlengthdelta = strlen(Header) - 7;
398131623Sdes	return (Header);
39924143Sjoerg}
40024143Sjoerg
40124143Sjoergstatic int swappgsin = -1;
40224143Sjoergstatic int swappgsout = -1;
40324143Sjoergextern struct timeval timeout;
40424143Sjoerg
405175420Speter
40624143Sjoergvoid
407131622Sdesget_system_info(struct system_info *si)
40824143Sjoerg{
409131623Sdes	long total;
410131623Sdes	struct loadavg sysload;
411131623Sdes	int mib[2];
412131623Sdes	struct timeval boottime;
413131623Sdes	size_t bt_size;
414175420Speter	int i, j;
415175420Speter	size_t size;
41624143Sjoerg
417223936Sjhb	/* get the CPU stats */
418223936Sjhb	size = (maxid + 1) * CPUSTATES * sizeof(long);
419223936Sjhb	if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
420223936Sjhb		err(1, "sysctlbyname kern.cp_times");
421223936Sjhb	GETSYSCTL("kern.cp_time", cp_time);
422131623Sdes	GETSYSCTL("vm.loadavg", sysload);
423131623Sdes	GETSYSCTL("kern.lastpid", lastpid);
42424143Sjoerg
425131623Sdes	/* convert load averages to doubles */
426131626Sdes	for (i = 0; i < 3; i++)
427131626Sdes		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
42824143Sjoerg
429223936Sjhb	/* convert cp_time counts to percentages */
430223936Sjhb	for (i = j = 0; i <= maxid; i++) {
431223936Sjhb		if ((cpumask & (1ul << i)) == 0)
432223936Sjhb			continue;
433223936Sjhb		percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
434223936Sjhb		    &pcpu_cp_time[j * CPUSTATES],
435223936Sjhb		    &pcpu_cp_old[j * CPUSTATES],
436223936Sjhb		    &pcpu_cp_diff[j * CPUSTATES]);
437223936Sjhb		j++;
438175420Speter	}
439223936Sjhb	percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
44024143Sjoerg
441131623Sdes	/* sum memory & swap statistics */
442131623Sdes	{
443131623Sdes		static unsigned int swap_delay = 0;
444131623Sdes		static int swapavail = 0;
445131623Sdes		static int swapfree = 0;
446189626Sjhb		static long bufspace = 0;
447131623Sdes		static int nspgsin, nspgsout;
44824143Sjoerg
449131623Sdes		GETSYSCTL("vfs.bufspace", bufspace);
450131623Sdes		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
451131623Sdes		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
452131623Sdes		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
453131623Sdes		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
454131623Sdes		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
455131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
456131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
457131623Sdes		/* convert memory stats to Kbytes */
458131623Sdes		memory_stats[0] = pagetok(memory_stats[0]);
459131623Sdes		memory_stats[1] = pagetok(memory_stats[1]);
460131623Sdes		memory_stats[2] = pagetok(memory_stats[2]);
461131623Sdes		memory_stats[3] = pagetok(memory_stats[3]);
462131623Sdes		memory_stats[4] = bufspace / 1024;
463131623Sdes		memory_stats[5] = pagetok(memory_stats[5]);
464131623Sdes		memory_stats[6] = -1;
46524143Sjoerg
466131623Sdes		/* first interval */
467131623Sdes		if (swappgsin < 0) {
468131623Sdes			swap_stats[4] = 0;
469131623Sdes			swap_stats[5] = 0;
470131623Sdes		}
47124143Sjoerg
472131623Sdes		/* compute differences between old and new swap statistic */
473131623Sdes		else {
474131623Sdes			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
475131623Sdes			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
476131623Sdes		}
47724143Sjoerg
478131623Sdes		swappgsin = nspgsin;
479131623Sdes		swappgsout = nspgsout;
48024143Sjoerg
481131623Sdes		/* call CPU heavy swapmode() only for changes */
482131623Sdes		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
483131623Sdes			swap_stats[3] = swapmode(&swapavail, &swapfree);
484131623Sdes			swap_stats[0] = swapavail;
485131623Sdes			swap_stats[1] = swapavail - swapfree;
486131623Sdes			swap_stats[2] = swapfree;
487131623Sdes		}
488131623Sdes		swap_delay = 1;
489131623Sdes		swap_stats[6] = -1;
49024143Sjoerg	}
49124143Sjoerg
492131623Sdes	/* set arrays and strings */
493175420Speter	if (pcpu_stats) {
494175420Speter		si->cpustates = pcpu_cpu_states;
495175420Speter		si->ncpus = ncpus;
496175420Speter	} else {
497175420Speter		si->cpustates = cpu_states;
498175420Speter		si->ncpus = 1;
499175420Speter	}
500131623Sdes	si->memory = memory_stats;
501131623Sdes	si->swap = swap_stats;
50224143Sjoerg
50324143Sjoerg
504131623Sdes	if (lastpid > 0) {
505131623Sdes		si->last_pid = lastpid;
506131623Sdes	} else {
507131623Sdes		si->last_pid = -1;
508131623Sdes	}
50942447Sobrien
510131623Sdes	/*
511131623Sdes	 * Print how long system has been up.
512131623Sdes	 * (Found by looking getting "boottime" from the kernel)
513131623Sdes	 */
514131623Sdes	mib[0] = CTL_KERN;
515131623Sdes	mib[1] = KERN_BOOTTIME;
516131623Sdes	bt_size = sizeof(boottime);
517131623Sdes	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
518131623Sdes	    boottime.tv_sec != 0) {
519131623Sdes		si->boottime = boottime;
520131623Sdes	} else {
521131623Sdes		si->boottime.tv_sec = -1;
522131623Sdes	}
52324143Sjoerg}
52424143Sjoerg
525132015Salfred#define NOPROC	((void *)-1)
526132015Salfred
527132955Salfred/*
528132955Salfred * We need to compare data from the old process entry with the new
529132955Salfred * process entry.
530132955Salfred * To facilitate doing this quickly we stash a pointer in the kinfo_proc
531132955Salfred * structure to cache the mapping.  We also use a negative cache pointer
532132955Salfred * of NOPROC to avoid duplicate lookups.
533132955Salfred * XXX: this could be done when the actual processes are fetched, we do
534132955Salfred * it here out of laziness.
535132955Salfred */
536131402Salfredconst struct kinfo_proc *
537131402Salfredget_old_proc(struct kinfo_proc *pp)
538131402Salfred{
539131402Salfred	struct kinfo_proc **oldpp, *oldp;
540131402Salfred
541132955Salfred	/*
542132955Salfred	 * If this is the first fetch of the kinfo_procs then we don't have
543132955Salfred	 * any previous entries.
544132955Salfred	 */
545131402Salfred	if (previous_proc_count == 0)
546131402Salfred		return (NULL);
547132955Salfred	/* negative cache? */
548132015Salfred	if (pp->ki_udata == NOPROC)
549132015Salfred		return (NULL);
550132955Salfred	/* cached? */
551132015Salfred	if (pp->ki_udata != NULL)
552132015Salfred		return (pp->ki_udata);
553132955Salfred	/*
554132955Salfred	 * Not cached,
555132955Salfred	 * 1) look up based on pid.
556132955Salfred	 * 2) compare process start.
557132955Salfred	 * If we fail here, then setup a negative cache entry, otherwise
558132955Salfred	 * cache it.
559132955Salfred	 */
560131402Salfred	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
561224188Sjhb	    sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
562132015Salfred	if (oldpp == NULL) {
563132015Salfred		pp->ki_udata = NOPROC;
564131402Salfred		return (NULL);
565132015Salfred	}
566131402Salfred	oldp = *oldpp;
567132015Salfred	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
568132015Salfred		pp->ki_udata = NOPROC;
569131402Salfred		return (NULL);
570132015Salfred	}
571132015Salfred	pp->ki_udata = oldp;
572131402Salfred	return (oldp);
573131402Salfred}
574131402Salfred
575132955Salfred/*
576132955Salfred * Return the total amount of IO done in blocks in/out and faults.
577132955Salfred * store the values individually in the pointers passed in.
578132955Salfred */
579131402Salfredlong
580158280Sbdeget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
581158280Sbde    long *vcsw, long *ivcsw)
582131402Salfred{
583131402Salfred	const struct kinfo_proc *oldp;
584131402Salfred	static struct kinfo_proc dummy;
585131402Salfred	long ret;
586131402Salfred
587131402Salfred	oldp = get_old_proc(pp);
588131402Salfred	if (oldp == NULL) {
589131402Salfred		bzero(&dummy, sizeof(dummy));
590131402Salfred		oldp = &dummy;
591131402Salfred	}
592131412Salfred	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
593131412Salfred	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
594131412Salfred	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
595133817Salfred	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
596133817Salfred	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
597131402Salfred	ret =
598131402Salfred	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
599131402Salfred	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
600131402Salfred	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
601131402Salfred	return (ret);
602131402Salfred}
603131402Salfred
604132955Salfred/*
605132955Salfred * Return the total number of block in/out and faults by a process.
606132955Salfred */
607131412Salfredlong
608131412Salfredget_io_total(struct kinfo_proc *pp)
609131412Salfred{
610131412Salfred	long dummy;
611131412Salfred
612133817Salfred	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
613131412Salfred}
614131412Salfred
61524143Sjoergstatic struct handle handle;
61624143Sjoerg
617131310Salfredcaddr_t
618131622Sdesget_process_info(struct system_info *si, struct process_select *sel,
619131626Sdes    int (*compare)(const void *, const void *))
62024143Sjoerg{
621131623Sdes	int i;
622131623Sdes	int total_procs;
623131623Sdes	long p_io;
624133817Salfred	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
625131623Sdes	int active_procs;
626131623Sdes	struct kinfo_proc **prefp;
627131623Sdes	struct kinfo_proc *pp;
62824143Sjoerg
629131623Sdes	/* these are copied out of sel for speed */
630131623Sdes	int show_idle;
631131623Sdes	int show_self;
632131623Sdes	int show_system;
633131623Sdes	int show_uid;
634131623Sdes	int show_command;
635222530Sjhb	int show_kidle;
63624143Sjoerg
637131623Sdes	/*
638131623Sdes	 * Save the previous process info.
639131623Sdes	 */
640131623Sdes	if (previous_proc_count_max < nproc) {
641131623Sdes		free(previous_procs);
642131626Sdes		previous_procs = malloc(nproc * sizeof(*previous_procs));
643131623Sdes		free(previous_pref);
644131626Sdes		previous_pref = malloc(nproc * sizeof(*previous_pref));
645131623Sdes		if (previous_procs == NULL || previous_pref == NULL) {
646131623Sdes			(void) fprintf(stderr, "top: Out of memory.\n");
647131623Sdes			quit(23);
648131623Sdes		}
649131623Sdes		previous_proc_count_max = nproc;
650131623Sdes	}
651131623Sdes	if (nproc) {
652131623Sdes		for (i = 0; i < nproc; i++)
653131623Sdes			previous_pref[i] = &previous_procs[i];
654131626Sdes		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
655158280Sbde		qsort(previous_pref, nproc, sizeof(*previous_pref),
656224188Sjhb		    ps.thread ? compare_tid : compare_pid);
657131623Sdes	}
658131623Sdes	previous_proc_count = nproc;
659131402Salfred
660224062Sjhb	pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
661224062Sjhb	    0, &nproc);
662131623Sdes	if (nproc > onproc)
663131626Sdes		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
664131623Sdes	if (pref == NULL || pbase == NULL) {
665131623Sdes		(void) fprintf(stderr, "top: Out of memory.\n");
666131623Sdes		quit(23);
667131623Sdes	}
668131623Sdes	/* get a pointer to the states summary array */
669131623Sdes	si->procstates = process_states;
67024143Sjoerg
671131623Sdes	/* set up flags which define what we are going to select */
672131623Sdes	show_idle = sel->idle;
673132024Sdes	show_self = sel->self == -1;
674131623Sdes	show_system = sel->system;
675131623Sdes	show_uid = sel->uid != -1;
676131623Sdes	show_command = sel->command != NULL;
677222530Sjhb	show_kidle = sel->kidle;
67824143Sjoerg
679131623Sdes	/* count up process states and get pointers to interesting procs */
680131623Sdes	total_procs = 0;
681131623Sdes	active_procs = 0;
682131623Sdes	total_inblock = 0;
683131623Sdes	total_oublock = 0;
684131623Sdes	total_majflt = 0;
685131623Sdes	memset((char *)process_states, 0, sizeof(process_states));
686131623Sdes	prefp = pref;
687131626Sdes	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
688131619Sdes
689131623Sdes		if (pp->ki_stat == 0)
690132024Sdes			/* not in use */
691132024Sdes			continue;
692131619Sdes
693131623Sdes		if (!show_self && pp->ki_pid == sel->self)
694131623Sdes			/* skip self */
695131623Sdes			continue;
696131619Sdes
697131623Sdes		if (!show_system && (pp->ki_flag & P_SYSTEM))
698131623Sdes			/* skip system process */
699131623Sdes			continue;
700131619Sdes
701158280Sbde		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
702158280Sbde		    &p_vcsw, &p_ivcsw);
703131623Sdes		total_inblock += p_inblock;
704131623Sdes		total_oublock += p_oublock;
705131623Sdes		total_majflt += p_majflt;
706131623Sdes		total_procs++;
707131626Sdes		process_states[pp->ki_stat]++;
708131619Sdes
709131623Sdes		if (pp->ki_stat == SZOMB)
710131623Sdes			/* skip zombies */
711131623Sdes			continue;
712131619Sdes
713223841Sjhb		if (!show_kidle && pp->ki_tdflags & TDF_IDLETD)
714223841Sjhb			/* skip kernel idle process */
715223841Sjhb			continue;
716223841Sjhb
717131623Sdes		if (displaymode == DISP_CPU && !show_idle &&
718159520Sse		    (pp->ki_pctcpu == 0 ||
719159520Sse		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
720131623Sdes			/* skip idle or non-running processes */
721131623Sdes			continue;
722131619Sdes
723131623Sdes		if (displaymode == DISP_IO && !show_idle && p_io == 0)
724131623Sdes			/* skip processes that aren't doing I/O */
725131623Sdes			continue;
726131619Sdes
727131623Sdes		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
728158280Sbde			/* skip proc. that don't belong to the selected UID */
729131623Sdes			continue;
730131619Sdes
731224062Sjhb		*prefp++ = pp;
732224062Sjhb		active_procs++;
733131623Sdes	}
734131623Sdes
735131623Sdes	/* if requested, sort the "interesting" processes */
736131623Sdes	if (compare != NULL)
737131626Sdes		qsort(pref, active_procs, sizeof(*pref), compare);
73824143Sjoerg
739131623Sdes	/* remember active and total counts */
740131623Sdes	si->p_total = total_procs;
741131623Sdes	si->p_active = pref_len = active_procs;
74224143Sjoerg
743131623Sdes	/* pass back a handle */
744131623Sdes	handle.next_proc = pref;
745131623Sdes	handle.remaining = active_procs;
746131623Sdes	return ((caddr_t)&handle);
74724143Sjoerg}
74824143Sjoerg
749131626Sdesstatic char fmt[128];	/* static area where result is built */
75024143Sjoerg
751131310Salfredchar *
752168710Sstasformat_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
75324143Sjoerg{
754131623Sdes	struct kinfo_proc *pp;
755131623Sdes	const struct kinfo_proc *oldp;
756131623Sdes	long cputime;
757131623Sdes	double pct;
758131623Sdes	struct handle *hp;
759131623Sdes	char status[16];
760131623Sdes	int state;
761131623Sdes	struct rusage ru, *rup;
762131623Sdes	long p_tot, s_tot;
763168799Srafan	char *proc_fmt, thr_buf[6], jid_buf[6];
764168710Sstas	char *cmdbuf = NULL;
765168710Sstas	char **args;
76624143Sjoerg
767131623Sdes	/* find and remember the next proc structure */
768131623Sdes	hp = (struct handle *)handle;
769131623Sdes	pp = *(hp->next_proc++);
770131623Sdes	hp->remaining--;
771131620Sdes
772131623Sdes	/* get the process's command name */
773172207Sjeff	if ((pp->ki_flag & P_INMEM) == 0) {
774131623Sdes		/*
775131623Sdes		 * Print swapped processes as <pname>
776131623Sdes		 */
777158280Sbde		size_t len;
778158280Sbde
779158280Sbde		len = strlen(pp->ki_comm);
780131626Sdes		if (len > sizeof(pp->ki_comm) - 3)
781131626Sdes			len = sizeof(pp->ki_comm) - 3;
782131626Sdes		memmove(pp->ki_comm + 1, pp->ki_comm, len);
783131626Sdes		pp->ki_comm[0] = '<';
784131626Sdes		pp->ki_comm[len + 1] = '>';
785131626Sdes		pp->ki_comm[len + 2] = '\0';
786131623Sdes	}
787131623Sdes
78824143Sjoerg	/*
789131623Sdes	 * Convert the process's runtime from microseconds to seconds.  This
790131623Sdes	 * time includes the interrupt time although that is not wanted here.
791131623Sdes	 * ps(1) is similarly sloppy.
79224143Sjoerg	 */
793131623Sdes	cputime = (pp->ki_runtime + 500000) / 1000000;
79424143Sjoerg
795131623Sdes	/* calculate the base for cpu percentages */
796131623Sdes	pct = pctdouble(pp->ki_pctcpu);
79724143Sjoerg
798131623Sdes	/* generate "STATE" field */
799131623Sdes	switch (state = pp->ki_stat) {
80024143Sjoerg	case SRUN:
801131623Sdes		if (smpmode && pp->ki_oncpu != 0xff)
802131623Sdes			sprintf(status, "CPU%d", pp->ki_oncpu);
803131623Sdes		else
804131623Sdes			strcpy(status, "RUN");
805131623Sdes		break;
806104388Sjhb	case SLOCK:
807131623Sdes		if (pp->ki_kiflag & KI_LOCKBLOCK) {
808131623Sdes			sprintf(status, "*%.6s", pp->ki_lockname);
809131623Sdes			break;
810131623Sdes		}
811131623Sdes		/* fall through */
81224143Sjoerg	case SSLEEP:
813131623Sdes		if (pp->ki_wmesg != NULL) {
814131623Sdes			sprintf(status, "%.6s", pp->ki_wmesg);
815131623Sdes			break;
816131623Sdes		}
817131623Sdes		/* FALLTHROUGH */
81824143Sjoerg	default:
81943720Sfenner
820131623Sdes		if (state >= 0 &&
821131623Sdes		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
822131626Sdes			sprintf(status, "%.6s", state_abbrev[state]);
823131623Sdes		else
824131623Sdes			sprintf(status, "?%5d", state);
825131623Sdes		break;
826131623Sdes	}
82724143Sjoerg
828168710Sstas	cmdbuf = (char *)malloc(cmdlengthdelta + 1);
829168710Sstas	if (cmdbuf == NULL) {
830168710Sstas		warn("malloc(%d)", cmdlengthdelta + 1);
831168710Sstas		return NULL;
832168710Sstas	}
833168710Sstas
834168710Sstas	if (!(flags & FMT_SHOWARGS)) {
835173004Sjulian		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
836224199Sbz		    pp->ki_tdname[0]) {
837224199Sbz			snprintf(cmdbuf, cmdlengthdelta, "{%s}", pp->ki_tdname);
838173004Sjulian		} else {
839173004Sjulian			snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
840168710Sstas		}
841173004Sjulian	} else {
842173004Sjulian		if (pp->ki_flag & P_SYSTEM ||
843173004Sjulian		    pp->ki_args == NULL ||
844173004Sjulian		    (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
845173004Sjulian		    !(*args)) {
846173004Sjulian			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
847224199Sbz		    	    pp->ki_tdname[0]) {
848173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
849224199Sbz				    "{%s}", pp->ki_tdname);
850173004Sjulian			} else {
851173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
852173004Sjulian				    "[%s]", pp->ki_comm);
853173004Sjulian			}
854173004Sjulian		} else {
855173004Sjulian			char *src, *dst, *argbuf;
856173004Sjulian			char *cmd;
857173004Sjulian			size_t argbuflen;
858173004Sjulian			size_t len;
859168710Sstas
860173004Sjulian			argbuflen = cmdlengthdelta * 4;
861173004Sjulian			argbuf = (char *)malloc(argbuflen + 1);
862173004Sjulian			if (argbuf == NULL) {
863173004Sjulian				warn("malloc(%d)", argbuflen + 1);
864173004Sjulian				free(cmdbuf);
865173004Sjulian				return NULL;
866173004Sjulian			}
867168710Sstas
868173004Sjulian			dst = argbuf;
869168710Sstas
870173004Sjulian			/* Extract cmd name from argv */
871173004Sjulian			cmd = strrchr(*args, '/');
872173004Sjulian			if (cmd == NULL)
873173004Sjulian				cmd = *args;
874173004Sjulian			else
875173004Sjulian				cmd++;
876168710Sstas
877173004Sjulian			for (; (src = *args++) != NULL; ) {
878173004Sjulian				if (*src == '\0')
879173004Sjulian					continue;
880173004Sjulian				len = (argbuflen - (dst - argbuf) - 1) / 4;
881173004Sjulian				strvisx(dst, src,
882173004Sjulian				    strlen(src) < len ? strlen(src) : len,
883173004Sjulian				    VIS_NL | VIS_CSTYLE);
884173004Sjulian				while (*dst != '\0')
885173004Sjulian					dst++;
886173004Sjulian				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
887173004Sjulian					*dst++ = ' '; /* add delimiting space */
888173004Sjulian			}
889173004Sjulian			if (dst != argbuf && dst[-1] == ' ')
890173004Sjulian				dst--;
891173004Sjulian			*dst = '\0';
892168710Sstas
893173004Sjulian			if (strcmp(cmd, pp->ki_comm) != 0 )
894173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
895173004Sjulian				    "%s (%s)",argbuf,  pp->ki_comm);
896173004Sjulian			else
897173004Sjulian				strlcpy(cmdbuf, argbuf, cmdlengthdelta);
898173004Sjulian
899173004Sjulian			free(argbuf);
900173004Sjulian		}
901168710Sstas	}
902168710Sstas
903168799Srafan	if (ps.jail == 0)
904168799Srafan		jid_buf[0] = '\0';
905168799Srafan	else
906168799Srafan		snprintf(jid_buf, sizeof(jid_buf), " %*d",
907168799Srafan		    sizeof(jid_buf) - 3, pp->ki_jid);
908168799Srafan
909131623Sdes	if (displaymode == DISP_IO) {
910131623Sdes		oldp = get_old_proc(pp);
911131623Sdes		if (oldp != NULL) {
912158280Sbde			ru.ru_inblock = RU(pp)->ru_inblock -
913158280Sbde			    RU(oldp)->ru_inblock;
914158280Sbde			ru.ru_oublock = RU(pp)->ru_oublock -
915158280Sbde			    RU(oldp)->ru_oublock;
916131623Sdes			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
917133817Salfred			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
918133817Salfred			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
919131623Sdes			rup = &ru;
920131623Sdes		} else {
921131623Sdes			rup = RU(pp);
922131623Sdes		}
923131623Sdes		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
924131623Sdes		s_tot = total_inblock + total_oublock + total_majflt;
925131402Salfred
926131623Sdes		sprintf(fmt, io_Proc_format,
927131623Sdes		    pp->ki_pid,
928168799Srafan		    jid_buf,
929158280Sbde		    namelength, namelength, (*get_userid)(pp->ki_ruid),
930133817Salfred		    rup->ru_nvcsw,
931133817Salfred		    rup->ru_nivcsw,
932131626Sdes		    rup->ru_inblock,
933131626Sdes		    rup->ru_oublock,
934131626Sdes		    rup->ru_majflt,
935131626Sdes		    p_tot,
936131626Sdes		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
937131623Sdes		    screen_width > cmdlengthdelta ?
938131623Sdes		    screen_width - cmdlengthdelta : 0,
939168710Sstas		    printable(cmdbuf));
940168710Sstas
941168710Sstas		free(cmdbuf);
942168710Sstas
943131623Sdes		return (fmt);
944131623Sdes	}
945145073Skeramida
946131623Sdes	/* format this entry */
947145073Skeramida	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
948145073Skeramida	if (ps.thread != 0)
949145073Skeramida		thr_buf[0] = '\0';
950145073Skeramida	else
951145073Skeramida		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
952145073Skeramida		    sizeof(thr_buf) - 2, pp->ki_numthreads);
953145073Skeramida
954145073Skeramida	sprintf(fmt, proc_fmt,
95569896Smckusick	    pp->ki_pid,
956168799Srafan	    jid_buf,
957158280Sbde	    namelength, namelength, (*get_userid)(pp->ki_ruid),
958145073Skeramida	    thr_buf,
95972377Sjake	    pp->ki_pri.pri_level - PZERO,
960158282Sbde	    format_nice(pp),
96137100Sdt	    format_k2(PROCSIZE(pp)),
96269896Smckusick	    format_k2(pagetok(pp->ki_rssize)),
96324143Sjoerg	    status,
96469896Smckusick	    smpmode ? pp->ki_lastcpu : 0,
96524143Sjoerg	    format_time(cputime),
966146342Skeramida	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
967158280Sbde	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
968168710Sstas	    printable(cmdbuf));
96924143Sjoerg
970168710Sstas	free(cmdbuf);
971168710Sstas
972131623Sdes	/* return the result */
973131623Sdes	return (fmt);
97424143Sjoerg}
97524143Sjoerg
976131310Salfredstatic void
977158282Sbdegetsysctl(const char *name, void *ptr, size_t len)
97824143Sjoerg{
979131623Sdes	size_t nlen = len;
980131310Salfred
981131623Sdes	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
982131623Sdes		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
983131623Sdes		    strerror(errno));
984131623Sdes		quit(23);
985131623Sdes	}
986131623Sdes	if (nlen != len) {
987158280Sbde		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
988158280Sbde		    name, (unsigned long)len, (unsigned long)nlen);
989131623Sdes		quit(23);
990131623Sdes	}
99124143Sjoerg}
99272951Srwatson
993164058Sbdestatic const char *
994164058Sbdeformat_nice(const struct kinfo_proc *pp)
995158282Sbde{
996164058Sbde	const char *fifo, *kthread;
997164058Sbde	int rtpri;
998164058Sbde	static char nicebuf[4 + 1];
999158282Sbde
1000164058Sbde	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1001164058Sbde	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1002164058Sbde	switch (PRI_BASE(pp->ki_pri.pri_class)) {
1003164058Sbde	case PRI_ITHD:
1004164058Sbde		return ("-");
1005164058Sbde	case PRI_REALTIME:
1006170774Sbde		/*
1007170774Sbde		 * XXX: the kernel doesn't tell us the original rtprio and
1008170774Sbde		 * doesn't really know what it was, so to recover it we
1009170774Sbde		 * must be more chummy with the implementation than the
1010170774Sbde		 * implementation is with itself.  pri_user gives a
1011170774Sbde		 * constant "base" priority, but is only initialized
1012170774Sbde		 * properly for user threads.  pri_native gives what the
1013170774Sbde		 * kernel calls the "base" priority, but it isn't constant
1014170774Sbde		 * since it is changed by priority propagation.  pri_native
1015170774Sbde		 * also isn't properly initialized for all threads, but it
1016170774Sbde		 * is properly initialized for kernel realtime and idletime
1017170774Sbde		 * threads.  Thus we use pri_user for the base priority of
1018170774Sbde		 * user threads (it is always correct) and pri_native for
1019170774Sbde		 * the base priority of kernel realtime and idletime threads
1020170774Sbde		 * (there is nothing better, and it is usually correct).
1021170774Sbde		 *
1022170774Sbde		 * The field width and thus the buffer are too small for
1023170774Sbde		 * values like "kr31F", but such values shouldn't occur,
1024170774Sbde		 * and if they do then the tailing "F" is not displayed.
1025170774Sbde		 */
1026170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1027170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1028164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1029164058Sbde		    kthread, rtpri, fifo);
1030164058Sbde		break;
1031164058Sbde	case PRI_TIMESHARE:
1032164058Sbde		if (pp->ki_flag & P_KTHREAD)
1033164058Sbde			return ("-");
1034164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1035164058Sbde		break;
1036164058Sbde	case PRI_IDLE:
1037170774Sbde		/* XXX: as above. */
1038170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1039170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1040164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1041164058Sbde		    kthread, rtpri, fifo);
1042164058Sbde		break;
1043164058Sbde	default:
1044164058Sbde		return ("?");
1045164058Sbde	}
1046158282Sbde	return (nicebuf);
1047158282Sbde}
1048158282Sbde
104938278Swosch/* comparison routines for qsort */
105024143Sjoerg
1051158282Sbdestatic int
1052131622Sdescompare_pid(const void *p1, const void *p2)
1053131402Salfred{
1054131623Sdes	const struct kinfo_proc * const *pp1 = p1;
1055131623Sdes	const struct kinfo_proc * const *pp2 = p2;
1056131402Salfred
1057131623Sdes	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1058131623Sdes		abort();
1059131402Salfred
1060131623Sdes	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1061131402Salfred}
1062131402Salfred
1063224188Sjhbstatic int
1064224188Sjhbcompare_tid(const void *p1, const void *p2)
1065224188Sjhb{
1066224188Sjhb	const struct kinfo_proc * const *pp1 = p1;
1067224188Sjhb	const struct kinfo_proc * const *pp2 = p2;
1068224188Sjhb
1069224188Sjhb	if ((*pp2)->ki_tid < 0 || (*pp1)->ki_tid < 0)
1070224188Sjhb		abort();
1071224188Sjhb
1072224188Sjhb	return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1073224188Sjhb}
1074224188Sjhb
107524143Sjoerg/*
107624143Sjoerg *  proc_compare - comparison function for "qsort"
107724143Sjoerg *	Compares the resource consumption of two processes using five
1078131620Sdes *	distinct keys.  The keys (in descending order of importance) are:
1079131620Sdes *	percent cpu, cpu ticks, state, resident set size, total virtual
1080131620Sdes *	memory usage.  The process states are ordered as follows (from least
1081131620Sdes *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
1082131620Sdes *	array declaration below maps a process state index into a number
1083131620Sdes *	that reflects this ordering.
108424143Sjoerg */
108524143Sjoerg
1086158280Sbdestatic int sorted_state[] = {
1087131623Sdes	0,	/* not used		*/
1088131623Sdes	3,	/* sleep		*/
1089131623Sdes	1,	/* ABANDONED (WAIT)	*/
1090131623Sdes	6,	/* run			*/
1091131623Sdes	5,	/* start		*/
1092131623Sdes	2,	/* zombie		*/
1093131623Sdes	4	/* stop			*/
109424143Sjoerg};
109538278Swosch
1096131620Sdes
1097146343Skeramida#define ORDERKEY_PCTCPU(a, b) do { \
1098146343Skeramida	long diff; \
1099146343Skeramida	if (ps.wcpu) \
1100158280Sbde		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1101158280Sbde		    (b))) - \
1102158280Sbde		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1103158280Sbde		    (a))); \
1104146343Skeramida	else \
1105146343Skeramida		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1106146343Skeramida	if (diff != 0) \
1107146343Skeramida		return (diff > 0 ? 1 : -1); \
1108131626Sdes} while (0)
110938278Swosch
1110131626Sdes#define ORDERKEY_CPTICKS(a, b) do { \
1111131628Sdes	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1112131626Sdes	if (diff != 0) \
1113131626Sdes		return (diff > 0 ? 1 : -1); \
1114131626Sdes} while (0)
111538278Swosch
1116131626Sdes#define ORDERKEY_STATE(a, b) do { \
1117131626Sdes	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1118131626Sdes	if (diff != 0) \
1119131626Sdes		return (diff > 0 ? 1 : -1); \
1120131626Sdes} while (0)
112138278Swosch
1122131626Sdes#define ORDERKEY_PRIO(a, b) do { \
1123131628Sdes	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1124131626Sdes	if (diff != 0) \
1125131626Sdes		return (diff > 0 ? 1 : -1); \
1126131626Sdes} while (0)
112738278Swosch
1128145073Skeramida#define	ORDERKEY_THREADS(a, b) do { \
1129145073Skeramida	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1130145073Skeramida	if (diff != 0) \
1131145073Skeramida		return (diff > 0 ? 1 : -1); \
1132145073Skeramida} while (0)
1133145073Skeramida
1134131626Sdes#define ORDERKEY_RSSIZE(a, b) do { \
1135131628Sdes	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1136131626Sdes	if (diff != 0) \
1137131626Sdes		return (diff > 0 ? 1 : -1); \
1138131626Sdes} while (0)
113938278Swosch
1140131626Sdes#define ORDERKEY_MEM(a, b) do { \
1141131628Sdes	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1142131626Sdes	if (diff != 0) \
1143131626Sdes		return (diff > 0 ? 1 : -1); \
1144131626Sdes} while (0)
114538278Swosch
1146168799Srafan#define ORDERKEY_JID(a, b) do { \
1147168799Srafan	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1148168799Srafan	if (diff != 0) \
1149168799Srafan		return (diff > 0 ? 1 : -1); \
1150168799Srafan} while (0)
1151168799Srafan
115238278Swosch/* compare_cpu - the comparison function for sorting by cpu percentage */
115338278Swosch
115424143Sjoergint
115538278Swosch#ifdef ORDER
1156131626Sdescompare_cpu(void *arg1, void *arg2)
115738278Swosch#else
1158131626Sdesproc_compare(void *arg1, void *arg2)
115938278Swosch#endif
116024143Sjoerg{
1161131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1162131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
116324143Sjoerg
1164131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1165131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1166131626Sdes	ORDERKEY_STATE(p1, p2);
1167131626Sdes	ORDERKEY_PRIO(p1, p2);
1168131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1169131626Sdes	ORDERKEY_MEM(p1, p2);
117024143Sjoerg
1171131626Sdes	return (0);
117224143Sjoerg}
117324143Sjoerg
117438278Swosch#ifdef ORDER
1175158280Sbde/* "cpu" compare routines */
1176158280Sbdeint compare_size(), compare_res(), compare_time(), compare_prio(),
1177158280Sbde    compare_threads();
117824143Sjoerg
1179158280Sbde/*
1180158280Sbde * "io" compare routines.  Context switches aren't i/o, but are displayed
1181158280Sbde * on the "io" display.
1182158280Sbde */
1183158280Sbdeint compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1184158280Sbde    compare_vcsw(), compare_ivcsw();
1185158280Sbde
1186133817Salfredint (*compares[])() = {
1187131623Sdes	compare_cpu,
1188131623Sdes	compare_size,
1189131623Sdes	compare_res,
1190131623Sdes	compare_time,
1191131623Sdes	compare_prio,
1192145073Skeramida	compare_threads,
1193133817Salfred	compare_iototal,
1194133817Salfred	compare_ioread,
1195133817Salfred	compare_iowrite,
1196133817Salfred	compare_iofault,
1197133817Salfred	compare_vcsw,
1198133817Salfred	compare_ivcsw,
1199168799Srafan	compare_jid,
1200131623Sdes	NULL
120138278Swosch};
120238278Swosch
120338278Swosch/* compare_size - the comparison function for sorting by total memory usage */
120438278Swosch
120538278Swoschint
1206131626Sdescompare_size(void *arg1, void *arg2)
120738278Swosch{
1208131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1209131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
121038278Swosch
1211131626Sdes	ORDERKEY_MEM(p1, p2);
1212131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1213131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1214131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1215131626Sdes	ORDERKEY_STATE(p1, p2);
1216131626Sdes	ORDERKEY_PRIO(p1, p2);
121738278Swosch
1218131626Sdes	return (0);
121938278Swosch}
122038278Swosch
122138278Swosch/* compare_res - the comparison function for sorting by resident set size */
122238278Swosch
122338278Swoschint
1224131626Sdescompare_res(void *arg1, void *arg2)
122538278Swosch{
1226131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1227131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
122838278Swosch
1229131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1230131626Sdes	ORDERKEY_MEM(p1, p2);
1231131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1232131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1233131626Sdes	ORDERKEY_STATE(p1, p2);
1234131626Sdes	ORDERKEY_PRIO(p1, p2);
123538278Swosch
1236131626Sdes	return (0);
123738278Swosch}
123838278Swosch
123938278Swosch/* compare_time - the comparison function for sorting by total cpu time */
124038278Swosch
124138278Swoschint
1242131626Sdescompare_time(void *arg1, void *arg2)
1243131310Salfred{
1244131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1245131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
124638278Swosch
1247131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1248131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1249131626Sdes	ORDERKEY_STATE(p1, p2);
1250131626Sdes	ORDERKEY_PRIO(p1, p2);
1251131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1252131626Sdes	ORDERKEY_MEM(p1, p2);
125338278Swosch
1254131626Sdes	return (0);
1255131623Sdes}
1256131310Salfred
1257131626Sdes/* compare_prio - the comparison function for sorting by priority */
125838278Swosch
125938278Swoschint
1260131626Sdescompare_prio(void *arg1, void *arg2)
126138278Swosch{
1262131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1263131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
126438278Swosch
1265131626Sdes	ORDERKEY_PRIO(p1, p2);
1266131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1267131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1268131626Sdes	ORDERKEY_STATE(p1, p2);
1269131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1270131626Sdes	ORDERKEY_MEM(p1, p2);
127138278Swosch
1272131626Sdes	return (0);
127338278Swosch}
1274145073Skeramida
1275145073Skeramida/* compare_threads - the comparison function for sorting by threads */
1276145073Skeramidaint
1277145073Skeramidacompare_threads(void *arg1, void *arg2)
1278145073Skeramida{
1279145073Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1280145073Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1281145073Skeramida
1282145073Skeramida	ORDERKEY_THREADS(p1, p2);
1283145073Skeramida	ORDERKEY_PCTCPU(p1, p2);
1284145073Skeramida	ORDERKEY_CPTICKS(p1, p2);
1285145073Skeramida	ORDERKEY_STATE(p1, p2);
1286145073Skeramida	ORDERKEY_PRIO(p1, p2);
1287145073Skeramida	ORDERKEY_RSSIZE(p1, p2);
1288145073Skeramida	ORDERKEY_MEM(p1, p2);
1289145073Skeramida
1290145073Skeramida	return (0);
1291145073Skeramida}
1292168799Srafan
1293168799Srafan/* compare_jid - the comparison function for sorting by jid */
1294168799Srafanstatic int
1295168799Srafancompare_jid(const void *arg1, const void *arg2)
1296168799Srafan{
1297168799Srafan	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1298168799Srafan	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1299168799Srafan
1300168799Srafan	ORDERKEY_JID(p1, p2);
1301168799Srafan	ORDERKEY_PCTCPU(p1, p2);
1302168799Srafan	ORDERKEY_CPTICKS(p1, p2);
1303168799Srafan	ORDERKEY_STATE(p1, p2);
1304168799Srafan	ORDERKEY_PRIO(p1, p2);
1305168799Srafan	ORDERKEY_RSSIZE(p1, p2);
1306168799Srafan	ORDERKEY_MEM(p1, p2);
1307168799Srafan
1308168799Srafan	return (0);
1309168799Srafan}
1310158280Sbde#endif /* ORDER */
131138278Swosch
1312158280Sbde/* assorted comparison functions for sorting by i/o */
1313131829Skeramida
1314131402Salfredint
1315131829Skeramida#ifdef ORDER
1316131829Skeramidacompare_iototal(void *arg1, void *arg2)
1317131829Skeramida#else
1318131626Sdesio_compare(void *arg1, void *arg2)
1319131829Skeramida#endif
1320131402Salfred{
1321131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1322131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1323131402Salfred
1324131626Sdes	return (get_io_total(p2) - get_io_total(p1));
1325131402Salfred}
1326131829Skeramida
1327131829Skeramida#ifdef ORDER
1328131829Skeramidaint
1329131829Skeramidacompare_ioread(void *arg1, void *arg2)
1330131829Skeramida{
1331131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1332131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1333131829Skeramida	long dummy, inp1, inp2;
1334131829Skeramida
1335133817Salfred	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1336133817Salfred	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1337131829Skeramida
1338131829Skeramida	return (inp2 - inp1);
1339131829Skeramida}
1340131829Skeramida
1341131829Skeramidaint
1342131829Skeramidacompare_iowrite(void *arg1, void *arg2)
1343131829Skeramida{
1344131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1345131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1346131829Skeramida	long dummy, oup1, oup2;
1347131829Skeramida
1348133817Salfred	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1349133817Salfred	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1350131829Skeramida
1351131829Skeramida	return (oup2 - oup1);
1352131829Skeramida}
1353131829Skeramida
1354131829Skeramidaint
1355131829Skeramidacompare_iofault(void *arg1, void *arg2)
1356131829Skeramida{
1357131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1358131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1359131829Skeramida	long dummy, flp1, flp2;
1360131829Skeramida
1361133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1362133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1363131829Skeramida
1364131829Skeramida	return (flp2 - flp1);
1365131829Skeramida}
1366131829Skeramida
1367133817Salfredint
1368133817Salfredcompare_vcsw(void *arg1, void *arg2)
1369133817Salfred{
1370133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1371133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1372133817Salfred	long dummy, flp1, flp2;
1373133817Salfred
1374133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1375133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1376133817Salfred
1377133817Salfred	return (flp2 - flp1);
1378133817Salfred}
1379133817Salfred
1380133817Salfredint
1381133817Salfredcompare_ivcsw(void *arg1, void *arg2)
1382133817Salfred{
1383133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1384133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1385133817Salfred	long dummy, flp1, flp2;
1386133817Salfred
1387133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1388133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1389133817Salfred
1390133817Salfred	return (flp2 - flp1);
1391133817Salfred}
1392131829Skeramida#endif /* ORDER */
1393131829Skeramida
139424143Sjoerg/*
139524143Sjoerg * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
139624143Sjoerg *		the process does not exist.
139724143Sjoerg *		It is EXTREMLY IMPORTANT that this function work correctly.
139824143Sjoerg *		If top runs setuid root (as in SVR4), then this function
139924143Sjoerg *		is the only thing that stands in the way of a serious
140024143Sjoerg *		security problem.  It validates requests for the "kill"
140124143Sjoerg *		and "renice" commands.
140224143Sjoerg */
140324143Sjoerg
1404131310Salfredint
1405131622Sdesproc_owner(int pid)
140624143Sjoerg{
1407131623Sdes	int cnt;
1408131623Sdes	struct kinfo_proc **prefp;
1409131623Sdes	struct kinfo_proc *pp;
141024143Sjoerg
1411131623Sdes	prefp = pref;
1412131623Sdes	cnt = pref_len;
1413131626Sdes	while (--cnt >= 0) {
1414131623Sdes		pp = *prefp++;
1415131623Sdes		if (pp->ki_pid == (pid_t)pid)
1416131623Sdes			return ((int)pp->ki_ruid);
141724143Sjoerg	}
1418131623Sdes	return (-1);
141924143Sjoerg}
142024143Sjoerg
1421158282Sbdestatic int
1422131622Sdesswapmode(int *retavail, int *retfree)
142324143Sjoerg{
142443053Sdillon	int n;
142543053Sdillon	int pagesize = getpagesize();
142643053Sdillon	struct kvm_swap swapary[1];
142724143Sjoerg
142843053Sdillon	*retavail = 0;
142943053Sdillon	*retfree = 0;
143024143Sjoerg
143143053Sdillon#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
143224143Sjoerg
143343053Sdillon	n = kvm_getswapinfo(kd, swapary, 1, 0);
143443697Sdillon	if (n < 0 || swapary[0].ksw_total == 0)
1435131623Sdes		return (0);
143624143Sjoerg
143743053Sdillon	*retavail = CONVERT(swapary[0].ksw_total);
143843053Sdillon	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
143924143Sjoerg
1440131626Sdes	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1441131623Sdes	return (n);
144243053Sdillon}
1443