2 * top - a top users display for Unix
4 * SYNOPSIS: For FreeBSD-2.x system
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, 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>
22 * $Id: machine.c,v 1.22 1999/03/05 16:38:13 bde Exp $
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>
50 #include <sys/rlist.h>
53 #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;
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 PP(pp, field) ((pp)->kp_proc . field)
79 #define EP(pp, field) ((pp)->kp_eproc . field)
80 #define VP(pp, field) ((pp)->kp_eproc.e_vm . field)
82 /* define what weighted cpu is. */
83 #define weighted_cpu(pct, pp) (PP((pp), p_swtime) == 0 ? 0.0 : \
84 ((pct) / (1.0 - exp(PP((pp), p_swtime) * logcpu))))
86 /* what we consider to be process size: */
87 #define PROCSIZE(pp) (VP((pp), vm_map.size) / 1024)
89 /* definitions for indices in the nlist array */
91 static struct nlist nlst[] = {
100 { "_bufspace" }, /* K in buffer cache */
102 { "_cnt" }, /* struct vmmeter cnt */
111 * These definitions control the format of the per-process area
114 static char smp_header[] =
115 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
117 #define smp_Proc_format \
118 "%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
120 static char up_header[] =
121 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
123 #define up_Proc_format \
124 "%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
128 /* process state names for the "STATE" column of the display */
129 /* the extra nulls in the string "run" are for adding a slash and
130 the processor number when needed */
132 char *state_abbrev[] =
134 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB",
140 /* values that we stash away in _init and use in later routines */
142 static double logcpu;
144 /* these are retrieved from the kernel in _init */
146 static load_avg ccpu;
148 /* these are offsets obtained via nlist and used in the get_ functions */
150 static unsigned long cp_time_offset;
151 static unsigned long avenrun_offset;
152 static unsigned long lastpid_offset;
154 static unsigned long cnt_offset;
155 static unsigned long bufspace_offset;
158 /* these are for calculating cpu state percentages */
160 static long cp_time[CPUSTATES];
161 static long cp_old[CPUSTATES];
162 static long cp_diff[CPUSTATES];
164 /* these are for detailing the process states */
166 int process_states[6];
167 char *procstatenames[] = {
168 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
173 /* these are for detailing the cpu states */
175 int cpu_states[CPUSTATES];
176 char *cpustatenames[] = {
177 "user", "nice", "system", "interrupt", "idle", NULL
180 /* these are for detailing the memory statistics */
183 char *memorynames[] = {
184 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
189 char *swapnames[] = {
191 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
196 /* these are for keeping track of the proc array */
199 static int onproc = -1;
201 static struct kinfo_proc *pbase;
202 static struct kinfo_proc **pref;
204 /* these are for getting the memory statistics */
206 static int pageshift; /* log base 2 of the pagesize */
208 /* define pagetok in terms of pageshift */
210 #define pagetok(size) ((size) << pageshift)
212 /* useful externals */
216 /* sorting orders. first is default */
217 char *ordernames[] = {
218 "cpu", "size", "res", "time", "pri", NULL
223 machine_init(statics)
225 struct statics *statics;
229 register int pagesize;
233 modelen = sizeof(smpmode);
234 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
235 sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
236 modelen != sizeof(smpmode))
239 while ((pw = getpwent()) != NULL) {
240 if (strlen(pw->pw_name) > namelength)
241 namelength = strlen(pw->pw_name);
248 if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
252 /* get the list of symbols we want to access in the kernel */
253 (void) kvm_nlist(kd, nlst);
254 if (nlst[0].n_type == 0)
256 fprintf(stderr, "top: nlist failed\n");
260 /* make sure they were all found */
261 if (i > 0 && check_nlist(nlst) > 0)
266 (void) getkval(nlst[X_CCPU].n_value, (int *)(&ccpu), sizeof(ccpu),
267 nlst[X_CCPU].n_name);
269 /* stash away certain offsets for later use */
270 cp_time_offset = nlst[X_CP_TIME].n_value;
271 avenrun_offset = nlst[X_AVENRUN].n_value;
272 lastpid_offset = nlst[X_LASTPID].n_value;
273 cnt_offset = nlst[X_CNT].n_value;
274 bufspace_offset = nlst[X_BUFSPACE].n_value;
276 /* this is used in calculating WCPU -- calculate it ahead of time */
277 logcpu = log(loaddouble(ccpu));
283 /* get the page size with "getpagesize" and calculate pageshift from it */
284 pagesize = getpagesize();
292 /* we only need the amount of log(2)1024 for our conversion */
293 pageshift -= LOG1024;
295 /* fill in the statics information */
296 statics->procstate_names = procstatenames;
297 statics->cpustate_names = cpustatenames;
298 statics->memory_names = memorynames;
299 statics->swap_names = swapnames;
301 statics->order_names = ordernames;
308 char *format_header(uname_field)
310 register char *uname_field;
314 static char Header[128];
316 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
317 namelength, namelength, uname_field);
319 cmdlength = 80 - strlen(Header) + 6;
324 static int swappgsin = -1;
325 static int swappgsout = -1;
326 extern struct timeval timeout;
331 struct system_info *si;
337 struct timeval boottime;
340 /* get the cp_time array */
341 (void) getkval(cp_time_offset, (int *)cp_time, sizeof(cp_time),
342 nlst[X_CP_TIME].n_name);
343 (void) getkval(avenrun_offset, (int *)avenrun, sizeof(avenrun),
344 nlst[X_AVENRUN].n_name);
346 (void) getkval(lastpid_offset, (int *)(&lastpid), sizeof(lastpid),
349 /* convert load averages to doubles */
352 register double *infoloadp;
356 struct loadavg sysload;
358 getkerninfo(KINFO_LOADAVG, &sysload, &size, 0);
361 infoloadp = si->load_avg;
363 for (i = 0; i < 3; i++)
366 *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
368 *infoloadp++ = loaddouble(*avenrunp++);
372 /* convert cp_time counts to percentages */
373 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
375 /* sum memory & swap statistics */
378 static unsigned int swap_delay = 0;
379 static int swapavail = 0;
380 static int swapfree = 0;
381 static int bufspace = 0;
383 (void) getkval(cnt_offset, (int *)(&sum), sizeof(sum),
385 (void) getkval(bufspace_offset, (int *)(&bufspace), sizeof(bufspace),
388 /* convert memory stats to Kbytes */
389 memory_stats[0] = pagetok(sum.v_active_count);
390 memory_stats[1] = pagetok(sum.v_inactive_count);
391 memory_stats[2] = pagetok(sum.v_wire_count);
392 memory_stats[3] = pagetok(sum.v_cache_count);
393 memory_stats[4] = bufspace / 1024;
394 memory_stats[5] = pagetok(sum.v_free_count);
395 memory_stats[6] = -1;
403 /* compute differences between old and new swap statistic */
405 swap_stats[4] = pagetok(((sum.v_swappgsin - swappgsin)));
406 swap_stats[5] = pagetok(((sum.v_swappgsout - swappgsout)));
409 swappgsin = sum.v_swappgsin;
410 swappgsout = sum.v_swappgsout;
412 /* call CPU heavy swapmode() only for changes */
413 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
414 swap_stats[3] = swapmode(&swapavail, &swapfree);
415 swap_stats[0] = swapavail;
416 swap_stats[1] = swapavail - swapfree;
417 swap_stats[2] = swapfree;
423 /* set arrays and strings */
424 si->cpustates = cpu_states;
425 si->memory = memory_stats;
426 si->swap = swap_stats;
430 si->last_pid = lastpid;
436 * Print how long system has been up.
437 * (Found by looking getting "boottime" from the kernel)
440 mib[1] = KERN_BOOTTIME;
441 bt_size = sizeof(boottime);
442 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
443 boottime.tv_sec != 0) {
444 si->boottime = boottime;
446 si->boottime.tv_sec = -1;
450 static struct handle handle;
452 caddr_t get_process_info(si, sel, compare)
454 struct system_info *si;
455 struct process_select *sel;
460 register int total_procs;
461 register int active_procs;
462 register struct kinfo_proc **prefp;
463 register struct kinfo_proc *pp;
465 /* these are copied out of sel for speed */
473 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
475 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
477 if (pref == NULL || pbase == NULL) {
478 (void) fprintf(stderr, "top: Out of memory.\n");
481 /* get a pointer to the states summary array */
482 si->procstates = process_states;
484 /* set up flags which define what we are going to select */
485 show_idle = sel->idle;
486 show_self = sel->self;
487 show_system = sel->system;
488 show_uid = sel->uid != -1;
489 show_command = sel->command != NULL;
491 /* count up process states and get pointers to interesting procs */
494 memset((char *)process_states, 0, sizeof(process_states));
496 for (pp = pbase, i = 0; i < nproc; pp++, i++)
499 * Place pointers to each valid proc structure in pref[].
500 * Process slots that are actually in use have a non-zero
501 * status field. Processes with P_SYSTEM set are system
502 * processes---these get ignored unless show_sysprocs is set.
504 if (PP(pp, p_stat) != 0 &&
505 (show_self != PP(pp, p_pid)) &&
506 (show_system || ((PP(pp, p_flag) & P_SYSTEM) == 0)))
509 process_states[(unsigned char) PP(pp, p_stat)]++;
510 if ((PP(pp, p_stat) != SZOMB) &&
511 (show_idle || (PP(pp, p_pctcpu) != 0) ||
512 (PP(pp, p_stat) == SRUN)) &&
513 (!show_uid || EP(pp, e_pcred.p_ruid) == (uid_t)sel->uid))
521 /* if requested, sort the "interesting" processes */
524 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
527 /* remember active and total counts */
528 si->p_total = total_procs;
529 si->p_active = pref_len = active_procs;
531 /* pass back a handle */
532 handle.next_proc = pref;
533 handle.remaining = active_procs;
534 return((caddr_t)&handle);
537 char fmt[128]; /* static area where result is built */
539 char *format_next_process(handle, get_userid)
542 char *(*get_userid)();
545 register struct kinfo_proc *pp;
546 register long cputime;
552 /* find and remember the next proc structure */
553 hp = (struct handle *)handle;
554 pp = *(hp->next_proc++);
558 /* get the process's user struct and set cputime */
559 if ((PP(pp, p_flag) & P_INMEM) == 0) {
561 * Print swapped processes as <pname>
563 char *comm = PP(pp, p_comm);
564 #define COMSIZ sizeof(PP(pp, p_comm))
566 (void) strncpy(buf, comm, COMSIZ);
568 (void) strncpy(&comm[1], buf, COMSIZ - 2);
569 comm[COMSIZ - 2] = '\0';
570 (void) strncat(comm, ">", COMSIZ - 1);
571 comm[COMSIZ - 1] = '\0';
575 /* This does not produce the correct results */
576 cputime = PP(pp, p_uticks) + PP(pp, p_sticks) + PP(pp, p_iticks);
578 /* This does not count interrupts */
579 cputime = (PP(pp, p_runtime) / 1000 + 500) / 1000;
581 /* calculate the base for cpu percentages */
582 pct = pctdouble(PP(pp, p_pctcpu));
584 /* generate "STATE" field */
585 switch (state = PP(pp, p_stat)) {
587 if (smpmode && PP(pp, p_oncpu) != 0xff)
588 sprintf(status, "CPU%d", PP(pp, p_oncpu));
590 strcpy(status, "RUN");
593 if (PP(pp, p_wmesg) != NULL) {
594 sprintf(status, "%.6s", EP(pp, e_wmesg));
601 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
602 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
604 sprintf(status, "?%5d", state);
608 /* format this entry */
610 smpmode ? smp_Proc_format : up_Proc_format,
612 namelength, namelength,
613 (*get_userid)(EP(pp, e_pcred.p_ruid)),
614 PP(pp, p_priority) - PZERO,
617 * normal time -> nice value -20 - +20
618 * real time 0 - 31 -> nice value -52 - -21
619 * idle time 0 - 31 -> nice value +21 - +52
621 (PP(pp, p_rtprio.type) == RTP_PRIO_NORMAL ?
622 PP(pp, p_nice) - NZERO :
623 (PP(pp, p_rtprio.type) == RTP_PRIO_REALTIME ?
624 (PRIO_MIN - 1 - RTP_PRIO_MAX + PP(pp, p_rtprio.prio)) :
625 (PRIO_MAX + 1 + PP(pp, p_rtprio.prio)))),
626 format_k2(PROCSIZE(pp)),
627 format_k2(pagetok(VP(pp, vm_rssize))),
629 smpmode ? PP(pp, p_lastcpu) : 0,
630 format_time(cputime),
631 100.0 * weighted_cpu(pct, pp),
634 printable(PP(pp, p_comm)));
636 /* return the result */
642 * check_nlist(nlst) - checks the nlist to see if any symbols were not
643 * found. For every symbol that was not found, a one-line
644 * message is printed to stderr. The routine returns the
645 * number of symbols NOT found.
648 static int check_nlist(nlst)
650 register struct nlist *nlst;
655 /* check to see if we got ALL the symbols we requested */
656 /* this will write one line to stderr for every symbol not found */
659 while (nlst->n_name != NULL)
661 if (nlst->n_type == 0)
663 /* this one wasn't found */
664 (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
676 * getkval(offset, ptr, size, refstr) - get a value out of the kernel.
677 * "offset" is the byte offset into the kernel for the desired value,
678 * "ptr" points to a buffer into which the value is retrieved,
679 * "size" is the size of the buffer (and the object to retrieve),
680 * "refstr" is a reference string used when printing error meessages,
681 * if "refstr" starts with a '!', then a failure on read will not
682 * be fatal (this may seem like a silly way to do things, but I
683 * really didn't want the overhead of another argument).
687 static int getkval(offset, ptr, size, refstr)
689 unsigned long offset;
695 if (kvm_read(kd, offset, (char *) ptr, size) != size)
703 fprintf(stderr, "top: kvm_read for %s: %s\n",
704 refstr, strerror(errno));
711 /* comparison routines for qsort */
714 * proc_compare - comparison function for "qsort"
715 * Compares the resource consumption of two processes using five
716 * distinct keys. The keys (in descending order of importance) are:
717 * percent cpu, cpu ticks, state, resident set size, total virtual
718 * memory usage. The process states are ordered as follows (from least
719 * to most important): WAIT, zombie, sleep, stop, start, run. The
720 * array declaration below maps a process state index into a number
721 * that reflects this ordering.
724 static unsigned char sorted_state[] =
728 1, /* ABANDONED (WAIT) */
736 #define ORDERKEY_PCTCPU \
737 if (lresult = (long) PP(p2, p_pctcpu) - (long) PP(p1, p_pctcpu), \
738 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
740 #define ORDERKEY_CPTICKS \
741 if ((result = PP(p2, p_runtime) - PP(p1, p_runtime)) == 0)
743 #define ORDERKEY_STATE \
744 if ((result = sorted_state[(unsigned char) PP(p2, p_stat)] - \
745 sorted_state[(unsigned char) PP(p1, p_stat)]) == 0)
747 #define ORDERKEY_PRIO \
748 if ((result = PP(p2, p_priority) - PP(p1, p_priority)) == 0)
750 #define ORDERKEY_RSSIZE \
751 if ((result = VP(p2, vm_rssize) - VP(p1, vm_rssize)) == 0)
753 #define ORDERKEY_MEM \
754 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
756 /* compare_cpu - the comparison function for sorting by cpu percentage */
760 compare_cpu(pp1, pp2)
762 proc_compare(pp1, pp2)
769 register struct kinfo_proc *p1;
770 register struct kinfo_proc *p2;
772 register pctcpu lresult;
774 /* remove one level of indirection */
775 p1 = *(struct kinfo_proc **) pp1;
776 p2 = *(struct kinfo_proc **) pp2;
790 /* compare routines */
791 int compare_size(), compare_res(), compare_time(), compare_prio();
793 int (*proc_compares[])() = {
802 /* compare_size - the comparison function for sorting by total memory usage */
805 compare_size(pp1, pp2)
811 register struct kinfo_proc *p1;
812 register struct kinfo_proc *p2;
814 register pctcpu lresult;
816 /* remove one level of indirection */
817 p1 = *(struct kinfo_proc **) pp1;
818 p2 = *(struct kinfo_proc **) pp2;
831 /* compare_res - the comparison function for sorting by resident set size */
834 compare_res(pp1, pp2)
840 register struct kinfo_proc *p1;
841 register struct kinfo_proc *p2;
843 register pctcpu lresult;
845 /* remove one level of indirection */
846 p1 = *(struct kinfo_proc **) pp1;
847 p2 = *(struct kinfo_proc **) pp2;
860 /* compare_time - the comparison function for sorting by total cpu time */
863 compare_time(pp1, pp2)
869 register struct kinfo_proc *p1;
870 register struct kinfo_proc *p2;
872 register pctcpu lresult;
874 /* remove one level of indirection */
875 p1 = *(struct kinfo_proc **) pp1;
876 p2 = *(struct kinfo_proc **) pp2;
889 /* compare_prio - the comparison function for sorting by cpu percentage */
892 compare_prio(pp1, pp2)
898 register struct kinfo_proc *p1;
899 register struct kinfo_proc *p2;
901 register pctcpu lresult;
903 /* remove one level of indirection */
904 p1 = *(struct kinfo_proc **) pp1;
905 p2 = *(struct kinfo_proc **) pp2;
920 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
921 * the process does not exist.
922 * It is EXTREMLY IMPORTANT that this function work correctly.
923 * If top runs setuid root (as in SVR4), then this function
924 * is the only thing that stands in the way of a serious
925 * security problem. It validates requests for the "kill"
926 * and "renice" commands.
935 register struct kinfo_proc **prefp;
936 register struct kinfo_proc *pp;
943 if (PP(pp, p_pid) == (pid_t)pid)
945 return((int)EP(pp, e_pcred.p_ruid));
953 * swapmode is based on a program called swapinfo written
954 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
957 #define SVAR(var) __STRING(var) /* to force expansion */
958 #define KGET(idx, var) \
959 KGET1(idx, &var, sizeof(var), SVAR(var))
960 #define KGET1(idx, p, s, msg) \
961 KGET2(nlst[idx].n_value, p, s, msg)
962 #define KGET2(addr, p, s, msg) \
963 if (kvm_read(kd, (u_long)(addr), p, s) != s) { \
964 warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
967 #define KGETRET(addr, p, s, msg) \
968 if (kvm_read(kd, (u_long)(addr), p, s) != s) { \
969 warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
975 swapmode(retavail, retfree)
980 int pagesize = getpagesize();
981 struct kvm_swap swapary[1];
986 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
988 n = kvm_getswapinfo(kd, swapary, 1, 0);
989 if (n < 0 || swapary[0].ksw_total == 0)
992 *retavail = CONVERT(swapary[0].ksw_total);
993 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
995 n = (int)((double)swapary[0].ksw_used * 100.0 /
996 (double)swapary[0].ksw_total);