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