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