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