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