xref: /freebsd/usr.bin/top/machine.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
1 /*
2  * top - a top users display for Unix
3  *
4  * SYNOPSIS:  For FreeBSD-2.x and later
5  *
6  * DESCRIPTION:
7  * Originally written for BSD4.4 system by Christos Zoulas.
8  * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9  * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10  *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
11  *
12  * This is the machine-dependent module for FreeBSD 2.2
13  * Works for:
14  *	FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
15  *
16  * LIBS: -lkvm
17  *
18  * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
19  *          Steven Wallace  <swallace@freebsd.org>
20  *          Wolfram Schneider <wosch@FreeBSD.org>
21  *          Thomas Moestl <tmoestl@gmx.net>
22  *
23  * $FreeBSD$
24  */
25 
26 
27 #include <sys/time.h>
28 #include <sys/types.h>
29 #include <sys/signal.h>
30 #include <sys/param.h>
31 
32 #include "os.h"
33 #include <stdio.h>
34 #include <nlist.h>
35 #include <math.h>
36 #include <kvm.h>
37 #include <pwd.h>
38 #include <sys/errno.h>
39 #include <sys/sysctl.h>
40 #include <sys/dkstat.h>
41 #include <sys/file.h>
42 #include <sys/time.h>
43 #include <sys/proc.h>
44 #include <sys/user.h>
45 #include <sys/vmmeter.h>
46 #include <sys/resource.h>
47 #include <sys/rtprio.h>
48 
49 /* Swap */
50 #include <stdlib.h>
51 
52 #include <unistd.h>
53 #include <osreldate.h> /* for changes in kernel structures */
54 
55 #include "top.h"
56 #include "machine.h"
57 #include "screen.h"
58 #include "utils.h"
59 
60 static void getsysctl(char *, void *, size_t);
61 
62 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
63 
64 extern char* printable(char *);
65 int swapmode(int *retavail, int *retfree);
66 static int smpmode;
67 static int namelength;
68 static int cmdlengthdelta;
69 
70 /* Prototypes for top internals */
71 void quit(int);
72 
73 /* get_process_info passes back a handle.  This is what it looks like: */
74 
75 struct handle
76 {
77     struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
78     int remaining;		/* number of pointers remaining */
79 };
80 
81 /* declarations for load_avg */
82 #include "loadavg.h"
83 
84 /* define what weighted cpu is.  */
85 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
86 			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
87 
88 /* what we consider to be process size: */
89 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
90 
91 /* definitions for indices in the nlist array */
92 
93 /*
94  *  These definitions control the format of the per-process area
95  */
96 
97 static char smp_header[] =
98   "  PID %-*.*s PRI NICE   SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
99 
100 #define smp_Proc_format \
101 	"%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
102 
103 static char up_header[] =
104   "  PID %-*.*s PRI NICE   SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
105 
106 #define up_Proc_format \
107 	"%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
108 
109 
110 
111 /* process state names for the "STATE" column of the display */
112 /* the extra nulls in the string "run" are for adding a slash and
113    the processor number when needed */
114 
115 char *state_abbrev[] =
116 {
117     "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
118 };
119 
120 
121 static kvm_t *kd;
122 
123 /* values that we stash away in _init and use in later routines */
124 
125 static double logcpu;
126 
127 /* these are retrieved from the kernel in _init */
128 
129 static load_avg  ccpu;
130 
131 /* these are used in the get_ functions */
132 
133 static int lastpid;
134 
135 /* these are for calculating cpu state percentages */
136 
137 static long cp_time[CPUSTATES];
138 static long cp_old[CPUSTATES];
139 static long cp_diff[CPUSTATES];
140 
141 /* these are for detailing the process states */
142 
143 int process_states[8];
144 char *procstatenames[] = {
145     "", " starting, ", " running, ", " sleeping, ", " stopped, ",
146     " zombie, ", " waiting, ", " lock, ",
147     NULL
148 };
149 
150 /* these are for detailing the cpu states */
151 
152 int cpu_states[CPUSTATES];
153 char *cpustatenames[] = {
154     "user", "nice", "system", "interrupt", "idle", NULL
155 };
156 
157 /* these are for detailing the memory statistics */
158 
159 int memory_stats[7];
160 char *memorynames[] = {
161     "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
162     NULL
163 };
164 
165 int swap_stats[7];
166 char *swapnames[] = {
167 /*   0           1            2           3            4       5 */
168     "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
169     NULL
170 };
171 
172 
173 /* these are for keeping track of the proc array */
174 
175 static int nproc;
176 static int onproc = -1;
177 static int pref_len;
178 static struct kinfo_proc *pbase;
179 static struct kinfo_proc **pref;
180 
181 /* these are for getting the memory statistics */
182 
183 static int pageshift;		/* log base 2 of the pagesize */
184 
185 /* define pagetok in terms of pageshift */
186 
187 #define pagetok(size) ((size) << pageshift)
188 
189 /* useful externals */
190 long percentages();
191 
192 #ifdef ORDER
193 /* sorting orders. first is default */
194 char *ordernames[] = {
195     "cpu", "size", "res", "time", "pri", NULL
196 };
197 #endif
198 
199 int
200 machine_init(statics)
201 
202 struct statics *statics;
203 
204 {
205     register int pagesize;
206     size_t modelen;
207     struct passwd *pw;
208 
209     modelen = sizeof(smpmode);
210     if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
211          sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
212 	modelen != sizeof(smpmode))
213 	    smpmode = 0;
214 
215     while ((pw = getpwent()) != NULL) {
216 	if (strlen(pw->pw_name) > namelength)
217 	    namelength = strlen(pw->pw_name);
218     }
219     if (namelength < 8)
220 	namelength = 8;
221     if (smpmode && namelength > 13)
222 	namelength = 13;
223     else if (namelength > 15)
224 	namelength = 15;
225 
226     if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, "kvm_open")) == NULL)
227 	return -1;
228 
229     GETSYSCTL("kern.ccpu", ccpu);
230 
231     /* this is used in calculating WCPU -- calculate it ahead of time */
232     logcpu = log(loaddouble(ccpu));
233 
234     pbase = NULL;
235     pref = NULL;
236     nproc = 0;
237     onproc = -1;
238     /* get the page size with "getpagesize" and calculate pageshift from it */
239     pagesize = getpagesize();
240     pageshift = 0;
241     while (pagesize > 1)
242     {
243 	pageshift++;
244 	pagesize >>= 1;
245     }
246 
247     /* we only need the amount of log(2)1024 for our conversion */
248     pageshift -= LOG1024;
249 
250     /* fill in the statics information */
251     statics->procstate_names = procstatenames;
252     statics->cpustate_names = cpustatenames;
253     statics->memory_names = memorynames;
254     statics->swap_names = swapnames;
255 #ifdef ORDER
256     statics->order_names = ordernames;
257 #endif
258 
259     /* all done! */
260     return(0);
261 }
262 
263 char *format_header(uname_field)
264 
265 register char *uname_field;
266 
267 {
268     static char Header[128];
269 
270     snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
271 	     namelength, namelength, uname_field);
272 
273     cmdlengthdelta = strlen(Header) - 7;
274 
275     return Header;
276 }
277 
278 static int swappgsin = -1;
279 static int swappgsout = -1;
280 extern struct timeval timeout;
281 
282 void
283 get_system_info(si)
284 
285 struct system_info *si;
286 
287 {
288     long total;
289     struct loadavg sysload;
290     int mib[2];
291     struct timeval boottime;
292     size_t bt_size;
293 
294     /* get the cp_time array */
295     GETSYSCTL("kern.cp_time", cp_time);
296     GETSYSCTL("vm.loadavg", sysload);
297     GETSYSCTL("kern.lastpid", lastpid);
298 
299     /* convert load averages to doubles */
300     {
301 	register int i;
302 	register double *infoloadp;
303 
304 	infoloadp = si->load_avg;
305 	for (i = 0; i < 3; i++)
306 	{
307 #ifdef notyet
308 	    *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
309 #endif
310 	    *infoloadp++ = loaddouble(sysload.ldavg[i]);
311 	}
312     }
313 
314     /* convert cp_time counts to percentages */
315     total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
316 
317     /* sum memory & swap statistics */
318     {
319 	static unsigned int swap_delay = 0;
320 	static int swapavail = 0;
321 	static int swapfree = 0;
322 	static int bufspace = 0;
323 	static int nspgsin, nspgsout;
324 
325 	GETSYSCTL("vfs.bufspace", bufspace);
326 	GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
327 	GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
328 	GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
329 	GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
330 	GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
331 	GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
332 	GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
333 	/* convert memory stats to Kbytes */
334 	memory_stats[0] = pagetok(memory_stats[0]);
335 	memory_stats[1] = pagetok(memory_stats[1]);
336 	memory_stats[2] = pagetok(memory_stats[2]);
337 	memory_stats[3] = pagetok(memory_stats[3]);
338 	memory_stats[4] = bufspace / 1024;
339 	memory_stats[5] = pagetok(memory_stats[5]);
340 	memory_stats[6] = -1;
341 
342 	/* first interval */
343         if (swappgsin < 0) {
344 	    swap_stats[4] = 0;
345 	    swap_stats[5] = 0;
346 	}
347 
348 	/* compute differences between old and new swap statistic */
349 	else {
350 	    swap_stats[4] = pagetok(((nspgsin - swappgsin)));
351 	    swap_stats[5] = pagetok(((nspgsout - swappgsout)));
352 	}
353 
354         swappgsin = nspgsin;
355 	swappgsout = nspgsout;
356 
357 	/* call CPU heavy swapmode() only for changes */
358         if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
359 	    swap_stats[3] = swapmode(&swapavail, &swapfree);
360 	    swap_stats[0] = swapavail;
361 	    swap_stats[1] = swapavail - swapfree;
362 	    swap_stats[2] = swapfree;
363 	}
364         swap_delay = 1;
365 	swap_stats[6] = -1;
366     }
367 
368     /* set arrays and strings */
369     si->cpustates = cpu_states;
370     si->memory = memory_stats;
371     si->swap = swap_stats;
372 
373 
374     if(lastpid > 0) {
375 	si->last_pid = lastpid;
376     } else {
377 	si->last_pid = -1;
378     }
379 
380     /*
381      * Print how long system has been up.
382      * (Found by looking getting "boottime" from the kernel)
383      */
384     mib[0] = CTL_KERN;
385     mib[1] = KERN_BOOTTIME;
386     bt_size = sizeof(boottime);
387     if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
388 	boottime.tv_sec != 0) {
389 	si->boottime = boottime;
390     } else {
391 	si->boottime.tv_sec = -1;
392     }
393 }
394 
395 static struct handle handle;
396 
397 caddr_t get_process_info(si, sel, compare)
398 
399 struct system_info *si;
400 struct process_select *sel;
401 int (*compare)();
402 
403 {
404     register int i;
405     register int total_procs;
406     register int active_procs;
407     register struct kinfo_proc **prefp;
408     register struct kinfo_proc *pp;
409 
410     /* these are copied out of sel for speed */
411     int show_idle;
412     int show_self;
413     int show_system;
414     int show_uid;
415     int show_command;
416 
417 
418     pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
419     if (nproc > onproc)
420 	pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
421 		* (onproc = nproc));
422     if (pref == NULL || pbase == NULL) {
423 	(void) fprintf(stderr, "top: Out of memory.\n");
424 	quit(23);
425     }
426     /* get a pointer to the states summary array */
427     si->procstates = process_states;
428 
429     /* set up flags which define what we are going to select */
430     show_idle = sel->idle;
431     show_self = sel->self;
432     show_system = sel->system;
433     show_uid = sel->uid != -1;
434     show_command = sel->command != NULL;
435 
436     /* count up process states and get pointers to interesting procs */
437     total_procs = 0;
438     active_procs = 0;
439     memset((char *)process_states, 0, sizeof(process_states));
440     prefp = pref;
441     for (pp = pbase, i = 0; i < nproc; pp++, i++)
442     {
443 	/*
444 	 *  Place pointers to each valid proc structure in pref[].
445 	 *  Process slots that are actually in use have a non-zero
446 	 *  status field.  Processes with P_SYSTEM set are system
447 	 *  processes---these get ignored unless show_sysprocs is set.
448 	 */
449 	if (pp->ki_stat != 0 &&
450 	    (show_self != pp->ki_pid) &&
451 	    (show_system || ((pp->ki_flag & P_SYSTEM) == 0)))
452 	{
453 	    total_procs++;
454 	    process_states[(unsigned char) pp->ki_stat]++;
455 	    if ((pp->ki_stat != SZOMB) &&
456 		(show_idle || (pp->ki_pctcpu != 0) ||
457 		 (pp->ki_stat == SRUN)) &&
458 		(!show_uid || pp->ki_ruid == (uid_t)sel->uid))
459 	    {
460 		*prefp++ = pp;
461 		active_procs++;
462 	    }
463 	}
464     }
465 
466     /* if requested, sort the "interesting" processes */
467     if (compare != NULL)
468     {
469 	qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
470     }
471 
472     /* remember active and total counts */
473     si->p_total = total_procs;
474     si->p_active = pref_len = active_procs;
475 
476     /* pass back a handle */
477     handle.next_proc = pref;
478     handle.remaining = active_procs;
479     return((caddr_t)&handle);
480 }
481 
482 char fmt[128];		/* static area where result is built */
483 
484 char *format_next_process(handle, get_userid)
485 
486 caddr_t handle;
487 char *(*get_userid)();
488 
489 {
490     register struct kinfo_proc *pp;
491     register long cputime;
492     register double pct;
493     struct handle *hp;
494     char status[16];
495     int state;
496 
497     /* find and remember the next proc structure */
498     hp = (struct handle *)handle;
499     pp = *(hp->next_proc++);
500     hp->remaining--;
501 
502     /* get the process's command name */
503     if ((pp->ki_sflag & PS_INMEM) == 0) {
504 	/*
505 	 * Print swapped processes as <pname>
506 	 */
507 	char *comm = pp->ki_comm;
508 #define COMSIZ sizeof(pp->ki_comm)
509 	char buf[COMSIZ];
510 	(void) strncpy(buf, comm, COMSIZ);
511 	comm[0] = '<';
512 	(void) strncpy(&comm[1], buf, COMSIZ - 2);
513 	comm[COMSIZ - 2] = '\0';
514 	(void) strncat(comm, ">", COMSIZ - 1);
515 	comm[COMSIZ - 1] = '\0';
516     }
517 
518     /*
519      * Convert the process's runtime from microseconds to seconds.  This
520      * time includes the interrupt time although that is not wanted here.
521      * ps(1) is similarly sloppy.
522      */
523     cputime = (pp->ki_runtime + 500000) / 1000000;
524 
525     /* calculate the base for cpu percentages */
526     pct = pctdouble(pp->ki_pctcpu);
527 
528     /* generate "STATE" field */
529     switch (state = pp->ki_stat) {
530 	case SRUN:
531 	    if (smpmode && pp->ki_oncpu != 0xff)
532 		sprintf(status, "CPU%d", pp->ki_oncpu);
533 	    else
534 		strcpy(status, "RUN");
535 	    break;
536 	case SLOCK:
537 	    if (pp->ki_kiflag & KI_LOCKBLOCK) {
538 		sprintf(status, "*%.6s", pp->ki_lockname);
539 	        break;
540 	    }
541 	    /* fall through */
542 	case SSLEEP:
543 	    if (pp->ki_wmesg != NULL) {
544 		sprintf(status, "%.6s", pp->ki_wmesg);
545 		break;
546 	    }
547 	    /* FALLTHROUGH */
548 	default:
549 
550 	    if (state >= 0 &&
551 	        state < sizeof(state_abbrev) / sizeof(*state_abbrev))
552 		    sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
553 	    else
554 		    sprintf(status, "?%5d", state);
555 	    break;
556     }
557 
558     /* format this entry */
559     sprintf(fmt,
560 	    smpmode ? smp_Proc_format : up_Proc_format,
561 	    pp->ki_pid,
562 	    namelength, namelength,
563 	    (*get_userid)(pp->ki_ruid),
564 	    pp->ki_pri.pri_level - PZERO,
565 
566 	    /*
567 	     * normal time      -> nice value -20 - +20
568 	     * real time 0 - 31 -> nice value -52 - -21
569 	     * idle time 0 - 31 -> nice value +21 - +52
570 	     */
571 	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
572 	    	pp->ki_nice - NZERO :
573 	    	(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
574 		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
575 		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
576 	    format_k2(PROCSIZE(pp)),
577 	    format_k2(pagetok(pp->ki_rssize)),
578 	    status,
579 	    smpmode ? pp->ki_lastcpu : 0,
580 	    format_time(cputime),
581 	    100.0 * weighted_cpu(pct, pp),
582 	    100.0 * pct,
583 	    screen_width > cmdlengthdelta ?
584 		screen_width - cmdlengthdelta :
585 		0,
586 	    printable(pp->ki_comm));
587 
588     /* return the result */
589     return(fmt);
590 }
591 
592 static void getsysctl (name, ptr, len)
593 
594 char *name;
595 void *ptr;
596 size_t len;
597 
598 {
599     size_t nlen = len;
600     if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
601 	    fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
602 		strerror(errno));
603 	    quit(23);
604     }
605     if (nlen != len) {
606 	    fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
607 		(unsigned long)len, (unsigned long)nlen);
608 	    quit(23);
609     }
610 }
611 
612 /* comparison routines for qsort */
613 
614 /*
615  *  proc_compare - comparison function for "qsort"
616  *	Compares the resource consumption of two processes using five
617  *  	distinct keys.  The keys (in descending order of importance) are:
618  *  	percent cpu, cpu ticks, state, resident set size, total virtual
619  *  	memory usage.  The process states are ordered as follows (from least
620  *  	to most important):  WAIT, zombie, sleep, stop, start, run.  The
621  *  	array declaration below maps a process state index into a number
622  *  	that reflects this ordering.
623  */
624 
625 static unsigned char sorted_state[] =
626 {
627     0,	/* not used		*/
628     3,	/* sleep		*/
629     1,	/* ABANDONED (WAIT)	*/
630     6,	/* run			*/
631     5,	/* start		*/
632     2,	/* zombie		*/
633     4	/* stop			*/
634 };
635 
636 
637 #define ORDERKEY_PCTCPU \
638   if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
639      (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
640 
641 #define ORDERKEY_CPTICKS \
642   if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
643                 p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
644 
645 #define ORDERKEY_STATE \
646   if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
647                 sorted_state[(unsigned char) p1->ki_stat]) == 0)
648 
649 #define ORDERKEY_PRIO \
650   if ((result = p2->ki_pri.pri_level - p1->ki_pri.pri_level) == 0)
651 
652 #define ORDERKEY_RSSIZE \
653   if ((result = p2->ki_rssize - p1->ki_rssize) == 0)
654 
655 #define ORDERKEY_MEM \
656   if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
657 
658 /* compare_cpu - the comparison function for sorting by cpu percentage */
659 
660 int
661 #ifdef ORDER
662 compare_cpu(pp1, pp2)
663 #else
664 proc_compare(pp1, pp2)
665 #endif
666 
667 struct proc **pp1;
668 struct proc **pp2;
669 
670 {
671     register struct kinfo_proc *p1;
672     register struct kinfo_proc *p2;
673     register int result;
674     register pctcpu lresult;
675 
676     /* remove one level of indirection */
677     p1 = *(struct kinfo_proc **) pp1;
678     p2 = *(struct kinfo_proc **) pp2;
679 
680     ORDERKEY_PCTCPU
681     ORDERKEY_CPTICKS
682     ORDERKEY_STATE
683     ORDERKEY_PRIO
684     ORDERKEY_RSSIZE
685     ORDERKEY_MEM
686     ;
687 
688     return(result);
689 }
690 
691 #ifdef ORDER
692 /* compare routines */
693 int compare_size(), compare_res(), compare_time(), compare_prio();
694 
695 int (*proc_compares[])() = {
696     compare_cpu,
697     compare_size,
698     compare_res,
699     compare_time,
700     compare_prio,
701     NULL
702 };
703 
704 /* compare_size - the comparison function for sorting by total memory usage */
705 
706 int
707 compare_size(pp1, pp2)
708 
709 struct proc **pp1;
710 struct proc **pp2;
711 
712 {
713     register struct kinfo_proc *p1;
714     register struct kinfo_proc *p2;
715     register int result;
716     register pctcpu lresult;
717 
718     /* remove one level of indirection */
719     p1 = *(struct kinfo_proc **) pp1;
720     p2 = *(struct kinfo_proc **) pp2;
721 
722     ORDERKEY_MEM
723     ORDERKEY_RSSIZE
724     ORDERKEY_PCTCPU
725     ORDERKEY_CPTICKS
726     ORDERKEY_STATE
727     ORDERKEY_PRIO
728     ;
729 
730     return(result);
731 }
732 
733 /* compare_res - the comparison function for sorting by resident set size */
734 
735 int
736 compare_res(pp1, pp2)
737 
738 struct proc **pp1;
739 struct proc **pp2;
740 
741 {
742     register struct kinfo_proc *p1;
743     register struct kinfo_proc *p2;
744     register int result;
745     register pctcpu lresult;
746 
747     /* remove one level of indirection */
748     p1 = *(struct kinfo_proc **) pp1;
749     p2 = *(struct kinfo_proc **) pp2;
750 
751     ORDERKEY_RSSIZE
752     ORDERKEY_MEM
753     ORDERKEY_PCTCPU
754     ORDERKEY_CPTICKS
755     ORDERKEY_STATE
756     ORDERKEY_PRIO
757     ;
758 
759     return(result);
760 }
761 
762 /* compare_time - the comparison function for sorting by total cpu time */
763 
764 int
765 compare_time(pp1, pp2)
766 
767 struct proc **pp1;
768 struct proc **pp2;
769 
770 {
771     register struct kinfo_proc *p1;
772     register struct kinfo_proc *p2;
773     register int result;
774     register pctcpu lresult;
775 
776     /* remove one level of indirection */
777     p1 = *(struct kinfo_proc **) pp1;
778     p2 = *(struct kinfo_proc **) pp2;
779 
780     ORDERKEY_CPTICKS
781     ORDERKEY_PCTCPU
782     ORDERKEY_STATE
783     ORDERKEY_PRIO
784     ORDERKEY_RSSIZE
785     ORDERKEY_MEM
786     ;
787 
788       return(result);
789   }
790 
791 /* compare_prio - the comparison function for sorting by cpu percentage */
792 
793 int
794 compare_prio(pp1, pp2)
795 
796 struct proc **pp1;
797 struct proc **pp2;
798 
799 {
800     register struct kinfo_proc *p1;
801     register struct kinfo_proc *p2;
802     register int result;
803     register pctcpu lresult;
804 
805     /* remove one level of indirection */
806     p1 = *(struct kinfo_proc **) pp1;
807     p2 = *(struct kinfo_proc **) pp2;
808 
809     ORDERKEY_PRIO
810     ORDERKEY_CPTICKS
811     ORDERKEY_PCTCPU
812     ORDERKEY_STATE
813     ORDERKEY_RSSIZE
814     ORDERKEY_MEM
815     ;
816 
817     return(result);
818 }
819 #endif
820 
821 /*
822  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
823  *		the process does not exist.
824  *		It is EXTREMLY IMPORTANT that this function work correctly.
825  *		If top runs setuid root (as in SVR4), then this function
826  *		is the only thing that stands in the way of a serious
827  *		security problem.  It validates requests for the "kill"
828  *		and "renice" commands.
829  */
830 
831 int proc_owner(pid)
832 
833 int pid;
834 
835 {
836     register int cnt;
837     register struct kinfo_proc **prefp;
838     register struct kinfo_proc *pp;
839 
840     prefp = pref;
841     cnt = pref_len;
842     while (--cnt >= 0)
843     {
844 	pp = *prefp++;
845 	if (pp->ki_pid == (pid_t)pid)
846 	{
847 	    return((int)pp->ki_ruid);
848 	}
849     }
850     return(-1);
851 }
852 
853 int
854 swapmode(retavail, retfree)
855 	int *retavail;
856 	int *retfree;
857 {
858 	int n;
859 	int pagesize = getpagesize();
860 	struct kvm_swap swapary[1];
861 
862 	*retavail = 0;
863 	*retfree = 0;
864 
865 #define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
866 
867 	n = kvm_getswapinfo(kd, swapary, 1, 0);
868 	if (n < 0 || swapary[0].ksw_total == 0)
869 		return(0);
870 
871 	*retavail = CONVERT(swapary[0].ksw_total);
872 	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
873 
874 	n = (int)((double)swapary[0].ksw_used * 100.0 /
875 	    (double)swapary[0].ksw_total);
876 	return(n);
877 }
878 
879