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