machine.c revision 224202
157429Smarkm/*
257429Smarkm * top - a top users display for Unix
357429Smarkm *
457429Smarkm * SYNOPSIS:  For FreeBSD-2.x and later
557429Smarkm *
657429Smarkm * DESCRIPTION:
757429Smarkm * Originally written for BSD4.4 system by Christos Zoulas.
857429Smarkm * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
957429Smarkm * Order support hacked in from top-3.5beta6/machine/m_aix41.c
1057429Smarkm *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
1157429Smarkm *
1257429Smarkm * This is the machine-dependent module for FreeBSD 2.2
1357429Smarkm * Works for:
1457429Smarkm *	FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
1557429Smarkm *
1657429Smarkm * LIBS: -lkvm
1757429Smarkm *
1857429Smarkm * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
1957429Smarkm *          Steven Wallace  <swallace@freebsd.org>
2057429Smarkm *          Wolfram Schneider <wosch@FreeBSD.org>
2157429Smarkm *          Thomas Moestl <tmoestl@gmx.net>
2257429Smarkm *
2357429Smarkm * $FreeBSD: head/usr.bin/top/machine.c 224202 2011-07-18 20:57:43Z bz $
2457429Smarkm */
2557429Smarkm
2657429Smarkm#include <sys/param.h>
2757429Smarkm#include <sys/errno.h>
2857429Smarkm#include <sys/file.h>
2957429Smarkm#include <sys/proc.h>
3057429Smarkm#include <sys/resource.h>
3157429Smarkm#include <sys/rtprio.h>
3257429Smarkm#include <sys/signal.h>
3357429Smarkm#include <sys/sysctl.h>
3457429Smarkm#include <sys/time.h>
3557429Smarkm#include <sys/user.h>
3657429Smarkm#include <sys/vmmeter.h>
3757429Smarkm
3857429Smarkm#include <err.h>
3957429Smarkm#include <kvm.h>
4057429Smarkm#include <math.h>
4157429Smarkm#include <nlist.h>
4257429Smarkm#include <paths.h>
4357429Smarkm#include <pwd.h>
4457429Smarkm#include <stdio.h>
4557429Smarkm#include <stdlib.h>
4657429Smarkm#include <string.h>
4757429Smarkm#include <strings.h>
4857429Smarkm#include <unistd.h>
4957429Smarkm#include <vis.h>
5057429Smarkm
5157429Smarkm#include "top.h"
5257429Smarkm#include "machine.h"
5357429Smarkm#include "screen.h"
5457429Smarkm#include "utils.h"
5557429Smarkm#include "layout.h"
5657429Smarkm
5757429Smarkm#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
5857429Smarkm#define	SMPUNAMELEN	13
5957429Smarkm#define	UPUNAMELEN	15
6057429Smarkm
6157429Smarkmextern struct process_select ps;
6257429Smarkmextern char* printable(char *);
63static int smpmode;
64enum displaymodes displaymode;
65#ifdef TOP_USERNAME_LEN
66static int namelength = TOP_USERNAME_LEN;
67#else
68static int namelength = 8;
69#endif
70static int cmdlengthdelta;
71
72/* Prototypes for top internals */
73void quit(int);
74
75/* get_process_info passes back a handle.  This is what it looks like: */
76
77struct handle {
78	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
79	int remaining;			/* number of pointers remaining */
80};
81
82/* declarations for load_avg */
83#include "loadavg.h"
84
85/* define what weighted cpu is.  */
86#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
87			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
88
89/* what we consider to be process size: */
90#define PROCSIZE(pp) ((pp)->ki_size / 1024)
91
92#define RU(pp)	(&(pp)->ki_rusage)
93#define RUTOT(pp) \
94	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
95
96
97/* definitions for indices in the nlist array */
98
99/*
100 *  These definitions control the format of the per-process area
101 */
102
103static char io_header[] =
104    "  PID%s %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
105
106#define io_Proc_format \
107    "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
108
109static char smp_header_thr[] =
110    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE   C   TIME %6s COMMAND";
111static char smp_header[] =
112    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE   C   TIME %6s COMMAND";
113
114#define smp_Proc_format \
115    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %2d%7s %5.2f%% %.*s"
116
117static char up_header_thr[] =
118    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
119static char up_header[] =
120    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
121
122#define up_Proc_format \
123    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
124
125
126/* process state names for the "STATE" column of the display */
127/* the extra nulls in the string "run" are for adding a slash and
128   the processor number when needed */
129
130char *state_abbrev[] = {
131	"", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
132};
133
134
135static kvm_t *kd;
136
137/* values that we stash away in _init and use in later routines */
138
139static double logcpu;
140
141/* these are retrieved from the kernel in _init */
142
143static load_avg  ccpu;
144
145/* these are used in the get_ functions */
146
147static int lastpid;
148
149/* these are for calculating cpu state percentages */
150
151static long cp_time[CPUSTATES];
152static long cp_old[CPUSTATES];
153static long cp_diff[CPUSTATES];
154
155/* these are for detailing the process states */
156
157int process_states[8];
158char *procstatenames[] = {
159	"", " starting, ", " running, ", " sleeping, ", " stopped, ",
160	" zombie, ", " waiting, ", " lock, ",
161	NULL
162};
163
164/* these are for detailing the cpu states */
165
166int cpu_states[CPUSTATES];
167char *cpustatenames[] = {
168	"user", "nice", "system", "interrupt", "idle", NULL
169};
170
171/* these are for detailing the memory statistics */
172
173int memory_stats[7];
174char *memorynames[] = {
175	"K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ",
176	"K Free", NULL
177};
178
179int swap_stats[7];
180char *swapnames[] = {
181	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
182	NULL
183};
184
185
186/* these are for keeping track of the proc array */
187
188static int nproc;
189static int onproc = -1;
190static int pref_len;
191static struct kinfo_proc *pbase;
192static struct kinfo_proc **pref;
193static struct kinfo_proc *previous_procs;
194static struct kinfo_proc **previous_pref;
195static int previous_proc_count = 0;
196static int previous_proc_count_max = 0;
197
198/* total number of io operations */
199static long total_inblock;
200static long total_oublock;
201static long total_majflt;
202
203/* these are for getting the memory statistics */
204
205static int pageshift;		/* log base 2 of the pagesize */
206
207/* define pagetok in terms of pageshift */
208
209#define pagetok(size) ((size) << pageshift)
210
211/* useful externals */
212long percentages();
213
214#ifdef ORDER
215/*
216 * Sorting orders.  The first element is the default.
217 */
218char *ordernames[] = {
219	"cpu", "size", "res", "time", "pri", "threads",
220	"total", "read", "write", "fault", "vcsw", "ivcsw",
221	"jid", NULL
222};
223#endif
224
225/* Per-cpu time states */
226static int maxcpu;
227static int maxid;
228static int ncpus;
229static u_long cpumask;
230static long *times;
231static long *pcpu_cp_time;
232static long *pcpu_cp_old;
233static long *pcpu_cp_diff;
234static int *pcpu_cpu_states;
235
236static int compare_jid(const void *a, const void *b);
237static int compare_pid(const void *a, const void *b);
238static int compare_tid(const void *a, const void *b);
239static const char *format_nice(const struct kinfo_proc *pp);
240static void getsysctl(const char *name, void *ptr, size_t len);
241static int swapmode(int *retavail, int *retfree);
242
243void
244toggle_pcpustats(struct statics *statics)
245{
246
247	if (ncpus == 1)
248		return;
249
250	/* Adjust display based on ncpus */
251	if (pcpu_stats) {
252		y_mem += ncpus - 1;	/* 3 */
253		y_swap += ncpus - 1;	/* 4 */
254		y_idlecursor += ncpus - 1; /* 5 */
255		y_message += ncpus - 1;	/* 5 */
256		y_header += ncpus - 1;	/* 6 */
257		y_procs += ncpus - 1;	/* 7 */
258		Header_lines += ncpus - 1; /* 7 */
259		statics->ncpus = ncpus;
260	} else {
261		y_mem = 3;
262		y_swap = 4;
263		y_idlecursor = 5;
264		y_message = 5;
265		y_header = 6;
266		y_procs = 7;
267		Header_lines = 7;
268		statics->ncpus = 1;
269	}
270}
271
272int
273machine_init(struct statics *statics, char do_unames)
274{
275	int i, j, empty, pagesize;
276	size_t size;
277	struct passwd *pw;
278
279	size = sizeof(smpmode);
280	if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
281	    NULL, 0) != 0 &&
282	    sysctlbyname("kern.smp.active", &smpmode, &size,
283	    NULL, 0) != 0) ||
284	    size != sizeof(smpmode))
285		smpmode = 0;
286
287	if (do_unames) {
288	    while ((pw = getpwent()) != NULL) {
289		if (strlen(pw->pw_name) > namelength)
290			namelength = strlen(pw->pw_name);
291	    }
292	}
293	if (smpmode && namelength > SMPUNAMELEN)
294		namelength = SMPUNAMELEN;
295	else if (namelength > UPUNAMELEN)
296		namelength = UPUNAMELEN;
297
298	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
299	if (kd == NULL)
300		return (-1);
301
302	GETSYSCTL("kern.ccpu", ccpu);
303
304	/* this is used in calculating WCPU -- calculate it ahead of time */
305	logcpu = log(loaddouble(ccpu));
306
307	pbase = NULL;
308	pref = NULL;
309	nproc = 0;
310	onproc = -1;
311
312	/* get the page size and calculate pageshift from it */
313	pagesize = getpagesize();
314	pageshift = 0;
315	while (pagesize > 1) {
316		pageshift++;
317		pagesize >>= 1;
318	}
319
320	/* we only need the amount of log(2)1024 for our conversion */
321	pageshift -= LOG1024;
322
323	/* fill in the statics information */
324	statics->procstate_names = procstatenames;
325	statics->cpustate_names = cpustatenames;
326	statics->memory_names = memorynames;
327	statics->swap_names = swapnames;
328#ifdef ORDER
329	statics->order_names = ordernames;
330#endif
331
332	/* Allocate state for per-CPU stats. */
333	cpumask = 0;
334	ncpus = 0;
335	GETSYSCTL("kern.smp.maxcpus", maxcpu);
336	size = sizeof(long) * maxcpu * CPUSTATES;
337	times = malloc(size);
338	if (times == NULL)
339		err(1, "malloc %zd bytes", size);
340	if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
341		err(1, "sysctlbyname kern.cp_times");
342	pcpu_cp_time = calloc(1, size);
343	maxid = (size / CPUSTATES / sizeof(long)) - 1;
344	for (i = 0; i <= maxid; i++) {
345		empty = 1;
346		for (j = 0; empty && j < CPUSTATES; j++) {
347			if (times[i * CPUSTATES + j] != 0)
348				empty = 0;
349		}
350		if (!empty) {
351			cpumask |= (1ul << i);
352			ncpus++;
353		}
354	}
355	size = sizeof(long) * ncpus * CPUSTATES;
356	pcpu_cp_old = calloc(1, size);
357	pcpu_cp_diff = calloc(1, size);
358	pcpu_cpu_states = calloc(1, size);
359	statics->ncpus = 1;
360
361	if (pcpu_stats)
362		toggle_pcpustats(statics);
363
364	/* all done! */
365	return (0);
366}
367
368char *
369format_header(char *uname_field)
370{
371	static char Header[128];
372	const char *prehead;
373
374	switch (displaymode) {
375	case DISP_CPU:
376		/*
377		 * The logic of picking the right header format seems reverse
378		 * here because we only want to display a THR column when
379		 * "thread mode" is off (and threads are not listed as
380		 * separate lines).
381		 */
382		prehead = smpmode ?
383		    (ps.thread ? smp_header : smp_header_thr) :
384		    (ps.thread ? up_header : up_header_thr);
385		snprintf(Header, sizeof(Header), prehead,
386		    ps.jail ? " JID" : "",
387		    namelength, namelength, uname_field,
388		    ps.wcpu ? "WCPU" : "CPU");
389		break;
390	case DISP_IO:
391		prehead = io_header;
392		snprintf(Header, sizeof(Header), prehead,
393		    ps.jail ? " JID" : "",
394		    namelength, namelength, uname_field);
395		break;
396	}
397	cmdlengthdelta = strlen(Header) - 7;
398	return (Header);
399}
400
401static int swappgsin = -1;
402static int swappgsout = -1;
403extern struct timeval timeout;
404
405
406void
407get_system_info(struct system_info *si)
408{
409	long total;
410	struct loadavg sysload;
411	int mib[2];
412	struct timeval boottime;
413	size_t bt_size;
414	int i, j;
415	size_t size;
416
417	/* get the CPU stats */
418	size = (maxid + 1) * CPUSTATES * sizeof(long);
419	if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
420		err(1, "sysctlbyname kern.cp_times");
421	GETSYSCTL("kern.cp_time", cp_time);
422	GETSYSCTL("vm.loadavg", sysload);
423	GETSYSCTL("kern.lastpid", lastpid);
424
425	/* convert load averages to doubles */
426	for (i = 0; i < 3; i++)
427		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
428
429	/* convert cp_time counts to percentages */
430	for (i = j = 0; i <= maxid; i++) {
431		if ((cpumask & (1ul << i)) == 0)
432			continue;
433		percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
434		    &pcpu_cp_time[j * CPUSTATES],
435		    &pcpu_cp_old[j * CPUSTATES],
436		    &pcpu_cp_diff[j * CPUSTATES]);
437		j++;
438	}
439	percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
440
441	/* sum memory & swap statistics */
442	{
443		static unsigned int swap_delay = 0;
444		static int swapavail = 0;
445		static int swapfree = 0;
446		static long bufspace = 0;
447		static int nspgsin, nspgsout;
448
449		GETSYSCTL("vfs.bufspace", bufspace);
450		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
451		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
452		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
453		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
454		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
455		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
456		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
457		/* convert memory stats to Kbytes */
458		memory_stats[0] = pagetok(memory_stats[0]);
459		memory_stats[1] = pagetok(memory_stats[1]);
460		memory_stats[2] = pagetok(memory_stats[2]);
461		memory_stats[3] = pagetok(memory_stats[3]);
462		memory_stats[4] = bufspace / 1024;
463		memory_stats[5] = pagetok(memory_stats[5]);
464		memory_stats[6] = -1;
465
466		/* first interval */
467		if (swappgsin < 0) {
468			swap_stats[4] = 0;
469			swap_stats[5] = 0;
470		}
471
472		/* compute differences between old and new swap statistic */
473		else {
474			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
475			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
476		}
477
478		swappgsin = nspgsin;
479		swappgsout = nspgsout;
480
481		/* call CPU heavy swapmode() only for changes */
482		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
483			swap_stats[3] = swapmode(&swapavail, &swapfree);
484			swap_stats[0] = swapavail;
485			swap_stats[1] = swapavail - swapfree;
486			swap_stats[2] = swapfree;
487		}
488		swap_delay = 1;
489		swap_stats[6] = -1;
490	}
491
492	/* set arrays and strings */
493	if (pcpu_stats) {
494		si->cpustates = pcpu_cpu_states;
495		si->ncpus = ncpus;
496	} else {
497		si->cpustates = cpu_states;
498		si->ncpus = 1;
499	}
500	si->memory = memory_stats;
501	si->swap = swap_stats;
502
503
504	if (lastpid > 0) {
505		si->last_pid = lastpid;
506	} else {
507		si->last_pid = -1;
508	}
509
510	/*
511	 * Print how long system has been up.
512	 * (Found by looking getting "boottime" from the kernel)
513	 */
514	mib[0] = CTL_KERN;
515	mib[1] = KERN_BOOTTIME;
516	bt_size = sizeof(boottime);
517	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
518	    boottime.tv_sec != 0) {
519		si->boottime = boottime;
520	} else {
521		si->boottime.tv_sec = -1;
522	}
523}
524
525#define NOPROC	((void *)-1)
526
527/*
528 * We need to compare data from the old process entry with the new
529 * process entry.
530 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
531 * structure to cache the mapping.  We also use a negative cache pointer
532 * of NOPROC to avoid duplicate lookups.
533 * XXX: this could be done when the actual processes are fetched, we do
534 * it here out of laziness.
535 */
536const struct kinfo_proc *
537get_old_proc(struct kinfo_proc *pp)
538{
539	struct kinfo_proc **oldpp, *oldp;
540
541	/*
542	 * If this is the first fetch of the kinfo_procs then we don't have
543	 * any previous entries.
544	 */
545	if (previous_proc_count == 0)
546		return (NULL);
547	/* negative cache? */
548	if (pp->ki_udata == NOPROC)
549		return (NULL);
550	/* cached? */
551	if (pp->ki_udata != NULL)
552		return (pp->ki_udata);
553	/*
554	 * Not cached,
555	 * 1) look up based on pid.
556	 * 2) compare process start.
557	 * If we fail here, then setup a negative cache entry, otherwise
558	 * cache it.
559	 */
560	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
561	    sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
562	if (oldpp == NULL) {
563		pp->ki_udata = NOPROC;
564		return (NULL);
565	}
566	oldp = *oldpp;
567	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
568		pp->ki_udata = NOPROC;
569		return (NULL);
570	}
571	pp->ki_udata = oldp;
572	return (oldp);
573}
574
575/*
576 * Return the total amount of IO done in blocks in/out and faults.
577 * store the values individually in the pointers passed in.
578 */
579long
580get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
581    long *vcsw, long *ivcsw)
582{
583	const struct kinfo_proc *oldp;
584	static struct kinfo_proc dummy;
585	long ret;
586
587	oldp = get_old_proc(pp);
588	if (oldp == NULL) {
589		bzero(&dummy, sizeof(dummy));
590		oldp = &dummy;
591	}
592	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
593	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
594	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
595	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
596	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
597	ret =
598	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
599	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
600	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
601	return (ret);
602}
603
604/*
605 * Return the total number of block in/out and faults by a process.
606 */
607long
608get_io_total(struct kinfo_proc *pp)
609{
610	long dummy;
611
612	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
613}
614
615static struct handle handle;
616
617caddr_t
618get_process_info(struct system_info *si, struct process_select *sel,
619    int (*compare)(const void *, const void *))
620{
621	int i;
622	int total_procs;
623	long p_io;
624	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
625	int active_procs;
626	struct kinfo_proc **prefp;
627	struct kinfo_proc *pp;
628
629	/* these are copied out of sel for speed */
630	int show_idle;
631	int show_self;
632	int show_system;
633	int show_uid;
634	int show_command;
635	int show_kidle;
636
637	/*
638	 * Save the previous process info.
639	 */
640	if (previous_proc_count_max < nproc) {
641		free(previous_procs);
642		previous_procs = malloc(nproc * sizeof(*previous_procs));
643		free(previous_pref);
644		previous_pref = malloc(nproc * sizeof(*previous_pref));
645		if (previous_procs == NULL || previous_pref == NULL) {
646			(void) fprintf(stderr, "top: Out of memory.\n");
647			quit(23);
648		}
649		previous_proc_count_max = nproc;
650	}
651	if (nproc) {
652		for (i = 0; i < nproc; i++)
653			previous_pref[i] = &previous_procs[i];
654		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
655		qsort(previous_pref, nproc, sizeof(*previous_pref),
656		    ps.thread ? compare_tid : compare_pid);
657	}
658	previous_proc_count = nproc;
659
660	pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
661	    0, &nproc);
662	if (nproc > onproc)
663		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
664	if (pref == NULL || pbase == NULL) {
665		(void) fprintf(stderr, "top: Out of memory.\n");
666		quit(23);
667	}
668	/* get a pointer to the states summary array */
669	si->procstates = process_states;
670
671	/* set up flags which define what we are going to select */
672	show_idle = sel->idle;
673	show_self = sel->self == -1;
674	show_system = sel->system;
675	show_uid = sel->uid != -1;
676	show_command = sel->command != NULL;
677	show_kidle = sel->kidle;
678
679	/* count up process states and get pointers to interesting procs */
680	total_procs = 0;
681	active_procs = 0;
682	total_inblock = 0;
683	total_oublock = 0;
684	total_majflt = 0;
685	memset((char *)process_states, 0, sizeof(process_states));
686	prefp = pref;
687	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
688
689		if (pp->ki_stat == 0)
690			/* not in use */
691			continue;
692
693		if (!show_self && pp->ki_pid == sel->self)
694			/* skip self */
695			continue;
696
697		if (!show_system && (pp->ki_flag & P_SYSTEM))
698			/* skip system process */
699			continue;
700
701		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
702		    &p_vcsw, &p_ivcsw);
703		total_inblock += p_inblock;
704		total_oublock += p_oublock;
705		total_majflt += p_majflt;
706		total_procs++;
707		process_states[pp->ki_stat]++;
708
709		if (pp->ki_stat == SZOMB)
710			/* skip zombies */
711			continue;
712
713		if (!show_kidle && pp->ki_tdflags & TDF_IDLETD)
714			/* skip kernel idle process */
715			continue;
716
717		if (displaymode == DISP_CPU && !show_idle &&
718		    (pp->ki_pctcpu == 0 ||
719		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
720			/* skip idle or non-running processes */
721			continue;
722
723		if (displaymode == DISP_IO && !show_idle && p_io == 0)
724			/* skip processes that aren't doing I/O */
725			continue;
726
727		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
728			/* skip proc. that don't belong to the selected UID */
729			continue;
730
731		*prefp++ = pp;
732		active_procs++;
733	}
734
735	/* if requested, sort the "interesting" processes */
736	if (compare != NULL)
737		qsort(pref, active_procs, sizeof(*pref), compare);
738
739	/* remember active and total counts */
740	si->p_total = total_procs;
741	si->p_active = pref_len = active_procs;
742
743	/* pass back a handle */
744	handle.next_proc = pref;
745	handle.remaining = active_procs;
746	return ((caddr_t)&handle);
747}
748
749static char fmt[128];	/* static area where result is built */
750
751char *
752format_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
753{
754	struct kinfo_proc *pp;
755	const struct kinfo_proc *oldp;
756	long cputime;
757	double pct;
758	struct handle *hp;
759	char status[16];
760	int state;
761	struct rusage ru, *rup;
762	long p_tot, s_tot;
763	char *proc_fmt, thr_buf[6], jid_buf[6];
764	char *cmdbuf = NULL;
765	char **args;
766
767	/* find and remember the next proc structure */
768	hp = (struct handle *)handle;
769	pp = *(hp->next_proc++);
770	hp->remaining--;
771
772	/* get the process's command name */
773	if ((pp->ki_flag & P_INMEM) == 0) {
774		/*
775		 * Print swapped processes as <pname>
776		 */
777		size_t len;
778
779		len = strlen(pp->ki_comm);
780		if (len > sizeof(pp->ki_comm) - 3)
781			len = sizeof(pp->ki_comm) - 3;
782		memmove(pp->ki_comm + 1, pp->ki_comm, len);
783		pp->ki_comm[0] = '<';
784		pp->ki_comm[len + 1] = '>';
785		pp->ki_comm[len + 2] = '\0';
786	}
787
788	/*
789	 * Convert the process's runtime from microseconds to seconds.  This
790	 * time includes the interrupt time although that is not wanted here.
791	 * ps(1) is similarly sloppy.
792	 */
793	cputime = (pp->ki_runtime + 500000) / 1000000;
794
795	/* calculate the base for cpu percentages */
796	pct = pctdouble(pp->ki_pctcpu);
797
798	/* generate "STATE" field */
799	switch (state = pp->ki_stat) {
800	case SRUN:
801		if (smpmode && pp->ki_oncpu != 0xff)
802			sprintf(status, "CPU%d", pp->ki_oncpu);
803		else
804			strcpy(status, "RUN");
805		break;
806	case SLOCK:
807		if (pp->ki_kiflag & KI_LOCKBLOCK) {
808			sprintf(status, "*%.6s", pp->ki_lockname);
809			break;
810		}
811		/* fall through */
812	case SSLEEP:
813		if (pp->ki_wmesg != NULL) {
814			sprintf(status, "%.6s", pp->ki_wmesg);
815			break;
816		}
817		/* FALLTHROUGH */
818	default:
819
820		if (state >= 0 &&
821		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
822			sprintf(status, "%.6s", state_abbrev[state]);
823		else
824			sprintf(status, "?%5d", state);
825		break;
826	}
827
828	cmdbuf = (char *)malloc(cmdlengthdelta + 1);
829	if (cmdbuf == NULL) {
830		warn("malloc(%d)", cmdlengthdelta + 1);
831		return NULL;
832	}
833
834	if (!(flags & FMT_SHOWARGS)) {
835		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
836		    pp->ki_tdname[0]) {
837			snprintf(cmdbuf, cmdlengthdelta, "%s{%s}", pp->ki_comm,
838			    pp->ki_tdname);
839		} else {
840			snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
841		}
842	} else {
843		if (pp->ki_flag & P_SYSTEM ||
844		    pp->ki_args == NULL ||
845		    (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
846		    !(*args)) {
847			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
848		    	    pp->ki_tdname[0]) {
849				snprintf(cmdbuf, cmdlengthdelta,
850				    "[%s{%s}]", pp->ki_comm, pp->ki_tdname);
851			} else {
852				snprintf(cmdbuf, cmdlengthdelta,
853				    "[%s]", pp->ki_comm);
854			}
855		} else {
856			char *src, *dst, *argbuf;
857			char *cmd;
858			size_t argbuflen;
859			size_t len;
860
861			argbuflen = cmdlengthdelta * 4;
862			argbuf = (char *)malloc(argbuflen + 1);
863			if (argbuf == NULL) {
864				warn("malloc(%d)", argbuflen + 1);
865				free(cmdbuf);
866				return NULL;
867			}
868
869			dst = argbuf;
870
871			/* Extract cmd name from argv */
872			cmd = strrchr(*args, '/');
873			if (cmd == NULL)
874				cmd = *args;
875			else
876				cmd++;
877
878			for (; (src = *args++) != NULL; ) {
879				if (*src == '\0')
880					continue;
881				len = (argbuflen - (dst - argbuf) - 1) / 4;
882				strvisx(dst, src,
883				    strlen(src) < len ? strlen(src) : len,
884				    VIS_NL | VIS_CSTYLE);
885				while (*dst != '\0')
886					dst++;
887				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
888					*dst++ = ' '; /* add delimiting space */
889			}
890			if (dst != argbuf && dst[-1] == ' ')
891				dst--;
892			*dst = '\0';
893
894			if (strcmp(cmd, pp->ki_comm) != 0 ) {
895				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
896				    pp->ki_tdname[0])
897					snprintf(cmdbuf, cmdlengthdelta,
898					    "%s (%s){%s}", argbuf, pp->ki_comm,
899					    pp->ki_tdname);
900				else
901					snprintf(cmdbuf, cmdlengthdelta,
902					    "%s (%s)", argbuf, pp->ki_comm);
903			} else {
904				if (ps.thread && pp->ki_flag & P_HADTHREADS &&
905				    pp->ki_tdname[0])
906					snprintf(cmdbuf, cmdlengthdelta,
907					    "%s{%s}", argbuf, pp->ki_tdname);
908				else
909					strlcpy(cmdbuf, argbuf, cmdlengthdelta);
910			}
911			free(argbuf);
912		}
913	}
914
915	if (ps.jail == 0)
916		jid_buf[0] = '\0';
917	else
918		snprintf(jid_buf, sizeof(jid_buf), " %*d",
919		    sizeof(jid_buf) - 3, pp->ki_jid);
920
921	if (displaymode == DISP_IO) {
922		oldp = get_old_proc(pp);
923		if (oldp != NULL) {
924			ru.ru_inblock = RU(pp)->ru_inblock -
925			    RU(oldp)->ru_inblock;
926			ru.ru_oublock = RU(pp)->ru_oublock -
927			    RU(oldp)->ru_oublock;
928			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
929			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
930			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
931			rup = &ru;
932		} else {
933			rup = RU(pp);
934		}
935		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
936		s_tot = total_inblock + total_oublock + total_majflt;
937
938		sprintf(fmt, io_Proc_format,
939		    pp->ki_pid,
940		    jid_buf,
941		    namelength, namelength, (*get_userid)(pp->ki_ruid),
942		    rup->ru_nvcsw,
943		    rup->ru_nivcsw,
944		    rup->ru_inblock,
945		    rup->ru_oublock,
946		    rup->ru_majflt,
947		    p_tot,
948		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
949		    screen_width > cmdlengthdelta ?
950		    screen_width - cmdlengthdelta : 0,
951		    printable(cmdbuf));
952
953		free(cmdbuf);
954
955		return (fmt);
956	}
957
958	/* format this entry */
959	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
960	if (ps.thread != 0)
961		thr_buf[0] = '\0';
962	else
963		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
964		    sizeof(thr_buf) - 2, pp->ki_numthreads);
965
966	sprintf(fmt, proc_fmt,
967	    pp->ki_pid,
968	    jid_buf,
969	    namelength, namelength, (*get_userid)(pp->ki_ruid),
970	    thr_buf,
971	    pp->ki_pri.pri_level - PZERO,
972	    format_nice(pp),
973	    format_k2(PROCSIZE(pp)),
974	    format_k2(pagetok(pp->ki_rssize)),
975	    status,
976	    smpmode ? pp->ki_lastcpu : 0,
977	    format_time(cputime),
978	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
979	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
980	    printable(cmdbuf));
981
982	free(cmdbuf);
983
984	/* return the result */
985	return (fmt);
986}
987
988static void
989getsysctl(const char *name, void *ptr, size_t len)
990{
991	size_t nlen = len;
992
993	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
994		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
995		    strerror(errno));
996		quit(23);
997	}
998	if (nlen != len) {
999		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1000		    name, (unsigned long)len, (unsigned long)nlen);
1001		quit(23);
1002	}
1003}
1004
1005static const char *
1006format_nice(const struct kinfo_proc *pp)
1007{
1008	const char *fifo, *kthread;
1009	int rtpri;
1010	static char nicebuf[4 + 1];
1011
1012	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1013	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
1014	switch (PRI_BASE(pp->ki_pri.pri_class)) {
1015	case PRI_ITHD:
1016		return ("-");
1017	case PRI_REALTIME:
1018		/*
1019		 * XXX: the kernel doesn't tell us the original rtprio and
1020		 * doesn't really know what it was, so to recover it we
1021		 * must be more chummy with the implementation than the
1022		 * implementation is with itself.  pri_user gives a
1023		 * constant "base" priority, but is only initialized
1024		 * properly for user threads.  pri_native gives what the
1025		 * kernel calls the "base" priority, but it isn't constant
1026		 * since it is changed by priority propagation.  pri_native
1027		 * also isn't properly initialized for all threads, but it
1028		 * is properly initialized for kernel realtime and idletime
1029		 * threads.  Thus we use pri_user for the base priority of
1030		 * user threads (it is always correct) and pri_native for
1031		 * the base priority of kernel realtime and idletime threads
1032		 * (there is nothing better, and it is usually correct).
1033		 *
1034		 * The field width and thus the buffer are too small for
1035		 * values like "kr31F", but such values shouldn't occur,
1036		 * and if they do then the tailing "F" is not displayed.
1037		 */
1038		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1039		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1040		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1041		    kthread, rtpri, fifo);
1042		break;
1043	case PRI_TIMESHARE:
1044		if (pp->ki_flag & P_KTHREAD)
1045			return ("-");
1046		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1047		break;
1048	case PRI_IDLE:
1049		/* XXX: as above. */
1050		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
1051		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1052		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1053		    kthread, rtpri, fifo);
1054		break;
1055	default:
1056		return ("?");
1057	}
1058	return (nicebuf);
1059}
1060
1061/* comparison routines for qsort */
1062
1063static int
1064compare_pid(const void *p1, const void *p2)
1065{
1066	const struct kinfo_proc * const *pp1 = p1;
1067	const struct kinfo_proc * const *pp2 = p2;
1068
1069	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1070		abort();
1071
1072	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1073}
1074
1075static int
1076compare_tid(const void *p1, const void *p2)
1077{
1078	const struct kinfo_proc * const *pp1 = p1;
1079	const struct kinfo_proc * const *pp2 = p2;
1080
1081	if ((*pp2)->ki_tid < 0 || (*pp1)->ki_tid < 0)
1082		abort();
1083
1084	return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1085}
1086
1087/*
1088 *  proc_compare - comparison function for "qsort"
1089 *	Compares the resource consumption of two processes using five
1090 *	distinct keys.  The keys (in descending order of importance) are:
1091 *	percent cpu, cpu ticks, state, resident set size, total virtual
1092 *	memory usage.  The process states are ordered as follows (from least
1093 *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
1094 *	array declaration below maps a process state index into a number
1095 *	that reflects this ordering.
1096 */
1097
1098static int sorted_state[] = {
1099	0,	/* not used		*/
1100	3,	/* sleep		*/
1101	1,	/* ABANDONED (WAIT)	*/
1102	6,	/* run			*/
1103	5,	/* start		*/
1104	2,	/* zombie		*/
1105	4	/* stop			*/
1106};
1107
1108
1109#define ORDERKEY_PCTCPU(a, b) do { \
1110	long diff; \
1111	if (ps.wcpu) \
1112		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1113		    (b))) - \
1114		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1115		    (a))); \
1116	else \
1117		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1118	if (diff != 0) \
1119		return (diff > 0 ? 1 : -1); \
1120} while (0)
1121
1122#define ORDERKEY_CPTICKS(a, b) do { \
1123	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1124	if (diff != 0) \
1125		return (diff > 0 ? 1 : -1); \
1126} while (0)
1127
1128#define ORDERKEY_STATE(a, b) do { \
1129	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1130	if (diff != 0) \
1131		return (diff > 0 ? 1 : -1); \
1132} while (0)
1133
1134#define ORDERKEY_PRIO(a, b) do { \
1135	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1136	if (diff != 0) \
1137		return (diff > 0 ? 1 : -1); \
1138} while (0)
1139
1140#define	ORDERKEY_THREADS(a, b) do { \
1141	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1142	if (diff != 0) \
1143		return (diff > 0 ? 1 : -1); \
1144} while (0)
1145
1146#define ORDERKEY_RSSIZE(a, b) do { \
1147	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1148	if (diff != 0) \
1149		return (diff > 0 ? 1 : -1); \
1150} while (0)
1151
1152#define ORDERKEY_MEM(a, b) do { \
1153	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1154	if (diff != 0) \
1155		return (diff > 0 ? 1 : -1); \
1156} while (0)
1157
1158#define ORDERKEY_JID(a, b) do { \
1159	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1160	if (diff != 0) \
1161		return (diff > 0 ? 1 : -1); \
1162} while (0)
1163
1164/* compare_cpu - the comparison function for sorting by cpu percentage */
1165
1166int
1167#ifdef ORDER
1168compare_cpu(void *arg1, void *arg2)
1169#else
1170proc_compare(void *arg1, void *arg2)
1171#endif
1172{
1173	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1174	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1175
1176	ORDERKEY_PCTCPU(p1, p2);
1177	ORDERKEY_CPTICKS(p1, p2);
1178	ORDERKEY_STATE(p1, p2);
1179	ORDERKEY_PRIO(p1, p2);
1180	ORDERKEY_RSSIZE(p1, p2);
1181	ORDERKEY_MEM(p1, p2);
1182
1183	return (0);
1184}
1185
1186#ifdef ORDER
1187/* "cpu" compare routines */
1188int compare_size(), compare_res(), compare_time(), compare_prio(),
1189    compare_threads();
1190
1191/*
1192 * "io" compare routines.  Context switches aren't i/o, but are displayed
1193 * on the "io" display.
1194 */
1195int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1196    compare_vcsw(), compare_ivcsw();
1197
1198int (*compares[])() = {
1199	compare_cpu,
1200	compare_size,
1201	compare_res,
1202	compare_time,
1203	compare_prio,
1204	compare_threads,
1205	compare_iototal,
1206	compare_ioread,
1207	compare_iowrite,
1208	compare_iofault,
1209	compare_vcsw,
1210	compare_ivcsw,
1211	compare_jid,
1212	NULL
1213};
1214
1215/* compare_size - the comparison function for sorting by total memory usage */
1216
1217int
1218compare_size(void *arg1, void *arg2)
1219{
1220	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1221	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1222
1223	ORDERKEY_MEM(p1, p2);
1224	ORDERKEY_RSSIZE(p1, p2);
1225	ORDERKEY_PCTCPU(p1, p2);
1226	ORDERKEY_CPTICKS(p1, p2);
1227	ORDERKEY_STATE(p1, p2);
1228	ORDERKEY_PRIO(p1, p2);
1229
1230	return (0);
1231}
1232
1233/* compare_res - the comparison function for sorting by resident set size */
1234
1235int
1236compare_res(void *arg1, void *arg2)
1237{
1238	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1239	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1240
1241	ORDERKEY_RSSIZE(p1, p2);
1242	ORDERKEY_MEM(p1, p2);
1243	ORDERKEY_PCTCPU(p1, p2);
1244	ORDERKEY_CPTICKS(p1, p2);
1245	ORDERKEY_STATE(p1, p2);
1246	ORDERKEY_PRIO(p1, p2);
1247
1248	return (0);
1249}
1250
1251/* compare_time - the comparison function for sorting by total cpu time */
1252
1253int
1254compare_time(void *arg1, void *arg2)
1255{
1256	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1257	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1258
1259	ORDERKEY_CPTICKS(p1, p2);
1260	ORDERKEY_PCTCPU(p1, p2);
1261	ORDERKEY_STATE(p1, p2);
1262	ORDERKEY_PRIO(p1, p2);
1263	ORDERKEY_RSSIZE(p1, p2);
1264	ORDERKEY_MEM(p1, p2);
1265
1266	return (0);
1267}
1268
1269/* compare_prio - the comparison function for sorting by priority */
1270
1271int
1272compare_prio(void *arg1, void *arg2)
1273{
1274	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1275	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1276
1277	ORDERKEY_PRIO(p1, p2);
1278	ORDERKEY_CPTICKS(p1, p2);
1279	ORDERKEY_PCTCPU(p1, p2);
1280	ORDERKEY_STATE(p1, p2);
1281	ORDERKEY_RSSIZE(p1, p2);
1282	ORDERKEY_MEM(p1, p2);
1283
1284	return (0);
1285}
1286
1287/* compare_threads - the comparison function for sorting by threads */
1288int
1289compare_threads(void *arg1, void *arg2)
1290{
1291	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1292	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1293
1294	ORDERKEY_THREADS(p1, p2);
1295	ORDERKEY_PCTCPU(p1, p2);
1296	ORDERKEY_CPTICKS(p1, p2);
1297	ORDERKEY_STATE(p1, p2);
1298	ORDERKEY_PRIO(p1, p2);
1299	ORDERKEY_RSSIZE(p1, p2);
1300	ORDERKEY_MEM(p1, p2);
1301
1302	return (0);
1303}
1304
1305/* compare_jid - the comparison function for sorting by jid */
1306static int
1307compare_jid(const void *arg1, const void *arg2)
1308{
1309	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1310	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1311
1312	ORDERKEY_JID(p1, p2);
1313	ORDERKEY_PCTCPU(p1, p2);
1314	ORDERKEY_CPTICKS(p1, p2);
1315	ORDERKEY_STATE(p1, p2);
1316	ORDERKEY_PRIO(p1, p2);
1317	ORDERKEY_RSSIZE(p1, p2);
1318	ORDERKEY_MEM(p1, p2);
1319
1320	return (0);
1321}
1322#endif /* ORDER */
1323
1324/* assorted comparison functions for sorting by i/o */
1325
1326int
1327#ifdef ORDER
1328compare_iototal(void *arg1, void *arg2)
1329#else
1330io_compare(void *arg1, void *arg2)
1331#endif
1332{
1333	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1334	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1335
1336	return (get_io_total(p2) - get_io_total(p1));
1337}
1338
1339#ifdef ORDER
1340int
1341compare_ioread(void *arg1, void *arg2)
1342{
1343	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1344	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1345	long dummy, inp1, inp2;
1346
1347	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1348	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1349
1350	return (inp2 - inp1);
1351}
1352
1353int
1354compare_iowrite(void *arg1, void *arg2)
1355{
1356	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1357	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1358	long dummy, oup1, oup2;
1359
1360	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1361	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1362
1363	return (oup2 - oup1);
1364}
1365
1366int
1367compare_iofault(void *arg1, void *arg2)
1368{
1369	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1370	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1371	long dummy, flp1, flp2;
1372
1373	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1374	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1375
1376	return (flp2 - flp1);
1377}
1378
1379int
1380compare_vcsw(void *arg1, void *arg2)
1381{
1382	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1383	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1384	long dummy, flp1, flp2;
1385
1386	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1387	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1388
1389	return (flp2 - flp1);
1390}
1391
1392int
1393compare_ivcsw(void *arg1, void *arg2)
1394{
1395	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1396	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1397	long dummy, flp1, flp2;
1398
1399	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1400	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1401
1402	return (flp2 - flp1);
1403}
1404#endif /* ORDER */
1405
1406/*
1407 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1408 *		the process does not exist.
1409 *		It is EXTREMLY IMPORTANT that this function work correctly.
1410 *		If top runs setuid root (as in SVR4), then this function
1411 *		is the only thing that stands in the way of a serious
1412 *		security problem.  It validates requests for the "kill"
1413 *		and "renice" commands.
1414 */
1415
1416int
1417proc_owner(int pid)
1418{
1419	int cnt;
1420	struct kinfo_proc **prefp;
1421	struct kinfo_proc *pp;
1422
1423	prefp = pref;
1424	cnt = pref_len;
1425	while (--cnt >= 0) {
1426		pp = *prefp++;
1427		if (pp->ki_pid == (pid_t)pid)
1428			return ((int)pp->ki_ruid);
1429	}
1430	return (-1);
1431}
1432
1433static int
1434swapmode(int *retavail, int *retfree)
1435{
1436	int n;
1437	int pagesize = getpagesize();
1438	struct kvm_swap swapary[1];
1439
1440	*retavail = 0;
1441	*retfree = 0;
1442
1443#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1444
1445	n = kvm_getswapinfo(kd, swapary, 1, 0);
1446	if (n < 0 || swapary[0].ksw_total == 0)
1447		return (0);
1448
1449	*retavail = CONVERT(swapary[0].ksw_total);
1450	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1451
1452	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1453	return (n);
1454}
1455