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