machine.c revision 1.83
1/* $OpenBSD: machine.c,v 1.83 2015/01/19 18:01:13 millert Exp $	 */
2
3/*-
4 * Copyright (c) 1994 Thorsten Lockert <tholo@sigmasoft.com>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 *    derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
19 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
20 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
21 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
24 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
27 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 *
29 * AUTHOR:  Thorsten Lockert <tholo@sigmasoft.com>
30 *          Adapted from BSD4.4 by Christos Zoulas <christos@ee.cornell.edu>
31 *          Patch for process wait display by Jarl F. Greipsland <jarle@idt.unit.no>
32 *	    Patch for -DORDER by Kenneth Stailey <kstailey@disclosure.com>
33 *	    Patch for new swapctl(2) by Tobias Weingartner <weingart@openbsd.org>
34 */
35
36#include <sys/param.h>	/* DEV_BSIZE MAXCOMLEN PZERO */
37#include <sys/types.h>
38#include <sys/signal.h>
39#include <sys/mount.h>
40#include <sys/proc.h>
41#include <sys/sched.h>
42#include <sys/swap.h>
43#include <sys/sysctl.h>
44
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <unistd.h>
49#include <err.h>
50#include <errno.h>
51
52#include "top.h"
53#include "display.h"
54#include "machine.h"
55#include "utils.h"
56
57static int	swapmode(int *, int *);
58static char	*state_abbr(struct kinfo_proc *);
59static char	*format_comm(struct kinfo_proc *);
60
61/* get_process_info passes back a handle.  This is what it looks like: */
62
63struct handle {
64	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
65	int		remaining;	/* number of pointers remaining */
66};
67
68/* what we consider to be process size: */
69#define PROCSIZE(pp) ((pp)->p_vm_tsize + (pp)->p_vm_dsize + (pp)->p_vm_ssize)
70
71/*
72 *  These definitions control the format of the per-process area
73 */
74static char header[] =
75	"  PID X        PRI NICE  SIZE   RES STATE     WAIT      TIME    CPU COMMAND";
76
77/* 0123456   -- field to fill in starts at header+6 */
78#define UNAME_START 6
79
80#define Proc_format \
81	"%5d %-8.8s %3d %4d %5s %5s %-9s %-7.7s %6s %5.2f%% %s"
82
83/* process state names for the "STATE" column of the display */
84/*
85 * the extra nulls in the string "run" are for adding a slash and the
86 * processor number when needed
87 */
88
89char	*state_abbrev[] = {
90	"", "start", "run", "sleep", "stop", "zomb", "dead", "onproc"
91};
92
93/* these are for calculating cpu state percentages */
94static int64_t     **cp_time;
95static int64_t     **cp_old;
96static int64_t     **cp_diff;
97
98/* these are for detailing the process states */
99int process_states[8];
100char *procstatenames[] = {
101	"", " starting, ", " running, ", " idle, ",
102	" stopped, ", " zombie, ", " dead, ", " on processor, ",
103	NULL
104};
105
106/* these are for detailing the cpu states */
107int64_t *cpu_states;
108char *cpustatenames[] = {
109	"user", "nice", "system", "interrupt", "idle", NULL
110};
111
112/* these are for detailing the memory statistics */
113int memory_stats[10];
114char *memorynames[] = {
115	"Real: ", "K/", "K act/tot ", "Free: ", "K ",
116	"Cache: ", "K ",
117	"Swap: ", "K/", "K",
118	NULL
119};
120
121/* these are names given to allowed sorting orders -- first is default */
122char	*ordernames[] = {
123	"cpu", "size", "res", "time", "pri", "pid", "command", NULL
124};
125
126/* these are for keeping track of the proc array */
127static int      nproc;
128static int      onproc = -1;
129static int      pref_len;
130static struct kinfo_proc *pbase;
131static struct kinfo_proc **pref;
132
133/* these are for getting the memory statistics */
134static int      pageshift;	/* log base 2 of the pagesize */
135
136/* define pagetok in terms of pageshift */
137#define pagetok(size) ((size) << pageshift)
138
139int		ncpu;
140int		fscale;
141
142unsigned int	maxslp;
143
144int
145getfscale(void)
146{
147	int mib[] = { CTL_KERN, KERN_FSCALE };
148	size_t size = sizeof(fscale);
149
150	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
151	    &fscale, &size, NULL, 0) < 0)
152		return (-1);
153	return fscale;
154}
155
156int
157getncpu(void)
158{
159	int mib[] = { CTL_HW, HW_NCPU };
160	int ncpu;
161	size_t size = sizeof(ncpu);
162
163	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
164	    &ncpu, &size, NULL, 0) == -1)
165		return (-1);
166
167	return (ncpu);
168}
169
170int
171machine_init(struct statics *statics)
172{
173	int pagesize, cpu;
174
175	ncpu = getncpu();
176	if (ncpu == -1)
177		return (-1);
178	if (getfscale() == -1)
179		return (-1);
180	cpu_states = calloc(ncpu, CPUSTATES * sizeof(int64_t));
181	if (cpu_states == NULL)
182		err(1, NULL);
183	cp_time = calloc(ncpu, sizeof(int64_t *));
184	cp_old  = calloc(ncpu, sizeof(int64_t *));
185	cp_diff = calloc(ncpu, sizeof(int64_t *));
186	if (cp_time == NULL || cp_old == NULL || cp_diff == NULL)
187		err(1, NULL);
188	for (cpu = 0; cpu < ncpu; cpu++) {
189		cp_time[cpu] = calloc(CPUSTATES, sizeof(int64_t));
190		cp_old[cpu] = calloc(CPUSTATES, sizeof(int64_t));
191		cp_diff[cpu] = calloc(CPUSTATES, sizeof(int64_t));
192		if (cp_time[cpu] == NULL || cp_old[cpu] == NULL ||
193		    cp_diff[cpu] == NULL)
194			err(1, NULL);
195	}
196
197	pbase = NULL;
198	pref = NULL;
199	onproc = -1;
200	nproc = 0;
201
202	/*
203	 * get the page size with "getpagesize" and calculate pageshift from
204	 * it
205	 */
206	pagesize = getpagesize();
207	pageshift = 0;
208	while (pagesize > 1) {
209		pageshift++;
210		pagesize >>= 1;
211	}
212
213	/* we only need the amount of log(2)1024 for our conversion */
214	pageshift -= LOG1024;
215
216	/* fill in the statics information */
217	statics->procstate_names = procstatenames;
218	statics->cpustate_names = cpustatenames;
219	statics->memory_names = memorynames;
220	statics->order_names = ordernames;
221	return (0);
222}
223
224char *
225format_header(char *uname_field)
226{
227	char *ptr;
228
229	ptr = header + UNAME_START;
230	while (*uname_field != '\0')
231		*ptr++ = *uname_field++;
232	return (header);
233}
234
235void
236get_system_info(struct system_info *si)
237{
238	static int sysload_mib[] = {CTL_VM, VM_LOADAVG};
239	static int uvmexp_mib[] = {CTL_VM, VM_UVMEXP};
240	static int bcstats_mib[] = {CTL_VFS, VFS_GENERIC, VFS_BCACHESTAT};
241	struct loadavg sysload;
242	struct uvmexp uvmexp;
243	struct bcachestats bcstats;
244	double *infoloadp;
245	size_t size;
246	int i;
247	int64_t *tmpstate;
248
249	if (ncpu > 1) {
250		int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, /*fillme*/0};
251
252		size = CPUSTATES * sizeof(int64_t);
253		for (i = 0; i < ncpu; i++) {
254			cp_time_mib[2] = i;
255			tmpstate = cpu_states + (CPUSTATES * i);
256			if (sysctl(cp_time_mib, 3, cp_time[i], &size, NULL, 0) < 0)
257				warn("sysctl kern.cp_time2 failed");
258			/* convert cp_time2 counts to percentages */
259			(void) percentages(CPUSTATES, tmpstate, cp_time[i],
260			    cp_old[i], cp_diff[i]);
261		}
262	} else {
263		int cp_time_mib[] = {CTL_KERN, KERN_CPTIME};
264		long cp_time_tmp[CPUSTATES];
265
266		size = sizeof(cp_time_tmp);
267		if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, NULL, 0) < 0)
268			warn("sysctl kern.cp_time failed");
269		for (i = 0; i < CPUSTATES; i++)
270			cp_time[0][i] = cp_time_tmp[i];
271		/* convert cp_time counts to percentages */
272		(void) percentages(CPUSTATES, cpu_states, cp_time[0],
273		    cp_old[0], cp_diff[0]);
274	}
275
276	size = sizeof(sysload);
277	if (sysctl(sysload_mib, 2, &sysload, &size, NULL, 0) < 0)
278		warn("sysctl failed");
279	infoloadp = si->load_avg;
280	for (i = 0; i < 3; i++)
281		*infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
282
283
284	/* get total -- systemwide main memory usage structure */
285	size = sizeof(uvmexp);
286	if (sysctl(uvmexp_mib, 2, &uvmexp, &size, NULL, 0) < 0) {
287		warn("sysctl failed");
288		bzero(&uvmexp, sizeof(uvmexp));
289	}
290	size = sizeof(bcstats);
291	if (sysctl(bcstats_mib, 3, &bcstats, &size, NULL, 0) < 0) {
292		warn("sysctl failed");
293		bzero(&bcstats, sizeof(bcstats));
294	}
295	/* convert memory stats to Kbytes */
296	memory_stats[0] = -1;
297	memory_stats[1] = pagetok(uvmexp.active);
298	memory_stats[2] = pagetok(uvmexp.npages - uvmexp.free);
299	memory_stats[3] = -1;
300	memory_stats[4] = pagetok(uvmexp.free);
301	memory_stats[5] = -1;
302	memory_stats[6] = pagetok(bcstats.numbufpages);
303	memory_stats[7] = -1;
304
305	if (!swapmode(&memory_stats[8], &memory_stats[9])) {
306		memory_stats[8] = 0;
307		memory_stats[9] = 0;
308	}
309
310	/* set arrays and strings */
311	si->cpustates = cpu_states;
312	si->memory = memory_stats;
313	si->last_pid = -1;
314}
315
316static struct handle handle;
317
318struct kinfo_proc *
319getprocs(int op, int arg, int *cnt)
320{
321	size_t size;
322	int mib[6] = {CTL_KERN, KERN_PROC, 0, 0, sizeof(struct kinfo_proc), 0};
323	static int maxslp_mib[] = {CTL_VM, VM_MAXSLP};
324	static struct kinfo_proc *procbase;
325	int st;
326
327	mib[2] = op;
328	mib[3] = arg;
329
330	size = sizeof(maxslp);
331	if (sysctl(maxslp_mib, 2, &maxslp, &size, NULL, 0) < 0) {
332		warn("sysctl vm.maxslp failed");
333		return (0);
334	}
335    retry:
336	free(procbase);
337	st = sysctl(mib, 6, NULL, &size, NULL, 0);
338	if (st == -1) {
339		/* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
340		return (0);
341	}
342	size = 5 * size / 4;			/* extra slop */
343	if ((procbase = malloc(size)) == NULL)
344		return (0);
345	mib[5] = (int)(size / sizeof(struct kinfo_proc));
346	st = sysctl(mib, 6, procbase, &size, NULL, 0);
347	if (st == -1) {
348		if (errno == ENOMEM)
349			goto retry;
350		/* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
351		return (0);
352	}
353	*cnt = (int)(size / sizeof(struct kinfo_proc));
354	return (procbase);
355}
356
357caddr_t
358get_process_info(struct system_info *si, struct process_select *sel,
359    int (*compare) (const void *, const void *))
360{
361	int show_idle, show_system, show_threads, show_uid, show_pid, show_cmd;
362	int hide_uid;
363	int total_procs, active_procs;
364	struct kinfo_proc **prefp, *pp;
365	int what = KERN_PROC_KTHREAD;
366
367	if (sel->threads)
368		what |= KERN_PROC_SHOW_THREADS;
369
370	if ((pbase = getprocs(what, 0, &nproc)) == NULL) {
371		/* warnx("%s", kvm_geterr(kd)); */
372		quit(23);
373	}
374	if (nproc > onproc)
375		pref = (struct kinfo_proc **)realloc(pref,
376		    sizeof(struct kinfo_proc *) * (onproc = nproc));
377	if (pref == NULL) {
378		warnx("Out of memory.");
379		quit(23);
380	}
381	/* get a pointer to the states summary array */
382	si->procstates = process_states;
383
384	/* set up flags which define what we are going to select */
385	show_idle = sel->idle;
386	show_system = sel->system;
387	show_threads = sel->threads;
388	show_uid = sel->uid != (uid_t)-1;
389	hide_uid = sel->huid != (uid_t)-1;
390	show_pid = sel->pid != (pid_t)-1;
391	show_cmd = sel->command != NULL;
392
393	/* count up process states and get pointers to interesting procs */
394	total_procs = 0;
395	active_procs = 0;
396	memset((char *) process_states, 0, sizeof(process_states));
397	prefp = pref;
398	for (pp = pbase; pp < &pbase[nproc]; pp++) {
399		/*
400		 *  Place pointers to each valid proc structure in pref[].
401		 *  Process slots that are actually in use have a non-zero
402		 *  status field.  Processes with P_SYSTEM set are system
403		 *  processes---these get ignored unless show_system is set.
404		 */
405		if (show_threads && pp->p_tid == -1)
406			continue;
407		if (pp->p_stat != 0 &&
408		    (show_system || (pp->p_flag & P_SYSTEM) == 0) &&
409		    (show_threads || (pp->p_flag & P_THREAD) == 0)) {
410			total_procs++;
411			process_states[(unsigned char) pp->p_stat]++;
412			if ((pp->p_psflags & PS_ZOMBIE) == 0 &&
413			    (show_idle || pp->p_pctcpu != 0 ||
414			    pp->p_stat == SRUN) &&
415			    (!hide_uid || pp->p_ruid != sel->huid) &&
416			    (!show_uid || pp->p_ruid == sel->uid) &&
417			    (!show_pid || pp->p_pid == sel->pid) &&
418			    (!show_cmd || strstr(pp->p_comm,
419				sel->command))) {
420				*prefp++ = pp;
421				active_procs++;
422			}
423		}
424	}
425
426	/* if requested, sort the "interesting" processes */
427	if (compare != NULL)
428		qsort((char *) pref, active_procs,
429		    sizeof(struct kinfo_proc *), compare);
430	/* remember active and total counts */
431	si->p_total = total_procs;
432	si->p_active = pref_len = active_procs;
433
434	/* pass back a handle */
435	handle.next_proc = pref;
436	handle.remaining = active_procs;
437	return ((caddr_t) & handle);
438}
439
440char fmt[MAX_COLS];	/* static area where result is built */
441
442static char *
443state_abbr(struct kinfo_proc *pp)
444{
445	static char buf[10];
446
447	if (ncpu > 1 && pp->p_cpuid != KI_NOCPU)
448		snprintf(buf, sizeof buf, "%s/%llu",
449		    state_abbrev[(unsigned char)pp->p_stat], pp->p_cpuid);
450	else
451		snprintf(buf, sizeof buf, "%s",
452		    state_abbrev[(unsigned char)pp->p_stat]);
453	return buf;
454}
455
456static char *
457format_comm(struct kinfo_proc *kp)
458{
459	static char **s, buf[MAX_COLS];
460	size_t siz = 100;
461	char **p;
462	int mib[4];
463	extern int show_args;
464
465	if (!show_args)
466		return (kp->p_comm);
467
468	for (;; siz *= 2) {
469		if ((s = realloc(s, siz)) == NULL)
470			err(1, NULL);
471		mib[0] = CTL_KERN;
472		mib[1] = KERN_PROC_ARGS;
473		mib[2] = kp->p_pid;
474		mib[3] = KERN_PROC_ARGV;
475		if (sysctl(mib, 4, s, &siz, NULL, 0) == 0)
476			break;
477		if (errno != ENOMEM)
478			return (kp->p_comm);
479	}
480	buf[0] = '\0';
481	for (p = s; *p != NULL; p++) {
482		if (p != s)
483			strlcat(buf, " ", sizeof(buf));
484		strlcat(buf, *p, sizeof(buf));
485	}
486	if (buf[0] == '\0')
487		return (kp->p_comm);
488	return (buf);
489}
490
491char *
492format_next_process(caddr_t handle, char *(*get_userid)(uid_t), pid_t *pid)
493{
494	char *p_wait;
495	struct kinfo_proc *pp;
496	struct handle *hp;
497	int cputime;
498	double pct;
499
500	/* find and remember the next proc structure */
501	hp = (struct handle *) handle;
502	pp = *(hp->next_proc++);
503	hp->remaining--;
504
505	cputime = pp->p_rtime_sec + ((pp->p_rtime_usec + 500000) / 1000000);
506
507	/* calculate the base for cpu percentages */
508	pct = (double)pp->p_pctcpu / fscale;
509
510	if (pp->p_wmesg[0])
511		p_wait = pp->p_wmesg;
512	else
513		p_wait = "-";
514
515	/* format this entry */
516	snprintf(fmt, sizeof fmt, Proc_format,
517	    pp->p_pid, (*get_userid)(pp->p_ruid),
518	    pp->p_priority - PZERO, pp->p_nice - NZERO,
519	    format_k(pagetok(PROCSIZE(pp))),
520	    format_k(pagetok(pp->p_vm_rssize)),
521	    (pp->p_stat == SSLEEP && pp->p_slptime > maxslp) ?
522	    "idle" : state_abbr(pp),
523	    p_wait, format_time(cputime), 100.0 * pct,
524	    printable(format_comm(pp)));
525
526	*pid = pp->p_pid;
527	/* return the result */
528	return (fmt);
529}
530
531/* comparison routine for qsort */
532static unsigned char sorted_state[] =
533{
534	0,			/* not used		 */
535	4,			/* start		 */
536	5,			/* run			 */
537	2,			/* sleep		 */
538	3,			/* stop			 */
539	1			/* zombie		 */
540};
541
542/*
543 *  proc_compares - comparison functions for "qsort"
544 */
545
546/*
547 * First, the possible comparison keys.  These are defined in such a way
548 * that they can be merely listed in the source code to define the actual
549 * desired ordering.
550 */
551
552#define ORDERKEY_PCTCPU \
553	if ((result = (int)(p2->p_pctcpu - p1->p_pctcpu)) == 0)
554#define ORDERKEY_CPUTIME \
555	if ((result = p2->p_rtime_sec - p1->p_rtime_sec) == 0) \
556		if ((result = p2->p_rtime_usec - p1->p_rtime_usec) == 0)
557#define ORDERKEY_STATE \
558	if ((result = sorted_state[(unsigned char)p2->p_stat] - \
559	    sorted_state[(unsigned char)p1->p_stat])  == 0)
560#define ORDERKEY_PRIO \
561	if ((result = p2->p_priority - p1->p_priority) == 0)
562#define ORDERKEY_RSSIZE \
563	if ((result = p2->p_vm_rssize - p1->p_vm_rssize) == 0)
564#define ORDERKEY_MEM \
565	if ((result = PROCSIZE(p2) - PROCSIZE(p1)) == 0)
566#define ORDERKEY_PID \
567	if ((result = p1->p_pid - p2->p_pid) == 0)
568#define ORDERKEY_CMD \
569	if ((result = strcmp(p1->p_comm, p2->p_comm)) == 0)
570
571/* compare_cpu - the comparison function for sorting by cpu percentage */
572static int
573compare_cpu(const void *v1, const void *v2)
574{
575	struct proc **pp1 = (struct proc **) v1;
576	struct proc **pp2 = (struct proc **) v2;
577	struct kinfo_proc *p1, *p2;
578	int result;
579
580	/* remove one level of indirection */
581	p1 = *(struct kinfo_proc **) pp1;
582	p2 = *(struct kinfo_proc **) pp2;
583
584	ORDERKEY_PCTCPU
585	ORDERKEY_CPUTIME
586	ORDERKEY_STATE
587	ORDERKEY_PRIO
588	ORDERKEY_RSSIZE
589	ORDERKEY_MEM
590		;
591	return (result);
592}
593
594/* compare_size - the comparison function for sorting by total memory usage */
595static int
596compare_size(const void *v1, const void *v2)
597{
598	struct proc **pp1 = (struct proc **) v1;
599	struct proc **pp2 = (struct proc **) v2;
600	struct kinfo_proc *p1, *p2;
601	int result;
602
603	/* remove one level of indirection */
604	p1 = *(struct kinfo_proc **) pp1;
605	p2 = *(struct kinfo_proc **) pp2;
606
607	ORDERKEY_MEM
608	ORDERKEY_RSSIZE
609	ORDERKEY_PCTCPU
610	ORDERKEY_CPUTIME
611	ORDERKEY_STATE
612	ORDERKEY_PRIO
613		;
614	return (result);
615}
616
617/* compare_res - the comparison function for sorting by resident set size */
618static int
619compare_res(const void *v1, const void *v2)
620{
621	struct proc **pp1 = (struct proc **) v1;
622	struct proc **pp2 = (struct proc **) v2;
623	struct kinfo_proc *p1, *p2;
624	int result;
625
626	/* remove one level of indirection */
627	p1 = *(struct kinfo_proc **) pp1;
628	p2 = *(struct kinfo_proc **) pp2;
629
630	ORDERKEY_RSSIZE
631	ORDERKEY_MEM
632	ORDERKEY_PCTCPU
633	ORDERKEY_CPUTIME
634	ORDERKEY_STATE
635	ORDERKEY_PRIO
636		;
637	return (result);
638}
639
640/* compare_time - the comparison function for sorting by CPU time */
641static int
642compare_time(const void *v1, const void *v2)
643{
644	struct proc **pp1 = (struct proc **) v1;
645	struct proc **pp2 = (struct proc **) v2;
646	struct kinfo_proc *p1, *p2;
647	int result;
648
649	/* remove one level of indirection */
650	p1 = *(struct kinfo_proc **) pp1;
651	p2 = *(struct kinfo_proc **) pp2;
652
653	ORDERKEY_CPUTIME
654	ORDERKEY_PCTCPU
655	ORDERKEY_STATE
656	ORDERKEY_PRIO
657	ORDERKEY_MEM
658	ORDERKEY_RSSIZE
659		;
660	return (result);
661}
662
663/* compare_prio - the comparison function for sorting by CPU time */
664static int
665compare_prio(const void *v1, const void *v2)
666{
667	struct proc   **pp1 = (struct proc **) v1;
668	struct proc   **pp2 = (struct proc **) v2;
669	struct kinfo_proc *p1, *p2;
670	int result;
671
672	/* remove one level of indirection */
673	p1 = *(struct kinfo_proc **) pp1;
674	p2 = *(struct kinfo_proc **) pp2;
675
676	ORDERKEY_PRIO
677	ORDERKEY_PCTCPU
678	ORDERKEY_CPUTIME
679	ORDERKEY_STATE
680	ORDERKEY_RSSIZE
681	ORDERKEY_MEM
682		;
683	return (result);
684}
685
686static int
687compare_pid(const void *v1, const void *v2)
688{
689	struct proc **pp1 = (struct proc **) v1;
690	struct proc **pp2 = (struct proc **) v2;
691	struct kinfo_proc *p1, *p2;
692	int result;
693
694	/* remove one level of indirection */
695	p1 = *(struct kinfo_proc **) pp1;
696	p2 = *(struct kinfo_proc **) pp2;
697
698	ORDERKEY_PID
699	ORDERKEY_PCTCPU
700	ORDERKEY_CPUTIME
701	ORDERKEY_STATE
702	ORDERKEY_PRIO
703	ORDERKEY_RSSIZE
704	ORDERKEY_MEM
705		;
706	return (result);
707}
708
709static int
710compare_cmd(const void *v1, const void *v2)
711{
712	struct proc **pp1 = (struct proc **) v1;
713	struct proc **pp2 = (struct proc **) v2;
714	struct kinfo_proc *p1, *p2;
715	int result;
716
717	/* remove one level of indirection */
718	p1 = *(struct kinfo_proc **) pp1;
719	p2 = *(struct kinfo_proc **) pp2;
720
721	ORDERKEY_CMD
722	ORDERKEY_PCTCPU
723	ORDERKEY_CPUTIME
724	ORDERKEY_STATE
725	ORDERKEY_PRIO
726	ORDERKEY_RSSIZE
727	ORDERKEY_MEM
728		;
729	return (result);
730}
731
732
733int (*proc_compares[])(const void *, const void *) = {
734	compare_cpu,
735	compare_size,
736	compare_res,
737	compare_time,
738	compare_prio,
739	compare_pid,
740	compare_cmd,
741	NULL
742};
743
744/*
745 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
746 *		the process does not exist.
747 *		It is EXTREMELY IMPORTANT that this function work correctly.
748 *		If top runs setuid root (as in SVR4), then this function
749 *		is the only thing that stands in the way of a serious
750 *		security problem.  It validates requests for the "kill"
751 *		and "renice" commands.
752 */
753uid_t
754proc_owner(pid_t pid)
755{
756	struct kinfo_proc **prefp, *pp;
757	int cnt;
758
759	prefp = pref;
760	cnt = pref_len;
761	while (--cnt >= 0) {
762		pp = *prefp++;
763		if (pp->p_pid == pid)
764			return ((uid_t)pp->p_ruid);
765	}
766	return (uid_t)(-1);
767}
768
769/*
770 * swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
771 * to be based on the new swapctl(2) system call.
772 */
773static int
774swapmode(int *used, int *total)
775{
776	struct swapent *swdev;
777	int nswap, rnswap, i;
778
779	nswap = swapctl(SWAP_NSWAP, 0, 0);
780	if (nswap == 0)
781		return 0;
782
783	swdev = calloc(nswap, sizeof(*swdev));
784	if (swdev == NULL)
785		return 0;
786
787	rnswap = swapctl(SWAP_STATS, swdev, nswap);
788	if (rnswap == -1) {
789		free(swdev);
790		return 0;
791	}
792
793	/* if rnswap != nswap, then what? */
794
795	/* Total things up */
796	*total = *used = 0;
797	for (i = 0; i < nswap; i++) {
798		if (swdev[i].se_flags & SWF_ENABLE) {
799			*used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
800			*total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
801		}
802	}
803	free(swdev);
804	return 1;
805}
806