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