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