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