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