machine.c revision 175195
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 175195 2008-01-09 18:06:24Z obrien $
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 <string.h>
46#include <strings.h>
47#include <unistd.h>
48#include <vis.h>
49
50#include "top.h"
51#include "machine.h"
52#include "screen.h"
53#include "utils.h"
54
55#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
56#define	SMPUNAMELEN	13
57#define	UPUNAMELEN	15
58
59extern struct process_select ps;
60extern char* printable(char *);
61static int smpmode;
62enum displaymodes displaymode;
63#ifdef TOP_USERNAME_LEN
64static int namelength = TOP_USERNAME_LEN;
65#else
66static int namelength = 8;
67#endif
68static int cmdlengthdelta;
69
70/* Prototypes for top internals */
71void quit(int);
72
73/* get_process_info passes back a handle.  This is what it looks like: */
74
75struct handle {
76	struct kinfo_proc **next_proc;	/* points to next valid proc pointer */
77	int remaining;			/* number of pointers remaining */
78};
79
80/* declarations for load_avg */
81#include "loadavg.h"
82
83/* define what weighted cpu is.  */
84#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
85			 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
86
87/* what we consider to be process size: */
88#define PROCSIZE(pp) ((pp)->ki_size / 1024)
89
90#define RU(pp)	(&(pp)->ki_rusage)
91#define RUTOT(pp) \
92	(RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
93
94
95/* definitions for indices in the nlist array */
96
97/*
98 *  These definitions control the format of the per-process area
99 */
100
101static char io_header[] =
102    "  PID%s %-*.*s   VCSW  IVCSW   READ  WRITE  FAULT  TOTAL PERCENT COMMAND";
103
104#define io_Proc_format \
105    "%5d%s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
106
107static char smp_header_thr[] =
108    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
109static char smp_header[] =
110    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE  C   TIME %6s COMMAND";
111
112#define smp_Proc_format \
113    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s %1x%7s %5.2f%% %.*s"
114
115static char up_header_thr[] =
116    "  PID%s %-*.*s  THR PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
117static char up_header[] =
118    "  PID%s %-*.*s "   "PRI NICE   SIZE    RES STATE    TIME %6s COMMAND";
119
120#define up_Proc_format \
121    "%5d%s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %5.2f%% %.*s"
122
123
124/* process state names for the "STATE" column of the display */
125/* the extra nulls in the string "run" are for adding a slash and
126   the processor number when needed */
127
128char *state_abbrev[] = {
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, ",
174	"K Free", NULL
175};
176
177int swap_stats[7];
178char *swapnames[] = {
179	"K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
180	NULL
181};
182
183
184/* these are for keeping track of the proc array */
185
186static int nproc;
187static int onproc = -1;
188static int pref_len;
189static struct kinfo_proc *pbase;
190static struct kinfo_proc **pref;
191static struct kinfo_proc *previous_procs;
192static struct kinfo_proc **previous_pref;
193static int previous_proc_count = 0;
194static int previous_proc_count_max = 0;
195
196/* total number of io operations */
197static long total_inblock;
198static long total_oublock;
199static long total_majflt;
200
201/* these are for getting the memory statistics */
202
203static int pageshift;		/* log base 2 of the pagesize */
204
205/* define pagetok in terms of pageshift */
206
207#define pagetok(size) ((size) << pageshift)
208
209/* useful externals */
210long percentages();
211
212#ifdef ORDER
213/*
214 * Sorting orders.  The first element is the default.
215 */
216char *ordernames[] = {
217	"cpu", "size", "res", "time", "pri", "threads",
218	"total", "read", "write", "fault", "vcsw", "ivcsw",
219	"jid", NULL
220};
221#endif
222
223static int compare_jid(const void *a, const void *b);
224static int compare_pid(const void *a, const void *b);
225static const char *format_nice(const struct kinfo_proc *pp);
226static void getsysctl(const char *name, void *ptr, size_t len);
227static int swapmode(int *retavail, int *retfree);
228
229int
230machine_init(struct statics *statics, char do_unames)
231{
232	int pagesize;
233	size_t modelen;
234	struct passwd *pw;
235
236	modelen = sizeof(smpmode);
237	if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen,
238	    NULL, 0) != 0 &&
239	    sysctlbyname("kern.smp.active", &smpmode, &modelen,
240	    NULL, 0) != 0) ||
241	    modelen != sizeof(smpmode))
242		smpmode = 0;
243
244	if (do_unames) {
245	    while ((pw = getpwent()) != NULL) {
246		if (strlen(pw->pw_name) > namelength)
247			namelength = strlen(pw->pw_name);
248	    }
249	}
250	if (smpmode && namelength > SMPUNAMELEN)
251		namelength = SMPUNAMELEN;
252	else if (namelength > UPUNAMELEN)
253		namelength = UPUNAMELEN;
254
255	kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
256	if (kd == NULL)
257		return (-1);
258
259	GETSYSCTL("kern.ccpu", ccpu);
260
261	/* this is used in calculating WCPU -- calculate it ahead of time */
262	logcpu = log(loaddouble(ccpu));
263
264	pbase = NULL;
265	pref = NULL;
266	nproc = 0;
267	onproc = -1;
268
269	/* get the page size and calculate pageshift from it */
270	pagesize = getpagesize();
271	pageshift = 0;
272	while (pagesize > 1) {
273		pageshift++;
274		pagesize >>= 1;
275	}
276
277	/* we only need the amount of log(2)1024 for our conversion */
278	pageshift -= LOG1024;
279
280	/* fill in the statics information */
281	statics->procstate_names = procstatenames;
282	statics->cpustate_names = cpustatenames;
283	statics->memory_names = memorynames;
284	statics->swap_names = swapnames;
285#ifdef ORDER
286	statics->order_names = ordernames;
287#endif
288
289	/* all done! */
290	return (0);
291}
292
293char *
294format_header(char *uname_field)
295{
296	static char Header[128];
297	const char *prehead;
298
299	switch (displaymode) {
300	case DISP_CPU:
301		/*
302		 * The logic of picking the right header format seems reverse
303		 * here because we only want to display a THR column when
304		 * "thread mode" is off (and threads are not listed as
305		 * separate lines).
306		 */
307		prehead = smpmode ?
308		    (ps.thread ? smp_header : smp_header_thr) :
309		    (ps.thread ? up_header : up_header_thr);
310		snprintf(Header, sizeof(Header), prehead,
311		    ps.jail ? " JID" : "",
312		    namelength, namelength, uname_field,
313		    ps.wcpu ? "WCPU" : "CPU");
314		break;
315	case DISP_IO:
316		prehead = io_header;
317		snprintf(Header, sizeof(Header), prehead,
318		    ps.jail ? " JID" : "",
319		    namelength, namelength, uname_field);
320		break;
321	}
322	cmdlengthdelta = strlen(Header) - 7;
323	return (Header);
324}
325
326static int swappgsin = -1;
327static int swappgsout = -1;
328extern struct timeval timeout;
329
330void
331get_system_info(struct system_info *si)
332{
333	long total;
334	struct loadavg sysload;
335	int mib[2];
336	struct timeval boottime;
337	size_t bt_size;
338	int i;
339
340	/* get the cp_time array */
341	GETSYSCTL("kern.cp_time", cp_time);
342	GETSYSCTL("vm.loadavg", sysload);
343	GETSYSCTL("kern.lastpid", lastpid);
344
345	/* convert load averages to doubles */
346	for (i = 0; i < 3; i++)
347		si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
348
349	/* convert cp_time counts to percentages */
350	total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
351
352	/* sum memory & swap statistics */
353	{
354		static unsigned int swap_delay = 0;
355		static int swapavail = 0;
356		static int swapfree = 0;
357		static int bufspace = 0;
358		static int nspgsin, nspgsout;
359
360		GETSYSCTL("vfs.bufspace", bufspace);
361		GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
362		GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
363		GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
364		GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
365		GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
366		GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
367		GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
368		/* convert memory stats to Kbytes */
369		memory_stats[0] = pagetok(memory_stats[0]);
370		memory_stats[1] = pagetok(memory_stats[1]);
371		memory_stats[2] = pagetok(memory_stats[2]);
372		memory_stats[3] = pagetok(memory_stats[3]);
373		memory_stats[4] = bufspace / 1024;
374		memory_stats[5] = pagetok(memory_stats[5]);
375		memory_stats[6] = -1;
376
377		/* first interval */
378		if (swappgsin < 0) {
379			swap_stats[4] = 0;
380			swap_stats[5] = 0;
381		}
382
383		/* compute differences between old and new swap statistic */
384		else {
385			swap_stats[4] = pagetok(((nspgsin - swappgsin)));
386			swap_stats[5] = pagetok(((nspgsout - swappgsout)));
387		}
388
389		swappgsin = nspgsin;
390		swappgsout = nspgsout;
391
392		/* call CPU heavy swapmode() only for changes */
393		if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
394			swap_stats[3] = swapmode(&swapavail, &swapfree);
395			swap_stats[0] = swapavail;
396			swap_stats[1] = swapavail - swapfree;
397			swap_stats[2] = swapfree;
398		}
399		swap_delay = 1;
400		swap_stats[6] = -1;
401	}
402
403	/* set arrays and strings */
404	si->cpustates = cpu_states;
405	si->memory = memory_stats;
406	si->swap = swap_stats;
407
408
409	if (lastpid > 0) {
410		si->last_pid = lastpid;
411	} else {
412		si->last_pid = -1;
413	}
414
415	/*
416	 * Print how long system has been up.
417	 * (Found by looking getting "boottime" from the kernel)
418	 */
419	mib[0] = CTL_KERN;
420	mib[1] = KERN_BOOTTIME;
421	bt_size = sizeof(boottime);
422	if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
423	    boottime.tv_sec != 0) {
424		si->boottime = boottime;
425	} else {
426		si->boottime.tv_sec = -1;
427	}
428}
429
430#define NOPROC	((void *)-1)
431
432/*
433 * We need to compare data from the old process entry with the new
434 * process entry.
435 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
436 * structure to cache the mapping.  We also use a negative cache pointer
437 * of NOPROC to avoid duplicate lookups.
438 * XXX: this could be done when the actual processes are fetched, we do
439 * it here out of laziness.
440 */
441const struct kinfo_proc *
442get_old_proc(struct kinfo_proc *pp)
443{
444	struct kinfo_proc **oldpp, *oldp;
445
446	/*
447	 * If this is the first fetch of the kinfo_procs then we don't have
448	 * any previous entries.
449	 */
450	if (previous_proc_count == 0)
451		return (NULL);
452	/* negative cache? */
453	if (pp->ki_udata == NOPROC)
454		return (NULL);
455	/* cached? */
456	if (pp->ki_udata != NULL)
457		return (pp->ki_udata);
458	/*
459	 * Not cached,
460	 * 1) look up based on pid.
461	 * 2) compare process start.
462	 * If we fail here, then setup a negative cache entry, otherwise
463	 * cache it.
464	 */
465	oldpp = bsearch(&pp, previous_pref, previous_proc_count,
466	    sizeof(*previous_pref), compare_pid);
467	if (oldpp == NULL) {
468		pp->ki_udata = NOPROC;
469		return (NULL);
470	}
471	oldp = *oldpp;
472	if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
473		pp->ki_udata = NOPROC;
474		return (NULL);
475	}
476	pp->ki_udata = oldp;
477	return (oldp);
478}
479
480/*
481 * Return the total amount of IO done in blocks in/out and faults.
482 * store the values individually in the pointers passed in.
483 */
484long
485get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
486    long *vcsw, long *ivcsw)
487{
488	const struct kinfo_proc *oldp;
489	static struct kinfo_proc dummy;
490	long ret;
491
492	oldp = get_old_proc(pp);
493	if (oldp == NULL) {
494		bzero(&dummy, sizeof(dummy));
495		oldp = &dummy;
496	}
497	*inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
498	*oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
499	*flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
500	*vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
501	*ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
502	ret =
503	    (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
504	    (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
505	    (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
506	return (ret);
507}
508
509/*
510 * Return the total number of block in/out and faults by a process.
511 */
512long
513get_io_total(struct kinfo_proc *pp)
514{
515	long dummy;
516
517	return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
518}
519
520static struct handle handle;
521
522caddr_t
523get_process_info(struct system_info *si, struct process_select *sel,
524    int (*compare)(const void *, const void *))
525{
526	int i;
527	int total_procs;
528	long p_io;
529	long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
530	int active_procs;
531	struct kinfo_proc **prefp;
532	struct kinfo_proc *pp;
533	struct kinfo_proc *prev_pp = NULL;
534
535	/* these are copied out of sel for speed */
536	int show_idle;
537	int show_self;
538	int show_system;
539	int show_uid;
540	int show_command;
541
542	/*
543	 * Save the previous process info.
544	 */
545	if (previous_proc_count_max < nproc) {
546		free(previous_procs);
547		previous_procs = malloc(nproc * sizeof(*previous_procs));
548		free(previous_pref);
549		previous_pref = malloc(nproc * sizeof(*previous_pref));
550		if (previous_procs == NULL || previous_pref == NULL) {
551			(void) fprintf(stderr, "top: Out of memory.\n");
552			quit(23);
553		}
554		previous_proc_count_max = nproc;
555	}
556	if (nproc) {
557		for (i = 0; i < nproc; i++)
558			previous_pref[i] = &previous_procs[i];
559		bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
560		qsort(previous_pref, nproc, sizeof(*previous_pref),
561		    compare_pid);
562	}
563	previous_proc_count = nproc;
564
565	pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
566	if (nproc > onproc)
567		pref = realloc(pref, sizeof(*pref) * (onproc = nproc));
568	if (pref == NULL || pbase == NULL) {
569		(void) fprintf(stderr, "top: Out of memory.\n");
570		quit(23);
571	}
572	/* get a pointer to the states summary array */
573	si->procstates = process_states;
574
575	/* set up flags which define what we are going to select */
576	show_idle = sel->idle;
577	show_self = sel->self == -1;
578	show_system = sel->system;
579	show_uid = sel->uid != -1;
580	show_command = sel->command != NULL;
581
582	/* count up process states and get pointers to interesting procs */
583	total_procs = 0;
584	active_procs = 0;
585	total_inblock = 0;
586	total_oublock = 0;
587	total_majflt = 0;
588	memset((char *)process_states, 0, sizeof(process_states));
589	prefp = pref;
590	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
591
592		if (pp->ki_stat == 0)
593			/* not in use */
594			continue;
595
596		if (!show_self && pp->ki_pid == sel->self)
597			/* skip self */
598			continue;
599
600		if (!show_system && (pp->ki_flag & P_SYSTEM))
601			/* skip system process */
602			continue;
603
604		p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
605		    &p_vcsw, &p_ivcsw);
606		total_inblock += p_inblock;
607		total_oublock += p_oublock;
608		total_majflt += p_majflt;
609		total_procs++;
610		process_states[pp->ki_stat]++;
611
612		if (pp->ki_stat == SZOMB)
613			/* skip zombies */
614			continue;
615
616		if (displaymode == DISP_CPU && !show_idle &&
617		    (pp->ki_pctcpu == 0 ||
618		     pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
619			/* skip idle or non-running processes */
620			continue;
621
622		if (displaymode == DISP_IO && !show_idle && p_io == 0)
623			/* skip processes that aren't doing I/O */
624			continue;
625
626		if (show_uid && pp->ki_ruid != (uid_t)sel->uid)
627			/* skip proc. that don't belong to the selected UID */
628			continue;
629
630		/*
631		 * When not showing threads, take the first thread
632		 * for output and add the fields that we can from
633		 * the rest of the process's threads rather than
634		 * using the system's mostly-broken KERN_PROC_PROC.
635		 */
636		if (sel->thread || prev_pp == NULL ||
637		    prev_pp->ki_pid != pp->ki_pid) {
638			*prefp++ = pp;
639			active_procs++;
640			prev_pp = pp;
641		} else {
642			prev_pp->ki_pctcpu += pp->ki_pctcpu;
643		}
644	}
645
646	/* if requested, sort the "interesting" processes */
647	if (compare != NULL)
648		qsort(pref, active_procs, sizeof(*pref), compare);
649
650	/* remember active and total counts */
651	si->p_total = total_procs;
652	si->p_active = pref_len = active_procs;
653
654	/* pass back a handle */
655	handle.next_proc = pref;
656	handle.remaining = active_procs;
657	return ((caddr_t)&handle);
658}
659
660static char fmt[128];	/* static area where result is built */
661
662char *
663format_next_process(caddr_t handle, char *(*get_userid)(int), int flags)
664{
665	struct kinfo_proc *pp;
666	const struct kinfo_proc *oldp;
667	long cputime;
668	double pct;
669	struct handle *hp;
670	char status[16];
671	int state;
672	struct rusage ru, *rup;
673	long p_tot, s_tot;
674	char *proc_fmt, thr_buf[6], jid_buf[6];
675	char *cmdbuf = NULL;
676	char **args;
677
678	/* find and remember the next proc structure */
679	hp = (struct handle *)handle;
680	pp = *(hp->next_proc++);
681	hp->remaining--;
682
683	/* get the process's command name */
684	if ((pp->ki_flag & P_INMEM) == 0) {
685		/*
686		 * Print swapped processes as <pname>
687		 */
688		size_t len;
689
690		len = strlen(pp->ki_comm);
691		if (len > sizeof(pp->ki_comm) - 3)
692			len = sizeof(pp->ki_comm) - 3;
693		memmove(pp->ki_comm + 1, pp->ki_comm, len);
694		pp->ki_comm[0] = '<';
695		pp->ki_comm[len + 1] = '>';
696		pp->ki_comm[len + 2] = '\0';
697	}
698
699	/*
700	 * Convert the process's runtime from microseconds to seconds.  This
701	 * time includes the interrupt time although that is not wanted here.
702	 * ps(1) is similarly sloppy.
703	 */
704	cputime = (pp->ki_runtime + 500000) / 1000000;
705
706	/* calculate the base for cpu percentages */
707	pct = pctdouble(pp->ki_pctcpu);
708
709	/* generate "STATE" field */
710	switch (state = pp->ki_stat) {
711	case SRUN:
712		if (smpmode && pp->ki_oncpu != 0xff)
713			sprintf(status, "CPU%d", pp->ki_oncpu);
714		else
715			strcpy(status, "RUN");
716		break;
717	case SLOCK:
718		if (pp->ki_kiflag & KI_LOCKBLOCK) {
719			sprintf(status, "*%.6s", pp->ki_lockname);
720			break;
721		}
722		/* fall through */
723	case SSLEEP:
724		if (pp->ki_wmesg != NULL) {
725			sprintf(status, "%.6s", pp->ki_wmesg);
726			break;
727		}
728		/* FALLTHROUGH */
729	default:
730
731		if (state >= 0 &&
732		    state < sizeof(state_abbrev) / sizeof(*state_abbrev))
733			sprintf(status, "%.6s", state_abbrev[state]);
734		else
735			sprintf(status, "?%5d", state);
736		break;
737	}
738
739	cmdbuf = (char *)malloc(cmdlengthdelta + 1);
740	if (cmdbuf == NULL) {
741		warn("malloc(%d)", cmdlengthdelta + 1);
742		return NULL;
743	}
744
745	if (!(flags & FMT_SHOWARGS)) {
746		if (ps.thread && pp->ki_flag & P_HADTHREADS &&
747		    pp->ki_ocomm[0]) {
748			snprintf(cmdbuf, cmdlengthdelta, "{%s}", pp->ki_ocomm);
749		} else {
750			snprintf(cmdbuf, cmdlengthdelta, "%s", pp->ki_comm);
751		}
752	} else {
753		if (pp->ki_flag & P_SYSTEM ||
754		    pp->ki_args == NULL ||
755		    (args = kvm_getargv(kd, pp, cmdlengthdelta)) == NULL ||
756		    !(*args)) {
757			if (ps.thread && pp->ki_flag & P_HADTHREADS &&
758		    	pp->ki_ocomm[0]) {
759				snprintf(cmdbuf, cmdlengthdelta,
760				    "{%s}", pp->ki_ocomm);
761			} else {
762				snprintf(cmdbuf, cmdlengthdelta,
763				    "[%s]", pp->ki_comm);
764			}
765		} else {
766			char *src, *dst, *argbuf;
767			char *cmd;
768			size_t argbuflen;
769			size_t len;
770
771			argbuflen = cmdlengthdelta * 4;
772			argbuf = (char *)malloc(argbuflen + 1);
773			if (argbuf == NULL) {
774				warn("malloc(%d)", argbuflen + 1);
775				free(cmdbuf);
776				return NULL;
777			}
778
779			dst = argbuf;
780
781			/* Extract cmd name from argv */
782			cmd = strrchr(*args, '/');
783			if (cmd == NULL)
784				cmd = *args;
785			else
786				cmd++;
787
788			for (; (src = *args++) != NULL; ) {
789				if (*src == '\0')
790					continue;
791				len = (argbuflen - (dst - argbuf) - 1) / 4;
792				strvisx(dst, src,
793				    strlen(src) < len ? strlen(src) : len,
794				    VIS_NL | VIS_CSTYLE);
795				while (*dst != '\0')
796					dst++;
797				if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
798					*dst++ = ' '; /* add delimiting space */
799			}
800			if (dst != argbuf && dst[-1] == ' ')
801				dst--;
802			*dst = '\0';
803
804			if (strcmp(cmd, pp->ki_comm) != 0 )
805				snprintf(cmdbuf, cmdlengthdelta,
806				    "%s (%s)",argbuf,  pp->ki_comm);
807			else
808				strlcpy(cmdbuf, argbuf, cmdlengthdelta);
809
810			free(argbuf);
811		}
812	}
813
814	if (ps.jail == 0)
815		jid_buf[0] = '\0';
816	else
817		snprintf(jid_buf, sizeof(jid_buf), " %*d",
818		    sizeof(jid_buf) - 3, pp->ki_jid);
819
820	if (displaymode == DISP_IO) {
821		oldp = get_old_proc(pp);
822		if (oldp != NULL) {
823			ru.ru_inblock = RU(pp)->ru_inblock -
824			    RU(oldp)->ru_inblock;
825			ru.ru_oublock = RU(pp)->ru_oublock -
826			    RU(oldp)->ru_oublock;
827			ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
828			ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
829			ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
830			rup = &ru;
831		} else {
832			rup = RU(pp);
833		}
834		p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
835		s_tot = total_inblock + total_oublock + total_majflt;
836
837		sprintf(fmt, io_Proc_format,
838		    pp->ki_pid,
839		    jid_buf,
840		    namelength, namelength, (*get_userid)(pp->ki_ruid),
841		    rup->ru_nvcsw,
842		    rup->ru_nivcsw,
843		    rup->ru_inblock,
844		    rup->ru_oublock,
845		    rup->ru_majflt,
846		    p_tot,
847		    s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
848		    screen_width > cmdlengthdelta ?
849		    screen_width - cmdlengthdelta : 0,
850		    printable(cmdbuf));
851
852		free(cmdbuf);
853
854		return (fmt);
855	}
856
857	/* format this entry */
858	proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
859	if (ps.thread != 0)
860		thr_buf[0] = '\0';
861	else
862		snprintf(thr_buf, sizeof(thr_buf), "%*d ",
863		    sizeof(thr_buf) - 2, pp->ki_numthreads);
864
865	sprintf(fmt, proc_fmt,
866	    pp->ki_pid,
867	    jid_buf,
868	    namelength, namelength, (*get_userid)(pp->ki_ruid),
869	    thr_buf,
870	    pp->ki_pri.pri_level - PZERO,
871	    format_nice(pp),
872	    format_k2(PROCSIZE(pp)),
873	    format_k2(pagetok(pp->ki_rssize)),
874	    status,
875	    smpmode ? pp->ki_lastcpu : 0,
876	    format_time(cputime),
877	    ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
878	    screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
879	    printable(cmdbuf));
880
881	free(cmdbuf);
882
883	/* return the result */
884	return (fmt);
885}
886
887static void
888getsysctl(const char *name, void *ptr, size_t len)
889{
890	size_t nlen = len;
891
892	if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
893		fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
894		    strerror(errno));
895		quit(23);
896	}
897	if (nlen != len) {
898		fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
899		    name, (unsigned long)len, (unsigned long)nlen);
900		quit(23);
901	}
902}
903
904static const char *
905format_nice(const struct kinfo_proc *pp)
906{
907	const char *fifo, *kthread;
908	int rtpri;
909	static char nicebuf[4 + 1];
910
911	fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
912	kthread = (pp->ki_flag & P_KTHREAD) ? "k" : "";
913	switch (PRI_BASE(pp->ki_pri.pri_class)) {
914	case PRI_ITHD:
915		return ("-");
916	case PRI_REALTIME:
917		/*
918		 * XXX: the kernel doesn't tell us the original rtprio and
919		 * doesn't really know what it was, so to recover it we
920		 * must be more chummy with the implementation than the
921		 * implementation is with itself.  pri_user gives a
922		 * constant "base" priority, but is only initialized
923		 * properly for user threads.  pri_native gives what the
924		 * kernel calls the "base" priority, but it isn't constant
925		 * since it is changed by priority propagation.  pri_native
926		 * also isn't properly initialized for all threads, but it
927		 * is properly initialized for kernel realtime and idletime
928		 * threads.  Thus we use pri_user for the base priority of
929		 * user threads (it is always correct) and pri_native for
930		 * the base priority of kernel realtime and idletime threads
931		 * (there is nothing better, and it is usually correct).
932		 *
933		 * The field width and thus the buffer are too small for
934		 * values like "kr31F", but such values shouldn't occur,
935		 * and if they do then the tailing "F" is not displayed.
936		 */
937		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
938		    pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
939		snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
940		    kthread, rtpri, fifo);
941		break;
942	case PRI_TIMESHARE:
943		if (pp->ki_flag & P_KTHREAD)
944			return ("-");
945		snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
946		break;
947	case PRI_IDLE:
948		/* XXX: as above. */
949		rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native :
950		    pp->ki_pri.pri_user) - PRI_MIN_IDLE;
951		snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
952		    kthread, rtpri, fifo);
953		break;
954	default:
955		return ("?");
956	}
957	return (nicebuf);
958}
959
960/* comparison routines for qsort */
961
962static int
963compare_pid(const void *p1, const void *p2)
964{
965	const struct kinfo_proc * const *pp1 = p1;
966	const struct kinfo_proc * const *pp2 = p2;
967
968	if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
969		abort();
970
971	return ((*pp1)->ki_pid - (*pp2)->ki_pid);
972}
973
974/*
975 *  proc_compare - comparison function for "qsort"
976 *	Compares the resource consumption of two processes using five
977 *	distinct keys.  The keys (in descending order of importance) are:
978 *	percent cpu, cpu ticks, state, resident set size, total virtual
979 *	memory usage.  The process states are ordered as follows (from least
980 *	to most important):  WAIT, zombie, sleep, stop, start, run.  The
981 *	array declaration below maps a process state index into a number
982 *	that reflects this ordering.
983 */
984
985static int sorted_state[] = {
986	0,	/* not used		*/
987	3,	/* sleep		*/
988	1,	/* ABANDONED (WAIT)	*/
989	6,	/* run			*/
990	5,	/* start		*/
991	2,	/* zombie		*/
992	4	/* stop			*/
993};
994
995
996#define ORDERKEY_PCTCPU(a, b) do { \
997	long diff; \
998	if (ps.wcpu) \
999		diff = floor(1.0E6 * weighted_cpu(pctdouble((b)->ki_pctcpu), \
1000		    (b))) - \
1001		    floor(1.0E6 * weighted_cpu(pctdouble((a)->ki_pctcpu), \
1002		    (a))); \
1003	else \
1004		diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \
1005	if (diff != 0) \
1006		return (diff > 0 ? 1 : -1); \
1007} while (0)
1008
1009#define ORDERKEY_CPTICKS(a, b) do { \
1010	int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1011	if (diff != 0) \
1012		return (diff > 0 ? 1 : -1); \
1013} while (0)
1014
1015#define ORDERKEY_STATE(a, b) do { \
1016	int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \
1017	if (diff != 0) \
1018		return (diff > 0 ? 1 : -1); \
1019} while (0)
1020
1021#define ORDERKEY_PRIO(a, b) do { \
1022	int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1023	if (diff != 0) \
1024		return (diff > 0 ? 1 : -1); \
1025} while (0)
1026
1027#define	ORDERKEY_THREADS(a, b) do { \
1028	int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1029	if (diff != 0) \
1030		return (diff > 0 ? 1 : -1); \
1031} while (0)
1032
1033#define ORDERKEY_RSSIZE(a, b) do { \
1034	long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1035	if (diff != 0) \
1036		return (diff > 0 ? 1 : -1); \
1037} while (0)
1038
1039#define ORDERKEY_MEM(a, b) do { \
1040	long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1041	if (diff != 0) \
1042		return (diff > 0 ? 1 : -1); \
1043} while (0)
1044
1045#define ORDERKEY_JID(a, b) do { \
1046	int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1047	if (diff != 0) \
1048		return (diff > 0 ? 1 : -1); \
1049} while (0)
1050
1051/* compare_cpu - the comparison function for sorting by cpu percentage */
1052
1053int
1054#ifdef ORDER
1055compare_cpu(void *arg1, void *arg2)
1056#else
1057proc_compare(void *arg1, void *arg2)
1058#endif
1059{
1060	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1061	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1062
1063	ORDERKEY_PCTCPU(p1, p2);
1064	ORDERKEY_CPTICKS(p1, p2);
1065	ORDERKEY_STATE(p1, p2);
1066	ORDERKEY_PRIO(p1, p2);
1067	ORDERKEY_RSSIZE(p1, p2);
1068	ORDERKEY_MEM(p1, p2);
1069
1070	return (0);
1071}
1072
1073#ifdef ORDER
1074/* "cpu" compare routines */
1075int compare_size(), compare_res(), compare_time(), compare_prio(),
1076    compare_threads();
1077
1078/*
1079 * "io" compare routines.  Context switches aren't i/o, but are displayed
1080 * on the "io" display.
1081 */
1082int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(),
1083    compare_vcsw(), compare_ivcsw();
1084
1085int (*compares[])() = {
1086	compare_cpu,
1087	compare_size,
1088	compare_res,
1089	compare_time,
1090	compare_prio,
1091	compare_threads,
1092	compare_iototal,
1093	compare_ioread,
1094	compare_iowrite,
1095	compare_iofault,
1096	compare_vcsw,
1097	compare_ivcsw,
1098	compare_jid,
1099	NULL
1100};
1101
1102/* compare_size - the comparison function for sorting by total memory usage */
1103
1104int
1105compare_size(void *arg1, void *arg2)
1106{
1107	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1108	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1109
1110	ORDERKEY_MEM(p1, p2);
1111	ORDERKEY_RSSIZE(p1, p2);
1112	ORDERKEY_PCTCPU(p1, p2);
1113	ORDERKEY_CPTICKS(p1, p2);
1114	ORDERKEY_STATE(p1, p2);
1115	ORDERKEY_PRIO(p1, p2);
1116
1117	return (0);
1118}
1119
1120/* compare_res - the comparison function for sorting by resident set size */
1121
1122int
1123compare_res(void *arg1, void *arg2)
1124{
1125	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1126	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1127
1128	ORDERKEY_RSSIZE(p1, p2);
1129	ORDERKEY_MEM(p1, p2);
1130	ORDERKEY_PCTCPU(p1, p2);
1131	ORDERKEY_CPTICKS(p1, p2);
1132	ORDERKEY_STATE(p1, p2);
1133	ORDERKEY_PRIO(p1, p2);
1134
1135	return (0);
1136}
1137
1138/* compare_time - the comparison function for sorting by total cpu time */
1139
1140int
1141compare_time(void *arg1, void *arg2)
1142{
1143	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1144	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1145
1146	ORDERKEY_CPTICKS(p1, p2);
1147	ORDERKEY_PCTCPU(p1, p2);
1148	ORDERKEY_STATE(p1, p2);
1149	ORDERKEY_PRIO(p1, p2);
1150	ORDERKEY_RSSIZE(p1, p2);
1151	ORDERKEY_MEM(p1, p2);
1152
1153	return (0);
1154}
1155
1156/* compare_prio - the comparison function for sorting by priority */
1157
1158int
1159compare_prio(void *arg1, void *arg2)
1160{
1161	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1162	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1163
1164	ORDERKEY_PRIO(p1, p2);
1165	ORDERKEY_CPTICKS(p1, p2);
1166	ORDERKEY_PCTCPU(p1, p2);
1167	ORDERKEY_STATE(p1, p2);
1168	ORDERKEY_RSSIZE(p1, p2);
1169	ORDERKEY_MEM(p1, p2);
1170
1171	return (0);
1172}
1173
1174/* compare_threads - the comparison function for sorting by threads */
1175int
1176compare_threads(void *arg1, void *arg2)
1177{
1178	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1179	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1180
1181	ORDERKEY_THREADS(p1, p2);
1182	ORDERKEY_PCTCPU(p1, p2);
1183	ORDERKEY_CPTICKS(p1, p2);
1184	ORDERKEY_STATE(p1, p2);
1185	ORDERKEY_PRIO(p1, p2);
1186	ORDERKEY_RSSIZE(p1, p2);
1187	ORDERKEY_MEM(p1, p2);
1188
1189	return (0);
1190}
1191
1192/* compare_jid - the comparison function for sorting by jid */
1193static int
1194compare_jid(const void *arg1, const void *arg2)
1195{
1196	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1197	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1198
1199	ORDERKEY_JID(p1, p2);
1200	ORDERKEY_PCTCPU(p1, p2);
1201	ORDERKEY_CPTICKS(p1, p2);
1202	ORDERKEY_STATE(p1, p2);
1203	ORDERKEY_PRIO(p1, p2);
1204	ORDERKEY_RSSIZE(p1, p2);
1205	ORDERKEY_MEM(p1, p2);
1206
1207	return (0);
1208}
1209#endif /* ORDER */
1210
1211/* assorted comparison functions for sorting by i/o */
1212
1213int
1214#ifdef ORDER
1215compare_iototal(void *arg1, void *arg2)
1216#else
1217io_compare(void *arg1, void *arg2)
1218#endif
1219{
1220	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1221	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1222
1223	return (get_io_total(p2) - get_io_total(p1));
1224}
1225
1226#ifdef ORDER
1227int
1228compare_ioread(void *arg1, void *arg2)
1229{
1230	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1231	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1232	long dummy, inp1, inp2;
1233
1234	(void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1235	(void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1236
1237	return (inp2 - inp1);
1238}
1239
1240int
1241compare_iowrite(void *arg1, void *arg2)
1242{
1243	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1244	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1245	long dummy, oup1, oup2;
1246
1247	(void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1248	(void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1249
1250	return (oup2 - oup1);
1251}
1252
1253int
1254compare_iofault(void *arg1, void *arg2)
1255{
1256	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1257	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1258	long dummy, flp1, flp2;
1259
1260	(void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1261	(void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1262
1263	return (flp2 - flp1);
1264}
1265
1266int
1267compare_vcsw(void *arg1, void *arg2)
1268{
1269	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1270	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1271	long dummy, flp1, flp2;
1272
1273	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1274	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1275
1276	return (flp2 - flp1);
1277}
1278
1279int
1280compare_ivcsw(void *arg1, void *arg2)
1281{
1282	struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1283	struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1284	long dummy, flp1, flp2;
1285
1286	(void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1287	(void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1288
1289	return (flp2 - flp1);
1290}
1291#endif /* ORDER */
1292
1293/*
1294 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1295 *		the process does not exist.
1296 *		It is EXTREMLY IMPORTANT that this function work correctly.
1297 *		If top runs setuid root (as in SVR4), then this function
1298 *		is the only thing that stands in the way of a serious
1299 *		security problem.  It validates requests for the "kill"
1300 *		and "renice" commands.
1301 */
1302
1303int
1304proc_owner(int pid)
1305{
1306	int cnt;
1307	struct kinfo_proc **prefp;
1308	struct kinfo_proc *pp;
1309
1310	prefp = pref;
1311	cnt = pref_len;
1312	while (--cnt >= 0) {
1313		pp = *prefp++;
1314		if (pp->ki_pid == (pid_t)pid)
1315			return ((int)pp->ki_ruid);
1316	}
1317	return (-1);
1318}
1319
1320static int
1321swapmode(int *retavail, int *retfree)
1322{
1323	int n;
1324	int pagesize = getpagesize();
1325	struct kvm_swap swapary[1];
1326
1327	*retavail = 0;
1328	*retfree = 0;
1329
1330#define CONVERT(v)	((quad_t)(v) * pagesize / 1024)
1331
1332	n = kvm_getswapinfo(kd, swapary, 1, 0);
1333	if (n < 0 || swapary[0].ksw_total == 0)
1334		return (0);
1335
1336	*retavail = CONVERT(swapary[0].ksw_total);
1337	*retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1338
1339	n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);
1340	return (n);
1341}
1342