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