xref: /freebsd/usr.bin/top/machine.c (revision 1f62718d8ba26d813d8c2e826ac5f4caee4c6730)
1511d9c65SJoerg Wunsch /*
2511d9c65SJoerg Wunsch  * top - a top users display for Unix
3511d9c65SJoerg Wunsch  *
4511d9c65SJoerg Wunsch  * DESCRIPTION:
5511d9c65SJoerg Wunsch  * Originally written for BSD4.4 system by Christos Zoulas.
6511d9c65SJoerg Wunsch  * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
7f3b2c2d1SWolfram Schneider  * Order support hacked in from top-3.5beta6/machine/m_aix41.c
8f3b2c2d1SWolfram Schneider  *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
9511d9c65SJoerg Wunsch  *
10511d9c65SJoerg Wunsch  * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
118d0d2676SEitan Adler  *          Steven Wallace  <swallace@FreeBSD.org>
12511d9c65SJoerg Wunsch  *          Wolfram Schneider <wosch@FreeBSD.org>
1339d513ecSRobert Watson  *          Thomas Moestl <tmoestl@gmx.net>
148d0d2676SEitan Adler  *          Eitan Adler <eadler@FreeBSD.org>
15511d9c65SJoerg Wunsch  */
16511d9c65SJoerg Wunsch 
17e96ed177SMark Johnston #include <sys/param.h>
18e96ed177SMark Johnston #include <sys/cpuset.h>
19511d9c65SJoerg Wunsch #include <sys/errno.h>
208d0d2676SEitan Adler #include <sys/fcntl.h>
218d0d2676SEitan Adler #include <sys/priority.h>
22511d9c65SJoerg Wunsch #include <sys/proc.h>
23e5aff02fSPeter Wemm #include <sys/resource.h>
2451c834c4SEitan Adler #include <sys/sbuf.h>
25cd23263cSDag-Erling Smørgrav #include <sys/sysctl.h>
26cd23263cSDag-Erling Smørgrav #include <sys/time.h>
27cd23263cSDag-Erling Smørgrav #include <sys/user.h>
28511d9c65SJoerg Wunsch 
29666cf873SEitan Adler #include <assert.h>
30d9b2153bSSergey Kandaurov #include <err.h>
31ac8f40eaSEitan Adler #include <libgen.h>
32cd23263cSDag-Erling Smørgrav #include <kvm.h>
33cd23263cSDag-Erling Smørgrav #include <math.h>
344946a00bSDag-Erling Smørgrav #include <paths.h>
35cd23263cSDag-Erling Smørgrav #include <stdio.h>
360b2f6ed1SEitan Adler #include <stdbool.h>
378d0d2676SEitan Adler #include <stdint.h>
38511d9c65SJoerg Wunsch #include <stdlib.h>
3942649453SStefan Farfeleder #include <string.h>
408d0d2676SEitan Adler #include <time.h>
4139d513ecSRobert Watson #include <unistd.h>
42faac60c8SStanislav Sedov #include <vis.h>
43511d9c65SJoerg Wunsch 
44511d9c65SJoerg Wunsch #include "top.h"
45fcfaa473SEitan Adler #include "display.h"
4647ffa267SEitan Adler #include "machine.h"
4747ffa267SEitan Adler #include "loadavg.h"
487f18d5d3SJohn Baldwin #include "screen.h"
4939d513ecSRobert Watson #include "utils.h"
5003117570SPeter Wemm #include "layout.h"
51511d9c65SJoerg Wunsch 
5239d513ecSRobert Watson #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
5339d513ecSRobert Watson 
54fcfaa473SEitan Adler extern struct timeval timeout;
5594154ff8SPeter Wemm static int smpmode;
56db6bb7fcSAlfred Perlstein enum displaymodes displaymode;
5751c834c4SEitan Adler static const int namelength = 10;
58069f49cfSBryan Drewery /* TOP_JID_LEN based on max of 999999 */
5951c834c4SEitan Adler #define TOP_JID_LEN 6
6051c834c4SEitan Adler #define TOP_SWAP_LEN 5
61511d9c65SJoerg Wunsch 
62511d9c65SJoerg Wunsch /* get_process_info passes back a handle.  This is what it looks like: */
63511d9c65SJoerg Wunsch 
64789e3877SBruce Evans struct handle {
65511d9c65SJoerg Wunsch 	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
66511d9c65SJoerg Wunsch 	int remaining;			/* number of pointers remaining */
67511d9c65SJoerg Wunsch };
68511d9c65SJoerg Wunsch 
69511d9c65SJoerg Wunsch 
70511d9c65SJoerg Wunsch /* define what weighted cpu is.  */
711f7d2501SKirk McKusick #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
721f7d2501SKirk McKusick 			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
73511d9c65SJoerg Wunsch 
74511d9c65SJoerg Wunsch /* what we consider to be process size: */
751f7d2501SKirk McKusick #define PROCSIZE(pp) ((pp)->ki_size / 1024)
76511d9c65SJoerg Wunsch 
77db6bb7fcSAlfred Perlstein #define RU(pp)	(&(pp)->ki_rusage)
78db6bb7fcSAlfred Perlstein 
79a9053954SJohn Baldwin #define	PCTCPU(pp) (pcpu[pp - pbase])
80db6bb7fcSAlfred Perlstein 
81511d9c65SJoerg Wunsch /* process state names for the "STATE" column of the display */
82511d9c65SJoerg Wunsch /* the extra nulls in the string "run" are for adding a slash and
83511d9c65SJoerg Wunsch    the processor number when needed */
84511d9c65SJoerg Wunsch 
85960a7f39SEitan Adler static const char *state_abbrev[] = {
860d632649SJohn Baldwin 	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
87511d9c65SJoerg Wunsch };
88511d9c65SJoerg Wunsch 
89511d9c65SJoerg Wunsch 
90511d9c65SJoerg Wunsch static kvm_t *kd;
91511d9c65SJoerg Wunsch 
92511d9c65SJoerg Wunsch /* values that we stash away in _init and use in later routines */
93511d9c65SJoerg Wunsch 
94511d9c65SJoerg Wunsch static double logcpu;
95511d9c65SJoerg Wunsch 
96511d9c65SJoerg Wunsch /* these are retrieved from the kernel in _init */
97511d9c65SJoerg Wunsch 
98511d9c65SJoerg Wunsch static load_avg  ccpu;
99511d9c65SJoerg Wunsch 
10039d513ecSRobert Watson /* these are used in the get_ functions */
101511d9c65SJoerg Wunsch 
10239d513ecSRobert Watson static int lastpid;
103511d9c65SJoerg Wunsch 
104511d9c65SJoerg Wunsch /* these are for calculating cpu state percentages */
105511d9c65SJoerg Wunsch 
106511d9c65SJoerg Wunsch static long cp_time[CPUSTATES];
107511d9c65SJoerg Wunsch static long cp_old[CPUSTATES];
108511d9c65SJoerg Wunsch static long cp_diff[CPUSTATES];
109511d9c65SJoerg Wunsch 
110511d9c65SJoerg Wunsch /* these are for detailing the process states */
111511d9c65SJoerg Wunsch 
1129f8096e3SEitan Adler static const char *procstatenames[] = {
113511d9c65SJoerg Wunsch 	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
1140d632649SJohn Baldwin 	" zombie, ", " waiting, ", " lock, ",
115511d9c65SJoerg Wunsch 	NULL
116511d9c65SJoerg Wunsch };
117eae589f1SEitan Adler static int process_states[nitems(procstatenames)];
118511d9c65SJoerg Wunsch 
119511d9c65SJoerg Wunsch /* these are for detailing the cpu states */
120511d9c65SJoerg Wunsch 
121a5ca08edSEitan Adler static int cpu_states[CPUSTATES];
1229f8096e3SEitan Adler static const char *cpustatenames[] = {
123511d9c65SJoerg Wunsch 	"user", "nice", "system", "interrupt", "idle", NULL
124511d9c65SJoerg Wunsch };
125511d9c65SJoerg Wunsch 
126511d9c65SJoerg Wunsch /* these are for detailing the memory statistics */
127511d9c65SJoerg Wunsch 
1289f8096e3SEitan Adler static const char *memorynames[] = {
129cc59e3a7SMark Johnston 	"K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
130789e3877SBruce Evans 	"K Free", NULL
131511d9c65SJoerg Wunsch };
132eae589f1SEitan Adler static int memory_stats[nitems(memorynames)];
133511d9c65SJoerg Wunsch 
1349f8096e3SEitan Adler static const char *arcnames[] = {
135b49af68cSJohn Baldwin 	"K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
1362e52fb92SJohn Baldwin 	NULL
1372e52fb92SJohn Baldwin };
138eae589f1SEitan Adler static int arc_stats[nitems(arcnames)];
1392e52fb92SJohn Baldwin 
1409f8096e3SEitan Adler static const char *carcnames[] = {
141d9a72328SAllan Jude 	"K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
1421dbfa4b5SAllan Jude 	NULL
1431dbfa4b5SAllan Jude };
144eae589f1SEitan Adler static int carc_stats[nitems(carcnames)];
1451dbfa4b5SAllan Jude 
1469f8096e3SEitan Adler static const char *swapnames[] = {
147511d9c65SJoerg Wunsch 	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
148511d9c65SJoerg Wunsch 	NULL
149511d9c65SJoerg Wunsch };
150eae589f1SEitan Adler static int swap_stats[nitems(swapnames)];
151511d9c65SJoerg Wunsch 
1522984a716SAllan Jude static int has_swap;
153511d9c65SJoerg Wunsch 
154511d9c65SJoerg Wunsch /* these are for keeping track of the proc array */
155511d9c65SJoerg Wunsch 
156511d9c65SJoerg Wunsch static int nproc;
157511d9c65SJoerg Wunsch static int onproc = -1;
158511d9c65SJoerg Wunsch static int pref_len;
159511d9c65SJoerg Wunsch static struct kinfo_proc *pbase;
160511d9c65SJoerg Wunsch static struct kinfo_proc **pref;
161db6bb7fcSAlfred Perlstein static struct kinfo_proc *previous_procs;
162db6bb7fcSAlfred Perlstein static struct kinfo_proc **previous_pref;
163db6bb7fcSAlfred Perlstein static int previous_proc_count = 0;
164db6bb7fcSAlfred Perlstein static int previous_proc_count_max = 0;
165a9053954SJohn Baldwin static int previous_thread;
166a9053954SJohn Baldwin 
167a9053954SJohn Baldwin /* data used for recalculating pctcpu */
168a9053954SJohn Baldwin static double *pcpu;
169a9053954SJohn Baldwin static struct timespec proc_uptime;
170a9053954SJohn Baldwin static struct timeval proc_wall_time;
171a9053954SJohn Baldwin static struct timeval previous_wall_time;
172a9053954SJohn Baldwin static uint64_t previous_interval = 0;
173511d9c65SJoerg Wunsch 
1747fe9a86aSAlfred Perlstein /* total number of io operations */
1757fe9a86aSAlfred Perlstein static long total_inblock;
1767fe9a86aSAlfred Perlstein static long total_oublock;
1777fe9a86aSAlfred Perlstein static long total_majflt;
1787fe9a86aSAlfred Perlstein 
179511d9c65SJoerg Wunsch /* these are for getting the memory statistics */
180511d9c65SJoerg Wunsch 
181a9053954SJohn Baldwin static int arc_enabled;
1821dbfa4b5SAllan Jude static int carc_enabled;
183511d9c65SJoerg Wunsch static int pageshift;		/* log base 2 of the pagesize */
184511d9c65SJoerg Wunsch 
185511d9c65SJoerg Wunsch /* define pagetok in terms of pageshift */
186511d9c65SJoerg Wunsch 
187511d9c65SJoerg Wunsch #define pagetok(size) ((size) << pageshift)
188511d9c65SJoerg Wunsch 
189b6924c93SDag-Erling Smørgrav /* swap usage */
190b6924c93SDag-Erling Smørgrav #define ki_swap(kip) \
191b6924c93SDag-Erling Smørgrav     ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
192b6924c93SDag-Erling Smørgrav 
19326b2243aSGiorgos Keramidas /*
19432efd263SGiorgos Keramidas  * Sorting orders.  The first element is the default.
19526b2243aSGiorgos Keramidas  */
1961d5b01e6SEitan Adler static const char *ordernames[] = {
19732efd263SGiorgos Keramidas 	"cpu", "size", "res", "time", "pri", "threads",
1986000ced1SRong-En Fan 	"total", "read", "write", "fault", "vcsw", "ivcsw",
199b6924c93SDag-Erling Smørgrav 	"jid", "swap", "pid", NULL
20026b2243aSGiorgos Keramidas };
201f3b2c2d1SWolfram Schneider 
20203117570SPeter Wemm /* Per-cpu time states */
20303117570SPeter Wemm static int maxcpu;
20403117570SPeter Wemm static int maxid;
20503117570SPeter Wemm static int ncpus;
206e96ed177SMark Johnston static cpuset_t cpumask;
20703117570SPeter Wemm static long *times;
20803117570SPeter Wemm static long *pcpu_cp_time;
20903117570SPeter Wemm static long *pcpu_cp_old;
21003117570SPeter Wemm static long *pcpu_cp_diff;
21103117570SPeter Wemm static int *pcpu_cpu_states;
21203117570SPeter Wemm 
213fc8ae86aSPhilip Paeps /* Battery units and states */
214fc8ae86aSPhilip Paeps static int battery_units;
215fc8ae86aSPhilip Paeps static int battery_life;
216fc8ae86aSPhilip Paeps 
217b6924c93SDag-Erling Smørgrav static int compare_swap(const void *a, const void *b);
2186000ced1SRong-En Fan static int compare_jid(const void *a, const void *b);
219de916c8bSBruce Evans static int compare_pid(const void *a, const void *b);
2202417d97eSJohn Baldwin static int compare_tid(const void *a, const void *b);
221de916c8bSBruce Evans static const char *format_nice(const struct kinfo_proc *pp);
222de916c8bSBruce Evans static void getsysctl(const char *name, void *ptr, size_t len);
223de916c8bSBruce Evans static int swapmode(int *retavail, int *retfree);
2242e52fb92SJohn Baldwin static void update_layout(void);
225f9995000SPietro Cerutti static int find_uid(uid_t needle, int *haystack);
226a00d703fSJohn Grafton static int cmd_matches(struct kinfo_proc *, const char *);
227f9995000SPietro Cerutti 
228f9995000SPietro Cerutti static int
find_uid(uid_t needle,int * haystack)229f9995000SPietro Cerutti find_uid(uid_t needle, int *haystack)
230f9995000SPietro Cerutti {
231f9995000SPietro Cerutti 	size_t i = 0;
232f9995000SPietro Cerutti 
233f9995000SPietro Cerutti 	for (; i < TOP_MAX_UIDS; ++i)
234f9995000SPietro Cerutti 		if ((uid_t)haystack[i] == needle)
235f9995000SPietro Cerutti 			return 1;
236d408c8f7SEitan Adler 	return (0);
237f9995000SPietro Cerutti }
238de916c8bSBruce Evans 
23951f202e9SJohn Baldwin void
toggle_pcpustats(void)240fcc3d62fSJohn Baldwin toggle_pcpustats(void)
24151f202e9SJohn Baldwin {
24251f202e9SJohn Baldwin 
24351f202e9SJohn Baldwin 	if (ncpus == 1)
24451f202e9SJohn Baldwin 		return;
2452e52fb92SJohn Baldwin 	update_layout();
2462e52fb92SJohn Baldwin }
24751f202e9SJohn Baldwin 
2482e52fb92SJohn Baldwin /* Adjust display based on ncpus and the ARC state. */
2492e52fb92SJohn Baldwin static void
update_layout(void)2502e52fb92SJohn Baldwin update_layout(void)
2512e52fb92SJohn Baldwin {
2522e52fb92SJohn Baldwin 
25351f202e9SJohn Baldwin 	y_mem = 3;
25454900c9bSJohn Baldwin 	y_arc = 4;
2551dbfa4b5SAllan Jude 	y_carc = 5;
2562984a716SAllan Jude 	y_swap = 3 + arc_enabled + carc_enabled + has_swap;
2572984a716SAllan Jude 	y_idlecursor = 4 + arc_enabled + carc_enabled + has_swap;
2582984a716SAllan Jude 	y_message = 4 + arc_enabled + carc_enabled + has_swap;
2592984a716SAllan Jude 	y_header = 5 + arc_enabled + carc_enabled + has_swap;
2602984a716SAllan Jude 	y_procs = 6 + arc_enabled + carc_enabled + has_swap;
2612984a716SAllan Jude 	Header_lines = 6 + arc_enabled + carc_enabled + has_swap;
2622e52fb92SJohn Baldwin 
2632e52fb92SJohn Baldwin 	if (pcpu_stats) {
26454900c9bSJohn Baldwin 		y_mem += ncpus - 1;
26554900c9bSJohn Baldwin 		y_arc += ncpus - 1;
2661dbfa4b5SAllan Jude 		y_carc += ncpus - 1;
2672e52fb92SJohn Baldwin 		y_swap += ncpus - 1;
2682e52fb92SJohn Baldwin 		y_idlecursor += ncpus - 1;
2692e52fb92SJohn Baldwin 		y_message += ncpus - 1;
2702e52fb92SJohn Baldwin 		y_header += ncpus - 1;
2712e52fb92SJohn Baldwin 		y_procs += ncpus - 1;
2722e52fb92SJohn Baldwin 		Header_lines += ncpus - 1;
27351f202e9SJohn Baldwin 	}
27451f202e9SJohn Baldwin }
27551f202e9SJohn Baldwin 
276511d9c65SJoerg Wunsch int
machine_init(struct statics * statics)2774b9ca404SEitan Adler machine_init(struct statics *statics)
278511d9c65SJoerg Wunsch {
27951f202e9SJohn Baldwin 	int i, j, empty, pagesize;
2802e52fb92SJohn Baldwin 	uint64_t arc_size;
2812984a716SAllan Jude 	int carc_en, nswapdev;
28251f202e9SJohn Baldwin 	size_t size;
28394154ff8SPeter Wemm 
28451f202e9SJohn Baldwin 	size = sizeof(smpmode);
2855211c24dSKonstantin Belousov 	if (sysctlbyname("kern.smp.active", &smpmode, &size, NULL, 0) != 0 ||
28651f202e9SJohn Baldwin 	    size != sizeof(smpmode))
28794154ff8SPeter Wemm 		smpmode = 0;
288511d9c65SJoerg Wunsch 
2891dbfa4b5SAllan Jude 	size = sizeof(arc_size);
2902e52fb92SJohn Baldwin 	if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
2912e52fb92SJohn Baldwin 	    NULL, 0) == 0 && arc_size != 0)
2922e52fb92SJohn Baldwin 		arc_enabled = 1;
2938781788dSMark Johnston 	size = sizeof(carc_en);
2948781788dSMark Johnston 	if (arc_enabled &&
2958781788dSMark Johnston 	    sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
296*1f62718dSMark Johnston 	    NULL, 0) == 0 && carc_en == 1) {
297*1f62718dSMark Johnston 		uint64_t uncomp_sz;
298*1f62718dSMark Johnston 
299*1f62718dSMark Johnston 		/*
300*1f62718dSMark Johnston 		 * Don't report compression stats if no data is in the ARC.
301*1f62718dSMark Johnston 		 * Otherwise, we end up printing a blank line.
302*1f62718dSMark Johnston 		 */
303*1f62718dSMark Johnston 		size = sizeof(uncomp_sz);
304*1f62718dSMark Johnston 		if (sysctlbyname("kstat.zfs.misc.arcstats.uncompressed_size",
305*1f62718dSMark Johnston 		    &uncomp_sz, &size, NULL, 0) == 0 && uncomp_sz != 0)
3068781788dSMark Johnston 			carc_enabled = 1;
307*1f62718dSMark Johnston 	}
3082e52fb92SJohn Baldwin 
3094946a00bSDag-Erling Smørgrav 	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
3104946a00bSDag-Erling Smørgrav 	if (kd == NULL)
3114946a00bSDag-Erling Smørgrav 		return (-1);
312511d9c65SJoerg Wunsch 
3132984a716SAllan Jude 	size = sizeof(nswapdev);
314*1f62718dSMark Johnston 	if (sysctlbyname("vm.nswapdev", &nswapdev, &size, NULL, 0) == 0 &&
315*1f62718dSMark Johnston 	    nswapdev != 0)
3162984a716SAllan Jude 		has_swap = 1;
3172984a716SAllan Jude 
31839d513ecSRobert Watson 	GETSYSCTL("kern.ccpu", ccpu);
319511d9c65SJoerg Wunsch 
320511d9c65SJoerg Wunsch 	/* this is used in calculating WCPU -- calculate it ahead of time */
321511d9c65SJoerg Wunsch 	logcpu = log(loaddouble(ccpu));
322511d9c65SJoerg Wunsch 
323511d9c65SJoerg Wunsch 	pbase = NULL;
324511d9c65SJoerg Wunsch 	pref = NULL;
325a9053954SJohn Baldwin 	pcpu = NULL;
326511d9c65SJoerg Wunsch 	nproc = 0;
327511d9c65SJoerg Wunsch 	onproc = -1;
328789e3877SBruce Evans 
329789e3877SBruce Evans 	/* get the page size and calculate pageshift from it */
330511d9c65SJoerg Wunsch 	pagesize = getpagesize();
331511d9c65SJoerg Wunsch 	pageshift = 0;
3324946a00bSDag-Erling Smørgrav 	while (pagesize > 1) {
333511d9c65SJoerg Wunsch 		pageshift++;
334511d9c65SJoerg Wunsch 		pagesize >>= 1;
335511d9c65SJoerg Wunsch 	}
336511d9c65SJoerg Wunsch 
337511d9c65SJoerg Wunsch 	/* we only need the amount of log(2)1024 for our conversion */
338511d9c65SJoerg Wunsch 	pageshift -= LOG1024;
339511d9c65SJoerg Wunsch 
340511d9c65SJoerg Wunsch 	/* fill in the statics information */
341511d9c65SJoerg Wunsch 	statics->procstate_names = procstatenames;
342511d9c65SJoerg Wunsch 	statics->cpustate_names = cpustatenames;
343511d9c65SJoerg Wunsch 	statics->memory_names = memorynames;
3442e52fb92SJohn Baldwin 	if (arc_enabled)
3452e52fb92SJohn Baldwin 		statics->arc_names = arcnames;
3462e52fb92SJohn Baldwin 	else
3472e52fb92SJohn Baldwin 		statics->arc_names = NULL;
3481dbfa4b5SAllan Jude 	if (carc_enabled)
3491dbfa4b5SAllan Jude 		statics->carc_names = carcnames;
3501dbfa4b5SAllan Jude 	else
3511dbfa4b5SAllan Jude 		statics->carc_names = NULL;
3522984a716SAllan Jude 	if (has_swap)
353511d9c65SJoerg Wunsch 		statics->swap_names = swapnames;
3542984a716SAllan Jude 	else
3552984a716SAllan Jude 		statics->swap_names = NULL;
3565d320d4bSAlfred Perlstein 	statics->order_names = ordernames;
357511d9c65SJoerg Wunsch 
35851f202e9SJohn Baldwin 	/* Allocate state for per-CPU stats. */
35903117570SPeter Wemm 	GETSYSCTL("kern.smp.maxcpus", maxcpu);
360d0bb69dcSEitan Adler 	times = calloc(maxcpu * CPUSTATES, sizeof(long));
36103117570SPeter Wemm 	if (times == NULL)
36259c8d5dcSEitan Adler 		err(1, "calloc for kern.smp.maxcpus");
363a2cda47aSEitan Adler 	size = sizeof(long) * maxcpu * CPUSTATES;
36403117570SPeter Wemm 	if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
36503117570SPeter Wemm 		err(1, "sysctlbyname kern.cp_times");
3663aaa0832SRuslan Ermilov 	pcpu_cp_time = calloc(1, size);
367e96ed177SMark Johnston 	maxid = MIN(size / CPUSTATES / sizeof(long) - 1, CPU_SETSIZE - 1);
368e96ed177SMark Johnston 	CPU_ZERO(&cpumask);
36903117570SPeter Wemm 	for (i = 0; i <= maxid; i++) {
37003117570SPeter Wemm 		empty = 1;
37103117570SPeter Wemm 		for (j = 0; empty && j < CPUSTATES; j++) {
37203117570SPeter Wemm 			if (times[i * CPUSTATES + j] != 0)
37303117570SPeter Wemm 				empty = 0;
37403117570SPeter Wemm 		}
375e96ed177SMark Johnston 		if (!empty)
376e96ed177SMark Johnston 			CPU_SET(i, &cpumask);
37703117570SPeter Wemm 	}
378e96ed177SMark Johnston 	ncpus = CPU_COUNT(&cpumask);
379d0bb69dcSEitan Adler 	assert(ncpus > 0);
380d0bb69dcSEitan Adler 	pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
381d0bb69dcSEitan Adler 	pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
382d0bb69dcSEitan Adler 	pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
383fcc3d62fSJohn Baldwin 	statics->ncpus = ncpus;
38451f202e9SJohn Baldwin 
385fc8ae86aSPhilip Paeps 	/* Allocate state of battery units reported via ACPI. */
386fc8ae86aSPhilip Paeps 	battery_units = 0;
387fc8ae86aSPhilip Paeps 	size = sizeof(int);
388fc8ae86aSPhilip Paeps 	sysctlbyname("hw.acpi.battery.units", &battery_units, &size, NULL, 0);
389fc8ae86aSPhilip Paeps 	statics->nbatteries = battery_units;
390fc8ae86aSPhilip Paeps 
3912e52fb92SJohn Baldwin 	update_layout();
39203117570SPeter Wemm 
393511d9c65SJoerg Wunsch 	/* all done! */
394511d9c65SJoerg Wunsch 	return (0);
395511d9c65SJoerg Wunsch }
396511d9c65SJoerg Wunsch 
39751c834c4SEitan Adler char *
format_header(const char * uname_field)3989f8096e3SEitan Adler format_header(const char *uname_field)
399511d9c65SJoerg Wunsch {
40051c834c4SEitan Adler 	static struct sbuf* header = NULL;
401511d9c65SJoerg Wunsch 
40251c834c4SEitan Adler 	/* clean up from last time. */
40351c834c4SEitan Adler 	if (header != NULL) {
4040515b88eSEitan Adler 		sbuf_clear(header);
4050515b88eSEitan Adler 	} else {
40651c834c4SEitan Adler 		header = sbuf_new_auto();
4070515b88eSEitan Adler 	}
408b6924c93SDag-Erling Smørgrav 
409db6bb7fcSAlfred Perlstein 	switch (displaymode) {
41051c834c4SEitan Adler 	case DISP_CPU: {
41151c834c4SEitan Adler 		sbuf_printf(header, "  %s", ps.thread_id ? " THR" : "PID");
41251c834c4SEitan Adler 		sbuf_printf(header, "%*s", ps.jail ? TOP_JID_LEN : 0,
41351c834c4SEitan Adler 									ps.jail ? " JID" : "");
41451c834c4SEitan Adler 		sbuf_printf(header, " %-*.*s  ", namelength, namelength, uname_field);
415550ddd16SEitan Adler 		if (!ps.thread) {
416550ddd16SEitan Adler 			sbuf_cat(header, "THR ");
417550ddd16SEitan Adler 		}
418550ddd16SEitan Adler 		sbuf_cat(header, "PRI NICE   SIZE    RES ");
419db365663SEitan Adler 		if (ps.swap) {
420db365663SEitan Adler 			sbuf_printf(header, "%*s ", TOP_SWAP_LEN - 1, "SWAP");
421db365663SEitan Adler 		}
422db365663SEitan Adler 		sbuf_cat(header, "STATE    ");
423db365663SEitan Adler 		if (smpmode) {
424db365663SEitan Adler 			sbuf_cat(header, "C   ");
425db365663SEitan Adler 		}
42651c834c4SEitan Adler 		sbuf_cat(header, "TIME ");
427db365663SEitan Adler 		sbuf_printf(header, " %6s ", ps.wcpu ? "WCPU" : "CPU");
42851c834c4SEitan Adler 		sbuf_cat(header, "COMMAND");
42951c834c4SEitan Adler 		sbuf_finish(header);
430db6bb7fcSAlfred Perlstein 		break;
43151c834c4SEitan Adler 	}
43251c834c4SEitan Adler 	case DISP_IO: {
4330515b88eSEitan Adler 		sbuf_printf(header, "  %s%*s %-*.*s",
4343edda95cSEitan Adler 			ps.thread_id ? " THR" : "PID",
43551c834c4SEitan Adler 		    ps.jail ? TOP_JID_LEN : 0, ps.jail ? " JID" : "",
436a2aff8b2SPeter Wemm 		    namelength, namelength, uname_field);
4370515b88eSEitan Adler 		sbuf_cat(header, "   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND");
4384ee90e6eSCy Schubert 		sbuf_finish(header);
439bbf750fbSGiorgos Keramidas 		break;
44051c834c4SEitan Adler 	}
441666cf873SEitan Adler 	case DISP_MAX:
442666cf873SEitan Adler 		assert("displaymode must not be set to DISP_MAX");
443bbf750fbSGiorgos Keramidas 	}
44451c834c4SEitan Adler 
44551c834c4SEitan Adler 	return sbuf_data(header);
446511d9c65SJoerg Wunsch }
447511d9c65SJoerg Wunsch 
448511d9c65SJoerg Wunsch static int swappgsin = -1;
449511d9c65SJoerg Wunsch static int swappgsout = -1;
450511d9c65SJoerg Wunsch 
45103117570SPeter Wemm 
452511d9c65SJoerg Wunsch void
get_system_info(struct system_info * si)453f6a10feaSDag-Erling Smørgrav get_system_info(struct system_info *si)
454511d9c65SJoerg Wunsch {
45598e53e5bSAndrew Gallatin 	struct loadavg sysload;
456a2641311SDavid E. O'Brien 	int mib[2];
457a2641311SDavid E. O'Brien 	struct timeval boottime;
4582e52fb92SJohn Baldwin 	uint64_t arc_stat, arc_stat2;
45903117570SPeter Wemm 	int i, j;
46003117570SPeter Wemm 	size_t size;
461511d9c65SJoerg Wunsch 
46251f202e9SJohn Baldwin 	/* get the CPU stats */
46303117570SPeter Wemm 	size = (maxid + 1) * CPUSTATES * sizeof(long);
46403117570SPeter Wemm 	if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
46503117570SPeter Wemm 		err(1, "sysctlbyname kern.cp_times");
46639d513ecSRobert Watson 	GETSYSCTL("kern.cp_time", cp_time);
46798e53e5bSAndrew Gallatin 	GETSYSCTL("vm.loadavg", sysload);
46839d513ecSRobert Watson 	GETSYSCTL("kern.lastpid", lastpid);
469511d9c65SJoerg Wunsch 
470511d9c65SJoerg Wunsch 	/* convert load averages to doubles */
471511d9c65SJoerg Wunsch 	for (i = 0; i < 3; i++)
4724946a00bSDag-Erling Smørgrav 		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
473511d9c65SJoerg Wunsch 
47451f202e9SJohn Baldwin 	/* convert cp_time counts to percentages */
475f89db435SRuslan Ermilov 	for (i = j = 0; i <= maxid; i++) {
476e96ed177SMark Johnston 		if (!CPU_ISSET(i, &cpumask))
47703117570SPeter Wemm 			continue;
47803117570SPeter Wemm 		percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
47903117570SPeter Wemm 		    &pcpu_cp_time[j * CPUSTATES],
48003117570SPeter Wemm 		    &pcpu_cp_old[j * CPUSTATES],
48103117570SPeter Wemm 		    &pcpu_cp_diff[j * CPUSTATES]);
482f89db435SRuslan Ermilov 		j++;
48303117570SPeter Wemm 	}
48403117570SPeter Wemm 	percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
485511d9c65SJoerg Wunsch 
486511d9c65SJoerg Wunsch 	/* sum memory & swap statistics */
487511d9c65SJoerg Wunsch 	{
488511d9c65SJoerg Wunsch 		static unsigned int swap_delay = 0;
489511d9c65SJoerg Wunsch 		static int swapavail = 0;
490511d9c65SJoerg Wunsch 		static int swapfree = 0;
491a0b9e7e3SJohn Baldwin 		static long bufspace = 0;
49283c9dea1SGleb Smirnoff 		static uint64_t nspgsin, nspgsout;
493511d9c65SJoerg Wunsch 
49439d513ecSRobert Watson 		GETSYSCTL("vfs.bufspace", bufspace);
49539d513ecSRobert Watson 		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
49639d513ecSRobert Watson 		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
497cc59e3a7SMark Johnston 		GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
498cc59e3a7SMark Johnston 		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
49939d513ecSRobert Watson 		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
50039d513ecSRobert Watson 		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
50139d513ecSRobert Watson 		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
502511d9c65SJoerg Wunsch 		/* convert memory stats to Kbytes */
5036243f7acSThomas Moestl 		memory_stats[0] = pagetok(memory_stats[0]);
5046243f7acSThomas Moestl 		memory_stats[1] = pagetok(memory_stats[1]);
5056243f7acSThomas Moestl 		memory_stats[2] = pagetok(memory_stats[2]);
5066243f7acSThomas Moestl 		memory_stats[3] = pagetok(memory_stats[3]);
507511d9c65SJoerg Wunsch 		memory_stats[4] = bufspace / 1024;
5086243f7acSThomas Moestl 		memory_stats[5] = pagetok(memory_stats[5]);
509511d9c65SJoerg Wunsch 		memory_stats[6] = -1;
510511d9c65SJoerg Wunsch 
511511d9c65SJoerg Wunsch 		/* first interval */
512511d9c65SJoerg Wunsch 		if (swappgsin < 0) {
513511d9c65SJoerg Wunsch 			swap_stats[4] = 0;
514511d9c65SJoerg Wunsch 			swap_stats[5] = 0;
515511d9c65SJoerg Wunsch 		}
516511d9c65SJoerg Wunsch 
517511d9c65SJoerg Wunsch 		/* compute differences between old and new swap statistic */
518511d9c65SJoerg Wunsch 		else {
51939d513ecSRobert Watson 			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
52039d513ecSRobert Watson 			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
521511d9c65SJoerg Wunsch 		}
522511d9c65SJoerg Wunsch 
52339d513ecSRobert Watson 		swappgsin = nspgsin;
52439d513ecSRobert Watson 		swappgsout = nspgsout;
525511d9c65SJoerg Wunsch 
526511d9c65SJoerg Wunsch 		/* call CPU heavy swapmode() only for changes */
527511d9c65SJoerg Wunsch 		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
528511d9c65SJoerg Wunsch 			swap_stats[3] = swapmode(&swapavail, &swapfree);
529511d9c65SJoerg Wunsch 			swap_stats[0] = swapavail;
530511d9c65SJoerg Wunsch 			swap_stats[1] = swapavail - swapfree;
531511d9c65SJoerg Wunsch 			swap_stats[2] = swapfree;
532511d9c65SJoerg Wunsch 		}
533511d9c65SJoerg Wunsch 		swap_delay = 1;
534511d9c65SJoerg Wunsch 		swap_stats[6] = -1;
535511d9c65SJoerg Wunsch 	}
536511d9c65SJoerg Wunsch 
5372e52fb92SJohn Baldwin 	if (arc_enabled) {
5382e52fb92SJohn Baldwin 		GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
5392e52fb92SJohn Baldwin 		arc_stats[0] = arc_stat >> 10;
5402e52fb92SJohn Baldwin 		GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
5412e52fb92SJohn Baldwin 		arc_stats[1] = arc_stat >> 10;
5422e52fb92SJohn Baldwin 		GETSYSCTL("vfs.zfs.mru_size", arc_stat);
5432e52fb92SJohn Baldwin 		arc_stats[2] = arc_stat >> 10;
5442e52fb92SJohn Baldwin 		GETSYSCTL("vfs.zfs.anon_size", arc_stat);
5452e52fb92SJohn Baldwin 		arc_stats[3] = arc_stat >> 10;
5462e52fb92SJohn Baldwin 		GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
5472e52fb92SJohn Baldwin 		GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
548b3c88c28SEitan Adler 		arc_stats[4] = (arc_stat + arc_stat2) >> 10;
549ef8e2d2dSMatt Macy 		GETSYSCTL("kstat.zfs.misc.arcstats.bonus_size", arc_stat);
5502e52fb92SJohn Baldwin 		arc_stats[5] = arc_stat >> 10;
551ef8e2d2dSMatt Macy 		GETSYSCTL("kstat.zfs.misc.arcstats.dnode_size", arc_stat);
552ef8e2d2dSMatt Macy 		arc_stats[5] += arc_stat >> 10;
553ef8e2d2dSMatt Macy 		GETSYSCTL("kstat.zfs.misc.arcstats.dbuf_size", arc_stat);
554ef8e2d2dSMatt Macy 		arc_stats[5] += arc_stat >> 10;
5552e52fb92SJohn Baldwin 		si->arc = arc_stats;
5562e52fb92SJohn Baldwin 	}
5571dbfa4b5SAllan Jude 	if (carc_enabled) {
5581dbfa4b5SAllan Jude 		GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
5591dbfa4b5SAllan Jude 		carc_stats[0] = arc_stat >> 10;
560d9a72328SAllan Jude 		carc_stats[2] = arc_stat >> 10; /* For ratio */
5611dbfa4b5SAllan Jude 		GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
5621dbfa4b5SAllan Jude 		carc_stats[1] = arc_stat >> 10;
5631dbfa4b5SAllan Jude 		si->carc = carc_stats;
5641dbfa4b5SAllan Jude 	}
5652e52fb92SJohn Baldwin 
566511d9c65SJoerg Wunsch 	/* set arrays and strings */
56703117570SPeter Wemm 	if (pcpu_stats) {
56803117570SPeter Wemm 		si->cpustates = pcpu_cpu_states;
56903117570SPeter Wemm 		si->ncpus = ncpus;
57003117570SPeter Wemm 	} else {
571511d9c65SJoerg Wunsch 		si->cpustates = cpu_states;
57203117570SPeter Wemm 		si->ncpus = 1;
57303117570SPeter Wemm 	}
574511d9c65SJoerg Wunsch 	si->memory = memory_stats;
575511d9c65SJoerg Wunsch 	si->swap = swap_stats;
576511d9c65SJoerg Wunsch 
577511d9c65SJoerg Wunsch 
578511d9c65SJoerg Wunsch 	if (lastpid > 0) {
579511d9c65SJoerg Wunsch 		si->last_pid = lastpid;
580511d9c65SJoerg Wunsch 	} else {
581511d9c65SJoerg Wunsch 		si->last_pid = -1;
582511d9c65SJoerg Wunsch 	}
583a2641311SDavid E. O'Brien 
584a2641311SDavid E. O'Brien 	/*
585a2641311SDavid E. O'Brien 	 * Print how long system has been up.
586a2641311SDavid E. O'Brien 	 * (Found by looking getting "boottime" from the kernel)
587a2641311SDavid E. O'Brien 	 */
588a2641311SDavid E. O'Brien 	mib[0] = CTL_KERN;
589a2641311SDavid E. O'Brien 	mib[1] = KERN_BOOTTIME;
5902e52fb92SJohn Baldwin 	size = sizeof(boottime);
591a22656f0SEnji Cooper 	if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
592a2641311SDavid E. O'Brien 	    boottime.tv_sec != 0) {
593a2641311SDavid E. O'Brien 		si->boottime = boottime;
594a2641311SDavid E. O'Brien 	} else {
595a2641311SDavid E. O'Brien 		si->boottime.tv_sec = -1;
596a2641311SDavid E. O'Brien 	}
597fc8ae86aSPhilip Paeps 
598fc8ae86aSPhilip Paeps 	battery_life = 0;
599fc8ae86aSPhilip Paeps 	if (battery_units > 0) {
600fc8ae86aSPhilip Paeps 		GETSYSCTL("hw.acpi.battery.life", battery_life);
601fc8ae86aSPhilip Paeps 	}
602fc8ae86aSPhilip Paeps 	si->battery = battery_life;
603511d9c65SJoerg Wunsch }
604511d9c65SJoerg Wunsch 
60598c151d6SAlfred Perlstein #define NOPROC	((void *)-1)
60698c151d6SAlfred Perlstein 
607dcd6f4bdSAlfred Perlstein /*
608dcd6f4bdSAlfred Perlstein  * We need to compare data from the old process entry with the new
609dcd6f4bdSAlfred Perlstein  * process entry.
610dcd6f4bdSAlfred Perlstein  * To facilitate doing this quickly we stash a pointer in the kinfo_proc
611dcd6f4bdSAlfred Perlstein  * structure to cache the mapping.  We also use a negative cache pointer
612dcd6f4bdSAlfred Perlstein  * of NOPROC to avoid duplicate lookups.
613dcd6f4bdSAlfred Perlstein  * XXX: this could be done when the actual processes are fetched, we do
614dcd6f4bdSAlfred Perlstein  * it here out of laziness.
615dcd6f4bdSAlfred Perlstein  */
616666cf873SEitan Adler static const struct kinfo_proc *
get_old_proc(struct kinfo_proc * pp)617db6bb7fcSAlfred Perlstein get_old_proc(struct kinfo_proc *pp)
618db6bb7fcSAlfred Perlstein {
619d408c8f7SEitan Adler 	const struct kinfo_proc * const *oldpp, *oldp;
620db6bb7fcSAlfred Perlstein 
621dcd6f4bdSAlfred Perlstein 	/*
622dcd6f4bdSAlfred Perlstein 	 * If this is the first fetch of the kinfo_procs then we don't have
623dcd6f4bdSAlfred Perlstein 	 * any previous entries.
624dcd6f4bdSAlfred Perlstein 	 */
625db6bb7fcSAlfred Perlstein 	if (previous_proc_count == 0)
626db6bb7fcSAlfred Perlstein 		return (NULL);
627dcd6f4bdSAlfred Perlstein 	/* negative cache? */
62898c151d6SAlfred Perlstein 	if (pp->ki_udata == NOPROC)
62998c151d6SAlfred Perlstein 		return (NULL);
630dcd6f4bdSAlfred Perlstein 	/* cached? */
63198c151d6SAlfred Perlstein 	if (pp->ki_udata != NULL)
63298c151d6SAlfred Perlstein 		return (pp->ki_udata);
633dcd6f4bdSAlfred Perlstein 	/*
634dcd6f4bdSAlfred Perlstein 	 * Not cached,
635dcd6f4bdSAlfred Perlstein 	 * 1) look up based on pid.
636dcd6f4bdSAlfred Perlstein 	 * 2) compare process start.
637dcd6f4bdSAlfred Perlstein 	 * If we fail here, then setup a negative cache entry, otherwise
638dcd6f4bdSAlfred Perlstein 	 * cache it.
639dcd6f4bdSAlfred Perlstein 	 */
640db6bb7fcSAlfred Perlstein 	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
6412417d97eSJohn Baldwin 	    sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
64298c151d6SAlfred Perlstein 	if (oldpp == NULL) {
64398c151d6SAlfred Perlstein 		pp->ki_udata = NOPROC;
644db6bb7fcSAlfred Perlstein 		return (NULL);
64598c151d6SAlfred Perlstein 	}
646db6bb7fcSAlfred Perlstein 	oldp = *oldpp;
6478d0d2676SEitan Adler 	if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
64898c151d6SAlfred Perlstein 		pp->ki_udata = NOPROC;
649db6bb7fcSAlfred Perlstein 		return (NULL);
65098c151d6SAlfred Perlstein 	}
651d0f687d3SDimitry Andric 	pp->ki_udata = __DECONST(void *, oldp);
652db6bb7fcSAlfred Perlstein 	return (oldp);
653db6bb7fcSAlfred Perlstein }
654db6bb7fcSAlfred Perlstein 
655dcd6f4bdSAlfred Perlstein /*
656dcd6f4bdSAlfred Perlstein  * Return the total amount of IO done in blocks in/out and faults.
657dcd6f4bdSAlfred Perlstein  * store the values individually in the pointers passed in.
658dcd6f4bdSAlfred Perlstein  */
659666cf873SEitan Adler static long
get_io_stats(const struct kinfo_proc * pp,long * inp,long * oup,long * flp,long * vcsw,long * ivcsw)6609f8096e3SEitan Adler get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
661789e3877SBruce Evans     long *vcsw, long *ivcsw)
662db6bb7fcSAlfred Perlstein {
663db6bb7fcSAlfred Perlstein 	const struct kinfo_proc *oldp;
664db6bb7fcSAlfred Perlstein 	static struct kinfo_proc dummy;
665db6bb7fcSAlfred Perlstein 	long ret;
666db6bb7fcSAlfred Perlstein 
667d0f687d3SDimitry Andric 	oldp = get_old_proc(__DECONST(struct kinfo_proc *, pp));
668db6bb7fcSAlfred Perlstein 	if (oldp == NULL) {
6698d0d2676SEitan Adler 		memset(&dummy, 0, sizeof(dummy));
670db6bb7fcSAlfred Perlstein 		oldp = &dummy;
671db6bb7fcSAlfred Perlstein 	}
6727fe9a86aSAlfred Perlstein 	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
6737fe9a86aSAlfred Perlstein 	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
6747fe9a86aSAlfred Perlstein 	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
6755d320d4bSAlfred Perlstein 	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
6765d320d4bSAlfred Perlstein 	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
677db6bb7fcSAlfred Perlstein 	ret =
678db6bb7fcSAlfred Perlstein 	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
679db6bb7fcSAlfred Perlstein 	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
680db6bb7fcSAlfred Perlstein 	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
681db6bb7fcSAlfred Perlstein 	return (ret);
682db6bb7fcSAlfred Perlstein }
683db6bb7fcSAlfred Perlstein 
684dcd6f4bdSAlfred Perlstein /*
685a9053954SJohn Baldwin  * If there was a previous update, use the delta in ki_runtime over
686a9053954SJohn Baldwin  * the previous interval to calculate pctcpu.  Otherwise, fall back
687a9053954SJohn Baldwin  * to using the kernel's ki_pctcpu.
688a9053954SJohn Baldwin  */
689a9053954SJohn Baldwin static double
proc_calc_pctcpu(struct kinfo_proc * pp)690a9053954SJohn Baldwin proc_calc_pctcpu(struct kinfo_proc *pp)
691a9053954SJohn Baldwin {
692a9053954SJohn Baldwin 	const struct kinfo_proc *oldp;
693a9053954SJohn Baldwin 
694a9053954SJohn Baldwin 	if (previous_interval != 0) {
695a9053954SJohn Baldwin 		oldp = get_old_proc(pp);
696a9053954SJohn Baldwin 		if (oldp != NULL)
697a9053954SJohn Baldwin 			return ((double)(pp->ki_runtime - oldp->ki_runtime)
698a9053954SJohn Baldwin 			    / previous_interval);
699a9053954SJohn Baldwin 
700a9053954SJohn Baldwin 		/*
701a9053954SJohn Baldwin 		 * If this process/thread was created during the previous
702a9053954SJohn Baldwin 		 * interval, charge it's total runtime to the previous
703a9053954SJohn Baldwin 		 * interval.
704a9053954SJohn Baldwin 		 */
705a9053954SJohn Baldwin 		else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
706a9053954SJohn Baldwin 		    (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
707a9053954SJohn Baldwin 		    pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
708a9053954SJohn Baldwin 			return ((double)pp->ki_runtime / previous_interval);
709a9053954SJohn Baldwin 	}
710a9053954SJohn Baldwin 	return (pctdouble(pp->ki_pctcpu));
711a9053954SJohn Baldwin }
712a9053954SJohn Baldwin 
713a9053954SJohn Baldwin /*
714a9053954SJohn Baldwin  * Return true if this process has used any CPU time since the
715a9053954SJohn Baldwin  * previous update.
716a9053954SJohn Baldwin  */
717a9053954SJohn Baldwin static int
proc_used_cpu(struct kinfo_proc * pp)718a9053954SJohn Baldwin proc_used_cpu(struct kinfo_proc *pp)
719a9053954SJohn Baldwin {
720a9053954SJohn Baldwin 	const struct kinfo_proc *oldp;
721a9053954SJohn Baldwin 
722a9053954SJohn Baldwin 	oldp = get_old_proc(pp);
723a9053954SJohn Baldwin 	if (oldp == NULL)
724a9053954SJohn Baldwin 		return (PCTCPU(pp) != 0);
725a9053954SJohn Baldwin 	return (pp->ki_runtime != oldp->ki_runtime ||
726a9053954SJohn Baldwin 	    RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
727a9053954SJohn Baldwin 	    RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
728a9053954SJohn Baldwin }
729a9053954SJohn Baldwin 
730a9053954SJohn Baldwin /*
731dcd6f4bdSAlfred Perlstein  * Return the total number of block in/out and faults by a process.
732dcd6f4bdSAlfred Perlstein  */
733666cf873SEitan Adler static long
get_io_total(const struct kinfo_proc * pp)7349f8096e3SEitan Adler get_io_total(const struct kinfo_proc *pp)
7357fe9a86aSAlfred Perlstein {
7367fe9a86aSAlfred Perlstein 	long dummy;
7377fe9a86aSAlfred Perlstein 
7385d320d4bSAlfred Perlstein 	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
7397fe9a86aSAlfred Perlstein }
7407fe9a86aSAlfred Perlstein 
741511d9c65SJoerg Wunsch static struct handle handle;
742511d9c65SJoerg Wunsch 
7431b7645c6SEitan Adler void *
get_process_info(struct system_info * si,struct process_select * sel,int (* compare)(const void *,const void *))744f6a10feaSDag-Erling Smørgrav get_process_info(struct system_info *si, struct process_select *sel,
7454946a00bSDag-Erling Smørgrav     int (*compare)(const void *, const void *))
746511d9c65SJoerg Wunsch {
747970636e9SAlfred Perlstein 	int i;
748970636e9SAlfred Perlstein 	int total_procs;
7497fe9a86aSAlfred Perlstein 	long p_io;
7505d320d4bSAlfred Perlstein 	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
751a9053954SJohn Baldwin 	long nsec;
752970636e9SAlfred Perlstein 	int active_procs;
753970636e9SAlfred Perlstein 	struct kinfo_proc **prefp;
754970636e9SAlfred Perlstein 	struct kinfo_proc *pp;
755a9053954SJohn Baldwin 	struct timespec previous_proc_uptime;
756511d9c65SJoerg Wunsch 
757db6bb7fcSAlfred Perlstein 	/*
758a9053954SJohn Baldwin 	 * If thread state was toggled, don't cache the previous processes.
759a9053954SJohn Baldwin 	 */
760a9053954SJohn Baldwin 	if (previous_thread != sel->thread)
761a9053954SJohn Baldwin 		nproc = 0;
762a9053954SJohn Baldwin 	previous_thread = sel->thread;
763a9053954SJohn Baldwin 
764a9053954SJohn Baldwin 	/*
765db6bb7fcSAlfred Perlstein 	 * Save the previous process info.
766db6bb7fcSAlfred Perlstein 	 */
767db6bb7fcSAlfred Perlstein 	if (previous_proc_count_max < nproc) {
768db6bb7fcSAlfred Perlstein 		free(previous_procs);
7694fedcd49SEitan Adler 		previous_procs = calloc(nproc, sizeof(*previous_procs));
770db6bb7fcSAlfred Perlstein 		free(previous_pref);
7714fedcd49SEitan Adler 		previous_pref = calloc(nproc, sizeof(*previous_pref));
772db6bb7fcSAlfred Perlstein 		if (previous_procs == NULL || previous_pref == NULL) {
7734fedcd49SEitan Adler 			fprintf(stderr, "top: Out of memory.\n");
77451b29cb7SRoman Bogorodskiy 			quit(TOP_EX_SYS_ERROR);
775db6bb7fcSAlfred Perlstein 		}
776db6bb7fcSAlfred Perlstein 		previous_proc_count_max = nproc;
777db6bb7fcSAlfred Perlstein 	}
778db6bb7fcSAlfred Perlstein 	if (nproc) {
779db6bb7fcSAlfred Perlstein 		for (i = 0; i < nproc; i++)
780db6bb7fcSAlfred Perlstein 			previous_pref[i] = &previous_procs[i];
7815dc98aeeSEitan Adler 		memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
782789e3877SBruce Evans 		qsort(previous_pref, nproc, sizeof(*previous_pref),
7832417d97eSJohn Baldwin 		    ps.thread ? compare_tid : compare_pid);
784db6bb7fcSAlfred Perlstein 	}
785db6bb7fcSAlfred Perlstein 	previous_proc_count = nproc;
786a9053954SJohn Baldwin 	previous_proc_uptime = proc_uptime;
787a9053954SJohn Baldwin 	previous_wall_time = proc_wall_time;
788a9053954SJohn Baldwin 	previous_interval = 0;
789db6bb7fcSAlfred Perlstein 
790b225f36eSJohn Baldwin 	pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
791b225f36eSJohn Baldwin 	    0, &nproc);
7924fb80c70SEitan Adler 	gettimeofday(&proc_wall_time, NULL);
793a9053954SJohn Baldwin 	if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
794a9053954SJohn Baldwin 		memset(&proc_uptime, 0, sizeof(proc_uptime));
795a9053954SJohn Baldwin 	else if (previous_proc_uptime.tv_sec != 0 &&
796a9053954SJohn Baldwin 	    previous_proc_uptime.tv_nsec != 0) {
797a9053954SJohn Baldwin 		previous_interval = (proc_uptime.tv_sec -
798a9053954SJohn Baldwin 		    previous_proc_uptime.tv_sec) * 1000000;
799a9053954SJohn Baldwin 		nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
800a9053954SJohn Baldwin 		if (nsec < 0) {
801a9053954SJohn Baldwin 			previous_interval -= 1000000;
802a9053954SJohn Baldwin 			nsec += 1000000000;
803a9053954SJohn Baldwin 		}
804a9053954SJohn Baldwin 		previous_interval += nsec / 1000;
805a9053954SJohn Baldwin 	}
806a9053954SJohn Baldwin 	if (nproc > onproc) {
807a9053954SJohn Baldwin 		pref = realloc(pref, sizeof(*pref) * nproc);
808a9053954SJohn Baldwin 		pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
809a9053954SJohn Baldwin 		onproc = nproc;
810a9053954SJohn Baldwin 	}
811a9053954SJohn Baldwin 	if (pref == NULL || pbase == NULL || pcpu == NULL) {
8124fb80c70SEitan Adler 		fprintf(stderr, "top: Out of memory.\n");
81351b29cb7SRoman Bogorodskiy 		quit(TOP_EX_SYS_ERROR);
814511d9c65SJoerg Wunsch 	}
815511d9c65SJoerg Wunsch 	/* get a pointer to the states summary array */
816511d9c65SJoerg Wunsch 	si->procstates = process_states;
817511d9c65SJoerg Wunsch 
818511d9c65SJoerg Wunsch 	/* count up process states and get pointers to interesting procs */
819511d9c65SJoerg Wunsch 	total_procs = 0;
820511d9c65SJoerg Wunsch 	active_procs = 0;
8217fe9a86aSAlfred Perlstein 	total_inblock = 0;
8227fe9a86aSAlfred Perlstein 	total_oublock = 0;
8237fe9a86aSAlfred Perlstein 	total_majflt = 0;
8240059e710SEitan Adler 	memset(process_states, 0, sizeof(process_states));
825511d9c65SJoerg Wunsch 	prefp = pref;
8264946a00bSDag-Erling Smørgrav 	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
8277fe9a86aSAlfred Perlstein 
828d62a717dSDag-Erling Smørgrav 		if (pp->ki_stat == 0)
829d62a717dSDag-Erling Smørgrav 			/* not in use */
830d62a717dSDag-Erling Smørgrav 			continue;
831d62a717dSDag-Erling Smørgrav 
832ef436ca6SEitan Adler 		if (!sel->self && pp->ki_pid == mypid && sel->pid == -1)
833d62a717dSDag-Erling Smørgrav 			/* skip self */
834d62a717dSDag-Erling Smørgrav 			continue;
835d62a717dSDag-Erling Smørgrav 
836ef436ca6SEitan Adler 		if (!sel->system && (pp->ki_flag & P_SYSTEM) && sel->pid == -1)
837d62a717dSDag-Erling Smørgrav 			/* skip system process */
838d62a717dSDag-Erling Smørgrav 			continue;
839d62a717dSDag-Erling Smørgrav 
840789e3877SBruce Evans 		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
841789e3877SBruce Evans 		    &p_vcsw, &p_ivcsw);
8427fe9a86aSAlfred Perlstein 		total_inblock += p_inblock;
8437fe9a86aSAlfred Perlstein 		total_oublock += p_oublock;
8447fe9a86aSAlfred Perlstein 		total_majflt += p_majflt;
845511d9c65SJoerg Wunsch 		total_procs++;
8464901ca08SEitan Adler 		process_states[(unsigned char)pp->ki_stat]++;
847d62a717dSDag-Erling Smørgrav 
848d62a717dSDag-Erling Smørgrav 		if (pp->ki_stat == SZOMB)
849d62a717dSDag-Erling Smørgrav 			/* skip zombies */
850d62a717dSDag-Erling Smørgrav 			continue;
851d62a717dSDag-Erling Smørgrav 
852ef436ca6SEitan Adler 		if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD && sel->pid == -1)
853034b7b80SJohn Baldwin 			/* skip kernel idle process */
854034b7b80SJohn Baldwin 			continue;
855034b7b80SJohn Baldwin 
856a9053954SJohn Baldwin 		PCTCPU(pp) = proc_calc_pctcpu(pp);
857e876f6d0SJohn Baldwin 		if (sel->thread && PCTCPU(pp) > 1.0)
858e876f6d0SJohn Baldwin 			PCTCPU(pp) = 1.0;
8594fb80c70SEitan Adler 		if (displaymode == DISP_CPU && !sel->idle &&
860a9053954SJohn Baldwin 		    (!proc_used_cpu(pp) ||
861d1b76f3fSStefan Eßer 		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
862d62a717dSDag-Erling Smørgrav 			/* skip idle or non-running processes */
863d62a717dSDag-Erling Smørgrav 			continue;
864d62a717dSDag-Erling Smørgrav 
8654fb80c70SEitan Adler 		if (displaymode == DISP_IO && !sel->idle && p_io == 0)
866d62a717dSDag-Erling Smørgrav 			/* skip processes that aren't doing I/O */
867d62a717dSDag-Erling Smørgrav 			continue;
868d62a717dSDag-Erling Smørgrav 
8694fb80c70SEitan Adler 		if (sel->jid != -1 && pp->ki_jid != sel->jid)
8701b60f972SBryan Drewery 			/* skip proc. that don't belong to the selected JID */
8711b60f972SBryan Drewery 			continue;
8721b60f972SBryan Drewery 
8734fb80c70SEitan Adler 		if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
874789e3877SBruce Evans 			/* skip proc. that don't belong to the selected UID */
875d62a717dSDag-Erling Smørgrav 			continue;
876d62a717dSDag-Erling Smørgrav 
8774fb80c70SEitan Adler 		if (sel->pid != -1 && pp->ki_pid != sel->pid)
87851b29cb7SRoman Bogorodskiy 			continue;
87951b29cb7SRoman Bogorodskiy 
880a00d703fSJohn Grafton 		if (!cmd_matches(pp, sel->command))
881a00d703fSJohn Grafton 			/* skip proc. that doesn't match grep string */
882a00d703fSJohn Grafton 			continue;
883a00d703fSJohn Grafton 
884511d9c65SJoerg Wunsch 		*prefp++ = pp;
885511d9c65SJoerg Wunsch 		active_procs++;
886511d9c65SJoerg Wunsch 	}
887511d9c65SJoerg Wunsch 
888511d9c65SJoerg Wunsch 	/* if requested, sort the "interesting" processes */
889511d9c65SJoerg Wunsch 	if (compare != NULL)
8904946a00bSDag-Erling Smørgrav 		qsort(pref, active_procs, sizeof(*pref), compare);
891511d9c65SJoerg Wunsch 
892511d9c65SJoerg Wunsch 	/* remember active and total counts */
893511d9c65SJoerg Wunsch 	si->p_total = total_procs;
8945ef89dbfSEitan Adler 	si->p_pactive = pref_len = active_procs;
895511d9c65SJoerg Wunsch 
896511d9c65SJoerg Wunsch 	/* pass back a handle */
897511d9c65SJoerg Wunsch 	handle.next_proc = pref;
898511d9c65SJoerg Wunsch 	handle.remaining = active_procs;
8994fb80c70SEitan Adler 	return (&handle);
900511d9c65SJoerg Wunsch }
901511d9c65SJoerg Wunsch 
902a00d703fSJohn Grafton static int
cmd_matches(struct kinfo_proc * proc,const char * term)903a00d703fSJohn Grafton cmd_matches(struct kinfo_proc *proc, const char *term)
904a00d703fSJohn Grafton {
905a00d703fSJohn Grafton 	char **args = NULL;
906a00d703fSJohn Grafton 
907a00d703fSJohn Grafton 	if (!term) {
908a00d703fSJohn Grafton 		/* No command filter set */
909a00d703fSJohn Grafton 		return 1;
910a00d703fSJohn Grafton 	} else {
911a00d703fSJohn Grafton 		/* Filter set, does process name contain term? */
912a00d703fSJohn Grafton 		if (strstr(proc->ki_comm, term))
913a00d703fSJohn Grafton 			return 1;
914a00d703fSJohn Grafton 		/* Search arguments only if arguments are displayed */
915a00d703fSJohn Grafton 		if (show_args) {
916a00d703fSJohn Grafton 			args = kvm_getargv(kd, proc, 1024);
917a00d703fSJohn Grafton 			if (args == NULL) {
918a00d703fSJohn Grafton 				/* Failed to get arguments so can't search them */
919a00d703fSJohn Grafton 				return 0;
920a00d703fSJohn Grafton 			}
921a00d703fSJohn Grafton 			while (*args != NULL) {
922a00d703fSJohn Grafton 				if (strstr(*args, term))
923a00d703fSJohn Grafton 					return 1;
924a00d703fSJohn Grafton 				args++;
925a00d703fSJohn Grafton 			}
926a00d703fSJohn Grafton 		}
927a00d703fSJohn Grafton 	}
928a00d703fSJohn Grafton 	return 0;
929a00d703fSJohn Grafton }
930a00d703fSJohn Grafton 
931970636e9SAlfred Perlstein char *
format_next_process(struct handle * xhandle,char * (* get_userid)(int),int flags)9328caf462eSEitan Adler format_next_process(struct handle * xhandle, char *(*get_userid)(int), int flags)
933511d9c65SJoerg Wunsch {
934970636e9SAlfred Perlstein 	struct kinfo_proc *pp;
935db6bb7fcSAlfred Perlstein 	const struct kinfo_proc *oldp;
936970636e9SAlfred Perlstein 	long cputime;
937dbcdf411SEitan Adler 	char status[22];
938666cf873SEitan Adler 	size_t state;
939db6bb7fcSAlfred Perlstein 	struct rusage ru, *rup;
9407fe9a86aSAlfred Perlstein 	long p_tot, s_tot;
941faac60c8SStanislav Sedov 	char *cmdbuf = NULL;
942eae589f1SEitan Adler 	char **args;
9430515b88eSEitan Adler 	static struct sbuf* procbuf = NULL;
9440515b88eSEitan Adler 
9450515b88eSEitan Adler 	/* clean up from last time. */
9460515b88eSEitan Adler 	if (procbuf != NULL) {
9470515b88eSEitan Adler 		sbuf_clear(procbuf);
9480515b88eSEitan Adler 	} else {
9490515b88eSEitan Adler 		procbuf = sbuf_new_auto();
9500515b88eSEitan Adler 	}
9510515b88eSEitan Adler 
952511d9c65SJoerg Wunsch 
953511d9c65SJoerg Wunsch 	/* find and remember the next proc structure */
9548caf462eSEitan Adler 	pp = *(xhandle->next_proc++);
9558caf462eSEitan Adler 	xhandle->remaining--;
956511d9c65SJoerg Wunsch 
957a8224b82SBruce Evans 	/* get the process's command name */
958b61ce5b0SJeff Roberson 	if ((pp->ki_flag & P_INMEM) == 0) {
959511d9c65SJoerg Wunsch 		/*
960511d9c65SJoerg Wunsch 		 * Print swapped processes as <pname>
961511d9c65SJoerg Wunsch 		 */
962789e3877SBruce Evans 		size_t len;
963789e3877SBruce Evans 
964789e3877SBruce Evans 		len = strlen(pp->ki_comm);
9654946a00bSDag-Erling Smørgrav 		if (len > sizeof(pp->ki_comm) - 3)
9664946a00bSDag-Erling Smørgrav 			len = sizeof(pp->ki_comm) - 3;
9674946a00bSDag-Erling Smørgrav 		memmove(pp->ki_comm + 1, pp->ki_comm, len);
9684946a00bSDag-Erling Smørgrav 		pp->ki_comm[0] = '<';
9694946a00bSDag-Erling Smørgrav 		pp->ki_comm[len + 1] = '>';
9704946a00bSDag-Erling Smørgrav 		pp->ki_comm[len + 2] = '\0';
971511d9c65SJoerg Wunsch 	}
972511d9c65SJoerg Wunsch 
973a8224b82SBruce Evans 	/*
974a8224b82SBruce Evans 	 * Convert the process's runtime from microseconds to seconds.  This
975a8224b82SBruce Evans 	 * time includes the interrupt time although that is not wanted here.
976a8224b82SBruce Evans 	 * ps(1) is similarly sloppy.
977a8224b82SBruce Evans 	 */
9781f7d2501SKirk McKusick 	cputime = (pp->ki_runtime + 500000) / 1000000;
979511d9c65SJoerg Wunsch 
980511d9c65SJoerg Wunsch 	/* generate "STATE" field */
9811f7d2501SKirk McKusick 	switch (state = pp->ki_stat) {
982511d9c65SJoerg Wunsch 	case SRUN:
983b666b032SJung-uk Kim 		if (smpmode && pp->ki_oncpu != NOCPU)
9841f7d2501SKirk McKusick 			sprintf(status, "CPU%d", pp->ki_oncpu);
985511d9c65SJoerg Wunsch 		else
986511d9c65SJoerg Wunsch 			strcpy(status, "RUN");
987511d9c65SJoerg Wunsch 		break;
9880d632649SJohn Baldwin 	case SLOCK:
9890d632649SJohn Baldwin 		if (pp->ki_kiflag & KI_LOCKBLOCK) {
9900d632649SJohn Baldwin 			sprintf(status, "*%.6s", pp->ki_lockname);
991089f9b7eSJohn Baldwin 			break;
992089f9b7eSJohn Baldwin 		}
993089f9b7eSJohn Baldwin 		/* fall through */
994511d9c65SJoerg Wunsch 	case SSLEEP:
9951f7d2501SKirk McKusick 		sprintf(status, "%.6s", pp->ki_wmesg);
996511d9c65SJoerg Wunsch 		break;
997511d9c65SJoerg Wunsch 	default:
9981005b436SBill Fenner 
9999f8096e3SEitan Adler 		if (state < nitems(state_abbrev)) {
10004946a00bSDag-Erling Smørgrav 			sprintf(status, "%.6s", state_abbrev[state]);
10019f8096e3SEitan Adler 		} else {
1002986a5bafSEitan Adler 			sprintf(status, "?%5zu", state);
10039f8096e3SEitan Adler 		}
1004511d9c65SJoerg Wunsch 		break;
1005511d9c65SJoerg Wunsch 	}
1006511d9c65SJoerg Wunsch 
10070a59db87SDaichi GOTO 	cmdbuf = calloc(screen_width + 1, 1);
1008faac60c8SStanislav Sedov 	if (cmdbuf == NULL) {
10090a59db87SDaichi GOTO 		warn("calloc(%d)", screen_width + 1);
1010faac60c8SStanislav Sedov 		return NULL;
1011faac60c8SStanislav Sedov 	}
1012faac60c8SStanislav Sedov 
1013faac60c8SStanislav Sedov 	if (!(flags & FMT_SHOWARGS)) {
10147ab24ea3SJulian Elischer 		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1015925af544SBjoern A. Zeeb 		    pp->ki_tdname[0]) {
10160a59db87SDaichi GOTO 			snprintf(cmdbuf, screen_width, "%s{%s%s}", pp->ki_comm,
10173d32d4a7SEric van Gyzen 			    pp->ki_tdname, pp->ki_moretdname);
10187ab24ea3SJulian Elischer 		} else {
10190a59db87SDaichi GOTO 			snprintf(cmdbuf, screen_width, "%s", pp->ki_comm);
1020faac60c8SStanislav Sedov 		}
10217ab24ea3SJulian Elischer 	} else {
10227ab24ea3SJulian Elischer 		if (pp->ki_flag & P_SYSTEM ||
10230a59db87SDaichi GOTO 		    (args = kvm_getargv(kd, pp, screen_width)) == NULL ||
10247ab24ea3SJulian Elischer 		    !(*args)) {
10257ab24ea3SJulian Elischer 			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1026925af544SBjoern A. Zeeb 		    	    pp->ki_tdname[0]) {
10270a59db87SDaichi GOTO 				snprintf(cmdbuf, screen_width,
10283d32d4a7SEric van Gyzen 				    "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
10293d32d4a7SEric van Gyzen 				    pp->ki_moretdname);
10307ab24ea3SJulian Elischer 			} else {
10310a59db87SDaichi GOTO 				snprintf(cmdbuf, screen_width,
10327ab24ea3SJulian Elischer 				    "[%s]", pp->ki_comm);
10337ab24ea3SJulian Elischer 			}
10347ab24ea3SJulian Elischer 		} else {
1035eae589f1SEitan Adler 			const char *src;
1036eae589f1SEitan Adler 			char *dst, *argbuf;
1037eae589f1SEitan Adler 			const char *cmd;
1038faac60c8SStanislav Sedov 			size_t argbuflen;
1039faac60c8SStanislav Sedov 			size_t len;
1040faac60c8SStanislav Sedov 
10410a59db87SDaichi GOTO 			argbuflen = screen_width * 4;
10424fedcd49SEitan Adler 			argbuf = calloc(argbuflen + 1, 1);
1043faac60c8SStanislav Sedov 			if (argbuf == NULL) {
10444fedcd49SEitan Adler 				warn("calloc(%zu)", argbuflen + 1);
1045faac60c8SStanislav Sedov 				free(cmdbuf);
1046faac60c8SStanislav Sedov 				return NULL;
1047faac60c8SStanislav Sedov 			}
1048faac60c8SStanislav Sedov 
1049faac60c8SStanislav Sedov 			dst = argbuf;
1050faac60c8SStanislav Sedov 
1051faac60c8SStanislav Sedov 			/* Extract cmd name from argv */
1052ac8f40eaSEitan Adler 			cmd = basename(*args);
1053faac60c8SStanislav Sedov 
1054faac60c8SStanislav Sedov 			for (; (src = *args++) != NULL; ) {
1055faac60c8SStanislav Sedov 				if (*src == '\0')
1056faac60c8SStanislav Sedov 					continue;
1057faac60c8SStanislav Sedov 				len = (argbuflen - (dst - argbuf) - 1) / 4;
10587ab24ea3SJulian Elischer 				strvisx(dst, src,
1059cd59e2f3SMarcelo Araujo 				    MIN(strlen(src), len),
106013858b88SYuri Pankov 				    VIS_NL | VIS_TAB | VIS_CSTYLE | VIS_OCTAL);
1061faac60c8SStanislav Sedov 				while (*dst != '\0')
1062faac60c8SStanislav Sedov 					dst++;
1063faac60c8SStanislav Sedov 				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1064faac60c8SStanislav Sedov 					*dst++ = ' '; /* add delimiting space */
1065faac60c8SStanislav Sedov 			}
1066faac60c8SStanislav Sedov 			if (dst != argbuf && dst[-1] == ' ')
1067faac60c8SStanislav Sedov 				dst--;
1068faac60c8SStanislav Sedov 			*dst = '\0';
1069faac60c8SStanislav Sedov 
1070c618a522SBjoern A. Zeeb 			if (strcmp(cmd, pp->ki_comm) != 0) {
1071c618a522SBjoern A. Zeeb 				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1072c618a522SBjoern A. Zeeb 				    pp->ki_tdname[0])
10730a59db87SDaichi GOTO 					snprintf(cmdbuf, screen_width,
10743d32d4a7SEric van Gyzen 					    "%s (%s){%s%s}", argbuf,
10753d32d4a7SEric van Gyzen 					    pp->ki_comm, pp->ki_tdname,
10763d32d4a7SEric van Gyzen 					    pp->ki_moretdname);
1077c618a522SBjoern A. Zeeb 				else
10780a59db87SDaichi GOTO 					snprintf(cmdbuf, screen_width,
10797ab24ea3SJulian Elischer 					    "%s (%s)", argbuf, pp->ki_comm);
1080c618a522SBjoern A. Zeeb 			} else {
1081c618a522SBjoern A. Zeeb 				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1082c618a522SBjoern A. Zeeb 				    pp->ki_tdname[0])
10830a59db87SDaichi GOTO 					snprintf(cmdbuf, screen_width,
10843d32d4a7SEric van Gyzen 					    "%s{%s%s}", argbuf, pp->ki_tdname,
10853d32d4a7SEric van Gyzen 					    pp->ki_moretdname);
1086faac60c8SStanislav Sedov 				else
10870a59db87SDaichi GOTO 					strlcpy(cmdbuf, argbuf, screen_width);
1088c618a522SBjoern A. Zeeb 			}
1089faac60c8SStanislav Sedov 			free(argbuf);
1090faac60c8SStanislav Sedov 		}
10917ab24ea3SJulian Elischer 	}
1092faac60c8SStanislav Sedov 
1093db6bb7fcSAlfred Perlstein 	if (displaymode == DISP_IO) {
1094db6bb7fcSAlfred Perlstein 		oldp = get_old_proc(pp);
1095db6bb7fcSAlfred Perlstein 		if (oldp != NULL) {
1096789e3877SBruce Evans 			ru.ru_inblock = RU(pp)->ru_inblock -
1097789e3877SBruce Evans 			    RU(oldp)->ru_inblock;
1098789e3877SBruce Evans 			ru.ru_oublock = RU(pp)->ru_oublock -
1099789e3877SBruce Evans 			    RU(oldp)->ru_oublock;
1100db6bb7fcSAlfred Perlstein 			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
11015d320d4bSAlfred Perlstein 			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
11025d320d4bSAlfred Perlstein 			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1103db6bb7fcSAlfred Perlstein 			rup = &ru;
1104db6bb7fcSAlfred Perlstein 		} else {
1105db6bb7fcSAlfred Perlstein 			rup = RU(pp);
1106db6bb7fcSAlfred Perlstein 		}
11077fe9a86aSAlfred Perlstein 		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
11087fe9a86aSAlfred Perlstein 		s_tot = total_inblock + total_oublock + total_majflt;
1109db6bb7fcSAlfred Perlstein 
11100515b88eSEitan Adler 		sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1111db365663SEitan Adler 
1112db365663SEitan Adler 		if (ps.jail) {
1113db365663SEitan Adler 			sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1114db365663SEitan Adler 		}
11150515b88eSEitan Adler 		sbuf_printf(procbuf, "%-*.*s", namelength, namelength, (*get_userid)(pp->ki_ruid));
11160515b88eSEitan Adler 		sbuf_printf(procbuf, "%6ld ", rup->ru_nvcsw);
11170515b88eSEitan Adler 		sbuf_printf(procbuf, "%6ld ", rup->ru_nivcsw);
11180515b88eSEitan Adler 		sbuf_printf(procbuf, "%6ld ", rup->ru_inblock);
11190515b88eSEitan Adler 		sbuf_printf(procbuf, "%6ld ", rup->ru_oublock);
11200515b88eSEitan Adler 		sbuf_printf(procbuf, "%6ld ", rup->ru_majflt);
11210515b88eSEitan Adler 		sbuf_printf(procbuf, "%6ld ", p_tot);
11220515b88eSEitan Adler 		sbuf_printf(procbuf, "%6.2f%% ", s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot));
1123faac60c8SStanislav Sedov 
1124db365663SEitan Adler 	} else {
1125db365663SEitan Adler 		sbuf_printf(procbuf, "%5d ", (ps.thread_id) ? pp->ki_tid : pp->ki_pid);
1126db365663SEitan Adler 		if (ps.jail) {
1127db365663SEitan Adler 			sbuf_printf(procbuf, "%*d ", TOP_JID_LEN - 1, pp->ki_jid);
1128db365663SEitan Adler 		}
1129db365663SEitan Adler 		sbuf_printf(procbuf, "%-*.*s ", namelength, namelength, (*get_userid)(pp->ki_ruid));
1130db365663SEitan Adler 
1131db365663SEitan Adler 		if (!ps.thread) {
1132db365663SEitan Adler 			sbuf_printf(procbuf, "%4d ", pp->ki_numthreads);
1133fedded8dSMark Johnston 		} else {
1134fedded8dSMark Johnston 			sbuf_printf(procbuf, " ");
1135db6bb7fcSAlfred Perlstein 		}
113632efd263SGiorgos Keramidas 
11370515b88eSEitan Adler 		sbuf_printf(procbuf, "%3d ", pp->ki_pri.pri_level - PZERO);
11380515b88eSEitan Adler 		sbuf_printf(procbuf, "%4s", format_nice(pp));
113910550f0bSEitan Adler 		sbuf_printf(procbuf, "%7s ", format_k(PROCSIZE(pp)));
114010550f0bSEitan Adler 		sbuf_printf(procbuf, "%6s ", format_k(pagetok(pp->ki_rssize)));
1141db365663SEitan Adler 		if (ps.swap) {
1142db365663SEitan Adler 			sbuf_printf(procbuf, "%*s ",
1143db365663SEitan Adler 				TOP_SWAP_LEN - 1,
1144db365663SEitan Adler 				format_k(pagetok(ki_swap(pp))));
1145db365663SEitan Adler 		}
11460515b88eSEitan Adler 		sbuf_printf(procbuf, "%-6.6s ", status);
1147db365663SEitan Adler 		if (smpmode) {
1148db365663SEitan Adler 			int cpu;
1149db365663SEitan Adler 			if (state == SRUN && pp->ki_oncpu != NOCPU) {
1150db365663SEitan Adler 				cpu = pp->ki_oncpu;
1151db365663SEitan Adler 			} else {
1152db365663SEitan Adler 				cpu = pp->ki_lastcpu;
1153db365663SEitan Adler 			}
1154db365663SEitan Adler 			sbuf_printf(procbuf, "%3d ", cpu);
1155db365663SEitan Adler 		}
1156db365663SEitan Adler 		sbuf_printf(procbuf, "%6s ", format_time(cputime));
1157db365663SEitan Adler 		sbuf_printf(procbuf, "%6.2f%% ", ps.wcpu ? 100.0 * weighted_cpu(PCTCPU(pp), pp) : 100.0 * PCTCPU(pp));
1158db365663SEitan Adler 	}
1159b1de37faSDaichi GOTO 	sbuf_printf(procbuf, "%s", cmdbuf);
1160db365663SEitan Adler 	free(cmdbuf);
11610515b88eSEitan Adler 	return (sbuf_data(procbuf));
1162511d9c65SJoerg Wunsch }
1163511d9c65SJoerg Wunsch 
1164970636e9SAlfred Perlstein static void
getsysctl(const char * name,void * ptr,size_t len)1165de916c8bSBruce Evans getsysctl(const char *name, void *ptr, size_t len)
1166511d9c65SJoerg Wunsch {
116798e53e5bSAndrew Gallatin 	size_t nlen = len;
1168970636e9SAlfred Perlstein 
116939d513ecSRobert Watson 	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
117039d513ecSRobert Watson 		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
117139d513ecSRobert Watson 		    strerror(errno));
117251b29cb7SRoman Bogorodskiy 		quit(TOP_EX_SYS_ERROR);
1173511d9c65SJoerg Wunsch 	}
117439d513ecSRobert Watson 	if (nlen != len) {
1175789e3877SBruce Evans 		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1176789e3877SBruce Evans 		    name, (unsigned long)len, (unsigned long)nlen);
117751b29cb7SRoman Bogorodskiy 		quit(TOP_EX_SYS_ERROR);
1178511d9c65SJoerg Wunsch 	}
1179511d9c65SJoerg Wunsch }
1180511d9c65SJoerg Wunsch 
11818dbbff5bSBruce Evans static const char *
format_nice(const struct kinfo_proc * pp)11828dbbff5bSBruce Evans format_nice(const struct kinfo_proc *pp)
1183de916c8bSBruce Evans {
118478b7ef01SKonstantin Belousov 	const char *fifo, *kproc;
11858dbbff5bSBruce Evans 	int rtpri;
11868dbbff5bSBruce Evans 	static char nicebuf[4 + 1];
1187de916c8bSBruce Evans 
11888dbbff5bSBruce Evans 	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
118978b7ef01SKonstantin Belousov 	kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
11908dbbff5bSBruce Evans 	switch (PRI_BASE(pp->ki_pri.pri_class)) {
11918dbbff5bSBruce Evans 	case PRI_ITHD:
11928dbbff5bSBruce Evans 		return ("-");
11938dbbff5bSBruce Evans 	case PRI_REALTIME:
1194e19249f7SBruce Evans 		/*
1195e19249f7SBruce Evans 		 * XXX: the kernel doesn't tell us the original rtprio and
1196e19249f7SBruce Evans 		 * doesn't really know what it was, so to recover it we
1197e19249f7SBruce Evans 		 * must be more chummy with the implementation than the
1198e19249f7SBruce Evans 		 * implementation is with itself.  pri_user gives a
1199e19249f7SBruce Evans 		 * constant "base" priority, but is only initialized
1200e19249f7SBruce Evans 		 * properly for user threads.  pri_native gives what the
1201e19249f7SBruce Evans 		 * kernel calls the "base" priority, but it isn't constant
1202e19249f7SBruce Evans 		 * since it is changed by priority propagation.  pri_native
1203e19249f7SBruce Evans 		 * also isn't properly initialized for all threads, but it
1204e19249f7SBruce Evans 		 * is properly initialized for kernel realtime and idletime
1205e19249f7SBruce Evans 		 * threads.  Thus we use pri_user for the base priority of
1206e19249f7SBruce Evans 		 * user threads (it is always correct) and pri_native for
1207e19249f7SBruce Evans 		 * the base priority of kernel realtime and idletime threads
1208e19249f7SBruce Evans 		 * (there is nothing better, and it is usually correct).
1209e19249f7SBruce Evans 		 *
1210e19249f7SBruce Evans 		 * The field width and thus the buffer are too small for
1211e19249f7SBruce Evans 		 * values like "kr31F", but such values shouldn't occur,
1212e19249f7SBruce Evans 		 * and if they do then the tailing "F" is not displayed.
1213e19249f7SBruce Evans 		 */
1214db57c70aSKonstantin Belousov 		rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1215e19249f7SBruce Evans 		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
12168dbbff5bSBruce Evans 		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
121778b7ef01SKonstantin Belousov 		    kproc, rtpri, fifo);
12188dbbff5bSBruce Evans 		break;
12198dbbff5bSBruce Evans 	case PRI_TIMESHARE:
1220db57c70aSKonstantin Belousov 		if (pp->ki_flag & P_KPROC)
12218dbbff5bSBruce Evans 			return ("-");
12228dbbff5bSBruce Evans 		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
12238dbbff5bSBruce Evans 		break;
12248dbbff5bSBruce Evans 	case PRI_IDLE:
1225e19249f7SBruce Evans 		/* XXX: as above. */
1226db57c70aSKonstantin Belousov 		rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1227e19249f7SBruce Evans 		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
12288dbbff5bSBruce Evans 		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
122978b7ef01SKonstantin Belousov 		    kproc, rtpri, fifo);
12308dbbff5bSBruce Evans 		break;
12318dbbff5bSBruce Evans 	default:
12328dbbff5bSBruce Evans 		return ("?");
12338dbbff5bSBruce Evans 	}
1234de916c8bSBruce Evans 	return (nicebuf);
1235de916c8bSBruce Evans }
1236de916c8bSBruce Evans 
1237f3b2c2d1SWolfram Schneider /* comparison routines for qsort */
1238511d9c65SJoerg Wunsch 
1239de916c8bSBruce Evans static int
compare_pid(const void * p1,const void * p2)1240f6a10feaSDag-Erling Smørgrav compare_pid(const void *p1, const void *p2)
1241db6bb7fcSAlfred Perlstein {
1242db6bb7fcSAlfred Perlstein 	const struct kinfo_proc * const *pp1 = p1;
1243db6bb7fcSAlfred Perlstein 	const struct kinfo_proc * const *pp2 = p2;
1244db6bb7fcSAlfred Perlstein 
12459f8096e3SEitan Adler 	assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1246db6bb7fcSAlfred Perlstein 
1247db6bb7fcSAlfred Perlstein 	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1248db6bb7fcSAlfred Perlstein }
1249db6bb7fcSAlfred Perlstein 
12502417d97eSJohn Baldwin static int
compare_tid(const void * p1,const void * p2)12512417d97eSJohn Baldwin compare_tid(const void *p1, const void *p2)
12522417d97eSJohn Baldwin {
12532417d97eSJohn Baldwin 	const struct kinfo_proc * const *pp1 = p1;
12542417d97eSJohn Baldwin 	const struct kinfo_proc * const *pp2 = p2;
12552417d97eSJohn Baldwin 
12569f8096e3SEitan Adler 	assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
12572417d97eSJohn Baldwin 
12582417d97eSJohn Baldwin 	return ((*pp1)->ki_tid - (*pp2)->ki_tid);
12592417d97eSJohn Baldwin }
12602417d97eSJohn Baldwin 
1261511d9c65SJoerg Wunsch /*
1262511d9c65SJoerg Wunsch  *  proc_compare - comparison function for "qsort"
1263511d9c65SJoerg Wunsch  *	Compares the resource consumption of two processes using five
1264511d9c65SJoerg Wunsch  *	distinct keys.  The keys (in descending order of importance) are:
1265511d9c65SJoerg Wunsch  *	percent cpu, cpu ticks, state, resident set size, total virtual
1266511d9c65SJoerg Wunsch  *	memory usage.  The process states are ordered as follows (from least
1267d636fc5bSKonstantin Belousov  *	to most important):  run, zombie, idle, interrupt wait, stop, sleep.
1268d636fc5bSKonstantin Belousov  *	The array declaration below maps a process state index into a
1269d636fc5bSKonstantin Belousov  *	number that reflects this ordering.
1270511d9c65SJoerg Wunsch  */
1271511d9c65SJoerg Wunsch 
12725c639345SKonstantin Belousov static const int sorted_state[] = {
1273bc2ac258SKonstantin Belousov 	[SIDL] =	3,	/* being created	*/
1274bc2ac258SKonstantin Belousov 	[SRUN] =	1,	/* running/runnable	*/
1275bc2ac258SKonstantin Belousov 	[SSLEEP] =	6,	/* sleeping		*/
1276bc2ac258SKonstantin Belousov 	[SSTOP] =	5,	/* stopped/suspended	*/
1277bc2ac258SKonstantin Belousov 	[SZOMB] =	2,	/* zombie		*/
12785bd5470aSKonstantin Belousov 	[SWAIT] =	4,	/* intr			*/
12796a5e6a50SKonstantin Belousov 	[SLOCK] =	7,	/* blocked on lock	*/
1280511d9c65SJoerg Wunsch };
1281511d9c65SJoerg Wunsch 
1282f3b2c2d1SWolfram Schneider 
12834946a00bSDag-Erling Smørgrav #define ORDERKEY_PCTCPU(a, b) do { \
1284a9053954SJohn Baldwin 	double diff; \
1285bbf750fbSGiorgos Keramidas 	if (ps.wcpu) \
1286a9053954SJohn Baldwin 		diff = weighted_cpu(PCTCPU((b)), (b)) - \
1287a9053954SJohn Baldwin 		    weighted_cpu(PCTCPU((a)), (a)); \
1288bbf750fbSGiorgos Keramidas 	else \
1289a9053954SJohn Baldwin 		diff = PCTCPU((b)) - PCTCPU((a)); \
12904946a00bSDag-Erling Smørgrav 	if (diff != 0) \
12914946a00bSDag-Erling Smørgrav 		return (diff > 0 ? 1 : -1); \
12924946a00bSDag-Erling Smørgrav } while (0)
1293f3b2c2d1SWolfram Schneider 
12944946a00bSDag-Erling Smørgrav #define ORDERKEY_CPTICKS(a, b) do { \
1295e38035a5SDag-Erling Smørgrav 	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
12964946a00bSDag-Erling Smørgrav 	if (diff != 0) \
12974946a00bSDag-Erling Smørgrav 		return (diff > 0 ? 1 : -1); \
12984946a00bSDag-Erling Smørgrav } while (0)
1299f3b2c2d1SWolfram Schneider 
13004946a00bSDag-Erling Smørgrav #define ORDERKEY_STATE(a, b) do { \
13014901ca08SEitan Adler 	int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
13024946a00bSDag-Erling Smørgrav 	if (diff != 0) \
13034946a00bSDag-Erling Smørgrav 		return (diff > 0 ? 1 : -1); \
13044946a00bSDag-Erling Smørgrav } while (0)
1305f3b2c2d1SWolfram Schneider 
13064946a00bSDag-Erling Smørgrav #define ORDERKEY_PRIO(a, b) do { \
1307e38035a5SDag-Erling Smørgrav 	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
13084946a00bSDag-Erling Smørgrav 	if (diff != 0) \
13094946a00bSDag-Erling Smørgrav 		return (diff > 0 ? 1 : -1); \
13104946a00bSDag-Erling Smørgrav } while (0)
1311f3b2c2d1SWolfram Schneider 
131232efd263SGiorgos Keramidas #define	ORDERKEY_THREADS(a, b) do { \
131332efd263SGiorgos Keramidas 	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
131432efd263SGiorgos Keramidas 	if (diff != 0) \
131532efd263SGiorgos Keramidas 		return (diff > 0 ? 1 : -1); \
131632efd263SGiorgos Keramidas } while (0)
131732efd263SGiorgos Keramidas 
13184946a00bSDag-Erling Smørgrav #define ORDERKEY_RSSIZE(a, b) do { \
1319e38035a5SDag-Erling Smørgrav 	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
13204946a00bSDag-Erling Smørgrav 	if (diff != 0) \
13214946a00bSDag-Erling Smørgrav 		return (diff > 0 ? 1 : -1); \
13224946a00bSDag-Erling Smørgrav } while (0)
1323f3b2c2d1SWolfram Schneider 
13244946a00bSDag-Erling Smørgrav #define ORDERKEY_MEM(a, b) do { \
1325e38035a5SDag-Erling Smørgrav 	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
13264946a00bSDag-Erling Smørgrav 	if (diff != 0) \
13274946a00bSDag-Erling Smørgrav 		return (diff > 0 ? 1 : -1); \
13284946a00bSDag-Erling Smørgrav } while (0)
1329f3b2c2d1SWolfram Schneider 
13306000ced1SRong-En Fan #define ORDERKEY_JID(a, b) do { \
13316000ced1SRong-En Fan 	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
13326000ced1SRong-En Fan 	if (diff != 0) \
13336000ced1SRong-En Fan 		return (diff > 0 ? 1 : -1); \
13346000ced1SRong-En Fan } while (0)
13356000ced1SRong-En Fan 
1336b6924c93SDag-Erling Smørgrav #define ORDERKEY_SWAP(a, b) do { \
1337b6924c93SDag-Erling Smørgrav 	int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1338b6924c93SDag-Erling Smørgrav 	if (diff != 0) \
1339b6924c93SDag-Erling Smørgrav 		return (diff > 0 ? 1 : -1); \
1340b6924c93SDag-Erling Smørgrav } while (0)
1341b6924c93SDag-Erling Smørgrav 
1342f3b2c2d1SWolfram Schneider /* compare_cpu - the comparison function for sorting by cpu percentage */
1343f3b2c2d1SWolfram Schneider 
1344666cf873SEitan Adler static int
compare_cpu(const void * arg1,const void * arg2)1345666cf873SEitan Adler compare_cpu(const void *arg1, const void *arg2)
1346511d9c65SJoerg Wunsch {
1347960a7f39SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1348960a7f39SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1349511d9c65SJoerg Wunsch 
13504946a00bSDag-Erling Smørgrav 	ORDERKEY_PCTCPU(p1, p2);
13514946a00bSDag-Erling Smørgrav 	ORDERKEY_CPTICKS(p1, p2);
13524946a00bSDag-Erling Smørgrav 	ORDERKEY_STATE(p1, p2);
13534946a00bSDag-Erling Smørgrav 	ORDERKEY_PRIO(p1, p2);
13544946a00bSDag-Erling Smørgrav 	ORDERKEY_RSSIZE(p1, p2);
13554946a00bSDag-Erling Smørgrav 	ORDERKEY_MEM(p1, p2);
1356511d9c65SJoerg Wunsch 
13574946a00bSDag-Erling Smørgrav 	return (0);
1358511d9c65SJoerg Wunsch }
1359511d9c65SJoerg Wunsch 
1360f3b2c2d1SWolfram Schneider /* compare_size - the comparison function for sorting by total memory usage */
1361f3b2c2d1SWolfram Schneider 
13629f8096e3SEitan Adler static int
compare_size(const void * arg1,const void * arg2)1363666cf873SEitan Adler compare_size(const void *arg1, const void *arg2)
1364f3b2c2d1SWolfram Schneider {
1365960a7f39SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1366960a7f39SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1367f3b2c2d1SWolfram Schneider 
13684946a00bSDag-Erling Smørgrav 	ORDERKEY_MEM(p1, p2);
13694946a00bSDag-Erling Smørgrav 	ORDERKEY_RSSIZE(p1, p2);
13704946a00bSDag-Erling Smørgrav 	ORDERKEY_PCTCPU(p1, p2);
13714946a00bSDag-Erling Smørgrav 	ORDERKEY_CPTICKS(p1, p2);
13724946a00bSDag-Erling Smørgrav 	ORDERKEY_STATE(p1, p2);
13734946a00bSDag-Erling Smørgrav 	ORDERKEY_PRIO(p1, p2);
1374f3b2c2d1SWolfram Schneider 
13754946a00bSDag-Erling Smørgrav 	return (0);
1376f3b2c2d1SWolfram Schneider }
1377f3b2c2d1SWolfram Schneider 
1378f3b2c2d1SWolfram Schneider /* compare_res - the comparison function for sorting by resident set size */
1379f3b2c2d1SWolfram Schneider 
13809f8096e3SEitan Adler static int
compare_res(const void * arg1,const void * arg2)1381666cf873SEitan Adler compare_res(const void *arg1, const void *arg2)
1382f3b2c2d1SWolfram Schneider {
1383960a7f39SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1384960a7f39SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1385f3b2c2d1SWolfram Schneider 
13864946a00bSDag-Erling Smørgrav 	ORDERKEY_RSSIZE(p1, p2);
13874946a00bSDag-Erling Smørgrav 	ORDERKEY_MEM(p1, p2);
13884946a00bSDag-Erling Smørgrav 	ORDERKEY_PCTCPU(p1, p2);
13894946a00bSDag-Erling Smørgrav 	ORDERKEY_CPTICKS(p1, p2);
13904946a00bSDag-Erling Smørgrav 	ORDERKEY_STATE(p1, p2);
13914946a00bSDag-Erling Smørgrav 	ORDERKEY_PRIO(p1, p2);
1392f3b2c2d1SWolfram Schneider 
13934946a00bSDag-Erling Smørgrav 	return (0);
1394f3b2c2d1SWolfram Schneider }
1395f3b2c2d1SWolfram Schneider 
1396f3b2c2d1SWolfram Schneider /* compare_time - the comparison function for sorting by total cpu time */
1397f3b2c2d1SWolfram Schneider 
13989f8096e3SEitan Adler static int
compare_time(const void * arg1,const void * arg2)1399666cf873SEitan Adler compare_time(const void *arg1, const void *arg2)
1400f3b2c2d1SWolfram Schneider {
1401960a7f39SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const  *)arg1;
1402960a7f39SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1403f3b2c2d1SWolfram Schneider 
14044946a00bSDag-Erling Smørgrav 	ORDERKEY_CPTICKS(p1, p2);
14054946a00bSDag-Erling Smørgrav 	ORDERKEY_PCTCPU(p1, p2);
14064946a00bSDag-Erling Smørgrav 	ORDERKEY_STATE(p1, p2);
14074946a00bSDag-Erling Smørgrav 	ORDERKEY_PRIO(p1, p2);
14084946a00bSDag-Erling Smørgrav 	ORDERKEY_RSSIZE(p1, p2);
14094946a00bSDag-Erling Smørgrav 	ORDERKEY_MEM(p1, p2);
1410f3b2c2d1SWolfram Schneider 
14114946a00bSDag-Erling Smørgrav 	return (0);
1412f3b2c2d1SWolfram Schneider }
1413f3b2c2d1SWolfram Schneider 
14144946a00bSDag-Erling Smørgrav /* compare_prio - the comparison function for sorting by priority */
1415f3b2c2d1SWolfram Schneider 
14169f8096e3SEitan Adler static int
compare_prio(const void * arg1,const void * arg2)1417666cf873SEitan Adler compare_prio(const void *arg1, const void *arg2)
1418f3b2c2d1SWolfram Schneider {
1419960a7f39SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1420960a7f39SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1421f3b2c2d1SWolfram Schneider 
14224946a00bSDag-Erling Smørgrav 	ORDERKEY_PRIO(p1, p2);
14234946a00bSDag-Erling Smørgrav 	ORDERKEY_CPTICKS(p1, p2);
14244946a00bSDag-Erling Smørgrav 	ORDERKEY_PCTCPU(p1, p2);
14254946a00bSDag-Erling Smørgrav 	ORDERKEY_STATE(p1, p2);
14264946a00bSDag-Erling Smørgrav 	ORDERKEY_RSSIZE(p1, p2);
14274946a00bSDag-Erling Smørgrav 	ORDERKEY_MEM(p1, p2);
1428f3b2c2d1SWolfram Schneider 
14294946a00bSDag-Erling Smørgrav 	return (0);
1430f3b2c2d1SWolfram Schneider }
143132efd263SGiorgos Keramidas 
143232efd263SGiorgos Keramidas /* compare_threads - the comparison function for sorting by threads */
1433666cf873SEitan Adler static int
compare_threads(const void * arg1,const void * arg2)1434666cf873SEitan Adler compare_threads(const void *arg1, const void *arg2)
143532efd263SGiorgos Keramidas {
1436960a7f39SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1437960a7f39SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
143832efd263SGiorgos Keramidas 
143932efd263SGiorgos Keramidas 	ORDERKEY_THREADS(p1, p2);
144032efd263SGiorgos Keramidas 	ORDERKEY_PCTCPU(p1, p2);
144132efd263SGiorgos Keramidas 	ORDERKEY_CPTICKS(p1, p2);
144232efd263SGiorgos Keramidas 	ORDERKEY_STATE(p1, p2);
144332efd263SGiorgos Keramidas 	ORDERKEY_PRIO(p1, p2);
144432efd263SGiorgos Keramidas 	ORDERKEY_RSSIZE(p1, p2);
144532efd263SGiorgos Keramidas 	ORDERKEY_MEM(p1, p2);
144632efd263SGiorgos Keramidas 
144732efd263SGiorgos Keramidas 	return (0);
144832efd263SGiorgos Keramidas }
14496000ced1SRong-En Fan 
14506000ced1SRong-En Fan /* compare_jid - the comparison function for sorting by jid */
14516000ced1SRong-En Fan static int
compare_jid(const void * arg1,const void * arg2)14526000ced1SRong-En Fan compare_jid(const void *arg1, const void *arg2)
14536000ced1SRong-En Fan {
1454960a7f39SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1455960a7f39SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
14566000ced1SRong-En Fan 
14576000ced1SRong-En Fan 	ORDERKEY_JID(p1, p2);
14586000ced1SRong-En Fan 	ORDERKEY_PCTCPU(p1, p2);
14596000ced1SRong-En Fan 	ORDERKEY_CPTICKS(p1, p2);
14606000ced1SRong-En Fan 	ORDERKEY_STATE(p1, p2);
14616000ced1SRong-En Fan 	ORDERKEY_PRIO(p1, p2);
14626000ced1SRong-En Fan 	ORDERKEY_RSSIZE(p1, p2);
14636000ced1SRong-En Fan 	ORDERKEY_MEM(p1, p2);
14646000ced1SRong-En Fan 
14656000ced1SRong-En Fan 	return (0);
14666000ced1SRong-En Fan }
1467b6924c93SDag-Erling Smørgrav 
1468b6924c93SDag-Erling Smørgrav /* compare_swap - the comparison function for sorting by swap */
1469b6924c93SDag-Erling Smørgrav static int
compare_swap(const void * arg1,const void * arg2)1470b6924c93SDag-Erling Smørgrav compare_swap(const void *arg1, const void *arg2)
1471b6924c93SDag-Erling Smørgrav {
14729f8096e3SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
14739f8096e3SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1474b6924c93SDag-Erling Smørgrav 
1475b6924c93SDag-Erling Smørgrav 	ORDERKEY_SWAP(p1, p2);
1476b6924c93SDag-Erling Smørgrav 	ORDERKEY_PCTCPU(p1, p2);
1477b6924c93SDag-Erling Smørgrav 	ORDERKEY_CPTICKS(p1, p2);
1478b6924c93SDag-Erling Smørgrav 	ORDERKEY_STATE(p1, p2);
1479b6924c93SDag-Erling Smørgrav 	ORDERKEY_PRIO(p1, p2);
1480b6924c93SDag-Erling Smørgrav 	ORDERKEY_RSSIZE(p1, p2);
1481b6924c93SDag-Erling Smørgrav 	ORDERKEY_MEM(p1, p2);
1482b6924c93SDag-Erling Smørgrav 
1483b6924c93SDag-Erling Smørgrav 	return (0);
1484b6924c93SDag-Erling Smørgrav }
1485511d9c65SJoerg Wunsch 
1486789e3877SBruce Evans /* assorted comparison functions for sorting by i/o */
148726b2243aSGiorgos Keramidas 
14889f8096e3SEitan Adler static int
compare_iototal(const void * arg1,const void * arg2)1489666cf873SEitan Adler compare_iototal(const void *arg1, const void *arg2)
1490db6bb7fcSAlfred Perlstein {
14919f8096e3SEitan Adler 	const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
14929f8096e3SEitan Adler 	const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1493db6bb7fcSAlfred Perlstein 
14944946a00bSDag-Erling Smørgrav 	return (get_io_total(p2) - get_io_total(p1));
1495db6bb7fcSAlfred Perlstein }
149626b2243aSGiorgos Keramidas 
1497666cf873SEitan Adler static int
compare_ioread(const void * arg1,const void * arg2)1498666cf873SEitan Adler compare_ioread(const void *arg1, const void *arg2)
149926b2243aSGiorgos Keramidas {
15009f8096e3SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
15019f8096e3SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
150226b2243aSGiorgos Keramidas 	long dummy, inp1, inp2;
150326b2243aSGiorgos Keramidas 
15045d320d4bSAlfred Perlstein 	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
15055d320d4bSAlfred Perlstein 	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
150626b2243aSGiorgos Keramidas 
150726b2243aSGiorgos Keramidas 	return (inp2 - inp1);
150826b2243aSGiorgos Keramidas }
150926b2243aSGiorgos Keramidas 
1510666cf873SEitan Adler static int
compare_iowrite(const void * arg1,const void * arg2)1511666cf873SEitan Adler compare_iowrite(const void *arg1, const void *arg2)
151226b2243aSGiorgos Keramidas {
15139f8096e3SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
15149f8096e3SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
151526b2243aSGiorgos Keramidas 	long dummy, oup1, oup2;
151626b2243aSGiorgos Keramidas 
15175d320d4bSAlfred Perlstein 	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
15185d320d4bSAlfred Perlstein 	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
151926b2243aSGiorgos Keramidas 
152026b2243aSGiorgos Keramidas 	return (oup2 - oup1);
152126b2243aSGiorgos Keramidas }
152226b2243aSGiorgos Keramidas 
1523666cf873SEitan Adler static int
compare_iofault(const void * arg1,const void * arg2)1524666cf873SEitan Adler compare_iofault(const void *arg1, const void *arg2)
152526b2243aSGiorgos Keramidas {
15269f8096e3SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
15279f8096e3SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
152826b2243aSGiorgos Keramidas 	long dummy, flp1, flp2;
152926b2243aSGiorgos Keramidas 
15305d320d4bSAlfred Perlstein 	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
15315d320d4bSAlfred Perlstein 	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
15325d320d4bSAlfred Perlstein 
15335d320d4bSAlfred Perlstein 	return (flp2 - flp1);
15345d320d4bSAlfred Perlstein }
15355d320d4bSAlfred Perlstein 
1536666cf873SEitan Adler static int
compare_vcsw(const void * arg1,const void * arg2)1537666cf873SEitan Adler compare_vcsw(const void *arg1, const void *arg2)
15385d320d4bSAlfred Perlstein {
15399f8096e3SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
15409f8096e3SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
15415d320d4bSAlfred Perlstein 	long dummy, flp1, flp2;
15425d320d4bSAlfred Perlstein 
15435d320d4bSAlfred Perlstein 	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
15445d320d4bSAlfred Perlstein 	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
15455d320d4bSAlfred Perlstein 
15465d320d4bSAlfred Perlstein 	return (flp2 - flp1);
15475d320d4bSAlfred Perlstein }
15485d320d4bSAlfred Perlstein 
15499f8096e3SEitan Adler static int
compare_ivcsw(const void * arg1,const void * arg2)1550666cf873SEitan Adler compare_ivcsw(const void *arg1, const void *arg2)
15515d320d4bSAlfred Perlstein {
15529f8096e3SEitan Adler 	const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
15539f8096e3SEitan Adler 	const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
15545d320d4bSAlfred Perlstein 	long dummy, flp1, flp2;
15555d320d4bSAlfred Perlstein 
15565d320d4bSAlfred Perlstein 	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
15575d320d4bSAlfred Perlstein 	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
155826b2243aSGiorgos Keramidas 
155926b2243aSGiorgos Keramidas 	return (flp2 - flp1);
156026b2243aSGiorgos Keramidas }
156126b2243aSGiorgos Keramidas 
15629f8096e3SEitan Adler int (*compares[])(const void *arg1, const void *arg2) = {
15639f8096e3SEitan Adler 	compare_cpu,
15649f8096e3SEitan Adler 	compare_size,
15659f8096e3SEitan Adler 	compare_res,
15669f8096e3SEitan Adler 	compare_time,
15679f8096e3SEitan Adler 	compare_prio,
15689f8096e3SEitan Adler 	compare_threads,
15699f8096e3SEitan Adler 	compare_iototal,
15709f8096e3SEitan Adler 	compare_ioread,
15719f8096e3SEitan Adler 	compare_iowrite,
15729f8096e3SEitan Adler 	compare_iofault,
15739f8096e3SEitan Adler 	compare_vcsw,
15749f8096e3SEitan Adler 	compare_ivcsw,
15759f8096e3SEitan Adler 	compare_jid,
15769f8096e3SEitan Adler 	compare_swap,
1577deb63adfSKyle Evans 	compare_pid,
15789f8096e3SEitan Adler 	NULL
15799f8096e3SEitan Adler };
15809f8096e3SEitan Adler 
15819f8096e3SEitan Adler 
1582de916c8bSBruce Evans static int
swapmode(int * retavail,int * retfree)1583f6a10feaSDag-Erling Smørgrav swapmode(int *retavail, int *retfree)
1584511d9c65SJoerg Wunsch {
15857bb42db9SMatthew Dillon 	int n;
15867bb42db9SMatthew Dillon 	struct kvm_swap swapary[1];
158724e470efSKonstantin Belousov 	static int pagesize = 0;
1588cda7a5d5SEitan Adler 	static unsigned long swap_maxpages = 0;
1589511d9c65SJoerg Wunsch 
15907bb42db9SMatthew Dillon 	*retavail = 0;
15917bb42db9SMatthew Dillon 	*retfree = 0;
1592511d9c65SJoerg Wunsch 
15937bb42db9SMatthew Dillon #define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
15947bb42db9SMatthew Dillon 
15957bb42db9SMatthew Dillon 	n = kvm_getswapinfo(kd, swapary, 1, 0);
159647b370f5SMatthew Dillon 	if (n < 0 || swapary[0].ksw_total == 0)
1597511d9c65SJoerg Wunsch 		return (0);
1598511d9c65SJoerg Wunsch 
159924e470efSKonstantin Belousov 	if (pagesize == 0)
160024e470efSKonstantin Belousov 		pagesize = getpagesize();
160124e470efSKonstantin Belousov 	if (swap_maxpages == 0)
160224e470efSKonstantin Belousov 		GETSYSCTL("vm.swap_maxpages", swap_maxpages);
160324e470efSKonstantin Belousov 
160424e470efSKonstantin Belousov 	/* ksw_total contains the total size of swap all devices which may
160524e470efSKonstantin Belousov 	   exceed the maximum swap size allocatable in the system */
160624e470efSKonstantin Belousov 	if ( swapary[0].ksw_total > swap_maxpages )
160724e470efSKonstantin Belousov 		swapary[0].ksw_total = swap_maxpages;
160824e470efSKonstantin Belousov 
16097bb42db9SMatthew Dillon 	*retavail = CONVERT(swapary[0].ksw_total);
16107bb42db9SMatthew Dillon 	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
16117bb42db9SMatthew Dillon 
1612db365663SEitan Adler #undef CONVERT
1613db365663SEitan Adler 
16144946a00bSDag-Erling Smørgrav 	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
16157bb42db9SMatthew Dillon 	return (n);
1616511d9c65SJoerg Wunsch }
1617