machine.c revision 45936
1228072Sbapt/*
2228072Sbapt * top - a top users display for Unix
3228072Sbapt *
4228072Sbapt * SYNOPSIS:  For FreeBSD-2.x system
5228072Sbapt *
6250125Sjkim * DESCRIPTION:
7250125Sjkim * Originally written for BSD4.4 system by Christos Zoulas.
8250125Sjkim * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9250125Sjkim * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10250125Sjkim *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
11250125Sjkim *
12250125Sjkim * This is the machine-dependent module for FreeBSD 2.2
13250125Sjkim * Works for:
14250125Sjkim *	FreeBSD 2.2, and probably FreeBSD 2.1.x
15250125Sjkim *
16250125Sjkim * LIBS: -lkvm
17250125Sjkim *
18250125Sjkim * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
19250125Sjkim *          Steven Wallace  <swallace@freebsd.org>
20250125Sjkim *          Wolfram Schneider <wosch@FreeBSD.org>
21250125Sjkim *
22250125Sjkim * $Id: machine.c,v 1.23 1999/03/07 06:55:47 bde Exp $
23250125Sjkim */
24250125Sjkim
25250125Sjkim
26250125Sjkim#include <sys/time.h>
27250125Sjkim#include <sys/types.h>
28250125Sjkim#include <sys/signal.h>
29250125Sjkim#include <sys/param.h>
30250125Sjkim
31250125Sjkim#include "os.h"
32250125Sjkim#include <stdio.h>
33250125Sjkim#include <nlist.h>
34250125Sjkim#include <math.h>
35250125Sjkim#include <kvm.h>
36228072Sbapt#include <pwd.h>
37228072Sbapt#include <sys/errno.h>
38228072Sbapt#include <sys/sysctl.h>
39228072Sbapt#include <sys/dkstat.h>
40228072Sbapt#include <sys/file.h>
41228072Sbapt#include <sys/time.h>
42228072Sbapt#include <sys/proc.h>
43228072Sbapt#include <sys/user.h>
44228072Sbapt#include <sys/vmmeter.h>
45228072Sbapt#include <sys/resource.h>
46228072Sbapt#include <sys/rtprio.h>
47228072Sbapt
48228072Sbapt/* Swap */
49228072Sbapt#include <stdlib.h>
50228072Sbapt#include <sys/rlist.h>
51228072Sbapt#include <sys/conf.h>
52228072Sbapt
53228072Sbapt#include <osreldate.h> /* for changes in kernel structures */
54228072Sbapt
55228072Sbapt#include "top.h"
56228072Sbapt#include "machine.h"
57228072Sbapt
58228072Sbaptstatic int check_nlist __P((struct nlist *));
59228072Sbaptstatic int getkval __P((unsigned long, int *, int, char *));
60228072Sbaptextern char* printable __P((char *));
61228072Sbaptint swapmode __P((int *retavail, int *retfree));
62228072Sbaptstatic int smpmode;
63228072Sbaptstatic int namelength;
64228072Sbaptstatic int cmdlength;
65228072Sbapt
66228072Sbapt
67228072Sbapt/* get_process_info passes back a handle.  This is what it looks like: */
68228072Sbapt
69228072Sbaptstruct handle
70228072Sbapt{
71228072Sbapt    struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
72228072Sbapt    int remaining;		/* number of pointers remaining */
73228072Sbapt};
74228072Sbapt
75228072Sbapt/* declarations for load_avg */
76228072Sbapt#include "loadavg.h"
77228072Sbapt
78228072Sbapt#define PP(pp, field) ((pp)->kp_proc . field)
79228072Sbapt#define EP(pp, field) ((pp)->kp_eproc . field)
80228072Sbapt#define VP(pp, field) ((pp)->kp_eproc.e_vm . field)
81228072Sbapt
82228072Sbapt/* define what weighted cpu is.  */
83228072Sbapt#define weighted_cpu(pct, pp) (PP((pp), p_swtime) == 0 ? 0.0 : \
84228072Sbapt			 ((pct) / (1.0 - exp(PP((pp), p_swtime) * logcpu))))
85228072Sbapt
86228072Sbapt/* what we consider to be process size: */
87228072Sbapt#define PROCSIZE(pp) (VP((pp), vm_map.size) / 1024)
88228072Sbapt
89228072Sbapt/* definitions for indices in the nlist array */
90228072Sbapt
91228072Sbaptstatic struct nlist nlst[] = {
92228072Sbapt#define X_CCPU		0
93228072Sbapt    { "_ccpu" },
94228072Sbapt#define X_CP_TIME	1
95228072Sbapt    { "_cp_time" },
96228072Sbapt#define X_AVENRUN	2
97228072Sbapt    { "_averunnable" },
98228072Sbapt
99228072Sbapt#define X_BUFSPACE	3
100228072Sbapt	{ "_bufspace" },	/* K in buffer cache */
101228072Sbapt#define X_CNT           4
102228072Sbapt    { "_cnt" },		        /* struct vmmeter cnt */
103228072Sbapt
104228072Sbapt/* Last pid */
105228072Sbapt#define X_LASTPID	5
106228072Sbapt    { "_nextpid" },
107228072Sbapt    { 0 }
108228072Sbapt};
109228072Sbapt
110228072Sbapt/*
111228072Sbapt *  These definitions control the format of the per-process area
112228072Sbapt */
113228072Sbapt
114228072Sbaptstatic char smp_header[] =
115228072Sbapt  "  PID %-*.*s PRI NICE  SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
116228072Sbapt
117228072Sbapt#define smp_Proc_format \
118228072Sbapt	"%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
119228072Sbapt
120228072Sbaptstatic char up_header[] =
121228072Sbapt  "  PID %-*.*s PRI NICE  SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
122228072Sbapt
123228072Sbapt#define up_Proc_format \
124228072Sbapt	"%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
125228072Sbapt
126228072Sbapt
127228072Sbapt
128228072Sbapt/* process state names for the "STATE" column of the display */
129228072Sbapt/* the extra nulls in the string "run" are for adding a slash and
130228072Sbapt   the processor number when needed */
131228072Sbapt
132228072Sbaptchar *state_abbrev[] =
133228072Sbapt{
134228072Sbapt    "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB",
135228072Sbapt};
136228072Sbapt
137228072Sbapt
138228072Sbaptstatic kvm_t *kd;
139228072Sbapt
140228072Sbapt/* values that we stash away in _init and use in later routines */
141228072Sbapt
142228072Sbaptstatic double logcpu;
143228072Sbapt
144228072Sbapt/* these are retrieved from the kernel in _init */
145228072Sbapt
146228072Sbaptstatic load_avg  ccpu;
147228072Sbapt
148228072Sbapt/* these are offsets obtained via nlist and used in the get_ functions */
149228072Sbapt
150228072Sbaptstatic unsigned long cp_time_offset;
151228072Sbaptstatic unsigned long avenrun_offset;
152228072Sbaptstatic unsigned long lastpid_offset;
153228072Sbaptstatic long lastpid;
154228072Sbaptstatic unsigned long cnt_offset;
155228072Sbaptstatic unsigned long bufspace_offset;
156228072Sbaptstatic long cnt;
157228072Sbapt
158228072Sbapt/* these are for calculating cpu state percentages */
159228072Sbapt
160228072Sbaptstatic long cp_time[CPUSTATES];
161228072Sbaptstatic long cp_old[CPUSTATES];
162228072Sbaptstatic long cp_diff[CPUSTATES];
163228072Sbapt
164228072Sbapt/* these are for detailing the process states */
165228072Sbapt
166228072Sbaptint process_states[6];
167228072Sbaptchar *procstatenames[] = {
168228072Sbapt    "", " starting, ", " running, ", " sleeping, ", " stopped, ",
169228072Sbapt    " zombie, ",
170228072Sbapt    NULL
171228072Sbapt};
172228072Sbapt
173228072Sbapt/* these are for detailing the cpu states */
174228072Sbapt
175228072Sbaptint cpu_states[CPUSTATES];
176228072Sbaptchar *cpustatenames[] = {
177228072Sbapt    "user", "nice", "system", "interrupt", "idle", NULL
178228072Sbapt};
179228072Sbapt
180228072Sbapt/* these are for detailing the memory statistics */
181228072Sbapt
182228072Sbaptint memory_stats[7];
183228072Sbaptchar *memorynames[] = {
184228072Sbapt    "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
185228072Sbapt    NULL
186228072Sbapt};
187228072Sbapt
188228072Sbaptint swap_stats[7];
189228072Sbaptchar *swapnames[] = {
190228072Sbapt/*   0           1            2           3            4       5 */
191228072Sbapt    "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
192228072Sbapt    NULL
193228072Sbapt};
194228072Sbapt
195228072Sbapt
196228072Sbapt/* these are for keeping track of the proc array */
197228072Sbapt
198228072Sbaptstatic int nproc;
199228072Sbaptstatic int onproc = -1;
200228072Sbaptstatic int pref_len;
201228072Sbaptstatic struct kinfo_proc *pbase;
202228072Sbaptstatic struct kinfo_proc **pref;
203228072Sbapt
204228072Sbapt/* these are for getting the memory statistics */
205228072Sbapt
206228072Sbaptstatic int pageshift;		/* log base 2 of the pagesize */
207228072Sbapt
208228072Sbapt/* define pagetok in terms of pageshift */
209228072Sbapt
210228072Sbapt#define pagetok(size) ((size) << pageshift)
211228072Sbapt
212228072Sbapt/* useful externals */
213228072Sbaptlong percentages();
214228072Sbapt
215228072Sbapt#ifdef ORDER
216228072Sbapt/* sorting orders. first is default */
217228072Sbaptchar *ordernames[] = {
218228072Sbapt    "cpu", "size", "res", "time", "pri", NULL
219228072Sbapt};
220228072Sbapt#endif
221228072Sbapt
222228072Sbaptint
223228072Sbaptmachine_init(statics)
224228072Sbapt
225228072Sbaptstruct statics *statics;
226228072Sbapt
227228072Sbapt{
228228072Sbapt    register int i = 0;
229228072Sbapt    register int pagesize;
230228072Sbapt    int modelen;
231228072Sbapt    struct passwd *pw;
232228072Sbapt
233228072Sbapt    modelen = sizeof(smpmode);
234228072Sbapt    if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
235228072Sbapt         sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
236228072Sbapt	modelen != sizeof(smpmode))
237228072Sbapt	    smpmode = 0;
238228072Sbapt
239228072Sbapt    while ((pw = getpwent()) != NULL) {
240228072Sbapt	if (strlen(pw->pw_name) > namelength)
241228072Sbapt	    namelength = strlen(pw->pw_name);
242228072Sbapt    }
243228072Sbapt    if (namelength < 8)
244228072Sbapt	namelength = 8;
245228072Sbapt    if (namelength > 16)
246228072Sbapt	namelength = 16;
247228072Sbapt
248228072Sbapt    if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
249228072Sbapt	return -1;
250228072Sbapt
251228072Sbapt
252228072Sbapt    /* get the list of symbols we want to access in the kernel */
253228072Sbapt    (void) kvm_nlist(kd, nlst);
254228072Sbapt    if (nlst[0].n_type == 0)
255228072Sbapt    {
256228072Sbapt	fprintf(stderr, "top: nlist failed\n");
257228072Sbapt	return(-1);
258228072Sbapt    }
259228072Sbapt
260228072Sbapt    /* make sure they were all found */
261228072Sbapt    if (i > 0 && check_nlist(nlst) > 0)
262228072Sbapt    {
263228072Sbapt	return(-1);
264228072Sbapt    }
265228072Sbapt
266228072Sbapt    (void) getkval(nlst[X_CCPU].n_value,   (int *)(&ccpu),	sizeof(ccpu),
267228072Sbapt	    nlst[X_CCPU].n_name);
268228072Sbapt
269228072Sbapt    /* stash away certain offsets for later use */
270228072Sbapt    cp_time_offset = nlst[X_CP_TIME].n_value;
271228072Sbapt    avenrun_offset = nlst[X_AVENRUN].n_value;
272228072Sbapt    lastpid_offset =  nlst[X_LASTPID].n_value;
273228072Sbapt    cnt_offset = nlst[X_CNT].n_value;
274228072Sbapt    bufspace_offset = nlst[X_BUFSPACE].n_value;
275228072Sbapt
276228072Sbapt    /* this is used in calculating WCPU -- calculate it ahead of time */
277228072Sbapt    logcpu = log(loaddouble(ccpu));
278228072Sbapt
279228072Sbapt    pbase = NULL;
280228072Sbapt    pref = NULL;
281228072Sbapt    nproc = 0;
282228072Sbapt    onproc = -1;
283228072Sbapt    /* get the page size with "getpagesize" and calculate pageshift from it */
284228072Sbapt    pagesize = getpagesize();
285228072Sbapt    pageshift = 0;
286228072Sbapt    while (pagesize > 1)
287228072Sbapt    {
288228072Sbapt	pageshift++;
289228072Sbapt	pagesize >>= 1;
290228072Sbapt    }
291228072Sbapt
292228072Sbapt    /* we only need the amount of log(2)1024 for our conversion */
293228072Sbapt    pageshift -= LOG1024;
294228072Sbapt
295228072Sbapt    /* fill in the statics information */
296228072Sbapt    statics->procstate_names = procstatenames;
297228072Sbapt    statics->cpustate_names = cpustatenames;
298228072Sbapt    statics->memory_names = memorynames;
299228072Sbapt    statics->swap_names = swapnames;
300228072Sbapt#ifdef ORDER
301228072Sbapt    statics->order_names = ordernames;
302228072Sbapt#endif
303228072Sbapt
304228072Sbapt    /* all done! */
305228072Sbapt    return(0);
306228072Sbapt}
307228072Sbapt
308228072Sbaptchar *format_header(uname_field)
309228072Sbapt
310228072Sbaptregister char *uname_field;
311228072Sbapt
312228072Sbapt{
313228072Sbapt    register char *ptr;
314228072Sbapt    static char Header[128];
315228072Sbapt
316228072Sbapt    snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
317228072Sbapt	     namelength, namelength, uname_field);
318228072Sbapt
319228072Sbapt    cmdlength = 80 - strlen(Header) + 6;
320228072Sbapt
321228072Sbapt    return Header;
322228072Sbapt}
323228072Sbapt
324228072Sbaptstatic int swappgsin = -1;
325228072Sbaptstatic int swappgsout = -1;
326228072Sbaptextern struct timeval timeout;
327228072Sbapt
328228072Sbaptvoid
329228072Sbaptget_system_info(si)
330228072Sbapt
331228072Sbaptstruct system_info *si;
332228072Sbapt
333228072Sbapt{
334228072Sbapt    long total;
335228072Sbapt    load_avg avenrun[3];
336228072Sbapt    int mib[2];
337228072Sbapt    struct timeval boottime;
338228072Sbapt    size_t bt_size;
339228072Sbapt
340228072Sbapt    /* get the cp_time array */
341228072Sbapt    (void) getkval(cp_time_offset, (int *)cp_time, sizeof(cp_time),
342228072Sbapt		   nlst[X_CP_TIME].n_name);
343228072Sbapt    (void) getkval(avenrun_offset, (int *)avenrun, sizeof(avenrun),
344228072Sbapt		   nlst[X_AVENRUN].n_name);
345228072Sbapt
346228072Sbapt    (void) getkval(lastpid_offset, (int *)(&lastpid), sizeof(lastpid),
347228072Sbapt		   "!");
348228072Sbapt
349228072Sbapt    /* convert load averages to doubles */
350228072Sbapt    {
351228072Sbapt	register int i;
352228072Sbapt	register double *infoloadp;
353228072Sbapt	load_avg *avenrunp;
354228072Sbapt
355228072Sbapt#ifdef notyet
356228072Sbapt	struct loadavg sysload;
357228072Sbapt	int size;
358228072Sbapt	getkerninfo(KINFO_LOADAVG, &sysload, &size, 0);
359228072Sbapt#endif
360228072Sbapt
361228072Sbapt	infoloadp = si->load_avg;
362228072Sbapt	avenrunp = avenrun;
363228072Sbapt	for (i = 0; i < 3; i++)
364228072Sbapt	{
365228072Sbapt#ifdef notyet
366228072Sbapt	    *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
367228072Sbapt#endif
368228072Sbapt	    *infoloadp++ = loaddouble(*avenrunp++);
369228072Sbapt	}
370228072Sbapt    }
371228072Sbapt
372228072Sbapt    /* convert cp_time counts to percentages */
373228072Sbapt    total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
374228072Sbapt
375228072Sbapt    /* sum memory & swap statistics */
376228072Sbapt    {
377228072Sbapt	struct vmmeter sum;
378228072Sbapt	static unsigned int swap_delay = 0;
379228072Sbapt	static int swapavail = 0;
380228072Sbapt	static int swapfree = 0;
381228072Sbapt	static int bufspace = 0;
382228072Sbapt
383228072Sbapt        (void) getkval(cnt_offset, (int *)(&sum), sizeof(sum),
384228072Sbapt		   "_cnt");
385228072Sbapt        (void) getkval(bufspace_offset, (int *)(&bufspace), sizeof(bufspace),
386228072Sbapt		   "_bufspace");
387228072Sbapt
388228072Sbapt	/* convert memory stats to Kbytes */
389228072Sbapt	memory_stats[0] = pagetok(sum.v_active_count);
390228072Sbapt	memory_stats[1] = pagetok(sum.v_inactive_count);
391228072Sbapt	memory_stats[2] = pagetok(sum.v_wire_count);
392228072Sbapt	memory_stats[3] = pagetok(sum.v_cache_count);
393228072Sbapt	memory_stats[4] = bufspace / 1024;
394228072Sbapt	memory_stats[5] = pagetok(sum.v_free_count);
395228072Sbapt	memory_stats[6] = -1;
396228072Sbapt
397228072Sbapt	/* first interval */
398228072Sbapt        if (swappgsin < 0) {
399228072Sbapt	    swap_stats[4] = 0;
400228072Sbapt	    swap_stats[5] = 0;
401228072Sbapt	}
402228072Sbapt
403228072Sbapt	/* compute differences between old and new swap statistic */
404228072Sbapt	else {
405228072Sbapt	    swap_stats[4] = pagetok(((sum.v_swappgsin - swappgsin)));
406228072Sbapt	    swap_stats[5] = pagetok(((sum.v_swappgsout - swappgsout)));
407228072Sbapt	}
408228072Sbapt
409228072Sbapt        swappgsin = sum.v_swappgsin;
410228072Sbapt	swappgsout = sum.v_swappgsout;
411228072Sbapt
412228072Sbapt	/* call CPU heavy swapmode() only for changes */
413228072Sbapt        if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
414228072Sbapt	    swap_stats[3] = swapmode(&swapavail, &swapfree);
415228072Sbapt	    swap_stats[0] = swapavail;
416228072Sbapt	    swap_stats[1] = swapavail - swapfree;
417228072Sbapt	    swap_stats[2] = swapfree;
418228072Sbapt	}
419228072Sbapt        swap_delay = 1;
420228072Sbapt	swap_stats[6] = -1;
421228072Sbapt    }
422228072Sbapt
423228072Sbapt    /* set arrays and strings */
424228072Sbapt    si->cpustates = cpu_states;
425228072Sbapt    si->memory = memory_stats;
426228072Sbapt    si->swap = swap_stats;
427228072Sbapt
428228072Sbapt
429228072Sbapt    if(lastpid > 0) {
430228072Sbapt	si->last_pid = lastpid;
431228072Sbapt    } else {
432228072Sbapt	si->last_pid = -1;
433228072Sbapt    }
434228072Sbapt
435228072Sbapt    /*
436228072Sbapt     * Print how long system has been up.
437228072Sbapt     * (Found by looking getting "boottime" from the kernel)
438228072Sbapt     */
439228072Sbapt    mib[0] = CTL_KERN;
440228072Sbapt    mib[1] = KERN_BOOTTIME;
441228072Sbapt    bt_size = sizeof(boottime);
442228072Sbapt    if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
443228072Sbapt	boottime.tv_sec != 0) {
444228072Sbapt	si->boottime = boottime;
445228072Sbapt    } else {
446228072Sbapt	si->boottime.tv_sec = -1;
447228072Sbapt    }
448228072Sbapt}
449228072Sbapt
450228072Sbaptstatic struct handle handle;
451228072Sbapt
452228072Sbaptcaddr_t get_process_info(si, sel, compare)
453228072Sbapt
454228072Sbaptstruct system_info *si;
455228072Sbaptstruct process_select *sel;
456228072Sbaptint (*compare)();
457228072Sbapt
458228072Sbapt{
459228072Sbapt    register int i;
460228072Sbapt    register int total_procs;
461228072Sbapt    register int active_procs;
462228072Sbapt    register struct kinfo_proc **prefp;
463228072Sbapt    register struct kinfo_proc *pp;
464228072Sbapt
465228072Sbapt    /* these are copied out of sel for speed */
466228072Sbapt    int show_idle;
467228072Sbapt    int show_self;
468228072Sbapt    int show_system;
469228072Sbapt    int show_uid;
470228072Sbapt    int show_command;
471228072Sbapt
472228072Sbapt
473228072Sbapt    pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
474228072Sbapt    if (nproc > onproc)
475228072Sbapt	pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
476228072Sbapt		* (onproc = nproc));
477228072Sbapt    if (pref == NULL || pbase == NULL) {
478228072Sbapt	(void) fprintf(stderr, "top: Out of memory.\n");
479228072Sbapt	quit(23);
480228072Sbapt    }
481228072Sbapt    /* get a pointer to the states summary array */
482228072Sbapt    si->procstates = process_states;
483228072Sbapt
484228072Sbapt    /* set up flags which define what we are going to select */
485228072Sbapt    show_idle = sel->idle;
486228072Sbapt    show_self = sel->self;
487228072Sbapt    show_system = sel->system;
488228072Sbapt    show_uid = sel->uid != -1;
489228072Sbapt    show_command = sel->command != NULL;
490228072Sbapt
491228072Sbapt    /* count up process states and get pointers to interesting procs */
492228072Sbapt    total_procs = 0;
493228072Sbapt    active_procs = 0;
494228072Sbapt    memset((char *)process_states, 0, sizeof(process_states));
495228072Sbapt    prefp = pref;
496228072Sbapt    for (pp = pbase, i = 0; i < nproc; pp++, i++)
497228072Sbapt    {
498228072Sbapt	/*
499228072Sbapt	 *  Place pointers to each valid proc structure in pref[].
500228072Sbapt	 *  Process slots that are actually in use have a non-zero
501228072Sbapt	 *  status field.  Processes with P_SYSTEM set are system
502228072Sbapt	 *  processes---these get ignored unless show_sysprocs is set.
503228072Sbapt	 */
504228072Sbapt	if (PP(pp, p_stat) != 0 &&
505228072Sbapt	    (show_self != PP(pp, p_pid)) &&
506228072Sbapt	    (show_system || ((PP(pp, p_flag) & P_SYSTEM) == 0)))
507228072Sbapt	{
508228072Sbapt	    total_procs++;
509228072Sbapt	    process_states[(unsigned char) PP(pp, p_stat)]++;
510228072Sbapt	    if ((PP(pp, p_stat) != SZOMB) &&
511228072Sbapt		(show_idle || (PP(pp, p_pctcpu) != 0) ||
512228072Sbapt		 (PP(pp, p_stat) == SRUN)) &&
513228072Sbapt		(!show_uid || EP(pp, e_pcred.p_ruid) == (uid_t)sel->uid))
514228072Sbapt	    {
515228072Sbapt		*prefp++ = pp;
516228072Sbapt		active_procs++;
517228072Sbapt	    }
518228072Sbapt	}
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	    	(RTP_PRIO_IS_REALTIME(PP(pp, p_rtprio.type)) ?
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