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