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