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