xref: /freebsd/usr.bin/top/machine.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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/file.h>
41 #include <sys/time.h>
42 #include <sys/proc.h>
43 #include <sys/user.h>
44 #include <sys/vmmeter.h>
45 #include <sys/resource.h>
46 #include <sys/rtprio.h>
47 
48 /* Swap */
49 #include <stdlib.h>
50 
51 #include <unistd.h>
52 #include <osreldate.h> /* for changes in kernel structures */
53 
54 #include "top.h"
55 #include "machine.h"
56 #include "screen.h"
57 #include "utils.h"
58 
59 static void getsysctl(char *, void *, size_t);
60 
61 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
62 
63 extern char* printable(char *);
64 int swapmode(int *retavail, int *retfree);
65 static int smpmode;
66 static int namelength;
67 static int cmdlengthdelta;
68 
69 /* Prototypes for top internals */
70 void quit(int);
71 
72 /* get_process_info passes back a handle.  This is what it looks like: */
73 
74 struct handle
75 {
76     struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
77     int remaining;		/* number of pointers remaining */
78 };
79 
80 /* declarations for load_avg */
81 #include "loadavg.h"
82 
83 /* define what weighted cpu is.  */
84 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
85 			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
86 
87 /* what we consider to be process size: */
88 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
89 
90 /* definitions for indices in the nlist array */
91 
92 /*
93  *  These definitions control the format of the per-process area
94  */
95 
96 static char smp_header[] =
97   "  PID %-*.*s PRI NICE   SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
98 
99 #define smp_Proc_format \
100 	"%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
101 
102 static char up_header[] =
103   "  PID %-*.*s PRI NICE   SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
104 
105 #define up_Proc_format \
106 	"%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
107 
108 
109 
110 /* process state names for the "STATE" column of the display */
111 /* the extra nulls in the string "run" are for adding a slash and
112    the processor number when needed */
113 
114 char *state_abbrev[] =
115 {
116     "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
117 };
118 
119 
120 static kvm_t *kd;
121 
122 /* values that we stash away in _init and use in later routines */
123 
124 static double logcpu;
125 
126 /* these are retrieved from the kernel in _init */
127 
128 static load_avg  ccpu;
129 
130 /* these are used in the get_ functions */
131 
132 static int lastpid;
133 
134 /* these are for calculating cpu state percentages */
135 
136 static long cp_time[CPUSTATES];
137 static long cp_old[CPUSTATES];
138 static long cp_diff[CPUSTATES];
139 
140 /* these are for detailing the process states */
141 
142 int process_states[8];
143 char *procstatenames[] = {
144     "", " starting, ", " running, ", " sleeping, ", " stopped, ",
145     " zombie, ", " waiting, ", " lock, ",
146     NULL
147 };
148 
149 /* these are for detailing the cpu states */
150 
151 int cpu_states[CPUSTATES];
152 char *cpustatenames[] = {
153     "user", "nice", "system", "interrupt", "idle", NULL
154 };
155 
156 /* these are for detailing the memory statistics */
157 
158 int memory_stats[7];
159 char *memorynames[] = {
160     "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
161     NULL
162 };
163 
164 int swap_stats[7];
165 char *swapnames[] = {
166 /*   0           1            2           3            4       5 */
167     "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
168     NULL
169 };
170 
171 
172 /* these are for keeping track of the proc array */
173 
174 static int nproc;
175 static int onproc = -1;
176 static int pref_len;
177 static struct kinfo_proc *pbase;
178 static struct kinfo_proc **pref;
179 
180 /* these are for getting the memory statistics */
181 
182 static int pageshift;		/* log base 2 of the pagesize */
183 
184 /* define pagetok in terms of pageshift */
185 
186 #define pagetok(size) ((size) << pageshift)
187 
188 /* useful externals */
189 long percentages();
190 
191 #ifdef ORDER
192 /* sorting orders. first is default */
193 char *ordernames[] = {
194     "cpu", "size", "res", "time", "pri", NULL
195 };
196 #endif
197 
198 int
199 machine_init(statics)
200 
201 struct statics *statics;
202 
203 {
204     register int pagesize;
205     size_t modelen;
206     struct passwd *pw;
207 
208     modelen = sizeof(smpmode);
209     if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
210          sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
211 	modelen != sizeof(smpmode))
212 	    smpmode = 0;
213 
214     while ((pw = getpwent()) != NULL) {
215 	if (strlen(pw->pw_name) > namelength)
216 	    namelength = strlen(pw->pw_name);
217     }
218     if (namelength < 8)
219 	namelength = 8;
220     if (smpmode && namelength > 13)
221 	namelength = 13;
222     else if (namelength > 15)
223 	namelength = 15;
224 
225     if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, "kvm_open")) == NULL)
226 	return -1;
227 
228     GETSYSCTL("kern.ccpu", ccpu);
229 
230     /* this is used in calculating WCPU -- calculate it ahead of time */
231     logcpu = log(loaddouble(ccpu));
232 
233     pbase = NULL;
234     pref = NULL;
235     nproc = 0;
236     onproc = -1;
237     /* get the page size with "getpagesize" and calculate pageshift from it */
238     pagesize = getpagesize();
239     pageshift = 0;
240     while (pagesize > 1)
241     {
242 	pageshift++;
243 	pagesize >>= 1;
244     }
245 
246     /* we only need the amount of log(2)1024 for our conversion */
247     pageshift -= LOG1024;
248 
249     /* fill in the statics information */
250     statics->procstate_names = procstatenames;
251     statics->cpustate_names = cpustatenames;
252     statics->memory_names = memorynames;
253     statics->swap_names = swapnames;
254 #ifdef ORDER
255     statics->order_names = ordernames;
256 #endif
257 
258     /* all done! */
259     return(0);
260 }
261 
262 char *format_header(uname_field)
263 
264 register char *uname_field;
265 
266 {
267     static char Header[128];
268 
269     snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
270 	     namelength, namelength, uname_field);
271 
272     cmdlengthdelta = strlen(Header) - 7;
273 
274     return Header;
275 }
276 
277 static int swappgsin = -1;
278 static int swappgsout = -1;
279 extern struct timeval timeout;
280 
281 void
282 get_system_info(si)
283 
284 struct system_info *si;
285 
286 {
287     long total;
288     struct loadavg sysload;
289     int mib[2];
290     struct timeval boottime;
291     size_t bt_size;
292 
293     /* get the cp_time array */
294     GETSYSCTL("kern.cp_time", cp_time);
295     GETSYSCTL("vm.loadavg", sysload);
296     GETSYSCTL("kern.lastpid", lastpid);
297 
298     /* convert load averages to doubles */
299     {
300 	register int i;
301 	register double *infoloadp;
302 
303 	infoloadp = si->load_avg;
304 	for (i = 0; i < 3; i++)
305 	{
306 #ifdef notyet
307 	    *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
308 #endif
309 	    *infoloadp++ = loaddouble(sysload.ldavg[i]);
310 	}
311     }
312 
313     /* convert cp_time counts to percentages */
314     total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
315 
316     /* sum memory & swap statistics */
317     {
318 	static unsigned int swap_delay = 0;
319 	static int swapavail = 0;
320 	static int swapfree = 0;
321 	static int bufspace = 0;
322 	static int nspgsin, nspgsout;
323 
324 	GETSYSCTL("vfs.bufspace", bufspace);
325 	GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
326 	GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
327 	GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
328 	GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
329 	GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
330 	GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
331 	GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
332 	/* convert memory stats to Kbytes */
333 	memory_stats[0] = pagetok(memory_stats[0]);
334 	memory_stats[1] = pagetok(memory_stats[1]);
335 	memory_stats[2] = pagetok(memory_stats[2]);
336 	memory_stats[3] = pagetok(memory_stats[3]);
337 	memory_stats[4] = bufspace / 1024;
338 	memory_stats[5] = pagetok(memory_stats[5]);
339 	memory_stats[6] = -1;
340 
341 	/* first interval */
342         if (swappgsin < 0) {
343 	    swap_stats[4] = 0;
344 	    swap_stats[5] = 0;
345 	}
346 
347 	/* compute differences between old and new swap statistic */
348 	else {
349 	    swap_stats[4] = pagetok(((nspgsin - swappgsin)));
350 	    swap_stats[5] = pagetok(((nspgsout - swappgsout)));
351 	}
352 
353         swappgsin = nspgsin;
354 	swappgsout = nspgsout;
355 
356 	/* call CPU heavy swapmode() only for changes */
357         if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
358 	    swap_stats[3] = swapmode(&swapavail, &swapfree);
359 	    swap_stats[0] = swapavail;
360 	    swap_stats[1] = swapavail - swapfree;
361 	    swap_stats[2] = swapfree;
362 	}
363         swap_delay = 1;
364 	swap_stats[6] = -1;
365     }
366 
367     /* set arrays and strings */
368     si->cpustates = cpu_states;
369     si->memory = memory_stats;
370     si->swap = swap_stats;
371 
372 
373     if(lastpid > 0) {
374 	si->last_pid = lastpid;
375     } else {
376 	si->last_pid = -1;
377     }
378 
379     /*
380      * Print how long system has been up.
381      * (Found by looking getting "boottime" from the kernel)
382      */
383     mib[0] = CTL_KERN;
384     mib[1] = KERN_BOOTTIME;
385     bt_size = sizeof(boottime);
386     if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
387 	boottime.tv_sec != 0) {
388 	si->boottime = boottime;
389     } else {
390 	si->boottime.tv_sec = -1;
391     }
392 }
393 
394 static struct handle handle;
395 
396 caddr_t get_process_info(si, sel, compare)
397 
398 struct system_info *si;
399 struct process_select *sel;
400 int (*compare)();
401 
402 {
403     register int i;
404     register int total_procs;
405     register int active_procs;
406     register struct kinfo_proc **prefp;
407     register struct kinfo_proc *pp;
408 
409     /* these are copied out of sel for speed */
410     int show_idle;
411     int show_self;
412     int show_system;
413     int show_uid;
414     int show_command;
415 
416 
417     pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
418 	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