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