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 * Hiten Pandya <hmp@backplane.com>
23 * $FreeBSD: src/usr.bin/top/machine.c,v 1.29.2.2 2001/07/31 20:27:05 tmm Exp $
24 * $DragonFly: src/usr.bin/top/machine.c,v 1.14 2004/12/22 11:01:49 joerg Exp $
29 #include <sys/types.h>
30 #include <sys/signal.h>
31 #include <sys/param.h>
39 #include <sys/errno.h>
40 #include <sys/sysctl.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 */
54 #include <sys/kinfo.h>
59 static int check_nlist(struct nlist *);
60 static int getkval(unsigned long, int *, int, char *);
61 extern char* printable(char *);
62 int swapmode(int *retavail, int *retfree);
64 static int namelength;
68 * needs to be a global symbol, so wrapper can be
69 * modified accordingly.
71 static int show_threads = 0;
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 PP(pp, field) ((pp)->kp_proc . field)
85 #define EP(pp, field) ((pp)->kp_eproc . field)
86 #define TP(pp, field) ((pp)->kp_thread . field)
87 #define VP(pp, field) ((pp)->kp_eproc.e_vm . field)
89 /* define what weighted cpu is. */
90 #define weighted_cpu(pct, pp) (PP((pp), p_swtime) == 0 ? 0.0 : \
91 ((pct) / (1.0 - exp(PP((pp), p_swtime) * logcpu))))
93 /* what we consider to be process size: */
94 #define PROCSIZE(pp) (VP((pp), vm_map.size) / 1024)
97 * These definitions control the format of the per-process area
100 static char smp_header[] =
101 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
103 #define smp_Proc_format \
104 "%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
106 static char up_header[] =
107 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
109 #define up_Proc_format \
110 "%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
114 /* process state names for the "STATE" column of the display */
115 /* the extra nulls in the string "run" are for adding a slash and
116 the processor number when needed */
118 char *state_abbrev[] =
120 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB",
126 /* values that we stash away in _init and use in later routines */
128 static double logcpu;
134 /* these are for calculating cpu state percentages */
136 static struct kinfo_cputime cp_time, cp_old;
138 /* these are for detailing the process states */
140 int process_states[6];
141 char *procstatenames[] = {
142 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
147 /* these are for detailing the cpu states */
149 int cpu_states[CPU_STATES];
150 char *cpustatenames[CPU_STATES + 1] = {
151 "user", "nice", "system", "interrupt", "idle", NULL
154 /* these are for detailing the memory statistics */
157 char *memorynames[] = {
158 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
163 char *swapnames[] = {
165 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
170 /* these are for keeping track of the proc array */
173 static int onproc = -1;
175 static struct kinfo_proc *pbase;
176 static struct kinfo_proc **pref;
178 /* these are for getting the memory statistics */
180 static int pageshift; /* log base 2 of the pagesize */
182 /* define pagetok in terms of pageshift */
184 #define pagetok(size) ((size) << pageshift)
187 /* sorting orders. first is default */
188 char *ordernames[] = {
189 "cpu", "size", "res", "time", "pri", "thr", NULL
194 cputime_percentages(int out[CPU_STATES], struct kinfo_cputime *new,
195 struct kinfo_cputime *old)
197 struct kinfo_cputime diffs;
199 uint64_t total_change, half_total;
204 diffs.cp_user = new->cp_user - old->cp_user;
205 diffs.cp_nice = new->cp_nice - old->cp_nice;
206 diffs.cp_sys = new->cp_sys - old->cp_sys;
207 diffs.cp_intr = new->cp_intr - old->cp_intr;
208 diffs.cp_idle = new->cp_idle - old->cp_idle;
209 total_change = diffs.cp_user + diffs.cp_nice + diffs.cp_sys +
210 diffs.cp_intr + diffs.cp_idle;
211 old->cp_user = new->cp_user;
212 old->cp_nice = new->cp_nice;
213 old->cp_sys = new->cp_sys;
214 old->cp_intr = new->cp_intr;
215 old->cp_idle = new->cp_idle;
217 /* avoid divide by zero potential */
218 if (total_change == 0)
221 /* calculate percentages based on overall change, rounding up */
222 half_total = total_change >> 1;
224 out[0] = ((diffs.cp_user * 1000LL + half_total) / total_change);
225 out[1] = ((diffs.cp_nice * 1000LL + half_total) / total_change);
226 out[2] = ((diffs.cp_sys * 1000LL + half_total) / total_change);
227 out[3] = ((diffs.cp_intr * 1000LL + half_total) / total_change);
228 out[4] = ((diffs.cp_idle * 1000LL + half_total) / total_change);
232 machine_init(struct statics *statics)
235 register int pagesize;
239 modelen = sizeof(smpmode);
240 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
241 sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
242 modelen != sizeof(smpmode))
245 while ((pw = getpwent()) != NULL) {
246 if (strlen(pw->pw_name) > namelength)
247 namelength = strlen(pw->pw_name);
251 if (smpmode && namelength > 13)
253 else if (namelength > 15)
256 if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
259 if (kinfo_get_sched_ccpu(&ccpu)) {
260 fprintf(stderr, "top: kinfo_get_sched_ccpu failed\n");
264 /* this is used in calculating WCPU -- calculate it ahead of time */
265 logcpu = log(loaddouble(ccpu));
271 /* get the page size with "getpagesize" and calculate pageshift from it */
272 pagesize = getpagesize();
280 /* we only need the amount of log(2)1024 for our conversion */
281 pageshift -= LOG1024;
283 /* fill in the statics information */
284 statics->procstate_names = procstatenames;
285 statics->cpustate_names = cpustatenames;
286 statics->memory_names = memorynames;
287 statics->swap_names = swapnames;
289 statics->order_names = ordernames;
296 char *format_header(register char *uname_field)
299 static char Header[128];
301 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
302 namelength, namelength, uname_field);
304 if (screen_width <= 79)
309 cmdlength = cmdlength - strlen(Header) + 6;
314 static int swappgsin = -1;
315 static int swappgsout = -1;
316 extern struct timeval timeout;
319 get_system_info(struct system_info *si)
323 struct timeval boottime;
326 if (kinfo_get_sched_cputime(&cp_time))
327 err(1, "kinfo_get_sched_cputime failed");
329 getloadavg(si->load_avg, 3);
333 /* convert cp_time counts to percentages */
334 cputime_percentages(cpu_states, &cp_time, &cp_old);
336 /* sum memory & swap statistics */
340 int vms_size = sizeof(vms);
341 int vmm_size = sizeof(vmm);
342 static unsigned int swap_delay = 0;
343 static int swapavail = 0;
344 static int swapfree = 0;
345 static int bufspace = 0;
347 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
348 perror("sysctlbyname: vm.vmstats");
351 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
352 perror("sysctlbyname: vm.vmstats");
355 if (kinfo_get_vfs_bufspace(&bufspace)) {
356 perror("kinfo_get_vfs_bufspace");
360 /* convert memory stats to Kbytes */
361 memory_stats[0] = pagetok(vms.v_active_count);
362 memory_stats[1] = pagetok(vms.v_inactive_count);
363 memory_stats[2] = pagetok(vms.v_wire_count);
364 memory_stats[3] = pagetok(vms.v_cache_count);
365 memory_stats[4] = bufspace / 1024;
366 memory_stats[5] = pagetok(vms.v_free_count);
367 memory_stats[6] = -1;
375 /* compute differences between old and new swap statistic */
377 swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
378 swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
381 swappgsin = vmm.v_swappgsin;
382 swappgsout = vmm.v_swappgsout;
384 /* call CPU heavy swapmode() only for changes */
385 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
386 swap_stats[3] = swapmode(&swapavail, &swapfree);
387 swap_stats[0] = swapavail;
388 swap_stats[1] = swapavail - swapfree;
389 swap_stats[2] = swapfree;
395 /* set arrays and strings */
396 si->cpustates = cpu_states;
397 si->memory = memory_stats;
398 si->swap = swap_stats;
402 si->last_pid = lastpid;
408 * Print how long system has been up.
409 * (Found by looking getting "boottime" from the kernel)
412 mib[1] = KERN_BOOTTIME;
413 bt_size = sizeof(boottime);
414 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
415 boottime.tv_sec != 0) {
416 si->boottime = boottime;
418 si->boottime.tv_sec = -1;
422 static struct handle handle;
424 caddr_t get_process_info(struct system_info *si, struct process_select *sel,
428 register int total_procs;
429 register int active_procs;
430 register struct kinfo_proc **prefp;
431 register struct kinfo_proc *pp;
433 /* these are copied out of sel for speed */
437 int show_only_threads;
442 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
444 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
446 if (pref == NULL || pbase == NULL) {
447 (void) fprintf(stderr, "top: Out of memory.\n");
450 /* get a pointer to the states summary array */
451 si->procstates = process_states;
453 /* set up flags which define what we are going to select */
454 show_idle = sel->idle;
455 show_self = sel->self;
456 show_system = sel->system;
457 show_threads = sel->threads;
458 show_only_threads = sel->only_threads;
459 show_uid = sel->uid != -1;
460 show_command = sel->command != NULL;
462 /* count up process states and get pointers to interesting procs */
465 memset((char *)process_states, 0, sizeof(process_states));
467 for (pp = pbase, i = 0; i < nproc; pp++, i++)
470 * Place pointers to each valid proc structure in pref[].
471 * Process slots that are actually in use have a non-zero
472 * status field. Processes with P_SYSTEM set are system
473 * processes---these get ignored unless show_sysprocs is set.
475 if ((show_threads && (TP(pp, td_proc) == NULL)) ||
476 (!show_only_threads && (PP(pp, p_stat) != 0 &&
477 (show_self != PP(pp, p_pid)) &&
478 (show_system || ((PP(pp, p_flag) & P_SYSTEM) == 0)))))
481 process_states[(unsigned char) PP(pp, p_stat)]++;
482 if ((show_threads && (TP(pp, td_proc) == NULL)) ||
483 (!show_only_threads && (PP(pp, p_stat) != SZOMB) &&
484 (show_idle || (PP(pp, p_pctcpu) != 0) ||
485 (PP(pp, p_stat) == SRUN)) &&
486 (!show_uid || EP(pp, e_ucred.cr_ruid) == (uid_t)sel->uid)))
494 /* if requested, sort the "interesting" processes */
497 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
500 /* remember active and total counts */
501 si->p_total = total_procs;
502 si->p_active = pref_len = active_procs;
504 /* pass back a handle */
505 handle.next_proc = pref;
506 handle.remaining = active_procs;
507 return((caddr_t)&handle);
510 char fmt[128]; /* static area where result is built */
512 char *format_next_process(caddr_t handle, char *(*get_userid)())
514 struct kinfo_proc *pp;
523 /* find and remember the next proc structure */
524 hp = (struct handle *)handle;
525 pp = *(hp->next_proc++);
528 /* set the wrapper for the process/thread name */
529 if ((PP(pp, p_flag) & P_INMEM) == 0)
530 wrapper = "[]"; /* swapped process [pname] */
531 else if (((PP(pp, p_flag) & P_SYSTEM) != 0) && (TP(pp, td_proc) != NULL))
532 wrapper = "()"; /* system process (pname) */
533 else if (show_threads && (TP(pp, td_proc) == NULL))
534 wrapper = "<>"; /* pure kernel threads <thread> */
538 /* get the process's command name */
539 if (wrapper != NULL) {
540 char *comm = TP(pp, td_comm);
541 #define COMSIZ sizeof(TP(pp, td_comm))
543 (void) strncpy(buf, comm, COMSIZ);
544 comm[0] = wrapper[0];
545 (void) strncpy(&comm[1], buf, COMSIZ - 2);
546 comm[COMSIZ - 2] = '\0';
547 (void) strncat(comm, &wrapper[1], COMSIZ - 1);
548 comm[COMSIZ - 1] = '\0';
552 * Convert the process's runtime from microseconds to seconds. This
553 * time includes the interrupt time although that is not wanted here.
554 * ps(1) is similarly sloppy.
556 cputime = (EP(pp, e_uticks) + EP(pp, e_sticks)) / 1000000;
558 /* calculate the base for cpu percentages */
559 pct = pctdouble(PP(pp, p_pctcpu));
561 /* generate "STATE" field */
562 switch (state = PP(pp, p_stat)) {
564 if (smpmode && TP(pp, td_flags) & TDF_RUNNING)
565 sprintf(status, "CPU%d", EP(pp, e_cpuid));
567 strcpy(status, "RUN");
570 if (TP(pp, td_wmesg) != NULL) {
571 sprintf(status, "%.6s", EP(pp, e_wmesg));
578 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
579 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
581 sprintf(status, "?%5d", state);
586 * idle time 0 - 31 -> nice value +21 - +52
587 * normal time -> nice value -20 - +20
588 * real time 0 - 31 -> nice value -52 - -21
589 * thread 0 - 31 -> nice value -53 -
591 switch(PP(pp, p_rtprio.type)) {
592 case RTP_PRIO_REALTIME:
593 nice = PRIO_MIN - 1 - RTP_PRIO_MAX + PP(pp, p_rtprio.prio);
596 nice = PRIO_MAX + 1 + PP(pp, p_rtprio.prio);
598 case RTP_PRIO_THREAD:
599 nice = PRIO_MIN - 1 - RTP_PRIO_MAX - PP(pp, p_rtprio.prio);
602 nice = PP(pp, p_nice);
607 /* format this entry */
608 snprintf(fmt, sizeof(fmt),
609 smpmode ? smp_Proc_format : up_Proc_format,
611 namelength, namelength,
612 (*get_userid)(EP(pp, e_ucred.cr_ruid)),
613 (show_threads && (TP(pp, td_proc) == NULL)) ? TP(pp, td_pri) :
616 format_k2(PROCSIZE(pp)),
617 format_k2(pagetok(VP(pp, vm_rssize))),
619 smpmode ? EP(pp, e_cpuid) : 0,
620 format_time(cputime),
621 100.0 * weighted_cpu(pct, pp),
624 printable(TP(pp, td_comm)));
626 /* return the result */
632 * check_nlist(nlst) - checks the nlist to see if any symbols were not
633 * found. For every symbol that was not found, a one-line
634 * message is printed to stderr. The routine returns the
635 * number of symbols NOT found.
638 static int check_nlist(register struct nlist *nlst)
642 /* check to see if we got ALL the symbols we requested */
643 /* this will write one line to stderr for every symbol not found */
646 while (nlst->n_name != NULL)
648 if (nlst->n_type == 0)
650 /* this one wasn't found */
651 (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
661 /* comparison routines for qsort */
664 * proc_compare - comparison function for "qsort"
665 * Compares the resource consumption of two processes using five
666 * distinct keys. The keys (in descending order of importance) are:
667 * percent cpu, cpu ticks, state, resident set size, total virtual
668 * memory usage. The process states are ordered as follows (from least
669 * to most important): WAIT, zombie, sleep, stop, start, run. The
670 * array declaration below maps a process state index into a number
671 * that reflects this ordering.
674 static unsigned char sorted_state[] =
678 1, /* ABANDONED (WAIT) */
686 #define ORDERKEY_PCTCPU \
687 if (lresult = (long) PP(p2, p_pctcpu) - (long) PP(p1, p_pctcpu), \
688 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
690 #define CPTICKS(p) (EP(p, e_uticks) + EP(p, e_sticks))
692 #define ORDERKEY_CPTICKS \
693 if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
694 CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
696 #define ORDERKEY_STATE \
697 if ((result = sorted_state[(unsigned char) PP(p2, p_stat)] - \
698 sorted_state[(unsigned char) PP(p1, p_stat)]) == 0)
700 #define ORDERKEY_PRIO \
701 if ((result = PP(p2, p_priority) - PP(p1, p_priority)) == 0)
703 #define ORDERKEY_KTHREADS \
704 if ((result = (TP(p1, td_proc) == NULL) - (TP(p2, td_proc) == NULL)) == 0)
706 #define ORDERKEY_KTHREADS_PRIO \
707 if ((result = TP(p2, td_pri) - TP(p1, td_pri)) == 0)
709 #define ORDERKEY_RSSIZE \
710 if ((result = VP(p2, vm_rssize) - VP(p1, vm_rssize)) == 0)
712 #define ORDERKEY_MEM \
713 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
715 /* compare_cpu - the comparison function for sorting by cpu percentage */
719 compare_cpu(struct proc **pp1, struct proc **pp2)
721 proc_compare(struct proc **pp1, struct proc **pp2)
724 register struct kinfo_proc *p1;
725 register struct kinfo_proc *p2;
727 register pctcpu lresult;
729 /* remove one level of indirection */
730 p1 = *(struct kinfo_proc **) pp1;
731 p2 = *(struct kinfo_proc **) pp2;
745 /* compare routines */
746 int compare_size(), compare_res(), compare_time(), compare_prio(), compare_thr();
748 int (*proc_compares[])() = {
758 /* compare_size - the comparison function for sorting by total memory usage */
761 compare_size(struct proc **pp1, struct proc **pp2)
763 register struct kinfo_proc *p1;
764 register struct kinfo_proc *p2;
766 register pctcpu lresult;
768 /* remove one level of indirection */
769 p1 = *(struct kinfo_proc **) pp1;
770 p2 = *(struct kinfo_proc **) pp2;
783 /* compare_res - the comparison function for sorting by resident set size */
786 compare_res(struct proc **pp1, struct proc **pp2)
788 register struct kinfo_proc *p1;
789 register struct kinfo_proc *p2;
791 register pctcpu lresult;
793 /* remove one level of indirection */
794 p1 = *(struct kinfo_proc **) pp1;
795 p2 = *(struct kinfo_proc **) pp2;
808 /* compare_time - the comparison function for sorting by total cpu time */
811 compare_time(struct proc **pp1, struct proc **pp2)
813 register struct kinfo_proc *p1;
814 register struct kinfo_proc *p2;
816 register pctcpu lresult;
818 /* remove one level of indirection */
819 p1 = *(struct kinfo_proc **) pp1;
820 p2 = *(struct kinfo_proc **) pp2;
825 ORDERKEY_KTHREADS_PRIO
835 /* compare_prio - the comparison function for sorting by cpu percentage */
838 compare_prio(struct proc **pp1, struct proc **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;
850 ORDERKEY_KTHREADS_PRIO
863 compare_thr(struct proc **pp1, struct proc **pp2)
865 register struct kinfo_proc *p1;
866 register struct kinfo_proc *p2;
868 register pctcpu lresult;
870 /* remove one level of indirection */
871 p1 = *(struct kinfo_proc **) pp1;
872 p2 = *(struct kinfo_proc **) pp2;
875 ORDERKEY_KTHREADS_PRIO
890 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
891 * the process does not exist.
892 * It is EXTREMLY IMPORTANT that this function work correctly.
893 * If top runs setuid root (as in SVR4), then this function
894 * is the only thing that stands in the way of a serious
895 * security problem. It validates requests for the "kill"
896 * and "renice" commands.
899 int proc_owner(int pid)
902 register struct kinfo_proc **prefp;
903 register struct kinfo_proc *pp;
910 if (PP(pp, p_pid) == (pid_t)pid)
912 return((int)EP(pp, e_ucred.cr_ruid));
920 * swapmode is based on a program called swapinfo written
921 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
924 swapmode(int *retavail, int *retfree)
927 int pagesize = getpagesize();
928 struct kvm_swap swapary[1];
933 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
935 n = kvm_getswapinfo(kd, swapary, 1, 0);
936 if (n < 0 || swapary[0].ksw_total == 0)
939 *retavail = CONVERT(swapary[0].ksw_total);
940 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
942 n = (int)((double)swapary[0].ksw_used * 100.0 /
943 (double)swapary[0].ksw_total);