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