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>
38 #include <sys/errno.h>
39 #include <sys/sysctl.h>
40 #include <sys/dkstat.h>
45 #include <sys/vmmeter.h>
46 #include <sys/resource.h>
47 #include <sys/rtprio.h>
53 #include <osreldate.h> /* for changes in kernel structures */
60 static void getsysctl __P((char *, void *, size_t));
62 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
64 extern char* printable __P((char *));
65 int swapmode __P((int *retavail, int *retfree));
67 static int namelength;
68 static int cmdlengthdelta;
70 /* Prototypes for top internals */
73 /* get_process_info passes back a handle. This is what it looks like: */
77 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
78 int remaining; /* number of pointers remaining */
81 /* declarations for load_avg */
84 /* define what weighted cpu is. */
85 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
86 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
88 /* what we consider to be process size: */
89 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
91 /* definitions for indices in the nlist array */
94 * These definitions control the format of the per-process area
97 static char smp_header[] =
98 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
100 #define smp_Proc_format \
101 "%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
103 static char up_header[] =
104 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
106 #define up_Proc_format \
107 "%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
111 /* process state names for the "STATE" column of the display */
112 /* the extra nulls in the string "run" are for adding a slash and
113 the processor number when needed */
115 char *state_abbrev[] =
117 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "MUTEX"
123 /* values that we stash away in _init and use in later routines */
125 static double logcpu;
127 /* these are retrieved from the kernel in _init */
129 static load_avg ccpu;
131 /* these are used in the get_ functions */
135 /* these are for calculating cpu state percentages */
137 static long cp_time[CPUSTATES];
138 static long cp_old[CPUSTATES];
139 static long cp_diff[CPUSTATES];
141 /* these are for detailing the process states */
143 int process_states[8];
144 char *procstatenames[] = {
145 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
146 " zombie, ", " waiting, ", " mutex, ",
150 /* these are for detailing the cpu states */
152 int cpu_states[CPUSTATES];
153 char *cpustatenames[] = {
154 "user", "nice", "system", "interrupt", "idle", NULL
157 /* these are for detailing the memory statistics */
160 char *memorynames[] = {
161 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
166 char *swapnames[] = {
168 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
173 /* these are for keeping track of the proc array */
176 static int onproc = -1;
178 static struct kinfo_proc *pbase;
179 static struct kinfo_proc **pref;
181 /* these are for getting the memory statistics */
183 static int pageshift; /* log base 2 of the pagesize */
185 /* define pagetok in terms of pageshift */
187 #define pagetok(size) ((size) << pageshift)
189 /* useful externals */
193 /* sorting orders. first is default */
194 char *ordernames[] = {
195 "cpu", "size", "res", "time", "pri", NULL
200 machine_init(statics)
202 struct statics *statics;
205 register int pagesize;
209 modelen = sizeof(smpmode);
210 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
211 sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) ||
212 modelen != sizeof(smpmode))
215 while ((pw = getpwent()) != NULL) {
216 if (strlen(pw->pw_name) > namelength)
217 namelength = strlen(pw->pw_name);
221 if (smpmode && namelength > 13)
223 else if (namelength > 15)
226 if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, "kvm_open")) == NULL)
229 GETSYSCTL("kern.ccpu", ccpu);
231 /* this is used in calculating WCPU -- calculate it ahead of time */
232 logcpu = log(loaddouble(ccpu));
238 /* get the page size with "getpagesize" and calculate pageshift from it */
239 pagesize = getpagesize();
247 /* we only need the amount of log(2)1024 for our conversion */
248 pageshift -= LOG1024;
250 /* fill in the statics information */
251 statics->procstate_names = procstatenames;
252 statics->cpustate_names = cpustatenames;
253 statics->memory_names = memorynames;
254 statics->swap_names = swapnames;
256 statics->order_names = ordernames;
263 char *format_header(uname_field)
265 register char *uname_field;
268 static char Header[128];
270 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
271 namelength, namelength, uname_field);
273 cmdlengthdelta = strlen(Header) - 7;
278 static int swappgsin = -1;
279 static int swappgsout = -1;
280 extern struct timeval timeout;
285 struct system_info *si;
289 struct loadavg sysload;
291 struct timeval boottime;
294 /* get the cp_time array */
295 GETSYSCTL("kern.cp_time", cp_time);
296 GETSYSCTL("vm.loadavg", sysload);
297 GETSYSCTL("kern.lastpid", lastpid);
299 /* convert load averages to doubles */
302 register double *infoloadp;
304 infoloadp = si->load_avg;
305 for (i = 0; i < 3; i++)
308 *infoloadp++ = ((double) sysload.ldavg[i]) / sysload.fscale;
310 *infoloadp++ = loaddouble(sysload.ldavg[i]);
314 /* convert cp_time counts to percentages */
315 total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
317 /* sum memory & swap statistics */
319 static unsigned int swap_delay = 0;
320 static int swapavail = 0;
321 static int swapfree = 0;
322 static int bufspace = 0;
323 static int nspgsin, nspgsout;
325 GETSYSCTL("vfs.bufspace", bufspace);
326 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
327 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
328 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]);
329 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]);
330 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
331 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
332 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
333 /* convert memory stats to Kbytes */
334 memory_stats[0] = pagetok(memory_stats[0]);
335 memory_stats[1] = pagetok(memory_stats[1]);
336 memory_stats[2] = pagetok(memory_stats[2]);
337 memory_stats[3] = pagetok(memory_stats[3]);
338 memory_stats[4] = bufspace / 1024;
339 memory_stats[5] = pagetok(memory_stats[5]);
340 memory_stats[6] = -1;
348 /* compute differences between old and new swap statistic */
350 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
351 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
355 swappgsout = nspgsout;
357 /* call CPU heavy swapmode() only for changes */
358 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
359 swap_stats[3] = swapmode(&swapavail, &swapfree);
360 swap_stats[0] = swapavail;
361 swap_stats[1] = swapavail - swapfree;
362 swap_stats[2] = swapfree;
368 /* set arrays and strings */
369 si->cpustates = cpu_states;
370 si->memory = memory_stats;
371 si->swap = swap_stats;
375 si->last_pid = lastpid;
381 * Print how long system has been up.
382 * (Found by looking getting "boottime" from the kernel)
385 mib[1] = KERN_BOOTTIME;
386 bt_size = sizeof(boottime);
387 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
388 boottime.tv_sec != 0) {
389 si->boottime = boottime;
391 si->boottime.tv_sec = -1;
395 static struct handle handle;
397 caddr_t get_process_info(si, sel, compare)
399 struct system_info *si;
400 struct process_select *sel;
405 register int total_procs;
406 register int active_procs;
407 register struct kinfo_proc **prefp;
408 register struct kinfo_proc *pp;
410 /* these are copied out of sel for speed */
418 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
420 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
422 if (pref == NULL || pbase == NULL) {
423 (void) fprintf(stderr, "top: Out of memory.\n");
426 /* get a pointer to the states summary array */
427 si->procstates = process_states;
429 /* set up flags which define what we are going to select */
430 show_idle = sel->idle;
431 show_self = sel->self;
432 show_system = sel->system;
433 show_uid = sel->uid != -1;
434 show_command = sel->command != NULL;
436 /* count up process states and get pointers to interesting procs */
439 memset((char *)process_states, 0, sizeof(process_states));
441 for (pp = pbase, i = 0; i < nproc; pp++, i++)
444 * Place pointers to each valid proc structure in pref[].
445 * Process slots that are actually in use have a non-zero
446 * status field. Processes with P_SYSTEM set are system
447 * processes---these get ignored unless show_sysprocs is set.
449 if (pp->ki_stat != 0 &&
450 (show_self != pp->ki_pid) &&
451 (show_system || ((pp->ki_flag & P_SYSTEM) == 0)))
454 process_states[(unsigned char) pp->ki_stat]++;
455 if ((pp->ki_stat != SZOMB) &&
456 (show_idle || (pp->ki_pctcpu != 0) ||
457 (pp->ki_stat == SRUN)) &&
458 (!show_uid || pp->ki_ruid == (uid_t)sel->uid))
466 /* if requested, sort the "interesting" processes */
469 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
472 /* remember active and total counts */
473 si->p_total = total_procs;
474 si->p_active = pref_len = active_procs;
476 /* pass back a handle */
477 handle.next_proc = pref;
478 handle.remaining = active_procs;
479 return((caddr_t)&handle);
482 char fmt[128]; /* static area where result is built */
484 char *format_next_process(handle, get_userid)
487 char *(*get_userid)();
490 register struct kinfo_proc *pp;
491 register long cputime;
497 /* find and remember the next proc structure */
498 hp = (struct handle *)handle;
499 pp = *(hp->next_proc++);
502 /* get the process's command name */
503 if ((pp->ki_sflag & PS_INMEM) == 0) {
505 * Print swapped processes as <pname>
507 char *comm = pp->ki_comm;
508 #define COMSIZ sizeof(pp->ki_comm)
510 (void) strncpy(buf, comm, COMSIZ);
512 (void) strncpy(&comm[1], buf, COMSIZ - 2);
513 comm[COMSIZ - 2] = '\0';
514 (void) strncat(comm, ">", COMSIZ - 1);
515 comm[COMSIZ - 1] = '\0';
519 * Convert the process's runtime from microseconds to seconds. This
520 * time includes the interrupt time although that is not wanted here.
521 * ps(1) is similarly sloppy.
523 cputime = (pp->ki_runtime + 500000) / 1000000;
525 /* calculate the base for cpu percentages */
526 pct = pctdouble(pp->ki_pctcpu);
528 /* generate "STATE" field */
529 switch (state = pp->ki_stat) {
531 if (smpmode && pp->ki_oncpu != 0xff)
532 sprintf(status, "CPU%d", pp->ki_oncpu);
534 strcpy(status, "RUN");
537 if (pp->ki_kiflag & KI_MTXBLOCK) {
538 sprintf(status, "*%.6s", pp->ki_mtxname);
543 if (pp->ki_wmesg != NULL) {
544 sprintf(status, "%.6s", pp->ki_wmesg);
551 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
552 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
554 sprintf(status, "?%5d", state);
558 /* format this entry */
560 smpmode ? smp_Proc_format : up_Proc_format,
562 namelength, namelength,
563 (*get_userid)(pp->ki_ruid),
564 pp->ki_pri.pri_level - PZERO,
567 * normal time -> nice value -20 - +20
568 * real time 0 - 31 -> nice value -52 - -21
569 * idle time 0 - 31 -> nice value +21 - +52
571 (pp->ki_pri.pri_class == PRI_TIMESHARE ?
572 pp->ki_nice - NZERO :
573 (PRI_IS_REALTIME(pp->ki_pri.pri_class) ?
574 (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) :
575 (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))),
576 format_k2(PROCSIZE(pp)),
577 format_k2(pagetok(pp->ki_rssize)),
579 smpmode ? pp->ki_lastcpu : 0,
580 format_time(cputime),
581 100.0 * weighted_cpu(pct, pp),
583 screen_width > cmdlengthdelta ?
584 screen_width - cmdlengthdelta :
586 printable(pp->ki_comm));
588 /* return the result */
592 static void getsysctl (name, ptr, len)
600 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
601 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
606 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name,
607 (unsigned long)len, (unsigned long)nlen);
612 /* comparison routines for qsort */
615 * proc_compare - comparison function for "qsort"
616 * Compares the resource consumption of two processes using five
617 * distinct keys. The keys (in descending order of importance) are:
618 * percent cpu, cpu ticks, state, resident set size, total virtual
619 * memory usage. The process states are ordered as follows (from least
620 * to most important): WAIT, zombie, sleep, stop, start, run. The
621 * array declaration below maps a process state index into a number
622 * that reflects this ordering.
625 static unsigned char sorted_state[] =
629 1, /* ABANDONED (WAIT) */
637 #define ORDERKEY_PCTCPU \
638 if (lresult = (long) p2->ki_pctcpu - (long) p1->ki_pctcpu, \
639 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
641 #define ORDERKEY_CPTICKS \
642 if ((result = p2->ki_runtime > p1->ki_runtime ? 1 : \
643 p2->ki_runtime < p1->ki_runtime ? -1 : 0) == 0)
645 #define ORDERKEY_STATE \
646 if ((result = sorted_state[(unsigned char) p2->ki_stat] - \
647 sorted_state[(unsigned char) p1->ki_stat]) == 0)
649 #define ORDERKEY_PRIO \
650 if ((result = p2->ki_pri.pri_level - p1->ki_pri.pri_level) == 0)
652 #define ORDERKEY_RSSIZE \
653 if ((result = p2->ki_rssize - p1->ki_rssize) == 0)
655 #define ORDERKEY_MEM \
656 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
658 /* compare_cpu - the comparison function for sorting by cpu percentage */
662 compare_cpu(pp1, pp2)
664 proc_compare(pp1, pp2)
671 register struct kinfo_proc *p1;
672 register struct kinfo_proc *p2;
674 register pctcpu lresult;
676 /* remove one level of indirection */
677 p1 = *(struct kinfo_proc **) pp1;
678 p2 = *(struct kinfo_proc **) pp2;
692 /* compare routines */
693 int compare_size(), compare_res(), compare_time(), compare_prio();
695 int (*proc_compares[])() = {
704 /* compare_size - the comparison function for sorting by total memory usage */
707 compare_size(pp1, pp2)
713 register struct kinfo_proc *p1;
714 register struct kinfo_proc *p2;
716 register pctcpu lresult;
718 /* remove one level of indirection */
719 p1 = *(struct kinfo_proc **) pp1;
720 p2 = *(struct kinfo_proc **) pp2;
733 /* compare_res - the comparison function for sorting by resident set size */
736 compare_res(pp1, pp2)
742 register struct kinfo_proc *p1;
743 register struct kinfo_proc *p2;
745 register pctcpu lresult;
747 /* remove one level of indirection */
748 p1 = *(struct kinfo_proc **) pp1;
749 p2 = *(struct kinfo_proc **) pp2;
762 /* compare_time - the comparison function for sorting by total cpu time */
765 compare_time(pp1, pp2)
771 register struct kinfo_proc *p1;
772 register struct kinfo_proc *p2;
774 register pctcpu lresult;
776 /* remove one level of indirection */
777 p1 = *(struct kinfo_proc **) pp1;
778 p2 = *(struct kinfo_proc **) pp2;
791 /* compare_prio - the comparison function for sorting by cpu percentage */
794 compare_prio(pp1, pp2)
800 register struct kinfo_proc *p1;
801 register struct kinfo_proc *p2;
803 register pctcpu lresult;
805 /* remove one level of indirection */
806 p1 = *(struct kinfo_proc **) pp1;
807 p2 = *(struct kinfo_proc **) pp2;
822 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
823 * the process does not exist.
824 * It is EXTREMLY IMPORTANT that this function work correctly.
825 * If top runs setuid root (as in SVR4), then this function
826 * is the only thing that stands in the way of a serious
827 * security problem. It validates requests for the "kill"
828 * and "renice" commands.
837 register struct kinfo_proc **prefp;
838 register struct kinfo_proc *pp;
845 if (pp->ki_pid == (pid_t)pid)
847 return((int)pp->ki_ruid);
854 swapmode(retavail, retfree)
859 int pagesize = getpagesize();
860 struct kvm_swap swapary[1];
865 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
867 n = kvm_getswapinfo(kd, swapary, 1, 0);
868 if (n < 0 || swapary[0].ksw_total == 0)
871 *retavail = CONVERT(swapary[0].ksw_total);
872 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
874 n = (int)((double)swapary[0].ksw_used * 100.0 /
875 (double)swapary[0].ksw_total);