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