machine.c revision 132955
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: head/usr.bin/top/machine.c 132955 2004-08-01 09:19:41Z alfred $
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
52static void getsysctl(char *, void *, size_t);
53
54#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
55
56extern char* printable(char *);
57int swapmode(int *retavail, int *retfree);
58static int smpmode;
59enum displaymodes displaymode;
60static int namelength;
61static int cmdlengthdelta;
62
63/* Prototypes for top internals */
64void quit(int);
65int compare_pid(const void *a, const void *b);
66
67/* get_process_info passes back a handle.  This is what it looks like: */
68
69struct 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
96static 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
102static 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
108static 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
120char *state_abbrev[] =
121{
122	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
123};
124
125
126static kvm_t *kd;
127
128/* values that we stash away in _init and use in later routines */
129
130static double logcpu;
131
132/* these are retrieved from the kernel in _init */
133
134static load_avg  ccpu;
135
136/* these are used in the get_ functions */
137
138static int lastpid;
139
140/* these are for calculating cpu state percentages */
141
142static long cp_time[CPUSTATES];
143static long cp_old[CPUSTATES];
144static long cp_diff[CPUSTATES];
145
146/* these are for detailing the process states */
147
148int process_states[8];
149char *procstatenames[] = {
150	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
151	" zombie, ", " waiting, ", " lock, ",
152	NULL
153};
154
155/* these are for detailing the cpu states */
156
157int cpu_states[CPUSTATES];
158char *cpustatenames[] = {
159	"user", "nice", "system", "interrupt", "idle", NULL
160};
161
162/* these are for detailing the memory statistics */
163
164int memory_stats[7];
165char *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
171int swap_stats[7];
172char *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
181static int nproc;
182static int onproc = -1;
183static int pref_len;
184static struct kinfo_proc *pbase;
185static struct kinfo_proc **pref;
186static struct kinfo_proc *previous_procs;
187static struct kinfo_proc **previous_pref;
188static int previous_proc_count = 0;
189static int previous_proc_count_max = 0;
190
191/* total number of io operations */
192static long total_inblock;
193static long total_oublock;
194static long total_majflt;
195
196/* these are for getting the memory statistics */
197
198static 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 */
205long 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 */
212char *proc_ordernames[] = {
213	"cpu", "size", "res", "time", "pri", NULL
214};
215char *io_ordernames[] = {
216	"total", "read", "write", "fault", 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	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
289char *
290format_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
312static int swappgsin = -1;
313static int swappgsout = -1;
314extern struct timeval timeout;
315
316void
317get_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/*
419 * We need to compare data from the old process entry with the new
420 * process entry.
421 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
422 * structure to cache the mapping.  We also use a negative cache pointer
423 * of NOPROC to avoid duplicate lookups.
424 * XXX: this could be done when the actual processes are fetched, we do
425 * it here out of laziness.
426 */
427const struct kinfo_proc *
428get_old_proc(struct kinfo_proc *pp)
429{
430	struct kinfo_proc **oldpp, *oldp;
431
432	/*
433	 * If this is the first fetch of the kinfo_procs then we don't have
434	 * any previous entries.
435	 */
436	if (previous_proc_count == 0)
437		return (NULL);
438	/* negative cache? */
439	if (pp->ki_udata == NOPROC)
440		return (NULL);
441	/* cached? */
442	if (pp->ki_udata != NULL)
443		return (pp->ki_udata);
444	/*
445	 * Not cached,
446	 * 1) look up based on pid.
447	 * 2) compare process start.
448	 * If we fail here, then setup a negative cache entry, otherwise
449	 * cache it.
450	 */
451	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
452	    sizeof(*previous_pref), compare_pid);
453	if (oldpp == NULL) {
454		pp->ki_udata = NOPROC;
455		return (NULL);
456	}
457	oldp = *oldpp;
458	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
459		pp->ki_udata = NOPROC;
460		return (NULL);
461	}
462	pp->ki_udata = oldp;
463	return (oldp);
464}
465
466/*
467 * Return the total amount of IO done in blocks in/out and faults.
468 * store the values individually in the pointers passed in.
469 */
470long
471get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp)
472{
473	const struct kinfo_proc *oldp;
474	static struct kinfo_proc dummy;
475	long ret;
476
477	oldp = get_old_proc(pp);
478	if (oldp == NULL) {
479		bzero(&dummy, sizeof(dummy));
480		oldp = &dummy;
481	}
482
483	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
484	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
485	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
486	ret =
487	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
488	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
489	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
490	return (ret);
491}
492
493/*
494 * Return the total number of block in/out and faults by a process.
495 */
496long
497get_io_total(struct kinfo_proc *pp)
498{
499	long dummy;
500
501	return (get_io_stats(pp, &dummy, &dummy, &dummy));
502}
503
504static struct handle handle;
505
506caddr_t
507get_process_info(struct system_info *si, struct process_select *sel,
508    int (*compare)(const void *, const void *))
509{
510	int i;
511	int total_procs;
512	long p_io;
513	long p_inblock, p_oublock, p_majflt;
514	int active_procs;
515	struct kinfo_proc **prefp;
516	struct kinfo_proc *pp;
517	struct kinfo_proc *prev_pp = NULL;
518
519	/* these are copied out of sel for speed */
520	int show_idle;
521	int show_self;
522	int show_system;
523	int show_uid;
524	int show_command;
525
526	/*
527	 * Save the previous process info.
528	 */
529	if (previous_proc_count_max < nproc) {
530		free(previous_procs);
531		previous_procs = malloc(nproc * sizeof(*previous_procs));
532		free(previous_pref);
533		previous_pref = malloc(nproc * sizeof(*previous_pref));
534		if (previous_procs == NULL || previous_pref == NULL) {
535			(void) fprintf(stderr, "top: Out of memory.\n");
536			quit(23);
537		}
538		previous_proc_count_max = nproc;
539	}
540	if (nproc) {
541		for (i = 0; i < nproc; i++)
542			previous_pref[i] = &previous_procs[i];
543		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
544		qsort(previous_pref, nproc, sizeof(*previous_pref), compare_pid);
545	}
546	previous_proc_count = nproc;
547
548	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
549	if (nproc > onproc)
550		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
551	if (pref == NULL || pbase == NULL) {
552		(void) fprintf(stderr, "top: Out of memory.\n");
553		quit(23);
554	}
555	/* get a pointer to the states summary array */
556	si->procstates = process_states;
557
558	/* set up flags which define what we are going to select */
559	show_idle = sel->idle;
560	show_self = sel->self == -1;
561	show_system = sel->system;
562	show_uid = sel->uid != -1;
563	show_command = sel->command != NULL;
564
565	/* count up process states and get pointers to interesting procs */
566	total_procs = 0;
567	active_procs = 0;
568	total_inblock = 0;
569	total_oublock = 0;
570	total_majflt = 0;
571	memset((char *)process_states, 0, sizeof(process_states));
572	prefp = pref;
573	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
574
575		if (pp->ki_stat == 0)
576			/* not in use */
577			continue;
578
579		if (!show_self && pp->ki_pid == sel->self)
580			/* skip self */
581			continue;
582
583		if (!show_system && (pp->ki_flag & P_SYSTEM))
584			/* skip system process */
585			continue;
586
587		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt);
588		total_inblock += p_inblock;
589		total_oublock += p_oublock;
590		total_majflt += p_majflt;
591		total_procs++;
592		process_states[pp->ki_stat]++;
593
594		if (pp->ki_stat == SZOMB)
595			/* skip zombies */
596			continue;
597
598		if (displaymode == DISP_CPU && !show_idle &&
599		    (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN))
600			/* skip idle or non-running processes */
601			continue;
602
603		if (displaymode == DISP_IO && !show_idle && p_io == 0)
604			/* skip processes that aren't doing I/O */
605			continue;
606
607		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
608			/* skip processes which don't belong to the selected UID */
609			continue;
610
611		/*
612		 * When not showing threads, take the first thread
613		 * for output and add the fields that we can from
614		 * the rest of the process's threads rather than
615		 * using the system's mostly-broken KERN_PROC_PROC.
616		 */
617		if (sel->thread || prev_pp == NULL ||
618		    prev_pp->ki_pid != pp->ki_pid) {
619			*prefp++ = pp;
620			active_procs++;
621			prev_pp = pp;
622		} else {
623			prev_pp->ki_pctcpu += pp->ki_pctcpu;
624		}
625	}
626
627	/* if requested, sort the "interesting" processes */
628	if (compare != NULL)
629		qsort(pref, active_procs, sizeof(*pref), compare);
630
631	/* remember active and total counts */
632	si->p_total = total_procs;
633	si->p_active = pref_len = active_procs;
634
635	/* pass back a handle */
636	handle.next_proc = pref;
637	handle.remaining = active_procs;
638	return ((caddr_t)&handle);
639}
640
641static char fmt[128];	/* static area where result is built */
642
643char *
644format_next_process(caddr_t handle, char *(*get_userid)(int))
645{
646	struct kinfo_proc *pp;
647	const struct kinfo_proc *oldp;
648	long cputime;
649	double pct;
650	struct handle *hp;
651	char status[16];
652	int state;
653	struct rusage ru, *rup;
654	long p_tot, s_tot;
655
656	/* find and remember the next proc structure */
657	hp = (struct handle *)handle;
658	pp = *(hp->next_proc++);
659	hp->remaining--;
660
661	/* get the process's command name */
662	if ((pp->ki_sflag & PS_INMEM) == 0) {
663		/*
664		 * Print swapped processes as <pname>
665		 */
666		size_t len = strlen(pp->ki_comm);
667		if (len > sizeof(pp->ki_comm) - 3)
668			len = sizeof(pp->ki_comm) - 3;
669		memmove(pp->ki_comm + 1, pp->ki_comm, len);
670		pp->ki_comm[0] = '<';
671		pp->ki_comm[len + 1] = '>';
672		pp->ki_comm[len + 2] = '\0';
673	}
674
675	/*
676	 * Convert the process's runtime from microseconds to seconds.  This
677	 * time includes the interrupt time although that is not wanted here.
678	 * ps(1) is similarly sloppy.
679	 */
680	cputime = (pp->ki_runtime + 500000) / 1000000;
681
682	/* calculate the base for cpu percentages */
683	pct = pctdouble(pp->ki_pctcpu);
684
685	/* generate "STATE" field */
686	switch (state = pp->ki_stat) {
687	case SRUN:
688		if (smpmode && pp->ki_oncpu != 0xff)
689			sprintf(status, "CPU%d", pp->ki_oncpu);
690		else
691			strcpy(status, "RUN");
692		break;
693	case SLOCK:
694		if (pp->ki_kiflag & KI_LOCKBLOCK) {
695			sprintf(status, "*%.6s", pp->ki_lockname);
696			break;
697		}
698		/* fall through */
699	case SSLEEP:
700		if (pp->ki_wmesg != NULL) {
701			sprintf(status, "%.6s", pp->ki_wmesg);
702			break;
703		}
704		/* FALLTHROUGH */
705	default:
706
707		if (state >= 0 &&
708		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
709			sprintf(status, "%.6s", state_abbrev[state]);
710		else
711			sprintf(status, "?%5d", state);
712		break;
713	}
714
715	if (displaymode == DISP_IO) {
716		oldp = get_old_proc(pp);
717		if (oldp != NULL) {
718			ru.ru_inblock = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
719			ru.ru_oublock = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
720			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
721			rup = &ru;
722		} else {
723			rup = RU(pp);
724		}
725		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
726		s_tot = total_inblock + total_oublock + total_majflt;
727
728		sprintf(fmt, io_Proc_format,
729		    pp->ki_pid,
730		    namelength, namelength,
731		    (*get_userid)(pp->ki_ruid),
732		    rup->ru_inblock,
733		    rup->ru_oublock,
734		    rup->ru_majflt,
735		    p_tot,
736		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
737		    screen_width > cmdlengthdelta ?
738		    screen_width - cmdlengthdelta : 0,
739		    printable(pp->ki_comm));
740		return (fmt);
741	}
742	/* format this entry */
743	sprintf(fmt,
744	    smpmode ? smp_Proc_format : up_Proc_format,
745	    pp->ki_pid,
746	    namelength, namelength,
747	    (*get_userid)(pp->ki_ruid),
748	    pp->ki_pri.pri_level - PZERO,
749
750	    /*
751	     * normal time      -> nice value -20 - +20
752	     * real time 0 - 31 -> nice value -52 - -21
753	     * idle time 0 - 31 -> nice value +21 - +52
754	     */
755	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
756		pp->ki_nice - NZERO :
757		(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
758		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
759		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
760	    format_k2(PROCSIZE(pp)),
761	    format_k2(pagetok(pp->ki_rssize)),
762	    status,
763	    smpmode ? pp->ki_lastcpu : 0,
764	    format_time(cputime),
765	    100.0 * weighted_cpu(pct, pp),
766	    100.0 * pct,
767	    screen_width > cmdlengthdelta ?
768	    screen_width - cmdlengthdelta :
769	    0,
770	    printable(pp->ki_comm));
771
772	/* return the result */
773	return (fmt);
774}
775
776static void
777getsysctl(char *name, void *ptr, size_t len)
778{
779	size_t nlen = len;
780
781	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
782		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
783		    strerror(errno));
784		quit(23);
785	}
786	if (nlen != len) {
787		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
788		    (unsigned long)len, (unsigned long)nlen);
789		quit(23);
790	}
791}
792
793/* comparison routines for qsort */
794
795int
796compare_pid(const void *p1, const void *p2)
797{
798	const struct kinfo_proc * const *pp1 = p1;
799	const struct kinfo_proc * const *pp2 = p2;
800
801	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
802		abort();
803
804	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
805}
806
807/*
808 *  proc_compare - comparison function for "qsort"
809 *	Compares the resource consumption of two processes using five
810 *	distinct keys.  The keys (in descending order of importance) are:
811 *	percent cpu, cpu ticks, state, resident set size, total virtual
812 *	memory usage.  The process states are ordered as follows (from least
813 *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
814 *	array declaration below maps a process state index into a number
815 *	that reflects this ordering.
816 */
817
818static int sorted_state[] =
819{
820	0,	/* not used		*/
821	3,	/* sleep		*/
822	1,	/* ABANDONED (WAIT)	*/
823	6,	/* run			*/
824	5,	/* start		*/
825	2,	/* zombie		*/
826	4	/* stop			*/
827};
828
829
830#define ORDERKEY_PCTCPU(a, b) do { \
831	long diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
832	if (diff != 0) \
833		return (diff > 0 ? 1 : -1); \
834} while (0)
835
836#define ORDERKEY_CPTICKS(a, b) do { \
837	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
838	if (diff != 0) \
839		return (diff > 0 ? 1 : -1); \
840} while (0)
841
842#define ORDERKEY_STATE(a, b) do { \
843	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
844	if (diff != 0) \
845		return (diff > 0 ? 1 : -1); \
846} while (0)
847
848#define ORDERKEY_PRIO(a, b) do { \
849	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
850	if (diff != 0) \
851		return (diff > 0 ? 1 : -1); \
852} while (0)
853
854#define ORDERKEY_RSSIZE(a, b) do { \
855	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
856	if (diff != 0) \
857		return (diff > 0 ? 1 : -1); \
858} while (0)
859
860#define ORDERKEY_MEM(a, b) do { \
861	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
862	if (diff != 0) \
863		return (diff > 0 ? 1 : -1); \
864} while (0)
865
866/* compare_cpu - the comparison function for sorting by cpu percentage */
867
868int
869#ifdef ORDER
870compare_cpu(void *arg1, void *arg2)
871#else
872proc_compare(void *arg1, void *arg2)
873#endif
874{
875	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
876	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
877
878	ORDERKEY_PCTCPU(p1, p2);
879	ORDERKEY_CPTICKS(p1, p2);
880	ORDERKEY_STATE(p1, p2);
881	ORDERKEY_PRIO(p1, p2);
882	ORDERKEY_RSSIZE(p1, p2);
883	ORDERKEY_MEM(p1, p2);
884
885	return (0);
886}
887
888#ifdef ORDER
889/* compare routines */
890int compare_size(), compare_res(), compare_time(), compare_prio();
891
892int (*proc_compares[])() = {
893	compare_cpu,
894	compare_size,
895	compare_res,
896	compare_time,
897	compare_prio,
898	NULL
899};
900
901/* compare_size - the comparison function for sorting by total memory usage */
902
903int
904compare_size(void *arg1, void *arg2)
905{
906	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
907	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
908
909	ORDERKEY_MEM(p1, p2);
910	ORDERKEY_RSSIZE(p1, p2);
911	ORDERKEY_PCTCPU(p1, p2);
912	ORDERKEY_CPTICKS(p1, p2);
913	ORDERKEY_STATE(p1, p2);
914	ORDERKEY_PRIO(p1, p2);
915
916	return (0);
917}
918
919/* compare_res - the comparison function for sorting by resident set size */
920
921int
922compare_res(void *arg1, void *arg2)
923{
924	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
925	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
926
927	ORDERKEY_RSSIZE(p1, p2);
928	ORDERKEY_MEM(p1, p2);
929	ORDERKEY_PCTCPU(p1, p2);
930	ORDERKEY_CPTICKS(p1, p2);
931	ORDERKEY_STATE(p1, p2);
932	ORDERKEY_PRIO(p1, p2);
933
934	return (0);
935}
936
937/* compare_time - the comparison function for sorting by total cpu time */
938
939int
940compare_time(void *arg1, void *arg2)
941{
942	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
943	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
944
945	ORDERKEY_CPTICKS(p1, p2);
946	ORDERKEY_PCTCPU(p1, p2);
947	ORDERKEY_STATE(p1, p2);
948	ORDERKEY_PRIO(p1, p2);
949	ORDERKEY_RSSIZE(p1, p2);
950	ORDERKEY_MEM(p1, p2);
951
952	return (0);
953}
954
955/* compare_prio - the comparison function for sorting by priority */
956
957int
958compare_prio(void *arg1, void *arg2)
959{
960	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
961	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
962
963	ORDERKEY_PRIO(p1, p2);
964	ORDERKEY_CPTICKS(p1, p2);
965	ORDERKEY_PCTCPU(p1, p2);
966	ORDERKEY_STATE(p1, p2);
967	ORDERKEY_RSSIZE(p1, p2);
968	ORDERKEY_MEM(p1, p2);
969
970	return (0);
971}
972#endif
973
974/* compare_io - the comparison function for sorting by total io */
975
976int
977#ifdef ORDER
978compare_iototal(void *arg1, void *arg2)
979#else
980io_compare(void *arg1, void *arg2)
981#endif
982{
983	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
984	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
985
986	return (get_io_total(p2) - get_io_total(p1));
987}
988
989#ifdef ORDER
990/* io compare routines */
991int compare_ioread(), compare_iowrite(), compare_iofault();
992
993int (*io_compares[])() = {
994	compare_iototal,
995	compare_ioread,
996	compare_iowrite,
997	compare_iofault,
998	NULL
999};
1000
1001int
1002compare_ioread(void *arg1, void *arg2)
1003{
1004	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1005	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1006	long dummy, inp1, inp2;
1007
1008	(void) get_io_stats(p1, &inp1, &dummy, &dummy);
1009	(void) get_io_stats(p2, &inp2, &dummy, &dummy);
1010
1011	return (inp2 - inp1);
1012}
1013
1014int
1015compare_iowrite(void *arg1, void *arg2)
1016{
1017	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1018	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1019	long dummy, oup1, oup2;
1020
1021	(void) get_io_stats(p1, &dummy, &oup1, &dummy);
1022	(void) get_io_stats(p2, &dummy, &oup2, &dummy);
1023
1024	return (oup2 - oup1);
1025}
1026
1027int
1028compare_iofault(void *arg1, void *arg2)
1029{
1030	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1031	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1032	long dummy, flp1, flp2;
1033
1034	(void) get_io_stats(p1, &dummy, &dummy, &flp1);
1035	(void) get_io_stats(p2, &dummy, &dummy, &flp2);
1036
1037	return (flp2 - flp1);
1038}
1039
1040#endif /* ORDER */
1041
1042/*
1043 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1044 *		the process does not exist.
1045 *		It is EXTREMLY IMPORTANT that this function work correctly.
1046 *		If top runs setuid root (as in SVR4), then this function
1047 *		is the only thing that stands in the way of a serious
1048 *		security problem.  It validates requests for the "kill"
1049 *		and "renice" commands.
1050 */
1051
1052int
1053proc_owner(int pid)
1054{
1055	int cnt;
1056	struct kinfo_proc **prefp;
1057	struct kinfo_proc *pp;
1058
1059	prefp = pref;
1060	cnt = pref_len;
1061	while (--cnt >= 0) {
1062		pp = *prefp++;
1063		if (pp->ki_pid == (pid_t)pid)
1064			return ((int)pp->ki_ruid);
1065	}
1066	return (-1);
1067}
1068
1069int
1070swapmode(int *retavail, int *retfree)
1071{
1072	int n;
1073	int pagesize = getpagesize();
1074	struct kvm_swap swapary[1];
1075
1076	*retavail = 0;
1077	*retfree = 0;
1078
1079#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1080
1081	n = kvm_getswapinfo(kd, swapary, 1, 0);
1082	if (n < 0 || swapary[0].ksw_total == 0)
1083		return (0);
1084
1085	*retavail = CONVERT(swapary[0].ksw_total);
1086	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1087
1088	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1089	return (n);
1090}
1091