machine.c revision 175420
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 175420 2008-01-18 01:43:14Z peter $
2424143Sjoerg */
2524143Sjoerg
2624143Sjoerg#include <sys/param.h>
2724143Sjoerg#include <sys/errno.h>
28131621Sdes#include <sys/file.h>
29131621Sdes#include <sys/proc.h>
30131621Sdes#include <sys/resource.h>
31131621Sdes#include <sys/rtprio.h>
32131621Sdes#include <sys/signal.h>
3324143Sjoerg#include <sys/sysctl.h>
3424143Sjoerg#include <sys/time.h>
3524143Sjoerg#include <sys/user.h>
3624143Sjoerg#include <sys/vmmeter.h>
3724143Sjoerg
38131621Sdes#include <kvm.h>
39131621Sdes#include <math.h>
40131621Sdes#include <nlist.h>
41131626Sdes#include <paths.h>
42131621Sdes#include <pwd.h>
43131621Sdes#include <stdio.h>
4424143Sjoerg#include <stdlib.h>
45144636Sstefanf#include <string.h>
46144636Sstefanf#include <strings.h>
4772951Srwatson#include <unistd.h>
48168710Sstas#include <vis.h>
4924143Sjoerg
5024143Sjoerg#include "top.h"
5124143Sjoerg#include "machine.h"
5269375Sjhb#include "screen.h"
5372951Srwatson#include "utils.h"
54175420Speter#include "layout.h"
5524143Sjoerg
5672951Srwatson#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
57146291Sobrien#define	SMPUNAMELEN	13
58146291Sobrien#define	UPUNAMELEN	15
5972951Srwatson
60145073Skeramidaextern struct process_select ps;
6192922Simpextern char* printable(char *);
6227340Speterstatic int smpmode;
63131402Salfredenum displaymodes displaymode;
64175195Sobrien#ifdef TOP_USERNAME_LEN
65175195Sobrienstatic int namelength = TOP_USERNAME_LEN;
66175195Sobrien#else
67146291Sobrienstatic int namelength = 8;
68175195Sobrien#endif
6969375Sjhbstatic int cmdlengthdelta;
7024143Sjoerg
7172951Srwatson/* Prototypes for top internals */
7292922Simpvoid quit(int);
7324143Sjoerg
7424143Sjoerg/* get_process_info passes back a handle.  This is what it looks like: */
7524143Sjoerg
76158280Sbdestruct handle {
77131623Sdes	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
78131623Sdes	int remaining;			/* number of pointers remaining */
7924143Sjoerg};
8024143Sjoerg
8124143Sjoerg/* declarations for load_avg */
8224143Sjoerg#include "loadavg.h"
8324143Sjoerg
8424143Sjoerg/* define what weighted cpu is.  */
8569896Smckusick#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
8669896Smckusick			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
8724143Sjoerg
8824143Sjoerg/* what we consider to be process size: */
8969896Smckusick#define PROCSIZE(pp) ((pp)->ki_size / 1024)
9024143Sjoerg
91131402Salfred#define RU(pp)	(&(pp)->ki_rusage)
92131402Salfred#define RUTOT(pp) \
93131402Salfred	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
94131402Salfred
95131402Salfred
9624143Sjoerg/* definitions for indices in the nlist array */
9724143Sjoerg
9824143Sjoerg/*
9924143Sjoerg *  These definitions control the format of the per-process area
10024143Sjoerg */
10124143Sjoerg
102131402Salfredstatic char io_header[] =
103168799Srafan    "  PID%s %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
104131402Salfred
105131402Salfred#define io_Proc_format \
106168799Srafan    "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
107131402Salfred
108145073Skeramidastatic char smp_header_thr[] =
109168799Srafan    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
11027340Speterstatic char smp_header[] =
111168799Srafan    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
11224143Sjoerg
11327340Speter#define smp_Proc_format \
114168799Srafan    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
11524143Sjoerg
116145073Skeramidastatic char up_header_thr[] =
117168799Srafan    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
11827340Speterstatic char up_header[] =
119168799Srafan    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
12024143Sjoerg
12127340Speter#define up_Proc_format \
122168799Srafan    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
12324143Sjoerg
12424143Sjoerg
12524143Sjoerg/* process state names for the "STATE" column of the display */
12624143Sjoerg/* the extra nulls in the string "run" are for adding a slash and
12724143Sjoerg   the processor number when needed */
12824143Sjoerg
129158280Sbdechar *state_abbrev[] = {
130131623Sdes	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
13124143Sjoerg};
13224143Sjoerg
13324143Sjoerg
13424143Sjoergstatic kvm_t *kd;
13524143Sjoerg
13624143Sjoerg/* values that we stash away in _init and use in later routines */
13724143Sjoerg
13824143Sjoergstatic double logcpu;
13924143Sjoerg
14024143Sjoerg/* these are retrieved from the kernel in _init */
14124143Sjoerg
14224143Sjoergstatic load_avg  ccpu;
14324143Sjoerg
14472951Srwatson/* these are used in the get_ functions */
14524143Sjoerg
14672951Srwatsonstatic int lastpid;
14724143Sjoerg
14824143Sjoerg/* these are for calculating cpu state percentages */
14924143Sjoerg
15024143Sjoergstatic long cp_time[CPUSTATES];
15124143Sjoergstatic long cp_old[CPUSTATES];
15224143Sjoergstatic long cp_diff[CPUSTATES];
15324143Sjoerg
15424143Sjoerg/* these are for detailing the process states */
15524143Sjoerg
15665557Sjasoneint process_states[8];
15724143Sjoergchar *procstatenames[] = {
158131623Sdes	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
159131623Sdes	" zombie, ", " waiting, ", " lock, ",
160131623Sdes	NULL
16124143Sjoerg};
16224143Sjoerg
16324143Sjoerg/* these are for detailing the cpu states */
16424143Sjoerg
16524143Sjoergint cpu_states[CPUSTATES];
16624143Sjoergchar *cpustatenames[] = {
167131623Sdes	"user", "nice", "system", "interrupt", "idle", NULL
16824143Sjoerg};
16924143Sjoerg
17024143Sjoerg/* these are for detailing the memory statistics */
17124143Sjoerg
17224143Sjoergint memory_stats[7];
17324143Sjoergchar *memorynames[] = {
174158280Sbde	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
175158280Sbde	"K Free", NULL
17624143Sjoerg};
17724143Sjoerg
17824143Sjoergint swap_stats[7];
17924143Sjoergchar *swapnames[] = {
180131623Sdes	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
181131623Sdes	NULL
18224143Sjoerg};
18324143Sjoerg
18424143Sjoerg
18524143Sjoerg/* these are for keeping track of the proc array */
18624143Sjoerg
18724143Sjoergstatic int nproc;
18824143Sjoergstatic int onproc = -1;
18924143Sjoergstatic int pref_len;
19024143Sjoergstatic struct kinfo_proc *pbase;
19124143Sjoergstatic struct kinfo_proc **pref;
192131402Salfredstatic struct kinfo_proc *previous_procs;
193131402Salfredstatic struct kinfo_proc **previous_pref;
194131402Salfredstatic int previous_proc_count = 0;
195131402Salfredstatic int previous_proc_count_max = 0;
19624143Sjoerg
197131412Salfred/* total number of io operations */
198131412Salfredstatic long total_inblock;
199131412Salfredstatic long total_oublock;
200131412Salfredstatic long total_majflt;
201131412Salfred
20224143Sjoerg/* these are for getting the memory statistics */
20324143Sjoerg
20424143Sjoergstatic int pageshift;		/* log base 2 of the pagesize */
20524143Sjoerg
20624143Sjoerg/* define pagetok in terms of pageshift */
20724143Sjoerg
20824143Sjoerg#define pagetok(size) ((size) << pageshift)
20924143Sjoerg
21024143Sjoerg/* useful externals */
21124143Sjoerglong percentages();
21224143Sjoerg
21338278Swosch#ifdef ORDER
214131829Skeramida/*
215145073Skeramida * Sorting orders.  The first element is the default.
216131829Skeramida */
217133817Salfredchar *ordernames[] = {
218145073Skeramida	"cpu", "size", "res", "time", "pri", "threads",
219168799Srafan	"total", "read", "write", "fault", "vcsw", "ivcsw",
220168799Srafan	"jid", NULL
22138278Swosch};
22238278Swosch#endif
22338278Swosch
224175420Speter/* Per-cpu time states */
225175420Speterstatic int maxcpu;
226175420Speterstatic int maxid;
227175420Speterstatic int ncpus;
228175420Speterstatic u_long cpumask;
229175420Speterstatic long *times;
230175420Speterstatic long *pcpu_cp_time;
231175420Speterstatic long *pcpu_cp_old;
232175420Speterstatic long *pcpu_cp_diff;
233175420Speterstatic int *pcpu_cpu_states;
234175420Speter
235168799Srafanstatic int compare_jid(const void *a, const void *b);
236158282Sbdestatic int compare_pid(const void *a, const void *b);
237158282Sbdestatic const char *format_nice(const struct kinfo_proc *pp);
238158282Sbdestatic void getsysctl(const char *name, void *ptr, size_t len);
239158282Sbdestatic int swapmode(int *retavail, int *retfree);
240158282Sbde
24124143Sjoergint
242175195Sobrienmachine_init(struct statics *statics, char do_unames)
24324143Sjoerg{
244131623Sdes	int pagesize;
245131623Sdes	size_t modelen;
246131623Sdes	struct passwd *pw;
24724143Sjoerg
248131623Sdes	modelen = sizeof(smpmode);
249158280Sbde	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
250158280Sbde	    NULL, 0) != 0 &&
251158280Sbde	    sysctlbyname("kern.smp.active", &smpmode, &modelen,
252158280Sbde	    NULL, 0) != 0) ||
253131623Sdes	    modelen != sizeof(smpmode))
254131623Sdes		smpmode = 0;
25527340Speter
256175195Sobrien	if (do_unames) {
257175195Sobrien	    while ((pw = getpwent()) != NULL) {
258131623Sdes		if (strlen(pw->pw_name) > namelength)
259131623Sdes			namelength = strlen(pw->pw_name);
260175195Sobrien	    }
261131623Sdes	}
262146291Sobrien	if (smpmode && namelength > SMPUNAMELEN)
263146291Sobrien		namelength = SMPUNAMELEN;
264146291Sobrien	else if (namelength > UPUNAMELEN)
265146291Sobrien		namelength = UPUNAMELEN;
26627390Speter
267131626Sdes	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
268131626Sdes	if (kd == NULL)
269131626Sdes		return (-1);
27024143Sjoerg
271131623Sdes	GETSYSCTL("kern.ccpu", ccpu);
27224143Sjoerg
273131623Sdes	/* this is used in calculating WCPU -- calculate it ahead of time */
274131623Sdes	logcpu = log(loaddouble(ccpu));
27524143Sjoerg
276131623Sdes	pbase = NULL;
277131623Sdes	pref = NULL;
278131623Sdes	nproc = 0;
279131623Sdes	onproc = -1;
280158280Sbde
281158280Sbde	/* get the page size and calculate pageshift from it */
282131623Sdes	pagesize = getpagesize();
283131623Sdes	pageshift = 0;
284131626Sdes	while (pagesize > 1) {
285131623Sdes		pageshift++;
286131623Sdes		pagesize >>= 1;
287131623Sdes	}
28824143Sjoerg
289131623Sdes	/* we only need the amount of log(2)1024 for our conversion */
290131623Sdes	pageshift -= LOG1024;
29124143Sjoerg
292131623Sdes	/* fill in the statics information */
293131623Sdes	statics->procstate_names = procstatenames;
294131623Sdes	statics->cpustate_names = cpustatenames;
295131623Sdes	statics->memory_names = memorynames;
296131623Sdes	statics->swap_names = swapnames;
29738278Swosch#ifdef ORDER
298133817Salfred	statics->order_names = ordernames;
29938278Swosch#endif
30024143Sjoerg
301175420Speter	/* Adjust display based on ncpus */
302175420Speter	if (pcpu_stats) {
303175420Speter		int i, j, empty;
304175420Speter		size_t size;
305175420Speter
306175420Speter		cpumask = 0;
307175420Speter		ncpus = 0;
308175420Speter		GETSYSCTL("kern.smp.maxcpus", maxcpu);
309175420Speter		size = sizeof(long) * maxcpu * CPUSTATES;
310175420Speter		times = malloc(size);
311175420Speter		if (times == NULL)
312175420Speter			err(1, "malloc %zd bytes", size);
313175420Speter		if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
314175420Speter			err(1, "sysctlbyname kern.cp_times");
315175420Speter		maxid = (size / CPUSTATES / sizeof(long)) - 1;
316175420Speter		for (i = 0; i <= maxid; i++) {
317175420Speter			empty = 1;
318175420Speter			for (j = 0; empty && j < CPUSTATES; j++) {
319175420Speter				if (times[i * CPUSTATES + j] != 0)
320175420Speter					empty = 0;
321175420Speter			}
322175420Speter			if (!empty) {
323175420Speter				cpumask |= (1ul << i);
324175420Speter				ncpus++;
325175420Speter			}
326175420Speter		}
327175420Speter
328175420Speter		if (ncpus > 1) {
329175420Speter			y_mem += ncpus - 1;	/* 3 */
330175420Speter			y_swap += ncpus - 1;	/* 4 */
331175420Speter			y_idlecursor += ncpus - 1; /* 5 */
332175420Speter			y_message += ncpus - 1;	/* 5 */
333175420Speter			y_header += ncpus - 1;	/* 6 */
334175420Speter			y_procs += ncpus - 1;	/* 7 */
335175420Speter			Header_lines += ncpus - 1; /* 7 */
336175420Speter		}
337175420Speter		size = sizeof(long) * ncpus * CPUSTATES;
338175420Speter		pcpu_cp_time = malloc(size);
339175420Speter		pcpu_cp_old = malloc(size);
340175420Speter		pcpu_cp_diff = malloc(size);
341175420Speter		pcpu_cpu_states = malloc(size);
342175420Speter		bzero(pcpu_cp_time, size);
343175420Speter		bzero(pcpu_cp_old, size);
344175420Speter		bzero(pcpu_cp_diff, size);
345175420Speter		bzero(pcpu_cpu_states, size);
346175420Speter		statics->ncpus = ncpus;
347175420Speter	} else {
348175420Speter		statics->ncpus = 1;
349175420Speter	}
350175420Speter
351131623Sdes	/* all done! */
352131623Sdes	return (0);
35324143Sjoerg}
35424143Sjoerg
355131310Salfredchar *
356131622Sdesformat_header(char *uname_field)
35724143Sjoerg{
358131623Sdes	static char Header[128];
359131623Sdes	const char *prehead;
36024143Sjoerg
361131623Sdes	switch (displaymode) {
362131623Sdes	case DISP_CPU:
363145073Skeramida		/*
364145073Skeramida		 * The logic of picking the right header format seems reverse
365145073Skeramida		 * here because we only want to display a THR column when
366145073Skeramida		 * "thread mode" is off (and threads are not listed as
367145073Skeramida		 * separate lines).
368145073Skeramida		 */
369145073Skeramida		prehead = smpmode ?
370145073Skeramida		    (ps.thread ? smp_header : smp_header_thr) :
371145073Skeramida		    (ps.thread ? up_header : up_header_thr);
372146342Skeramida		snprintf(Header, sizeof(Header), prehead,
373168799Srafan		    ps.jail ? " JID" : "",
374146342Skeramida		    namelength, namelength, uname_field,
375146342Skeramida		    ps.wcpu ? "WCPU" : "CPU");
376131623Sdes		break;
377131623Sdes	case DISP_IO:
378131623Sdes		prehead = io_header;
379146342Skeramida		snprintf(Header, sizeof(Header), prehead,
380168799Srafan		    ps.jail ? " JID" : "",
381146342Skeramida		    namelength, namelength, uname_field);
382131623Sdes		break;
383131623Sdes	}
384131623Sdes	cmdlengthdelta = strlen(Header) - 7;
385131623Sdes	return (Header);
38624143Sjoerg}
38724143Sjoerg
38824143Sjoergstatic int swappgsin = -1;
38924143Sjoergstatic int swappgsout = -1;
39024143Sjoergextern struct timeval timeout;
39124143Sjoerg
392175420Speter
39324143Sjoergvoid
394131622Sdesget_system_info(struct system_info *si)
39524143Sjoerg{
396131623Sdes	long total;
397131623Sdes	struct loadavg sysload;
398131623Sdes	int mib[2];
399131623Sdes	struct timeval boottime;
400131623Sdes	size_t bt_size;
401175420Speter	int i, j;
402175420Speter	size_t size;
40324143Sjoerg
404131623Sdes	/* get the cp_time array */
405175420Speter	if (pcpu_stats) {
406175420Speter		size = (maxid + 1) * CPUSTATES * sizeof(long);
407175420Speter		if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
408175420Speter			err(1, "sysctlbyname kern.cp_times");
409175420Speter	} else {
410175420Speter		GETSYSCTL("kern.cp_time", cp_time);
411175420Speter	}
412131623Sdes	GETSYSCTL("vm.loadavg", sysload);
413131623Sdes	GETSYSCTL("kern.lastpid", lastpid);
41424143Sjoerg
415131623Sdes	/* convert load averages to doubles */
416131626Sdes	for (i = 0; i < 3; i++)
417131626Sdes		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
41824143Sjoerg
419175420Speter	if (pcpu_stats) {
420175420Speter		for (i = j = 0; i <= maxid; i++, j++) {
421175420Speter			if (cpumask && (1ul << i) == 0)
422175420Speter				continue;
423175420Speter			/* convert cp_time counts to percentages */
424175420Speter			percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
425175420Speter			    &pcpu_cp_time[j * CPUSTATES],
426175420Speter			    &pcpu_cp_old[j * CPUSTATES],
427175420Speter			    &pcpu_cp_diff[j * CPUSTATES]);
428175420Speter		}
429175420Speter	} else {
430175420Speter		/* convert cp_time counts to percentages */
431175420Speter		percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
432175420Speter	}
43324143Sjoerg
434131623Sdes	/* sum memory & swap statistics */
435131623Sdes	{
436131623Sdes		static unsigned int swap_delay = 0;
437131623Sdes		static int swapavail = 0;
438131623Sdes		static int swapfree = 0;
439131623Sdes		static int bufspace = 0;
440131623Sdes		static int nspgsin, nspgsout;
44124143Sjoerg
442131623Sdes		GETSYSCTL("vfs.bufspace", bufspace);
443131623Sdes		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
444131623Sdes		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
445131623Sdes		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
446131623Sdes		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
447131623Sdes		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
448131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
449131623Sdes		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
450131623Sdes		/* convert memory stats to Kbytes */
451131623Sdes		memory_stats[0] = pagetok(memory_stats[0]);
452131623Sdes		memory_stats[1] = pagetok(memory_stats[1]);
453131623Sdes		memory_stats[2] = pagetok(memory_stats[2]);
454131623Sdes		memory_stats[3] = pagetok(memory_stats[3]);
455131623Sdes		memory_stats[4] = bufspace / 1024;
456131623Sdes		memory_stats[5] = pagetok(memory_stats[5]);
457131623Sdes		memory_stats[6] = -1;
45824143Sjoerg
459131623Sdes		/* first interval */
460131623Sdes		if (swappgsin < 0) {
461131623Sdes			swap_stats[4] = 0;
462131623Sdes			swap_stats[5] = 0;
463131623Sdes		}
46424143Sjoerg
465131623Sdes		/* compute differences between old and new swap statistic */
466131623Sdes		else {
467131623Sdes			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
468131623Sdes			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
469131623Sdes		}
47024143Sjoerg
471131623Sdes		swappgsin = nspgsin;
472131623Sdes		swappgsout = nspgsout;
47324143Sjoerg
474131623Sdes		/* call CPU heavy swapmode() only for changes */
475131623Sdes		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
476131623Sdes			swap_stats[3] = swapmode(&swapavail, &swapfree);
477131623Sdes			swap_stats[0] = swapavail;
478131623Sdes			swap_stats[1] = swapavail - swapfree;
479131623Sdes			swap_stats[2] = swapfree;
480131623Sdes		}
481131623Sdes		swap_delay = 1;
482131623Sdes		swap_stats[6] = -1;
48324143Sjoerg	}
48424143Sjoerg
485131623Sdes	/* set arrays and strings */
486175420Speter	if (pcpu_stats) {
487175420Speter		si->cpustates = pcpu_cpu_states;
488175420Speter		si->cpumask = cpumask;
489175420Speter		si->ncpus = ncpus;
490175420Speter	} else {
491175420Speter		si->cpustates = cpu_states;
492175420Speter		si->cpumask = 1;
493175420Speter		si->ncpus = 1;
494175420Speter	}
495131623Sdes	si->memory = memory_stats;
496131623Sdes	si->swap = swap_stats;
49724143Sjoerg
49824143Sjoerg
499131623Sdes	if (lastpid > 0) {
500131623Sdes		si->last_pid = lastpid;
501131623Sdes	} else {
502131623Sdes		si->last_pid = -1;
503131623Sdes	}
50442447Sobrien
505131623Sdes	/*
506131623Sdes	 * Print how long system has been up.
507131623Sdes	 * (Found by looking getting "boottime" from the kernel)
508131623Sdes	 */
509131623Sdes	mib[0] = CTL_KERN;
510131623Sdes	mib[1] = KERN_BOOTTIME;
511131623Sdes	bt_size = sizeof(boottime);
512131623Sdes	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
513131623Sdes	    boottime.tv_sec != 0) {
514131623Sdes		si->boottime = boottime;
515131623Sdes	} else {
516131623Sdes		si->boottime.tv_sec = -1;
517131623Sdes	}
51824143Sjoerg}
51924143Sjoerg
520132015Salfred#define NOPROC	((void *)-1)
521132015Salfred
522132955Salfred/*
523132955Salfred * We need to compare data from the old process entry with the new
524132955Salfred * process entry.
525132955Salfred * To facilitate doing this quickly we stash a pointer in the kinfo_proc
526132955Salfred * structure to cache the mapping.  We also use a negative cache pointer
527132955Salfred * of NOPROC to avoid duplicate lookups.
528132955Salfred * XXX: this could be done when the actual processes are fetched, we do
529132955Salfred * it here out of laziness.
530132955Salfred */
531131402Salfredconst struct kinfo_proc *
532131402Salfredget_old_proc(struct kinfo_proc *pp)
533131402Salfred{
534131402Salfred	struct kinfo_proc **oldpp, *oldp;
535131402Salfred
536132955Salfred	/*
537132955Salfred	 * If this is the first fetch of the kinfo_procs then we don't have
538132955Salfred	 * any previous entries.
539132955Salfred	 */
540131402Salfred	if (previous_proc_count == 0)
541131402Salfred		return (NULL);
542132955Salfred	/* negative cache? */
543132015Salfred	if (pp->ki_udata == NOPROC)
544132015Salfred		return (NULL);
545132955Salfred	/* cached? */
546132015Salfred	if (pp->ki_udata != NULL)
547132015Salfred		return (pp->ki_udata);
548132955Salfred	/*
549132955Salfred	 * Not cached,
550132955Salfred	 * 1) look up based on pid.
551132955Salfred	 * 2) compare process start.
552132955Salfred	 * If we fail here, then setup a negative cache entry, otherwise
553132955Salfred	 * cache it.
554132955Salfred	 */
555131402Salfred	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
556131626Sdes	    sizeof(*previous_pref), compare_pid);
557132015Salfred	if (oldpp == NULL) {
558132015Salfred		pp->ki_udata = NOPROC;
559131402Salfred		return (NULL);
560132015Salfred	}
561131402Salfred	oldp = *oldpp;
562132015Salfred	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
563132015Salfred		pp->ki_udata = NOPROC;
564131402Salfred		return (NULL);
565132015Salfred	}
566132015Salfred	pp->ki_udata = oldp;
567131402Salfred	return (oldp);
568131402Salfred}
569131402Salfred
570132955Salfred/*
571132955Salfred * Return the total amount of IO done in blocks in/out and faults.
572132955Salfred * store the values individually in the pointers passed in.
573132955Salfred */
574131402Salfredlong
575158280Sbdeget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
576158280Sbde    long *vcsw, long *ivcsw)
577131402Salfred{
578131402Salfred	const struct kinfo_proc *oldp;
579131402Salfred	static struct kinfo_proc dummy;
580131402Salfred	long ret;
581131402Salfred
582131402Salfred	oldp = get_old_proc(pp);
583131402Salfred	if (oldp == NULL) {
584131402Salfred		bzero(&dummy, sizeof(dummy));
585131402Salfred		oldp = &dummy;
586131402Salfred	}
587131412Salfred	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
588131412Salfred	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
589131412Salfred	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
590133817Salfred	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
591133817Salfred	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
592131402Salfred	ret =
593131402Salfred	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
594131402Salfred	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
595131402Salfred	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
596131402Salfred	return (ret);
597131402Salfred}
598131402Salfred
599132955Salfred/*
600132955Salfred * Return the total number of block in/out and faults by a process.
601132955Salfred */
602131412Salfredlong
603131412Salfredget_io_total(struct kinfo_proc *pp)
604131412Salfred{
605131412Salfred	long dummy;
606131412Salfred
607133817Salfred	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
608131412Salfred}
609131412Salfred
61024143Sjoergstatic struct handle handle;
61124143Sjoerg
612131310Salfredcaddr_t
613131622Sdesget_process_info(struct system_info *si, struct process_select *sel,
614131626Sdes    int (*compare)(const void *, const void *))
61524143Sjoerg{
616131623Sdes	int i;
617131623Sdes	int total_procs;
618131623Sdes	long p_io;
619133817Salfred	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
620131623Sdes	int active_procs;
621131623Sdes	struct kinfo_proc **prefp;
622131623Sdes	struct kinfo_proc *pp;
623131623Sdes	struct kinfo_proc *prev_pp = NULL;
62424143Sjoerg
625131623Sdes	/* these are copied out of sel for speed */
626131623Sdes	int show_idle;
627131623Sdes	int show_self;
628131623Sdes	int show_system;
629131623Sdes	int show_uid;
630131623Sdes	int show_command;
63124143Sjoerg
632131623Sdes	/*
633131623Sdes	 * Save the previous process info.
634131623Sdes	 */
635131623Sdes	if (previous_proc_count_max < nproc) {
636131623Sdes		free(previous_procs);
637131626Sdes		previous_procs = malloc(nproc * sizeof(*previous_procs));
638131623Sdes		free(previous_pref);
639131626Sdes		previous_pref = malloc(nproc * sizeof(*previous_pref));
640131623Sdes		if (previous_procs == NULL || previous_pref == NULL) {
641131623Sdes			(void) fprintf(stderr, "top: Out of memory.\n");
642131623Sdes			quit(23);
643131623Sdes		}
644131623Sdes		previous_proc_count_max = nproc;
645131623Sdes	}
646131623Sdes	if (nproc) {
647131623Sdes		for (i = 0; i < nproc; i++)
648131623Sdes			previous_pref[i] = &previous_procs[i];
649131626Sdes		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
650158280Sbde		qsort(previous_pref, nproc, sizeof(*previous_pref),
651158280Sbde		    compare_pid);
652131623Sdes	}
653131623Sdes	previous_proc_count = nproc;
654131402Salfred
655131623Sdes	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
656131623Sdes	if (nproc > onproc)
657131626Sdes		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
658131623Sdes	if (pref == NULL || pbase == NULL) {
659131623Sdes		(void) fprintf(stderr, "top: Out of memory.\n");
660131623Sdes		quit(23);
661131623Sdes	}
662131623Sdes	/* get a pointer to the states summary array */
663131623Sdes	si->procstates = process_states;
66424143Sjoerg
665131623Sdes	/* set up flags which define what we are going to select */
666131623Sdes	show_idle = sel->idle;
667132024Sdes	show_self = sel->self == -1;
668131623Sdes	show_system = sel->system;
669131623Sdes	show_uid = sel->uid != -1;
670131623Sdes	show_command = sel->command != NULL;
67124143Sjoerg
672131623Sdes	/* count up process states and get pointers to interesting procs */
673131623Sdes	total_procs = 0;
674131623Sdes	active_procs = 0;
675131623Sdes	total_inblock = 0;
676131623Sdes	total_oublock = 0;
677131623Sdes	total_majflt = 0;
678131623Sdes	memset((char *)process_states, 0, sizeof(process_states));
679131623Sdes	prefp = pref;
680131626Sdes	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
681131619Sdes
682131623Sdes		if (pp->ki_stat == 0)
683132024Sdes			/* not in use */
684132024Sdes			continue;
685131619Sdes
686131623Sdes		if (!show_self && pp->ki_pid == sel->self)
687131623Sdes			/* skip self */
688131623Sdes			continue;
689131619Sdes
690131623Sdes		if (!show_system && (pp->ki_flag & P_SYSTEM))
691131623Sdes			/* skip system process */
692131623Sdes			continue;
693131619Sdes
694158280Sbde		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
695158280Sbde		    &p_vcsw, &p_ivcsw);
696131623Sdes		total_inblock += p_inblock;
697131623Sdes		total_oublock += p_oublock;
698131623Sdes		total_majflt += p_majflt;
699131623Sdes		total_procs++;
700131626Sdes		process_states[pp->ki_stat]++;
701131619Sdes
702131623Sdes		if (pp->ki_stat == SZOMB)
703131623Sdes			/* skip zombies */
704131623Sdes			continue;
705131619Sdes
706131623Sdes		if (displaymode == DISP_CPU && !show_idle &&
707159520Sse		    (pp->ki_pctcpu == 0 ||
708159520Sse		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
709131623Sdes			/* skip idle or non-running processes */
710131623Sdes			continue;
711131619Sdes
712131623Sdes		if (displaymode == DISP_IO && !show_idle && p_io == 0)
713131623Sdes			/* skip processes that aren't doing I/O */
714131623Sdes			continue;
715131619Sdes
716131623Sdes		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
717158280Sbde			/* skip proc. that don't belong to the selected UID */
718131623Sdes			continue;
719131619Sdes
720131623Sdes		/*
721131623Sdes		 * When not showing threads, take the first thread
722131623Sdes		 * for output and add the fields that we can from
723131623Sdes		 * the rest of the process's threads rather than
724131623Sdes		 * using the system's mostly-broken KERN_PROC_PROC.
725131623Sdes		 */
726131626Sdes		if (sel->thread || prev_pp == NULL ||
727131626Sdes		    prev_pp->ki_pid != pp->ki_pid) {
728131623Sdes			*prefp++ = pp;
729131623Sdes			active_procs++;
730131623Sdes			prev_pp = pp;
731131623Sdes		} else {
732131623Sdes			prev_pp->ki_pctcpu += pp->ki_pctcpu;
733131623Sdes		}
734131623Sdes	}
735131623Sdes
736131623Sdes	/* if requested, sort the "interesting" processes */
737131623Sdes	if (compare != NULL)
738131626Sdes		qsort(pref, active_procs, sizeof(*pref), compare);
73924143Sjoerg
740131623Sdes	/* remember active and total counts */
741131623Sdes	si->p_total = total_procs;
742131623Sdes	si->p_active = pref_len = active_procs;
74324143Sjoerg
744131623Sdes	/* pass back a handle */
745131623Sdes	handle.next_proc = pref;
746131623Sdes	handle.remaining = active_procs;
747131623Sdes	return ((caddr_t)&handle);
74824143Sjoerg}
74924143Sjoerg
750131626Sdesstatic char fmt[128];	/* static area where result is built */
75124143Sjoerg
752131310Salfredchar *
753168710Sstasformat_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
75424143Sjoerg{
755131623Sdes	struct kinfo_proc *pp;
756131623Sdes	const struct kinfo_proc *oldp;
757131623Sdes	long cputime;
758131623Sdes	double pct;
759131623Sdes	struct handle *hp;
760131623Sdes	char status[16];
761131623Sdes	int state;
762131623Sdes	struct rusage ru, *rup;
763131623Sdes	long p_tot, s_tot;
764168799Srafan	char *proc_fmt, thr_buf[6], jid_buf[6];
765168710Sstas	char *cmdbuf = NULL;
766168710Sstas	char **args;
76724143Sjoerg
768131623Sdes	/* find and remember the next proc structure */
769131623Sdes	hp = (struct handle *)handle;
770131623Sdes	pp = *(hp->next_proc++);
771131623Sdes	hp->remaining--;
772131620Sdes
773131623Sdes	/* get the process's command name */
774172207Sjeff	if ((pp->ki_flag & P_INMEM) == 0) {
775131623Sdes		/*
776131623Sdes		 * Print swapped processes as <pname>
777131623Sdes		 */
778158280Sbde		size_t len;
779158280Sbde
780158280Sbde		len = strlen(pp->ki_comm);
781131626Sdes		if (len > sizeof(pp->ki_comm) - 3)
782131626Sdes			len = sizeof(pp->ki_comm) - 3;
783131626Sdes		memmove(pp->ki_comm + 1, pp->ki_comm, len);
784131626Sdes		pp->ki_comm[0] = '<';
785131626Sdes		pp->ki_comm[len + 1] = '>';
786131626Sdes		pp->ki_comm[len + 2] = '\0';
787131623Sdes	}
788131623Sdes
78924143Sjoerg	/*
790131623Sdes	 * Convert the process's runtime from microseconds to seconds.  This
791131623Sdes	 * time includes the interrupt time although that is not wanted here.
792131623Sdes	 * ps(1) is similarly sloppy.
79324143Sjoerg	 */
794131623Sdes	cputime = (pp->ki_runtime + 500000) / 1000000;
79524143Sjoerg
796131623Sdes	/* calculate the base for cpu percentages */
797131623Sdes	pct = pctdouble(pp->ki_pctcpu);
79824143Sjoerg
799131623Sdes	/* generate "STATE" field */
800131623Sdes	switch (state = pp->ki_stat) {
80124143Sjoerg	case SRUN:
802131623Sdes		if (smpmode && pp->ki_oncpu != 0xff)
803131623Sdes			sprintf(status, "CPU%d", pp->ki_oncpu);
804131623Sdes		else
805131623Sdes			strcpy(status, "RUN");
806131623Sdes		break;
807104388Sjhb	case SLOCK:
808131623Sdes		if (pp->ki_kiflag & KI_LOCKBLOCK) {
809131623Sdes			sprintf(status, "*%.6s", pp->ki_lockname);
810131623Sdes			break;
811131623Sdes		}
812131623Sdes		/* fall through */
81324143Sjoerg	case SSLEEP:
814131623Sdes		if (pp->ki_wmesg != NULL) {
815131623Sdes			sprintf(status, "%.6s", pp->ki_wmesg);
816131623Sdes			break;
817131623Sdes		}
818131623Sdes		/* FALLTHROUGH */
81924143Sjoerg	default:
82043720Sfenner
821131623Sdes		if (state >= 0 &&
822131623Sdes		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
823131626Sdes			sprintf(status, "%.6s", state_abbrev[state]);
824131623Sdes		else
825131623Sdes			sprintf(status, "?%5d", state);
826131623Sdes		break;
827131623Sdes	}
82824143Sjoerg
829168710Sstas	cmdbuf = (char *)malloc(cmdlengthdelta + 1);
830168710Sstas	if (cmdbuf == NULL) {
831168710Sstas		warn("malloc(%d)", cmdlengthdelta + 1);
832168710Sstas		return NULL;
833168710Sstas	}
834168710Sstas
835168710Sstas	if (!(flags & FMT_SHOWARGS)) {
836173004Sjulian		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
837173004Sjulian		    pp->ki_ocomm[0]) {
838173004Sjulian			snprintf(cmdbuf, cmdlengthdelta, "{%s}", pp->ki_ocomm);
839173004Sjulian		} else {
840173004Sjulian			snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
841168710Sstas		}
842173004Sjulian	} else {
843173004Sjulian		if (pp->ki_flag & P_SYSTEM ||
844173004Sjulian		    pp->ki_args == NULL ||
845173004Sjulian		    (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
846173004Sjulian		    !(*args)) {
847173004Sjulian			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
848173004Sjulian		    	pp->ki_ocomm[0]) {
849173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
850173004Sjulian				    "{%s}", pp->ki_ocomm);
851173004Sjulian			} else {
852173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
853173004Sjulian				    "[%s]", pp->ki_comm);
854173004Sjulian			}
855173004Sjulian		} else {
856173004Sjulian			char *src, *dst, *argbuf;
857173004Sjulian			char *cmd;
858173004Sjulian			size_t argbuflen;
859173004Sjulian			size_t len;
860168710Sstas
861173004Sjulian			argbuflen = cmdlengthdelta * 4;
862173004Sjulian			argbuf = (char *)malloc(argbuflen + 1);
863173004Sjulian			if (argbuf == NULL) {
864173004Sjulian				warn("malloc(%d)", argbuflen + 1);
865173004Sjulian				free(cmdbuf);
866173004Sjulian				return NULL;
867173004Sjulian			}
868168710Sstas
869173004Sjulian			dst = argbuf;
870168710Sstas
871173004Sjulian			/* Extract cmd name from argv */
872173004Sjulian			cmd = strrchr(*args, '/');
873173004Sjulian			if (cmd == NULL)
874173004Sjulian				cmd = *args;
875173004Sjulian			else
876173004Sjulian				cmd++;
877168710Sstas
878173004Sjulian			for (; (src = *args++) != NULL; ) {
879173004Sjulian				if (*src == '\0')
880173004Sjulian					continue;
881173004Sjulian				len = (argbuflen - (dst - argbuf) - 1) / 4;
882173004Sjulian				strvisx(dst, src,
883173004Sjulian				    strlen(src) < len ? strlen(src) : len,
884173004Sjulian				    VIS_NL | VIS_CSTYLE);
885173004Sjulian				while (*dst != '\0')
886173004Sjulian					dst++;
887173004Sjulian				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
888173004Sjulian					*dst++ = ' '; /* add delimiting space */
889173004Sjulian			}
890173004Sjulian			if (dst != argbuf && dst[-1] == ' ')
891173004Sjulian				dst--;
892173004Sjulian			*dst = '\0';
893168710Sstas
894173004Sjulian			if (strcmp(cmd, pp->ki_comm) != 0 )
895173004Sjulian				snprintf(cmdbuf, cmdlengthdelta,
896173004Sjulian				    "%s (%s)",argbuf,  pp->ki_comm);
897173004Sjulian			else
898173004Sjulian				strlcpy(cmdbuf, argbuf, cmdlengthdelta);
899173004Sjulian
900173004Sjulian			free(argbuf);
901173004Sjulian		}
902168710Sstas	}
903168710Sstas
904168799Srafan	if (ps.jail == 0)
905168799Srafan		jid_buf[0] = '\0';
906168799Srafan	else
907168799Srafan		snprintf(jid_buf, sizeof(jid_buf), " %*d",
908168799Srafan		    sizeof(jid_buf) - 3, pp->ki_jid);
909168799Srafan
910131623Sdes	if (displaymode == DISP_IO) {
911131623Sdes		oldp = get_old_proc(pp);
912131623Sdes		if (oldp != NULL) {
913158280Sbde			ru.ru_inblock = RU(pp)->ru_inblock -
914158280Sbde			    RU(oldp)->ru_inblock;
915158280Sbde			ru.ru_oublock = RU(pp)->ru_oublock -
916158280Sbde			    RU(oldp)->ru_oublock;
917131623Sdes			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
918133817Salfred			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
919133817Salfred			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
920131623Sdes			rup = &ru;
921131623Sdes		} else {
922131623Sdes			rup = RU(pp);
923131623Sdes		}
924131623Sdes		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
925131623Sdes		s_tot = total_inblock + total_oublock + total_majflt;
926131402Salfred
927131623Sdes		sprintf(fmt, io_Proc_format,
928131623Sdes		    pp->ki_pid,
929168799Srafan		    jid_buf,
930158280Sbde		    namelength, namelength, (*get_userid)(pp->ki_ruid),
931133817Salfred		    rup->ru_nvcsw,
932133817Salfred		    rup->ru_nivcsw,
933131626Sdes		    rup->ru_inblock,
934131626Sdes		    rup->ru_oublock,
935131626Sdes		    rup->ru_majflt,
936131626Sdes		    p_tot,
937131626Sdes		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
938131623Sdes		    screen_width > cmdlengthdelta ?
939131623Sdes		    screen_width - cmdlengthdelta : 0,
940168710Sstas		    printable(cmdbuf));
941168710Sstas
942168710Sstas		free(cmdbuf);
943168710Sstas
944131623Sdes		return (fmt);
945131623Sdes	}
946145073Skeramida
947131623Sdes	/* format this entry */
948145073Skeramida	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
949145073Skeramida	if (ps.thread != 0)
950145073Skeramida		thr_buf[0] = '\0';
951145073Skeramida	else
952145073Skeramida		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
953145073Skeramida		    sizeof(thr_buf) - 2, pp->ki_numthreads);
954145073Skeramida
955145073Skeramida	sprintf(fmt, proc_fmt,
95669896Smckusick	    pp->ki_pid,
957168799Srafan	    jid_buf,
958158280Sbde	    namelength, namelength, (*get_userid)(pp->ki_ruid),
959145073Skeramida	    thr_buf,
96072377Sjake	    pp->ki_pri.pri_level - PZERO,
961158282Sbde	    format_nice(pp),
96237100Sdt	    format_k2(PROCSIZE(pp)),
96369896Smckusick	    format_k2(pagetok(pp->ki_rssize)),
96424143Sjoerg	    status,
96569896Smckusick	    smpmode ? pp->ki_lastcpu : 0,
96624143Sjoerg	    format_time(cputime),
967146342Skeramida	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
968158280Sbde	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
969168710Sstas	    printable(cmdbuf));
97024143Sjoerg
971168710Sstas	free(cmdbuf);
972168710Sstas
973131623Sdes	/* return the result */
974131623Sdes	return (fmt);
97524143Sjoerg}
97624143Sjoerg
977131310Salfredstatic void
978158282Sbdegetsysctl(const char *name, void *ptr, size_t len)
97924143Sjoerg{
980131623Sdes	size_t nlen = len;
981131310Salfred
982131623Sdes	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
983131623Sdes		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
984131623Sdes		    strerror(errno));
985131623Sdes		quit(23);
986131623Sdes	}
987131623Sdes	if (nlen != len) {
988158280Sbde		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
989158280Sbde		    name, (unsigned long)len, (unsigned long)nlen);
990131623Sdes		quit(23);
991131623Sdes	}
99224143Sjoerg}
99372951Srwatson
994164058Sbdestatic const char *
995164058Sbdeformat_nice(const struct kinfo_proc *pp)
996158282Sbde{
997164058Sbde	const char *fifo, *kthread;
998164058Sbde	int rtpri;
999164058Sbde	static char nicebuf[4 + 1];
1000158282Sbde
1001164058Sbde	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1002164058Sbde	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1003164058Sbde	switch (PRI_BASE(pp->ki_pri.pri_class)) {
1004164058Sbde	case PRI_ITHD:
1005164058Sbde		return ("-");
1006164058Sbde	case PRI_REALTIME:
1007170774Sbde		/*
1008170774Sbde		 * XXX: the kernel doesn't tell us the original rtprio and
1009170774Sbde		 * doesn't really know what it was, so to recover it we
1010170774Sbde		 * must be more chummy with the implementation than the
1011170774Sbde		 * implementation is with itself.  pri_user gives a
1012170774Sbde		 * constant "base" priority, but is only initialized
1013170774Sbde		 * properly for user threads.  pri_native gives what the
1014170774Sbde		 * kernel calls the "base" priority, but it isn't constant
1015170774Sbde		 * since it is changed by priority propagation.  pri_native
1016170774Sbde		 * also isn't properly initialized for all threads, but it
1017170774Sbde		 * is properly initialized for kernel realtime and idletime
1018170774Sbde		 * threads.  Thus we use pri_user for the base priority of
1019170774Sbde		 * user threads (it is always correct) and pri_native for
1020170774Sbde		 * the base priority of kernel realtime and idletime threads
1021170774Sbde		 * (there is nothing better, and it is usually correct).
1022170774Sbde		 *
1023170774Sbde		 * The field width and thus the buffer are too small for
1024170774Sbde		 * values like "kr31F", but such values shouldn't occur,
1025170774Sbde		 * and if they do then the tailing "F" is not displayed.
1026170774Sbde		 */
1027170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1028170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1029164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1030164058Sbde		    kthread, rtpri, fifo);
1031164058Sbde		break;
1032164058Sbde	case PRI_TIMESHARE:
1033164058Sbde		if (pp->ki_flag & P_KTHREAD)
1034164058Sbde			return ("-");
1035164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1036164058Sbde		break;
1037164058Sbde	case PRI_IDLE:
1038170774Sbde		/* XXX: as above. */
1039170774Sbde		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1040170774Sbde		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1041164058Sbde		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1042164058Sbde		    kthread, rtpri, fifo);
1043164058Sbde		break;
1044164058Sbde	default:
1045164058Sbde		return ("?");
1046164058Sbde	}
1047158282Sbde	return (nicebuf);
1048158282Sbde}
1049158282Sbde
105038278Swosch/* comparison routines for qsort */
105124143Sjoerg
1052158282Sbdestatic int
1053131622Sdescompare_pid(const void *p1, const void *p2)
1054131402Salfred{
1055131623Sdes	const struct kinfo_proc * const *pp1 = p1;
1056131623Sdes	const struct kinfo_proc * const *pp2 = p2;
1057131402Salfred
1058131623Sdes	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1059131623Sdes		abort();
1060131402Salfred
1061131623Sdes	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1062131402Salfred}
1063131402Salfred
106424143Sjoerg/*
106524143Sjoerg *  proc_compare - comparison function for "qsort"
106624143Sjoerg *	Compares the resource consumption of two processes using five
1067131620Sdes *	distinct keys.  The keys (in descending order of importance) are:
1068131620Sdes *	percent cpu, cpu ticks, state, resident set size, total virtual
1069131620Sdes *	memory usage.  The process states are ordered as follows (from least
1070131620Sdes *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
1071131620Sdes *	array declaration below maps a process state index into a number
1072131620Sdes *	that reflects this ordering.
107324143Sjoerg */
107424143Sjoerg
1075158280Sbdestatic int sorted_state[] = {
1076131623Sdes	0,	/* not used		*/
1077131623Sdes	3,	/* sleep		*/
1078131623Sdes	1,	/* ABANDONED (WAIT)	*/
1079131623Sdes	6,	/* run			*/
1080131623Sdes	5,	/* start		*/
1081131623Sdes	2,	/* zombie		*/
1082131623Sdes	4	/* stop			*/
108324143Sjoerg};
108438278Swosch
1085131620Sdes
1086146343Skeramida#define ORDERKEY_PCTCPU(a, b) do { \
1087146343Skeramida	long diff; \
1088146343Skeramida	if (ps.wcpu) \
1089158280Sbde		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1090158280Sbde		    (b))) - \
1091158280Sbde		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1092158280Sbde		    (a))); \
1093146343Skeramida	else \
1094146343Skeramida		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1095146343Skeramida	if (diff != 0) \
1096146343Skeramida		return (diff > 0 ? 1 : -1); \
1097131626Sdes} while (0)
109838278Swosch
1099131626Sdes#define ORDERKEY_CPTICKS(a, b) do { \
1100131628Sdes	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1101131626Sdes	if (diff != 0) \
1102131626Sdes		return (diff > 0 ? 1 : -1); \
1103131626Sdes} while (0)
110438278Swosch
1105131626Sdes#define ORDERKEY_STATE(a, b) do { \
1106131626Sdes	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1107131626Sdes	if (diff != 0) \
1108131626Sdes		return (diff > 0 ? 1 : -1); \
1109131626Sdes} while (0)
111038278Swosch
1111131626Sdes#define ORDERKEY_PRIO(a, b) do { \
1112131628Sdes	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1113131626Sdes	if (diff != 0) \
1114131626Sdes		return (diff > 0 ? 1 : -1); \
1115131626Sdes} while (0)
111638278Swosch
1117145073Skeramida#define	ORDERKEY_THREADS(a, b) do { \
1118145073Skeramida	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1119145073Skeramida	if (diff != 0) \
1120145073Skeramida		return (diff > 0 ? 1 : -1); \
1121145073Skeramida} while (0)
1122145073Skeramida
1123131626Sdes#define ORDERKEY_RSSIZE(a, b) do { \
1124131628Sdes	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1125131626Sdes	if (diff != 0) \
1126131626Sdes		return (diff > 0 ? 1 : -1); \
1127131626Sdes} while (0)
112838278Swosch
1129131626Sdes#define ORDERKEY_MEM(a, b) do { \
1130131628Sdes	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1131131626Sdes	if (diff != 0) \
1132131626Sdes		return (diff > 0 ? 1 : -1); \
1133131626Sdes} while (0)
113438278Swosch
1135168799Srafan#define ORDERKEY_JID(a, b) do { \
1136168799Srafan	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1137168799Srafan	if (diff != 0) \
1138168799Srafan		return (diff > 0 ? 1 : -1); \
1139168799Srafan} while (0)
1140168799Srafan
114138278Swosch/* compare_cpu - the comparison function for sorting by cpu percentage */
114238278Swosch
114324143Sjoergint
114438278Swosch#ifdef ORDER
1145131626Sdescompare_cpu(void *arg1, void *arg2)
114638278Swosch#else
1147131626Sdesproc_compare(void *arg1, void *arg2)
114838278Swosch#endif
114924143Sjoerg{
1150131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1151131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
115224143Sjoerg
1153131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1154131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1155131626Sdes	ORDERKEY_STATE(p1, p2);
1156131626Sdes	ORDERKEY_PRIO(p1, p2);
1157131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1158131626Sdes	ORDERKEY_MEM(p1, p2);
115924143Sjoerg
1160131626Sdes	return (0);
116124143Sjoerg}
116224143Sjoerg
116338278Swosch#ifdef ORDER
1164158280Sbde/* "cpu" compare routines */
1165158280Sbdeint compare_size(), compare_res(), compare_time(), compare_prio(),
1166158280Sbde    compare_threads();
116724143Sjoerg
1168158280Sbde/*
1169158280Sbde * "io" compare routines.  Context switches aren't i/o, but are displayed
1170158280Sbde * on the "io" display.
1171158280Sbde */
1172158280Sbdeint compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1173158280Sbde    compare_vcsw(), compare_ivcsw();
1174158280Sbde
1175133817Salfredint (*compares[])() = {
1176131623Sdes	compare_cpu,
1177131623Sdes	compare_size,
1178131623Sdes	compare_res,
1179131623Sdes	compare_time,
1180131623Sdes	compare_prio,
1181145073Skeramida	compare_threads,
1182133817Salfred	compare_iototal,
1183133817Salfred	compare_ioread,
1184133817Salfred	compare_iowrite,
1185133817Salfred	compare_iofault,
1186133817Salfred	compare_vcsw,
1187133817Salfred	compare_ivcsw,
1188168799Srafan	compare_jid,
1189131623Sdes	NULL
119038278Swosch};
119138278Swosch
119238278Swosch/* compare_size - the comparison function for sorting by total memory usage */
119338278Swosch
119438278Swoschint
1195131626Sdescompare_size(void *arg1, void *arg2)
119638278Swosch{
1197131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1198131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
119938278Swosch
1200131626Sdes	ORDERKEY_MEM(p1, p2);
1201131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1202131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1203131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1204131626Sdes	ORDERKEY_STATE(p1, p2);
1205131626Sdes	ORDERKEY_PRIO(p1, p2);
120638278Swosch
1207131626Sdes	return (0);
120838278Swosch}
120938278Swosch
121038278Swosch/* compare_res - the comparison function for sorting by resident set size */
121138278Swosch
121238278Swoschint
1213131626Sdescompare_res(void *arg1, void *arg2)
121438278Swosch{
1215131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1216131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
121738278Swosch
1218131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1219131626Sdes	ORDERKEY_MEM(p1, p2);
1220131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1221131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1222131626Sdes	ORDERKEY_STATE(p1, p2);
1223131626Sdes	ORDERKEY_PRIO(p1, p2);
122438278Swosch
1225131626Sdes	return (0);
122638278Swosch}
122738278Swosch
122838278Swosch/* compare_time - the comparison function for sorting by total cpu time */
122938278Swosch
123038278Swoschint
1231131626Sdescompare_time(void *arg1, void *arg2)
1232131310Salfred{
1233131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1234131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
123538278Swosch
1236131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1237131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1238131626Sdes	ORDERKEY_STATE(p1, p2);
1239131626Sdes	ORDERKEY_PRIO(p1, p2);
1240131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1241131626Sdes	ORDERKEY_MEM(p1, p2);
124238278Swosch
1243131626Sdes	return (0);
1244131623Sdes}
1245131310Salfred
1246131626Sdes/* compare_prio - the comparison function for sorting by priority */
124738278Swosch
124838278Swoschint
1249131626Sdescompare_prio(void *arg1, void *arg2)
125038278Swosch{
1251131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1252131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
125338278Swosch
1254131626Sdes	ORDERKEY_PRIO(p1, p2);
1255131626Sdes	ORDERKEY_CPTICKS(p1, p2);
1256131626Sdes	ORDERKEY_PCTCPU(p1, p2);
1257131626Sdes	ORDERKEY_STATE(p1, p2);
1258131626Sdes	ORDERKEY_RSSIZE(p1, p2);
1259131626Sdes	ORDERKEY_MEM(p1, p2);
126038278Swosch
1261131626Sdes	return (0);
126238278Swosch}
1263145073Skeramida
1264145073Skeramida/* compare_threads - the comparison function for sorting by threads */
1265145073Skeramidaint
1266145073Skeramidacompare_threads(void *arg1, void *arg2)
1267145073Skeramida{
1268145073Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1269145073Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1270145073Skeramida
1271145073Skeramida	ORDERKEY_THREADS(p1, p2);
1272145073Skeramida	ORDERKEY_PCTCPU(p1, p2);
1273145073Skeramida	ORDERKEY_CPTICKS(p1, p2);
1274145073Skeramida	ORDERKEY_STATE(p1, p2);
1275145073Skeramida	ORDERKEY_PRIO(p1, p2);
1276145073Skeramida	ORDERKEY_RSSIZE(p1, p2);
1277145073Skeramida	ORDERKEY_MEM(p1, p2);
1278145073Skeramida
1279145073Skeramida	return (0);
1280145073Skeramida}
1281168799Srafan
1282168799Srafan/* compare_jid - the comparison function for sorting by jid */
1283168799Srafanstatic int
1284168799Srafancompare_jid(const void *arg1, const void *arg2)
1285168799Srafan{
1286168799Srafan	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1287168799Srafan	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1288168799Srafan
1289168799Srafan	ORDERKEY_JID(p1, p2);
1290168799Srafan	ORDERKEY_PCTCPU(p1, p2);
1291168799Srafan	ORDERKEY_CPTICKS(p1, p2);
1292168799Srafan	ORDERKEY_STATE(p1, p2);
1293168799Srafan	ORDERKEY_PRIO(p1, p2);
1294168799Srafan	ORDERKEY_RSSIZE(p1, p2);
1295168799Srafan	ORDERKEY_MEM(p1, p2);
1296168799Srafan
1297168799Srafan	return (0);
1298168799Srafan}
1299158280Sbde#endif /* ORDER */
130038278Swosch
1301158280Sbde/* assorted comparison functions for sorting by i/o */
1302131829Skeramida
1303131402Salfredint
1304131829Skeramida#ifdef ORDER
1305131829Skeramidacompare_iototal(void *arg1, void *arg2)
1306131829Skeramida#else
1307131626Sdesio_compare(void *arg1, void *arg2)
1308131829Skeramida#endif
1309131402Salfred{
1310131626Sdes	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1311131626Sdes	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1312131402Salfred
1313131626Sdes	return (get_io_total(p2) - get_io_total(p1));
1314131402Salfred}
1315131829Skeramida
1316131829Skeramida#ifdef ORDER
1317131829Skeramidaint
1318131829Skeramidacompare_ioread(void *arg1, void *arg2)
1319131829Skeramida{
1320131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1321131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1322131829Skeramida	long dummy, inp1, inp2;
1323131829Skeramida
1324133817Salfred	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1325133817Salfred	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1326131829Skeramida
1327131829Skeramida	return (inp2 - inp1);
1328131829Skeramida}
1329131829Skeramida
1330131829Skeramidaint
1331131829Skeramidacompare_iowrite(void *arg1, void *arg2)
1332131829Skeramida{
1333131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1334131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1335131829Skeramida	long dummy, oup1, oup2;
1336131829Skeramida
1337133817Salfred	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1338133817Salfred	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1339131829Skeramida
1340131829Skeramida	return (oup2 - oup1);
1341131829Skeramida}
1342131829Skeramida
1343131829Skeramidaint
1344131829Skeramidacompare_iofault(void *arg1, void *arg2)
1345131829Skeramida{
1346131829Skeramida	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1347131829Skeramida	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1348131829Skeramida	long dummy, flp1, flp2;
1349131829Skeramida
1350133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1351133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1352131829Skeramida
1353131829Skeramida	return (flp2 - flp1);
1354131829Skeramida}
1355131829Skeramida
1356133817Salfredint
1357133817Salfredcompare_vcsw(void *arg1, void *arg2)
1358133817Salfred{
1359133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1360133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1361133817Salfred	long dummy, flp1, flp2;
1362133817Salfred
1363133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1364133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1365133817Salfred
1366133817Salfred	return (flp2 - flp1);
1367133817Salfred}
1368133817Salfred
1369133817Salfredint
1370133817Salfredcompare_ivcsw(void *arg1, void *arg2)
1371133817Salfred{
1372133817Salfred	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1373133817Salfred	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1374133817Salfred	long dummy, flp1, flp2;
1375133817Salfred
1376133817Salfred	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1377133817Salfred	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1378133817Salfred
1379133817Salfred	return (flp2 - flp1);
1380133817Salfred}
1381131829Skeramida#endif /* ORDER */
1382131829Skeramida
138324143Sjoerg/*
138424143Sjoerg * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
138524143Sjoerg *		the process does not exist.
138624143Sjoerg *		It is EXTREMLY IMPORTANT that this function work correctly.
138724143Sjoerg *		If top runs setuid root (as in SVR4), then this function
138824143Sjoerg *		is the only thing that stands in the way of a serious
138924143Sjoerg *		security problem.  It validates requests for the "kill"
139024143Sjoerg *		and "renice" commands.
139124143Sjoerg */
139224143Sjoerg
1393131310Salfredint
1394131622Sdesproc_owner(int pid)
139524143Sjoerg{
1396131623Sdes	int cnt;
1397131623Sdes	struct kinfo_proc **prefp;
1398131623Sdes	struct kinfo_proc *pp;
139924143Sjoerg
1400131623Sdes	prefp = pref;
1401131623Sdes	cnt = pref_len;
1402131626Sdes	while (--cnt >= 0) {
1403131623Sdes		pp = *prefp++;
1404131623Sdes		if (pp->ki_pid == (pid_t)pid)
1405131623Sdes			return ((int)pp->ki_ruid);
140624143Sjoerg	}
1407131623Sdes	return (-1);
140824143Sjoerg}
140924143Sjoerg
1410158282Sbdestatic int
1411131622Sdesswapmode(int *retavail, int *retfree)
141224143Sjoerg{
141343053Sdillon	int n;
141443053Sdillon	int pagesize = getpagesize();
141543053Sdillon	struct kvm_swap swapary[1];
141624143Sjoerg
141743053Sdillon	*retavail = 0;
141843053Sdillon	*retfree = 0;
141924143Sjoerg
142043053Sdillon#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
142124143Sjoerg
142243053Sdillon	n = kvm_getswapinfo(kd, swapary, 1, 0);
142343697Sdillon	if (n < 0 || swapary[0].ksw_total == 0)
1424131623Sdes		return (0);
142524143Sjoerg
142643053Sdillon	*retavail = CONVERT(swapary[0].ksw_total);
142743053Sdillon	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
142824143Sjoerg
1429131626Sdes	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1430131623Sdes	return (n);
143143053Sdillon}
1432