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 */
57 static int check_nlist __P((struct nlist *));
58 static int getkval __P((unsigned long, int *, int, char *));
59 extern char* printable __P((char *));
60 int swapmode __P((int *retavail, int *retfree));
62 static int namelength;
66 /* get_process_info passes back a handle. This is what it looks like: */
70 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
71 int remaining; /* number of pointers remaining */
74 /* declarations for load_avg */
77 #define PP(pp, field) ((pp)->kp_proc . field)
78 #define EP(pp, field) ((pp)->kp_eproc . field)
79 #define VP(pp, field) ((pp)->kp_eproc.e_vm . field)
81 /* define what weighted cpu is. */
82 #define weighted_cpu(pct, pp) (PP((pp), p_swtime) == 0 ? 0.0 : \
83 ((pct) / (1.0 - exp(PP((pp), p_swtime) * logcpu))))
85 /* what we consider to be process size: */
86 #define PROCSIZE(pp) (VP((pp), vm_map.size) / 1024)
88 /* definitions for indices in the nlist array */
90 static struct nlist nlst[] = {
99 { "_bufspace" }, /* K in buffer cache */
101 { "_cnt" }, /* struct vmmeter cnt */
110 * These definitions control the format of the per-process area
113 static char smp_header[] =
114 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
116 #define smp_Proc_format \
117 "%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
119 static char up_header[] =
120 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
122 #define up_Proc_format \
123 "%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
127 /* process state names for the "STATE" column of the display */
128 /* the extra nulls in the string "run" are for adding a slash and
129 the processor number when needed */
131 char *state_abbrev[] =
133 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB",
139 /* values that we stash away in _init and use in later routines */
141 static double logcpu;
143 /* these are retrieved from the kernel in _init */
145 static load_avg ccpu;
147 /* these are offsets obtained via nlist and used in the get_ functions */
149 static unsigned long cp_time_offset;
150 static unsigned long avenrun_offset;
151 static unsigned long lastpid_offset;
153 static unsigned long cnt_offset;
154 static unsigned long bufspace_offset;
157 /* these are for calculating cpu state percentages */
159 static long cp_time[CPUSTATES];
160 static long cp_old[CPUSTATES];
161 static long cp_diff[CPUSTATES];
163 /* these are for detailing the process states */
165 int process_states[6];
166 char *procstatenames[] = {
167 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
172 /* these are for detailing the cpu states */
174 int cpu_states[CPUSTATES];
175 char *cpustatenames[] = {
176 "user", "nice", "system", "interrupt", "idle", NULL
179 /* these are for detailing the memory statistics */
182 char *memorynames[] = {
183 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
188 char *swapnames[] = {
190 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
195 /* these are for keeping track of the proc array */
198 static int onproc = -1;
200 static struct kinfo_proc *pbase;
201 static struct kinfo_proc **pref;
203 /* these are for getting the memory statistics */
205 static int pageshift; /* log base 2 of the pagesize */
207 /* define pagetok in terms of pageshift */
209 #define pagetok(size) ((size) << pageshift)
211 /* useful externals */
215 /* sorting orders. first is default */
216 char *ordernames[] = {
217 "cpu", "size", "res", "time", "pri", NULL
222 machine_init(statics)
224 struct statics *statics;
228 register int pagesize;
232 modelen = sizeof(smpmode);
233 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
234 sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
235 modelen != sizeof(smpmode))
238 while ((pw = getpwent()) != NULL) {
239 if (strlen(pw->pw_name) > namelength)
240 namelength = strlen(pw->pw_name);
247 if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
251 /* get the list of symbols we want to access in the kernel */
252 (void) kvm_nlist(kd, nlst);
253 if (nlst[0].n_type == 0)
255 fprintf(stderr, "top: nlist failed\n");
259 /* make sure they were all found */
260 if (i > 0 && check_nlist(nlst) > 0)
265 (void) getkval(nlst[X_CCPU].n_value, (int *)(&ccpu), sizeof(ccpu),
266 nlst[X_CCPU].n_name);
268 /* stash away certain offsets for later use */
269 cp_time_offset = nlst[X_CP_TIME].n_value;
270 avenrun_offset = nlst[X_AVENRUN].n_value;
271 lastpid_offset = nlst[X_LASTPID].n_value;
272 cnt_offset = nlst[X_CNT].n_value;
273 bufspace_offset = nlst[X_BUFSPACE].n_value;
275 /* this is used in calculating WCPU -- calculate it ahead of time */
276 logcpu = log(loaddouble(ccpu));
282 /* get the page size with "getpagesize" and calculate pageshift from it */
283 pagesize = getpagesize();
291 /* we only need the amount of log(2)1024 for our conversion */
292 pageshift -= LOG1024;
294 /* fill in the statics information */
295 statics->procstate_names = procstatenames;
296 statics->cpustate_names = cpustatenames;
297 statics->memory_names = memorynames;
298 statics->swap_names = swapnames;
300 statics->order_names = ordernames;
307 char *format_header(uname_field)
309 register char *uname_field;
313 static char Header[128];
315 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
316 namelength, namelength, uname_field);
318 cmdlength = 80 - strlen(Header) + 6;
323 static int swappgsin = -1;
324 static int swappgsout = -1;
325 extern struct timeval timeout;
330 struct system_info *si;
336 struct timeval boottime;
339 /* get the cp_time array */
340 (void) getkval(cp_time_offset, (int *)cp_time, sizeof(cp_time),
341 nlst[X_CP_TIME].n_name);
342 (void) getkval(avenrun_offset, (int *)avenrun, sizeof(avenrun),
343 nlst[X_AVENRUN].n_name);
345 (void) getkval(lastpid_offset, (int *)(&lastpid), sizeof(lastpid),
348 /* convert load averages to doubles */
351 register double *infoloadp;
355 struct loadavg sysload;
357 getkerninfo(KINFO_LOADAVG, &sysload, &size, 0);
360 infoloadp = si->load_avg;
362 for (i = 0; i < 3; i++)
365 *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
367 *infoloadp++ = loaddouble(*avenrunp++);
371 /* convert cp_time counts to percentages */
372 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
374 /* sum memory & swap statistics */
377 static unsigned int swap_delay = 0;
378 static int swapavail = 0;
379 static int swapfree = 0;
380 static int bufspace = 0;
382 (void) getkval(cnt_offset, (int *)(&sum), sizeof(sum),
384 (void) getkval(bufspace_offset, (int *)(&bufspace), sizeof(bufspace),
387 /* convert memory stats to Kbytes */
388 memory_stats[0] = pagetok(sum.v_active_count);
389 memory_stats[1] = pagetok(sum.v_inactive_count);
390 memory_stats[2] = pagetok(sum.v_wire_count);
391 memory_stats[3] = pagetok(sum.v_cache_count);
392 memory_stats[4] = bufspace / 1024;
393 memory_stats[5] = pagetok(sum.v_free_count);
394 memory_stats[6] = -1;
402 /* compute differences between old and new swap statistic */
404 swap_stats[4] = pagetok(((sum.v_swappgsin - swappgsin)));
405 swap_stats[5] = pagetok(((sum.v_swappgsout - swappgsout)));
408 swappgsin = sum.v_swappgsin;
409 swappgsout = sum.v_swappgsout;
411 /* call CPU heavy swapmode() only for changes */
412 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
413 swap_stats[3] = swapmode(&swapavail, &swapfree);
414 swap_stats[0] = swapavail;
415 swap_stats[1] = swapavail - swapfree;
416 swap_stats[2] = swapfree;
422 /* set arrays and strings */
423 si->cpustates = cpu_states;
424 si->memory = memory_stats;
425 si->swap = swap_stats;
429 si->last_pid = lastpid;
435 * Print how long system has been up.
436 * (Found by looking getting "boottime" from the kernel)
439 mib[1] = KERN_BOOTTIME;
440 bt_size = sizeof(boottime);
441 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
442 boottime.tv_sec != 0) {
443 si->boottime = boottime;
445 si->boottime.tv_sec = -1;
449 static struct handle handle;
451 caddr_t get_process_info(si, sel, compare)
453 struct system_info *si;
454 struct process_select *sel;
459 register int total_procs;
460 register int active_procs;
461 register struct kinfo_proc **prefp;
462 register struct kinfo_proc *pp;
464 /* these are copied out of sel for speed */
472 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
474 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
476 if (pref == NULL || pbase == NULL) {
477 (void) fprintf(stderr, "top: Out of memory.\n");
480 /* get a pointer to the states summary array */
481 si->procstates = process_states;
483 /* set up flags which define what we are going to select */
484 show_idle = sel->idle;
485 show_self = sel->self;
486 show_system = sel->system;
487 show_uid = sel->uid != -1;
488 show_command = sel->command != NULL;
490 /* count up process states and get pointers to interesting procs */
493 memset((char *)process_states, 0, sizeof(process_states));
495 for (pp = pbase, i = 0; i < nproc; pp++, i++)
498 * Place pointers to each valid proc structure in pref[].
499 * Process slots that are actually in use have a non-zero
500 * status field. Processes with P_SYSTEM set are system
501 * processes---these get ignored unless show_sysprocs is set.
503 if (PP(pp, p_stat) != 0 &&
504 (show_self != PP(pp, p_pid)) &&
505 (show_system || ((PP(pp, p_flag) & P_SYSTEM) == 0)))
508 process_states[(unsigned char) PP(pp, p_stat)]++;
509 if ((PP(pp, p_stat) != SZOMB) &&
510 (show_idle || (PP(pp, p_pctcpu) != 0) ||
511 (PP(pp, p_stat) == SRUN)) &&
512 (!show_uid || EP(pp, e_pcred.p_ruid) == (uid_t)sel->uid))
520 /* if requested, sort the "interesting" processes */
523 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
526 /* remember active and total counts */
527 si->p_total = total_procs;
528 si->p_active = pref_len = active_procs;
530 /* pass back a handle */
531 handle.next_proc = pref;
532 handle.remaining = active_procs;
533 return((caddr_t)&handle);
536 char fmt[128]; /* static area where result is built */
538 char *format_next_process(handle, get_userid)
541 char *(*get_userid)();
544 register struct kinfo_proc *pp;
545 register long cputime;
551 /* find and remember the next proc structure */
552 hp = (struct handle *)handle;
553 pp = *(hp->next_proc++);
556 /* get the process's command name */
557 if ((PP(pp, p_flag) & P_INMEM) == 0) {
559 * Print swapped processes as <pname>
561 char *comm = PP(pp, p_comm);
562 #define COMSIZ sizeof(PP(pp, p_comm))
564 (void) strncpy(buf, comm, COMSIZ);
566 (void) strncpy(&comm[1], buf, COMSIZ - 2);
567 comm[COMSIZ - 2] = '\0';
568 (void) strncat(comm, ">", COMSIZ - 1);
569 comm[COMSIZ - 1] = '\0';
573 * Convert the process's runtime from microseconds to seconds. This
574 * time includes the interrupt time although that is not wanted here.
575 * ps(1) is similarly sloppy.
577 cputime = (PP(pp, p_runtime) + 500000) / 1000000;
579 /* calculate the base for cpu percentages */
580 pct = pctdouble(PP(pp, p_pctcpu));
582 /* generate "STATE" field */
583 switch (state = PP(pp, p_stat)) {
585 if (smpmode && PP(pp, p_oncpu) != 0xff)
586 sprintf(status, "CPU%d", PP(pp, p_oncpu));
588 strcpy(status, "RUN");
591 if (PP(pp, p_wmesg) != NULL) {
592 sprintf(status, "%.6s", EP(pp, e_wmesg));
599 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
600 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
602 sprintf(status, "?%5d", state);
606 /* format this entry */
608 smpmode ? smp_Proc_format : up_Proc_format,
610 namelength, namelength,
611 (*get_userid)(EP(pp, e_pcred.p_ruid)),
612 PP(pp, p_priority) - PZERO,
615 * normal time -> nice value -20 - +20
616 * real time 0 - 31 -> nice value -52 - -21
617 * idle time 0 - 31 -> nice value +21 - +52
619 (PP(pp, p_rtprio.type) == RTP_PRIO_NORMAL ?
620 PP(pp, p_nice) - NZERO :
621 (RTP_PRIO_IS_REALTIME(PP(pp, p_rtprio.type)) ?
622 (PRIO_MIN - 1 - RTP_PRIO_MAX + PP(pp, p_rtprio.prio)) :
623 (PRIO_MAX + 1 + PP(pp, p_rtprio.prio)))),
624 format_k2(PROCSIZE(pp)),
625 format_k2(pagetok(VP(pp, vm_rssize))),
627 smpmode ? PP(pp, p_lastcpu) : 0,
628 format_time(cputime),
629 100.0 * weighted_cpu(pct, pp),
632 printable(PP(pp, p_comm)));
634 /* return the result */
640 * check_nlist(nlst) - checks the nlist to see if any symbols were not
641 * found. For every symbol that was not found, a one-line
642 * message is printed to stderr. The routine returns the
643 * number of symbols NOT found.
646 static int check_nlist(nlst)
648 register struct nlist *nlst;
653 /* check to see if we got ALL the symbols we requested */
654 /* this will write one line to stderr for every symbol not found */
657 while (nlst->n_name != NULL)
659 if (nlst->n_type == 0)
661 /* this one wasn't found */
662 (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
674 * getkval(offset, ptr, size, refstr) - get a value out of the kernel.
675 * "offset" is the byte offset into the kernel for the desired value,
676 * "ptr" points to a buffer into which the value is retrieved,
677 * "size" is the size of the buffer (and the object to retrieve),
678 * "refstr" is a reference string used when printing error meessages,
679 * if "refstr" starts with a '!', then a failure on read will not
680 * be fatal (this may seem like a silly way to do things, but I
681 * really didn't want the overhead of another argument).
685 static int getkval(offset, ptr, size, refstr)
687 unsigned long offset;
693 if (kvm_read(kd, offset, (char *) ptr, size) != size)
701 fprintf(stderr, "top: kvm_read for %s: %s\n",
702 refstr, strerror(errno));
709 /* comparison routines for qsort */
712 * proc_compare - comparison function for "qsort"
713 * Compares the resource consumption of two processes using five
714 * distinct keys. The keys (in descending order of importance) are:
715 * percent cpu, cpu ticks, state, resident set size, total virtual
716 * memory usage. The process states are ordered as follows (from least
717 * to most important): WAIT, zombie, sleep, stop, start, run. The
718 * array declaration below maps a process state index into a number
719 * that reflects this ordering.
722 static unsigned char sorted_state[] =
726 1, /* ABANDONED (WAIT) */
734 #define ORDERKEY_PCTCPU \
735 if (lresult = (long) PP(p2, p_pctcpu) - (long) PP(p1, p_pctcpu), \
736 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
738 #define ORDERKEY_CPTICKS \
739 if ((result = PP(p2, p_runtime) > PP(p1, p_runtime) ? 1 : \
740 PP(p2, p_runtime) < PP(p1, p_runtime) ? -1 : 0) == 0)
742 #define ORDERKEY_STATE \
743 if ((result = sorted_state[(unsigned char) PP(p2, p_stat)] - \
744 sorted_state[(unsigned char) PP(p1, p_stat)]) == 0)
746 #define ORDERKEY_PRIO \
747 if ((result = PP(p2, p_priority) - PP(p1, p_priority)) == 0)
749 #define ORDERKEY_RSSIZE \
750 if ((result = VP(p2, vm_rssize) - VP(p1, vm_rssize)) == 0)
752 #define ORDERKEY_MEM \
753 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
755 /* compare_cpu - the comparison function for sorting by cpu percentage */
759 compare_cpu(pp1, pp2)
761 proc_compare(pp1, pp2)
768 register struct kinfo_proc *p1;
769 register struct kinfo_proc *p2;
771 register pctcpu lresult;
773 /* remove one level of indirection */
774 p1 = *(struct kinfo_proc **) pp1;
775 p2 = *(struct kinfo_proc **) pp2;
789 /* compare routines */
790 int compare_size(), compare_res(), compare_time(), compare_prio();
792 int (*proc_compares[])() = {
801 /* compare_size - the comparison function for sorting by total memory usage */
804 compare_size(pp1, pp2)
810 register struct kinfo_proc *p1;
811 register struct kinfo_proc *p2;
813 register pctcpu lresult;
815 /* remove one level of indirection */
816 p1 = *(struct kinfo_proc **) pp1;
817 p2 = *(struct kinfo_proc **) pp2;
830 /* compare_res - the comparison function for sorting by resident set size */
833 compare_res(pp1, pp2)
839 register struct kinfo_proc *p1;
840 register struct kinfo_proc *p2;
842 register pctcpu lresult;
844 /* remove one level of indirection */
845 p1 = *(struct kinfo_proc **) pp1;
846 p2 = *(struct kinfo_proc **) pp2;
859 /* compare_time - the comparison function for sorting by total cpu time */
862 compare_time(pp1, pp2)
868 register struct kinfo_proc *p1;
869 register struct kinfo_proc *p2;
871 register pctcpu lresult;
873 /* remove one level of indirection */
874 p1 = *(struct kinfo_proc **) pp1;
875 p2 = *(struct kinfo_proc **) pp2;
888 /* compare_prio - the comparison function for sorting by cpu percentage */
891 compare_prio(pp1, pp2)
897 register struct kinfo_proc *p1;
898 register struct kinfo_proc *p2;
900 register pctcpu lresult;
902 /* remove one level of indirection */
903 p1 = *(struct kinfo_proc **) pp1;
904 p2 = *(struct kinfo_proc **) pp2;
919 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
920 * the process does not exist.
921 * It is EXTREMLY IMPORTANT that this function work correctly.
922 * If top runs setuid root (as in SVR4), then this function
923 * is the only thing that stands in the way of a serious
924 * security problem. It validates requests for the "kill"
925 * and "renice" commands.
934 register struct kinfo_proc **prefp;
935 register struct kinfo_proc *pp;
942 if (PP(pp, p_pid) == (pid_t)pid)
944 return((int)EP(pp, e_pcred.p_ruid));
952 * swapmode is based on a program called swapinfo written
953 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
956 #define SVAR(var) __STRING(var) /* to force expansion */
957 #define KGET(idx, var) \
958 KGET1(idx, &var, sizeof(var), SVAR(var))
959 #define KGET1(idx, p, s, msg) \
960 KGET2(nlst[idx].n_value, p, s, msg)
961 #define KGET2(addr, p, s, msg) \
962 if (kvm_read(kd, (u_long)(addr), p, s) != s) { \
963 warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
966 #define KGETRET(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)); \
974 swapmode(retavail, retfree)
979 int pagesize = getpagesize();
980 struct kvm_swap swapary[1];
985 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
987 n = kvm_getswapinfo(kd, swapary, 1, 0);
988 if (n < 0 || swapary[0].ksw_total == 0)
991 *retavail = CONVERT(swapary[0].ksw_total);
992 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
994 n = (int)((double)swapary[0].ksw_used * 100.0 /
995 (double)swapary[0].ksw_total);