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