machine.c revision 222530
1327952Sdim/*
2283625Sdim * top - a top users display for Unix
3353358Sdim *
4353358Sdim * SYNOPSIS:  For FreeBSD-2.x and later
5353358Sdim *
6283625Sdim * DESCRIPTION:
7283625Sdim * Originally written for BSD4.4 system by Christos Zoulas.
8283625Sdim * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9283625Sdim * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10283625Sdim *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
11283625Sdim *
12283625Sdim * This is the machine-dependent module for FreeBSD 2.2
13283625Sdim * Works for:
14283625Sdim *	FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
15283625Sdim *
16283625Sdim * LIBS: -lkvm
17283625Sdim *
18283625Sdim * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
19283625Sdim *          Steven Wallace  <swallace@freebsd.org>
20283625Sdim *          Wolfram Schneider <wosch@FreeBSD.org>
21283625Sdim *          Thomas Moestl <tmoestl@gmx.net>
22283625Sdim *
23283625Sdim * $FreeBSD: head/usr.bin/top/machine.c 222530 2011-05-31 15:11:23Z jhb $
24283625Sdim */
25283625Sdim
26283625Sdim#include <sys/param.h>
27283625Sdim#include <sys/errno.h>
28283625Sdim#include <sys/file.h>
29283625Sdim#include <sys/proc.h>
30283625Sdim#include <sys/resource.h>
31283625Sdim#include <sys/rtprio.h>
32283625Sdim#include <sys/signal.h>
33283625Sdim#include <sys/sysctl.h>
34283625Sdim#include <sys/time.h>
35283625Sdim#include <sys/user.h>
36283625Sdim#include <sys/vmmeter.h>
37283625Sdim
38283625Sdim#include <err.h>
39283625Sdim#include <kvm.h>
40283625Sdim#include <math.h>
41283625Sdim#include <nlist.h>
42283625Sdim#include <paths.h>
43283625Sdim#include <pwd.h>
44283625Sdim#include <stdio.h>
45296417Sdim#include <stdlib.h>
46296417Sdim#include <string.h>
47327952Sdim#include <strings.h>
48283625Sdim#include <unistd.h>
49327952Sdim#include <vis.h>
50296417Sdim
51296417Sdim#include "top.h"
52296417Sdim#include "machine.h"
53327952Sdim#include "screen.h"
54283625Sdim#include "utils.h"
55341825Sdim#include "layout.h"
56327952Sdim
57283625Sdim#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
58283625Sdim#define	SMPUNAMELEN	13
59327952Sdim#define	UPUNAMELEN	15
60327952Sdim
61283625Sdimextern struct process_select ps;
62327952Sdimextern char* printable(char *);
63283625Sdimstatic int smpmode;
64327952Sdimenum displaymodes displaymode;
65341825Sdim#ifdef TOP_USERNAME_LEN
66283625Sdimstatic int namelength = TOP_USERNAME_LEN;
67283625Sdim#else
68296417Sdimstatic int namelength = 8;
69327952Sdim#endif
70327952Sdimstatic int cmdlengthdelta;
71341825Sdim
72327952Sdim/* Prototypes for top internals */
73327952Sdimvoid quit(int);
74327952Sdim
75327952Sdim/* get_process_info passes back a handle.  This is what it looks like: */
76360784Sdim
77296417Sdimstruct handle {
78327952Sdim	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
79327952Sdim	int remaining;			/* number of pointers remaining */
80283625Sdim};
81327952Sdim
82327952Sdim/* declarations for load_avg */
83296417Sdim#include "loadavg.h"
84327952Sdim
85327952Sdim/* define what weighted cpu is.  */
86327952Sdim#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
87283625Sdim			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
88327952Sdim
89327952Sdim/* what we consider to be process size: */
90283625Sdim#define PROCSIZE(pp) ((pp)->ki_size / 1024)
91283625Sdim
92283625Sdim#define RU(pp)	(&(pp)->ki_rusage)
93283625Sdim#define RUTOT(pp) \
94283625Sdim	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
95283625Sdim
96283625Sdim
97296417Sdim/* definitions for indices in the nlist array */
98327952Sdim
99327952Sdim/*
100296417Sdim *  These definitions control the format of the per-process area
101283625Sdim */
102327952Sdim
103341825Sdimstatic char io_header[] =
104283625Sdim    "  PID%s %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
105283625Sdim
106283625Sdim#define io_Proc_format \
107283625Sdim    "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
108283625Sdim
109283625Sdimstatic char smp_header_thr[] =
110283625Sdim    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE   C   TIME %6s COMMAND";
111283625Sdimstatic char smp_header[] =
112283625Sdim    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE   C   TIME %6s COMMAND";
113283625Sdim
114283625Sdim#define smp_Proc_format \
115327952Sdim    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %2d%7s %5.2f%% %.*s"
116283625Sdim
117283625Sdimstatic char up_header_thr[] =
118283625Sdim    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
119283625Sdimstatic char up_header[] =
120327952Sdim    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
121283625Sdim
122283625Sdim#define up_Proc_format \
123283625Sdim    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
124283625Sdim
125327952Sdim
126283625Sdim/* process state names for the "STATE" column of the display */
127283625Sdim/* the extra nulls in the string "run" are for adding a slash and
128283625Sdim   the processor number when needed */
129327952Sdim
130283625Sdimchar *state_abbrev[] = {
131283625Sdim	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
132283625Sdim};
133327952Sdim
134341825Sdim
135341825Sdimstatic kvm_t *kd;
136341825Sdim
137283625Sdim/* values that we stash away in _init and use in later routines */
138283625Sdim
139327952Sdimstatic double logcpu;
140283625Sdim
141283625Sdim/* these are retrieved from the kernel in _init */
142327952Sdim
143283625Sdimstatic load_avg  ccpu;
144283625Sdim
145327952Sdim/* these are used in the get_ functions */
146341825Sdim
147341825Sdimstatic int lastpid;
148341825Sdim
149283625Sdim/* these are for calculating cpu state percentages */
150283625Sdim
151327952Sdimstatic long cp_time[CPUSTATES];
152327952Sdimstatic long cp_old[CPUSTATES];
153327952Sdimstatic long cp_diff[CPUSTATES];
154296417Sdim
155296417Sdim/* these are for detailing the process states */
156327952Sdim
157296417Sdimint process_states[8];
158296417Sdimchar *procstatenames[] = {
159283625Sdim	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
160341825Sdim	" zombie, ", " waiting, ", " lock, ",
161283625Sdim	NULL
162283625Sdim};
163296417Sdim
164283625Sdim/* these are for detailing the cpu states */
165296417Sdim
166296417Sdimint cpu_states[CPUSTATES];
167296417Sdimchar *cpustatenames[] = {
168296417Sdim	"user", "nice", "system", "interrupt", "idle", NULL
169296417Sdim};
170296417Sdim
171296417Sdim/* these are for detailing the memory statistics */
172296417Sdim
173296417Sdimint memory_stats[7];
174296417Sdimchar *memorynames[] = {
175296417Sdim	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
176296417Sdim	"K Free", NULL
177296417Sdim};
178296417Sdim
179296417Sdimint swap_stats[7];
180341825Sdimchar *swapnames[] = {
181283625Sdim	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
182283625Sdim	NULL
183283625Sdim};
184283625Sdim
185296417Sdim
186283625Sdim/* these are for keeping track of the proc array */
187341825Sdim
188283625Sdimstatic int nproc;
189283625Sdimstatic int onproc = -1;
190283625Sdimstatic int pref_len;
191283625Sdimstatic struct kinfo_proc *pbase;
192283625Sdimstatic struct kinfo_proc **pref;
193283625Sdimstatic struct kinfo_proc *previous_procs;
194283625Sdimstatic struct kinfo_proc **previous_pref;
195283625Sdimstatic int previous_proc_count = 0;
196341825Sdimstatic int previous_proc_count_max = 0;
197283625Sdim
198341825Sdim/* total number of io operations */
199341825Sdimstatic long total_inblock;
200283625Sdimstatic long total_oublock;
201283625Sdimstatic long total_majflt;
202341825Sdim
203283625Sdim/* these are for getting the memory statistics */
204296417Sdim
205296417Sdimstatic int pageshift;		/* log base 2 of the pagesize */
206283625Sdim
207283625Sdim/* define pagetok in terms of pageshift */
208283625Sdim
209283625Sdim#define pagetok(size) ((size) << pageshift)
210283625Sdim
211283625Sdim/* useful externals */
212283625Sdimlong percentages();
213283625Sdim
214341825Sdim#ifdef ORDER
215296417Sdim/*
216296417Sdim * Sorting orders.  The first element is the default.
217283625Sdim */
218283625Sdimchar *ordernames[] = {
219283625Sdim	"cpu", "size", "res", "time", "pri", "threads",
220283625Sdim	"total", "read", "write", "fault", "vcsw", "ivcsw",
221283625Sdim	"jid", NULL
222283625Sdim};
223283625Sdim#endif
224283625Sdim
225283625Sdim/* Per-cpu time states */
226283625Sdimstatic int maxcpu;
227283625Sdimstatic int maxid;
228283625Sdimstatic int ncpus;
229283625Sdimstatic u_long cpumask;
230341825Sdimstatic long *times;
231283625Sdimstatic long *pcpu_cp_time;
232283625Sdimstatic long *pcpu_cp_old;
233283625Sdimstatic long *pcpu_cp_diff;
234341825Sdimstatic int *pcpu_cpu_states;
235341825Sdim
236341825Sdimstatic int compare_jid(const void *a, const void *b);
237341825Sdimstatic int compare_pid(const void *a, const void *b);
238341825Sdimstatic const char *format_nice(const struct kinfo_proc *pp);
239314564Sdimstatic void getsysctl(const char *name, void *ptr, size_t len);
240283625Sdimstatic int swapmode(int *retavail, int *retfree);
241341825Sdim
242283625Sdimint
243283625Sdimmachine_init(struct statics *statics, char do_unames)
244283625Sdim{
245283625Sdim	int pagesize;
246327952Sdim	size_t modelen;
247327952Sdim	struct passwd *pw;
248283625Sdim
249327952Sdim	modelen = sizeof(smpmode);
250283625Sdim	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
251283625Sdim	    NULL, 0) != 0 &&
252321369Sdim	    sysctlbyname("kern.smp.active", &smpmode, &modelen,
253283625Sdim	    NULL, 0) != 0) ||
254283625Sdim	    modelen != sizeof(smpmode))
255283625Sdim		smpmode = 0;
256283625Sdim
257341825Sdim	if (do_unames) {
258321369Sdim	    while ((pw = getpwent()) != NULL) {
259283625Sdim		if (strlen(pw->pw_name) > namelength)
260296417Sdim			namelength = strlen(pw->pw_name);
261296417Sdim	    }
262353358Sdim	}
263353358Sdim	if (smpmode && namelength > SMPUNAMELEN)
264353358Sdim		namelength = SMPUNAMELEN;
265353358Sdim	else if (namelength > UPUNAMELEN)
266353358Sdim		namelength = UPUNAMELEN;
267353358Sdim
268353358Sdim	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
269353358Sdim	if (kd == NULL)
270353358Sdim		return (-1);
271283625Sdim
272283625Sdim	GETSYSCTL("kern.ccpu", ccpu);
273341825Sdim
274283625Sdim	/* this is used in calculating WCPU -- calculate it ahead of time */
275283625Sdim	logcpu = log(loaddouble(ccpu));
276283625Sdim
277296417Sdim	pbase = NULL;
278283625Sdim	pref = NULL;
279341825Sdim	nproc = 0;
280341825Sdim	onproc = -1;
281341825Sdim
282360784Sdim	/* get the page size and calculate pageshift from it */
283283625Sdim	pagesize = getpagesize();
284283625Sdim	pageshift = 0;
285360784Sdim	while (pagesize > 1) {
286341825Sdim		pageshift++;
287341825Sdim		pagesize >>= 1;
288341825Sdim	}
289341825Sdim
290341825Sdim	/* we only need the amount of log(2)1024 for our conversion */
291341825Sdim	pageshift -= LOG1024;
292341825Sdim
293296417Sdim	/* fill in the statics information */
294296417Sdim	statics->procstate_names = procstatenames;
295296417Sdim	statics->cpustate_names = cpustatenames;
296296417Sdim	statics->memory_names = memorynames;
297296417Sdim	statics->swap_names = swapnames;
298296417Sdim#ifdef ORDER
299296417Sdim	statics->order_names = ordernames;
300296417Sdim#endif
301283625Sdim
302341825Sdim	/* Adjust display based on ncpus */
303341825Sdim	if (pcpu_stats) {
304341825Sdim		int i, j, empty;
305341825Sdim		size_t size;
306283625Sdim
307283625Sdim		cpumask = 0;
308283625Sdim		ncpus = 0;
309283625Sdim		GETSYSCTL("kern.smp.maxcpus", maxcpu);
310283625Sdim		size = sizeof(long) * maxcpu * CPUSTATES;
311283625Sdim		times = malloc(size);
312341825Sdim		if (times == NULL)
313283625Sdim			err(1, "malloc %zd bytes", size);
314314564Sdim		if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
315314564Sdim			err(1, "sysctlbyname kern.cp_times");
316283625Sdim		pcpu_cp_time = calloc(1, size);
317283625Sdim		maxid = (size / CPUSTATES / sizeof(long)) - 1;
318283625Sdim		for (i = 0; i <= maxid; i++) {
319283625Sdim			empty = 1;
320283625Sdim			for (j = 0; empty && j < CPUSTATES; j++) {
321283625Sdim				if (times[i * CPUSTATES + j] != 0)
322296417Sdim					empty = 0;
323296417Sdim			}
324283625Sdim			if (!empty) {
325283625Sdim				cpumask |= (1ul << i);
326283625Sdim				ncpus++;
327296417Sdim			}
328296417Sdim		}
329283625Sdim
330283625Sdim		if (ncpus > 1) {
331283625Sdim			y_mem += ncpus - 1;	/* 3 */
332283625Sdim			y_swap += ncpus - 1;	/* 4 */
333283625Sdim			y_idlecursor += ncpus - 1; /* 5 */
334283625Sdim			y_message += ncpus - 1;	/* 5 */
335283625Sdim			y_header += ncpus - 1;	/* 6 */
336341825Sdim			y_procs += ncpus - 1;	/* 7 */
337283625Sdim			Header_lines += ncpus - 1; /* 7 */
338283625Sdim		}
339283625Sdim		size = sizeof(long) * ncpus * CPUSTATES;
340283625Sdim		pcpu_cp_old = calloc(1, size);
341283625Sdim		pcpu_cp_diff = calloc(1, size);
342321369Sdim		pcpu_cpu_states = calloc(1, size);
343321369Sdim		statics->ncpus = ncpus;
344321369Sdim	} else {
345321369Sdim		statics->ncpus = 1;
346321369Sdim	}
347321369Sdim
348283625Sdim	/* all done! */
349321369Sdim	return (0);
350283625Sdim}
351283625Sdim
352283625Sdimchar *
353283625Sdimformat_header(char *uname_field)
354283625Sdim{
355296417Sdim	static char Header[128];
356283625Sdim	const char *prehead;
357283625Sdim
358283625Sdim	switch (displaymode) {
359321369Sdim	case DISP_CPU:
360283625Sdim		/*
361283625Sdim		 * The logic of picking the right header format seems reverse
362283625Sdim		 * here because we only want to display a THR column when
363283625Sdim		 * "thread mode" is off (and threads are not listed as
364283625Sdim		 * separate lines).
365283625Sdim		 */
366283625Sdim		prehead = smpmode ?
367283625Sdim		    (ps.thread ? smp_header : smp_header_thr) :
368283625Sdim		    (ps.thread ? up_header : up_header_thr);
369283625Sdim		snprintf(Header, sizeof(Header), prehead,
370341825Sdim		    ps.jail ? " JID" : "",
371341825Sdim		    namelength, namelength, uname_field,
372283625Sdim		    ps.wcpu ? "WCPU" : "CPU");
373283625Sdim		break;
374283625Sdim	case DISP_IO:
375283625Sdim		prehead = io_header;
376283625Sdim		snprintf(Header, sizeof(Header), prehead,
377283625Sdim		    ps.jail ? " JID" : "",
378283625Sdim		    namelength, namelength, uname_field);
379283625Sdim		break;
380283625Sdim	}
381283625Sdim	cmdlengthdelta = strlen(Header) - 7;
382283625Sdim	return (Header);
383283625Sdim}
384283625Sdim
385283625Sdimstatic int swappgsin = -1;
386283625Sdimstatic int swappgsout = -1;
387296417Sdimextern struct timeval timeout;
388296417Sdim
389296417Sdim
390296417Sdimvoid
391296417Sdimget_system_info(struct system_info *si)
392296417Sdim{
393296417Sdim	long total;
394296417Sdim	struct loadavg sysload;
395296417Sdim	int mib[2];
396296417Sdim	struct timeval boottime;
397296417Sdim	size_t bt_size;
398296417Sdim	int i, j;
399296417Sdim	size_t size;
400296417Sdim
401296417Sdim	/* get the cp_time array */
402296417Sdim	if (pcpu_stats) {
403296417Sdim		size = (maxid + 1) * CPUSTATES * sizeof(long);
404296417Sdim		if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
405283625Sdim			err(1, "sysctlbyname kern.cp_times");
406283625Sdim	} else {
407283625Sdim		GETSYSCTL("kern.cp_time", cp_time);
408283625Sdim	}
409283625Sdim	GETSYSCTL("vm.loadavg", sysload);
410283625Sdim	GETSYSCTL("kern.lastpid", lastpid);
411283625Sdim
412283625Sdim	/* convert load averages to doubles */
413283625Sdim	for (i = 0; i < 3; i++)
414283625Sdim		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
415296417Sdim
416296417Sdim	if (pcpu_stats) {
417296417Sdim		for (i = j = 0; i <= maxid; i++) {
418296417Sdim			if ((cpumask & (1ul << i)) == 0)
419296417Sdim				continue;
420283625Sdim			/* convert cp_time counts to percentages */
421296417Sdim			percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
422296417Sdim			    &pcpu_cp_time[j * CPUSTATES],
423296417Sdim			    &pcpu_cp_old[j * CPUSTATES],
424296417Sdim			    &pcpu_cp_diff[j * CPUSTATES]);
425296417Sdim			j++;
426296417Sdim		}
427296417Sdim	} else {
428283625Sdim		/* convert cp_time counts to percentages */
429296417Sdim		percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
430296417Sdim	}
431296417Sdim
432296417Sdim	/* sum memory & swap statistics */
433296417Sdim	{
434296417Sdim		static unsigned int swap_delay = 0;
435296417Sdim		static int swapavail = 0;
436296417Sdim		static int swapfree = 0;
437296417Sdim		static long bufspace = 0;
438296417Sdim		static int nspgsin, nspgsout;
439296417Sdim
440296417Sdim		GETSYSCTL("vfs.bufspace", bufspace);
441296417Sdim		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
442296417Sdim		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
443296417Sdim		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
444296417Sdim		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
445296417Sdim		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
446283625Sdim		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
447283625Sdim		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
448283625Sdim		/* convert memory stats to Kbytes */
449283625Sdim		memory_stats[0] = pagetok(memory_stats[0]);
450341825Sdim		memory_stats[1] = pagetok(memory_stats[1]);
451341825Sdim		memory_stats[2] = pagetok(memory_stats[2]);
452341825Sdim		memory_stats[3] = pagetok(memory_stats[3]);
453341825Sdim		memory_stats[4] = bufspace / 1024;
454341825Sdim		memory_stats[5] = pagetok(memory_stats[5]);
455341825Sdim		memory_stats[6] = -1;
456341825Sdim
457341825Sdim		/* first interval */
458296417Sdim		if (swappgsin < 0) {
459341825Sdim			swap_stats[4] = 0;
460296417Sdim			swap_stats[5] = 0;
461296417Sdim		}
462296417Sdim
463283625Sdim		/* compute differences between old and new swap statistic */
464327952Sdim		else {
465283625Sdim			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
466296417Sdim			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
467341825Sdim		}
468283625Sdim
469283625Sdim		swappgsin = nspgsin;
470283625Sdim		swappgsout = nspgsout;
471341825Sdim
472341825Sdim		/* call CPU heavy swapmode() only for changes */
473296417Sdim		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
474296417Sdim			swap_stats[3] = swapmode(&swapavail, &swapfree);
475296417Sdim			swap_stats[0] = swapavail;
476296417Sdim			swap_stats[1] = swapavail - swapfree;
477296417Sdim			swap_stats[2] = swapfree;
478296417Sdim		}
479341825Sdim		swap_delay = 1;
480341825Sdim		swap_stats[6] = -1;
481341825Sdim	}
482296417Sdim
483296417Sdim	/* set arrays and strings */
484296417Sdim	if (pcpu_stats) {
485296417Sdim		si->cpustates = pcpu_cpu_states;
486296417Sdim		si->ncpus = ncpus;
487296417Sdim	} else {
488283625Sdim		si->cpustates = cpu_states;
489341825Sdim		si->ncpus = 1;
490341825Sdim	}
491283625Sdim	si->memory = memory_stats;
492341825Sdim	si->swap = swap_stats;
493341825Sdim
494341825Sdim
495341825Sdim	if (lastpid > 0) {
496341825Sdim		si->last_pid = lastpid;
497341825Sdim	} else {
498341825Sdim		si->last_pid = -1;
499341825Sdim	}
500341825Sdim
501341825Sdim	/*
502341825Sdim	 * Print how long system has been up.
503341825Sdim	 * (Found by looking getting "boottime" from the kernel)
504341825Sdim	 */
505341825Sdim	mib[0] = CTL_KERN;
506341825Sdim	mib[1] = KERN_BOOTTIME;
507341825Sdim	bt_size = sizeof(boottime);
508341825Sdim	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
509341825Sdim	    boottime.tv_sec != 0) {
510341825Sdim		si->boottime = boottime;
511296417Sdim	} else {
512296417Sdim		si->boottime.tv_sec = -1;
513283625Sdim	}
514296417Sdim}
515283625Sdim
516283625Sdim#define NOPROC	((void *)-1)
517283625Sdim
518296417Sdim/*
519283625Sdim * We need to compare data from the old process entry with the new
520283625Sdim * process entry.
521283625Sdim * To facilitate doing this quickly we stash a pointer in the kinfo_proc
522341825Sdim * structure to cache the mapping.  We also use a negative cache pointer
523283625Sdim * of NOPROC to avoid duplicate lookups.
524283625Sdim * XXX: this could be done when the actual processes are fetched, we do
525283625Sdim * it here out of laziness.
526283625Sdim */
527283625Sdimconst struct kinfo_proc *
528283625Sdimget_old_proc(struct kinfo_proc *pp)
529283625Sdim{
530283625Sdim	struct kinfo_proc **oldpp, *oldp;
531283625Sdim
532283625Sdim	/*
533283625Sdim	 * If this is the first fetch of the kinfo_procs then we don't have
534283625Sdim	 * any previous entries.
535341825Sdim	 */
536283625Sdim	if (previous_proc_count == 0)
537283625Sdim		return (NULL);
538283625Sdim	/* negative cache? */
539341825Sdim	if (pp->ki_udata == NOPROC)
540341825Sdim		return (NULL);
541283625Sdim	/* cached? */
542283625Sdim	if (pp->ki_udata != NULL)
543283625Sdim		return (pp->ki_udata);
544341825Sdim	/*
545341825Sdim	 * Not cached,
546341825Sdim	 * 1) look up based on pid.
547341825Sdim	 * 2) compare process start.
548341825Sdim	 * If we fail here, then setup a negative cache entry, otherwise
549341825Sdim	 * cache it.
550283625Sdim	 */
551283625Sdim	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
552283625Sdim	    sizeof(*previous_pref), compare_pid);
553283625Sdim	if (oldpp == NULL) {
554283625Sdim		pp->ki_udata = NOPROC;
555283625Sdim		return (NULL);
556283625Sdim	}
557341825Sdim	oldp = *oldpp;
558341825Sdim	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
559283625Sdim		pp->ki_udata = NOPROC;
560283625Sdim		return (NULL);
561283625Sdim	}
562283625Sdim	pp->ki_udata = oldp;
563283625Sdim	return (oldp);
564283625Sdim}
565283625Sdim
566283625Sdim/*
567283625Sdim * Return the total amount of IO done in blocks in/out and faults.
568283625Sdim * store the values individually in the pointers passed in.
569283625Sdim */
570283625Sdimlong
571283625Sdimget_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
572296417Sdim    long *vcsw, long *ivcsw)
573283625Sdim{
574283625Sdim	const struct kinfo_proc *oldp;
575283625Sdim	static struct kinfo_proc dummy;
576283625Sdim	long ret;
577283625Sdim
578283625Sdim	oldp = get_old_proc(pp);
579283625Sdim	if (oldp == NULL) {
580341825Sdim		bzero(&dummy, sizeof(dummy));
581341825Sdim		oldp = &dummy;
582341825Sdim	}
583341825Sdim	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
584283625Sdim	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
585314564Sdim	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
586314564Sdim	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
587314564Sdim	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
588283625Sdim	ret =
589283625Sdim	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
590283625Sdim	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
591296417Sdim	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
592296417Sdim	return (ret);
593296417Sdim}
594296417Sdim
595296417Sdim/*
596296417Sdim * Return the total number of block in/out and faults by a process.
597296417Sdim */
598327952Sdimlong
599327952Sdimget_io_total(struct kinfo_proc *pp)
600327952Sdim{
601327952Sdim	long dummy;
602327952Sdim
603327952Sdim	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
604327952Sdim}
605327952Sdim
606327952Sdimstatic struct handle handle;
607327952Sdim
608327952Sdimcaddr_t
609296417Sdimget_process_info(struct system_info *si, struct process_select *sel,
610296417Sdim    int (*compare)(const void *, const void *))
611296417Sdim{
612296417Sdim	int i;
613296417Sdim	int total_procs;
614296417Sdim	long p_io;
615296417Sdim	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
616296417Sdim	int active_procs;
617296417Sdim	struct kinfo_proc **prefp;
618296417Sdim	struct kinfo_proc *pp;
619	struct kinfo_proc *prev_pp = NULL;
620
621	/* these are copied out of sel for speed */
622	int show_idle;
623	int show_self;
624	int show_system;
625	int show_uid;
626	int show_command;
627	int show_kidle;
628
629	/*
630	 * Save the previous process info.
631	 */
632	if (previous_proc_count_max < nproc) {
633		free(previous_procs);
634		previous_procs = malloc(nproc * sizeof(*previous_procs));
635		free(previous_pref);
636		previous_pref = malloc(nproc * sizeof(*previous_pref));
637		if (previous_procs == NULL || previous_pref == NULL) {
638			(void) fprintf(stderr, "top: Out of memory.\n");
639			quit(23);
640		}
641		previous_proc_count_max = nproc;
642	}
643	if (nproc) {
644		for (i = 0; i < nproc; i++)
645			previous_pref[i] = &previous_procs[i];
646		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
647		qsort(previous_pref, nproc, sizeof(*previous_pref),
648		    compare_pid);
649	}
650	previous_proc_count = nproc;
651
652	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
653	if (nproc > onproc)
654		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
655	if (pref == NULL || pbase == NULL) {
656		(void) fprintf(stderr, "top: Out of memory.\n");
657		quit(23);
658	}
659	/* get a pointer to the states summary array */
660	si->procstates = process_states;
661
662	/* set up flags which define what we are going to select */
663	show_idle = sel->idle;
664	show_self = sel->self == -1;
665	show_system = sel->system;
666	show_uid = sel->uid != -1;
667	show_command = sel->command != NULL;
668	show_kidle = sel->kidle;
669
670	/* count up process states and get pointers to interesting procs */
671	total_procs = 0;
672	active_procs = 0;
673	total_inblock = 0;
674	total_oublock = 0;
675	total_majflt = 0;
676	memset((char *)process_states, 0, sizeof(process_states));
677	prefp = pref;
678	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
679
680		if (pp->ki_stat == 0)
681			/* not in use */
682			continue;
683
684		if (!show_self && pp->ki_pid == sel->self)
685			/* skip self */
686			continue;
687
688		if (!show_system && (pp->ki_flag & P_SYSTEM))
689			/* skip system process */
690			continue;
691
692		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
693		    &p_vcsw, &p_ivcsw);
694		total_inblock += p_inblock;
695		total_oublock += p_oublock;
696		total_majflt += p_majflt;
697		total_procs++;
698		process_states[pp->ki_stat]++;
699
700		if (pp->ki_stat == SZOMB)
701			/* skip zombies */
702			continue;
703
704		if (displaymode == DISP_CPU && !show_idle &&
705		    (pp->ki_pctcpu == 0 ||
706		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
707			/* skip idle or non-running processes */
708			continue;
709
710		if (displaymode == DISP_CPU && !show_kidle &&
711		    pp->ki_tdflags & TDF_IDLETD)
712			/* skip kernel idle process */
713			continue;
714
715		if (displaymode == DISP_IO && !show_idle && p_io == 0)
716			/* skip processes that aren't doing I/O */
717			continue;
718
719		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
720			/* skip proc. that don't belong to the selected UID */
721			continue;
722
723		/*
724		 * When not showing threads, take the first thread
725		 * for output and add the fields that we can from
726		 * the rest of the process's threads rather than
727		 * using the system's mostly-broken KERN_PROC_PROC.
728		 */
729		if (sel->thread || prev_pp == NULL ||
730		    prev_pp->ki_pid != pp->ki_pid) {
731			*prefp++ = pp;
732			active_procs++;
733			prev_pp = pp;
734		} else {
735			prev_pp->ki_pctcpu += pp->ki_pctcpu;
736			prev_pp->ki_runtime += pp->ki_runtime;
737		}
738	}
739
740	/* if requested, sort the "interesting" processes */
741	if (compare != NULL)
742		qsort(pref, active_procs, sizeof(*pref), compare);
743
744	/* remember active and total counts */
745	si->p_total = total_procs;
746	si->p_active = pref_len = active_procs;
747
748	/* pass back a handle */
749	handle.next_proc = pref;
750	handle.remaining = active_procs;
751	return ((caddr_t)&handle);
752}
753
754static char fmt[128];	/* static area where result is built */
755
756char *
757format_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
758{
759	struct kinfo_proc *pp;
760	const struct kinfo_proc *oldp;
761	long cputime;
762	double pct;
763	struct handle *hp;
764	char status[16];
765	int state;
766	struct rusage ru, *rup;
767	long p_tot, s_tot;
768	char *proc_fmt, thr_buf[6], jid_buf[6];
769	char *cmdbuf = NULL;
770	char **args;
771
772	/* find and remember the next proc structure */
773	hp = (struct handle *)handle;
774	pp = *(hp->next_proc++);
775	hp->remaining--;
776
777	/* get the process's command name */
778	if ((pp->ki_flag & P_INMEM) == 0) {
779		/*
780		 * Print swapped processes as <pname>
781		 */
782		size_t len;
783
784		len = strlen(pp->ki_comm);
785		if (len > sizeof(pp->ki_comm) - 3)
786			len = sizeof(pp->ki_comm) - 3;
787		memmove(pp->ki_comm + 1, pp->ki_comm, len);
788		pp->ki_comm[0] = '<';
789		pp->ki_comm[len + 1] = '>';
790		pp->ki_comm[len + 2] = '\0';
791	}
792
793	/*
794	 * Convert the process's runtime from microseconds to seconds.  This
795	 * time includes the interrupt time although that is not wanted here.
796	 * ps(1) is similarly sloppy.
797	 */
798	cputime = (pp->ki_runtime + 500000) / 1000000;
799
800	/* calculate the base for cpu percentages */
801	pct = pctdouble(pp->ki_pctcpu);
802
803	/* generate "STATE" field */
804	switch (state = pp->ki_stat) {
805	case SRUN:
806		if (smpmode && pp->ki_oncpu != 0xff)
807			sprintf(status, "CPU%d", pp->ki_oncpu);
808		else
809			strcpy(status, "RUN");
810		break;
811	case SLOCK:
812		if (pp->ki_kiflag & KI_LOCKBLOCK) {
813			sprintf(status, "*%.6s", pp->ki_lockname);
814			break;
815		}
816		/* fall through */
817	case SSLEEP:
818		if (pp->ki_wmesg != NULL) {
819			sprintf(status, "%.6s", pp->ki_wmesg);
820			break;
821		}
822		/* FALLTHROUGH */
823	default:
824
825		if (state >= 0 &&
826		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
827			sprintf(status, "%.6s", state_abbrev[state]);
828		else
829			sprintf(status, "?%5d", state);
830		break;
831	}
832
833	cmdbuf = (char *)malloc(cmdlengthdelta + 1);
834	if (cmdbuf == NULL) {
835		warn("malloc(%d)", cmdlengthdelta + 1);
836		return NULL;
837	}
838
839	if (!(flags & FMT_SHOWARGS)) {
840		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
841		    pp->ki_ocomm[0]) {
842			snprintf(cmdbuf, cmdlengthdelta, "{%s}", pp->ki_ocomm);
843		} else {
844			snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
845		}
846	} else {
847		if (pp->ki_flag & P_SYSTEM ||
848		    pp->ki_args == NULL ||
849		    (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
850		    !(*args)) {
851			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
852		    	pp->ki_ocomm[0]) {
853				snprintf(cmdbuf, cmdlengthdelta,
854				    "{%s}", pp->ki_ocomm);
855			} else {
856				snprintf(cmdbuf, cmdlengthdelta,
857				    "[%s]", pp->ki_comm);
858			}
859		} else {
860			char *src, *dst, *argbuf;
861			char *cmd;
862			size_t argbuflen;
863			size_t len;
864
865			argbuflen = cmdlengthdelta * 4;
866			argbuf = (char *)malloc(argbuflen + 1);
867			if (argbuf == NULL) {
868				warn("malloc(%d)", argbuflen + 1);
869				free(cmdbuf);
870				return NULL;
871			}
872
873			dst = argbuf;
874
875			/* Extract cmd name from argv */
876			cmd = strrchr(*args, '/');
877			if (cmd == NULL)
878				cmd = *args;
879			else
880				cmd++;
881
882			for (; (src = *args++) != NULL; ) {
883				if (*src == '\0')
884					continue;
885				len = (argbuflen - (dst - argbuf) - 1) / 4;
886				strvisx(dst, src,
887				    strlen(src) < len ? strlen(src) : len,
888				    VIS_NL | VIS_CSTYLE);
889				while (*dst != '\0')
890					dst++;
891				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
892					*dst++ = ' '; /* add delimiting space */
893			}
894			if (dst != argbuf && dst[-1] == ' ')
895				dst--;
896			*dst = '\0';
897
898			if (strcmp(cmd, pp->ki_comm) != 0 )
899				snprintf(cmdbuf, cmdlengthdelta,
900				    "%s (%s)",argbuf,  pp->ki_comm);
901			else
902				strlcpy(cmdbuf, argbuf, cmdlengthdelta);
903
904			free(argbuf);
905		}
906	}
907
908	if (ps.jail == 0)
909		jid_buf[0] = '\0';
910	else
911		snprintf(jid_buf, sizeof(jid_buf), " %*d",
912		    sizeof(jid_buf) - 3, pp->ki_jid);
913
914	if (displaymode == DISP_IO) {
915		oldp = get_old_proc(pp);
916		if (oldp != NULL) {
917			ru.ru_inblock = RU(pp)->ru_inblock -
918			    RU(oldp)->ru_inblock;
919			ru.ru_oublock = RU(pp)->ru_oublock -
920			    RU(oldp)->ru_oublock;
921			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
922			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
923			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
924			rup = &ru;
925		} else {
926			rup = RU(pp);
927		}
928		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
929		s_tot = total_inblock + total_oublock + total_majflt;
930
931		sprintf(fmt, io_Proc_format,
932		    pp->ki_pid,
933		    jid_buf,
934		    namelength, namelength, (*get_userid)(pp->ki_ruid),
935		    rup->ru_nvcsw,
936		    rup->ru_nivcsw,
937		    rup->ru_inblock,
938		    rup->ru_oublock,
939		    rup->ru_majflt,
940		    p_tot,
941		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
942		    screen_width > cmdlengthdelta ?
943		    screen_width - cmdlengthdelta : 0,
944		    printable(cmdbuf));
945
946		free(cmdbuf);
947
948		return (fmt);
949	}
950
951	/* format this entry */
952	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
953	if (ps.thread != 0)
954		thr_buf[0] = '\0';
955	else
956		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
957		    sizeof(thr_buf) - 2, pp->ki_numthreads);
958
959	sprintf(fmt, proc_fmt,
960	    pp->ki_pid,
961	    jid_buf,
962	    namelength, namelength, (*get_userid)(pp->ki_ruid),
963	    thr_buf,
964	    pp->ki_pri.pri_level - PZERO,
965	    format_nice(pp),
966	    format_k2(PROCSIZE(pp)),
967	    format_k2(pagetok(pp->ki_rssize)),
968	    status,
969	    smpmode ? pp->ki_lastcpu : 0,
970	    format_time(cputime),
971	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
972	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
973	    printable(cmdbuf));
974
975	free(cmdbuf);
976
977	/* return the result */
978	return (fmt);
979}
980
981static void
982getsysctl(const char *name, void *ptr, size_t len)
983{
984	size_t nlen = len;
985
986	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
987		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
988		    strerror(errno));
989		quit(23);
990	}
991	if (nlen != len) {
992		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
993		    name, (unsigned long)len, (unsigned long)nlen);
994		quit(23);
995	}
996}
997
998static const char *
999format_nice(const struct kinfo_proc *pp)
1000{
1001	const char *fifo, *kthread;
1002	int rtpri;
1003	static char nicebuf[4 + 1];
1004
1005	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1006	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1007	switch (PRI_BASE(pp->ki_pri.pri_class)) {
1008	case PRI_ITHD:
1009		return ("-");
1010	case PRI_REALTIME:
1011		/*
1012		 * XXX: the kernel doesn't tell us the original rtprio and
1013		 * doesn't really know what it was, so to recover it we
1014		 * must be more chummy with the implementation than the
1015		 * implementation is with itself.  pri_user gives a
1016		 * constant "base" priority, but is only initialized
1017		 * properly for user threads.  pri_native gives what the
1018		 * kernel calls the "base" priority, but it isn't constant
1019		 * since it is changed by priority propagation.  pri_native
1020		 * also isn't properly initialized for all threads, but it
1021		 * is properly initialized for kernel realtime and idletime
1022		 * threads.  Thus we use pri_user for the base priority of
1023		 * user threads (it is always correct) and pri_native for
1024		 * the base priority of kernel realtime and idletime threads
1025		 * (there is nothing better, and it is usually correct).
1026		 *
1027		 * The field width and thus the buffer are too small for
1028		 * values like "kr31F", but such values shouldn't occur,
1029		 * and if they do then the tailing "F" is not displayed.
1030		 */
1031		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1032		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1033		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1034		    kthread, rtpri, fifo);
1035		break;
1036	case PRI_TIMESHARE:
1037		if (pp->ki_flag & P_KTHREAD)
1038			return ("-");
1039		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1040		break;
1041	case PRI_IDLE:
1042		/* XXX: as above. */
1043		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1044		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1045		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1046		    kthread, rtpri, fifo);
1047		break;
1048	default:
1049		return ("?");
1050	}
1051	return (nicebuf);
1052}
1053
1054/* comparison routines for qsort */
1055
1056static int
1057compare_pid(const void *p1, const void *p2)
1058{
1059	const struct kinfo_proc * const *pp1 = p1;
1060	const struct kinfo_proc * const *pp2 = p2;
1061
1062	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1063		abort();
1064
1065	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1066}
1067
1068/*
1069 *  proc_compare - comparison function for "qsort"
1070 *	Compares the resource consumption of two processes using five
1071 *	distinct keys.  The keys (in descending order of importance) are:
1072 *	percent cpu, cpu ticks, state, resident set size, total virtual
1073 *	memory usage.  The process states are ordered as follows (from least
1074 *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
1075 *	array declaration below maps a process state index into a number
1076 *	that reflects this ordering.
1077 */
1078
1079static int sorted_state[] = {
1080	0,	/* not used		*/
1081	3,	/* sleep		*/
1082	1,	/* ABANDONED (WAIT)	*/
1083	6,	/* run			*/
1084	5,	/* start		*/
1085	2,	/* zombie		*/
1086	4	/* stop			*/
1087};
1088
1089
1090#define ORDERKEY_PCTCPU(a, b) do { \
1091	long diff; \
1092	if (ps.wcpu) \
1093		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1094		    (b))) - \
1095		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1096		    (a))); \
1097	else \
1098		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1099	if (diff != 0) \
1100		return (diff > 0 ? 1 : -1); \
1101} while (0)
1102
1103#define ORDERKEY_CPTICKS(a, b) do { \
1104	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1105	if (diff != 0) \
1106		return (diff > 0 ? 1 : -1); \
1107} while (0)
1108
1109#define ORDERKEY_STATE(a, b) do { \
1110	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1111	if (diff != 0) \
1112		return (diff > 0 ? 1 : -1); \
1113} while (0)
1114
1115#define ORDERKEY_PRIO(a, b) do { \
1116	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1117	if (diff != 0) \
1118		return (diff > 0 ? 1 : -1); \
1119} while (0)
1120
1121#define	ORDERKEY_THREADS(a, b) do { \
1122	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1123	if (diff != 0) \
1124		return (diff > 0 ? 1 : -1); \
1125} while (0)
1126
1127#define ORDERKEY_RSSIZE(a, b) do { \
1128	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1129	if (diff != 0) \
1130		return (diff > 0 ? 1 : -1); \
1131} while (0)
1132
1133#define ORDERKEY_MEM(a, b) do { \
1134	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1135	if (diff != 0) \
1136		return (diff > 0 ? 1 : -1); \
1137} while (0)
1138
1139#define ORDERKEY_JID(a, b) do { \
1140	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1141	if (diff != 0) \
1142		return (diff > 0 ? 1 : -1); \
1143} while (0)
1144
1145/* compare_cpu - the comparison function for sorting by cpu percentage */
1146
1147int
1148#ifdef ORDER
1149compare_cpu(void *arg1, void *arg2)
1150#else
1151proc_compare(void *arg1, void *arg2)
1152#endif
1153{
1154	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1155	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1156
1157	ORDERKEY_PCTCPU(p1, p2);
1158	ORDERKEY_CPTICKS(p1, p2);
1159	ORDERKEY_STATE(p1, p2);
1160	ORDERKEY_PRIO(p1, p2);
1161	ORDERKEY_RSSIZE(p1, p2);
1162	ORDERKEY_MEM(p1, p2);
1163
1164	return (0);
1165}
1166
1167#ifdef ORDER
1168/* "cpu" compare routines */
1169int compare_size(), compare_res(), compare_time(), compare_prio(),
1170    compare_threads();
1171
1172/*
1173 * "io" compare routines.  Context switches aren't i/o, but are displayed
1174 * on the "io" display.
1175 */
1176int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1177    compare_vcsw(), compare_ivcsw();
1178
1179int (*compares[])() = {
1180	compare_cpu,
1181	compare_size,
1182	compare_res,
1183	compare_time,
1184	compare_prio,
1185	compare_threads,
1186	compare_iototal,
1187	compare_ioread,
1188	compare_iowrite,
1189	compare_iofault,
1190	compare_vcsw,
1191	compare_ivcsw,
1192	compare_jid,
1193	NULL
1194};
1195
1196/* compare_size - the comparison function for sorting by total memory usage */
1197
1198int
1199compare_size(void *arg1, void *arg2)
1200{
1201	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1202	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1203
1204	ORDERKEY_MEM(p1, p2);
1205	ORDERKEY_RSSIZE(p1, p2);
1206	ORDERKEY_PCTCPU(p1, p2);
1207	ORDERKEY_CPTICKS(p1, p2);
1208	ORDERKEY_STATE(p1, p2);
1209	ORDERKEY_PRIO(p1, p2);
1210
1211	return (0);
1212}
1213
1214/* compare_res - the comparison function for sorting by resident set size */
1215
1216int
1217compare_res(void *arg1, void *arg2)
1218{
1219	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1220	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1221
1222	ORDERKEY_RSSIZE(p1, p2);
1223	ORDERKEY_MEM(p1, p2);
1224	ORDERKEY_PCTCPU(p1, p2);
1225	ORDERKEY_CPTICKS(p1, p2);
1226	ORDERKEY_STATE(p1, p2);
1227	ORDERKEY_PRIO(p1, p2);
1228
1229	return (0);
1230}
1231
1232/* compare_time - the comparison function for sorting by total cpu time */
1233
1234int
1235compare_time(void *arg1, void *arg2)
1236{
1237	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1238	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1239
1240	ORDERKEY_CPTICKS(p1, p2);
1241	ORDERKEY_PCTCPU(p1, p2);
1242	ORDERKEY_STATE(p1, p2);
1243	ORDERKEY_PRIO(p1, p2);
1244	ORDERKEY_RSSIZE(p1, p2);
1245	ORDERKEY_MEM(p1, p2);
1246
1247	return (0);
1248}
1249
1250/* compare_prio - the comparison function for sorting by priority */
1251
1252int
1253compare_prio(void *arg1, void *arg2)
1254{
1255	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1256	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1257
1258	ORDERKEY_PRIO(p1, p2);
1259	ORDERKEY_CPTICKS(p1, p2);
1260	ORDERKEY_PCTCPU(p1, p2);
1261	ORDERKEY_STATE(p1, p2);
1262	ORDERKEY_RSSIZE(p1, p2);
1263	ORDERKEY_MEM(p1, p2);
1264
1265	return (0);
1266}
1267
1268/* compare_threads - the comparison function for sorting by threads */
1269int
1270compare_threads(void *arg1, void *arg2)
1271{
1272	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1273	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1274
1275	ORDERKEY_THREADS(p1, p2);
1276	ORDERKEY_PCTCPU(p1, p2);
1277	ORDERKEY_CPTICKS(p1, p2);
1278	ORDERKEY_STATE(p1, p2);
1279	ORDERKEY_PRIO(p1, p2);
1280	ORDERKEY_RSSIZE(p1, p2);
1281	ORDERKEY_MEM(p1, p2);
1282
1283	return (0);
1284}
1285
1286/* compare_jid - the comparison function for sorting by jid */
1287static int
1288compare_jid(const void *arg1, const void *arg2)
1289{
1290	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1291	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1292
1293	ORDERKEY_JID(p1, p2);
1294	ORDERKEY_PCTCPU(p1, p2);
1295	ORDERKEY_CPTICKS(p1, p2);
1296	ORDERKEY_STATE(p1, p2);
1297	ORDERKEY_PRIO(p1, p2);
1298	ORDERKEY_RSSIZE(p1, p2);
1299	ORDERKEY_MEM(p1, p2);
1300
1301	return (0);
1302}
1303#endif /* ORDER */
1304
1305/* assorted comparison functions for sorting by i/o */
1306
1307int
1308#ifdef ORDER
1309compare_iototal(void *arg1, void *arg2)
1310#else
1311io_compare(void *arg1, void *arg2)
1312#endif
1313{
1314	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1315	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1316
1317	return (get_io_total(p2) - get_io_total(p1));
1318}
1319
1320#ifdef ORDER
1321int
1322compare_ioread(void *arg1, void *arg2)
1323{
1324	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1325	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1326	long dummy, inp1, inp2;
1327
1328	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1329	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1330
1331	return (inp2 - inp1);
1332}
1333
1334int
1335compare_iowrite(void *arg1, void *arg2)
1336{
1337	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1338	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1339	long dummy, oup1, oup2;
1340
1341	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1342	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1343
1344	return (oup2 - oup1);
1345}
1346
1347int
1348compare_iofault(void *arg1, void *arg2)
1349{
1350	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1351	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1352	long dummy, flp1, flp2;
1353
1354	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1355	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1356
1357	return (flp2 - flp1);
1358}
1359
1360int
1361compare_vcsw(void *arg1, void *arg2)
1362{
1363	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1364	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1365	long dummy, flp1, flp2;
1366
1367	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1368	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1369
1370	return (flp2 - flp1);
1371}
1372
1373int
1374compare_ivcsw(void *arg1, void *arg2)
1375{
1376	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1377	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1378	long dummy, flp1, flp2;
1379
1380	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1381	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1382
1383	return (flp2 - flp1);
1384}
1385#endif /* ORDER */
1386
1387/*
1388 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1389 *		the process does not exist.
1390 *		It is EXTREMLY IMPORTANT that this function work correctly.
1391 *		If top runs setuid root (as in SVR4), then this function
1392 *		is the only thing that stands in the way of a serious
1393 *		security problem.  It validates requests for the "kill"
1394 *		and "renice" commands.
1395 */
1396
1397int
1398proc_owner(int pid)
1399{
1400	int cnt;
1401	struct kinfo_proc **prefp;
1402	struct kinfo_proc *pp;
1403
1404	prefp = pref;
1405	cnt = pref_len;
1406	while (--cnt >= 0) {
1407		pp = *prefp++;
1408		if (pp->ki_pid == (pid_t)pid)
1409			return ((int)pp->ki_ruid);
1410	}
1411	return (-1);
1412}
1413
1414static int
1415swapmode(int *retavail, int *retfree)
1416{
1417	int n;
1418	int pagesize = getpagesize();
1419	struct kvm_swap swapary[1];
1420
1421	*retavail = 0;
1422	*retfree = 0;
1423
1424#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1425
1426	n = kvm_getswapinfo(kd, swapary, 1, 0);
1427	if (n < 0 || swapary[0].ksw_total == 0)
1428		return (0);
1429
1430	*retavail = CONVERT(swapary[0].ksw_total);
1431	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1432
1433	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1434	return (n);
1435}
1436