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>
54 #include <osreldate.h> /* for changes in kernel structures */
61 static void getsysctl __P((char *, void *, size_t));
63 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
65 extern char* printable __P((char *));
66 int swapmode __P((int *retavail, int *retfree));
68 static int namelength;
69 static int cmdlengthdelta;
71 /* Prototypes for top internals */
74 /* get_process_info passes back a handle. This is what it looks like: */
78 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
79 int remaining; /* number of pointers remaining */
82 /* declarations for load_avg */
85 /* define what weighted cpu is. */
86 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
87 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
89 /* what we consider to be process size: */
90 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
92 /* definitions for indices in the nlist array */
95 * These definitions control the format of the per-process area
98 static char smp_header[] =
99 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
101 #define smp_Proc_format \
102 "%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
104 static char up_header[] =
105 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
107 #define up_Proc_format \
108 "%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
112 /* process state names for the "STATE" column of the display */
113 /* the extra nulls in the string "run" are for adding a slash and
114 the processor number when needed */
116 char *state_abbrev[] =
118 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "MUTEX"
124 /* values that we stash away in _init and use in later routines */
126 static double logcpu;
128 /* these are retrieved from the kernel in _init */
130 static load_avg ccpu;
132 /* these are used in the get_ functions */
136 /* these are for calculating cpu state percentages */
138 static long cp_time[CPUSTATES];
139 static long cp_old[CPUSTATES];
140 static long cp_diff[CPUSTATES];
142 /* these are for detailing the process states */
144 int process_states[8];
145 char *procstatenames[] = {
146 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
147 " zombie, ", " waiting, ", " mutex, ",
151 /* these are for detailing the cpu states */
153 int cpu_states[CPUSTATES];
154 char *cpustatenames[] = {
155 "user", "nice", "system", "interrupt", "idle", NULL
158 /* these are for detailing the memory statistics */
161 char *memorynames[] = {
162 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
167 char *swapnames[] = {
169 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
174 /* these are for keeping track of the proc array */
177 static int onproc = -1;
179 static struct kinfo_proc *pbase;
180 static struct kinfo_proc **pref;
182 /* these are for getting the memory statistics */
184 static int pageshift; /* log base 2 of the pagesize */
186 /* define pagetok in terms of pageshift */
188 #define pagetok(size) ((size) << pageshift)
190 /* useful externals */
194 /* sorting orders. first is default */
195 char *ordernames[] = {
196 "cpu", "size", "res", "time", "pri", NULL
201 machine_init(statics)
203 struct statics *statics;
206 register int pagesize;
210 modelen = sizeof(smpmode);
211 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
212 sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
213 modelen != sizeof(smpmode))
216 while ((pw = getpwent()) != NULL) {
217 if (strlen(pw->pw_name) > namelength)
218 namelength = strlen(pw->pw_name);
222 if (smpmode && namelength > 13)
224 else if (namelength > 15)
227 if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, "kvm_open")) == NULL)
230 GETSYSCTL("kern.ccpu", ccpu);
232 /* this is used in calculating WCPU -- calculate it ahead of time */
233 logcpu = log(loaddouble(ccpu));
239 /* get the page size with "getpagesize" and calculate pageshift from it */
240 pagesize = getpagesize();
248 /* we only need the amount of log(2)1024 for our conversion */
249 pageshift -= LOG1024;
251 /* fill in the statics information */
252 statics->procstate_names = procstatenames;
253 statics->cpustate_names = cpustatenames;
254 statics->memory_names = memorynames;
255 statics->swap_names = swapnames;
257 statics->order_names = ordernames;
264 char *format_header(uname_field)
266 register char *uname_field;
269 static char Header[128];
271 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
272 namelength, namelength, uname_field);
274 cmdlengthdelta = strlen(Header) - 7;
279 static int swappgsin = -1;
280 static int swappgsout = -1;
281 extern struct timeval timeout;
286 struct system_info *si;
290 struct loadavg sysload;
292 struct timeval boottime;
295 /* get the cp_time array */
296 GETSYSCTL("kern.cp_time", cp_time);
297 GETSYSCTL("vm.loadavg", sysload);
298 GETSYSCTL("kern.lastpid", lastpid);
300 /* convert load averages to doubles */
303 register double *infoloadp;
305 infoloadp = si->load_avg;
306 for (i = 0; i < 3; i++)
309 *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
311 *infoloadp++ = loaddouble(sysload.ldavg[i]);
315 /* convert cp_time counts to percentages */
316 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
318 /* sum memory & swap statistics */
320 static unsigned int swap_delay = 0;
321 static int swapavail = 0;
322 static int swapfree = 0;
323 static int bufspace = 0;
324 static int nspgsin, nspgsout;
326 GETSYSCTL("vfs.bufspace", bufspace);
327 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
328 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
329 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
330 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
331 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
332 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
333 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
334 /* convert memory stats to Kbytes */
335 memory_stats[0] = pagetok(memory_stats[0]);
336 memory_stats[1] = pagetok(memory_stats[1]);
337 memory_stats[2] = pagetok(memory_stats[2]);
338 memory_stats[3] = pagetok(memory_stats[3]);
339 memory_stats[4] = bufspace / 1024;
340 memory_stats[5] = pagetok(memory_stats[5]);
341 memory_stats[6] = -1;
349 /* compute differences between old and new swap statistic */
351 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
352 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
356 swappgsout = nspgsout;
358 /* call CPU heavy swapmode() only for changes */
359 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
360 swap_stats[3] = swapmode(&swapavail, &swapfree);
361 swap_stats[0] = swapavail;
362 swap_stats[1] = swapavail - swapfree;
363 swap_stats[2] = swapfree;
369 /* set arrays and strings */
370 si->cpustates = cpu_states;
371 si->memory = memory_stats;
372 si->swap = swap_stats;
376 si->last_pid = lastpid;
382 * Print how long system has been up.
383 * (Found by looking getting "boottime" from the kernel)
386 mib[1] = KERN_BOOTTIME;
387 bt_size = sizeof(boottime);
388 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
389 boottime.tv_sec != 0) {
390 si->boottime = boottime;
392 si->boottime.tv_sec = -1;
396 static struct handle handle;
398 caddr_t get_process_info(si, sel, compare)
400 struct system_info *si;
401 struct process_select *sel;
406 register int total_procs;
407 register int active_procs;
408 register struct kinfo_proc **prefp;
409 register struct kinfo_proc *pp;
411 /* these are copied out of sel for speed */
419 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
421 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
423 if (pref == NULL || pbase == NULL) {
424 (void) fprintf(stderr, "top: Out of memory.\n");
427 /* get a pointer to the states summary array */
428 si->procstates = process_states;
430 /* set up flags which define what we are going to select */
431 show_idle = sel->idle;
432 show_self = sel->self;
433 show_system = sel->system;
434 show_uid = sel->uid != -1;
435 show_command = sel->command != NULL;
437 /* count up process states and get pointers to interesting procs */
440 memset((char *)process_states, 0, sizeof(process_states));
442 for (pp = pbase, i = 0; i < nproc; pp++, i++)
445 * Place pointers to each valid proc structure in pref[].
446 * Process slots that are actually in use have a non-zero
447 * status field. Processes with P_SYSTEM set are system
448 * processes---these get ignored unless show_sysprocs is set.
450 if (pp->ki_stat != 0 &&
451 (show_self != pp->ki_pid) &&
452 (show_system || ((pp->ki_flag & P_SYSTEM) == 0)))
455 process_states[(unsigned char) pp->ki_stat]++;
456 if ((pp->ki_stat != SZOMB) &&
457 (show_idle || (pp->ki_pctcpu != 0) ||
458 (pp->ki_stat == SRUN)) &&
459 (!show_uid || pp->ki_ruid == (uid_t)sel->uid))
467 /* if requested, sort the "interesting" processes */
470 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
473 /* remember active and total counts */
474 si->p_total = total_procs;
475 si->p_active = pref_len = active_procs;
477 /* pass back a handle */
478 handle.next_proc = pref;
479 handle.remaining = active_procs;
480 return((caddr_t)&handle);
483 char fmt[128]; /* static area where result is built */
485 char *format_next_process(handle, get_userid)
488 char *(*get_userid)();
491 register struct kinfo_proc *pp;
492 register long cputime;
498 /* find and remember the next proc structure */
499 hp = (struct handle *)handle;
500 pp = *(hp->next_proc++);
503 /* get the process's command name */
504 if ((pp->ki_sflag & PS_INMEM) == 0) {
506 * Print swapped processes as <pname>
508 char *comm = pp->ki_comm;
509 #define COMSIZ sizeof(pp->ki_comm)
511 (void) strncpy(buf, comm, COMSIZ);
513 (void) strncpy(&comm[1], buf, COMSIZ - 2);
514 comm[COMSIZ - 2] = '\0';
515 (void) strncat(comm, ">", COMSIZ - 1);
516 comm[COMSIZ - 1] = '\0';
520 * Convert the process's runtime from microseconds to seconds. This
521 * time includes the interrupt time although that is not wanted here.
522 * ps(1) is similarly sloppy.
524 cputime = (pp->ki_runtime + 500000) / 1000000;
526 /* calculate the base for cpu percentages */
527 pct = pctdouble(pp->ki_pctcpu);
529 /* generate "STATE" field */
530 switch (state = pp->ki_stat) {
532 if (smpmode && pp->ki_oncpu != 0xff)
533 sprintf(status, "CPU%d", pp->ki_oncpu);
535 strcpy(status, "RUN");
538 if (pp->ki_kiflag & KI_MTXBLOCK) {
539 sprintf(status, "*%.6s", pp->ki_mtxname);
544 if (pp->ki_wmesg != NULL) {
545 sprintf(status, "%.6s", pp->ki_wmesg);
552 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
553 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
555 sprintf(status, "?%5d", state);
559 /* format this entry */
561 smpmode ? smp_Proc_format : up_Proc_format,
563 namelength, namelength,
564 (*get_userid)(pp->ki_ruid),
565 pp->ki_pri.pri_level - PZERO,
568 * normal time -> nice value -20 - +20
569 * real time 0 - 31 -> nice value -52 - -21
570 * idle time 0 - 31 -> nice value +21 - +52
572 (pp->ki_pri.pri_class == PRI_TIMESHARE ?
573 pp->ki_nice - NZERO :
574 (PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
575 (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
576 (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
577 format_k2(PROCSIZE(pp)),
578 format_k2(pagetok(pp->ki_rssize)),
580 smpmode ? pp->ki_lastcpu : 0,
581 format_time(cputime),
582 100.0 * weighted_cpu(pct, pp),
584 screen_width > cmdlengthdelta ?
585 screen_width - cmdlengthdelta :
587 printable(pp->ki_comm));
589 /* return the result */
593 static void getsysctl (name, ptr, len)
601 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
602 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
607 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
608 (unsigned long)len, (unsigned long)nlen);
613 /* comparison routines for qsort */
616 * proc_compare - comparison function for "qsort"
617 * Compares the resource consumption of two processes using five
618 * distinct keys. The keys (in descending order of importance) are:
619 * percent cpu, cpu ticks, state, resident set size, total virtual
620 * memory usage. The process states are ordered as follows (from least
621 * to most important): WAIT, zombie, sleep, stop, start, run. The
622 * array declaration below maps a process state index into a number
623 * that reflects this ordering.
626 static unsigned char sorted_state[] =
630 1, /* ABANDONED (WAIT) */
638 #define ORDERKEY_PCTCPU \
639 if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
640 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
642 #define ORDERKEY_CPTICKS \
643 if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
644 p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
646 #define ORDERKEY_STATE \
647 if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
648 sorted_state[(unsigned char) p1->ki_stat]) == 0)
650 #define ORDERKEY_PRIO \
651 if ((result = p2->ki_pri.pri_level - p1->ki_pri.pri_level) == 0)
653 #define ORDERKEY_RSSIZE \
654 if ((result = p2->ki_rssize - p1->ki_rssize) == 0)
656 #define ORDERKEY_MEM \
657 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
659 /* compare_cpu - the comparison function for sorting by cpu percentage */
663 compare_cpu(pp1, pp2)
665 proc_compare(pp1, pp2)
672 register struct kinfo_proc *p1;
673 register struct kinfo_proc *p2;
675 register pctcpu lresult;
677 /* remove one level of indirection */
678 p1 = *(struct kinfo_proc **) pp1;
679 p2 = *(struct kinfo_proc **) pp2;
693 /* compare routines */
694 int compare_size(), compare_res(), compare_time(), compare_prio();
696 int (*proc_compares[])() = {
705 /* compare_size - the comparison function for sorting by total memory usage */
708 compare_size(pp1, pp2)
714 register struct kinfo_proc *p1;
715 register struct kinfo_proc *p2;
717 register pctcpu lresult;
719 /* remove one level of indirection */
720 p1 = *(struct kinfo_proc **) pp1;
721 p2 = *(struct kinfo_proc **) pp2;
734 /* compare_res - the comparison function for sorting by resident set size */
737 compare_res(pp1, pp2)
743 register struct kinfo_proc *p1;
744 register struct kinfo_proc *p2;
746 register pctcpu lresult;
748 /* remove one level of indirection */
749 p1 = *(struct kinfo_proc **) pp1;
750 p2 = *(struct kinfo_proc **) pp2;
763 /* compare_time - the comparison function for sorting by total cpu time */
766 compare_time(pp1, pp2)
772 register struct kinfo_proc *p1;
773 register struct kinfo_proc *p2;
775 register pctcpu lresult;
777 /* remove one level of indirection */
778 p1 = *(struct kinfo_proc **) pp1;
779 p2 = *(struct kinfo_proc **) pp2;
792 /* compare_prio - the comparison function for sorting by cpu percentage */
795 compare_prio(pp1, pp2)
801 register struct kinfo_proc *p1;
802 register struct kinfo_proc *p2;
804 register pctcpu lresult;
806 /* remove one level of indirection */
807 p1 = *(struct kinfo_proc **) pp1;
808 p2 = *(struct kinfo_proc **) pp2;
823 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
824 * the process does not exist.
825 * It is EXTREMLY IMPORTANT that this function work correctly.
826 * If top runs setuid root (as in SVR4), then this function
827 * is the only thing that stands in the way of a serious
828 * security problem. It validates requests for the "kill"
829 * and "renice" commands.
838 register struct kinfo_proc **prefp;
839 register struct kinfo_proc *pp;
846 if (pp->ki_pid == (pid_t)pid)
848 return((int)pp->ki_ruid);
855 swapmode(retavail, retfree)
860 int pagesize = getpagesize();
861 struct kvm_swap swapary[1];
866 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
868 n = kvm_getswapinfo(kd, swapary, 1, 0);
869 if (n < 0 || swapary[0].ksw_total == 0)
872 *retavail = CONVERT(swapary[0].ksw_total);
873 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
875 n = (int)((double)swapary[0].ksw_used * 100.0 /
876 (double)swapary[0].ksw_total);