1/*
2 * top - a top users display for Unix
3 *
4 * DESCRIPTION:
5 * Originally written for BSD4.4 system by Christos Zoulas.
6 * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
7 * Order support hacked in from top-3.5beta6/machine/m_aix41.c
8 *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
9 *
10 * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
11 *          Steven Wallace  <swallace@FreeBSD.org>
12 *          Wolfram Schneider <wosch@FreeBSD.org>
13 *          Thomas Moestl <tmoestl@gmx.net>
14 *          Eitan Adler <eadler@FreeBSD.org>
15 *
16 * $FreeBSD$
17 */
18
19#include <sys/errno.h>
20#include <sys/fcntl.h>
21#include <sys/param.h>
22#include <sys/priority.h>
23#include <sys/proc.h>
24#include <sys/resource.h>
25#include <sys/sbuf.h>
26#include <sys/sysctl.h>
27#include <sys/time.h>
28#include <sys/user.h>
29
30#include <assert.h>
31#include <err.h>
32#include <libgen.h>
33#include <kvm.h>
34#include <math.h>
35#include <paths.h>
36#include <stdio.h>
37#include <stdbool.h>
38#include <stdint.h>
39#include <stdlib.h>
40#include <string.h>
41#include <time.h>
42#include <unistd.h>
43#include <vis.h>
44
45#include "top.h"
46#include "display.h"
47#include "machine.h"
48#include "loadavg.h"
49#include "screen.h"
50#include "utils.h"
51#include "layout.h"
52
53#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
54
55extern struct timeval timeout;
56static int smpmode;
57enum displaymodes displaymode;
58static const int namelength = 10;
59/* TOP_JID_LEN based on max of 999999 */
60#define TOP_JID_LEN 6
61#define TOP_SWAP_LEN 5
62
63/* get_process_info passes back a handle.  This is what it looks like: */
64
65struct handle {
66	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
67	int remaining;			/* number of pointers remaining */
68};
69
70
71/* define what weighted cpu is.  */
72#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
73			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
74
75/* what we consider to be process size: */
76#define PROCSIZE(pp) ((pp)->ki_size / 1024)
77
78#define RU(pp)	(&(pp)->ki_rusage)
79
80#define	PCTCPU(pp) (pcpu[pp - pbase])
81
82/* process state names for the "STATE" column of the display */
83/* the extra nulls in the string "run" are for adding a slash and
84   the processor number when needed */
85
86static const char *state_abbrev[] = {
87	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
88};
89
90
91static kvm_t *kd;
92
93/* values that we stash away in _init and use in later routines */
94
95static double logcpu;
96
97/* these are retrieved from the kernel in _init */
98
99static load_avg  ccpu;
100
101/* these are used in the get_ functions */
102
103static int lastpid;
104
105/* these are for calculating cpu state percentages */
106
107static long cp_time[CPUSTATES];
108static long cp_old[CPUSTATES];
109static long cp_diff[CPUSTATES];
110
111/* these are for detailing the process states */
112
113static const char *procstatenames[] = {
114	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
115	" zombie, ", " waiting, ", " lock, ",
116	NULL
117};
118static int process_states[nitems(procstatenames)];
119
120/* these are for detailing the cpu states */
121
122static int cpu_states[CPUSTATES];
123static const char *cpustatenames[] = {
124	"user", "nice", "system", "interrupt", "idle", NULL
125};
126
127/* these are for detailing the memory statistics */
128
129static const char *memorynames[] = {
130	"K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
131	"K Free", NULL
132};
133static int memory_stats[nitems(memorynames)];
134
135static const char *arcnames[] = {
136	"K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
137	NULL
138};
139static int arc_stats[nitems(arcnames)];
140
141static const char *carcnames[] = {
142	"K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
143	NULL
144};
145static int carc_stats[nitems(carcnames)];
146
147static const char *swapnames[] = {
148	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
149	NULL
150};
151static int swap_stats[nitems(swapnames)];
152
153static int has_swap;
154
155/* these are for keeping track of the proc array */
156
157static int nproc;
158static int onproc = -1;
159static int pref_len;
160static struct kinfo_proc *pbase;
161static struct kinfo_proc **pref;
162static struct kinfo_proc *previous_procs;
163static struct kinfo_proc **previous_pref;
164static int previous_proc_count = 0;
165static int previous_proc_count_max = 0;
166static int previous_thread;
167
168/* data used for recalculating pctcpu */
169static double *pcpu;
170static struct timespec proc_uptime;
171static struct timeval proc_wall_time;
172static struct timeval previous_wall_time;
173static uint64_t previous_interval = 0;
174
175/* total number of io operations */
176static long total_inblock;
177static long total_oublock;
178static long total_majflt;
179
180/* these are for getting the memory statistics */
181
182static int arc_enabled;
183static int carc_enabled;
184static int pageshift;		/* log base 2 of the pagesize */
185
186/* define pagetok in terms of pageshift */
187
188#define pagetok(size) ((size) << pageshift)
189
190/* swap usage */
191#define ki_swap(kip) \
192    ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
193
194/*
195 * Sorting orders.  The first element is the default.
196 */
197static const char *ordernames[] = {
198	"cpu", "size", "res", "time", "pri", "threads",
199	"total", "read", "write", "fault", "vcsw", "ivcsw",
200	"jid", "swap", "pid", NULL
201};
202
203/* Per-cpu time states */
204static int maxcpu;
205static int maxid;
206static int ncpus;
207static unsigned long cpumask;
208static long *times;
209static long *pcpu_cp_time;
210static long *pcpu_cp_old;
211static long *pcpu_cp_diff;
212static int *pcpu_cpu_states;
213
214static int compare_swap(const void *a, const void *b);
215static int compare_jid(const void *a, const void *b);
216static int compare_pid(const void *a, const void *b);
217static int compare_tid(const void *a, const void *b);
218static const char *format_nice(const struct kinfo_proc *pp);
219static void getsysctl(const char *name, void *ptr, size_t len);
220static int swapmode(int *retavail, int *retfree);
221static void update_layout(void);
222static int find_uid(uid_t needle, int *haystack);
223
224static int
225find_uid(uid_t needle, int *haystack)
226{
227	size_t i = 0;
228
229	for (; i < TOP_MAX_UIDS; ++i)
230		if ((uid_t)haystack[i] == needle)
231			return 1;
232	return (0);
233}
234
235void
236toggle_pcpustats(void)
237{
238
239	if (ncpus == 1)
240		return;
241	update_layout();
242}
243
244/* Adjust display based on ncpus and the ARC state. */
245static void
246update_layout(void)
247{
248
249	y_mem = 3;
250	y_arc = 4;
251	y_carc = 5;
252	y_swap = 3 + arc_enabled + carc_enabled + has_swap;
253	y_idlecursor = 4 + arc_enabled + carc_enabled + has_swap;
254	y_message = 4 + arc_enabled + carc_enabled + has_swap;
255	y_header = 5 + arc_enabled + carc_enabled + has_swap;
256	y_procs = 6 + arc_enabled + carc_enabled + has_swap;
257	Header_lines = 6 + arc_enabled + carc_enabled + has_swap;
258
259	if (pcpu_stats) {
260		y_mem += ncpus - 1;
261		y_arc += ncpus - 1;
262		y_carc += ncpus - 1;
263		y_swap += ncpus - 1;
264		y_idlecursor += ncpus - 1;
265		y_message += ncpus - 1;
266		y_header += ncpus - 1;
267		y_procs += ncpus - 1;
268		Header_lines += ncpus - 1;
269	}
270}
271
272int
273machine_init(struct statics *statics)
274{
275	int i, j, empty, pagesize;
276	uint64_t arc_size;
277	int carc_en, nswapdev;
278	size_t size;
279
280	size = sizeof(smpmode);
281	if (sysctlbyname("kern.smp.active", &smpmode, &size, NULL, 0) != 0 ||
282	    size != sizeof(smpmode))
283		smpmode = 0;
284
285	size = sizeof(arc_size);
286	if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
287	    NULL, 0) == 0 && arc_size != 0)
288		arc_enabled = 1;
289	size = sizeof(carc_en);
290	if (arc_enabled &&
291	    sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
292	    NULL, 0) == 0 && carc_en == 1)
293		carc_enabled = 1;
294
295	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
296	if (kd == NULL)
297		return (-1);
298
299	size = sizeof(nswapdev);
300	if (sysctlbyname("vm.nswapdev", &nswapdev, &size, NULL,
301		0) == 0 && nswapdev != 0)
302			has_swap = 1;
303
304	GETSYSCTL("kern.ccpu", ccpu);
305
306	/* this is used in calculating WCPU -- calculate it ahead of time */
307	logcpu = log(loaddouble(ccpu));
308
309	pbase = NULL;
310	pref = NULL;
311	pcpu = NULL;
312	nproc = 0;
313	onproc = -1;
314
315	/* get the page size and calculate pageshift from it */
316	pagesize = getpagesize();
317	pageshift = 0;
318	while (pagesize > 1) {
319		pageshift++;
320		pagesize >>= 1;
321	}
322
323	/* we only need the amount of log(2)1024 for our conversion */
324	pageshift -= LOG1024;
325
326	/* fill in the statics information */
327	statics->procstate_names = procstatenames;
328	statics->cpustate_names = cpustatenames;
329	statics->memory_names = memorynames;
330	if (arc_enabled)
331		statics->arc_names = arcnames;
332	else
333		statics->arc_names = NULL;
334	if (carc_enabled)
335		statics->carc_names = carcnames;
336	else
337		statics->carc_names = NULL;
338	if (has_swap)
339		statics->swap_names = swapnames;
340	else
341		statics->swap_names = NULL;
342	statics->order_names = ordernames;
343
344	/* Allocate state for per-CPU stats. */
345	cpumask = 0;
346	ncpus = 0;
347	GETSYSCTL("kern.smp.maxcpus", maxcpu);
348	times = calloc(maxcpu * CPUSTATES, sizeof(long));
349	if (times == NULL)
350		err(1, "calloc for kern.smp.maxcpus");
351	size = sizeof(long) * maxcpu * CPUSTATES;
352	if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
353		err(1, "sysctlbyname kern.cp_times");
354	pcpu_cp_time = calloc(1, size);
355	maxid = (size / CPUSTATES / sizeof(long)) - 1;
356	for (i = 0; i <= maxid; i++) {
357		empty = 1;
358		for (j = 0; empty && j < CPUSTATES; j++) {
359			if (times[i * CPUSTATES + j] != 0)
360				empty = 0;
361		}
362		if (!empty) {
363			cpumask |= (1ul << i);
364			ncpus++;
365		}
366	}
367	assert(ncpus > 0);
368	pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
369	pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
370	pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
371	statics->ncpus = ncpus;
372
373	update_layout();
374
375	/* all done! */
376	return (0);
377}
378
379char *
380format_header(const char *uname_field)
381{
382	static struct sbuf* header = NULL;
383
384	/* clean up from last time. */
385	if (header != NULL) {
386		sbuf_clear(header);
387	} else {
388		header = sbuf_new_auto();
389	}
390
391	switch (displaymode) {
392	case DISP_CPU: {
393		sbuf_printf(header, "  %s", ps.thread_id ? " THR" : "PID");
394		sbuf_printf(header, "%*s", ps.jail ? TOP_JID_LEN : 0,
395									ps.jail ? " JID" : "");
396		sbuf_printf(header, " %-*.*s  ", namelength, namelength, uname_field);
397		if (!ps.thread) {
398			sbuf_cat(header, "THR ");
399		}
400		sbuf_cat(header, "PRI NICE   SIZE    RES ");
401		if (ps.swap) {
402			sbuf_printf(header, "%*s ", TOP_SWAP_LEN - 1, "SWAP");
403		}
404		sbuf_cat(header, "STATE    ");
405		if (smpmode) {
406			sbuf_cat(header, "C   ");
407		}
408		sbuf_cat(header, "TIME ");
409		sbuf_printf(header, " %6s ", ps.wcpu ? "WCPU" : "CPU");
410		sbuf_cat(header, "COMMAND");
411		sbuf_finish(header);
412		break;
413	}
414	case DISP_IO: {
415		sbuf_printf(header, "  %s%*s %-*.*s",
416			ps.thread_id ? " THR" : "PID",
417		    ps.jail ? TOP_JID_LEN : 0, ps.jail ? " JID" : "",
418		    namelength, namelength, uname_field);
419		sbuf_cat(header, "   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND");
420		sbuf_finish(header);
421		break;
422	}
423	case DISP_MAX:
424		assert("displaymode must not be set to DISP_MAX");
425	}
426
427	return sbuf_data(header);
428}
429
430static int swappgsin = -1;
431static int swappgsout = -1;
432
433
434void
435get_system_info(struct system_info *si)
436{
437	struct loadavg sysload;
438	int mib[2];
439	struct timeval boottime;
440	uint64_t arc_stat, arc_stat2;
441	int i, j;
442	size_t size;
443
444	/* get the CPU stats */
445	size = (maxid + 1) * CPUSTATES * sizeof(long);
446	if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
447		err(1, "sysctlbyname kern.cp_times");
448	GETSYSCTL("kern.cp_time", cp_time);
449	GETSYSCTL("vm.loadavg", sysload);
450	GETSYSCTL("kern.lastpid", lastpid);
451
452	/* convert load averages to doubles */
453	for (i = 0; i < 3; i++)
454		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
455
456	/* convert cp_time counts to percentages */
457	for (i = j = 0; i <= maxid; i++) {
458		if ((cpumask & (1ul << i)) == 0)
459			continue;
460		percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
461		    &pcpu_cp_time[j * CPUSTATES],
462		    &pcpu_cp_old[j * CPUSTATES],
463		    &pcpu_cp_diff[j * CPUSTATES]);
464		j++;
465	}
466	percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
467
468	/* sum memory & swap statistics */
469	{
470		static unsigned int swap_delay = 0;
471		static int swapavail = 0;
472		static int swapfree = 0;
473		static long bufspace = 0;
474		static uint64_t nspgsin, nspgsout;
475
476		GETSYSCTL("vfs.bufspace", bufspace);
477		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
478		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
479		GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
480		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
481		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
482		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
483		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
484		/* convert memory stats to Kbytes */
485		memory_stats[0] = pagetok(memory_stats[0]);
486		memory_stats[1] = pagetok(memory_stats[1]);
487		memory_stats[2] = pagetok(memory_stats[2]);
488		memory_stats[3] = pagetok(memory_stats[3]);
489		memory_stats[4] = bufspace / 1024;
490		memory_stats[5] = pagetok(memory_stats[5]);
491		memory_stats[6] = -1;
492
493		/* first interval */
494		if (swappgsin < 0) {
495			swap_stats[4] = 0;
496			swap_stats[5] = 0;
497		}
498
499		/* compute differences between old and new swap statistic */
500		else {
501			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
502			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
503		}
504
505		swappgsin = nspgsin;
506		swappgsout = nspgsout;
507
508		/* call CPU heavy swapmode() only for changes */
509		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
510			swap_stats[3] = swapmode(&swapavail, &swapfree);
511			swap_stats[0] = swapavail;
512			swap_stats[1] = swapavail - swapfree;
513			swap_stats[2] = swapfree;
514		}
515		swap_delay = 1;
516		swap_stats[6] = -1;
517	}
518
519	if (arc_enabled) {
520		GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
521		arc_stats[0] = arc_stat >> 10;
522		GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
523		arc_stats[1] = arc_stat >> 10;
524		GETSYSCTL("vfs.zfs.mru_size", arc_stat);
525		arc_stats[2] = arc_stat >> 10;
526		GETSYSCTL("vfs.zfs.anon_size", arc_stat);
527		arc_stats[3] = arc_stat >> 10;
528		GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
529		GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
530		arc_stats[4] = (arc_stat + arc_stat2) >> 10;
531		GETSYSCTL("kstat.zfs.misc.arcstats.bonus_size", arc_stat);
532		arc_stats[5] = arc_stat >> 10;
533		GETSYSCTL("kstat.zfs.misc.arcstats.dnode_size", arc_stat);
534		arc_stats[5] += arc_stat >> 10;
535		GETSYSCTL("kstat.zfs.misc.arcstats.dbuf_size", arc_stat);
536		arc_stats[5] += arc_stat >> 10;
537		si->arc = arc_stats;
538	}
539	if (carc_enabled) {
540		GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
541		carc_stats[0] = arc_stat >> 10;
542		carc_stats[2] = arc_stat >> 10; /* For ratio */
543		GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
544		carc_stats[1] = arc_stat >> 10;
545		si->carc = carc_stats;
546	}
547
548	/* set arrays and strings */
549	if (pcpu_stats) {
550		si->cpustates = pcpu_cpu_states;
551		si->ncpus = ncpus;
552	} else {
553		si->cpustates = cpu_states;
554		si->ncpus = 1;
555	}
556	si->memory = memory_stats;
557	si->swap = swap_stats;
558
559
560	if (lastpid > 0) {
561		si->last_pid = lastpid;
562	} else {
563		si->last_pid = -1;
564	}
565
566	/*
567	 * Print how long system has been up.
568	 * (Found by looking getting "boottime" from the kernel)
569	 */
570	mib[0] = CTL_KERN;
571	mib[1] = KERN_BOOTTIME;
572	size = sizeof(boottime);
573	if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
574	    boottime.tv_sec != 0) {
575		si->boottime = boottime;
576	} else {
577		si->boottime.tv_sec = -1;
578	}
579}
580
581#define NOPROC	((void *)-1)
582
583/*
584 * We need to compare data from the old process entry with the new
585 * process entry.
586 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
587 * structure to cache the mapping.  We also use a negative cache pointer
588 * of NOPROC to avoid duplicate lookups.
589 * XXX: this could be done when the actual processes are fetched, we do
590 * it here out of laziness.
591 */
592static const struct kinfo_proc *
593get_old_proc(struct kinfo_proc *pp)
594{
595	const struct kinfo_proc * const *oldpp, *oldp;
596
597	/*
598	 * If this is the first fetch of the kinfo_procs then we don't have
599	 * any previous entries.
600	 */
601	if (previous_proc_count == 0)
602		return (NULL);
603	/* negative cache? */
604	if (pp->ki_udata == NOPROC)
605		return (NULL);
606	/* cached? */
607	if (pp->ki_udata != NULL)
608		return (pp->ki_udata);
609	/*
610	 * Not cached,
611	 * 1) look up based on pid.
612	 * 2) compare process start.
613	 * If we fail here, then setup a negative cache entry, otherwise
614	 * cache it.
615	 */
616	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
617	    sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
618	if (oldpp == NULL) {
619		pp->ki_udata = NOPROC;
620		return (NULL);
621	}
622	oldp = *oldpp;
623	if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
624		pp->ki_udata = NOPROC;
625		return (NULL);
626	}
627	pp->ki_udata = __DECONST(void *, oldp);
628	return (oldp);
629}
630
631/*
632 * Return the total amount of IO done in blocks in/out and faults.
633 * store the values individually in the pointers passed in.
634 */
635static long
636get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
637    long *vcsw, long *ivcsw)
638{
639	const struct kinfo_proc *oldp;
640	static struct kinfo_proc dummy;
641	long ret;
642
643	oldp = get_old_proc(__DECONST(struct kinfo_proc *, pp));
644	if (oldp == NULL) {
645		memset(&dummy, 0, sizeof(dummy));
646		oldp = &dummy;
647	}
648	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
649	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
650	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
651	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
652	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
653	ret =
654	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
655	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
656	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
657	return (ret);
658}
659
660/*
661 * If there was a previous update, use the delta in ki_runtime over
662 * the previous interval to calculate pctcpu.  Otherwise, fall back
663 * to using the kernel's ki_pctcpu.
664 */
665static double
666proc_calc_pctcpu(struct kinfo_proc *pp)
667{
668	const struct kinfo_proc *oldp;
669
670	if (previous_interval != 0) {
671		oldp = get_old_proc(pp);
672		if (oldp != NULL)
673			return ((double)(pp->ki_runtime - oldp->ki_runtime)
674			    / previous_interval);
675
676		/*
677		 * If this process/thread was created during the previous
678		 * interval, charge it's total runtime to the previous
679		 * interval.
680		 */
681		else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
682		    (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
683		    pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
684			return ((double)pp->ki_runtime / previous_interval);
685	}
686	return (pctdouble(pp->ki_pctcpu));
687}
688
689/*
690 * Return true if this process has used any CPU time since the
691 * previous update.
692 */
693static int
694proc_used_cpu(struct kinfo_proc *pp)
695{
696	const struct kinfo_proc *oldp;
697
698	oldp = get_old_proc(pp);
699	if (oldp == NULL)
700		return (PCTCPU(pp) != 0);
701	return (pp->ki_runtime != oldp->ki_runtime ||
702	    RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
703	    RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
704}
705
706/*
707 * Return the total number of block in/out and faults by a process.
708 */
709static long
710get_io_total(const struct kinfo_proc *pp)
711{
712	long dummy;
713
714	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
715}
716
717static struct handle handle;
718
719void *
720get_process_info(struct system_info *si, struct process_select *sel,
721    int (*compare)(const void *, const void *))
722{
723	int i;
724	int total_procs;
725	long p_io;
726	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
727	long nsec;
728	int active_procs;
729	struct kinfo_proc **prefp;
730	struct kinfo_proc *pp;
731	struct timespec previous_proc_uptime;
732
733	/*
734	 * If thread state was toggled, don't cache the previous processes.
735	 */
736	if (previous_thread != sel->thread)
737		nproc = 0;
738	previous_thread = sel->thread;
739
740	/*
741	 * Save the previous process info.
742	 */
743	if (previous_proc_count_max < nproc) {
744		free(previous_procs);
745		previous_procs = calloc(nproc, sizeof(*previous_procs));
746		free(previous_pref);
747		previous_pref = calloc(nproc, sizeof(*previous_pref));
748		if (previous_procs == NULL || previous_pref == NULL) {
749			fprintf(stderr, "top: Out of memory.\n");
750			quit(TOP_EX_SYS_ERROR);
751		}
752		previous_proc_count_max = nproc;
753	}
754	if (nproc) {
755		for (i = 0; i < nproc; i++)
756			previous_pref[i] = &previous_procs[i];
757		memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
758		qsort(previous_pref, nproc, sizeof(*previous_pref),
759		    ps.thread ? compare_tid : compare_pid);
760	}
761	previous_proc_count = nproc;
762	previous_proc_uptime = proc_uptime;
763	previous_wall_time = proc_wall_time;
764	previous_interval = 0;
765
766	pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
767	    0, &nproc);
768	gettimeofday(&proc_wall_time, NULL);
769	if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
770		memset(&proc_uptime, 0, sizeof(proc_uptime));
771	else if (previous_proc_uptime.tv_sec != 0 &&
772	    previous_proc_uptime.tv_nsec != 0) {
773		previous_interval = (proc_uptime.tv_sec -
774		    previous_proc_uptime.tv_sec) * 1000000;
775		nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
776		if (nsec < 0) {
777			previous_interval -= 1000000;
778			nsec += 1000000000;
779		}
780		previous_interval += nsec / 1000;
781	}
782	if (nproc > onproc) {
783		pref = realloc(pref, sizeof(*pref) * nproc);
784		pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
785		onproc = nproc;
786	}
787	if (pref == NULL || pbase == NULL || pcpu == NULL) {
788		fprintf(stderr, "top: Out of memory.\n");
789		quit(TOP_EX_SYS_ERROR);
790	}
791	/* get a pointer to the states summary array */
792	si->procstates = process_states;
793
794	/* count up process states and get pointers to interesting procs */
795	total_procs = 0;
796	active_procs = 0;
797	total_inblock = 0;
798	total_oublock = 0;
799	total_majflt = 0;
800	memset(process_states, 0, sizeof(process_states));
801	prefp = pref;
802	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
803
804		if (pp->ki_stat == 0)
805			/* not in use */
806			continue;
807
808		if (!sel->self && pp->ki_pid == mypid && sel->pid == -1)
809			/* skip self */
810			continue;
811
812		if (!sel->system && (pp->ki_flag & P_SYSTEM) && sel->pid == -1)
813			/* skip system process */
814			continue;
815
816		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
817		    &p_vcsw, &p_ivcsw);
818		total_inblock += p_inblock;
819		total_oublock += p_oublock;
820		total_majflt += p_majflt;
821		total_procs++;
822		process_states[(unsigned char)pp->ki_stat]++;
823
824		if (pp->ki_stat == SZOMB)
825			/* skip zombies */
826			continue;
827
828		if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD && sel->pid == -1)
829			/* skip kernel idle process */
830			continue;
831
832		PCTCPU(pp) = proc_calc_pctcpu(pp);
833		if (sel->thread && PCTCPU(pp) > 1.0)
834			PCTCPU(pp) = 1.0;
835		if (displaymode == DISP_CPU && !sel->idle &&
836		    (!proc_used_cpu(pp) ||
837		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
838			/* skip idle or non-running processes */
839			continue;
840
841		if (displaymode == DISP_IO && !sel->idle && p_io == 0)
842			/* skip processes that aren't doing I/O */
843			continue;
844
845		if (sel->jid != -1 && pp->ki_jid != sel->jid)
846			/* skip proc. that don't belong to the selected JID */
847			continue;
848
849		if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
850			/* skip proc. that don't belong to the selected UID */
851			continue;
852
853		if (sel->pid != -1 && pp->ki_pid != sel->pid)
854			continue;
855
856		*prefp++ = pp;
857		active_procs++;
858	}
859
860	/* if requested, sort the "interesting" processes */
861	if (compare != NULL)
862		qsort(pref, active_procs, sizeof(*pref), compare);
863
864	/* remember active and total counts */
865	si->p_total = total_procs;
866	si->p_pactive = pref_len = active_procs;
867
868	/* pass back a handle */
869	handle.next_proc = pref;
870	handle.remaining = active_procs;
871	return (&handle);
872}
873
874char *
875format_next_process(struct handle * xhandle, char *(*get_userid)(int), int flags)
876{
877	struct kinfo_proc *pp;
878	const struct kinfo_proc *oldp;
879	long cputime;
880	char status[22];
881	size_t state;
882	struct rusage ru, *rup;
883	long p_tot, s_tot;
884	char *cmdbuf = NULL;
885	char **args;
886	static struct sbuf* procbuf = NULL;
887
888	/* clean up from last time. */
889	if (procbuf != NULL) {
890		sbuf_clear(procbuf);
891	} else {
892		procbuf = sbuf_new_auto();
893	}
894
895
896	/* find and remember the next proc structure */
897	pp = *(xhandle->next_proc++);
898	xhandle->remaining--;
899
900	/* get the process's command name */
901	if ((pp->ki_flag & P_INMEM) == 0) {
902		/*
903		 * Print swapped processes as <pname>
904		 */
905		size_t len;
906
907		len = strlen(pp->ki_comm);
908		if (len > sizeof(pp->ki_comm) - 3)
909			len = sizeof(pp->ki_comm) - 3;
910		memmove(pp->ki_comm + 1, pp->ki_comm, len);
911		pp->ki_comm[0] = '<';
912		pp->ki_comm[len + 1] = '>';
913		pp->ki_comm[len + 2] = '\0';
914	}
915
916	/*
917	 * Convert the process's runtime from microseconds to seconds.  This
918	 * time includes the interrupt time although that is not wanted here.
919	 * ps(1) is similarly sloppy.
920	 */
921	cputime = (pp->ki_runtime + 500000) / 1000000;
922
923	/* generate "STATE" field */
924	switch (state = pp->ki_stat) {
925	case SRUN:
926		if (smpmode && pp->ki_oncpu != NOCPU)
927			sprintf(status, "CPU%d", pp->ki_oncpu);
928		else
929			strcpy(status, "RUN");
930		break;
931	case SLOCK:
932		if (pp->ki_kiflag & KI_LOCKBLOCK) {
933			sprintf(status, "*%.6s", pp->ki_lockname);
934			break;
935		}
936		/* fall through */
937	case SSLEEP:
938		sprintf(status, "%.6s", pp->ki_wmesg);
939		break;
940	default:
941
942		if (state < nitems(state_abbrev)) {
943			sprintf(status, "%.6s", state_abbrev[state]);
944		} else {
945			sprintf(status, "?%5zu", state);
946		}
947		break;
948	}
949
950	cmdbuf = calloc(screen_width + 1, 1);
951	if (cmdbuf == NULL) {
952		warn("calloc(%d)", screen_width + 1);
953		return NULL;
954	}
955
956	if (!(flags & FMT_SHOWARGS)) {
957		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
958		    pp->ki_tdname[0]) {
959			snprintf(cmdbuf, screen_width, "%s{%s%s}", pp->ki_comm,
960			    pp->ki_tdname, pp->ki_moretdname);
961		} else {
962			snprintf(cmdbuf, screen_width, "%s", pp->ki_comm);
963		}
964	} else {
965		if (pp->ki_flag & P_SYSTEM ||
966		    (args = kvm_getargv(kd, pp, screen_width)) == NULL ||
967		    !(*args)) {
968			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
969		    	    pp->ki_tdname[0]) {
970				snprintf(cmdbuf, screen_width,
971				    "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
972				    pp->ki_moretdname);
973			} else {
974				snprintf(cmdbuf, screen_width,
975				    "[%s]", pp->ki_comm);
976			}
977		} else {
978			const char *src;
979			char *dst, *argbuf;
980			const char *cmd;
981			size_t argbuflen;
982			size_t len;
983
984			argbuflen = screen_width * 4;
985			argbuf = calloc(argbuflen + 1, 1);
986			if (argbuf == NULL) {
987				warn("calloc(%zu)", argbuflen + 1);
988				free(cmdbuf);
989				return NULL;
990			}
991
992			dst = argbuf;
993
994			/* Extract cmd name from argv */
995			cmd = basename(*args);
996
997			for (; (src = *args++) != NULL; ) {
998				if (*src == '\0')
999					continue;
1000				len = (argbuflen - (dst - argbuf) - 1) / 4;
1001				strvisx(dst, src,
1002				    MIN(strlen(src), len),
1003				    VIS_NL | VIS_CSTYLE);
1004				while (*dst != '\0')
1005					dst++;
1006				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1007					*dst++ = ' '; /* add delimiting space */
1008			}
1009			if (dst != argbuf && dst[-1] == ' ')
1010				dst--;
1011			*dst = '\0';
1012
1013			if (strcmp(cmd, pp->ki_comm) != 0) {
1014				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1015				    pp->ki_tdname[0])
1016					snprintf(cmdbuf, screen_width,
1017					    "%s (%s){%s%s}", argbuf,
1018					    pp->ki_comm, pp->ki_tdname,
1019					    pp->ki_moretdname);
1020				else
1021					snprintf(cmdbuf, screen_width,
1022					    "%s (%s)", argbuf, pp->ki_comm);
1023			} else {
1024				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1025				    pp->ki_tdname[0])
1026					snprintf(cmdbuf, screen_width,
1027					    "%s{%s%s}", argbuf, pp->ki_tdname,
1028					    pp->ki_moretdname);
1029				else
1030					strlcpy(cmdbuf, argbuf, screen_width);
1031			}
1032			free(argbuf);
1033		}
1034	}
1035
1036	if (displaymode == DISP_IO) {
1037		oldp = get_old_proc(pp);
1038		if (oldp != NULL) {
1039			ru.ru_inblock = RU(pp)->ru_inblock -
1040			    RU(oldp)->ru_inblock;
1041			ru.ru_oublock = RU(pp)->ru_oublock -
1042			    RU(oldp)->ru_oublock;
1043			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1044			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1045			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1046			rup = &ru;
1047		} else {
1048			rup = RU(pp);
1049		}
1050		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1051		s_tot = total_inblock + total_oublock + total_majflt;
1052
1053		sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1054
1055		if (ps.jail) {
1056			sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1057		}
1058		sbuf_printf(procbuf, "%-*.*s", namelength, namelength, (*get_userid)(pp->ki_ruid));
1059		sbuf_printf(procbuf, "%6ld ", rup->ru_nvcsw);
1060		sbuf_printf(procbuf, "%6ld ", rup->ru_nivcsw);
1061		sbuf_printf(procbuf, "%6ld ", rup->ru_inblock);
1062		sbuf_printf(procbuf, "%6ld ", rup->ru_oublock);
1063		sbuf_printf(procbuf, "%6ld ", rup->ru_majflt);
1064		sbuf_printf(procbuf, "%6ld ", p_tot);
1065		sbuf_printf(procbuf, "%6.2f%% ", s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot));
1066
1067	} else {
1068		sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1069		if (ps.jail) {
1070			sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1071		}
1072		sbuf_printf(procbuf, "%-*.*s ", namelength, namelength, (*get_userid)(pp->ki_ruid));
1073
1074		if (!ps.thread) {
1075			sbuf_printf(procbuf, "%4d ", pp->ki_numthreads);
1076		} else {
1077			sbuf_printf(procbuf, " ");
1078		}
1079
1080		sbuf_printf(procbuf, "%3d ", pp->ki_pri.pri_level - PZERO);
1081		sbuf_printf(procbuf, "%4s", format_nice(pp));
1082		sbuf_printf(procbuf, "%7s ", format_k(PROCSIZE(pp)));
1083		sbuf_printf(procbuf, "%6s ", format_k(pagetok(pp->ki_rssize)));
1084		if (ps.swap) {
1085			sbuf_printf(procbuf, "%*s ",
1086				TOP_SWAP_LEN - 1,
1087				format_k(pagetok(ki_swap(pp))));
1088		}
1089		sbuf_printf(procbuf, "%-6.6s ", status);
1090		if (smpmode) {
1091			int cpu;
1092			if (state == SRUN && pp->ki_oncpu != NOCPU) {
1093				cpu = pp->ki_oncpu;
1094			} else {
1095				cpu = pp->ki_lastcpu;
1096			}
1097			sbuf_printf(procbuf, "%3d ", cpu);
1098		}
1099		sbuf_printf(procbuf, "%6s ", format_time(cputime));
1100		sbuf_printf(procbuf, "%6.2f%% ", ps.wcpu ? 100.0 * weighted_cpu(PCTCPU(pp), pp) : 100.0 * PCTCPU(pp));
1101	}
1102	sbuf_printf(procbuf, "%s", printable(cmdbuf));
1103	free(cmdbuf);
1104	return (sbuf_data(procbuf));
1105}
1106
1107static void
1108getsysctl(const char *name, void *ptr, size_t len)
1109{
1110	size_t nlen = len;
1111
1112	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1113		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1114		    strerror(errno));
1115		quit(TOP_EX_SYS_ERROR);
1116	}
1117	if (nlen != len) {
1118		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1119		    name, (unsigned long)len, (unsigned long)nlen);
1120		quit(TOP_EX_SYS_ERROR);
1121	}
1122}
1123
1124static const char *
1125format_nice(const struct kinfo_proc *pp)
1126{
1127	const char *fifo, *kproc;
1128	int rtpri;
1129	static char nicebuf[4 + 1];
1130
1131	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1132	kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1133	switch (PRI_BASE(pp->ki_pri.pri_class)) {
1134	case PRI_ITHD:
1135		return ("-");
1136	case PRI_REALTIME:
1137		/*
1138		 * XXX: the kernel doesn't tell us the original rtprio and
1139		 * doesn't really know what it was, so to recover it we
1140		 * must be more chummy with the implementation than the
1141		 * implementation is with itself.  pri_user gives a
1142		 * constant "base" priority, but is only initialized
1143		 * properly for user threads.  pri_native gives what the
1144		 * kernel calls the "base" priority, but it isn't constant
1145		 * since it is changed by priority propagation.  pri_native
1146		 * also isn't properly initialized for all threads, but it
1147		 * is properly initialized for kernel realtime and idletime
1148		 * threads.  Thus we use pri_user for the base priority of
1149		 * user threads (it is always correct) and pri_native for
1150		 * the base priority of kernel realtime and idletime threads
1151		 * (there is nothing better, and it is usually correct).
1152		 *
1153		 * The field width and thus the buffer are too small for
1154		 * values like "kr31F", but such values shouldn't occur,
1155		 * and if they do then the tailing "F" is not displayed.
1156		 */
1157		rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1158		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1159		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1160		    kproc, rtpri, fifo);
1161		break;
1162	case PRI_TIMESHARE:
1163		if (pp->ki_flag & P_KPROC)
1164			return ("-");
1165		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1166		break;
1167	case PRI_IDLE:
1168		/* XXX: as above. */
1169		rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1170		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1171		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1172		    kproc, rtpri, fifo);
1173		break;
1174	default:
1175		return ("?");
1176	}
1177	return (nicebuf);
1178}
1179
1180/* comparison routines for qsort */
1181
1182static int
1183compare_pid(const void *p1, const void *p2)
1184{
1185	const struct kinfo_proc * const *pp1 = p1;
1186	const struct kinfo_proc * const *pp2 = p2;
1187
1188	assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1189
1190	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1191}
1192
1193static int
1194compare_tid(const void *p1, const void *p2)
1195{
1196	const struct kinfo_proc * const *pp1 = p1;
1197	const struct kinfo_proc * const *pp2 = p2;
1198
1199	assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1200
1201	return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1202}
1203
1204/*
1205 *  proc_compare - comparison function for "qsort"
1206 *	Compares the resource consumption of two processes using five
1207 *	distinct keys.  The keys (in descending order of importance) are:
1208 *	percent cpu, cpu ticks, state, resident set size, total virtual
1209 *	memory usage.  The process states are ordered as follows (from least
1210 *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
1211 *	array declaration below maps a process state index into a number
1212 *	that reflects this ordering.
1213 */
1214
1215static int sorted_state[] = {
1216	0,	/* not used		*/
1217	3,	/* sleep		*/
1218	1,	/* ABANDONED (WAIT)	*/
1219	6,	/* run			*/
1220	5,	/* start		*/
1221	2,	/* zombie		*/
1222	4	/* stop			*/
1223};
1224
1225
1226#define ORDERKEY_PCTCPU(a, b) do { \
1227	double diff; \
1228	if (ps.wcpu) \
1229		diff = weighted_cpu(PCTCPU((b)), (b)) - \
1230		    weighted_cpu(PCTCPU((a)), (a)); \
1231	else \
1232		diff = PCTCPU((b)) - PCTCPU((a)); \
1233	if (diff != 0) \
1234		return (diff > 0 ? 1 : -1); \
1235} while (0)
1236
1237#define ORDERKEY_CPTICKS(a, b) do { \
1238	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1239	if (diff != 0) \
1240		return (diff > 0 ? 1 : -1); \
1241} while (0)
1242
1243#define ORDERKEY_STATE(a, b) do { \
1244	int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1245	if (diff != 0) \
1246		return (diff > 0 ? 1 : -1); \
1247} while (0)
1248
1249#define ORDERKEY_PRIO(a, b) do { \
1250	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1251	if (diff != 0) \
1252		return (diff > 0 ? 1 : -1); \
1253} while (0)
1254
1255#define	ORDERKEY_THREADS(a, b) do { \
1256	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1257	if (diff != 0) \
1258		return (diff > 0 ? 1 : -1); \
1259} while (0)
1260
1261#define ORDERKEY_RSSIZE(a, b) do { \
1262	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1263	if (diff != 0) \
1264		return (diff > 0 ? 1 : -1); \
1265} while (0)
1266
1267#define ORDERKEY_MEM(a, b) do { \
1268	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1269	if (diff != 0) \
1270		return (diff > 0 ? 1 : -1); \
1271} while (0)
1272
1273#define ORDERKEY_JID(a, b) do { \
1274	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1275	if (diff != 0) \
1276		return (diff > 0 ? 1 : -1); \
1277} while (0)
1278
1279#define ORDERKEY_SWAP(a, b) do { \
1280	int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1281	if (diff != 0) \
1282		return (diff > 0 ? 1 : -1); \
1283} while (0)
1284
1285/* compare_cpu - the comparison function for sorting by cpu percentage */
1286
1287static int
1288compare_cpu(const void *arg1, const void *arg2)
1289{
1290	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1291	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1292
1293	ORDERKEY_PCTCPU(p1, p2);
1294	ORDERKEY_CPTICKS(p1, p2);
1295	ORDERKEY_STATE(p1, p2);
1296	ORDERKEY_PRIO(p1, p2);
1297	ORDERKEY_RSSIZE(p1, p2);
1298	ORDERKEY_MEM(p1, p2);
1299
1300	return (0);
1301}
1302
1303/* compare_size - the comparison function for sorting by total memory usage */
1304
1305static int
1306compare_size(const void *arg1, const void *arg2)
1307{
1308	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1309	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1310
1311	ORDERKEY_MEM(p1, p2);
1312	ORDERKEY_RSSIZE(p1, p2);
1313	ORDERKEY_PCTCPU(p1, p2);
1314	ORDERKEY_CPTICKS(p1, p2);
1315	ORDERKEY_STATE(p1, p2);
1316	ORDERKEY_PRIO(p1, p2);
1317
1318	return (0);
1319}
1320
1321/* compare_res - the comparison function for sorting by resident set size */
1322
1323static int
1324compare_res(const void *arg1, const void *arg2)
1325{
1326	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1327	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1328
1329	ORDERKEY_RSSIZE(p1, p2);
1330	ORDERKEY_MEM(p1, p2);
1331	ORDERKEY_PCTCPU(p1, p2);
1332	ORDERKEY_CPTICKS(p1, p2);
1333	ORDERKEY_STATE(p1, p2);
1334	ORDERKEY_PRIO(p1, p2);
1335
1336	return (0);
1337}
1338
1339/* compare_time - the comparison function for sorting by total cpu time */
1340
1341static int
1342compare_time(const void *arg1, const void *arg2)
1343{
1344	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const  *)arg1;
1345	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1346
1347	ORDERKEY_CPTICKS(p1, p2);
1348	ORDERKEY_PCTCPU(p1, p2);
1349	ORDERKEY_STATE(p1, p2);
1350	ORDERKEY_PRIO(p1, p2);
1351	ORDERKEY_RSSIZE(p1, p2);
1352	ORDERKEY_MEM(p1, p2);
1353
1354	return (0);
1355}
1356
1357/* compare_prio - the comparison function for sorting by priority */
1358
1359static int
1360compare_prio(const void *arg1, const void *arg2)
1361{
1362	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1363	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1364
1365	ORDERKEY_PRIO(p1, p2);
1366	ORDERKEY_CPTICKS(p1, p2);
1367	ORDERKEY_PCTCPU(p1, p2);
1368	ORDERKEY_STATE(p1, p2);
1369	ORDERKEY_RSSIZE(p1, p2);
1370	ORDERKEY_MEM(p1, p2);
1371
1372	return (0);
1373}
1374
1375/* compare_threads - the comparison function for sorting by threads */
1376static int
1377compare_threads(const void *arg1, const void *arg2)
1378{
1379	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1380	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1381
1382	ORDERKEY_THREADS(p1, p2);
1383	ORDERKEY_PCTCPU(p1, p2);
1384	ORDERKEY_CPTICKS(p1, p2);
1385	ORDERKEY_STATE(p1, p2);
1386	ORDERKEY_PRIO(p1, p2);
1387	ORDERKEY_RSSIZE(p1, p2);
1388	ORDERKEY_MEM(p1, p2);
1389
1390	return (0);
1391}
1392
1393/* compare_jid - the comparison function for sorting by jid */
1394static int
1395compare_jid(const void *arg1, const void *arg2)
1396{
1397	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1398	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1399
1400	ORDERKEY_JID(p1, p2);
1401	ORDERKEY_PCTCPU(p1, p2);
1402	ORDERKEY_CPTICKS(p1, p2);
1403	ORDERKEY_STATE(p1, p2);
1404	ORDERKEY_PRIO(p1, p2);
1405	ORDERKEY_RSSIZE(p1, p2);
1406	ORDERKEY_MEM(p1, p2);
1407
1408	return (0);
1409}
1410
1411/* compare_swap - the comparison function for sorting by swap */
1412static int
1413compare_swap(const void *arg1, const void *arg2)
1414{
1415	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1416	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1417
1418	ORDERKEY_SWAP(p1, p2);
1419	ORDERKEY_PCTCPU(p1, p2);
1420	ORDERKEY_CPTICKS(p1, p2);
1421	ORDERKEY_STATE(p1, p2);
1422	ORDERKEY_PRIO(p1, p2);
1423	ORDERKEY_RSSIZE(p1, p2);
1424	ORDERKEY_MEM(p1, p2);
1425
1426	return (0);
1427}
1428
1429/* assorted comparison functions for sorting by i/o */
1430
1431static int
1432compare_iototal(const void *arg1, const void *arg2)
1433{
1434	const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1435	const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1436
1437	return (get_io_total(p2) - get_io_total(p1));
1438}
1439
1440static int
1441compare_ioread(const void *arg1, const void *arg2)
1442{
1443	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1444	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1445	long dummy, inp1, inp2;
1446
1447	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1448	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1449
1450	return (inp2 - inp1);
1451}
1452
1453static int
1454compare_iowrite(const void *arg1, const void *arg2)
1455{
1456	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1457	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1458	long dummy, oup1, oup2;
1459
1460	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1461	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1462
1463	return (oup2 - oup1);
1464}
1465
1466static int
1467compare_iofault(const void *arg1, const void *arg2)
1468{
1469	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1470	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1471	long dummy, flp1, flp2;
1472
1473	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1474	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1475
1476	return (flp2 - flp1);
1477}
1478
1479static int
1480compare_vcsw(const void *arg1, const void *arg2)
1481{
1482	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1483	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1484	long dummy, flp1, flp2;
1485
1486	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1487	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1488
1489	return (flp2 - flp1);
1490}
1491
1492static int
1493compare_ivcsw(const void *arg1, const void *arg2)
1494{
1495	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1496	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1497	long dummy, flp1, flp2;
1498
1499	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1500	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1501
1502	return (flp2 - flp1);
1503}
1504
1505int (*compares[])(const void *arg1, const void *arg2) = {
1506	compare_cpu,
1507	compare_size,
1508	compare_res,
1509	compare_time,
1510	compare_prio,
1511	compare_threads,
1512	compare_iototal,
1513	compare_ioread,
1514	compare_iowrite,
1515	compare_iofault,
1516	compare_vcsw,
1517	compare_ivcsw,
1518	compare_jid,
1519	compare_swap,
1520	NULL
1521};
1522
1523
1524static int
1525swapmode(int *retavail, int *retfree)
1526{
1527	int n;
1528	struct kvm_swap swapary[1];
1529	static int pagesize = 0;
1530	static unsigned long swap_maxpages = 0;
1531
1532	*retavail = 0;
1533	*retfree = 0;
1534
1535#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1536
1537	n = kvm_getswapinfo(kd, swapary, 1, 0);
1538	if (n < 0 || swapary[0].ksw_total == 0)
1539		return (0);
1540
1541	if (pagesize == 0)
1542		pagesize = getpagesize();
1543	if (swap_maxpages == 0)
1544		GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1545
1546	/* ksw_total contains the total size of swap all devices which may
1547	   exceed the maximum swap size allocatable in the system */
1548	if ( swapary[0].ksw_total > swap_maxpages )
1549		swapary[0].ksw_total = swap_maxpages;
1550
1551	*retavail = CONVERT(swapary[0].ksw_total);
1552	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1553
1554#undef CONVERT
1555
1556	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1557	return (n);
1558}
1559