machine.c revision 131627
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 131627 2004-07-05 14:52:06Z des $
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/* sorting orders. first is default */
209char *ordernames[] = {
210	"cpu", "size", "res", "time", "pri", NULL
211};
212#endif
213
214int
215machine_init(struct statics *statics)
216{
217	int pagesize;
218	size_t modelen;
219	struct passwd *pw;
220
221	modelen = sizeof(smpmode);
222	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
223		sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
224	    modelen != sizeof(smpmode))
225		smpmode = 0;
226
227	while ((pw = getpwent()) != NULL) {
228		if (strlen(pw->pw_name) > namelength)
229			namelength = strlen(pw->pw_name);
230	}
231	if (namelength < 8)
232		namelength = 8;
233	if (smpmode && namelength > 13)
234		namelength = 13;
235	else if (namelength > 15)
236		namelength = 15;
237
238	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
239	if (kd == NULL)
240		return (-1);
241
242	GETSYSCTL("kern.ccpu", ccpu);
243
244	/* this is used in calculating WCPU -- calculate it ahead of time */
245	logcpu = log(loaddouble(ccpu));
246
247	pbase = NULL;
248	pref = NULL;
249	nproc = 0;
250	onproc = -1;
251	/* get the page size with "getpagesize" and calculate pageshift from it */
252	pagesize = getpagesize();
253	pageshift = 0;
254	while (pagesize > 1) {
255		pageshift++;
256		pagesize >>= 1;
257	}
258
259	/* we only need the amount of log(2)1024 for our conversion */
260	pageshift -= LOG1024;
261
262	/* fill in the statics information */
263	statics->procstate_names = procstatenames;
264	statics->cpustate_names = cpustatenames;
265	statics->memory_names = memorynames;
266	statics->swap_names = swapnames;
267#ifdef ORDER
268	statics->order_names = ordernames;
269#endif
270
271	/* all done! */
272	return (0);
273}
274
275char *
276format_header(char *uname_field)
277{
278	static char Header[128];
279	const char *prehead;
280
281	switch (displaymode) {
282	case DISP_CPU:
283		prehead = smpmode ? smp_header : up_header;
284		break;
285	case DISP_IO:
286		prehead = io_header;
287		break;
288	}
289
290	snprintf(Header, sizeof(Header), prehead,
291	    namelength, namelength, uname_field);
292
293	cmdlengthdelta = strlen(Header) - 7;
294
295	return (Header);
296}
297
298static int swappgsin = -1;
299static int swappgsout = -1;
300extern struct timeval timeout;
301
302void
303get_system_info(struct system_info *si)
304{
305	long total;
306	struct loadavg sysload;
307	int mib[2];
308	struct timeval boottime;
309	size_t bt_size;
310	int i;
311
312	/* get the cp_time array */
313	GETSYSCTL("kern.cp_time", cp_time);
314	GETSYSCTL("vm.loadavg", sysload);
315	GETSYSCTL("kern.lastpid", lastpid);
316
317	/* convert load averages to doubles */
318	for (i = 0; i < 3; i++)
319		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
320
321	/* convert cp_time counts to percentages */
322	total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
323
324	/* sum memory & swap statistics */
325	{
326		static unsigned int swap_delay = 0;
327		static int swapavail = 0;
328		static int swapfree = 0;
329		static int bufspace = 0;
330		static int nspgsin, nspgsout;
331
332		GETSYSCTL("vfs.bufspace", bufspace);
333		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
334		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
335		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
336		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
337		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
338		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
339		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
340		/* convert memory stats to Kbytes */
341		memory_stats[0] = pagetok(memory_stats[0]);
342		memory_stats[1] = pagetok(memory_stats[1]);
343		memory_stats[2] = pagetok(memory_stats[2]);
344		memory_stats[3] = pagetok(memory_stats[3]);
345		memory_stats[4] = bufspace / 1024;
346		memory_stats[5] = pagetok(memory_stats[5]);
347		memory_stats[6] = -1;
348
349		/* first interval */
350		if (swappgsin < 0) {
351			swap_stats[4] = 0;
352			swap_stats[5] = 0;
353		}
354
355		/* compute differences between old and new swap statistic */
356		else {
357			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
358			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
359		}
360
361		swappgsin = nspgsin;
362		swappgsout = nspgsout;
363
364		/* call CPU heavy swapmode() only for changes */
365		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
366			swap_stats[3] = swapmode(&swapavail, &swapfree);
367			swap_stats[0] = swapavail;
368			swap_stats[1] = swapavail - swapfree;
369			swap_stats[2] = swapfree;
370		}
371		swap_delay = 1;
372		swap_stats[6] = -1;
373	}
374
375	/* set arrays and strings */
376	si->cpustates = cpu_states;
377	si->memory = memory_stats;
378	si->swap = swap_stats;
379
380
381	if (lastpid > 0) {
382		si->last_pid = lastpid;
383	} else {
384		si->last_pid = -1;
385	}
386
387	/*
388	 * Print how long system has been up.
389	 * (Found by looking getting "boottime" from the kernel)
390	 */
391	mib[0] = CTL_KERN;
392	mib[1] = KERN_BOOTTIME;
393	bt_size = sizeof(boottime);
394	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
395	    boottime.tv_sec != 0) {
396		si->boottime = boottime;
397	} else {
398		si->boottime.tv_sec = -1;
399	}
400}
401
402const struct kinfo_proc *
403get_old_proc(struct kinfo_proc *pp)
404{
405	struct kinfo_proc **oldpp, *oldp;
406
407	if (previous_proc_count == 0)
408		return (NULL);
409	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
410	    sizeof(*previous_pref), compare_pid);
411	if (oldpp == NULL)
412		return (NULL);
413	oldp = *oldpp;
414	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0)
415		return (NULL);
416	return (oldp);
417}
418
419long
420get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp)
421{
422	const struct kinfo_proc *oldp;
423	static struct kinfo_proc dummy;
424	long ret;
425
426	oldp = get_old_proc(pp);
427	if (oldp == NULL) {
428		bzero(&dummy, sizeof(dummy));
429		oldp = &dummy;
430	}
431
432	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
433	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
434	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
435	ret =
436	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
437	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
438	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
439	return (ret);
440}
441
442long
443get_io_total(struct kinfo_proc *pp)
444{
445	long dummy;
446
447	return (get_io_stats(pp, &dummy, &dummy, &dummy));
448}
449
450static struct handle handle;
451
452caddr_t
453get_process_info(struct system_info *si, struct process_select *sel,
454    int (*compare)(const void *, const void *))
455{
456	int i;
457	int total_procs;
458	long p_io;
459	long p_inblock, p_oublock, p_majflt;
460	int active_procs;
461	struct kinfo_proc **prefp;
462	struct kinfo_proc *pp;
463	struct kinfo_proc *prev_pp = NULL;
464
465	/* these are copied out of sel for speed */
466	int show_idle;
467	int show_self;
468	int show_system;
469	int show_uid;
470	int show_command;
471
472	/*
473	 * Save the previous process info.
474	 */
475	if (previous_proc_count_max < nproc) {
476		free(previous_procs);
477		previous_procs = malloc(nproc * sizeof(*previous_procs));
478		free(previous_pref);
479		previous_pref = malloc(nproc * sizeof(*previous_pref));
480		if (previous_procs == NULL || previous_pref == NULL) {
481			(void) fprintf(stderr, "top: Out of memory.\n");
482			quit(23);
483		}
484		previous_proc_count_max = nproc;
485	}
486	if (nproc) {
487		for (i = 0; i < nproc; i++)
488			previous_pref[i] = &previous_procs[i];
489		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
490		qsort(previous_pref, nproc, sizeof(*previous_pref), compare_pid);
491	}
492	previous_proc_count = nproc;
493
494	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
495	if (nproc > onproc)
496		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
497	if (pref == NULL || pbase == NULL) {
498		(void) fprintf(stderr, "top: Out of memory.\n");
499		quit(23);
500	}
501	/* get a pointer to the states summary array */
502	si->procstates = process_states;
503
504	/* set up flags which define what we are going to select */
505	show_idle = sel->idle;
506	show_self = sel->self;
507	show_system = sel->system;
508	show_uid = sel->uid != -1;
509	show_command = sel->command != NULL;
510
511	/* count up process states and get pointers to interesting procs */
512	total_procs = 0;
513	active_procs = 0;
514	total_inblock = 0;
515	total_oublock = 0;
516	total_majflt = 0;
517	memset((char *)process_states, 0, sizeof(process_states));
518	prefp = pref;
519	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
520
521		if (pp->ki_stat == 0)
522		/* not in use */
523		continue;
524
525		if (!show_self && pp->ki_pid == sel->self)
526			/* skip self */
527			continue;
528
529		if (!show_system && (pp->ki_flag & P_SYSTEM))
530			/* skip system process */
531			continue;
532
533		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt);
534		total_inblock += p_inblock;
535		total_oublock += p_oublock;
536		total_majflt += p_majflt;
537		total_procs++;
538		process_states[pp->ki_stat]++;
539
540		if (pp->ki_stat == SZOMB)
541			/* skip zombies */
542			continue;
543
544		if (displaymode == DISP_CPU && !show_idle &&
545		    (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN))
546			/* skip idle or non-running processes */
547			continue;
548
549		if (displaymode == DISP_IO && !show_idle && p_io == 0)
550			/* skip processes that aren't doing I/O */
551			continue;
552
553		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
554			/* skip processes which don't belong to the selected UID */
555			continue;
556
557		/*
558		 * When not showing threads, take the first thread
559		 * for output and add the fields that we can from
560		 * the rest of the process's threads rather than
561		 * using the system's mostly-broken KERN_PROC_PROC.
562		 */
563		if (sel->thread || prev_pp == NULL ||
564		    prev_pp->ki_pid != pp->ki_pid) {
565			*prefp++ = pp;
566			active_procs++;
567			prev_pp = pp;
568		} else {
569			prev_pp->ki_pctcpu += pp->ki_pctcpu;
570		}
571	}
572
573	/* if requested, sort the "interesting" processes */
574	if (compare != NULL)
575		qsort(pref, active_procs, sizeof(*pref), compare);
576
577	/* remember active and total counts */
578	si->p_total = total_procs;
579	si->p_active = pref_len = active_procs;
580
581	/* pass back a handle */
582	handle.next_proc = pref;
583	handle.remaining = active_procs;
584	return ((caddr_t)&handle);
585}
586
587static char fmt[128];	/* static area where result is built */
588
589char *
590format_next_process(caddr_t handle, char *(*get_userid)(int))
591{
592	struct kinfo_proc *pp;
593	const struct kinfo_proc *oldp;
594	long cputime;
595	double pct;
596	struct handle *hp;
597	char status[16];
598	int state;
599	struct rusage ru, *rup;
600	long p_tot, s_tot;
601
602	/* find and remember the next proc structure */
603	hp = (struct handle *)handle;
604	pp = *(hp->next_proc++);
605	hp->remaining--;
606
607	/* get the process's command name */
608	if ((pp->ki_sflag & PS_INMEM) == 0) {
609		/*
610		 * Print swapped processes as <pname>
611		 */
612		size_t len = strlen(pp->ki_comm);
613		if (len > sizeof(pp->ki_comm) - 3)
614			len = sizeof(pp->ki_comm) - 3;
615		memmove(pp->ki_comm + 1, pp->ki_comm, len);
616		pp->ki_comm[0] = '<';
617		pp->ki_comm[len + 1] = '>';
618		pp->ki_comm[len + 2] = '\0';
619	}
620
621	/*
622	 * Convert the process's runtime from microseconds to seconds.  This
623	 * time includes the interrupt time although that is not wanted here.
624	 * ps(1) is similarly sloppy.
625	 */
626	cputime = (pp->ki_runtime + 500000) / 1000000;
627
628	/* calculate the base for cpu percentages */
629	pct = pctdouble(pp->ki_pctcpu);
630
631	/* generate "STATE" field */
632	switch (state = pp->ki_stat) {
633	case SRUN:
634		if (smpmode && pp->ki_oncpu != 0xff)
635			sprintf(status, "CPU%d", pp->ki_oncpu);
636		else
637			strcpy(status, "RUN");
638		break;
639	case SLOCK:
640		if (pp->ki_kiflag & KI_LOCKBLOCK) {
641			sprintf(status, "*%.6s", pp->ki_lockname);
642			break;
643		}
644		/* fall through */
645	case SSLEEP:
646		if (pp->ki_wmesg != NULL) {
647			sprintf(status, "%.6s", pp->ki_wmesg);
648			break;
649		}
650		/* FALLTHROUGH */
651	default:
652
653		if (state >= 0 &&
654		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
655			sprintf(status, "%.6s", state_abbrev[state]);
656		else
657			sprintf(status, "?%5d", state);
658		break;
659	}
660
661	if (displaymode == DISP_IO) {
662		oldp = get_old_proc(pp);
663		if (oldp != NULL) {
664			ru.ru_inblock = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
665			ru.ru_oublock = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
666			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
667			rup = &ru;
668		} else {
669			rup = RU(pp);
670		}
671		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
672		s_tot = total_inblock + total_oublock + total_majflt;
673
674		sprintf(fmt, io_Proc_format,
675		    pp->ki_pid,
676		    namelength, namelength,
677		    (*get_userid)(pp->ki_ruid),
678		    rup->ru_inblock,
679		    rup->ru_oublock,
680		    rup->ru_majflt,
681		    p_tot,
682		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
683		    screen_width > cmdlengthdelta ?
684		    screen_width - cmdlengthdelta : 0,
685		    printable(pp->ki_comm));
686		return (fmt);
687	}
688	/* format this entry */
689	sprintf(fmt,
690	    smpmode ? smp_Proc_format : up_Proc_format,
691	    pp->ki_pid,
692	    namelength, namelength,
693	    (*get_userid)(pp->ki_ruid),
694	    pp->ki_pri.pri_level - PZERO,
695
696	    /*
697	     * normal time      -> nice value -20 - +20
698	     * real time 0 - 31 -> nice value -52 - -21
699	     * idle time 0 - 31 -> nice value +21 - +52
700	     */
701	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
702		pp->ki_nice - NZERO :
703		(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
704		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
705		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
706	    format_k2(PROCSIZE(pp)),
707	    format_k2(pagetok(pp->ki_rssize)),
708	    status,
709	    smpmode ? pp->ki_lastcpu : 0,
710	    format_time(cputime),
711	    100.0 * weighted_cpu(pct, pp),
712	    100.0 * pct,
713	    screen_width > cmdlengthdelta ?
714	    screen_width - cmdlengthdelta :
715	    0,
716	    printable(pp->ki_comm));
717
718	/* return the result */
719	return (fmt);
720}
721
722static void
723getsysctl(char *name, void *ptr, size_t len)
724{
725	size_t nlen = len;
726
727	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
728		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
729		    strerror(errno));
730		quit(23);
731	}
732	if (nlen != len) {
733		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
734		    (unsigned long)len, (unsigned long)nlen);
735		quit(23);
736	}
737}
738
739/* comparison routines for qsort */
740
741int
742compare_pid(const void *p1, const void *p2)
743{
744	const struct kinfo_proc * const *pp1 = p1;
745	const struct kinfo_proc * const *pp2 = p2;
746
747	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
748		abort();
749
750	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
751}
752
753/*
754 *  proc_compare - comparison function for "qsort"
755 *	Compares the resource consumption of two processes using five
756 *	distinct keys.  The keys (in descending order of importance) are:
757 *	percent cpu, cpu ticks, state, resident set size, total virtual
758 *	memory usage.  The process states are ordered as follows (from least
759 *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
760 *	array declaration below maps a process state index into a number
761 *	that reflects this ordering.
762 */
763
764static int sorted_state[] =
765{
766	0,	/* not used		*/
767	3,	/* sleep		*/
768	1,	/* ABANDONED (WAIT)	*/
769	6,	/* run			*/
770	5,	/* start		*/
771	2,	/* zombie		*/
772	4	/* stop			*/
773};
774
775
776#define ORDERKEY_PCTCPU(a, b) do { \
777	long diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
778	if (diff != 0) \
779		return (diff > 0 ? 1 : -1); \
780} while (0)
781
782#define ORDERKEY_CPTICKS(a, b) do { \
783	int64_t diff = (b)->ki_runtime - (a)->ki_runtime; \
784	if (diff != 0) \
785		return (diff > 0 ? 1 : -1); \
786} while (0)
787
788#define ORDERKEY_STATE(a, b) do { \
789	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
790	if (diff != 0) \
791		return (diff > 0 ? 1 : -1); \
792} while (0)
793
794#define ORDERKEY_PRIO(a, b) do { \
795	int diff = (b)->ki_pri.pri_level - (a)->ki_pri.pri_level; \
796	if (diff != 0) \
797		return (diff > 0 ? 1 : -1); \
798} while (0)
799
800#define ORDERKEY_RSSIZE(a, b) do { \
801	long diff = (b)->ki_rssize - (a)->ki_rssize; \
802	if (diff != 0) \
803		return (diff > 0 ? 1 : -1); \
804} while (0)
805
806#define ORDERKEY_MEM(a, b) do { \
807	long diff = PROCSIZE((b)) - PROCSIZE((a)); \
808	if (diff != 0) \
809		return (diff > 0 ? 1 : -1); \
810} while (0)
811
812/* compare_cpu - the comparison function for sorting by cpu percentage */
813
814int
815#ifdef ORDER
816compare_cpu(void *arg1, void *arg2)
817#else
818proc_compare(void *arg1, void *arg2)
819#endif
820{
821	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
822	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
823
824	ORDERKEY_PCTCPU(p1, p2);
825	ORDERKEY_CPTICKS(p1, p2);
826	ORDERKEY_STATE(p1, p2);
827	ORDERKEY_PRIO(p1, p2);
828	ORDERKEY_RSSIZE(p1, p2);
829	ORDERKEY_MEM(p1, p2);
830
831	return (0);
832}
833
834#ifdef ORDER
835/* compare routines */
836int compare_size(), compare_res(), compare_time(), compare_prio();
837
838int (*proc_compares[])() = {
839	compare_cpu,
840	compare_size,
841	compare_res,
842	compare_time,
843	compare_prio,
844	NULL
845};
846
847/* compare_size - the comparison function for sorting by total memory usage */
848
849int
850compare_size(void *arg1, void *arg2)
851{
852	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
853	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
854
855	ORDERKEY_MEM(p1, p2);
856	ORDERKEY_RSSIZE(p1, p2);
857	ORDERKEY_PCTCPU(p1, p2);
858	ORDERKEY_CPTICKS(p1, p2);
859	ORDERKEY_STATE(p1, p2);
860	ORDERKEY_PRIO(p1, p2);
861
862	return (0);
863}
864
865/* compare_res - the comparison function for sorting by resident set size */
866
867int
868compare_res(void *arg1, void *arg2)
869{
870	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
871	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
872
873	ORDERKEY_RSSIZE(p1, p2);
874	ORDERKEY_MEM(p1, p2);
875	ORDERKEY_PCTCPU(p1, p2);
876	ORDERKEY_CPTICKS(p1, p2);
877	ORDERKEY_STATE(p1, p2);
878	ORDERKEY_PRIO(p1, p2);
879
880	return (0);
881}
882
883/* compare_time - the comparison function for sorting by total cpu time */
884
885int
886compare_time(void *arg1, void *arg2)
887{
888	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
889	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
890
891	ORDERKEY_CPTICKS(p1, p2);
892	ORDERKEY_PCTCPU(p1, p2);
893	ORDERKEY_STATE(p1, p2);
894	ORDERKEY_PRIO(p1, p2);
895	ORDERKEY_RSSIZE(p1, p2);
896	ORDERKEY_MEM(p1, p2);
897
898	return (0);
899}
900
901/* compare_prio - the comparison function for sorting by priority */
902
903int
904compare_prio(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_PRIO(p1, p2);
910	ORDERKEY_CPTICKS(p1, p2);
911	ORDERKEY_PCTCPU(p1, p2);
912	ORDERKEY_STATE(p1, p2);
913	ORDERKEY_RSSIZE(p1, p2);
914	ORDERKEY_MEM(p1, p2);
915
916	return (0);
917}
918#endif
919
920int
921io_compare(void *arg1, void *arg2)
922{
923	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
924	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
925
926	return (get_io_total(p2) - get_io_total(p1));
927}
928/*
929 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
930 *		the process does not exist.
931 *		It is EXTREMLY IMPORTANT that this function work correctly.
932 *		If top runs setuid root (as in SVR4), then this function
933 *		is the only thing that stands in the way of a serious
934 *		security problem.  It validates requests for the "kill"
935 *		and "renice" commands.
936 */
937
938int
939proc_owner(int pid)
940{
941	int cnt;
942	struct kinfo_proc **prefp;
943	struct kinfo_proc *pp;
944
945	prefp = pref;
946	cnt = pref_len;
947	while (--cnt >= 0) {
948		pp = *prefp++;
949		if (pp->ki_pid == (pid_t)pid)
950			return ((int)pp->ki_ruid);
951	}
952	return (-1);
953}
954
955int
956swapmode(int *retavail, int *retfree)
957{
958	int n;
959	int pagesize = getpagesize();
960	struct kvm_swap swapary[1];
961
962	*retavail = 0;
963	*retfree = 0;
964
965#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
966
967	n = kvm_getswapinfo(kd, swapary, 1, 0);
968	if (n < 0 || swapary[0].ksw_total == 0)
969		return (0);
970
971	*retavail = CONVERT(swapary[0].ksw_total);
972	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
973
974	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
975	return (n);
976}
977