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