2 * top - a top users display for Unix
4 * SYNOPSIS: For FreeBSD-2.x and later
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/)
12 * This is the machine-dependent module for FreeBSD 2.2
14 * FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x
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>
28 #include <sys/types.h>
29 #include <sys/signal.h>
30 #include <sys/param.h>
39 #include <sys/errno.h>
40 #include <sys/sysctl.h>
41 #include <sys/dkstat.h>
46 #include <sys/vmmeter.h>
47 #include <sys/resource.h>
48 #include <sys/rtprio.h>
55 #include <osreldate.h> /* for changes in kernel structures */
62 static void getsysctl __P((char *, void *, size_t));
64 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
66 extern char* printable __P((char *));
67 int swapmode __P((int *retavail, int *retfree));
69 static int namelength;
70 static int cmdlengthdelta;
72 /* Prototypes for top internals */
75 /* get_process_info passes back a handle. This is what it looks like: */
79 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
80 int remaining; /* number of pointers remaining */
83 /* declarations for load_avg */
86 /* define what weighted cpu is. */
87 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
88 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
90 /* what we consider to be process size: */
91 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
93 /* definitions for indices in the nlist array */
96 * These definitions control the format of the per-process area
99 static char smp_header[] =
100 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
102 #define smp_Proc_format \
103 "%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
105 static char up_header[] =
106 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
108 #define up_Proc_format \
109 "%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
113 /* process state names for the "STATE" column of the display */
114 /* the extra nulls in the string "run" are for adding a slash and
115 the processor number when needed */
117 char *state_abbrev[] =
119 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "MUTEX"
125 /* values that we stash away in _init and use in later routines */
127 static double logcpu;
129 /* these are retrieved from the kernel in _init */
131 static load_avg ccpu;
133 /* these are used in the get_ functions */
137 /* these are for calculating cpu state percentages */
139 static long cp_time[CPUSTATES];
140 static long cp_old[CPUSTATES];
141 static long cp_diff[CPUSTATES];
143 /* these are for detailing the process states */
145 int process_states[8];
146 char *procstatenames[] = {
147 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
148 " zombie, ", " waiting, ", " mutex, ",
152 /* these are for detailing the cpu states */
154 int cpu_states[CPUSTATES];
155 char *cpustatenames[] = {
156 "user", "nice", "system", "interrupt", "idle", NULL
159 /* these are for detailing the memory statistics */
162 char *memorynames[] = {
163 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
168 char *swapnames[] = {
170 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
175 /* these are for keeping track of the proc array */
178 static int onproc = -1;
180 static struct kinfo_proc *pbase;
181 static struct kinfo_proc **pref;
183 /* these are for getting the memory statistics */
185 static int pageshift; /* log base 2 of the pagesize */
187 /* define pagetok in terms of pageshift */
189 #define pagetok(size) ((size) << pageshift)
191 /* useful externals */
195 /* sorting orders. first is default */
196 char *ordernames[] = {
197 "cpu", "size", "res", "time", "pri", NULL
202 machine_init(statics)
204 struct statics *statics;
207 register int pagesize;
211 modelen = sizeof(smpmode);
212 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
213 sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
214 modelen != sizeof(smpmode))
217 while ((pw = getpwent()) != NULL) {
218 if (strlen(pw->pw_name) > namelength)
219 namelength = strlen(pw->pw_name);
223 if (smpmode && namelength > 13)
225 else if (namelength > 15)
228 if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, "kvm_open")) == NULL)
231 GETSYSCTL("kern.ccpu", ccpu);
233 /* this is used in calculating WCPU -- calculate it ahead of time */
234 logcpu = log(loaddouble(ccpu));
240 /* get the page size with "getpagesize" and calculate pageshift from it */
241 pagesize = getpagesize();
249 /* we only need the amount of log(2)1024 for our conversion */
250 pageshift -= LOG1024;
252 /* fill in the statics information */
253 statics->procstate_names = procstatenames;
254 statics->cpustate_names = cpustatenames;
255 statics->memory_names = memorynames;
256 statics->swap_names = swapnames;
258 statics->order_names = ordernames;
265 char *format_header(uname_field)
267 register char *uname_field;
270 static char Header[128];
272 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
273 namelength, namelength, uname_field);
275 cmdlengthdelta = strlen(Header) - 7;
280 static int swappgsin = -1;
281 static int swappgsout = -1;
282 extern struct timeval timeout;
287 struct system_info *si;
291 struct loadavg sysload;
293 struct timeval boottime;
296 /* get the cp_time array */
297 GETSYSCTL("kern.cp_time", cp_time);
298 GETSYSCTL("vm.loadavg", sysload);
299 GETSYSCTL("kern.lastpid", lastpid);
301 /* convert load averages to doubles */
304 register double *infoloadp;
306 infoloadp = si->load_avg;
307 for (i = 0; i < 3; i++)
310 *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
312 *infoloadp++ = loaddouble(sysload.ldavg[i]);
316 /* convert cp_time counts to percentages */
317 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
319 /* sum memory & swap statistics */
321 static unsigned int swap_delay = 0;
322 static int swapavail = 0;
323 static int swapfree = 0;
324 static int bufspace = 0;
325 static int nspgsin, nspgsout;
327 GETSYSCTL("vfs.bufspace", bufspace);
328 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
329 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
330 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
331 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
332 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
333 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
334 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
335 /* convert memory stats to Kbytes */
336 memory_stats[0] = pagetok(memory_stats[0]);
337 memory_stats[1] = pagetok(memory_stats[1]);
338 memory_stats[2] = pagetok(memory_stats[2]);
339 memory_stats[3] = pagetok(memory_stats[3]);
340 memory_stats[4] = bufspace / 1024;
341 memory_stats[5] = pagetok(memory_stats[5]);
342 memory_stats[6] = -1;
350 /* compute differences between old and new swap statistic */
352 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
353 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
357 swappgsout = nspgsout;
359 /* call CPU heavy swapmode() only for changes */
360 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
361 swap_stats[3] = swapmode(&swapavail, &swapfree);
362 swap_stats[0] = swapavail;
363 swap_stats[1] = swapavail - swapfree;
364 swap_stats[2] = swapfree;
370 /* set arrays and strings */
371 si->cpustates = cpu_states;
372 si->memory = memory_stats;
373 si->swap = swap_stats;
377 si->last_pid = lastpid;
383 * Print how long system has been up.
384 * (Found by looking getting "boottime" from the kernel)
387 mib[1] = KERN_BOOTTIME;
388 bt_size = sizeof(boottime);
389 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
390 boottime.tv_sec != 0) {
391 si->boottime = boottime;
393 si->boottime.tv_sec = -1;
397 static struct handle handle;
399 caddr_t get_process_info(si, sel, compare)
401 struct system_info *si;
402 struct process_select *sel;
407 register int total_procs;
408 register int active_procs;
409 register struct kinfo_proc **prefp;
410 register struct kinfo_proc *pp;
412 /* these are copied out of sel for speed */
420 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
422 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
424 if (pref == NULL || pbase == NULL) {
425 (void) fprintf(stderr, "top: Out of memory.\n");
428 /* get a pointer to the states summary array */
429 si->procstates = process_states;
431 /* set up flags which define what we are going to select */
432 show_idle = sel->idle;
433 show_self = sel->self;
434 show_system = sel->system;
435 show_uid = sel->uid != -1;
436 show_command = sel->command != NULL;
438 /* count up process states and get pointers to interesting procs */
441 memset((char *)process_states, 0, sizeof(process_states));
443 for (pp = pbase, i = 0; i < nproc; pp++, i++)
446 * Place pointers to each valid proc structure in pref[].
447 * Process slots that are actually in use have a non-zero
448 * status field. Processes with P_SYSTEM set are system
449 * processes---these get ignored unless show_sysprocs is set.
451 if (pp->ki_stat != 0 &&
452 (show_self != pp->ki_pid) &&
453 (show_system || ((pp->ki_flag & P_SYSTEM) == 0)))
456 process_states[(unsigned char) pp->ki_stat]++;
457 if ((pp->ki_stat != SZOMB) &&
458 (show_idle || (pp->ki_pctcpu != 0) ||
459 (pp->ki_stat == SRUN)) &&
460 (!show_uid || pp->ki_ruid == (uid_t)sel->uid))
468 /* if requested, sort the "interesting" processes */
471 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
474 /* remember active and total counts */
475 si->p_total = total_procs;
476 si->p_active = pref_len = active_procs;
478 /* pass back a handle */
479 handle.next_proc = pref;
480 handle.remaining = active_procs;
481 return((caddr_t)&handle);
484 char fmt[128]; /* static area where result is built */
486 char *format_next_process(handle, get_userid)
489 char *(*get_userid)();
492 register struct kinfo_proc *pp;
493 register long cputime;
499 /* find and remember the next proc structure */
500 hp = (struct handle *)handle;
501 pp = *(hp->next_proc++);
504 /* get the process's command name */
505 if ((pp->ki_sflag & PS_INMEM) == 0) {
507 * Print swapped processes as <pname>
509 char *comm = pp->ki_comm;
510 #define COMSIZ sizeof(pp->ki_comm)
512 (void) strncpy(buf, comm, COMSIZ);
514 (void) strncpy(&comm[1], buf, COMSIZ - 2);
515 comm[COMSIZ - 2] = '\0';
516 (void) strncat(comm, ">", COMSIZ - 1);
517 comm[COMSIZ - 1] = '\0';
521 * Convert the process's runtime from microseconds to seconds. This
522 * time includes the interrupt time although that is not wanted here.
523 * ps(1) is similarly sloppy.
525 cputime = (pp->ki_runtime + 500000) / 1000000;
527 /* calculate the base for cpu percentages */
528 pct = pctdouble(pp->ki_pctcpu);
530 /* generate "STATE" field */
531 switch (state = pp->ki_stat) {
533 if (smpmode && pp->ki_oncpu != 0xff)
534 sprintf(status, "CPU%d", pp->ki_oncpu);
536 strcpy(status, "RUN");
539 if (pp->ki_kiflag & KI_MTXBLOCK) {
540 sprintf(status, "*%.6s", pp->ki_mtxname);
545 if (pp->ki_wmesg != NULL) {
546 sprintf(status, "%.6s", pp->ki_wmesg);
553 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
554 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
556 sprintf(status, "?%5d", state);
560 /* format this entry */
562 smpmode ? smp_Proc_format : up_Proc_format,
564 namelength, namelength,
565 (*get_userid)(pp->ki_ruid),
566 pp->ki_pri.pri_level - PZERO,
569 * normal time -> nice value -20 - +20
570 * real time 0 - 31 -> nice value -52 - -21
571 * idle time 0 - 31 -> nice value +21 - +52
573 (pp->ki_pri.pri_class == PRI_TIMESHARE ?
574 pp->ki_nice - NZERO :
575 (PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
576 (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
577 (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
578 format_k2(PROCSIZE(pp)),
579 format_k2(pagetok(pp->ki_rssize)),
581 smpmode ? pp->ki_lastcpu : 0,
582 format_time(cputime),
583 100.0 * weighted_cpu(pct, pp),
585 screen_width > cmdlengthdelta ?
586 screen_width - cmdlengthdelta :
588 printable(pp->ki_comm));
590 /* return the result */
594 static void getsysctl (name, ptr, len)
602 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
603 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
608 fprintf(stderr, "top: sysctl(%s...) expected %d, got %d\n", name,
614 /* comparison routines for qsort */
617 * proc_compare - comparison function for "qsort"
618 * Compares the resource consumption of two processes using five
619 * distinct keys. The keys (in descending order of importance) are:
620 * percent cpu, cpu ticks, state, resident set size, total virtual
621 * memory usage. The process states are ordered as follows (from least
622 * to most important): WAIT, zombie, sleep, stop, start, run. The
623 * array declaration below maps a process state index into a number
624 * that reflects this ordering.
627 static unsigned char sorted_state[] =
631 1, /* ABANDONED (WAIT) */
639 #define ORDERKEY_PCTCPU \
640 if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
641 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
643 #define ORDERKEY_CPTICKS \
644 if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
645 p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
647 #define ORDERKEY_STATE \
648 if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
649 sorted_state[(unsigned char) p1->ki_stat]) == 0)
651 #define ORDERKEY_PRIO \
652 if ((result = p2->ki_pri.pri_level - p1->ki_pri.pri_level) == 0)
654 #define ORDERKEY_RSSIZE \
655 if ((result = p2->ki_rssize - p1->ki_rssize) == 0)
657 #define ORDERKEY_MEM \
658 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
660 /* compare_cpu - the comparison function for sorting by cpu percentage */
664 compare_cpu(pp1, pp2)
666 proc_compare(pp1, pp2)
673 register struct kinfo_proc *p1;
674 register struct kinfo_proc *p2;
676 register pctcpu lresult;
678 /* remove one level of indirection */
679 p1 = *(struct kinfo_proc **) pp1;
680 p2 = *(struct kinfo_proc **) pp2;
694 /* compare routines */
695 int compare_size(), compare_res(), compare_time(), compare_prio();
697 int (*proc_compares[])() = {
706 /* compare_size - the comparison function for sorting by total memory usage */
709 compare_size(pp1, pp2)
715 register struct kinfo_proc *p1;
716 register struct kinfo_proc *p2;
718 register pctcpu lresult;
720 /* remove one level of indirection */
721 p1 = *(struct kinfo_proc **) pp1;
722 p2 = *(struct kinfo_proc **) pp2;
735 /* compare_res - the comparison function for sorting by resident set size */
738 compare_res(pp1, pp2)
744 register struct kinfo_proc *p1;
745 register struct kinfo_proc *p2;
747 register pctcpu lresult;
749 /* remove one level of indirection */
750 p1 = *(struct kinfo_proc **) pp1;
751 p2 = *(struct kinfo_proc **) pp2;
764 /* compare_time - the comparison function for sorting by total cpu time */
767 compare_time(pp1, pp2)
773 register struct kinfo_proc *p1;
774 register struct kinfo_proc *p2;
776 register pctcpu lresult;
778 /* remove one level of indirection */
779 p1 = *(struct kinfo_proc **) pp1;
780 p2 = *(struct kinfo_proc **) pp2;
793 /* compare_prio - the comparison function for sorting by cpu percentage */
796 compare_prio(pp1, pp2)
802 register struct kinfo_proc *p1;
803 register struct kinfo_proc *p2;
805 register pctcpu lresult;
807 /* remove one level of indirection */
808 p1 = *(struct kinfo_proc **) pp1;
809 p2 = *(struct kinfo_proc **) pp2;
824 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
825 * the process does not exist.
826 * It is EXTREMLY IMPORTANT that this function work correctly.
827 * If top runs setuid root (as in SVR4), then this function
828 * is the only thing that stands in the way of a serious
829 * security problem. It validates requests for the "kill"
830 * and "renice" commands.
839 register struct kinfo_proc **prefp;
840 register struct kinfo_proc *pp;
847 if (pp->ki_pid == (pid_t)pid)
849 return((int)pp->ki_ruid);
856 swapmode(retavail, retfree)
861 int pagesize = getpagesize();
862 struct kvm_swap swapary[1];
867 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
869 n = kvm_getswapinfo(kd, swapary, 1, 0);
870 if (n < 0 || swapary[0].ksw_total == 0)
873 *retavail = CONVERT(swapary[0].ksw_total);
874 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
876 n = (int)((double)swapary[0].ksw_used * 100.0 /
877 (double)swapary[0].ksw_total);