machine.c revision 1.108
1/* $OpenBSD: machine.c,v 1.108 2020/08/23 21:11:55 kn 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 *);
60static int	cmd_matches(struct kinfo_proc *, char *);
61static char	**get_proc_args(struct kinfo_proc *);
62
63/* get_process_info passes back a handle.  This is what it looks like: */
64
65struct handle {
66	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
67};
68
69/* what we consider to be process size: */
70#define PROCSIZE(pp) ((pp)->p_vm_tsize + (pp)->p_vm_dsize + (pp)->p_vm_ssize)
71
72/*
73 *  These definitions control the format of the per-process area
74 */
75static char header[] =
76	"  PID X        PRI NICE  SIZE   RES STATE     WAIT      TIME    CPU COMMAND";
77
78/* 0123456   -- field to fill in starts at header+6 */
79#define UNAME_START 6
80
81#define Proc_format \
82	"%5d %-8.8s %3d %4d %5s %5s %-9s %-7.7s %6s %5.2f%% %s"
83
84/* process state names for the "STATE" column of the display */
85char	*state_abbrev[] = {
86	"", "start", "run", "sleep", "stop", "zomb", "dead", "onproc"
87};
88
89/* these are for calculating cpu state percentages */
90static struct cpustats	*cp_time;
91static struct cpustats	*cp_old;
92static struct cpustats	*cp_diff;
93
94/* these are for detailing the process states */
95int process_states[8];
96char *procstatenames[] = {
97	"", " starting, ", " running, ", " idle, ",
98	" stopped, ", " zombie, ", " dead, ", " on processor, ",
99	NULL
100};
101
102/* these are for detailing the cpu states */
103int64_t *cpu_states;
104char *cpustatenames[] = {
105	"user", "nice", "sys", "spin", "intr", "idle", NULL
106};
107
108/* this is for tracking which cpus are online */
109int *cpu_online;
110
111/* these are for detailing the memory statistics */
112int memory_stats[10];
113char *memorynames[] = {
114	"Real: ", "K/", "K act/tot ", "Free: ", "K ",
115	"Cache: ", "K ",
116	"Swap: ", "K/", "K",
117	NULL
118};
119
120/* these are names given to allowed sorting orders -- first is default */
121char	*ordernames[] = {
122	"cpu", "size", "res", "time", "pri", "pid", "command", NULL
123};
124
125/* these are for keeping track of the proc array */
126static int	nproc;
127static int	onproc = -1;
128static int	pref_len;
129static struct kinfo_proc *pbase;
130static struct kinfo_proc **pref;
131
132/* these are for getting the memory statistics */
133static int	pageshift;	/* log base 2 of the pagesize */
134
135/* define pagetok in terms of pageshift */
136#define pagetok(size) ((size) << pageshift)
137
138int		ncpu;
139int		ncpuonline;
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) == -1)
152		return (-1);
153	return fscale;
154}
155
156int
157getncpu(void)
158{
159	int mib[] = { CTL_HW, HW_NCPU };
160	int numcpu;
161	size_t size = sizeof(numcpu);
162
163	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
164	    &numcpu, &size, NULL, 0) == -1)
165		return (-1);
166
167	return (numcpu);
168}
169
170int
171getncpuonline(void)
172{
173	int mib[] = { CTL_HW, HW_NCPUONLINE };
174	int numcpu;
175	size_t size = sizeof(numcpu);
176
177	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
178	    &numcpu, &size, NULL, 0) == -1)
179		return (-1);
180
181	return (numcpu);
182}
183
184int
185machine_init(struct statics *statics)
186{
187	int pagesize;
188
189	ncpu = getncpu();
190	if (ncpu == -1)
191		return (-1);
192	if (getfscale() == -1)
193		return (-1);
194	cpu_states = calloc(ncpu, CPUSTATES * sizeof(int64_t));
195	if (cpu_states == NULL)
196		err(1, NULL);
197	cp_time = calloc(ncpu, sizeof(*cp_time));
198	cp_old  = calloc(ncpu, sizeof(*cp_old));
199	cp_diff = calloc(ncpu, sizeof(*cp_diff));
200	if (cp_time == NULL || cp_old == NULL || cp_diff == NULL)
201		err(1, NULL);
202	cpu_online = calloc(ncpu, sizeof(*cpu_online));
203	if (cpu_online == NULL)
204		err(1, NULL);
205
206	/*
207	 * get the page size with "getpagesize" and calculate pageshift from
208	 * it
209	 */
210	pagesize = getpagesize();
211	pageshift = 0;
212	while (pagesize > 1) {
213		pageshift++;
214		pagesize >>= 1;
215	}
216
217	/* we only need the amount of log(2)1024 for our conversion */
218	pageshift -= LOG1024;
219
220	/* fill in the statics information */
221	statics->procstate_names = procstatenames;
222	statics->cpustate_names = cpustatenames;
223	statics->memory_names = memorynames;
224	statics->order_names = ordernames;
225	return (0);
226}
227
228char *
229format_header(char *second_field)
230{
231	char *field_name, *thread_field = "     TID";
232	char *ptr;
233
234	field_name = second_field ? second_field : thread_field;
235
236	ptr = header + UNAME_START;
237	while (*field_name != '\0')
238		*ptr++ = *field_name++;
239	return (header);
240}
241
242void
243get_system_info(struct system_info *si)
244{
245	static int cpustats_mib[] = {CTL_KERN, KERN_CPUSTATS, /*fillme*/0};
246	static int sysload_mib[] = {CTL_VM, VM_LOADAVG};
247	static int uvmexp_mib[] = {CTL_VM, VM_UVMEXP};
248	static int bcstats_mib[] = {CTL_VFS, VFS_GENERIC, VFS_BCACHESTAT};
249	struct loadavg sysload;
250	struct uvmexp uvmexp;
251	struct bcachestats bcstats;
252	double *infoloadp;
253	size_t size;
254	int i;
255	int64_t *tmpstate;
256
257	size = sizeof(*cp_time);
258	for (i = 0; i < ncpu; i++) {
259		cpustats_mib[2] = i;
260		tmpstate = cpu_states + (CPUSTATES * i);
261		if (sysctl(cpustats_mib, 3, &cp_time[i], &size, NULL, 0) == -1)
262			warn("sysctl kern.cpustats failed");
263		/* convert cpustats counts to percentages */
264		(void) percentages(CPUSTATES, tmpstate, cp_time[i].cs_time,
265		    cp_old[i].cs_time, cp_diff[i].cs_time);
266		/* note whether the cpu is online */
267		cpu_online[i] = (cp_time[i].cs_flags & CPUSTATS_ONLINE) != 0;
268	}
269
270	size = sizeof(sysload);
271	if (sysctl(sysload_mib, 2, &sysload, &size, NULL, 0) == -1)
272		warn("sysctl failed");
273	infoloadp = si->load_avg;
274	for (i = 0; i < 3; i++)
275		*infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
276
277
278	/* get total -- systemwide main memory usage structure */
279	size = sizeof(uvmexp);
280	if (sysctl(uvmexp_mib, 2, &uvmexp, &size, NULL, 0) == -1) {
281		warn("sysctl failed");
282		bzero(&uvmexp, sizeof(uvmexp));
283	}
284	size = sizeof(bcstats);
285	if (sysctl(bcstats_mib, 3, &bcstats, &size, NULL, 0) == -1) {
286		warn("sysctl failed");
287		bzero(&bcstats, sizeof(bcstats));
288	}
289	/* convert memory stats to Kbytes */
290	memory_stats[0] = -1;
291	memory_stats[1] = pagetok(uvmexp.active);
292	memory_stats[2] = pagetok(uvmexp.npages - uvmexp.free);
293	memory_stats[3] = -1;
294	memory_stats[4] = pagetok(uvmexp.free);
295	memory_stats[5] = -1;
296	memory_stats[6] = pagetok(bcstats.numbufpages);
297	memory_stats[7] = -1;
298
299	if (!swapmode(&memory_stats[8], &memory_stats[9])) {
300		memory_stats[8] = 0;
301		memory_stats[9] = 0;
302	}
303
304	/* set arrays and strings */
305	si->cpustates = cpu_states;
306	si->cpuonline = cpu_online;
307	si->memory = memory_stats;
308	si->last_pid = -1;
309}
310
311static struct handle handle;
312
313struct kinfo_proc *
314getprocs(int op, int arg, int *cnt)
315{
316	size_t size;
317	int mib[6] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0,
318	    sizeof(struct kinfo_proc), 0};
319	static int maxslp_mib[] = {CTL_VM, VM_MAXSLP};
320	static struct kinfo_proc *procbase;
321	int st;
322
323	mib[2] = op;
324	mib[3] = arg;
325
326	size = sizeof(maxslp);
327	if (sysctl(maxslp_mib, 2, &maxslp, &size, NULL, 0) == -1) {
328		warn("sysctl vm.maxslp failed");
329		return (0);
330	}
331    retry:
332	free(procbase);
333	st = sysctl(mib, 6, NULL, &size, NULL, 0);
334	if (st == -1) {
335		/* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
336		return (0);
337	}
338	size = 5 * size / 4;			/* extra slop */
339	if ((procbase = malloc(size)) == NULL)
340		return (0);
341	mib[5] = (int)(size / sizeof(struct kinfo_proc));
342	st = sysctl(mib, 6, procbase, &size, NULL, 0);
343	if (st == -1) {
344		if (errno == ENOMEM)
345			goto retry;
346		/* _kvm_syserr(kd, kd->program, "kvm_getprocs"); */
347		return (0);
348	}
349	*cnt = (int)(size / sizeof(struct kinfo_proc));
350	return (procbase);
351}
352
353static char **
354get_proc_args(struct kinfo_proc *kp)
355{
356	static char	**s;
357	static size_t	siz = 1023;
358	int		mib[4];
359
360	if (!s && !(s = malloc(siz)))
361		err(1, NULL);
362
363	mib[0] = CTL_KERN;
364	mib[1] = KERN_PROC_ARGS;
365	mib[2] = kp->p_pid;
366	mib[3] = KERN_PROC_ARGV;
367	for (;;) {
368		size_t space = siz;
369		if (sysctl(mib, 4, s, &space, NULL, 0) == 0)
370			break;
371		if (errno != ENOMEM)
372			return NULL;
373		siz *= 2;
374		if ((s = realloc(s, siz)) == NULL)
375			err(1, NULL);
376	}
377	return s;
378}
379
380static int
381cmd_matches(struct kinfo_proc *proc, char *term)
382{
383	extern int	show_args;
384	char		**args = NULL;
385
386	if (!term) {
387		/* No command filter set */
388		return 1;
389	} else {
390		/* Filter set, process name needs to contain term */
391		if (strstr(proc->p_comm, term))
392			return 1;
393		/* If showing arguments, search those as well */
394		if (show_args) {
395			args = get_proc_args(proc);
396
397			if (args == NULL) {
398				/* Failed to get args, so can't search them */
399				return 0;
400			}
401
402			while (*args != NULL) {
403				if (strstr(*args, term))
404					return 1;
405				args++;
406			}
407		}
408	}
409	return 0;
410}
411
412struct handle *
413get_process_info(struct system_info *si, struct process_select *sel,
414    int (*compare) (const void *, const void *))
415{
416	int show_idle, show_system, show_threads, show_uid, show_pid, show_cmd;
417	int show_rtable, hide_rtable, hide_uid;
418	int total_procs, active_procs;
419	struct kinfo_proc **prefp, *pp;
420	int what = KERN_PROC_ALL;
421
422	show_system = sel->system;
423	show_threads = sel->threads;
424
425	if (show_system)
426		what = KERN_PROC_KTHREAD;
427	if (show_threads)
428		what |= KERN_PROC_SHOW_THREADS;
429
430	if ((pbase = getprocs(what, 0, &nproc)) == NULL) {
431		/* warnx("%s", kvm_geterr(kd)); */
432		quit(23);
433	}
434	if (nproc > onproc)
435		pref = reallocarray(pref, (onproc = nproc),
436		    sizeof(struct kinfo_proc *));
437	if (pref == NULL) {
438		warnx("Out of memory.");
439		quit(23);
440	}
441	/* get a pointer to the states summary array */
442	si->procstates = process_states;
443
444	/* set up flags which define what we are going to select */
445	show_idle = sel->idle;
446	show_uid = sel->uid != (uid_t)-1;
447	hide_uid = sel->huid != (uid_t)-1;
448	show_pid = sel->pid != (pid_t)-1;
449	show_rtable = sel->rtableid != -1;
450	hide_rtable = sel->hrtableid != -1;
451	show_cmd = sel->command != NULL;
452
453	/* count up process states and get pointers to interesting procs */
454	total_procs = 0;
455	active_procs = 0;
456	memset((char *) process_states, 0, sizeof(process_states));
457	prefp = pref;
458	for (pp = pbase; pp < &pbase[nproc]; pp++) {
459		/*
460		 * When showing threads, we want to ignore the structure
461		 * that represents the entire process, which has TID == -1
462		 */
463		if (show_threads && pp->p_tid == -1)
464			continue;
465		/*
466		 * Place pointers to each valid proc structure in pref[].
467		 * Process slots that are actually in use have a non-zero
468		 * status field.
469		 */
470		if (pp->p_stat != 0) {
471			total_procs++;
472			process_states[(unsigned char) pp->p_stat]++;
473			if ((pp->p_psflags & PS_ZOMBIE) == 0 &&
474			    (show_idle || pp->p_pctcpu != 0 ||
475			    pp->p_stat == SRUN) &&
476			    (!hide_uid || pp->p_ruid != sel->huid) &&
477			    (!show_uid || pp->p_ruid == sel->uid) &&
478			    (!show_pid || pp->p_pid == sel->pid) &&
479			    (!hide_rtable || pp->p_rtableid != sel->hrtableid) &&
480			    (!show_rtable || pp->p_rtableid == sel->rtableid) &&
481			    (!show_cmd || cmd_matches(pp, sel->command))) {
482				*prefp++ = pp;
483				active_procs++;
484			}
485		}
486	}
487
488	qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
489	/* remember active and total counts */
490	si->p_total = total_procs;
491	si->p_active = pref_len = active_procs;
492
493	/* pass back a handle */
494	handle.next_proc = pref;
495	return &handle;
496}
497
498char fmt[MAX_COLS];	/* static area where result is built */
499
500static char *
501state_abbr(struct kinfo_proc *pp)
502{
503	static char buf[10];
504
505	if (ncpu > 1 && pp->p_cpuid != KI_NOCPU)
506		snprintf(buf, sizeof buf, "%s/%llu",
507		    state_abbrev[(unsigned char)pp->p_stat], pp->p_cpuid);
508	else
509		snprintf(buf, sizeof buf, "%s",
510		    state_abbrev[(unsigned char)pp->p_stat]);
511	return buf;
512}
513
514static char *
515format_comm(struct kinfo_proc *kp)
516{
517	static char	buf[MAX_COLS];
518	char		**p, **s;
519	extern int	show_args;
520
521	if (!show_args)
522		return (kp->p_comm);
523
524	s = get_proc_args(kp);
525	if (s == NULL)
526		return kp->p_comm;
527
528	buf[0] = '\0';
529	for (p = s; *p != NULL; p++) {
530		if (p != s)
531			strlcat(buf, " ", sizeof(buf));
532		strlcat(buf, *p, sizeof(buf));
533	}
534	if (buf[0] == '\0')
535		return (kp->p_comm);
536	return (buf);
537}
538
539void
540skip_processes(struct handle *hndl, int n)
541{
542	hndl->next_proc += n;
543}
544
545char *
546format_next_process(struct handle *hndl, const char *(*get_userid)(uid_t, int),
547    pid_t *pid)
548{
549	char *p_wait;
550	struct kinfo_proc *pp;
551	int cputime;
552	double pct;
553	char buf[16];
554
555	/* find and remember the next proc structure */
556	pp = *(hndl->next_proc++);
557
558	cputime = pp->p_rtime_sec + ((pp->p_rtime_usec + 500000) / 1000000);
559
560	/* calculate the base for cpu percentages */
561	pct = (double)pp->p_pctcpu / fscale;
562
563	if (pp->p_wmesg[0])
564		p_wait = pp->p_wmesg;
565	else
566		p_wait = "-";
567
568	if (get_userid == NULL)
569		snprintf(buf, sizeof(buf), "%8d", pp->p_tid);
570	else
571		snprintf(buf, sizeof(buf), "%s", (*get_userid)(pp->p_ruid, 0));
572
573	/* format this entry */
574	snprintf(fmt, sizeof(fmt), Proc_format, pp->p_pid, buf,
575	    pp->p_priority - PZERO, pp->p_nice - NZERO,
576	    format_k(pagetok(PROCSIZE(pp))),
577	    format_k(pagetok(pp->p_vm_rssize)),
578	    (pp->p_stat == SSLEEP && pp->p_slptime > maxslp) ?
579	    "idle" : state_abbr(pp),
580	    p_wait, format_time(cputime), 100.0 * pct,
581	    printable(format_comm(pp)));
582
583	*pid = pp->p_pid;
584	/* return the result */
585	return (fmt);
586}
587
588/* comparison routine for qsort */
589static unsigned char sorted_state[] =
590{
591	0,			/* not used		 */
592	4,			/* start		 */
593	5,			/* run			 */
594	2,			/* sleep		 */
595	3,			/* stop			 */
596	1			/* zombie		 */
597};
598
599extern int rev_order;
600
601/*
602 *  proc_compares - comparison functions for "qsort"
603 */
604
605/*
606 * First, the possible comparison keys.  These are defined in such a way
607 * that they can be merely listed in the source code to define the actual
608 * desired ordering.
609 */
610
611#define ORDERKEY_PCTCPU \
612	if ((result = (int)(p2->p_pctcpu - p1->p_pctcpu)) == 0)
613#define ORDERKEY_CPUTIME \
614	if ((result = p2->p_rtime_sec - p1->p_rtime_sec) == 0) \
615		if ((result = p2->p_rtime_usec - p1->p_rtime_usec) == 0)
616#define ORDERKEY_STATE \
617	if ((result = sorted_state[(unsigned char)p2->p_stat] - \
618	    sorted_state[(unsigned char)p1->p_stat])  == 0)
619#define ORDERKEY_PRIO \
620	if ((result = p2->p_priority - p1->p_priority) == 0)
621#define ORDERKEY_RSSIZE \
622	if ((result = p2->p_vm_rssize - p1->p_vm_rssize) == 0)
623#define ORDERKEY_MEM \
624	if ((result = PROCSIZE(p2) - PROCSIZE(p1)) == 0)
625#define ORDERKEY_PID \
626	if ((result = p1->p_pid - p2->p_pid) == 0)
627#define ORDERKEY_CMD \
628	if ((result = strcmp(p1->p_comm, p2->p_comm)) == 0)
629
630/* remove one level of indirection and set sort order */
631#define SETORDER do { \
632		if (rev_order) { \
633			p1 = *(struct kinfo_proc **) v2; \
634			p2 = *(struct kinfo_proc **) v1; \
635		} else { \
636			p1 = *(struct kinfo_proc **) v1; \
637			p2 = *(struct kinfo_proc **) v2; \
638		} \
639	} while (0)
640
641/* compare_cpu - the comparison function for sorting by cpu percentage */
642static int
643compare_cpu(const void *v1, const void *v2)
644{
645	struct kinfo_proc *p1, *p2;
646	int result;
647
648	SETORDER;
649
650	ORDERKEY_PCTCPU
651	ORDERKEY_CPUTIME
652	ORDERKEY_STATE
653	ORDERKEY_PRIO
654	ORDERKEY_RSSIZE
655	ORDERKEY_MEM
656		;
657	return (result);
658}
659
660/* compare_size - the comparison function for sorting by total memory usage */
661static int
662compare_size(const void *v1, const void *v2)
663{
664	struct kinfo_proc *p1, *p2;
665	int result;
666
667	SETORDER;
668
669	ORDERKEY_MEM
670	ORDERKEY_RSSIZE
671	ORDERKEY_PCTCPU
672	ORDERKEY_CPUTIME
673	ORDERKEY_STATE
674	ORDERKEY_PRIO
675		;
676	return (result);
677}
678
679/* compare_res - the comparison function for sorting by resident set size */
680static int
681compare_res(const void *v1, const void *v2)
682{
683	struct kinfo_proc *p1, *p2;
684	int result;
685
686	SETORDER;
687
688	ORDERKEY_RSSIZE
689	ORDERKEY_MEM
690	ORDERKEY_PCTCPU
691	ORDERKEY_CPUTIME
692	ORDERKEY_STATE
693	ORDERKEY_PRIO
694		;
695	return (result);
696}
697
698/* compare_time - the comparison function for sorting by CPU time */
699static int
700compare_time(const void *v1, const void *v2)
701{
702	struct kinfo_proc *p1, *p2;
703	int result;
704
705	SETORDER;
706
707	ORDERKEY_CPUTIME
708	ORDERKEY_PCTCPU
709	ORDERKEY_STATE
710	ORDERKEY_PRIO
711	ORDERKEY_MEM
712	ORDERKEY_RSSIZE
713		;
714	return (result);
715}
716
717/* compare_prio - the comparison function for sorting by CPU time */
718static int
719compare_prio(const void *v1, const void *v2)
720{
721	struct kinfo_proc *p1, *p2;
722	int result;
723
724	SETORDER;
725
726	ORDERKEY_PRIO
727	ORDERKEY_PCTCPU
728	ORDERKEY_CPUTIME
729	ORDERKEY_STATE
730	ORDERKEY_RSSIZE
731	ORDERKEY_MEM
732		;
733	return (result);
734}
735
736static int
737compare_pid(const void *v1, const void *v2)
738{
739	struct kinfo_proc *p1, *p2;
740	int result;
741
742	SETORDER;
743
744	ORDERKEY_PID
745	ORDERKEY_PCTCPU
746	ORDERKEY_CPUTIME
747	ORDERKEY_STATE
748	ORDERKEY_PRIO
749	ORDERKEY_RSSIZE
750	ORDERKEY_MEM
751		;
752	return (result);
753}
754
755static int
756compare_cmd(const void *v1, const void *v2)
757{
758	struct kinfo_proc *p1, *p2;
759	int result;
760
761	SETORDER;
762
763	ORDERKEY_CMD
764	ORDERKEY_PCTCPU
765	ORDERKEY_CPUTIME
766	ORDERKEY_STATE
767	ORDERKEY_PRIO
768	ORDERKEY_RSSIZE
769	ORDERKEY_MEM
770		;
771	return (result);
772}
773
774
775int (*proc_compares[])(const void *, const void *) = {
776	compare_cpu,
777	compare_size,
778	compare_res,
779	compare_time,
780	compare_prio,
781	compare_pid,
782	compare_cmd,
783	NULL
784};
785
786/*
787 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
788 *		the process does not exist.
789 *		It is EXTREMELY IMPORTANT that this function work correctly.
790 *		If top runs setuid root (as in SVR4), then this function
791 *		is the only thing that stands in the way of a serious
792 *		security problem.  It validates requests for the "kill"
793 *		and "renice" commands.
794 */
795uid_t
796proc_owner(pid_t pid)
797{
798	struct kinfo_proc **prefp, *pp;
799	int cnt;
800
801	prefp = pref;
802	cnt = pref_len;
803	while (--cnt >= 0) {
804		pp = *prefp++;
805		if (pp->p_pid == pid)
806			return ((uid_t)pp->p_ruid);
807	}
808	return (uid_t)(-1);
809}
810
811/*
812 * swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
813 * to be based on the new swapctl(2) system call.
814 */
815static int
816swapmode(int *used, int *total)
817{
818	struct swapent *swdev;
819	int nswap, rnswap, i;
820
821	nswap = swapctl(SWAP_NSWAP, 0, 0);
822	if (nswap == 0)
823		return 0;
824
825	swdev = calloc(nswap, sizeof(*swdev));
826	if (swdev == NULL)
827		return 0;
828
829	rnswap = swapctl(SWAP_STATS, swdev, nswap);
830	if (rnswap == -1) {
831		free(swdev);
832		return 0;
833	}
834
835	/* if rnswap != nswap, then what? */
836
837	/* Total things up */
838	*total = *used = 0;
839	for (i = 0; i < nswap; i++) {
840		if (swdev[i].se_flags & SWF_ENABLE) {
841			*used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
842			*total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
843		}
844	}
845	free(swdev);
846	return 1;
847}
848