machine.c revision 131619
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 131619 2004-07-05 12:48:17Z des $
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 PERCENT COMMAND";
105
106#define io_Proc_format \
107	"%5d %-*.*s %6d %6d %6d %6d %6.2f%% %.*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/* total number of io operations */
198static long total_inblock;
199static long total_oublock;
200static long total_majflt;
201
202/* these are for getting the memory statistics */
203
204static int pageshift;		/* log base 2 of the pagesize */
205
206/* define pagetok in terms of pageshift */
207
208#define pagetok(size) ((size) << pageshift)
209
210/* useful externals */
211long percentages();
212
213#ifdef ORDER
214/* sorting orders. first is default */
215char *ordernames[] = {
216    "cpu", "size", "res", "time", "pri", NULL
217};
218#endif
219
220int
221machine_init(statics)
222    struct statics *statics;
223{
224    int pagesize;
225    size_t modelen;
226    struct passwd *pw;
227
228    modelen = sizeof(smpmode);
229    if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
230         sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
231	modelen != sizeof(smpmode))
232	    smpmode = 0;
233
234    while ((pw = getpwent()) != NULL) {
235	if (strlen(pw->pw_name) > namelength)
236	    namelength = strlen(pw->pw_name);
237    }
238    if (namelength < 8)
239	namelength = 8;
240    if (smpmode && namelength > 13)
241	namelength = 13;
242    else if (namelength > 15)
243	namelength = 15;
244
245    if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, "kvm_open")) == NULL)
246	return -1;
247
248    GETSYSCTL("kern.ccpu", ccpu);
249
250    /* this is used in calculating WCPU -- calculate it ahead of time */
251    logcpu = log(loaddouble(ccpu));
252
253    pbase = NULL;
254    pref = NULL;
255    nproc = 0;
256    onproc = -1;
257    /* get the page size with "getpagesize" and calculate pageshift from it */
258    pagesize = getpagesize();
259    pageshift = 0;
260    while (pagesize > 1)
261    {
262	pageshift++;
263	pagesize >>= 1;
264    }
265
266    /* we only need the amount of log(2)1024 for our conversion */
267    pageshift -= LOG1024;
268
269    /* fill in the statics information */
270    statics->procstate_names = procstatenames;
271    statics->cpustate_names = cpustatenames;
272    statics->memory_names = memorynames;
273    statics->swap_names = swapnames;
274#ifdef ORDER
275    statics->order_names = ordernames;
276#endif
277
278    /* all done! */
279    return(0);
280}
281
282char *
283format_header(uname_field)
284    char *uname_field;
285
286{
287    static char Header[128];
288    const char *prehead;
289
290    switch (displaymode) {
291    case DISP_CPU:
292	    prehead = smpmode ? smp_header : up_header;
293	    break;
294    case DISP_IO:
295	    prehead = io_header;
296	    break;
297    }
298
299    snprintf(Header, sizeof(Header), prehead,
300	     namelength, namelength, uname_field);
301
302    cmdlengthdelta = strlen(Header) - 7;
303
304    return Header;
305}
306
307static int swappgsin = -1;
308static int swappgsout = -1;
309extern struct timeval timeout;
310
311void
312get_system_info(si)
313    struct system_info *si;
314{
315    long total;
316    struct loadavg sysload;
317    int mib[2];
318    struct timeval boottime;
319    size_t bt_size;
320
321    /* get the cp_time array */
322    GETSYSCTL("kern.cp_time", cp_time);
323    GETSYSCTL("vm.loadavg", sysload);
324    GETSYSCTL("kern.lastpid", lastpid);
325
326    /* convert load averages to doubles */
327    {
328	int i;
329	double *infoloadp;
330
331	infoloadp = si->load_avg;
332	for (i = 0; i < 3; i++)
333	{
334#ifdef notyet
335	    *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
336#endif
337	    *infoloadp++ = loaddouble(sysload.ldavg[i]);
338	}
339    }
340
341    /* convert cp_time counts to percentages */
342    total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
343
344    /* sum memory & swap statistics */
345    {
346	static unsigned int swap_delay = 0;
347	static int swapavail = 0;
348	static int swapfree = 0;
349	static int bufspace = 0;
350	static int nspgsin, nspgsout;
351
352	GETSYSCTL("vfs.bufspace", bufspace);
353	GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
354	GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
355	GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
356	GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
357	GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
358	GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
359	GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
360	/* convert memory stats to Kbytes */
361	memory_stats[0] = pagetok(memory_stats[0]);
362	memory_stats[1] = pagetok(memory_stats[1]);
363	memory_stats[2] = pagetok(memory_stats[2]);
364	memory_stats[3] = pagetok(memory_stats[3]);
365	memory_stats[4] = bufspace / 1024;
366	memory_stats[5] = pagetok(memory_stats[5]);
367	memory_stats[6] = -1;
368
369	/* first interval */
370        if (swappgsin < 0) {
371	    swap_stats[4] = 0;
372	    swap_stats[5] = 0;
373	}
374
375	/* compute differences between old and new swap statistic */
376	else {
377	    swap_stats[4] = pagetok(((nspgsin - swappgsin)));
378	    swap_stats[5] = pagetok(((nspgsout - swappgsout)));
379	}
380
381        swappgsin = nspgsin;
382	swappgsout = nspgsout;
383
384	/* call CPU heavy swapmode() only for changes */
385        if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
386	    swap_stats[3] = swapmode(&swapavail, &swapfree);
387	    swap_stats[0] = swapavail;
388	    swap_stats[1] = swapavail - swapfree;
389	    swap_stats[2] = swapfree;
390	}
391        swap_delay = 1;
392	swap_stats[6] = -1;
393    }
394
395    /* set arrays and strings */
396    si->cpustates = cpu_states;
397    si->memory = memory_stats;
398    si->swap = swap_stats;
399
400
401    if(lastpid > 0) {
402	si->last_pid = lastpid;
403    } else {
404	si->last_pid = -1;
405    }
406
407    /*
408     * Print how long system has been up.
409     * (Found by looking getting "boottime" from the kernel)
410     */
411    mib[0] = CTL_KERN;
412    mib[1] = KERN_BOOTTIME;
413    bt_size = sizeof(boottime);
414    if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
415	boottime.tv_sec != 0) {
416	si->boottime = boottime;
417    } else {
418	si->boottime.tv_sec = -1;
419    }
420}
421
422const struct kinfo_proc *
423get_old_proc(struct kinfo_proc *pp)
424{
425	struct kinfo_proc **oldpp, *oldp;
426
427	if (previous_proc_count == 0)
428		return (NULL);
429	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
430	    sizeof(struct kinfo_proc *), compare_pid);
431	if (oldpp == NULL)
432		return (NULL);
433	oldp = *oldpp;
434	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0)
435		return (NULL);
436	return (oldp);
437}
438
439long
440get_io_stats(pp, inp, oup, flp)
441	struct kinfo_proc *pp;
442	long *inp, *oup, *flp;
443{
444	const struct kinfo_proc *oldp;
445	static struct kinfo_proc dummy;
446	long ret;
447
448	oldp = get_old_proc(pp);
449	if (oldp == NULL) {
450		bzero(&dummy, sizeof(dummy));
451		oldp = &dummy;
452	}
453
454	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
455	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
456	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
457	ret =
458	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
459	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
460	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
461	return (ret);
462}
463
464long
465get_io_total(struct kinfo_proc *pp)
466{
467	long dummy;
468
469	return (get_io_stats(pp, &dummy, &dummy, &dummy));
470}
471
472static struct handle handle;
473
474caddr_t
475get_process_info(si, sel, compare)
476    struct system_info *si;
477    struct process_select *sel;
478    int (*compare)();
479{
480    int i;
481    int total_procs;
482    long p_io;
483    long p_inblock, p_oublock, p_majflt;
484    int active_procs;
485    struct kinfo_proc **prefp;
486    struct kinfo_proc *pp;
487    struct kinfo_proc *prev_pp = NULL;
488
489    /* these are copied out of sel for speed */
490    int show_idle;
491    int show_self;
492    int show_system;
493    int show_uid;
494    int show_command;
495
496    /*
497     * Save the previous process info.
498     */
499    if (previous_proc_count_max < nproc) {
500	    free(previous_procs);
501	    previous_procs = malloc(nproc * sizeof(struct kinfo_proc));
502	    free(previous_pref);
503	    previous_pref = malloc(nproc * sizeof(struct kinfo_proc *));
504	    if (previous_procs == NULL || previous_pref == NULL) {
505		    (void) fprintf(stderr, "top: Out of memory.\n");
506		    quit(23);
507	    }
508	    previous_proc_count_max = nproc;
509    }
510    if (nproc) {
511	    for (i = 0; i < nproc; i++)
512		    previous_pref[i] = &previous_procs[i];
513	    bcopy(pbase, previous_procs, nproc * sizeof(struct kinfo_proc));
514	    qsort(previous_pref, nproc,
515		sizeof(struct kinfo_proc *), compare_pid);
516    }
517    previous_proc_count = nproc;
518
519    pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
520    if (nproc > onproc)
521	pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
522		* (onproc = nproc));
523    if (pref == NULL || pbase == NULL) {
524	(void) fprintf(stderr, "top: Out of memory.\n");
525	quit(23);
526    }
527    /* get a pointer to the states summary array */
528    si->procstates = process_states;
529
530    /* set up flags which define what we are going to select */
531    show_idle = sel->idle;
532    show_self = sel->self;
533    show_system = sel->system;
534    show_uid = sel->uid != -1;
535    show_command = sel->command != NULL;
536
537    /* count up process states and get pointers to interesting procs */
538    total_procs = 0;
539    active_procs = 0;
540    total_inblock = 0;
541    total_oublock = 0;
542    total_majflt = 0;
543    memset((char *)process_states, 0, sizeof(process_states));
544    prefp = pref;
545    for (pp = pbase, i = 0; i < nproc; pp++, i++)
546    {
547	/*
548	 *  Place pointers to each valid proc structure in pref[].
549	 */
550
551	if (pp->ki_stat == 0)
552	    /* not in use */
553	    continue;
554
555	if (!show_self && pp->ki_pid == sel->self)
556	    /* skip self */
557	    continue;
558
559	if (!show_system && (pp->ki_flag & P_SYSTEM))
560	    /* skip system process */
561	    continue;
562
563	p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt);
564	total_inblock += p_inblock;
565	total_oublock += p_oublock;
566	total_majflt += p_majflt;
567	total_procs++;
568	process_states[(unsigned char) pp->ki_stat]++;
569
570	if (pp->ki_stat == SZOMB)
571	    /* skip zombies */
572	    continue;
573
574	if (displaymode == DISP_CPU && !show_idle &&
575	    (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN))
576	    /* skip idle or non-running processes */
577	    continue;
578
579	if (displaymode == DISP_IO && !show_idle && p_io == 0)
580	    /* skip processes that aren't doing I/O */
581	    continue;
582
583	if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
584	    /* skip processes which don't belong to the selected UID */
585	    continue;
586
587	/*
588	 * When not showing threads, take the first thread
589	 * for output and add the fields that we can from
590	 * the rest of the process's threads rather than
591	 * using the system's mostly-broken KERN_PROC_PROC.
592	 */
593	if (sel->thread || prev_pp == NULL || prev_pp->ki_pid != pp->ki_pid)
594	{
595	    *prefp++ = pp;
596	    active_procs++;
597	    prev_pp = pp;
598	} else {
599	    prev_pp->ki_pctcpu += pp->ki_pctcpu;
600	}
601    }
602
603    /* if requested, sort the "interesting" processes */
604    if (compare != NULL)
605    {
606	qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
607    }
608
609    /* remember active and total counts */
610    si->p_total = total_procs;
611    si->p_active = pref_len = active_procs;
612
613    /* pass back a handle */
614    handle.next_proc = pref;
615    handle.remaining = active_procs;
616    return((caddr_t)&handle);
617}
618
619char fmt[128];		/* static area where result is built */
620
621char *
622format_next_process(handle, get_userid)
623    caddr_t handle;
624    char *(*get_userid)();
625{
626    struct kinfo_proc *pp;
627    const struct kinfo_proc *oldp;
628    long cputime;
629    double pct;
630    struct handle *hp;
631    char status[16];
632    int state;
633    struct rusage ru, *rup;
634    long p_tot, s_tot;
635
636    /* find and remember the next proc structure */
637    hp = (struct handle *)handle;
638    pp = *(hp->next_proc++);
639    hp->remaining--;
640
641    /* get the process's command name */
642    if ((pp->ki_sflag & PS_INMEM) == 0) {
643	/*
644	 * Print swapped processes as <pname>
645	 */
646	char *comm = pp->ki_comm;
647#define COMSIZ sizeof(pp->ki_comm)
648	char buf[COMSIZ];
649	(void) strncpy(buf, comm, COMSIZ);
650	comm[0] = '<';
651	(void) strncpy(&comm[1], buf, COMSIZ - 2);
652	comm[COMSIZ - 2] = '\0';
653	(void) strncat(comm, ">", COMSIZ - 1);
654	comm[COMSIZ - 1] = '\0';
655    }
656
657    /*
658     * Convert the process's runtime from microseconds to seconds.  This
659     * time includes the interrupt time although that is not wanted here.
660     * ps(1) is similarly sloppy.
661     */
662    cputime = (pp->ki_runtime + 500000) / 1000000;
663
664    /* calculate the base for cpu percentages */
665    pct = pctdouble(pp->ki_pctcpu);
666
667    /* generate "STATE" field */
668    switch (state = pp->ki_stat) {
669	case SRUN:
670	    if (smpmode && pp->ki_oncpu != 0xff)
671		sprintf(status, "CPU%d", pp->ki_oncpu);
672	    else
673		strcpy(status, "RUN");
674	    break;
675	case SLOCK:
676	    if (pp->ki_kiflag & KI_LOCKBLOCK) {
677		sprintf(status, "*%.6s", pp->ki_lockname);
678	        break;
679	    }
680	    /* fall through */
681	case SSLEEP:
682	    if (pp->ki_wmesg != NULL) {
683		sprintf(status, "%.6s", pp->ki_wmesg);
684		break;
685	    }
686	    /* FALLTHROUGH */
687	default:
688
689	    if (state >= 0 &&
690	        state < sizeof(state_abbrev) / sizeof(*state_abbrev))
691		    sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
692	    else
693		    sprintf(status, "?%5d", state);
694	    break;
695    }
696
697    if (displaymode == DISP_IO) {
698	    oldp = get_old_proc(pp);
699	    if (oldp != NULL) {
700		   ru.ru_inblock = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
701		   ru.ru_oublock = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
702		   ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
703		   rup = &ru;
704	    } else {
705		   rup = RU(pp);
706	    }
707	    p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
708	    s_tot = total_inblock + total_oublock + total_majflt;
709
710	    sprintf(fmt, io_Proc_format,
711		pp->ki_pid,
712		namelength, namelength,
713		(*get_userid)(pp->ki_ruid),
714		(int)rup->ru_inblock,
715		(int)rup->ru_oublock,
716		(int)rup->ru_majflt,
717		(int)p_tot,
718		p_tot == 0 ? 0.0 : ((float)(p_tot * 100))/(float)s_tot,
719		screen_width > cmdlengthdelta ?
720		screen_width - cmdlengthdelta : 0,
721		printable(pp->ki_comm));
722	    return (fmt);
723    }
724    /* format this entry */
725    sprintf(fmt,
726	    smpmode ? smp_Proc_format : up_Proc_format,
727	    pp->ki_pid,
728	    namelength, namelength,
729	    (*get_userid)(pp->ki_ruid),
730	    pp->ki_pri.pri_level - PZERO,
731
732	    /*
733	     * normal time      -> nice value -20 - +20
734	     * real time 0 - 31 -> nice value -52 - -21
735	     * idle time 0 - 31 -> nice value +21 - +52
736	     */
737	    (pp->ki_pri.pri_class ==  PRI_TIMESHARE ?
738	    	pp->ki_nice - NZERO :
739	    	(PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
740		    (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
741		    (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
742	    format_k2(PROCSIZE(pp)),
743	    format_k2(pagetok(pp->ki_rssize)),
744	    status,
745	    smpmode ? pp->ki_lastcpu : 0,
746	    format_time(cputime),
747	    100.0 * weighted_cpu(pct, pp),
748	    100.0 * pct,
749	    screen_width > cmdlengthdelta ?
750		screen_width - cmdlengthdelta :
751		0,
752	    printable(pp->ki_comm));
753
754    /* return the result */
755    return(fmt);
756}
757
758static void
759getsysctl(name, ptr, len)
760    char *name;
761    void *ptr;
762    size_t len;
763{
764    size_t nlen = len;
765
766    if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
767	    fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
768		strerror(errno));
769	    quit(23);
770    }
771    if (nlen != len) {
772	    fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
773		(unsigned long)len, (unsigned long)nlen);
774	    quit(23);
775    }
776}
777
778/* comparison routines for qsort */
779
780int
781compare_pid(p1, p2)
782    const void *p1, *p2;
783{
784    const struct kinfo_proc * const *pp1 = p1;
785    const struct kinfo_proc * const *pp2 = p2;
786
787    if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
788	    abort();
789
790    return ((*pp1)->ki_pid - (*pp2)->ki_pid);
791}
792
793/*
794 *  proc_compare - comparison function for "qsort"
795 *	Compares the resource consumption of two processes using five
796 *  	distinct keys.  The keys (in descending order of importance) are:
797 *  	percent cpu, cpu ticks, state, resident set size, total virtual
798 *  	memory usage.  The process states are ordered as follows (from least
799 *  	to most important):  WAIT, zombie, sleep, stop, start, run.  The
800 *  	array declaration below maps a process state index into a number
801 *  	that reflects this ordering.
802 */
803
804static unsigned char sorted_state[] =
805{
806    0,	/* not used		*/
807    3,	/* sleep		*/
808    1,	/* ABANDONED (WAIT)	*/
809    6,	/* run			*/
810    5,	/* start		*/
811    2,	/* zombie		*/
812    4	/* stop			*/
813};
814
815
816#define ORDERKEY_PCTCPU \
817  if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
818     (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
819
820#define ORDERKEY_CPTICKS \
821  if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
822                p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
823
824#define ORDERKEY_STATE \
825  if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
826                sorted_state[(unsigned char) p1->ki_stat]) == 0)
827
828#define ORDERKEY_PRIO \
829  if ((result = p2->ki_pri.pri_level - p1->ki_pri.pri_level) == 0)
830
831#define ORDERKEY_RSSIZE \
832  if ((result = p2->ki_rssize - p1->ki_rssize) == 0)
833
834#define ORDERKEY_MEM \
835  if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
836
837/* compare_cpu - the comparison function for sorting by cpu percentage */
838
839int
840#ifdef ORDER
841compare_cpu(pp1, pp2)
842#else
843proc_compare(pp1, pp2)
844#endif
845    struct proc **pp1;
846    struct proc **pp2;
847{
848    struct kinfo_proc *p1;
849    struct kinfo_proc *p2;
850    int result;
851    pctcpu lresult;
852
853    /* remove one level of indirection */
854    p1 = *(struct kinfo_proc **) pp1;
855    p2 = *(struct kinfo_proc **) pp2;
856
857    ORDERKEY_PCTCPU
858    ORDERKEY_CPTICKS
859    ORDERKEY_STATE
860    ORDERKEY_PRIO
861    ORDERKEY_RSSIZE
862    ORDERKEY_MEM
863    ;
864
865    return(result);
866}
867
868#ifdef ORDER
869/* compare routines */
870int compare_size(), compare_res(), compare_time(), compare_prio();
871
872int (*proc_compares[])() = {
873    compare_cpu,
874    compare_size,
875    compare_res,
876    compare_time,
877    compare_prio,
878    NULL
879};
880
881/* compare_size - the comparison function for sorting by total memory usage */
882
883int
884compare_size(pp1, pp2)
885    struct proc **pp1;
886    struct proc **pp2;
887{
888    struct kinfo_proc *p1;
889    struct kinfo_proc *p2;
890    int result;
891    pctcpu lresult;
892
893    /* remove one level of indirection */
894    p1 = *(struct kinfo_proc **) pp1;
895    p2 = *(struct kinfo_proc **) pp2;
896
897    ORDERKEY_MEM
898    ORDERKEY_RSSIZE
899    ORDERKEY_PCTCPU
900    ORDERKEY_CPTICKS
901    ORDERKEY_STATE
902    ORDERKEY_PRIO
903    ;
904
905    return(result);
906}
907
908/* compare_res - the comparison function for sorting by resident set size */
909
910int
911compare_res(pp1, pp2)
912    struct proc **pp1;
913    struct proc **pp2;
914{
915    struct kinfo_proc *p1;
916    struct kinfo_proc *p2;
917    int result;
918    pctcpu lresult;
919
920    /* remove one level of indirection */
921    p1 = *(struct kinfo_proc **) pp1;
922    p2 = *(struct kinfo_proc **) pp2;
923
924    ORDERKEY_RSSIZE
925    ORDERKEY_MEM
926    ORDERKEY_PCTCPU
927    ORDERKEY_CPTICKS
928    ORDERKEY_STATE
929    ORDERKEY_PRIO
930    ;
931
932    return(result);
933}
934
935/* compare_time - the comparison function for sorting by total cpu time */
936
937int
938compare_time(pp1, pp2)
939    struct proc **pp1;
940    struct proc **pp2;
941{
942    struct kinfo_proc *p1;
943    struct kinfo_proc *p2;
944    int result;
945    pctcpu lresult;
946
947    /* remove one level of indirection */
948    p1 = *(struct kinfo_proc **) pp1;
949    p2 = *(struct kinfo_proc **) pp2;
950
951    ORDERKEY_CPTICKS
952    ORDERKEY_PCTCPU
953    ORDERKEY_STATE
954    ORDERKEY_PRIO
955    ORDERKEY_RSSIZE
956    ORDERKEY_MEM
957    ;
958
959      return(result);
960  }
961
962/* compare_prio - the comparison function for sorting by cpu percentage */
963
964int
965compare_prio(pp1, pp2)
966    struct proc **pp1;
967    struct proc **pp2;
968{
969    struct kinfo_proc *p1;
970    struct kinfo_proc *p2;
971    int result;
972    pctcpu lresult;
973
974    /* remove one level of indirection */
975    p1 = *(struct kinfo_proc **) pp1;
976    p2 = *(struct kinfo_proc **) pp2;
977
978    ORDERKEY_PRIO
979    ORDERKEY_CPTICKS
980    ORDERKEY_PCTCPU
981    ORDERKEY_STATE
982    ORDERKEY_RSSIZE
983    ORDERKEY_MEM
984    ;
985
986    return(result);
987}
988#endif
989
990int
991io_compare(pp1, pp2)
992	struct kinfo_proc **pp1, **pp2;
993{
994	long t1, t2;
995
996	t1 = get_io_total(*pp1);
997	t2 = get_io_total(*pp2);
998	return (t2 - t1);
999}
1000/*
1001 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1002 *		the process does not exist.
1003 *		It is EXTREMLY IMPORTANT that this function work correctly.
1004 *		If top runs setuid root (as in SVR4), then this function
1005 *		is the only thing that stands in the way of a serious
1006 *		security problem.  It validates requests for the "kill"
1007 *		and "renice" commands.
1008 */
1009
1010int
1011proc_owner(pid)
1012    int pid;
1013{
1014    int cnt;
1015    struct kinfo_proc **prefp;
1016    struct kinfo_proc *pp;
1017
1018    prefp = pref;
1019    cnt = pref_len;
1020    while (--cnt >= 0)
1021    {
1022	pp = *prefp++;
1023	if (pp->ki_pid == (pid_t)pid)
1024	{
1025	    return((int)pp->ki_ruid);
1026	}
1027    }
1028    return(-1);
1029}
1030
1031int
1032swapmode(retavail, retfree)
1033	int *retavail;
1034	int *retfree;
1035{
1036	int n;
1037	int pagesize = getpagesize();
1038	struct kvm_swap swapary[1];
1039
1040	*retavail = 0;
1041	*retfree = 0;
1042
1043#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1044
1045	n = kvm_getswapinfo(kd, swapary, 1, 0);
1046	if (n < 0 || swapary[0].ksw_total == 0)
1047		return(0);
1048
1049	*retavail = CONVERT(swapary[0].ksw_total);
1050	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1051
1052	n = (int)((double)swapary[0].ksw_used * 100.0 /
1053	    (double)swapary[0].ksw_total);
1054	return(n);
1055}
1056
1057