machine.c revision 69370
1322810Shselasky/*
2322810Shselasky * top - a top users display for Unix
3322810Shselasky *
4322810Shselasky * SYNOPSIS:  For FreeBSD-2.x and later
5322810Shselasky *
6322810Shselasky * DESCRIPTION:
7322810Shselasky * Originally written for BSD4.4 system by Christos Zoulas.
8322810Shselasky * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
9322810Shselasky * Order support hacked in from top-3.5beta6/machine/m_aix41.c
10322810Shselasky *   by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
11322810Shselasky *
12322810Shselasky * This is the machine-dependent module for FreeBSD 2.2
13322810Shselasky * Works for:
14322810Shselasky *	FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
15322810Shselasky *
16322810Shselasky * LIBS: -lkvm
17322810Shselasky *
18322810Shselasky * AUTHOR:  Christos Zoulas <christos@ee.cornell.edu>
19322810Shselasky *          Steven Wallace  <swallace@freebsd.org>
20322810Shselasky *          Wolfram Schneider <wosch@FreeBSD.org>
21322810Shselasky *
22322810Shselasky * $FreeBSD: head/usr.bin/top/machine.c 69370 2000-11-29 20:22:34Z jhb $
23322810Shselasky */
24322810Shselasky
25322810Shselasky
26322810Shselasky#include <sys/time.h>
27322810Shselasky#include <sys/types.h>
28331769Shselasky#include <sys/signal.h>
29322810Shselasky#include <sys/param.h>
30322810Shselasky
31322810Shselasky#include "os.h"
32322810Shselasky#include <stdio.h>
33331769Shselasky#include <nlist.h>
34331769Shselasky#include <math.h>
35331769Shselasky#include <kvm.h>
36322810Shselasky#include <pwd.h>
37331769Shselasky#include <sys/errno.h>
38322810Shselasky#include <sys/sysctl.h>
39322810Shselasky#include <sys/dkstat.h>
40322810Shselasky#include <sys/file.h>
41331769Shselasky#include <sys/time.h>
42331769Shselasky#include <sys/proc.h>
43331769Shselasky#include <sys/user.h>
44331769Shselasky#include <sys/vmmeter.h>
45331769Shselasky#include <sys/resource.h>
46322810Shselasky#include <sys/rtprio.h>
47322810Shselasky
48331769Shselasky/* Swap */
49331769Shselasky#include <stdlib.h>
50331769Shselasky#include <sys/conf.h>
51322810Shselasky
52322810Shselasky#include <osreldate.h> /* for changes in kernel structures */
53322810Shselasky
54337101Shselasky#include "top.h"
55337101Shselasky#include "machine.h"
56337101Shselasky
57337101Shselaskystatic int check_nlist __P((struct nlist *));
58322810Shselaskystatic int getkval __P((unsigned long, int *, int, char *));
59322810Shselaskyextern char* printable __P((char *));
60322810Shselaskyint swapmode __P((int *retavail, int *retfree));
61322810Shselaskystatic int smpmode;
62322810Shselaskystatic int namelength;
63322810Shselaskystatic int cmdlength;
64322810Shselasky
65322810Shselasky
66322810Shselasky/* get_process_info passes back a handle.  This is what it looks like: */
67322810Shselasky
68322810Shselaskystruct handle
69322810Shselasky{
70337101Shselasky    struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
71337101Shselasky    int remaining;		/* number of pointers remaining */
72331769Shselasky};
73331769Shselasky
74322810Shselasky/* declarations for load_avg */
75331769Shselasky#include "loadavg.h"
76322810Shselasky
77322810Shselasky#define PP(pp, field) ((pp)->kp_proc . field)
78331769Shselasky#define EP(pp, field) ((pp)->kp_eproc . field)
79331769Shselasky#define VP(pp, field) ((pp)->kp_eproc.e_vm . field)
80331769Shselasky
81331769Shselasky/* define what weighted cpu is.  */
82331769Shselasky#define weighted_cpu(pct, pp) (PP((pp), p_swtime) == 0 ? 0.0 : \
83331769Shselasky			 ((pct) / (1.0 - exp(PP((pp), p_swtime) * logcpu))))
84331769Shselasky
85331769Shselasky/* what we consider to be process size: */
86331769Shselasky#define PROCSIZE(pp) (VP((pp), vm_map.size) / 1024)
87331769Shselasky
88331769Shselasky/* definitions for indices in the nlist array */
89331769Shselasky
90322810Shselaskystatic struct nlist nlst[] = {
91331769Shselasky#define X_CCPU		0
92331769Shselasky    { "_ccpu" },
93331769Shselasky#define X_CP_TIME	1
94331769Shselasky    { "_cp_time" },
95331769Shselasky#define X_AVENRUN	2
96322810Shselasky    { "_averunnable" },
97331769Shselasky
98331769Shselasky#define X_BUFSPACE	3
99331769Shselasky	{ "_bufspace" },	/* K in buffer cache */
100331769Shselasky#define X_CNT           4
101331769Shselasky    { "_cnt" },		        /* struct vmmeter cnt */
102331769Shselasky
103322810Shselasky/* Last pid */
104331769Shselasky#define X_LASTPID	5
105331769Shselasky    { "_nextpid" },
106331769Shselasky    { 0 }
107331769Shselasky};
108331769Shselasky
109331769Shselasky/*
110322810Shselasky *  These definitions control the format of the per-process area
111331769Shselasky */
112331769Shselasky
113331769Shselaskystatic char smp_header[] =
114331769Shselasky  "  PID %-*.*s PRI NICE  SIZE    RES STATE  C   TIME   WCPU    CPU COMMAND";
115331769Shselasky
116331769Shselasky#define smp_Proc_format \
117322810Shselasky	"%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
118331769Shselasky
119331769Shselaskystatic char up_header[] =
120331769Shselasky  "  PID %-*.*s PRI NICE  SIZE    RES STATE    TIME   WCPU    CPU COMMAND";
121331769Shselasky
122331769Shselasky#define up_Proc_format \
123331769Shselasky	"%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
124331769Shselasky
125331769Shselasky
126331769Shselasky
127331769Shselasky/* process state names for the "STATE" column of the display */
128331769Shselasky/* the extra nulls in the string "run" are for adding a slash and
129331769Shselasky   the processor number when needed */
130331769Shselasky
131331769Shselaskychar *state_abbrev[] =
132331769Shselasky{
133331769Shselasky    "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "MUTEX"
134331769Shselasky};
135331769Shselasky
136331769Shselasky
137331769Shselaskystatic kvm_t *kd;
138331769Shselasky
139331769Shselasky/* values that we stash away in _init and use in later routines */
140331769Shselasky
141331769Shselaskystatic double logcpu;
142322810Shselasky
143331769Shselasky/* these are retrieved from the kernel in _init */
144322810Shselasky
145322810Shselaskystatic load_avg  ccpu;
146331769Shselasky
147331769Shselasky/* these are offsets obtained via nlist and used in the get_ functions */
148322810Shselasky
149331769Shselaskystatic unsigned long cp_time_offset;
150331769Shselaskystatic unsigned long avenrun_offset;
151322810Shselaskystatic unsigned long lastpid_offset;
152322810Shselaskystatic long lastpid;
153331769Shselaskystatic unsigned long cnt_offset;
154331769Shselaskystatic unsigned long bufspace_offset;
155322810Shselaskystatic long cnt;
156331769Shselasky
157331769Shselasky/* these are for calculating cpu state percentages */
158331769Shselasky
159331769Shselaskystatic long cp_time[CPUSTATES];
160331769Shselaskystatic long cp_old[CPUSTATES];
161331769Shselaskystatic long cp_diff[CPUSTATES];
162331769Shselasky
163331769Shselasky/* these are for detailing the process states */
164331769Shselasky
165331769Shselaskyint process_states[8];
166331769Shselaskychar *procstatenames[] = {
167331769Shselasky    "", " starting, ", " running, ", " sleeping, ", " stopped, ",
168331769Shselasky    " zombie, ", " waiting, ", " mutex, ",
169331769Shselasky    NULL
170331805Shselasky};
171331805Shselasky
172331805Shselasky/* these are for detailing the cpu states */
173331805Shselasky
174331805Shselaskyint cpu_states[CPUSTATES];
175331805Shselaskychar *cpustatenames[] = {
176331805Shselasky    "user", "nice", "system", "interrupt", "idle", NULL
177331805Shselasky};
178331805Shselasky
179331805Shselasky/* these are for detailing the memory statistics */
180331805Shselasky
181331805Shselaskyint memory_stats[7];
182331805Shselaskychar *memorynames[] = {
183331805Shselasky    "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
184331805Shselasky    NULL
185331805Shselasky};
186331805Shselasky
187331805Shselaskyint swap_stats[7];
188331805Shselaskychar *swapnames[] = {
189331805Shselasky/*   0           1            2           3            4       5 */
190331805Shselasky    "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
191331805Shselasky    NULL
192331805Shselasky};
193331805Shselasky
194331805Shselasky
195331805Shselasky/* these are for keeping track of the proc array */
196331805Shselasky
197331805Shselaskystatic int nproc;
198331805Shselaskystatic int onproc = -1;
199331805Shselaskystatic int pref_len;
200331805Shselaskystatic struct kinfo_proc *pbase;
201331805Shselaskystatic struct kinfo_proc **pref;
202331805Shselasky
203331805Shselasky/* these are for getting the memory statistics */
204331805Shselasky
205331805Shselaskystatic int pageshift;		/* log base 2 of the pagesize */
206331805Shselasky
207331805Shselasky/* define pagetok in terms of pageshift */
208331805Shselasky
209331805Shselasky#define pagetok(size) ((size) << pageshift)
210331805Shselasky
211331805Shselasky/* useful externals */
212331805Shselaskylong percentages();
213331805Shselasky
214331805Shselasky#ifdef ORDER
215331805Shselasky/* sorting orders. first is default */
216331805Shselaskychar *ordernames[] = {
217331805Shselasky    "cpu", "size", "res", "time", "pri", NULL
218331805Shselasky};
219331805Shselasky#endif
220331805Shselasky
221331805Shselaskyint
222331805Shselaskymachine_init(statics)
223331805Shselasky
224331805Shselaskystruct statics *statics;
225331805Shselasky
226331805Shselasky{
227331805Shselasky    register int i = 0;
228331769Shselasky    register int pagesize;
229331769Shselasky    int modelen;
230331769Shselasky    struct passwd *pw;
231322810Shselasky
232331769Shselasky    modelen = sizeof(smpmode);
233331769Shselasky    if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
234331769Shselasky         sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
235331805Shselasky	modelen != sizeof(smpmode))
236331805Shselasky	    smpmode = 0;
237322810Shselasky
238331769Shselasky    while ((pw = getpwent()) != NULL) {
239331769Shselasky	if (strlen(pw->pw_name) > namelength)
240331805Shselasky	    namelength = strlen(pw->pw_name);
241331805Shselasky    }
242331805Shselasky    if (namelength < 8)
243331805Shselasky	namelength = 8;
244331805Shselasky    if (namelength > 15)
245331805Shselasky	namelength = 15;
246331805Shselasky
247331805Shselasky    if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
248331805Shselasky	return -1;
249331805Shselasky
250331769Shselasky
251331769Shselasky    /* get the list of symbols we want to access in the kernel */
252331769Shselasky    (void) kvm_nlist(kd, nlst);
253331769Shselasky    if (nlst[0].n_type == 0)
254331769Shselasky    {
255331769Shselasky	fprintf(stderr, "top: nlist failed\n");
256331769Shselasky	return(-1);
257331769Shselasky    }
258331769Shselasky
259331769Shselasky    /* make sure they were all found */
260331769Shselasky    if (i > 0 && check_nlist(nlst) > 0)
261331769Shselasky    {
262331769Shselasky	return(-1);
263331769Shselasky    }
264331769Shselasky
265331769Shselasky    (void) getkval(nlst[X_CCPU].n_value,   (int *)(&ccpu),	sizeof(ccpu),
266331769Shselasky	    nlst[X_CCPU].n_name);
267331769Shselasky
268331769Shselasky    /* stash away certain offsets for later use */
269331769Shselasky    cp_time_offset = nlst[X_CP_TIME].n_value;
270331769Shselasky    avenrun_offset = nlst[X_AVENRUN].n_value;
271331769Shselasky    lastpid_offset =  nlst[X_LASTPID].n_value;
272331769Shselasky    cnt_offset = nlst[X_CNT].n_value;
273331769Shselasky    bufspace_offset = nlst[X_BUFSPACE].n_value;
274331769Shselasky
275331769Shselasky    /* this is used in calculating WCPU -- calculate it ahead of time */
276331769Shselasky    logcpu = log(loaddouble(ccpu));
277331769Shselasky
278331769Shselasky    pbase = NULL;
279331769Shselasky    pref = NULL;
280331769Shselasky    nproc = 0;
281331769Shselasky    onproc = -1;
282331769Shselasky    /* get the page size with "getpagesize" and calculate pageshift from it */
283331769Shselasky    pagesize = getpagesize();
284331769Shselasky    pageshift = 0;
285331769Shselasky    while (pagesize > 1)
286331769Shselasky    {
287331769Shselasky	pageshift++;
288331769Shselasky	pagesize >>= 1;
289331769Shselasky    }
290337078Shselasky
291331769Shselasky    /* we only need the amount of log(2)1024 for our conversion */
292331769Shselasky    pageshift -= LOG1024;
293331769Shselasky
294331769Shselasky    /* fill in the statics information */
295331769Shselasky    statics->procstate_names = procstatenames;
296337078Shselasky    statics->cpustate_names = cpustatenames;
297337078Shselasky    statics->memory_names = memorynames;
298331769Shselasky    statics->swap_names = swapnames;
299337078Shselasky#ifdef ORDER
300331769Shselasky    statics->order_names = ordernames;
301331769Shselasky#endif
302331769Shselasky
303331769Shselasky    /* all done! */
304331769Shselasky    return(0);
305331769Shselasky}
306331769Shselasky
307331769Shselaskychar *format_header(uname_field)
308331769Shselasky
309331769Shselaskyregister char *uname_field;
310322810Shselasky
311331769Shselasky{
312322810Shselasky    register char *ptr;
313331769Shselasky    static char Header[128];
314331769Shselasky
315331769Shselasky    snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
316331769Shselasky	     namelength, namelength, uname_field);
317331769Shselasky
318331769Shselasky    cmdlength = 80 - strlen(Header) + 6;
319331769Shselasky
320331769Shselasky    return Header;
321331769Shselasky}
322331769Shselasky
323331769Shselaskystatic int swappgsin = -1;
324331769Shselaskystatic int swappgsout = -1;
325331769Shselaskyextern struct timeval timeout;
326331769Shselasky
327331769Shselaskyvoid
328322810Shselaskyget_system_info(si)
329322810Shselasky
330331769Shselaskystruct system_info *si;
331331769Shselasky
332331769Shselasky{
333331769Shselasky    long total;
334331769Shselasky    load_avg avenrun[3];
335331769Shselasky    int mib[2];
336331769Shselasky    struct timeval boottime;
337331769Shselasky    size_t bt_size;
338331769Shselasky
339331769Shselasky    /* get the cp_time array */
340331769Shselasky    (void) getkval(cp_time_offset, (int *)cp_time, sizeof(cp_time),
341331769Shselasky		   nlst[X_CP_TIME].n_name);
342331769Shselasky    (void) getkval(avenrun_offset, (int *)avenrun, sizeof(avenrun),
343331769Shselasky		   nlst[X_AVENRUN].n_name);
344331769Shselasky
345331769Shselasky    (void) getkval(lastpid_offset, (int *)(&lastpid), sizeof(lastpid),
346331769Shselasky		   "!");
347331769Shselasky
348331769Shselasky    /* convert load averages to doubles */
349331769Shselasky    {
350331769Shselasky	register int i;
351331769Shselasky	register double *infoloadp;
352331769Shselasky	load_avg *avenrunp;
353331769Shselasky
354331769Shselasky#ifdef notyet
355331769Shselasky	struct loadavg sysload;
356331769Shselasky	int size;
357331769Shselasky	getkerninfo(KINFO_LOADAVG, &sysload, &size, 0);
358331769Shselasky#endif
359331769Shselasky
360331769Shselasky	infoloadp = si->load_avg;
361331769Shselasky	avenrunp = avenrun;
362331769Shselasky	for (i = 0; i < 3; i++)
363331769Shselasky	{
364331769Shselasky#ifdef notyet
365331769Shselasky	    *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
366331769Shselasky#endif
367331769Shselasky	    *infoloadp++ = loaddouble(*avenrunp++);
368331769Shselasky	}
369331769Shselasky    }
370331769Shselasky
371331769Shselasky    /* convert cp_time counts to percentages */
372331769Shselasky    total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
373331769Shselasky
374331769Shselasky    /* sum memory & swap statistics */
375331769Shselasky    {
376331769Shselasky	struct vmmeter sum;
377331769Shselasky	static unsigned int swap_delay = 0;
378331769Shselasky	static int swapavail = 0;
379331769Shselasky	static int swapfree = 0;
380331769Shselasky	static int bufspace = 0;
381331769Shselasky
382331769Shselasky        (void) getkval(cnt_offset, (int *)(&sum), sizeof(sum),
383331769Shselasky		   "_cnt");
384331769Shselasky        (void) getkval(bufspace_offset, (int *)(&bufspace), sizeof(bufspace),
385337098Shselasky		   "_bufspace");
386337098Shselasky
387337098Shselasky	/* convert memory stats to Kbytes */
388337098Shselasky	memory_stats[0] = pagetok(sum.v_active_count);
389337098Shselasky	memory_stats[1] = pagetok(sum.v_inactive_count);
390337098Shselasky	memory_stats[2] = pagetok(sum.v_wire_count);
391337098Shselasky	memory_stats[3] = pagetok(sum.v_cache_count);
392337098Shselasky	memory_stats[4] = bufspace / 1024;
393337098Shselasky	memory_stats[5] = pagetok(sum.v_free_count);
394337098Shselasky	memory_stats[6] = -1;
395337098Shselasky
396337098Shselasky	/* first interval */
397337098Shselasky        if (swappgsin < 0) {
398337098Shselasky	    swap_stats[4] = 0;
399337098Shselasky	    swap_stats[5] = 0;
400337098Shselasky	}
401337098Shselasky
402337098Shselasky	/* compute differences between old and new swap statistic */
403337098Shselasky	else {
404337098Shselasky	    swap_stats[4] = pagetok(((sum.v_swappgsin - swappgsin)));
405337098Shselasky	    swap_stats[5] = pagetok(((sum.v_swappgsout - swappgsout)));
406322810Shselasky	}
407322810Shselasky
408331769Shselasky        swappgsin = sum.v_swappgsin;
409331769Shselasky	swappgsout = sum.v_swappgsout;
410331769Shselasky
411322810Shselasky	/* call CPU heavy swapmode() only for changes */
412322810Shselasky        if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
413322810Shselasky	    swap_stats[3] = swapmode(&swapavail, &swapfree);
414322810Shselasky	    swap_stats[0] = swapavail;
415322810Shselasky	    swap_stats[1] = swapavail - swapfree;
416322810Shselasky	    swap_stats[2] = swapfree;
417322810Shselasky	}
418322810Shselasky        swap_delay = 1;
419322810Shselasky	swap_stats[6] = -1;
420322810Shselasky    }
421322810Shselasky
422322810Shselasky    /* set arrays and strings */
423322810Shselasky    si->cpustates = cpu_states;
424322810Shselasky    si->memory = memory_stats;
425322810Shselasky    si->swap = swap_stats;
426322810Shselasky
427322810Shselasky
428322810Shselasky    if(lastpid > 0) {
429322810Shselasky	si->last_pid = lastpid;
430322810Shselasky    } else {
431331769Shselasky	si->last_pid = -1;
432331769Shselasky    }
433331769Shselasky
434331769Shselasky    /*
435331769Shselasky     * Print how long system has been up.
436331769Shselasky     * (Found by looking getting "boottime" from the kernel)
437331769Shselasky     */
438331769Shselasky    mib[0] = CTL_KERN;
439331769Shselasky    mib[1] = KERN_BOOTTIME;
440331769Shselasky    bt_size = sizeof(boottime);
441331769Shselasky    if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
442331769Shselasky	boottime.tv_sec != 0) {
443331769Shselasky	si->boottime = boottime;
444331769Shselasky    } else {
445331769Shselasky	si->boottime.tv_sec = -1;
446331769Shselasky    }
447331769Shselasky}
448331769Shselasky
449331769Shselaskystatic struct handle handle;
450331769Shselasky
451331769Shselaskycaddr_t get_process_info(si, sel, compare)
452331769Shselasky
453322810Shselaskystruct system_info *si;
454322810Shselaskystruct process_select *sel;
455322810Shselaskyint (*compare)();
456322810Shselasky
457322810Shselasky{
458322810Shselasky    register int i;
459322810Shselasky    register int total_procs;
460322810Shselasky    register int active_procs;
461322810Shselasky    register struct kinfo_proc **prefp;
462322810Shselasky    register struct kinfo_proc *pp;
463331769Shselasky
464322810Shselasky    /* these are copied out of sel for speed */
465322810Shselasky    int show_idle;
466322810Shselasky    int show_self;
467322810Shselasky    int show_system;
468331769Shselasky    int show_uid;
469322810Shselasky    int show_command;
470322810Shselasky
471322810Shselasky
472331769Shselasky    pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
473322810Shselasky    if (nproc > onproc)
474322810Shselasky	pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
475322810Shselasky		* (onproc = nproc));
476322810Shselasky    if (pref == NULL || pbase == NULL) {
477331769Shselasky	(void) fprintf(stderr, "top: Out of memory.\n");
478331769Shselasky	quit(23);
479331769Shselasky    }
480331769Shselasky    /* get a pointer to the states summary array */
481331769Shselasky    si->procstates = process_states;
482331769Shselasky
483322810Shselasky    /* set up flags which define what we are going to select */
484322810Shselasky    show_idle = sel->idle;
485322810Shselasky    show_self = sel->self;
486322810Shselasky    show_system = sel->system;
487322810Shselasky    show_uid = sel->uid != -1;
488322810Shselasky    show_command = sel->command != NULL;
489322810Shselasky
490322810Shselasky    /* count up process states and get pointers to interesting procs */
491322810Shselasky    total_procs = 0;
492322810Shselasky    active_procs = 0;
493331769Shselasky    memset((char *)process_states, 0, sizeof(process_states));
494322810Shselasky    prefp = pref;
495322810Shselasky    for (pp = pbase, i = 0; i < nproc; pp++, i++)
496322810Shselasky    {
497322810Shselasky	/*
498322810Shselasky	 *  Place pointers to each valid proc structure in pref[].
499322810Shselasky	 *  Process slots that are actually in use have a non-zero
500322810Shselasky	 *  status field.  Processes with P_SYSTEM set are system
501322810Shselasky	 *  processes---these get ignored unless show_sysprocs is set.
502322810Shselasky	 */
503322810Shselasky	if (PP(pp, p_stat) != 0 &&
504322810Shselasky	    (show_self != PP(pp, p_pid)) &&
505322810Shselasky	    (show_system || ((PP(pp, p_flag) & P_SYSTEM) == 0)))
506322810Shselasky	{
507322810Shselasky	    total_procs++;
508322810Shselasky	    process_states[(unsigned char) PP(pp, p_stat)]++;
509322810Shselasky	    if ((PP(pp, p_stat) != SZOMB) &&
510322810Shselasky		(show_idle || (PP(pp, p_pctcpu) != 0) ||
511322810Shselasky		 (PP(pp, p_stat) == SRUN)) &&
512322810Shselasky		(!show_uid || EP(pp, e_pcred.p_ruid) == (uid_t)sel->uid))
513331769Shselasky	    {
514322810Shselasky		*prefp++ = pp;
515322810Shselasky		active_procs++;
516322810Shselasky	    }
517322810Shselasky	}
518322810Shselasky    }
519322810Shselasky
520322810Shselasky    /* if requested, sort the "interesting" processes */
521322810Shselasky    if (compare != NULL)
522322810Shselasky    {
523322810Shselasky	qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
524322810Shselasky    }
525322810Shselasky
526322810Shselasky    /* remember active and total counts */
527322810Shselasky    si->p_total = total_procs;
528322810Shselasky    si->p_active = pref_len = active_procs;
529322810Shselasky
530322810Shselasky    /* pass back a handle */
531322810Shselasky    handle.next_proc = pref;
532331769Shselasky    handle.remaining = active_procs;
533322810Shselasky    return((caddr_t)&handle);
534322810Shselasky}
535322810Shselasky
536331769Shselaskychar fmt[128];		/* static area where result is built */
537322810Shselasky
538322810Shselaskychar *format_next_process(handle, get_userid)
539322810Shselasky
540331769Shselaskycaddr_t handle;
541322810Shselaskychar *(*get_userid)();
542322810Shselasky
543322810Shselasky{
544322810Shselasky    register struct kinfo_proc *pp;
545331769Shselasky    register long cputime;
546331769Shselasky    register double pct;
547331769Shselasky    struct handle *hp;
548331769Shselasky    char status[16];
549331769Shselasky    int state;
550322810Shselasky
551322810Shselasky    /* find and remember the next proc structure */
552322810Shselasky    hp = (struct handle *)handle;
553331769Shselasky    pp = *(hp->next_proc++);
554322810Shselasky    hp->remaining--;
555322810Shselasky
556322810Shselasky    /* get the process's command name */
557322810Shselasky    if ((PP(pp, p_flag) & P_INMEM) == 0) {
558322810Shselasky	/*
559322810Shselasky	 * Print swapped processes as <pname>
560322810Shselasky	 */
561331769Shselasky	char *comm = PP(pp, p_comm);
562322810Shselasky#define COMSIZ sizeof(PP(pp, p_comm))
563322810Shselasky	char buf[COMSIZ];
564322810Shselasky	(void) strncpy(buf, comm, COMSIZ);
565322810Shselasky	comm[0] = '<';
566322810Shselasky	(void) strncpy(&comm[1], buf, COMSIZ - 2);
567322810Shselasky	comm[COMSIZ - 2] = '\0';
568322810Shselasky	(void) strncat(comm, ">", COMSIZ - 1);
569322810Shselasky	comm[COMSIZ - 1] = '\0';
570322810Shselasky    }
571331769Shselasky
572331769Shselasky    /*
573322810Shselasky     * Convert the process's runtime from microseconds to seconds.  This
574322810Shselasky     * time includes the interrupt time although that is not wanted here.
575322810Shselasky     * ps(1) is similarly sloppy.
576331769Shselasky     */
577322810Shselasky    cputime = (PP(pp, p_runtime) + 500000) / 1000000;
578322810Shselasky
579331769Shselasky    /* calculate the base for cpu percentages */
580331769Shselasky    pct = pctdouble(PP(pp, p_pctcpu));
581331769Shselasky
582331769Shselasky    /* generate "STATE" field */
583322810Shselasky    switch (state = PP(pp, p_stat)) {
584331769Shselasky	case SRUN:
585331769Shselasky	    if (smpmode && PP(pp, p_oncpu) != 0xff)
586331769Shselasky		sprintf(status, "CPU%d", PP(pp, p_oncpu));
587331769Shselasky	    else
588331769Shselasky		strcpy(status, "RUN");
589322810Shselasky	    break;
590331769Shselasky	case SMTX:
591331769Shselasky	    if (PP(pp, p_mtxname) != NULL) {
592331769Shselasky		sprintf(status, "*%.6s", EP(pp, e_mtxname));
593322810Shselasky	        break;
594322810Shselasky	    }
595322810Shselasky	    /* fall through */
596322810Shselasky	case SSLEEP:
597322810Shselasky	    if (PP(pp, p_wmesg) != NULL) {
598322810Shselasky		sprintf(status, "%.6s", EP(pp, e_wmesg));
599322810Shselasky		break;
600322810Shselasky	    }
601322810Shselasky	    /* fall through */
602322810Shselasky	default:
603322810Shselasky
604322810Shselasky	    if (state >= 0 &&
605322810Shselasky	        state < sizeof(state_abbrev) / sizeof(*state_abbrev))
606322810Shselasky		    sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
607322810Shselasky	    else
608331769Shselasky		    sprintf(status, "?%5d", state);
609322810Shselasky	    break;
610322810Shselasky    }
611322810Shselasky
612322810Shselasky    /* format this entry */
613322810Shselasky    sprintf(fmt,
614322810Shselasky	    smpmode ? smp_Proc_format : up_Proc_format,
615322810Shselasky	    PP(pp, p_pid),
616322810Shselasky	    namelength, namelength,
617322810Shselasky	    (*get_userid)(EP(pp, e_pcred.p_ruid)),
618322810Shselasky	    PP(pp, p_priority) - PZERO,
619322810Shselasky
620322810Shselasky	    /*
621322810Shselasky	     * normal time      -> nice value -20 - +20
622322810Shselasky	     * real time 0 - 31 -> nice value -52 - -21
623331769Shselasky	     * idle time 0 - 31 -> nice value +21 - +52
624331769Shselasky	     */
625331769Shselasky	    (PP(pp, p_rtprio.type) ==  RTP_PRIO_NORMAL ?
626331769Shselasky	    	PP(pp, p_nice) - NZERO :
627331769Shselasky	    	(RTP_PRIO_IS_REALTIME(PP(pp, p_rtprio.type)) ?
628331769Shselasky		    (PRIO_MIN - 1 - RTP_PRIO_MAX + PP(pp, p_rtprio.prio)) :
629331769Shselasky		    (PRIO_MAX + 1 + PP(pp, p_rtprio.prio)))),
630322810Shselasky	    format_k2(PROCSIZE(pp)),
631331769Shselasky	    format_k2(pagetok(VP(pp, vm_rssize))),
632331769Shselasky	    status,
633331769Shselasky	    smpmode ? PP(pp, p_lastcpu) : 0,
634331769Shselasky	    format_time(cputime),
635331769Shselasky	    100.0 * weighted_cpu(pct, pp),
636331769Shselasky	    100.0 * pct,
637331769Shselasky	    cmdlength,
638331769Shselasky	    printable(PP(pp, p_comm)));
639331769Shselasky
640322810Shselasky    /* return the result */
641322810Shselasky    return(fmt);
642322810Shselasky}
643331769Shselasky
644331769Shselasky
645331769Shselasky/*
646331769Shselasky * check_nlist(nlst) - checks the nlist to see if any symbols were not
647331769Shselasky *		found.  For every symbol that was not found, a one-line
648331769Shselasky *		message is printed to stderr.  The routine returns the
649331769Shselasky *		number of symbols NOT found.
650331769Shselasky */
651331769Shselasky
652331769Shselaskystatic int check_nlist(nlst)
653331769Shselasky
654331769Shselaskyregister struct nlist *nlst;
655331769Shselasky
656331769Shselasky{
657331769Shselasky    register int i;
658331769Shselasky
659331769Shselasky    /* check to see if we got ALL the symbols we requested */
660331769Shselasky    /* this will write one line to stderr for every symbol not found */
661331769Shselasky
662331769Shselasky    i = 0;
663331769Shselasky    while (nlst->n_name != NULL)
664331769Shselasky    {
665331769Shselasky	if (nlst->n_type == 0)
666331769Shselasky	{
667331769Shselasky	    /* this one wasn't found */
668331769Shselasky	    (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
669331769Shselasky			   nlst->n_name);
670331769Shselasky	    i = 1;
671331769Shselasky	}
672331769Shselasky	nlst++;
673331769Shselasky    }
674331769Shselasky
675331769Shselasky    return(i);
676331769Shselasky}
677331769Shselasky
678331769Shselasky
679331769Shselasky/*
680331769Shselasky *  getkval(offset, ptr, size, refstr) - get a value out of the kernel.
681331769Shselasky *	"offset" is the byte offset into the kernel for the desired value,
682331769Shselasky *  	"ptr" points to a buffer into which the value is retrieved,
683331769Shselasky *  	"size" is the size of the buffer (and the object to retrieve),
684331769Shselasky *  	"refstr" is a reference string used when printing error meessages,
685331769Shselasky *	    if "refstr" starts with a '!', then a failure on read will not
686331769Shselasky *  	    be fatal (this may seem like a silly way to do things, but I
687331769Shselasky *  	    really didn't want the overhead of another argument).
688331769Shselasky *
689331769Shselasky */
690322810Shselasky
691322810Shselaskystatic int getkval(offset, ptr, size, refstr)
692322810Shselasky
693322810Shselaskyunsigned long offset;
694331769Shselaskyint *ptr;
695322810Shselaskyint size;
696322810Shselaskychar *refstr;
697322810Shselasky
698322810Shselasky{
699331769Shselasky    if (kvm_read(kd, offset, (char *) ptr, size) != size)
700331769Shselasky    {
701331769Shselasky	if (*refstr == '!')
702322810Shselasky	{
703331769Shselasky	    return(0);
704322810Shselasky	}
705322810Shselasky	else
706322810Shselasky	{
707322810Shselasky	    fprintf(stderr, "top: kvm_read for %s: %s\n",
708322810Shselasky		refstr, strerror(errno));
709322810Shselasky	    quit(23);
710322810Shselasky	}
711322810Shselasky    }
712322810Shselasky    return(1);
713322810Shselasky}
714322810Shselasky
715331769Shselasky/* comparison routines for qsort */
716331769Shselasky
717322810Shselasky/*
718331769Shselasky *  proc_compare - comparison function for "qsort"
719322810Shselasky *	Compares the resource consumption of two processes using five
720322810Shselasky *  	distinct keys.  The keys (in descending order of importance) are:
721322810Shselasky *  	percent cpu, cpu ticks, state, resident set size, total virtual
722322810Shselasky *  	memory usage.  The process states are ordered as follows (from least
723322810Shselasky *  	to most important):  WAIT, zombie, sleep, stop, start, run.  The
724331769Shselasky *  	array declaration below maps a process state index into a number
725331769Shselasky *  	that reflects this ordering.
726322810Shselasky */
727331769Shselasky
728331769Shselaskystatic unsigned char sorted_state[] =
729331769Shselasky{
730331769Shselasky    0,	/* not used		*/
731331769Shselasky    3,	/* sleep		*/
732331769Shselasky    1,	/* ABANDONED (WAIT)	*/
733331769Shselasky    6,	/* run			*/
734331769Shselasky    5,	/* start		*/
735331769Shselasky    2,	/* zombie		*/
736331769Shselasky    4	/* stop			*/
737331769Shselasky};
738331769Shselasky
739331769Shselasky
740331769Shselasky#define ORDERKEY_PCTCPU \
741331769Shselasky  if (lresult = (long) PP(p2, p_pctcpu) - (long) PP(p1, p_pctcpu), \
742331769Shselasky     (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
743331769Shselasky
744331769Shselasky#define ORDERKEY_CPTICKS \
745331769Shselasky  if ((result = PP(p2, p_runtime) > PP(p1, p_runtime) ? 1 : \
746331769Shselasky                PP(p2, p_runtime) < PP(p1, p_runtime) ? -1 : 0) == 0)
747331769Shselasky
748331769Shselasky#define ORDERKEY_STATE \
749331769Shselasky  if ((result = sorted_state[(unsigned char) PP(p2, p_stat)] - \
750331769Shselasky                sorted_state[(unsigned char) PP(p1, p_stat)]) == 0)
751331769Shselasky
752331769Shselasky#define ORDERKEY_PRIO \
753331769Shselasky  if ((result = PP(p2, p_priority) - PP(p1, p_priority)) == 0)
754331769Shselasky
755331769Shselasky#define ORDERKEY_RSSIZE \
756331769Shselasky  if ((result = VP(p2, vm_rssize) - VP(p1, vm_rssize)) == 0)
757322810Shselasky
758322810Shselasky#define ORDERKEY_MEM \
759322810Shselasky  if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
760322810Shselasky
761322810Shselasky/* compare_cpu - the comparison function for sorting by cpu percentage */
762322810Shselasky
763322810Shselaskyint
764322810Shselasky#ifdef ORDER
765322810Shselaskycompare_cpu(pp1, pp2)
766322810Shselasky#else
767322810Shselaskyproc_compare(pp1, pp2)
768322810Shselasky#endif
769322810Shselasky
770322810Shselaskystruct proc **pp1;
771322810Shselaskystruct proc **pp2;
772322810Shselasky
773322810Shselasky{
774322810Shselasky    register struct kinfo_proc *p1;
775322810Shselasky    register struct kinfo_proc *p2;
776322810Shselasky    register int result;
777331769Shselasky    register pctcpu lresult;
778331769Shselasky
779322810Shselasky    /* remove one level of indirection */
780322810Shselasky    p1 = *(struct kinfo_proc **) pp1;
781322810Shselasky    p2 = *(struct kinfo_proc **) pp2;
782322810Shselasky
783322810Shselasky    ORDERKEY_PCTCPU
784322810Shselasky    ORDERKEY_CPTICKS
785322810Shselasky    ORDERKEY_STATE
786322810Shselasky    ORDERKEY_PRIO
787322810Shselasky    ORDERKEY_RSSIZE
788322810Shselasky    ORDERKEY_MEM
789322810Shselasky    ;
790322810Shselasky
791322810Shselasky    return(result);
792322810Shselasky}
793322810Shselasky
794322810Shselasky#ifdef ORDER
795322810Shselasky/* compare routines */
796322810Shselaskyint compare_size(), compare_res(), compare_time(), compare_prio();
797322810Shselasky
798322810Shselaskyint (*proc_compares[])() = {
799322810Shselasky    compare_cpu,
800322810Shselasky    compare_size,
801322810Shselasky    compare_res,
802322810Shselasky    compare_time,
803322810Shselasky    compare_prio,
804322810Shselasky    NULL
805322810Shselasky};
806322810Shselasky
807322810Shselasky/* compare_size - the comparison function for sorting by total memory usage */
808322810Shselasky
809322810Shselaskyint
810322810Shselaskycompare_size(pp1, pp2)
811322810Shselasky
812322810Shselaskystruct proc **pp1;
813322810Shselaskystruct proc **pp2;
814322810Shselasky
815322810Shselasky{
816322810Shselasky    register struct kinfo_proc *p1;
817322810Shselasky    register struct kinfo_proc *p2;
818322810Shselasky    register int result;
819322810Shselasky    register pctcpu lresult;
820322810Shselasky
821322810Shselasky    /* remove one level of indirection */
822322810Shselasky    p1 = *(struct kinfo_proc **) pp1;
823322810Shselasky    p2 = *(struct kinfo_proc **) pp2;
824322810Shselasky
825322810Shselasky    ORDERKEY_MEM
826322810Shselasky    ORDERKEY_RSSIZE
827322810Shselasky    ORDERKEY_PCTCPU
828322810Shselasky    ORDERKEY_CPTICKS
829322810Shselasky    ORDERKEY_STATE
830322810Shselasky    ORDERKEY_PRIO
831322810Shselasky    ;
832322810Shselasky
833322810Shselasky    return(result);
834322810Shselasky}
835322810Shselasky
836322810Shselasky/* compare_res - the comparison function for sorting by resident set size */
837322810Shselasky
838322810Shselaskyint
839322810Shselaskycompare_res(pp1, pp2)
840322810Shselasky
841322810Shselaskystruct proc **pp1;
842331769Shselaskystruct proc **pp2;
843331769Shselasky
844322810Shselasky{
845322810Shselasky    register struct kinfo_proc *p1;
846322810Shselasky    register struct kinfo_proc *p2;
847322810Shselasky    register int result;
848331769Shselasky    register pctcpu lresult;
849322810Shselasky
850322810Shselasky    /* remove one level of indirection */
851322810Shselasky    p1 = *(struct kinfo_proc **) pp1;
852322810Shselasky    p2 = *(struct kinfo_proc **) pp2;
853322810Shselasky
854322810Shselasky    ORDERKEY_RSSIZE
855331769Shselasky    ORDERKEY_MEM
856322810Shselasky    ORDERKEY_PCTCPU
857322810Shselasky    ORDERKEY_CPTICKS
858322810Shselasky    ORDERKEY_STATE
859322810Shselasky    ORDERKEY_PRIO
860322810Shselasky    ;
861322810Shselasky
862322810Shselasky    return(result);
863322810Shselasky}
864322810Shselasky
865331769Shselasky/* compare_time - the comparison function for sorting by total cpu time */
866322810Shselasky
867322810Shselaskyint
868322810Shselaskycompare_time(pp1, pp2)
869322810Shselasky
870322810Shselaskystruct proc **pp1;
871322810Shselaskystruct proc **pp2;
872322810Shselasky
873322810Shselasky{
874322810Shselasky    register struct kinfo_proc *p1;
875322810Shselasky    register struct kinfo_proc *p2;
876322810Shselasky    register int result;
877322810Shselasky    register pctcpu lresult;
878322810Shselasky
879322810Shselasky    /* remove one level of indirection */
880322810Shselasky    p1 = *(struct kinfo_proc **) pp1;
881322810Shselasky    p2 = *(struct kinfo_proc **) pp2;
882322810Shselasky
883331769Shselasky    ORDERKEY_CPTICKS
884322810Shselasky    ORDERKEY_PCTCPU
885331769Shselasky    ORDERKEY_STATE
886322810Shselasky    ORDERKEY_PRIO
887331769Shselasky    ORDERKEY_RSSIZE
888322810Shselasky    ORDERKEY_MEM
889331769Shselasky    ;
890331769Shselasky
891322810Shselasky      return(result);
892322810Shselasky  }
893322810Shselasky
894322810Shselasky/* compare_prio - the comparison function for sorting by cpu percentage */
895322810Shselasky
896322810Shselaskyint
897322810Shselaskycompare_prio(pp1, pp2)
898322810Shselasky
899322810Shselaskystruct proc **pp1;
900322810Shselaskystruct proc **pp2;
901322810Shselasky
902322810Shselasky{
903322810Shselasky    register struct kinfo_proc *p1;
904322810Shselasky    register struct kinfo_proc *p2;
905322810Shselasky    register int result;
906322810Shselasky    register pctcpu lresult;
907322810Shselasky
908322810Shselasky    /* remove one level of indirection */
909322810Shselasky    p1 = *(struct kinfo_proc **) pp1;
910322810Shselasky    p2 = *(struct kinfo_proc **) pp2;
911322810Shselasky
912322810Shselasky    ORDERKEY_PRIO
913322810Shselasky    ORDERKEY_CPTICKS
914322810Shselasky    ORDERKEY_PCTCPU
915322810Shselasky    ORDERKEY_STATE
916322810Shselasky    ORDERKEY_RSSIZE
917322810Shselasky    ORDERKEY_MEM
918322810Shselasky    ;
919322810Shselasky
920322810Shselasky    return(result);
921322810Shselasky}
922322810Shselasky#endif
923322810Shselasky
924322810Shselasky/*
925322810Shselasky * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
926322810Shselasky *		the process does not exist.
927322810Shselasky *		It is EXTREMLY IMPORTANT that this function work correctly.
928322810Shselasky *		If top runs setuid root (as in SVR4), then this function
929322810Shselasky *		is the only thing that stands in the way of a serious
930322810Shselasky *		security problem.  It validates requests for the "kill"
931322810Shselasky *		and "renice" commands.
932322810Shselasky */
933331769Shselasky
934322810Shselaskyint proc_owner(pid)
935322810Shselasky
936331769Shselaskyint pid;
937322810Shselasky
938322810Shselasky{
939322810Shselasky    register int cnt;
940322810Shselasky    register struct kinfo_proc **prefp;
941322810Shselasky    register struct kinfo_proc *pp;
942322810Shselasky
943322810Shselasky    prefp = pref;
944322810Shselasky    cnt = pref_len;
945322810Shselasky    while (--cnt >= 0)
946322810Shselasky    {
947322810Shselasky	pp = *prefp++;
948322810Shselasky	if (PP(pp, p_pid) == (pid_t)pid)
949322810Shselasky	{
950322810Shselasky	    return((int)EP(pp, e_pcred.p_ruid));
951322810Shselasky	}
952322810Shselasky    }
953322810Shselasky    return(-1);
954331769Shselasky}
955322810Shselasky
956322810Shselasky
957322810Shselasky/*
958322810Shselasky * swapmode is based on a program called swapinfo written
959322810Shselasky * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
960322810Shselasky */
961322810Shselasky
962331769Shselasky#define	SVAR(var) __STRING(var)	/* to force expansion */
963322810Shselasky#define	KGET(idx, var)							\
964322810Shselasky	KGET1(idx, &var, sizeof(var), SVAR(var))
965322810Shselasky#define	KGET1(idx, p, s, msg)						\
966322810Shselasky	KGET2(nlst[idx].n_value, p, s, msg)
967322810Shselasky#define	KGET2(addr, p, s, msg)						\
968322810Shselasky	if (kvm_read(kd, (u_long)(addr), p, s) != s) {		        \
969322810Shselasky		warnx("cannot read %s: %s", msg, kvm_geterr(kd));       \
970322810Shselasky		return (0);                                             \
971322810Shselasky       }
972322810Shselasky#define	KGETRET(addr, p, s, msg)					\
973331769Shselasky	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
974322810Shselasky		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
975322810Shselasky		return (0);						\
976322810Shselasky	}
977331769Shselasky
978322810Shselasky
979322810Shselaskyint
980322810Shselaskyswapmode(retavail, retfree)
981322810Shselasky	int *retavail;
982322810Shselasky	int *retfree;
983322810Shselasky{
984322810Shselasky	int n;
985322810Shselasky	int pagesize = getpagesize();
986322810Shselasky	struct kvm_swap swapary[1];
987322810Shselasky
988322810Shselasky	*retavail = 0;
989322810Shselasky	*retfree = 0;
990322810Shselasky
991322810Shselasky#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
992322810Shselasky
993322810Shselasky	n = kvm_getswapinfo(kd, swapary, 1, 0);
994322810Shselasky	if (n < 0 || swapary[0].ksw_total == 0)
995322810Shselasky		return(0);
996322810Shselasky
997322810Shselasky	*retavail = CONVERT(swapary[0].ksw_total);
998322810Shselasky	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
999322810Shselasky
1000322810Shselasky	n = (int)((double)swapary[0].ksw_used * 100.0 /
1001322810Shselasky	    (double)swapary[0].ksw_total);
1002331769Shselasky	return(n);
1003322810Shselasky}
1004322810Shselasky
1005322810Shselasky