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