2 * top - a top users display for Unix
4 * SYNOPSIS: For DragonFly 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 DragonFly 2.5.1
14 * DragonFly 2.x and above
18 * AUTHOR: Jan Lentfer <Jan.Lentfer@web.de>
19 * This module has been put together from different sources and is based on the
20 * work of many other people, e.g. Matthew Dillon, Simon Schubert, Jordan Gordeev.
22 * $FreeBSD: src/usr.bin/top/machine.c,v 1.29.2.2 2001/07/31 20:27:05 tmm Exp $
23 * $DragonFly: src/usr.bin/top/machine.c,v 1.26 2008/10/16 01:52:33 swildner Exp $
28 #include <sys/types.h>
29 #include <sys/signal.h>
30 #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>
53 #include <osreldate.h> /* for changes in kernel structures */
55 #include <sys/kinfo.h>
64 static int check_nlist(struct nlist *);
65 static int getkval(unsigned long, int *, int, char *);
67 int swapmode(int *retavail, int *retfree);
69 static int namelength;
75 * needs to be a global symbol, so wrapper can be
76 * modified accordingly.
78 static int show_threads = 0;
80 /* get_process_info passes back a handle. This is what it looks like: */
84 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
85 int remaining; /* number of pointers remaining */
88 /* declarations for load_avg */
91 #define PP(pp, field) ((pp)->kp_ ## field)
92 #define LP(pp, field) ((pp)->kp_lwp.kl_ ## field)
93 #define VP(pp, field) ((pp)->kp_vm_ ## field)
95 /* define what weighted cpu is. */
96 #define weighted_cpu(pct, pp) (PP((pp), swtime) == 0 ? 0.0 : \
97 ((pct) / (1.0 - exp(PP((pp), swtime) * logcpu))))
99 /* what we consider to be process size: */
100 #define PROCSIZE(pp) (VP((pp), map_size) / 1024)
103 * These definitions control the format of the per-process area
106 static char smp_header[] =
107 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
109 #define smp_Proc_format \
110 "%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
112 static char up_header[] =
113 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
115 #define up_Proc_format \
116 "%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
120 /* process state names for the "STATE" column of the display */
121 /* the extra nulls in the string "run" are for adding a slash and
122 the processor number when needed */
124 const char *state_abbrev[] =
126 "", "RUN\0\0\0", "STOP", "SLEEP",
132 /* values that we stash away in _init and use in later routines */
134 static double logcpu;
139 /* these are for calculating cpu state percentages */
141 static struct kinfo_cputime *cp_time, *cp_old;
143 /* these are for detailing the process states */
145 int process_states[6];
146 char *procstatenames[] = {
147 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
152 /* these are for detailing the cpu states */
155 char *cpustatenames[CPU_STATES + 1] = {
156 "user", "nice", "system", "interrupt", "idle", NULL
159 /* these are for detailing the memory statistics */
161 long memory_stats[7];
162 char *memorynames[] = {
163 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
168 char *swapnames[] = {
170 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
175 /* these are for keeping track of the proc array */
178 static int onproc = -1;
180 static struct kinfo_proc *pbase;
181 static struct kinfo_proc **pref;
183 /* these are for getting the memory statistics */
185 static int pageshift; /* log base 2 of the pagesize */
187 /* define pagetok in terms of pageshift */
189 #define pagetok(size) ((size) << pageshift)
191 /* sorting orders. first is default */
192 char *ordernames[] = {
193 "cpu", "size", "res", "time", "pri", "thr", NULL
196 /* compare routines */
197 int proc_compare(), compare_size(), compare_res(), compare_time(), compare_prio(), compare_thr();
199 int (*proc_compares[])() = {
209 cputime_percentages(int out[CPU_STATES], struct kinfo_cputime *new,
210 struct kinfo_cputime *old)
212 struct kinfo_cputime diffs;
213 uint64_t total_change, half_total;
218 diffs.cp_user = new->cp_user - old->cp_user;
219 diffs.cp_nice = new->cp_nice - old->cp_nice;
220 diffs.cp_sys = new->cp_sys - old->cp_sys;
221 diffs.cp_intr = new->cp_intr - old->cp_intr;
222 diffs.cp_idle = new->cp_idle - old->cp_idle;
223 total_change = diffs.cp_user + diffs.cp_nice + diffs.cp_sys +
224 diffs.cp_intr + diffs.cp_idle;
225 old->cp_user = new->cp_user;
226 old->cp_nice = new->cp_nice;
227 old->cp_sys = new->cp_sys;
228 old->cp_intr = new->cp_intr;
229 old->cp_idle = new->cp_idle;
231 /* avoid divide by zero potential */
232 if (total_change == 0)
235 /* calculate percentages based on overall change, rounding up */
236 half_total = total_change >> 1;
238 out[0] = ((diffs.cp_user * 1000LL + half_total) / total_change);
239 out[1] = ((diffs.cp_nice * 1000LL + half_total) / total_change);
240 out[2] = ((diffs.cp_sys * 1000LL + half_total) / total_change);
241 out[3] = ((diffs.cp_intr * 1000LL + half_total) / total_change);
242 out[4] = ((diffs.cp_idle * 1000LL + half_total) / total_change);
246 machine_init(struct statics *statics)
251 struct timeval boottime;
254 if (kinfo_get_cpus(&n_cpus))
255 err(1, "kinfo_get_cpus failed");
259 modelen = sizeof(boottime);
260 if (sysctlbyname("kern.boottime", &boottime, &modelen, NULL, 0) == -1) {
262 /* we have no boottime to report */
263 boottime.tv_sec = -1;
266 modelen = sizeof(smpmode);
267 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
268 sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
269 modelen != sizeof(smpmode))
272 while ((pw = getpwent()) != NULL) {
273 if ((int)strlen(pw->pw_name) > namelength)
274 namelength = strlen(pw->pw_name);
278 if (smpmode && namelength > 13)
280 else if (namelength > 15)
283 if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
286 if (kinfo_get_sched_ccpu(&ccpu)) {
287 fprintf(stderr, "top: kinfo_get_sched_ccpu failed\n");
291 /* this is used in calculating WCPU -- calculate it ahead of time */
292 logcpu = log(loaddouble(ccpu));
298 /* get the page size with "getpagesize" and calculate pageshift from it */
299 pagesize = getpagesize();
307 /* we only need the amount of log(2)1024 for our conversion */
308 pageshift -= LOG1024;
310 /* fill in the statics information */
311 statics->procstate_names = procstatenames;
312 statics->cpustate_names = cpustatenames;
313 statics->memory_names = memorynames;
314 statics->boottime = boottime.tv_sec;
315 statics->swap_names = swapnames;
316 statics->order_names = ordernames;
323 format_header(char *uname_field)
325 static char Header[128];
327 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
328 namelength, namelength, uname_field);
330 if (screen_width <= 79)
335 cmdlength = cmdlength - strlen(Header) + 6;
340 static int swappgsin = -1;
341 static int swappgsout = -1;
342 extern struct timeval timeout;
345 get_system_info(struct system_info *si)
350 if (cpu_states == NULL) {
351 cpu_states = malloc(sizeof(*cpu_states) * CPU_STATES * n_cpus);
352 if (cpu_states == NULL)
354 bzero(cpu_states, sizeof(*cpu_states) * CPU_STATES * n_cpus);
356 if (cp_time == NULL) {
357 cp_time = malloc(2 * n_cpus * sizeof(cp_time[0]));
360 cp_old = cp_time + n_cpus;
362 len = n_cpus * sizeof(cp_old[0]);
364 if (sysctlbyname("kern.cputime", cp_old, &len, NULL, 0))
365 err(1, "kern.cputime");
368 len = n_cpus * sizeof(cp_time[0]);
370 if (sysctlbyname("kern.cputime", cp_time, &len, NULL, 0))
371 err(1, "kern.cputime");
373 getloadavg(si->load_avg, 3);
377 /* convert cp_time counts to percentages */
378 for (cpu = 0; cpu < n_cpus; ++cpu) {
379 cputime_percentages(cpu_states + cpu * CPU_STATES,
380 &cp_time[cpu], &cp_old[cpu]);
383 /* sum memory & swap statistics */
387 size_t vms_size = sizeof(vms);
388 size_t vmm_size = sizeof(vmm);
389 static unsigned int swap_delay = 0;
390 static int swapavail = 0;
391 static int swapfree = 0;
392 static int bufspace = 0;
394 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0))
395 err(1, "sysctlbyname: vm.vmstats");
397 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0))
398 err(1, "sysctlbyname: vm.vmmeter");
400 if (kinfo_get_vfs_bufspace(&bufspace))
401 err(1, "kinfo_get_vfs_bufspace");
403 /* convert memory stats to Kbytes */
404 memory_stats[0] = pagetok(vms.v_active_count);
405 memory_stats[1] = pagetok(vms.v_inactive_count);
406 memory_stats[2] = pagetok(vms.v_wire_count);
407 memory_stats[3] = pagetok(vms.v_cache_count);
408 memory_stats[4] = bufspace / 1024;
409 memory_stats[5] = pagetok(vms.v_free_count);
410 memory_stats[6] = -1;
418 /* compute differences between old and new swap statistic */
420 swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
421 swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
424 swappgsin = vmm.v_swappgsin;
425 swappgsout = vmm.v_swappgsout;
427 /* call CPU heavy swapmode() only for changes */
428 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
429 swap_stats[3] = swapmode(&swapavail, &swapfree);
430 swap_stats[0] = swapavail;
431 swap_stats[1] = swapavail - swapfree;
432 swap_stats[2] = swapfree;
438 /* set arrays and strings */
439 si->cpustates = cpu_states;
440 si->memory = memory_stats;
441 si->swap = swap_stats;
445 si->last_pid = lastpid;
452 static struct handle handle;
454 caddr_t get_process_info(struct system_info *si, struct process_select *sel,
460 struct kinfo_proc **prefp;
461 struct kinfo_proc *pp;
463 /* 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_system = sel->system;
483 show_uid = sel->uid != -1;
485 /* count up process states and get pointers to interesting procs */
488 memset((char *)process_states, 0, sizeof(process_states));
490 for (pp = pbase, i = 0; i < nproc; pp++, i++)
493 * Place pointers to each valid proc structure in pref[].
494 * Process slots that are actually in use have a non-zero
495 * status field. Processes with P_SYSTEM set are system
496 * processes---these get ignored unless show_sysprocs is set.
498 if ((show_threads && (LP(pp, pid) == -1)) ||
499 (show_system || ((PP(pp, flags) & P_SYSTEM) == 0)))
502 process_states[(unsigned char) PP(pp, stat)]++;
503 if ((show_threads && (LP(pp, pid) == -1)) ||
504 (show_idle || (LP(pp, pctcpu) != 0) ||
505 (LP(pp, stat) == LSRUN)) &&
506 (!show_uid || PP(pp, ruid) == (uid_t)sel->uid))
514 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *),
515 proc_compares[compare_index]);
517 /* remember active and total counts */
518 si->p_total = total_procs;
519 si->p_active = pref_len = active_procs;
521 /* pass back a handle */
522 handle.next_proc = pref;
523 handle.remaining = active_procs;
524 return((caddr_t)&handle);
527 char fmt[128]; /* static area where result is built */
530 format_next_process(caddr_t xhandle, char *(*get_userid)(int))
532 struct kinfo_proc *pp;
541 /* find and remember the next proc structure */
542 hp = (struct handle *)xhandle;
543 pp = *(hp->next_proc++);
546 /* set the wrapper for the process/thread name */
547 if ((PP(pp, flags) & P_SWAPPEDOUT))
548 wrapper = "[]"; /* swapped process [pname] */
549 else if (((PP(pp, flags) & P_SYSTEM) != 0) && (LP(pp, pid) > 0))
550 wrapper = "()"; /* system process (pname) */
551 else if (show_threads && (LP(pp, pid) == -1))
552 wrapper = "<>"; /* pure kernel threads <thread> */
556 /* get the process's command name */
557 if (wrapper != NULL) {
558 char *comm = PP(pp, comm);
559 #define COMSIZ sizeof(PP(pp, comm))
561 (void) strncpy(buf, comm, COMSIZ);
562 comm[0] = wrapper[0];
563 (void) strncpy(&comm[1], buf, COMSIZ - 2);
564 comm[COMSIZ - 2] = '\0';
565 (void) strncat(comm, &wrapper[1], 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 = (LP(pp, uticks) + LP(pp, sticks)) / 1000000;
576 /* calculate the base for cpu percentages */
577 pct = pctdouble(LP(pp, pctcpu));
579 /* generate "STATE" field */
580 switch (state = LP(pp, stat)) {
582 if (smpmode && LP(pp, tdflags) & TDF_RUNNING)
583 sprintf(status, "CPU%d", LP(pp, cpuid));
585 strcpy(status, "RUN");
588 if (LP(pp, wmesg) != NULL) {
589 sprintf(status, "%.6s", LP(pp, wmesg));
596 (unsigned)state < sizeof(state_abbrev) / sizeof(*state_abbrev))
597 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
599 sprintf(status, "?%5d", state);
603 if (PP(pp, stat) == SZOMB)
604 strcpy(status, "ZOMB");
607 * idle time 0 - 31 -> nice value +21 - +52
608 * normal time -> nice value -20 - +20
609 * real time 0 - 31 -> nice value -52 - -21
610 * thread 0 - 31 -> nice value -53 -
612 switch(LP(pp, rtprio.type)) {
613 case RTP_PRIO_REALTIME:
614 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX + LP(pp, rtprio.prio);
617 xnice = PRIO_MAX + 1 + LP(pp, rtprio.prio);
619 case RTP_PRIO_THREAD:
620 xnice = PRIO_MIN - 1 - RTP_PRIO_MAX - LP(pp, rtprio.prio);
623 xnice = PP(pp, nice);
627 /* format this entry */
628 snprintf(fmt, sizeof(fmt),
629 smpmode ? smp_Proc_format : up_Proc_format,
631 namelength, namelength,
632 get_userid(PP(pp, ruid)),
633 (int)((show_threads && (LP(pp, pid) == -1)) ?
634 LP(pp, tdprio) : LP(pp, prio)),
636 format_k(PROCSIZE(pp)),
637 format_k(pagetok(VP(pp, rssize))),
639 (int)(smpmode ? LP(pp, cpuid) : 0),
640 format_time(cputime),
641 100.0 * weighted_cpu(pct, pp),
644 printable(PP(pp, comm)));
646 /* return the result */
652 * check_nlist(nlst) - checks the nlist to see if any symbols were not
653 * found. For every symbol that was not found, a one-line
654 * message is printed to stderr. The routine returns the
655 * number of symbols NOT found.
658 check_nlist(struct nlist *nlst)
662 /* check to see if we got ALL the symbols we requested */
663 /* this will write one line to stderr for every symbol not found */
666 while (nlst->n_name != NULL)
668 if (nlst->n_type == 0)
670 /* this one wasn't found */
671 (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
682 /* comparison routines for qsort */
685 * proc_compare - comparison function for "qsort"
686 * Compares the resource consumption of two processes using five
687 * distinct keys. The keys (in descending order of importance) are:
688 * percent cpu, cpu ticks, state, resident set size, total virtual
689 * memory usage. The process states are ordered as follows (from least
690 * to most important): WAIT, zombie, sleep, stop, start, run. The
691 * array declaration below maps a process state index into a number
692 * that reflects this ordering.
695 static unsigned char sorted_state[] =
699 1, /* ABANDONED (WAIT) */
707 #define ORDERKEY_PCTCPU \
708 if (lresult = (long) LP(p2, pctcpu) - (long) LP(p1, pctcpu), \
709 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
711 #define CPTICKS(p) (LP(p, uticks) + LP(p, sticks))
713 #define ORDERKEY_CPTICKS \
714 if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
715 CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
717 #define ORDERKEY_STATE \
718 if ((result = sorted_state[(unsigned char) PP(p2, stat)] - \
719 sorted_state[(unsigned char) PP(p1, stat)]) == 0)
721 #define ORDERKEY_PRIO \
722 if ((result = LP(p2, prio) - LP(p1, prio)) == 0)
724 #define ORDERKEY_KTHREADS \
725 if ((result = (LP(p1, pid) == 0) - (LP(p2, pid) == 0)) == 0)
727 #define ORDERKEY_KTHREADS_PRIO \
728 if ((result = LP(p2, tdprio) - LP(p1, tdprio)) == 0)
730 #define ORDERKEY_RSSIZE \
731 if ((result = VP(p2, rssize) - VP(p1, rssize)) == 0)
733 #define ORDERKEY_MEM \
734 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
736 /* compare_cpu - the comparison function for sorting by cpu percentage */
739 proc_compare(const void *arg1, const void *arg2)
741 const struct proc *const*pp1 = arg1;
742 const struct proc *const*pp2 = arg2;
743 const struct kinfo_proc *p1;
744 const struct kinfo_proc *p2;
748 /* remove one level of indirection */
749 p1 = *(const struct kinfo_proc *const *) pp1;
750 p2 = *(const struct kinfo_proc *const *) pp2;
763 /* compare_size - the comparison function for sorting by total memory usage */
766 compare_size(const void *arg1, const void *arg2)
768 struct proc *const *pp1 = arg1;
769 struct proc *const *pp2 = arg2;
770 struct kinfo_proc *p1;
771 struct kinfo_proc *p2;
775 /* remove one level of indirection */
776 p1 = *(struct kinfo_proc *const*) pp1;
777 p2 = *(struct kinfo_proc *const*) pp2;
790 /* compare_res - the comparison function for sorting by resident set size */
793 compare_res(const void *arg1, const void *arg2)
795 struct proc *const *pp1 = arg1;
796 struct proc *const *pp2 = arg2;
797 struct kinfo_proc *p1;
798 struct kinfo_proc *p2;
802 /* remove one level of indirection */
803 p1 = *(struct kinfo_proc *const*) pp1;
804 p2 = *(struct kinfo_proc *const*) pp2;
817 /* compare_time - the comparison function for sorting by total cpu time */
820 compare_time(const void *arg1, const void *arg2)
822 struct proc *const *pp1 = arg1;
823 struct proc *const *pp2 = arg2;
824 const struct kinfo_proc *p1;
825 const struct kinfo_proc *p2;
829 /* remove one level of indirection */
830 p1 = *(struct kinfo_proc *const*) pp1;
831 p2 = *(struct kinfo_proc *const*) pp2;
836 ORDERKEY_KTHREADS_PRIO
846 /* compare_prio - the comparison function for sorting by cpu percentage */
849 compare_prio(const void *arg1, const void *arg2)
851 struct proc *const *pp1 = arg1;
852 struct proc *const *pp2 = arg2;
853 const struct kinfo_proc *p1;
854 const struct kinfo_proc *p2;
858 /* remove one level of indirection */
859 p1 = *(struct kinfo_proc *const*) pp1;
860 p2 = *(struct kinfo_proc *const*) pp2;
863 ORDERKEY_KTHREADS_PRIO
876 compare_thr(const void *arg1, const void *arg2)
878 struct proc *const *pp1 = arg1;
879 struct proc *const *pp2 = arg2;
880 const struct kinfo_proc *p1;
881 const struct kinfo_proc *p2;
885 /* remove one level of indirection */
886 p1 = *(struct kinfo_proc *const*) pp1;
887 p2 = *(struct kinfo_proc *const*) pp2;
890 ORDERKEY_KTHREADS_PRIO
902 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
903 * the process does not exist.
904 * It is EXTREMLY IMPORTANT that this function work correctly.
905 * If top runs setuid root (as in SVR4), then this function
906 * is the only thing that stands in the way of a serious
907 * security problem. It validates requests for the "kill"
908 * and "renice" commands.
915 struct kinfo_proc **prefp;
916 struct kinfo_proc *pp;
923 if (PP(pp, pid) == (pid_t)pid)
925 return((int)PP(pp, ruid));
933 * swapmode is based on a program called swapinfo written
934 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
937 swapmode(int *retavail, int *retfree)
940 int pagesize = getpagesize();
941 struct kvm_swap swapary[1];
946 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
948 n = kvm_getswapinfo(kd, swapary, 1, 0);
949 if (n < 0 || swapary[0].ksw_total == 0)
952 *retavail = CONVERT(swapary[0].ksw_total);
953 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
955 n = (int)((double)swapary[0].ksw_used * 100.0 /
956 (double)swapary[0].ksw_total);