xref: /freebsd/usr.bin/top/machine.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
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, KERN_PROC_ALL, 0, &nproc);
418     if (nproc > onproc)
419 	pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
420 		* (onproc = nproc));
421     if (pref == NULL || pbase == NULL) {
422 	(void) fprintf(stderr, "top: Out of memory.\n");
423 	quit(23);
424     }
425     /* get a pointer to the states summary array */
426     si->procstates = process_states;
427 
428     /* set up flags which define what we are going to select */
429     show_idle = sel->idle;
430     show_self = sel->self;
431     show_system = sel->system;
432     show_uid = sel->uid != -1;
433     show_command = sel->command != NULL;
434 
435     /* count up process states and get pointers to interesting procs */
436     total_procs = 0;
437     active_procs = 0;
438     memset((char *)process_states, 0, sizeof(process_states));
439     prefp = pref;
440     for (pp = pbase, i = 0; i < nproc; pp++, i++)
441     {
442 	/*
443 	 *  Place pointers to each valid proc structure in pref[].
444 	 *  Process slots that are actually in use have a non-zero
445 	 *  status field.  Processes with P_SYSTEM set are system
446 	 *  processes---these get ignored unless show_sysprocs is set.
447 	 */
448 	if (pp->ki_stat != 0 &&
449 	    (show_self != pp->ki_pid) &&
450 	    (show_system || ((pp->ki_flag & P_SYSTEM) == 0)))
451 	{
452 	    total_procs++;
453 	    process_states[(unsigned char) pp->ki_stat]++;
454 	    if ((pp->ki_stat != SZOMB) &&
455 		(show_idle || (pp->ki_pctcpu != 0) ||
456 		 (pp->ki_stat == SRUN)) &&
457 		(!show_uid || pp->ki_ruid == (uid_t)sel->uid))
458 	    {
459 		*prefp++ = pp;
460 		active_procs++;
461 	    }
462 	}
463     }
464 
465     /* if requested, sort the "interesting" processes */
466     if (compare != NULL)
467     {
468 	qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
469     }
470 
471     /* remember active and total counts */
472     si->p_total = total_procs;
473     si->p_active = pref_len = active_procs;
474 
475     /* pass back a handle */
476     handle.next_proc = pref;
477     handle.remaining = active_procs;
478     return((caddr_t)&handle);
479 }
480 
481 char fmt[128];		/* static area where result is built */
482 
483 char *format_next_process(handle, get_userid)
484 
485 caddr_t handle;
486 char *(*get_userid)();
487 
488 {
489     register struct kinfo_proc *pp;
490     register long cputime;
491     register double pct;
492     struct handle *hp;
493     char status[16];
494     int state;
495 
496     /* find and remember the next proc structure */
497     hp = (struct handle *)handle;
498     pp = *(hp->next_proc++);
499     hp->remaining--;
500 
501     /* get the process's command name */
502     if ((pp->ki_sflag & PS_INMEM) == 0) {
503 	/*
504 	 * Print swapped processes as <pname>
505 	 */
506 	char *comm = pp->ki_comm;
507 #define COMSIZ sizeof(pp->ki_comm)
508 	char buf[COMSIZ];
509 	(void) strncpy(buf, comm, COMSIZ);
510 	comm[0] = '<';
511 	(void) strncpy(&comm[1], buf, COMSIZ - 2);
512 	comm[COMSIZ - 2] = '\0';
513 	(void) strncat(comm, ">", COMSIZ - 1);
514 	comm[COMSIZ - 1] = '\0';
515     }
516 
517     /*
518      * Convert the process's runtime from microseconds to seconds.  This
519      * time includes the interrupt time although that is not wanted here.
520      * ps(1) is similarly sloppy.
521      */
522     cputime = (pp->ki_runtime + 500000) / 1000000;
523 
524     /* calculate the base for cpu percentages */
525     pct = pctdouble(pp->ki_pctcpu);
526 
527     /* generate "STATE" field */
528     switch (state = pp->ki_stat) {
529 	case SRUN:
530 	    if (smpmode && pp->ki_oncpu != 0xff)
531 		sprintf(status, "CPU%d", pp->ki_oncpu);
532 	    else
533 		strcpy(status, "RUN");
534 	    break;
535 	case SLOCK:
536 	    if (pp->ki_kiflag & KI_LOCKBLOCK) {
537 		sprintf(status, "*%.6s", pp->ki_lockname);
538 	        break;
539 	    }
540 	    /* fall through */
541 	case SSLEEP:
542 	    if (pp->ki_wmesg != NULL) {
543 		sprintf(status, "%.6s", pp->ki_wmesg);
544 		break;
545 	    }
546 	    /* FALLTHROUGH */
547 	default:
548 
549 	    if (state >= 0 &&
550 	        state < sizeof(state_abbrev) / sizeof(*state_abbrev))
551 		    sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
552 	    else
553 		    sprintf(status, "?%5d", state);
554 	    break;
555     }
556 
557     /* format this entry */
558     sprintf(fmt,
559 	    smpmode ? smp_Proc_format : up_Proc_format,
560 	    pp->ki_pid,
561 	    namelength, namelength,
562 	    (*get_userid)(pp->ki_ruid),
563 	    pp->ki_pri.pri_level - PZERO,
564 
565 	    /*
566 	     * normal time      -> nice value -20 - +20
567 	     * real time 0 - 31 -> nice value -52 - -21
568 	     * idle time 0 - 31 -> nice value +21 - +52
569 	     */
570 	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
571 	    	pp->ki_nice - NZERO :
572 	    	(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
573 		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
574 		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
575 	    format_k2(PROCSIZE(pp)),
576 	    format_k2(pagetok(pp->ki_rssize)),
577 	    status,
578 	    smpmode ? pp->ki_lastcpu : 0,
579 	    format_time(cputime),
580 	    100.0 * weighted_cpu(pct, pp),
581 	    100.0 * pct,
582 	    screen_width > cmdlengthdelta ?
583 		screen_width - cmdlengthdelta :
584 		0,
585 	    printable(pp->ki_comm));
586 
587     /* return the result */
588     return(fmt);
589 }
590 
591 static void getsysctl (name, ptr, len)
592 
593 char *name;
594 void *ptr;
595 size_t len;
596 
597 {
598     size_t nlen = len;
599     if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
600 	    fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
601 		strerror(errno));
602 	    quit(23);
603     }
604     if (nlen != len) {
605 	    fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
606 		(unsigned long)len, (unsigned long)nlen);
607 	    quit(23);
608     }
609 }
610 
611 /* comparison routines for qsort */
612 
613 /*
614  *  proc_compare - comparison function for "qsort"
615  *	Compares the resource consumption of two processes using five
616  *  	distinct keys.  The keys (in descending order of importance) are:
617  *  	percent cpu, cpu ticks, state, resident set size, total virtual
618  *  	memory usage.  The process states are ordered as follows (from least
619  *  	to most important):  WAIT, zombie, sleep, stop, start, run.  The
620  *  	array declaration below maps a process state index into a number
621  *  	that reflects this ordering.
622  */
623 
624 static unsigned char sorted_state[] =
625 {
626     0,	/* not used		*/
627     3,	/* sleep		*/
628     1,	/* ABANDONED (WAIT)	*/
629     6,	/* run			*/
630     5,	/* start		*/
631     2,	/* zombie		*/
632     4	/* stop			*/
633 };
634 
635 
636 #define ORDERKEY_PCTCPU \
637   if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
638      (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
639 
640 #define ORDERKEY_CPTICKS \
641   if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
642                 p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
643 
644 #define ORDERKEY_STATE \
645   if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
646                 sorted_state[(unsigned char) p1->ki_stat]) == 0)
647 
648 #define ORDERKEY_PRIO \
649   if ((result = p2->ki_pri.pri_level - p1->ki_pri.pri_level) == 0)
650 
651 #define ORDERKEY_RSSIZE \
652   if ((result = p2->ki_rssize - p1->ki_rssize) == 0)
653 
654 #define ORDERKEY_MEM \
655   if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
656 
657 /* compare_cpu - the comparison function for sorting by cpu percentage */
658 
659 int
660 #ifdef ORDER
661 compare_cpu(pp1, pp2)
662 #else
663 proc_compare(pp1, pp2)
664 #endif
665 
666 struct proc **pp1;
667 struct proc **pp2;
668 
669 {
670     register struct kinfo_proc *p1;
671     register struct kinfo_proc *p2;
672     register int result;
673     register pctcpu lresult;
674 
675     /* remove one level of indirection */
676     p1 = *(struct kinfo_proc **) pp1;
677     p2 = *(struct kinfo_proc **) pp2;
678 
679     ORDERKEY_PCTCPU
680     ORDERKEY_CPTICKS
681     ORDERKEY_STATE
682     ORDERKEY_PRIO
683     ORDERKEY_RSSIZE
684     ORDERKEY_MEM
685     ;
686 
687     return(result);
688 }
689 
690 #ifdef ORDER
691 /* compare routines */
692 int compare_size(), compare_res(), compare_time(), compare_prio();
693 
694 int (*proc_compares[])() = {
695     compare_cpu,
696     compare_size,
697     compare_res,
698     compare_time,
699     compare_prio,
700     NULL
701 };
702 
703 /* compare_size - the comparison function for sorting by total memory usage */
704 
705 int
706 compare_size(pp1, pp2)
707 
708 struct proc **pp1;
709 struct proc **pp2;
710 
711 {
712     register struct kinfo_proc *p1;
713     register struct kinfo_proc *p2;
714     register int result;
715     register pctcpu lresult;
716 
717     /* remove one level of indirection */
718     p1 = *(struct kinfo_proc **) pp1;
719     p2 = *(struct kinfo_proc **) pp2;
720 
721     ORDERKEY_MEM
722     ORDERKEY_RSSIZE
723     ORDERKEY_PCTCPU
724     ORDERKEY_CPTICKS
725     ORDERKEY_STATE
726     ORDERKEY_PRIO
727     ;
728 
729     return(result);
730 }
731 
732 /* compare_res - the comparison function for sorting by resident set size */
733 
734 int
735 compare_res(pp1, pp2)
736 
737 struct proc **pp1;
738 struct proc **pp2;
739 
740 {
741     register struct kinfo_proc *p1;
742     register struct kinfo_proc *p2;
743     register int result;
744     register pctcpu lresult;
745 
746     /* remove one level of indirection */
747     p1 = *(struct kinfo_proc **) pp1;
748     p2 = *(struct kinfo_proc **) pp2;
749 
750     ORDERKEY_RSSIZE
751     ORDERKEY_MEM
752     ORDERKEY_PCTCPU
753     ORDERKEY_CPTICKS
754     ORDERKEY_STATE
755     ORDERKEY_PRIO
756     ;
757 
758     return(result);
759 }
760 
761 /* compare_time - the comparison function for sorting by total cpu time */
762 
763 int
764 compare_time(pp1, pp2)
765 
766 struct proc **pp1;
767 struct proc **pp2;
768 
769 {
770     register struct kinfo_proc *p1;
771     register struct kinfo_proc *p2;
772     register int result;
773     register pctcpu lresult;
774 
775     /* remove one level of indirection */
776     p1 = *(struct kinfo_proc **) pp1;
777     p2 = *(struct kinfo_proc **) pp2;
778 
779     ORDERKEY_CPTICKS
780     ORDERKEY_PCTCPU
781     ORDERKEY_STATE
782     ORDERKEY_PRIO
783     ORDERKEY_RSSIZE
784     ORDERKEY_MEM
785     ;
786 
787       return(result);
788   }
789 
790 /* compare_prio - the comparison function for sorting by cpu percentage */
791 
792 int
793 compare_prio(pp1, pp2)
794 
795 struct proc **pp1;
796 struct proc **pp2;
797 
798 {
799     register struct kinfo_proc *p1;
800     register struct kinfo_proc *p2;
801     register int result;
802     register pctcpu lresult;
803 
804     /* remove one level of indirection */
805     p1 = *(struct kinfo_proc **) pp1;
806     p2 = *(struct kinfo_proc **) pp2;
807 
808     ORDERKEY_PRIO
809     ORDERKEY_CPTICKS
810     ORDERKEY_PCTCPU
811     ORDERKEY_STATE
812     ORDERKEY_RSSIZE
813     ORDERKEY_MEM
814     ;
815 
816     return(result);
817 }
818 #endif
819 
820 /*
821  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
822  *		the process does not exist.
823  *		It is EXTREMLY IMPORTANT that this function work correctly.
824  *		If top runs setuid root (as in SVR4), then this function
825  *		is the only thing that stands in the way of a serious
826  *		security problem.  It validates requests for the "kill"
827  *		and "renice" commands.
828  */
829 
830 int proc_owner(pid)
831 
832 int pid;
833 
834 {
835     register int cnt;
836     register struct kinfo_proc **prefp;
837     register struct kinfo_proc *pp;
838 
839     prefp = pref;
840     cnt = pref_len;
841     while (--cnt >= 0)
842     {
843 	pp = *prefp++;
844 	if (pp->ki_pid == (pid_t)pid)
845 	{
846 	    return((int)pp->ki_ruid);
847 	}
848     }
849     return(-1);
850 }
851 
852 int
853 swapmode(retavail, retfree)
854 	int *retavail;
855 	int *retfree;
856 {
857 	int n;
858 	int pagesize = getpagesize();
859 	struct kvm_swap swapary[1];
860 
861 	*retavail = 0;
862 	*retfree = 0;
863 
864 #define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
865 
866 	n = kvm_getswapinfo(kd, swapary, 1, 0);
867 	if (n < 0 || swapary[0].ksw_total == 0)
868 		return(0);
869 
870 	*retavail = CONVERT(swapary[0].ksw_total);
871 	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
872 
873 	n = (int)((double)swapary[0].ksw_used * 100.0 /
874 	    (double)swapary[0].ksw_total);
875 	return(n);
876 }
877 
878