xref: /dragonfly/usr.bin/top/m_dragonfly.c (revision c9c5aa9e)
1 /*
2  * top - a top users display for Unix
3  *
4  * SYNOPSIS:  For DragonFly 2.x and later
5  *
6  * DESCRIPTION:
7  * Originally written for BSD4.4 system by Christos Zoulas.
8  * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9  * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10  *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
11  *
12  * This is the machine-dependent module for DragonFly 2.5.1
13  * Should work for:
14  *	DragonFly 2.x and above
15  *
16  * LIBS: -lkvm
17  *
18  * AUTHOR: Jan Lentfer <Jan.Lentfer@web.de>
19  * This module has been put together from different sources and is based on the
20  * work of many other people, e.g. Matthew Dillon, Simon Schubert, Jordan Gordeev.
21  *
22  * $FreeBSD: src/usr.bin/top/machine.c,v 1.29.2.2 2001/07/31 20:27:05 tmm Exp $
23  */
24 
25 #include <sys/user.h>
26 #include <sys/types.h>
27 #include <sys/time.h>
28 #include <sys/signal.h>
29 #include <sys/param.h>
30 
31 #include "os.h"
32 #include <err.h>
33 #include <fcntl.h>
34 #include <kvm.h>
35 #include <stdio.h>
36 #include <unistd.h>
37 #include <math.h>
38 #include <pwd.h>
39 #include <sys/errno.h>
40 #include <sys/sysctl.h>
41 #include <sys/vmmeter.h>
42 #include <sys/resource.h>
43 #include <sys/rtprio.h>
44 
45 /* Swap */
46 #include <stdlib.h>
47 #include <string.h>
48 #include <sys/conf.h>
49 
50 #include <osreldate.h>		/* for changes in kernel structures */
51 
52 #include <sys/kinfo.h>
53 #include <kinfo.h>
54 #include "top.h"
55 #include "display.h"
56 #include "machine.h"
57 #include "screen.h"
58 #include "utils.h"
59 
60 int swapmode(int *retavail, int *retfree);
61 static int namelength;
62 static int cmdlength;
63 static int show_fullcmd;
64 
65 int n_cpus, enable_ncpus;
66 
67 /* get_process_info passes back a handle.  This is what it looks like: */
68 
69 struct handle {
70 	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
71 	int remaining;		/* number of pointers remaining */
72 	int show_threads;
73 };
74 
75 /* declarations for load_avg */
76 #include "loadavg.h"
77 
78 #define PP(pp, field) ((pp)->kp_ ## field)
79 #define LP(pp, field) ((pp)->kp_lwp.kl_ ## field)
80 #define VP(pp, field) ((pp)->kp_vm_ ## field)
81 
82 /* what we consider to be process size: */
83 #define PROCSIZE(pp) (VP((pp), map_size) / 1024)
84 
85 /*
86  * These definitions control the format of the per-process area
87  */
88 
89 static char smp_header[] =
90 "   PID %-*.*s NICE  SIZE    RES    STATE   C   TIME   CTIME    CPU COMMAND";
91 
92 #define smp_Proc_format \
93 	"%6d %-*.*s %3d%7s %6s %8.8s %3d %6s %7s %5.2f%% %.*s"
94 
95 /* process state names for the "STATE" column of the display */
96 /*
97  * the extra nulls in the string "run" are for adding a slash and the
98  * processor number when needed
99  */
100 
101 const char *state_abbrev[] = {
102 	"", "RUN\0\0\0", "STOP", "SLEEP",
103 };
104 
105 
106 static kvm_t *kd;
107 
108 /* values that we stash away in _init and use in later routines */
109 
110 static long lastpid;
111 
112 /* these are for calculating cpu state percentages */
113 
114 static struct kinfo_cputime *cp_time, *cp_old;
115 
116 /* these are for detailing the process states */
117 
118 #define MAXPSTATES	6
119 
120 int process_states[MAXPSTATES];
121 
122 char *procstatenames[] = {
123 	" running, ", " idle, ", " active, ", " stopped, ", " zombie, ",
124 	NULL
125 };
126 
127 /* these are for detailing the cpu states */
128 #define CPU_STATES 5
129 int *cpu_states;
130 int* cpu_averages;
131 char *cpustatenames[CPU_STATES + 1] = {
132 	"user", "nice", "system", "interrupt", "idle", NULL
133 };
134 
135 /* these are for detailing the memory statistics */
136 
137 long memory_stats[7];
138 char *memorynames[] = {
139 	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
140 	NULL
141 };
142 
143 long swap_stats[7];
144 char *swapnames[] = {
145 	/* 0           1            2           3            4       5 */
146 	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
147 	NULL
148 };
149 
150 
151 /* these are for keeping track of the proc array */
152 
153 static int nproc;
154 static int onproc = -1;
155 static int pref_len;
156 static struct kinfo_proc *pbase;
157 static struct kinfo_proc **pref;
158 
159 static uint64_t prev_pbase_time;	/* unit: us */
160 static struct kinfo_proc *prev_pbase;
161 static int prev_pbase_alloc;
162 static int prev_nproc;
163 static int fscale;
164 
165 /* these are for getting the memory statistics */
166 
167 static int pageshift;		/* log base 2 of the pagesize */
168 
169 /* define pagetok in terms of pageshift */
170 
171 #define pagetok(size) ((size) << pageshift)
172 
173 /* sorting orders. first is default */
174 char *ordernames[] = {
175   "cpu", "size", "res", "time", "pri", "thr", "pid", "ctime",  "pres", NULL
176 };
177 
178 /* compare routines */
179 int proc_compare (struct kinfo_proc **, struct kinfo_proc **);
180 int compare_size (struct kinfo_proc **, struct kinfo_proc **);
181 int compare_res (struct kinfo_proc **, struct kinfo_proc **);
182 int compare_time (struct kinfo_proc **, struct kinfo_proc **);
183 int compare_ctime (struct kinfo_proc **, struct kinfo_proc **);
184 int compare_prio(struct kinfo_proc **, struct kinfo_proc **);
185 int compare_thr (struct kinfo_proc **, struct kinfo_proc **);
186 int compare_pid (struct kinfo_proc **, struct kinfo_proc **);
187 int compare_pres(struct kinfo_proc **, struct kinfo_proc **);
188 
189 int (*proc_compares[]) (struct kinfo_proc **,struct kinfo_proc **) = {
190 	proc_compare,
191 	compare_size,
192 	compare_res,
193 	compare_time,
194 	compare_prio,
195 	compare_thr,
196 	compare_pid,
197 	compare_ctime,
198 	compare_pres,
199 	NULL
200 };
201 
202 static void
203 cputime_percentages(int out[CPU_STATES], struct kinfo_cputime *new,
204     struct kinfo_cputime *old)
205 {
206 	struct kinfo_cputime diffs;
207 	uint64_t total_change, half_total;
208 
209 	/* initialization */
210 	total_change = 0;
211 
212 	diffs.cp_user = new->cp_user - old->cp_user;
213 	diffs.cp_nice = new->cp_nice - old->cp_nice;
214 	diffs.cp_sys = new->cp_sys - old->cp_sys;
215 	diffs.cp_intr = new->cp_intr - old->cp_intr;
216 	diffs.cp_idle = new->cp_idle - old->cp_idle;
217 	total_change = diffs.cp_user + diffs.cp_nice + diffs.cp_sys +
218 	    diffs.cp_intr + diffs.cp_idle;
219 	old->cp_user = new->cp_user;
220 	old->cp_nice = new->cp_nice;
221 	old->cp_sys = new->cp_sys;
222 	old->cp_intr = new->cp_intr;
223 	old->cp_idle = new->cp_idle;
224 
225 	/* avoid divide by zero potential */
226 	if (total_change == 0)
227 		total_change = 1;
228 
229 	/* calculate percentages based on overall change, rounding up */
230 	half_total = total_change >> 1;
231 
232 	out[0] = ((diffs.cp_user * 1000LL + half_total) / total_change);
233 	out[1] = ((diffs.cp_nice * 1000LL + half_total) / total_change);
234 	out[2] = ((diffs.cp_sys * 1000LL + half_total) / total_change);
235 	out[3] = ((diffs.cp_intr * 1000LL + half_total) / total_change);
236 	out[4] = ((diffs.cp_idle * 1000LL + half_total) / total_change);
237 }
238 
239 int
240 machine_init(struct statics *statics)
241 {
242 	int pagesize;
243 	size_t prmlen;
244 	struct passwd *pw;
245 
246 	if (n_cpus < 1) {
247 		if (kinfo_get_cpus(&n_cpus))
248 			err(1, "kinfo_get_cpus failed");
249 	}
250 	/* get boot time */
251 
252 	prmlen = sizeof(fscale);
253 	if (sysctlbyname("kern.fscale", &fscale, &prmlen, NULL, 0) == -1)
254 		err(1, "sysctl kern.fscale failed");
255 
256 	while ((pw = getpwent()) != NULL) {
257 		if ((int)strlen(pw->pw_name) > namelength)
258 			namelength = strlen(pw->pw_name);
259 	}
260 	if (namelength < 8)
261 		namelength = 8;
262 	if (namelength > 13)
263 		namelength = 13;
264 
265 	if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL)) == NULL)
266 		return -1;
267 
268 	pbase = NULL;
269 	pref = NULL;
270 	nproc = 0;
271 	onproc = -1;
272 	prev_pbase = NULL;
273 	prev_pbase_alloc = 0;
274 	prev_pbase_time = 0;
275 	prev_nproc = 0;
276 	/*
277 	 * get the page size with "getpagesize" and calculate pageshift from
278 	 * it
279 	 */
280 	pagesize = getpagesize();
281 	pageshift = 0;
282 	while (pagesize > 1) {
283 		pageshift++;
284 		pagesize >>= 1;
285 	}
286 
287 	/* we only need the amount of log(2)1024 for our conversion */
288 	pageshift -= LOG1024;
289 
290 	/* fill in the statics information */
291 	statics->procstate_names = procstatenames;
292 	statics->cpustate_names = cpustatenames;
293 	statics->memory_names = memorynames;
294 	statics->unused01 = 0;
295 	statics->swap_names = swapnames;
296 	statics->order_names = ordernames;
297 	/* we need kvm descriptor in order to show full commands */
298 	statics->flags.fullcmds = kd != NULL;
299 	statics->flags.threads = 1;
300 
301 	/* all done! */
302 	return (0);
303 }
304 
305 char *
306 format_header(char *uname_field)
307 {
308 	static char Header[128];
309 
310 	snprintf(Header, sizeof(Header), smp_header,
311 	    namelength, namelength, uname_field);
312 
313 	if (screen_width <= 79)
314 		cmdlength = 80;
315 	else
316 		cmdlength = screen_width;
317 
318 	cmdlength = cmdlength - strlen(Header) + 6;
319 
320 	return Header;
321 }
322 
323 static int swappgsin = -1;
324 static int swappgsout = -1;
325 extern struct timeval timeout;
326 
327 void
328 get_system_info(struct system_info *si)
329 {
330 	size_t len;
331 	int cpu;
332 
333 	if (cpu_states == NULL) {
334 		cpu_states = malloc(sizeof(*cpu_states) * CPU_STATES * n_cpus);
335 		if (cpu_states == NULL)
336 			err(1, "malloc");
337 		bzero(cpu_states, sizeof(*cpu_states) * CPU_STATES * n_cpus);
338 	}
339 	if (cp_time == NULL) {
340 		cp_time = malloc(2 * n_cpus * sizeof(cp_time[0]));
341 		if (cp_time == NULL)
342 			err(1, "cp_time");
343 		cp_old = cp_time + n_cpus;
344 		len = n_cpus * sizeof(cp_old[0]);
345 		bzero(cp_time, len);
346 		if (sysctlbyname("kern.cputime", cp_old, &len, NULL, 0))
347 			err(1, "kern.cputime");
348 	}
349 	len = n_cpus * sizeof(cp_time[0]);
350 	bzero(cp_time, len);
351 	if (sysctlbyname("kern.cputime", cp_time, &len, NULL, 0))
352 		err(1, "kern.cputime");
353 
354 	getloadavg(si->load_avg, 3);
355 
356 	lastpid = 0;
357 
358 	/* convert cp_time counts to percentages */
359 	int combine_cpus = (enable_ncpus == 0 && n_cpus > 1);
360 	for (cpu = 0; cpu < n_cpus; ++cpu) {
361 		cputime_percentages(cpu_states + cpu * CPU_STATES,
362 		    &cp_time[cpu], &cp_old[cpu]);
363 	}
364 	if (combine_cpus) {
365 		if (cpu_averages == NULL) {
366 			cpu_averages = malloc(sizeof(*cpu_averages) * CPU_STATES);
367 			if (cpu_averages == NULL)
368 				err(1, "cpu_averages");
369 		}
370 		bzero(cpu_averages, sizeof(*cpu_averages) * CPU_STATES);
371 		for (cpu = 0; cpu < n_cpus; ++cpu) {
372 			int j = 0;
373 			cpu_averages[0] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
374 			cpu_averages[1] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
375 			cpu_averages[2] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
376 			cpu_averages[3] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
377 			cpu_averages[4] += *(cpu_states + ((cpu * CPU_STATES) + j++) );
378 		}
379 		for (int i = 0; i < CPU_STATES; ++i)
380 			cpu_averages[i] /= n_cpus;
381 	}
382 
383 	/* sum memory & swap statistics */
384 	{
385 		struct vmmeter vmm;
386 		struct vmstats vms;
387 		size_t vms_size = sizeof(vms);
388 		size_t vmm_size = sizeof(vmm);
389 		static unsigned int swap_delay = 0;
390 		static int swapavail = 0;
391 		static int swapfree = 0;
392 		static long bufspace = 0;
393 
394 		if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0))
395 			err(1, "sysctlbyname: vm.vmstats");
396 
397 		if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0))
398 			err(1, "sysctlbyname: vm.vmmeter");
399 
400 		if (kinfo_get_vfs_bufspace(&bufspace))
401 			err(1, "kinfo_get_vfs_bufspace");
402 
403 		/* convert memory stats to Kbytes */
404 		memory_stats[0] = pagetok(vms.v_active_count);
405 		memory_stats[1] = pagetok(vms.v_inactive_count);
406 		memory_stats[2] = pagetok(vms.v_wire_count);
407 		memory_stats[3] = pagetok(vms.v_cache_count);
408 		memory_stats[4] = bufspace / 1024;
409 		memory_stats[5] = pagetok(vms.v_free_count);
410 		memory_stats[6] = -1;
411 
412 		/* first interval */
413 		if (swappgsin < 0) {
414 			swap_stats[4] = 0;
415 			swap_stats[5] = 0;
416 		}
417 		/* compute differences between old and new swap statistic */
418 		else {
419 			swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
420 			swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
421 		}
422 
423 		swappgsin = vmm.v_swappgsin;
424 		swappgsout = vmm.v_swappgsout;
425 
426 		/* call CPU heavy swapmode() only for changes */
427 		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
428 			swap_stats[3] = swapmode(&swapavail, &swapfree);
429 			swap_stats[0] = swapavail;
430 			swap_stats[1] = swapavail - swapfree;
431 			swap_stats[2] = swapfree;
432 		}
433 		swap_delay = 1;
434 		swap_stats[6] = -1;
435 	}
436 
437 	/* set arrays and strings */
438 	si->cpustates = combine_cpus == 1 ?
439 	    cpu_averages : cpu_states;
440 	si->memory = memory_stats;
441 	si->swap = swap_stats;
442 
443 
444 	if (lastpid > 0) {
445 		si->last_pid = lastpid;
446 	} else {
447 		si->last_pid = -1;
448 	}
449 }
450 
451 
452 static struct handle handle;
453 
454 static void
455 fixup_pctcpu(struct kinfo_proc *fixit, uint64_t d)
456 {
457 	struct kinfo_proc *pp;
458 	uint64_t ticks;
459 	int i;
460 
461 	if (prev_nproc == 0 || d == 0)
462 		return;
463 
464 	if (LP(fixit, pid) == -1) {
465 		/* Skip kernel "idle" threads */
466 		if (PP(fixit, stat) == SIDL)
467 			return;
468 		for (pp = prev_pbase, i = 0; i < prev_nproc; pp++, i++) {
469 			if (LP(pp, pid) == -1 &&
470 			    PP(pp, ktaddr) == PP(fixit, ktaddr))
471 				break;
472 		}
473 	} else {
474 		for (pp = prev_pbase, i = 0; i < prev_nproc; pp++, i++) {
475 			if (LP(pp, pid) == LP(fixit, pid) &&
476 			    LP(pp, tid) == LP(fixit, tid)) {
477 				if (PP(pp, paddr) != PP(fixit, paddr)) {
478 					/* pid/tid are reused */
479 					pp = NULL;
480 				}
481 				break;
482 			}
483 		}
484 	}
485 	if (i == prev_nproc || pp == NULL)
486 		return;
487 
488 	ticks = LP(fixit, iticks) - LP(pp, iticks);
489 	ticks += LP(fixit, sticks) - LP(pp, sticks);
490 	ticks += LP(fixit, uticks) - LP(pp, uticks);
491 	if (ticks > d * 1000)
492 		ticks = d * 1000;
493 	LP(fixit, pctcpu) = (ticks * (uint64_t)fscale) / d;
494 }
495 
496 caddr_t
497 get_process_info(struct system_info *si, struct process_select *sel,
498     int compare_index)
499 {
500 	struct timespec tv;
501 	uint64_t t, d = 0;
502 
503 	int i;
504 	int total_procs;
505 	int active_procs;
506 	struct kinfo_proc **prefp;
507 	struct kinfo_proc *pp;
508 
509 	/* these are copied out of sel for speed */
510 	int show_idle;
511 	int show_system;
512 	int show_uid;
513 	int show_threads;
514 	char *match_command;
515 
516 	show_threads = sel->threads;
517 
518 	pbase = kvm_getprocs(kd,
519 	    KERN_PROC_ALL | (show_threads ? KERN_PROC_FLAG_LWP : 0), 0, &nproc);
520 	if (nproc > onproc)
521 		pref = (struct kinfo_proc **)realloc(pref, sizeof(struct kinfo_proc *)
522 		    * (onproc = nproc));
523 	if (pref == NULL || pbase == NULL) {
524 		(void)fprintf(stderr, "top: Out of memory.\n");
525 		quit(23);
526 	}
527 
528 	clock_gettime(CLOCK_MONOTONIC_PRECISE, &tv);
529 	t = (tv.tv_sec * 1000000ULL) + (tv.tv_nsec / 1000ULL);
530 	if (prev_pbase_time > 0 && t > prev_pbase_time)
531 		d = t - prev_pbase_time;
532 
533 	/* get a pointer to the states summary array */
534 	si->procstates = process_states;
535 
536 	/* set up flags which define what we are going to select */
537 	show_idle = sel->idle;
538 	show_system = sel->system;
539 	show_uid = sel->uid != -1;
540 	show_fullcmd = sel->fullcmd;
541 	match_command = sel->command;
542 
543 	/* count up process states and get pointers to interesting procs */
544 	total_procs = 0;
545 	active_procs = 0;
546 	memset((char *)process_states, 0, sizeof(process_states));
547 	prefp = pref;
548 	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
549 		/*
550 		 * Place pointers to each valid proc structure in pref[].
551 		 * Process slots that are actually in use have a non-zero
552 		 * status field.  Processes with P_SYSTEM set are system
553 		 * processes---these get ignored unless show_sysprocs is set.
554 		 */
555 		if ((show_system && (LP(pp, pid) == -1)) ||
556 		    (show_system || ((PP(pp, flags) & P_SYSTEM) == 0))) {
557 			int lpstate = LP(pp, stat);
558 			int pstate = PP(pp, stat);
559 
560 			total_procs++;
561 			if (lpstate == LSRUN)
562 				process_states[0]++;
563 			if (pstate >= 0 && pstate < MAXPSTATES - 1)
564 				process_states[pstate]++;
565 
566 			if (match_command != NULL &&
567 			    strstr(PP(pp, comm), match_command) == NULL) {
568 				/* Command does not match */
569 				continue;
570 			}
571 
572 			if (show_uid && PP(pp, ruid) != (uid_t)sel->uid) {
573 				/* UID does not match */
574 				continue;
575 			}
576 
577 			if (!show_system && LP(pp, pid) == -1) {
578 				/* Don't show system processes */
579 				continue;
580 			}
581 
582 			/* Fix up pctcpu before show_idle test */
583 			fixup_pctcpu(pp, d);
584 
585 			if (!show_idle && LP(pp, pctcpu) == 0 &&
586 			    lpstate != LSRUN) {
587 				/* Don't show idle processes */
588 				continue;
589 			}
590 
591 			*prefp++ = pp;
592 			active_procs++;
593 		}
594 	}
595 
596 	/*
597 	 * Save kinfo_procs for later pctcpu fixup.
598 	 */
599 	if (prev_pbase_alloc < nproc) {
600 		prev_pbase_alloc = nproc;
601 		prev_pbase = realloc(prev_pbase,
602 		    prev_pbase_alloc * sizeof(struct kinfo_proc));
603 		if (prev_pbase == NULL) {
604 			fprintf(stderr, "top: Out of memory.\n");
605 			quit(23);
606 		}
607 	}
608 	prev_nproc = nproc;
609 	prev_pbase_time = t;
610 	memcpy(prev_pbase, pbase, nproc * sizeof(struct kinfo_proc));
611 
612 	qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *),
613 	    (int (*)(const void *, const void *))proc_compares[compare_index]);
614 
615 	/* remember active and total counts */
616 	si->p_total = total_procs;
617 	si->p_active = pref_len = active_procs;
618 
619 	/* pass back a handle */
620 	handle.next_proc = pref;
621 	handle.remaining = active_procs;
622 	handle.show_threads = show_threads;
623 	return ((caddr_t) & handle);
624 }
625 
626 char fmt[MAX_COLS];		/* static area where result is built */
627 
628 char *
629 format_next_process(caddr_t xhandle, char *(*get_userid) (int))
630 {
631 	struct kinfo_proc *pp;
632 	long cputime;
633 	long ccputime;
634 	double pct;
635 	struct handle *hp;
636 	char status[16];
637 	int state;
638 	int xnice;
639 	char *comm;
640 	char cputime_fmt[10], ccputime_fmt[10];
641 
642 	/* find and remember the next proc structure */
643 	hp = (struct handle *)xhandle;
644 	pp = *(hp->next_proc++);
645 	hp->remaining--;
646 
647 	/* get the process's command name */
648 	if (show_fullcmd) {
649 		char **comm_full = kvm_getargv(kd, pp, 0);
650 		if (comm_full != NULL)
651 			comm = *comm_full;
652 		else
653 			comm = PP(pp, comm);
654 	}
655 	else {
656 		comm = PP(pp, comm);
657 	}
658 
659 	/* the actual field to display */
660 	char cmdfield[MAX_COLS];
661 
662 	if (PP(pp, flags) & P_SYSTEM) {
663 		/* system process */
664 		snprintf(cmdfield, sizeof cmdfield, "[%s]", comm);
665 	} else if (hp->show_threads && PP(pp, nthreads) > 1) {
666 		/* display it as a thread */
667 		if (strcmp(PP(pp, comm), LP(pp, comm)) == 0) {
668 			snprintf(cmdfield, sizeof cmdfield, "%s{%d}", comm,
669 			    LP(pp, tid));
670 		} else {
671 			/* show thread name in addition to tid */
672 			snprintf(cmdfield, sizeof cmdfield, "%s{%d/%s}", comm,
673 			    LP(pp, tid), LP(pp, comm));
674 		}
675 	} else {
676 		snprintf(cmdfield, sizeof cmdfield, "%s", comm);
677 	}
678 
679 	/*
680 	 * Convert the process's runtime from microseconds to seconds.  This
681 	 * time includes the interrupt time to be in compliance with ps output.
682 	 */
683 	cputime = (LP(pp, uticks) + LP(pp, sticks) + LP(pp, iticks)) / 1000000;
684 	ccputime = cputime + PP(pp, cru).ru_stime.tv_sec + PP(pp, cru).ru_utime.tv_sec;
685 	format_time(cputime, cputime_fmt, sizeof(cputime_fmt));
686 	format_time(ccputime, ccputime_fmt, sizeof(ccputime_fmt));
687 
688 	/* calculate the base for cpu percentages */
689 	pct = pctdouble(LP(pp, pctcpu));
690 
691 	/* generate "STATE" field */
692 	switch (state = LP(pp, stat)) {
693 	case LSRUN:
694 		if (LP(pp, tdflags) & TDF_RUNNING)
695 			sprintf(status, "CPU%d", LP(pp, cpuid));
696 		else
697 			strcpy(status, "RUN");
698 		break;
699 	case LSSLEEP:
700 		if (LP(pp, wmesg) != NULL) {
701 			sprintf(status, "%.8s", LP(pp, wmesg)); /* WMESGLEN */
702 			break;
703 		}
704 		/* fall through */
705 	default:
706 
707 		if (state >= 0 && (unsigned)state < NELEM(state_abbrev))
708 			sprintf(status, "%.6s", state_abbrev[(unsigned char)state]);
709 		else
710 			sprintf(status, "?%5d", state);
711 		break;
712 	}
713 
714 	if (PP(pp, stat) == SZOMB)
715 		strcpy(status, "ZOMB");
716 
717 	/*
718 	 * idle time 0 - 31 -> nice value +21 - +52 normal time      -> nice
719 	 * value -20 - +20 real time 0 - 31 -> nice value -52 - -21 thread
720 	 * 0 - 31 -> nice value -53 -
721 	 */
722 	switch (LP(pp, rtprio.type)) {
723 	case RTP_PRIO_REALTIME:
724 		xnice = PRIO_MIN - 1 - RTP_PRIO_MAX + LP(pp, rtprio.prio);
725 		break;
726 	case RTP_PRIO_IDLE:
727 		xnice = PRIO_MAX + 1 + LP(pp, rtprio.prio);
728 		break;
729 	case RTP_PRIO_THREAD:
730 		xnice = PRIO_MIN - 1 - RTP_PRIO_MAX - LP(pp, rtprio.prio);
731 		break;
732 	default:
733 		xnice = PP(pp, nice);
734 		break;
735 	}
736 
737 	/* format this entry */
738 	snprintf(fmt, sizeof(fmt),
739 	    smp_Proc_format,
740 	    (int)PP(pp, pid),
741 	    namelength, namelength,
742 	    get_userid(PP(pp, ruid)),
743 	    (int)xnice,
744 	    format_k(PROCSIZE(pp)),
745 	    format_k(pagetok(VP(pp, rssize))),
746 	    status,
747 	    LP(pp, cpuid),
748 	    cputime_fmt,
749 	    ccputime_fmt,
750 	    100.0 * pct,
751 	    cmdlength,
752 	    cmdfield);
753 
754 	/* return the result */
755 	return (fmt);
756 }
757 
758 /* comparison routines for qsort */
759 
760 /*
761  *  proc_compare - comparison function for "qsort"
762  *	Compares the resource consumption of two processes using five
763  *  	distinct keys.  The keys (in descending order of importance) are:
764  *  	percent cpu, cpu ticks, state, resident set size, total virtual
765  *  	memory usage.  The process states are ordered as follows (from least
766  *  	to most important):  WAIT, zombie, sleep, stop, start, run.  The
767  *  	array declaration below maps a process state index into a number
768  *  	that reflects this ordering.
769  */
770 
771 static unsigned char sorted_state[] =
772 {
773 	0,			/* not used		 */
774 	3,			/* sleep		 */
775 	1,			/* ABANDONED (WAIT)	 */
776 	6,			/* run			 */
777 	5,			/* start		 */
778 	2,			/* zombie		 */
779 	4			/* stop			 */
780 };
781 
782 
783 #define ORDERKEY_PCTCPU \
784   if (lresult = (long) LP(p2, pctcpu) - (long) LP(p1, pctcpu), \
785      (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
786 
787 #define CPTICKS(p)	(LP(p, uticks) + LP(p, sticks) + LP(p, iticks))
788 
789 #define ORDERKEY_CPTICKS \
790   if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
791 		CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
792 
793 #define CTIME(p)	(((LP(p, uticks) + LP(p, sticks) + LP(p, iticks))/1000000) + \
794   PP(p, cru).ru_stime.tv_sec + PP(p, cru).ru_utime.tv_sec)
795 
796 #define ORDERKEY_CTIME \
797    if ((result = CTIME(p2) > CTIME(p1) ? 1 : \
798 		CTIME(p2) < CTIME(p1) ? -1 : 0) == 0)
799 
800 #define ORDERKEY_STATE \
801   if ((result = sorted_state[(unsigned char) PP(p2, stat)] - \
802                 sorted_state[(unsigned char) PP(p1, stat)]) == 0)
803 
804 #define ORDERKEY_PRIO \
805   if ((result = LP(p2, prio) - LP(p1, prio)) == 0)
806 
807 #define ORDERKEY_KTHREADS \
808   if ((result = (LP(p1, pid) == 0) - (LP(p2, pid) == 0)) == 0)
809 
810 #define ORDERKEY_KTHREADS_PRIO \
811   if ((result = LP(p2, tdprio) - LP(p1, tdprio)) == 0)
812 
813 #define ORDERKEY_RSSIZE \
814   if ((result = VP(p2, rssize) - VP(p1, rssize)) == 0)
815 
816 #define ORDERKEY_MEM \
817   if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
818 
819 #define ORDERKEY_PID \
820   if ( (result = PP(p1, pid) - PP(p2, pid)) == 0)
821 
822 #define ORDERKEY_PRSSIZE \
823   if((result = VP(p2, prssize) - VP(p1, prssize)) == 0)
824 
825 static __inline int
826 orderkey_kernidle(const struct kinfo_proc *p1, const struct kinfo_proc *p2)
827 {
828 	int p1_kidle = 0, p2_kidle = 0;
829 
830 	if (LP(p1, pid) == -1 && PP(p1, stat) == SIDL)
831 		p1_kidle = 1;
832 	if (LP(p2, pid) == -1 && PP(p2, stat) == SIDL)
833 		p2_kidle = 1;
834 
835 	if (!p2_kidle && p1_kidle)
836 		return 1;
837 	if (p2_kidle && !p1_kidle)
838 		return -1;
839 	return 0;
840 }
841 
842 #define ORDERKEY_KIDLE	if ((result = orderkey_kernidle(p1, p2)) == 0)
843 
844 /* compare_cpu - the comparison function for sorting by cpu percentage */
845 
846 int
847 proc_compare(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
848 {
849 	struct kinfo_proc *p1;
850 	struct kinfo_proc *p2;
851 	int result;
852 	pctcpu lresult;
853 
854 	/* remove one level of indirection */
855 	p1 = *(struct kinfo_proc **) pp1;
856 	p2 = *(struct kinfo_proc **) pp2;
857 
858 	ORDERKEY_KIDLE
859 	ORDERKEY_PCTCPU
860 	ORDERKEY_CPTICKS
861 	ORDERKEY_STATE
862 	ORDERKEY_PRIO
863 	ORDERKEY_RSSIZE
864 	ORDERKEY_MEM
865 	{}
866 
867 	return (result);
868 }
869 
870 /* compare_size - the comparison function for sorting by total memory usage */
871 
872 int
873 compare_size(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
874 {
875 	struct kinfo_proc *p1;
876 	struct kinfo_proc *p2;
877 	int result;
878 	pctcpu lresult;
879 
880 	/* remove one level of indirection */
881 	p1 = *(struct kinfo_proc **) pp1;
882 	p2 = *(struct kinfo_proc **) pp2;
883 
884 	ORDERKEY_MEM
885 	ORDERKEY_RSSIZE
886 	ORDERKEY_KIDLE
887 	ORDERKEY_PCTCPU
888 	ORDERKEY_CPTICKS
889 	ORDERKEY_STATE
890 	ORDERKEY_PRIO
891 	{}
892 
893 	return (result);
894 }
895 
896 /* compare_res - the comparison function for sorting by resident set size */
897 
898 int
899 compare_res(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
900 {
901 	struct kinfo_proc *p1;
902 	struct kinfo_proc *p2;
903 	int result;
904 	pctcpu lresult;
905 
906 	/* remove one level of indirection */
907 	p1 = *(struct kinfo_proc **) pp1;
908 	p2 = *(struct kinfo_proc **) pp2;
909 
910 	ORDERKEY_RSSIZE
911 	ORDERKEY_MEM
912 	ORDERKEY_KIDLE
913 	ORDERKEY_PCTCPU
914 	ORDERKEY_CPTICKS
915 	ORDERKEY_STATE
916 	ORDERKEY_PRIO
917 	{}
918 
919 	return (result);
920 }
921 
922 /* compare_pres - the comparison function for sorting by proportional resident set size */
923 
924 int
925 compare_pres(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
926 {
927 	struct kinfo_proc *p1;
928 	struct kinfo_proc *p2;
929 	int result;
930 	pctcpu lresult;
931 
932 	/* remove one level of indirection */
933 	p1 = *(struct kinfo_proc **) pp1;
934 	p2 = *(struct kinfo_proc **) pp2;
935 
936 	ORDERKEY_PRSSIZE
937 	ORDERKEY_RSSIZE
938 	ORDERKEY_MEM
939 	ORDERKEY_KIDLE
940 	ORDERKEY_PCTCPU
941 	ORDERKEY_CPTICKS
942 	ORDERKEY_STATE
943 	ORDERKEY_PRIO
944 	{}
945 
946 	return (result);
947 }
948 
949 /* compare_time - the comparison function for sorting by total cpu time */
950 
951 int
952 compare_time(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
953 {
954 	struct kinfo_proc *p1;
955 	struct kinfo_proc *p2;
956 	int result;
957 	pctcpu lresult;
958 
959 	/* remove one level of indirection */
960 	p1 = *(struct kinfo_proc **) pp1;
961 	p2 = *(struct kinfo_proc **) pp2;
962 
963 	ORDERKEY_KIDLE
964 	ORDERKEY_CPTICKS
965 	ORDERKEY_PCTCPU
966 	ORDERKEY_KTHREADS
967 	ORDERKEY_KTHREADS_PRIO
968 	ORDERKEY_STATE
969 	ORDERKEY_PRIO
970 	ORDERKEY_RSSIZE
971 	ORDERKEY_MEM
972 	{}
973 
974 	return (result);
975 }
976 
977 int
978 compare_ctime(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
979 {
980 	struct kinfo_proc *p1;
981 	struct kinfo_proc *p2;
982 	int result;
983 	pctcpu lresult;
984 
985 	/* remove one level of indirection */
986 	p1 = *(struct kinfo_proc **) pp1;
987 	p2 = *(struct kinfo_proc **) pp2;
988 
989 	ORDERKEY_KIDLE
990 	ORDERKEY_CTIME
991 	ORDERKEY_PCTCPU
992 	ORDERKEY_KTHREADS
993 	ORDERKEY_KTHREADS_PRIO
994 	ORDERKEY_STATE
995 	ORDERKEY_PRIO
996 	ORDERKEY_RSSIZE
997 	ORDERKEY_MEM
998 	{}
999 
1000 	return (result);
1001 }
1002 
1003 /* compare_prio - the comparison function for sorting by cpu percentage */
1004 
1005 int
1006 compare_prio(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
1007 {
1008 	struct kinfo_proc *p1;
1009 	struct kinfo_proc *p2;
1010 	int result;
1011 	pctcpu lresult;
1012 
1013 	/* remove one level of indirection */
1014 	p1 = *(struct kinfo_proc **) pp1;
1015 	p2 = *(struct kinfo_proc **) pp2;
1016 
1017 	ORDERKEY_KTHREADS
1018 	ORDERKEY_KTHREADS_PRIO
1019 	ORDERKEY_PRIO
1020 	ORDERKEY_KIDLE
1021 	ORDERKEY_CPTICKS
1022 	ORDERKEY_PCTCPU
1023 	ORDERKEY_STATE
1024 	ORDERKEY_RSSIZE
1025 	ORDERKEY_MEM
1026 	{}
1027 
1028 	return (result);
1029 }
1030 
1031 int
1032 compare_thr(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
1033 {
1034 	struct kinfo_proc *p1;
1035 	struct kinfo_proc *p2;
1036 	int result;
1037 	pctcpu lresult;
1038 
1039 	/* remove one level of indirection */
1040 	p1 = *(struct kinfo_proc **)pp1;
1041 	p2 = *(struct kinfo_proc **)pp2;
1042 
1043 	ORDERKEY_KTHREADS
1044 	ORDERKEY_KTHREADS_PRIO
1045 	ORDERKEY_KIDLE
1046 	ORDERKEY_CPTICKS
1047 	ORDERKEY_PCTCPU
1048 	ORDERKEY_STATE
1049 	ORDERKEY_RSSIZE
1050 	ORDERKEY_MEM
1051 	{}
1052 
1053 	return (result);
1054 }
1055 
1056 /* compare_pid - the comparison function for sorting by process id */
1057 
1058 int
1059 compare_pid(struct kinfo_proc **pp1, struct kinfo_proc **pp2)
1060 {
1061 	struct kinfo_proc *p1;
1062 	struct kinfo_proc *p2;
1063 	int result;
1064 
1065 	/* remove one level of indirection */
1066 	p1 = *(struct kinfo_proc **) pp1;
1067 	p2 = *(struct kinfo_proc **) pp2;
1068 
1069 	ORDERKEY_PID
1070 	;
1071 
1072 	return(result);
1073 }
1074 
1075 /*
1076  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1077  *		the process does not exist.
1078  *		It is EXTREMLY IMPORTANT that this function work correctly.
1079  *		If top runs setuid root (as in SVR4), then this function
1080  *		is the only thing that stands in the way of a serious
1081  *		security problem.  It validates requests for the "kill"
1082  *		and "renice" commands.
1083  */
1084 
1085 int
1086 proc_owner(int pid)
1087 {
1088 	int xcnt;
1089 	struct kinfo_proc **prefp;
1090 	struct kinfo_proc *pp;
1091 
1092 	prefp = pref;
1093 	xcnt = pref_len;
1094 	while (--xcnt >= 0) {
1095 		pp = *prefp++;
1096 		if (PP(pp, pid) == (pid_t) pid) {
1097 			return ((int)PP(pp, ruid));
1098 		}
1099 	}
1100 	return (-1);
1101 }
1102 
1103 
1104 /*
1105  * swapmode is based on a program called swapinfo written
1106  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
1107  */
1108 int
1109 swapmode(int *retavail, int *retfree)
1110 {
1111 	int n;
1112 	int pagesize = getpagesize();
1113 	struct kvm_swap swapary[1];
1114 
1115 	*retavail = 0;
1116 	*retfree = 0;
1117 
1118 #define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1119 
1120 	n = kvm_getswapinfo(kd, swapary, 1, 0);
1121 	if (n < 0 || swapary[0].ksw_total == 0)
1122 		return (0);
1123 
1124 	*retavail = CONVERT(swapary[0].ksw_total);
1125 	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1126 
1127 	n = (int)((double)swapary[0].ksw_used * 100.0 /
1128 	    (double)swapary[0].ksw_total);
1129 	return (n);
1130 }
1131