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