xref: /freebsd/usr.bin/top/machine.c (revision c98323078dede7579020518ec84cdcb478e5c142)
1 /*
2  * top - a top users display for Unix
3  *
4  * SYNOPSIS:  For FreeBSD-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 FreeBSD 2.2
13  * Works for:
14  *	FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
15  *
16  * LIBS: -lkvm
17  *
18  * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
19  *          Steven Wallace  <swallace@freebsd.org>
20  *          Wolfram Schneider <wosch@FreeBSD.org>
21  *          Thomas Moestl <tmoestl@gmx.net>
22  *
23  * $FreeBSD$
24  */
25 
26 #include <sys/param.h>
27 #include <sys/errno.h>
28 #include <sys/file.h>
29 #include <sys/proc.h>
30 #include <sys/resource.h>
31 #include <sys/rtprio.h>
32 #include <sys/signal.h>
33 #include <sys/sysctl.h>
34 #include <sys/time.h>
35 #include <sys/user.h>
36 #include <sys/vmmeter.h>
37 
38 #include <kvm.h>
39 #include <math.h>
40 #include <nlist.h>
41 #include <paths.h>
42 #include <pwd.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 
47 #include "top.h"
48 #include "machine.h"
49 #include "screen.h"
50 #include "utils.h"
51 
52 static void getsysctl(char *, void *, size_t);
53 
54 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
55 
56 extern char* printable(char *);
57 int swapmode(int *retavail, int *retfree);
58 static int smpmode;
59 enum displaymodes displaymode;
60 static int namelength;
61 static int cmdlengthdelta;
62 
63 /* Prototypes for top internals */
64 void quit(int);
65 int compare_pid(const void *a, const void *b);
66 
67 /* get_process_info passes back a handle.  This is what it looks like: */
68 
69 struct handle
70 {
71 	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
72 	int remaining;			/* number of pointers remaining */
73 };
74 
75 /* declarations for load_avg */
76 #include "loadavg.h"
77 
78 /* define what weighted cpu is.  */
79 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
80 			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
81 
82 /* what we consider to be process size: */
83 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
84 
85 #define RU(pp)	(&(pp)->ki_rusage)
86 #define RUTOT(pp) \
87 	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
88 
89 
90 /* definitions for indices in the nlist array */
91 
92 /*
93  *  These definitions control the format of the per-process area
94  */
95 
96 static char io_header[] =
97 	"  PID %-*.*s   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
98 
99 #define io_Proc_format \
100 	"%5d %-*.*s %6ld %6ld %6ld %6ld %6.2f%% %.*s"
101 
102 static char smp_header[] =
103 	"  PID %-*.*s PRI NICE   SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
104 
105 #define smp_Proc_format \
106 	"%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
107 
108 static char up_header[] =
109 	"  PID %-*.*s PRI NICE   SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
110 
111 #define up_Proc_format \
112 	"%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
113 
114 
115 
116 /* process state names for the "STATE" column of the display */
117 /* the extra nulls in the string "run" are for adding a slash and
118    the processor number when needed */
119 
120 char *state_abbrev[] =
121 {
122 	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
123 };
124 
125 
126 static kvm_t *kd;
127 
128 /* values that we stash away in _init and use in later routines */
129 
130 static double logcpu;
131 
132 /* these are retrieved from the kernel in _init */
133 
134 static load_avg  ccpu;
135 
136 /* these are used in the get_ functions */
137 
138 static int lastpid;
139 
140 /* these are for calculating cpu state percentages */
141 
142 static long cp_time[CPUSTATES];
143 static long cp_old[CPUSTATES];
144 static long cp_diff[CPUSTATES];
145 
146 /* these are for detailing the process states */
147 
148 int process_states[8];
149 char *procstatenames[] = {
150 	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
151 	" zombie, ", " waiting, ", " lock, ",
152 	NULL
153 };
154 
155 /* these are for detailing the cpu states */
156 
157 int cpu_states[CPUSTATES];
158 char *cpustatenames[] = {
159 	"user", "nice", "system", "interrupt", "idle", NULL
160 };
161 
162 /* these are for detailing the memory statistics */
163 
164 int memory_stats[7];
165 char *memorynames[] = {
166 	/* 0             1            2            3            4          5 */
167 	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
168 	NULL
169 };
170 
171 int swap_stats[7];
172 char *swapnames[] = {
173 	/* 0            1           2           3            4         5 */
174 	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
175 	NULL
176 };
177 
178 
179 /* these are for keeping track of the proc array */
180 
181 static int nproc;
182 static int onproc = -1;
183 static int pref_len;
184 static struct kinfo_proc *pbase;
185 static struct kinfo_proc **pref;
186 static struct kinfo_proc *previous_procs;
187 static struct kinfo_proc **previous_pref;
188 static int previous_proc_count = 0;
189 static int previous_proc_count_max = 0;
190 
191 /* total number of io operations */
192 static long total_inblock;
193 static long total_oublock;
194 static long total_majflt;
195 
196 /* these are for getting the memory statistics */
197 
198 static int pageshift;		/* log base 2 of the pagesize */
199 
200 /* define pagetok in terms of pageshift */
201 
202 #define pagetok(size) ((size) << pageshift)
203 
204 /* useful externals */
205 long percentages();
206 
207 #ifdef ORDER
208 /*
209  * Sorting orders.  One vector per display mode.
210  * The first element is the default for each mode.
211  */
212 char *proc_ordernames[] = {
213 	"cpu", "size", "res", "time", "pri", NULL
214 };
215 char *io_ordernames[] = {
216 	"total", "read", "write", "fault", NULL
217 };
218 #endif
219 
220 int
221 machine_init(struct statics *statics)
222 {
223 	int pagesize;
224 	size_t modelen;
225 	struct passwd *pw;
226 
227 	modelen = sizeof(smpmode);
228 	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
229 		sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
230 	    modelen != sizeof(smpmode))
231 		smpmode = 0;
232 
233 	while ((pw = getpwent()) != NULL) {
234 		if (strlen(pw->pw_name) > namelength)
235 			namelength = strlen(pw->pw_name);
236 	}
237 	if (namelength < 8)
238 		namelength = 8;
239 	if (smpmode && namelength > 13)
240 		namelength = 13;
241 	else if (namelength > 15)
242 		namelength = 15;
243 
244 	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
245 	if (kd == NULL)
246 		return (-1);
247 
248 	GETSYSCTL("kern.ccpu", ccpu);
249 
250 	/* this is used in calculating WCPU -- calculate it ahead of time */
251 	logcpu = log(loaddouble(ccpu));
252 
253 	pbase = NULL;
254 	pref = NULL;
255 	nproc = 0;
256 	onproc = -1;
257 	/* get the page size with "getpagesize" and calculate pageshift from it */
258 	pagesize = getpagesize();
259 	pageshift = 0;
260 	while (pagesize > 1) {
261 		pageshift++;
262 		pagesize >>= 1;
263 	}
264 
265 	/* we only need the amount of log(2)1024 for our conversion */
266 	pageshift -= LOG1024;
267 
268 	/* fill in the statics information */
269 	statics->procstate_names = procstatenames;
270 	statics->cpustate_names = cpustatenames;
271 	statics->memory_names = memorynames;
272 	statics->swap_names = swapnames;
273 #ifdef ORDER
274 	switch (displaymode) {
275 	case DISP_IO:
276 		statics->order_names = io_ordernames;
277 		break;
278 	case DISP_CPU:
279 	default:
280 		statics->order_names = proc_ordernames;
281 		break;
282 	}
283 #endif
284 
285 	/* all done! */
286 	return (0);
287 }
288 
289 char *
290 format_header(char *uname_field)
291 {
292 	static char Header[128];
293 	const char *prehead;
294 
295 	switch (displaymode) {
296 	case DISP_CPU:
297 		prehead = smpmode ? smp_header : up_header;
298 		break;
299 	case DISP_IO:
300 		prehead = io_header;
301 		break;
302 	}
303 
304 	snprintf(Header, sizeof(Header), prehead,
305 	    namelength, namelength, uname_field);
306 
307 	cmdlengthdelta = strlen(Header) - 7;
308 
309 	return (Header);
310 }
311 
312 static int swappgsin = -1;
313 static int swappgsout = -1;
314 extern struct timeval timeout;
315 
316 void
317 get_system_info(struct system_info *si)
318 {
319 	long total;
320 	struct loadavg sysload;
321 	int mib[2];
322 	struct timeval boottime;
323 	size_t bt_size;
324 	int i;
325 
326 	/* get the cp_time array */
327 	GETSYSCTL("kern.cp_time", cp_time);
328 	GETSYSCTL("vm.loadavg", sysload);
329 	GETSYSCTL("kern.lastpid", lastpid);
330 
331 	/* convert load averages to doubles */
332 	for (i = 0; i < 3; i++)
333 		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
334 
335 	/* convert cp_time counts to percentages */
336 	total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
337 
338 	/* sum memory & swap statistics */
339 	{
340 		static unsigned int swap_delay = 0;
341 		static int swapavail = 0;
342 		static int swapfree = 0;
343 		static int bufspace = 0;
344 		static int nspgsin, nspgsout;
345 
346 		GETSYSCTL("vfs.bufspace", bufspace);
347 		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
348 		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
349 		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
350 		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
351 		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
352 		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
353 		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
354 		/* convert memory stats to Kbytes */
355 		memory_stats[0] = pagetok(memory_stats[0]);
356 		memory_stats[1] = pagetok(memory_stats[1]);
357 		memory_stats[2] = pagetok(memory_stats[2]);
358 		memory_stats[3] = pagetok(memory_stats[3]);
359 		memory_stats[4] = bufspace / 1024;
360 		memory_stats[5] = pagetok(memory_stats[5]);
361 		memory_stats[6] = -1;
362 
363 		/* first interval */
364 		if (swappgsin < 0) {
365 			swap_stats[4] = 0;
366 			swap_stats[5] = 0;
367 		}
368 
369 		/* compute differences between old and new swap statistic */
370 		else {
371 			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
372 			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
373 		}
374 
375 		swappgsin = nspgsin;
376 		swappgsout = nspgsout;
377 
378 		/* call CPU heavy swapmode() only for changes */
379 		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
380 			swap_stats[3] = swapmode(&swapavail, &swapfree);
381 			swap_stats[0] = swapavail;
382 			swap_stats[1] = swapavail - swapfree;
383 			swap_stats[2] = swapfree;
384 		}
385 		swap_delay = 1;
386 		swap_stats[6] = -1;
387 	}
388 
389 	/* set arrays and strings */
390 	si->cpustates = cpu_states;
391 	si->memory = memory_stats;
392 	si->swap = swap_stats;
393 
394 
395 	if (lastpid > 0) {
396 		si->last_pid = lastpid;
397 	} else {
398 		si->last_pid = -1;
399 	}
400 
401 	/*
402 	 * Print how long system has been up.
403 	 * (Found by looking getting "boottime" from the kernel)
404 	 */
405 	mib[0] = CTL_KERN;
406 	mib[1] = KERN_BOOTTIME;
407 	bt_size = sizeof(boottime);
408 	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
409 	    boottime.tv_sec != 0) {
410 		si->boottime = boottime;
411 	} else {
412 		si->boottime.tv_sec = -1;
413 	}
414 }
415 
416 #define NOPROC	((void *)-1)
417 
418 const struct kinfo_proc *
419 get_old_proc(struct kinfo_proc *pp)
420 {
421 	struct kinfo_proc **oldpp, *oldp;
422 
423 	if (previous_proc_count == 0)
424 		return (NULL);
425 	if (pp->ki_udata == NOPROC)
426 		return (NULL);
427 	if (pp->ki_udata != NULL)
428 		return (pp->ki_udata);
429 	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
430 	    sizeof(*previous_pref), compare_pid);
431 	if (oldpp == NULL) {
432 		pp->ki_udata = NOPROC;
433 		return (NULL);
434 	}
435 	oldp = *oldpp;
436 	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
437 		pp->ki_udata = NOPROC;
438 		return (NULL);
439 	}
440 	pp->ki_udata = oldp;
441 	return (oldp);
442 }
443 
444 long
445 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp)
446 {
447 	const struct kinfo_proc *oldp;
448 	static struct kinfo_proc dummy;
449 	long ret;
450 
451 	oldp = get_old_proc(pp);
452 	if (oldp == NULL) {
453 		bzero(&dummy, sizeof(dummy));
454 		oldp = &dummy;
455 	}
456 
457 	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
458 	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
459 	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
460 	ret =
461 	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
462 	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
463 	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
464 	return (ret);
465 }
466 
467 long
468 get_io_total(struct kinfo_proc *pp)
469 {
470 	long dummy;
471 
472 	return (get_io_stats(pp, &dummy, &dummy, &dummy));
473 }
474 
475 static struct handle handle;
476 
477 caddr_t
478 get_process_info(struct system_info *si, struct process_select *sel,
479     int (*compare)(const void *, const void *))
480 {
481 	int i;
482 	int total_procs;
483 	long p_io;
484 	long p_inblock, p_oublock, p_majflt;
485 	int active_procs;
486 	struct kinfo_proc **prefp;
487 	struct kinfo_proc *pp;
488 	struct kinfo_proc *prev_pp = NULL;
489 
490 	/* these are copied out of sel for speed */
491 	int show_idle;
492 	int show_self;
493 	int show_system;
494 	int show_uid;
495 	int show_command;
496 
497 	/*
498 	 * Save the previous process info.
499 	 */
500 	if (previous_proc_count_max < nproc) {
501 		free(previous_procs);
502 		previous_procs = malloc(nproc * sizeof(*previous_procs));
503 		free(previous_pref);
504 		previous_pref = malloc(nproc * sizeof(*previous_pref));
505 		if (previous_procs == NULL || previous_pref == NULL) {
506 			(void) fprintf(stderr, "top: Out of memory.\n");
507 			quit(23);
508 		}
509 		previous_proc_count_max = nproc;
510 	}
511 	if (nproc) {
512 		for (i = 0; i < nproc; i++)
513 			previous_pref[i] = &previous_procs[i];
514 		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
515 		qsort(previous_pref, nproc, sizeof(*previous_pref), compare_pid);
516 	}
517 	previous_proc_count = nproc;
518 
519 	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
520 	if (nproc > onproc)
521 		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
522 	if (pref == NULL || pbase == NULL) {
523 		(void) fprintf(stderr, "top: Out of memory.\n");
524 		quit(23);
525 	}
526 	/* get a pointer to the states summary array */
527 	si->procstates = process_states;
528 
529 	/* set up flags which define what we are going to select */
530 	show_idle = sel->idle;
531 	show_self = sel->self == -1;
532 	show_system = sel->system;
533 	show_uid = sel->uid != -1;
534 	show_command = sel->command != NULL;
535 
536 	/* count up process states and get pointers to interesting procs */
537 	total_procs = 0;
538 	active_procs = 0;
539 	total_inblock = 0;
540 	total_oublock = 0;
541 	total_majflt = 0;
542 	memset((char *)process_states, 0, sizeof(process_states));
543 	prefp = pref;
544 	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
545 
546 		if (pp->ki_stat == 0)
547 			/* not in use */
548 			continue;
549 
550 		if (!show_self && pp->ki_pid == sel->self)
551 			/* skip self */
552 			continue;
553 
554 		if (!show_system && (pp->ki_flag & P_SYSTEM))
555 			/* skip system process */
556 			continue;
557 
558 		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt);
559 		total_inblock += p_inblock;
560 		total_oublock += p_oublock;
561 		total_majflt += p_majflt;
562 		total_procs++;
563 		process_states[pp->ki_stat]++;
564 
565 		if (pp->ki_stat == SZOMB)
566 			/* skip zombies */
567 			continue;
568 
569 		if (displaymode == DISP_CPU && !show_idle &&
570 		    (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN))
571 			/* skip idle or non-running processes */
572 			continue;
573 
574 		if (displaymode == DISP_IO && !show_idle && p_io == 0)
575 			/* skip processes that aren't doing I/O */
576 			continue;
577 
578 		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
579 			/* skip processes which don't belong to the selected UID */
580 			continue;
581 
582 		/*
583 		 * When not showing threads, take the first thread
584 		 * for output and add the fields that we can from
585 		 * the rest of the process's threads rather than
586 		 * using the system's mostly-broken KERN_PROC_PROC.
587 		 */
588 		if (sel->thread || prev_pp == NULL ||
589 		    prev_pp->ki_pid != pp->ki_pid) {
590 			*prefp++ = pp;
591 			active_procs++;
592 			prev_pp = pp;
593 		} else {
594 			prev_pp->ki_pctcpu += pp->ki_pctcpu;
595 		}
596 	}
597 
598 	/* if requested, sort the "interesting" processes */
599 	if (compare != NULL)
600 		qsort(pref, active_procs, sizeof(*pref), compare);
601 
602 	/* remember active and total counts */
603 	si->p_total = total_procs;
604 	si->p_active = pref_len = active_procs;
605 
606 	/* pass back a handle */
607 	handle.next_proc = pref;
608 	handle.remaining = active_procs;
609 	return ((caddr_t)&handle);
610 }
611 
612 static char fmt[128];	/* static area where result is built */
613 
614 char *
615 format_next_process(caddr_t handle, char *(*get_userid)(int))
616 {
617 	struct kinfo_proc *pp;
618 	const struct kinfo_proc *oldp;
619 	long cputime;
620 	double pct;
621 	struct handle *hp;
622 	char status[16];
623 	int state;
624 	struct rusage ru, *rup;
625 	long p_tot, s_tot;
626 
627 	/* find and remember the next proc structure */
628 	hp = (struct handle *)handle;
629 	pp = *(hp->next_proc++);
630 	hp->remaining--;
631 
632 	/* get the process's command name */
633 	if ((pp->ki_sflag & PS_INMEM) == 0) {
634 		/*
635 		 * Print swapped processes as <pname>
636 		 */
637 		size_t len = strlen(pp->ki_comm);
638 		if (len > sizeof(pp->ki_comm) - 3)
639 			len = sizeof(pp->ki_comm) - 3;
640 		memmove(pp->ki_comm + 1, pp->ki_comm, len);
641 		pp->ki_comm[0] = '<';
642 		pp->ki_comm[len + 1] = '>';
643 		pp->ki_comm[len + 2] = '\0';
644 	}
645 
646 	/*
647 	 * Convert the process's runtime from microseconds to seconds.  This
648 	 * time includes the interrupt time although that is not wanted here.
649 	 * ps(1) is similarly sloppy.
650 	 */
651 	cputime = (pp->ki_runtime + 500000) / 1000000;
652 
653 	/* calculate the base for cpu percentages */
654 	pct = pctdouble(pp->ki_pctcpu);
655 
656 	/* generate "STATE" field */
657 	switch (state = pp->ki_stat) {
658 	case SRUN:
659 		if (smpmode && pp->ki_oncpu != 0xff)
660 			sprintf(status, "CPU%d", pp->ki_oncpu);
661 		else
662 			strcpy(status, "RUN");
663 		break;
664 	case SLOCK:
665 		if (pp->ki_kiflag & KI_LOCKBLOCK) {
666 			sprintf(status, "*%.6s", pp->ki_lockname);
667 			break;
668 		}
669 		/* fall through */
670 	case SSLEEP:
671 		if (pp->ki_wmesg != NULL) {
672 			sprintf(status, "%.6s", pp->ki_wmesg);
673 			break;
674 		}
675 		/* FALLTHROUGH */
676 	default:
677 
678 		if (state >= 0 &&
679 		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
680 			sprintf(status, "%.6s", state_abbrev[state]);
681 		else
682 			sprintf(status, "?%5d", state);
683 		break;
684 	}
685 
686 	if (displaymode == DISP_IO) {
687 		oldp = get_old_proc(pp);
688 		if (oldp != NULL) {
689 			ru.ru_inblock = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
690 			ru.ru_oublock = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
691 			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
692 			rup = &ru;
693 		} else {
694 			rup = RU(pp);
695 		}
696 		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
697 		s_tot = total_inblock + total_oublock + total_majflt;
698 
699 		sprintf(fmt, io_Proc_format,
700 		    pp->ki_pid,
701 		    namelength, namelength,
702 		    (*get_userid)(pp->ki_ruid),
703 		    rup->ru_inblock,
704 		    rup->ru_oublock,
705 		    rup->ru_majflt,
706 		    p_tot,
707 		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
708 		    screen_width > cmdlengthdelta ?
709 		    screen_width - cmdlengthdelta : 0,
710 		    printable(pp->ki_comm));
711 		return (fmt);
712 	}
713 	/* format this entry */
714 	sprintf(fmt,
715 	    smpmode ? smp_Proc_format : up_Proc_format,
716 	    pp->ki_pid,
717 	    namelength, namelength,
718 	    (*get_userid)(pp->ki_ruid),
719 	    pp->ki_pri.pri_level - PZERO,
720 
721 	    /*
722 	     * normal time      -> nice value -20 - +20
723 	     * real time 0 - 31 -> nice value -52 - -21
724 	     * idle time 0 - 31 -> nice value +21 - +52
725 	     */
726 	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
727 		pp->ki_nice - NZERO :
728 		(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
729 		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
730 		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
731 	    format_k2(PROCSIZE(pp)),
732 	    format_k2(pagetok(pp->ki_rssize)),
733 	    status,
734 	    smpmode ? pp->ki_lastcpu : 0,
735 	    format_time(cputime),
736 	    100.0 * weighted_cpu(pct, pp),
737 	    100.0 * pct,
738 	    screen_width > cmdlengthdelta ?
739 	    screen_width - cmdlengthdelta :
740 	    0,
741 	    printable(pp->ki_comm));
742 
743 	/* return the result */
744 	return (fmt);
745 }
746 
747 static void
748 getsysctl(char *name, void *ptr, size_t len)
749 {
750 	size_t nlen = len;
751 
752 	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
753 		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
754 		    strerror(errno));
755 		quit(23);
756 	}
757 	if (nlen != len) {
758 		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
759 		    (unsigned long)len, (unsigned long)nlen);
760 		quit(23);
761 	}
762 }
763 
764 /* comparison routines for qsort */
765 
766 int
767 compare_pid(const void *p1, const void *p2)
768 {
769 	const struct kinfo_proc * const *pp1 = p1;
770 	const struct kinfo_proc * const *pp2 = p2;
771 
772 	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
773 		abort();
774 
775 	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
776 }
777 
778 /*
779  *  proc_compare - comparison function for "qsort"
780  *	Compares the resource consumption of two processes using five
781  *	distinct keys.  The keys (in descending order of importance) are:
782  *	percent cpu, cpu ticks, state, resident set size, total virtual
783  *	memory usage.  The process states are ordered as follows (from least
784  *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
785  *	array declaration below maps a process state index into a number
786  *	that reflects this ordering.
787  */
788 
789 static int sorted_state[] =
790 {
791 	0,	/* not used		*/
792 	3,	/* sleep		*/
793 	1,	/* ABANDONED (WAIT)	*/
794 	6,	/* run			*/
795 	5,	/* start		*/
796 	2,	/* zombie		*/
797 	4	/* stop			*/
798 };
799 
800 
801 #define ORDERKEY_PCTCPU(a, b) do { \
802 	long diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
803 	if (diff != 0) \
804 		return (diff > 0 ? 1 : -1); \
805 } while (0)
806 
807 #define ORDERKEY_CPTICKS(a, b) do { \
808 	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
809 	if (diff != 0) \
810 		return (diff > 0 ? 1 : -1); \
811 } while (0)
812 
813 #define ORDERKEY_STATE(a, b) do { \
814 	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
815 	if (diff != 0) \
816 		return (diff > 0 ? 1 : -1); \
817 } while (0)
818 
819 #define ORDERKEY_PRIO(a, b) do { \
820 	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
821 	if (diff != 0) \
822 		return (diff > 0 ? 1 : -1); \
823 } while (0)
824 
825 #define ORDERKEY_RSSIZE(a, b) do { \
826 	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
827 	if (diff != 0) \
828 		return (diff > 0 ? 1 : -1); \
829 } while (0)
830 
831 #define ORDERKEY_MEM(a, b) do { \
832 	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
833 	if (diff != 0) \
834 		return (diff > 0 ? 1 : -1); \
835 } while (0)
836 
837 /* compare_cpu - the comparison function for sorting by cpu percentage */
838 
839 int
840 #ifdef ORDER
841 compare_cpu(void *arg1, void *arg2)
842 #else
843 proc_compare(void *arg1, void *arg2)
844 #endif
845 {
846 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
847 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
848 
849 	ORDERKEY_PCTCPU(p1, p2);
850 	ORDERKEY_CPTICKS(p1, p2);
851 	ORDERKEY_STATE(p1, p2);
852 	ORDERKEY_PRIO(p1, p2);
853 	ORDERKEY_RSSIZE(p1, p2);
854 	ORDERKEY_MEM(p1, p2);
855 
856 	return (0);
857 }
858 
859 #ifdef ORDER
860 /* compare routines */
861 int compare_size(), compare_res(), compare_time(), compare_prio();
862 
863 int (*proc_compares[])() = {
864 	compare_cpu,
865 	compare_size,
866 	compare_res,
867 	compare_time,
868 	compare_prio,
869 	NULL
870 };
871 
872 /* compare_size - the comparison function for sorting by total memory usage */
873 
874 int
875 compare_size(void *arg1, void *arg2)
876 {
877 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
878 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
879 
880 	ORDERKEY_MEM(p1, p2);
881 	ORDERKEY_RSSIZE(p1, p2);
882 	ORDERKEY_PCTCPU(p1, p2);
883 	ORDERKEY_CPTICKS(p1, p2);
884 	ORDERKEY_STATE(p1, p2);
885 	ORDERKEY_PRIO(p1, p2);
886 
887 	return (0);
888 }
889 
890 /* compare_res - the comparison function for sorting by resident set size */
891 
892 int
893 compare_res(void *arg1, void *arg2)
894 {
895 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
896 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
897 
898 	ORDERKEY_RSSIZE(p1, p2);
899 	ORDERKEY_MEM(p1, p2);
900 	ORDERKEY_PCTCPU(p1, p2);
901 	ORDERKEY_CPTICKS(p1, p2);
902 	ORDERKEY_STATE(p1, p2);
903 	ORDERKEY_PRIO(p1, p2);
904 
905 	return (0);
906 }
907 
908 /* compare_time - the comparison function for sorting by total cpu time */
909 
910 int
911 compare_time(void *arg1, void *arg2)
912 {
913 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
914 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
915 
916 	ORDERKEY_CPTICKS(p1, p2);
917 	ORDERKEY_PCTCPU(p1, p2);
918 	ORDERKEY_STATE(p1, p2);
919 	ORDERKEY_PRIO(p1, p2);
920 	ORDERKEY_RSSIZE(p1, p2);
921 	ORDERKEY_MEM(p1, p2);
922 
923 	return (0);
924 }
925 
926 /* compare_prio - the comparison function for sorting by priority */
927 
928 int
929 compare_prio(void *arg1, void *arg2)
930 {
931 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
932 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
933 
934 	ORDERKEY_PRIO(p1, p2);
935 	ORDERKEY_CPTICKS(p1, p2);
936 	ORDERKEY_PCTCPU(p1, p2);
937 	ORDERKEY_STATE(p1, p2);
938 	ORDERKEY_RSSIZE(p1, p2);
939 	ORDERKEY_MEM(p1, p2);
940 
941 	return (0);
942 }
943 #endif
944 
945 /* compare_io - the comparison function for sorting by total io */
946 
947 int
948 #ifdef ORDER
949 compare_iototal(void *arg1, void *arg2)
950 #else
951 io_compare(void *arg1, void *arg2)
952 #endif
953 {
954 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
955 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
956 
957 	return (get_io_total(p2) - get_io_total(p1));
958 }
959 
960 #ifdef ORDER
961 /* io compare routines */
962 int compare_ioread(), compare_iowrite(), compare_iofault();
963 
964 int (*io_compares[])() = {
965 	compare_iototal,
966 	compare_ioread,
967 	compare_iowrite,
968 	compare_iofault,
969 	NULL
970 };
971 
972 int
973 compare_ioread(void *arg1, void *arg2)
974 {
975 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
976 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
977 	long dummy, inp1, inp2;
978 
979 	(void) get_io_stats(p1, &inp1, &dummy, &dummy);
980 	(void) get_io_stats(p2, &inp2, &dummy, &dummy);
981 
982 	return (inp2 - inp1);
983 }
984 
985 int
986 compare_iowrite(void *arg1, void *arg2)
987 {
988 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
989 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
990 	long dummy, oup1, oup2;
991 
992 	(void) get_io_stats(p1, &dummy, &oup1, &dummy);
993 	(void) get_io_stats(p2, &dummy, &oup2, &dummy);
994 
995 	return (oup2 - oup1);
996 }
997 
998 int
999 compare_iofault(void *arg1, void *arg2)
1000 {
1001 	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1002 	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1003 	long dummy, flp1, flp2;
1004 
1005 	(void) get_io_stats(p1, &dummy, &dummy, &flp1);
1006 	(void) get_io_stats(p2, &dummy, &dummy, &flp2);
1007 
1008 	return (flp2 - flp1);
1009 }
1010 
1011 #endif /* ORDER */
1012 
1013 /*
1014  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1015  *		the process does not exist.
1016  *		It is EXTREMLY IMPORTANT that this function work correctly.
1017  *		If top runs setuid root (as in SVR4), then this function
1018  *		is the only thing that stands in the way of a serious
1019  *		security problem.  It validates requests for the "kill"
1020  *		and "renice" commands.
1021  */
1022 
1023 int
1024 proc_owner(int pid)
1025 {
1026 	int cnt;
1027 	struct kinfo_proc **prefp;
1028 	struct kinfo_proc *pp;
1029 
1030 	prefp = pref;
1031 	cnt = pref_len;
1032 	while (--cnt >= 0) {
1033 		pp = *prefp++;
1034 		if (pp->ki_pid == (pid_t)pid)
1035 			return ((int)pp->ki_ruid);
1036 	}
1037 	return (-1);
1038 }
1039 
1040 int
1041 swapmode(int *retavail, int *retfree)
1042 {
1043 	int n;
1044 	int pagesize = getpagesize();
1045 	struct kvm_swap swapary[1];
1046 
1047 	*retavail = 0;
1048 	*retfree = 0;
1049 
1050 #define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1051 
1052 	n = kvm_getswapinfo(kd, swapary, 1, 0);
1053 	if (n < 0 || swapary[0].ksw_total == 0)
1054 		return (0);
1055 
1056 	*retavail = CONVERT(swapary[0].ksw_total);
1057 	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1058 
1059 	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1060 	return (n);
1061 }
1062