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