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