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