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>
27 #include <sys/types.h>
28 #include <sys/signal.h>
29 #include <sys/param.h>
37 #include <sys/errno.h>
38 #include <sys/sysctl.h>
39 #include <sys/dkstat.h>
44 #include <sys/vmmeter.h>
45 #include <sys/resource.h>
46 #include <sys/rtprio.h>
52 #include <osreldate.h> /* for changes in kernel structures */
58 static int check_nlist __P((struct nlist *));
59 static int getkval __P((unsigned long, int *, int, char *));
60 extern char* printable __P((char *));
61 int swapmode __P((int *retavail, int *retfree));
63 static int namelength;
64 static int cmdlengthdelta;
67 /* get_process_info passes back a handle. This is what it looks like: */
71 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
72 int remaining; /* number of pointers remaining */
75 /* declarations for load_avg */
78 /* define what weighted cpu is. */
79 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
80 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
82 /* what we consider to be process size: */
83 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
85 /* definitions for indices in the nlist array */
87 static struct nlist nlst[] = {
96 { "_bufspace" }, /* K in buffer cache */
98 { "_cnt" }, /* struct vmmeter cnt */
107 * These definitions control the format of the per-process area
110 static char smp_header[] =
111 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
113 #define smp_Proc_format \
114 "%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
116 static char up_header[] =
117 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
119 #define up_Proc_format \
120 "%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
124 /* process state names for the "STATE" column of the display */
125 /* the extra nulls in the string "run" are for adding a slash and
126 the processor number when needed */
128 char *state_abbrev[] =
130 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "MUTEX"
136 /* values that we stash away in _init and use in later routines */
138 static double logcpu;
140 /* these are retrieved from the kernel in _init */
142 static load_avg ccpu;
144 /* these are offsets obtained via nlist and used in the get_ functions */
146 static unsigned long cp_time_offset;
147 static unsigned long avenrun_offset;
148 static unsigned long lastpid_offset;
150 static unsigned long cnt_offset;
151 static unsigned long bufspace_offset;
154 /* these are for calculating cpu state percentages */
156 static long cp_time[CPUSTATES];
157 static long cp_old[CPUSTATES];
158 static long cp_diff[CPUSTATES];
160 /* these are for detailing the process states */
162 int process_states[8];
163 char *procstatenames[] = {
164 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
165 " zombie, ", " waiting, ", " mutex, ",
169 /* these are for detailing the cpu states */
171 int cpu_states[CPUSTATES];
172 char *cpustatenames[] = {
173 "user", "nice", "system", "interrupt", "idle", NULL
176 /* these are for detailing the memory statistics */
179 char *memorynames[] = {
180 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
185 char *swapnames[] = {
187 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
192 /* these are for keeping track of the proc array */
195 static int onproc = -1;
197 static struct kinfo_proc *pbase;
198 static struct kinfo_proc **pref;
200 /* these are for getting the memory statistics */
202 static int pageshift; /* log base 2 of the pagesize */
204 /* define pagetok in terms of pageshift */
206 #define pagetok(size) ((size) << pageshift)
208 /* useful externals */
212 /* sorting orders. first is default */
213 char *ordernames[] = {
214 "cpu", "size", "res", "time", "pri", NULL
219 machine_init(statics)
221 struct statics *statics;
225 register int pagesize;
229 modelen = sizeof(smpmode);
230 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
231 sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
232 modelen != sizeof(smpmode))
235 while ((pw = getpwent()) != NULL) {
236 if (strlen(pw->pw_name) > namelength)
237 namelength = strlen(pw->pw_name);
244 if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
248 /* get the list of symbols we want to access in the kernel */
249 (void) kvm_nlist(kd, nlst);
250 if (nlst[0].n_type == 0)
252 fprintf(stderr, "top: nlist failed\n");
256 /* make sure they were all found */
257 if (i > 0 && check_nlist(nlst) > 0)
262 (void) getkval(nlst[X_CCPU].n_value, (int *)(&ccpu), sizeof(ccpu),
263 nlst[X_CCPU].n_name);
265 /* stash away certain offsets for later use */
266 cp_time_offset = nlst[X_CP_TIME].n_value;
267 avenrun_offset = nlst[X_AVENRUN].n_value;
268 lastpid_offset = nlst[X_LASTPID].n_value;
269 cnt_offset = nlst[X_CNT].n_value;
270 bufspace_offset = nlst[X_BUFSPACE].n_value;
272 /* this is used in calculating WCPU -- calculate it ahead of time */
273 logcpu = log(loaddouble(ccpu));
279 /* get the page size with "getpagesize" and calculate pageshift from it */
280 pagesize = getpagesize();
288 /* we only need the amount of log(2)1024 for our conversion */
289 pageshift -= LOG1024;
291 /* fill in the statics information */
292 statics->procstate_names = procstatenames;
293 statics->cpustate_names = cpustatenames;
294 statics->memory_names = memorynames;
295 statics->swap_names = swapnames;
297 statics->order_names = ordernames;
304 char *format_header(uname_field)
306 register char *uname_field;
310 static char Header[128];
312 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
313 namelength, namelength, uname_field);
315 cmdlengthdelta = strlen(Header) - 7;
320 static int swappgsin = -1;
321 static int swappgsout = -1;
322 extern struct timeval timeout;
327 struct system_info *si;
333 struct timeval boottime;
336 /* get the cp_time array */
337 (void) getkval(cp_time_offset, (int *)cp_time, sizeof(cp_time),
338 nlst[X_CP_TIME].n_name);
339 (void) getkval(avenrun_offset, (int *)avenrun, sizeof(avenrun),
340 nlst[X_AVENRUN].n_name);
342 (void) getkval(lastpid_offset, (int *)(&lastpid), sizeof(lastpid),
345 /* convert load averages to doubles */
348 register double *infoloadp;
352 struct loadavg sysload;
354 getkerninfo(KINFO_LOADAVG, &sysload, &size, 0);
357 infoloadp = si->load_avg;
359 for (i = 0; i < 3; i++)
362 *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
364 *infoloadp++ = loaddouble(*avenrunp++);
368 /* convert cp_time counts to percentages */
369 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
371 /* sum memory & swap statistics */
374 static unsigned int swap_delay = 0;
375 static int swapavail = 0;
376 static int swapfree = 0;
377 static int bufspace = 0;
379 (void) getkval(cnt_offset, (int *)(&sum), sizeof(sum),
381 (void) getkval(bufspace_offset, (int *)(&bufspace), sizeof(bufspace),
384 /* convert memory stats to Kbytes */
385 memory_stats[0] = pagetok(sum.v_active_count);
386 memory_stats[1] = pagetok(sum.v_inactive_count);
387 memory_stats[2] = pagetok(sum.v_wire_count);
388 memory_stats[3] = pagetok(sum.v_cache_count);
389 memory_stats[4] = bufspace / 1024;
390 memory_stats[5] = pagetok(sum.v_free_count);
391 memory_stats[6] = -1;
399 /* compute differences between old and new swap statistic */
401 swap_stats[4] = pagetok(((sum.v_swappgsin - swappgsin)));
402 swap_stats[5] = pagetok(((sum.v_swappgsout - swappgsout)));
405 swappgsin = sum.v_swappgsin;
406 swappgsout = sum.v_swappgsout;
408 /* call CPU heavy swapmode() only for changes */
409 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
410 swap_stats[3] = swapmode(&swapavail, &swapfree);
411 swap_stats[0] = swapavail;
412 swap_stats[1] = swapavail - swapfree;
413 swap_stats[2] = swapfree;
419 /* set arrays and strings */
420 si->cpustates = cpu_states;
421 si->memory = memory_stats;
422 si->swap = swap_stats;
426 si->last_pid = lastpid;
432 * Print how long system has been up.
433 * (Found by looking getting "boottime" from the kernel)
436 mib[1] = KERN_BOOTTIME;
437 bt_size = sizeof(boottime);
438 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
439 boottime.tv_sec != 0) {
440 si->boottime = boottime;
442 si->boottime.tv_sec = -1;
446 static struct handle handle;
448 caddr_t get_process_info(si, sel, compare)
450 struct system_info *si;
451 struct process_select *sel;
456 register int total_procs;
457 register int active_procs;
458 register struct kinfo_proc **prefp;
459 register struct kinfo_proc *pp;
461 /* these are copied out of sel for speed */
469 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
471 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
473 if (pref == NULL || pbase == NULL) {
474 (void) fprintf(stderr, "top: Out of memory.\n");
477 /* get a pointer to the states summary array */
478 si->procstates = process_states;
480 /* set up flags which define what we are going to select */
481 show_idle = sel->idle;
482 show_self = sel->self;
483 show_system = sel->system;
484 show_uid = sel->uid != -1;
485 show_command = sel->command != NULL;
487 /* count up process states and get pointers to interesting procs */
490 memset((char *)process_states, 0, sizeof(process_states));
492 for (pp = pbase, i = 0; i < nproc; pp++, i++)
495 * Place pointers to each valid proc structure in pref[].
496 * Process slots that are actually in use have a non-zero
497 * status field. Processes with P_SYSTEM set are system
498 * processes---these get ignored unless show_sysprocs is set.
500 if (pp->ki_stat != 0 &&
501 (show_self != pp->ki_pid) &&
502 (show_system || ((pp->ki_flag & P_SYSTEM) == 0)))
505 process_states[(unsigned char) pp->ki_stat]++;
506 if ((pp->ki_stat != SZOMB) &&
507 (show_idle || (pp->ki_pctcpu != 0) ||
508 (pp->ki_stat == SRUN)) &&
509 (!show_uid || pp->ki_ruid == (uid_t)sel->uid))
517 /* if requested, sort the "interesting" processes */
520 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
523 /* remember active and total counts */
524 si->p_total = total_procs;
525 si->p_active = pref_len = active_procs;
527 /* pass back a handle */
528 handle.next_proc = pref;
529 handle.remaining = active_procs;
530 return((caddr_t)&handle);
533 char fmt[128]; /* static area where result is built */
535 char *format_next_process(handle, get_userid)
538 char *(*get_userid)();
541 register struct kinfo_proc *pp;
542 register long cputime;
548 /* find and remember the next proc structure */
549 hp = (struct handle *)handle;
550 pp = *(hp->next_proc++);
553 /* get the process's command name */
554 if ((pp->ki_flag & P_INMEM) == 0) {
556 * Print swapped processes as <pname>
558 char *comm = pp->ki_comm;
559 #define COMSIZ sizeof(pp->ki_comm)
561 (void) strncpy(buf, comm, COMSIZ);
563 (void) strncpy(&comm[1], buf, COMSIZ - 2);
564 comm[COMSIZ - 2] = '\0';
565 (void) strncat(comm, ">", COMSIZ - 1);
566 comm[COMSIZ - 1] = '\0';
570 * Convert the process's runtime from microseconds to seconds. This
571 * time includes the interrupt time although that is not wanted here.
572 * ps(1) is similarly sloppy.
574 cputime = (pp->ki_runtime + 500000) / 1000000;
576 /* calculate the base for cpu percentages */
577 pct = pctdouble(pp->ki_pctcpu);
579 /* generate "STATE" field */
580 switch (state = pp->ki_stat) {
582 if (smpmode && pp->ki_oncpu != 0xff)
583 sprintf(status, "CPU%d", pp->ki_oncpu);
585 strcpy(status, "RUN");
588 if (pp->ki_kiflag & KI_MTXBLOCK) {
589 sprintf(status, "*%.6s", pp->ki_mtxname);
594 if (pp->ki_wmesg != NULL) {
595 sprintf(status, "%.6s", pp->ki_wmesg);
602 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
603 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
605 sprintf(status, "?%5d", state);
609 /* format this entry */
611 smpmode ? smp_Proc_format : up_Proc_format,
613 namelength, namelength,
614 (*get_userid)(pp->ki_ruid),
615 pp->ki_priority - PZERO,
618 * normal time -> nice value -20 - +20
619 * real time 0 - 31 -> nice value -52 - -21
620 * idle time 0 - 31 -> nice value +21 - +52
622 (pp->ki_rtprio.type == RTP_PRIO_NORMAL ?
623 pp->ki_nice - NZERO :
624 (RTP_PRIO_IS_REALTIME(pp->ki_rtprio.type) ?
625 (PRIO_MIN - 1 - RTP_PRIO_MAX + pp->ki_rtprio.prio) :
626 (PRIO_MAX + 1 + pp->ki_rtprio.prio))),
627 format_k2(PROCSIZE(pp)),
628 format_k2(pagetok(pp->ki_rssize)),
630 smpmode ? pp->ki_lastcpu : 0,
631 format_time(cputime),
632 100.0 * weighted_cpu(pct, pp),
634 screen_width > cmdlengthdelta ?
635 screen_width - cmdlengthdelta :
637 printable(pp->ki_comm));
639 /* return the result */
645 * check_nlist(nlst) - checks the nlist to see if any symbols were not
646 * found. For every symbol that was not found, a one-line
647 * message is printed to stderr. The routine returns the
648 * number of symbols NOT found.
651 static int check_nlist(nlst)
653 register struct nlist *nlst;
658 /* check to see if we got ALL the symbols we requested */
659 /* this will write one line to stderr for every symbol not found */
662 while (nlst->n_name != NULL)
664 if (nlst->n_type == 0)
666 /* this one wasn't found */
667 (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
679 * getkval(offset, ptr, size, refstr) - get a value out of the kernel.
680 * "offset" is the byte offset into the kernel for the desired value,
681 * "ptr" points to a buffer into which the value is retrieved,
682 * "size" is the size of the buffer (and the object to retrieve),
683 * "refstr" is a reference string used when printing error meessages,
684 * if "refstr" starts with a '!', then a failure on read will not
685 * be fatal (this may seem like a silly way to do things, but I
686 * really didn't want the overhead of another argument).
690 static int getkval(offset, ptr, size, refstr)
692 unsigned long offset;
698 if (kvm_read(kd, offset, (char *) ptr, size) != size)
706 fprintf(stderr, "top: kvm_read for %s: %s\n",
707 refstr, strerror(errno));
714 /* comparison routines for qsort */
717 * proc_compare - comparison function for "qsort"
718 * Compares the resource consumption of two processes using five
719 * distinct keys. The keys (in descending order of importance) are:
720 * percent cpu, cpu ticks, state, resident set size, total virtual
721 * memory usage. The process states are ordered as follows (from least
722 * to most important): WAIT, zombie, sleep, stop, start, run. The
723 * array declaration below maps a process state index into a number
724 * that reflects this ordering.
727 static unsigned char sorted_state[] =
731 1, /* ABANDONED (WAIT) */
739 #define ORDERKEY_PCTCPU \
740 if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
741 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
743 #define ORDERKEY_CPTICKS \
744 if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
745 p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
747 #define ORDERKEY_STATE \
748 if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
749 sorted_state[(unsigned char) p1->ki_stat]) == 0)
751 #define ORDERKEY_PRIO \
752 if ((result = p2->ki_priority - p1->ki_priority) == 0)
754 #define ORDERKEY_RSSIZE \
755 if ((result = p2->ki_rssize - p1->ki_rssize) == 0)
757 #define ORDERKEY_MEM \
758 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
760 /* compare_cpu - the comparison function for sorting by cpu percentage */
764 compare_cpu(pp1, pp2)
766 proc_compare(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;
794 /* compare routines */
795 int compare_size(), compare_res(), compare_time(), compare_prio();
797 int (*proc_compares[])() = {
806 /* compare_size - the comparison function for sorting by total memory usage */
809 compare_size(pp1, pp2)
815 register struct kinfo_proc *p1;
816 register struct kinfo_proc *p2;
818 register pctcpu lresult;
820 /* remove one level of indirection */
821 p1 = *(struct kinfo_proc **) pp1;
822 p2 = *(struct kinfo_proc **) pp2;
835 /* compare_res - the comparison function for sorting by resident set size */
838 compare_res(pp1, pp2)
844 register struct kinfo_proc *p1;
845 register struct kinfo_proc *p2;
847 register pctcpu lresult;
849 /* remove one level of indirection */
850 p1 = *(struct kinfo_proc **) pp1;
851 p2 = *(struct kinfo_proc **) pp2;
864 /* compare_time - the comparison function for sorting by total cpu time */
867 compare_time(pp1, pp2)
873 register struct kinfo_proc *p1;
874 register struct kinfo_proc *p2;
876 register pctcpu lresult;
878 /* remove one level of indirection */
879 p1 = *(struct kinfo_proc **) pp1;
880 p2 = *(struct kinfo_proc **) pp2;
893 /* compare_prio - the comparison function for sorting by cpu percentage */
896 compare_prio(pp1, pp2)
902 register struct kinfo_proc *p1;
903 register struct kinfo_proc *p2;
905 register pctcpu lresult;
907 /* remove one level of indirection */
908 p1 = *(struct kinfo_proc **) pp1;
909 p2 = *(struct kinfo_proc **) pp2;
924 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
925 * the process does not exist.
926 * It is EXTREMLY IMPORTANT that this function work correctly.
927 * If top runs setuid root (as in SVR4), then this function
928 * is the only thing that stands in the way of a serious
929 * security problem. It validates requests for the "kill"
930 * and "renice" commands.
939 register struct kinfo_proc **prefp;
940 register struct kinfo_proc *pp;
947 if (pp->ki_pid == (pid_t)pid)
949 return((int)pp->ki_ruid);
957 * swapmode is based on a program called swapinfo written
958 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
961 #define SVAR(var) __STRING(var) /* to force expansion */
962 #define KGET(idx, var) \
963 KGET1(idx, &var, sizeof(var), SVAR(var))
964 #define KGET1(idx, p, s, msg) \
965 KGET2(nlst[idx].n_value, p, s, msg)
966 #define KGET2(addr, p, s, msg) \
967 if (kvm_read(kd, (u_long)(addr), p, s) != s) { \
968 warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
971 #define KGETRET(addr, p, s, msg) \
972 if (kvm_read(kd, (u_long)(addr), p, s) != s) { \
973 warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
979 swapmode(retavail, retfree)
984 int pagesize = getpagesize();
985 struct kvm_swap swapary[1];
990 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
992 n = kvm_getswapinfo(kd, swapary, 1, 0);
993 if (n < 0 || swapary[0].ksw_total == 0)
996 *retavail = CONVERT(swapary[0].ksw_total);
997 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
999 n = (int)((double)swapary[0].ksw_used * 100.0 /
1000 (double)swapary[0].ksw_total);