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