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