2 * top - a top users display for Unix
5 * Originally written for BSD4.4 system by Christos Zoulas.
6 * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider
7 * Order support hacked in from top-3.5beta6/machine/m_aix41.c
8 * by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/)
10 * AUTHOR: Christos Zoulas <christos@ee.cornell.edu>
11 * Steven Wallace <swallace@freebsd.org>
12 * Wolfram Schneider <wosch@FreeBSD.org>
13 * Thomas Moestl <tmoestl@gmx.net>
18 #include <sys/param.h>
19 #include <sys/errno.h>
22 #include <sys/resource.h>
23 #include <sys/rtprio.h>
24 #include <sys/signal.h>
25 #include <sys/sysctl.h>
28 #include <sys/vmmeter.h>
52 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
53 #define SMPUNAMELEN 13
56 extern struct timeval timeout;
58 enum displaymodes displaymode;
59 static int namelength = 8;
60 /* TOP_JID_LEN based on max of 999999 */
62 #define TOP_SWAP_LEN 6
64 static int swaplength;
65 static int cmdlengthdelta;
67 /* 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 */
75 /* define what weighted cpu is. */
76 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
77 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
79 /* what we consider to be process size: */
80 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
82 #define RU(pp) (&(pp)->ki_rusage)
84 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
86 #define PCTCPU(pp) (pcpu[pp - pbase])
88 /* definitions for indices in the nlist array */
91 * These definitions control the format of the per-process area
94 static char io_header[] =
95 " PID%*s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
97 #define io_Proc_format \
98 "%5d%*s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s"
100 static char smp_header_thr[] =
101 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
102 static char smp_header[] =
103 " PID%*s %-*.*s " "PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
105 #define smp_Proc_format \
106 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s %2d%7s %6.2f%% %.*s"
108 static char up_header_thr[] =
109 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
110 static char up_header[] =
111 " PID%*s %-*.*s " "PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
113 #define up_Proc_format \
114 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s%.0d%7s %6.2f%% %.*s"
117 /* process state names for the "STATE" column of the display */
118 /* the extra nulls in the string "run" are for adding a slash and
119 the processor number when needed */
121 static char *state_abbrev[] = {
122 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
128 /* values that we stash away in _init and use in later routines */
130 static double logcpu;
132 /* these are retrieved from the kernel in _init */
134 static load_avg ccpu;
136 /* these are used in the get_ functions */
140 /* these are for calculating cpu state percentages */
142 static long cp_time[CPUSTATES];
143 static long cp_old[CPUSTATES];
144 static long cp_diff[CPUSTATES];
146 /* these are for detailing the process states */
148 static int process_states[8];
149 static char *procstatenames[] = {
150 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
151 " zombie, ", " waiting, ", " lock, ",
155 /* these are for detailing the cpu states */
157 static int cpu_states[CPUSTATES];
158 static char *cpustatenames[] = {
159 "user", "nice", "system", "interrupt", "idle", NULL
162 /* these are for detailing the memory statistics */
164 static int memory_stats[7];
165 static char *memorynames[] = {
166 "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
170 static int arc_stats[7];
171 static char *arcnames[] = {
172 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
176 static int carc_stats[4];
177 static char *carcnames[] = {
178 "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
182 static int swap_stats[7];
183 static char *swapnames[] = {
184 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
189 /* these are for keeping track of the proc array */
192 static int onproc = -1;
194 static struct kinfo_proc *pbase;
195 static struct kinfo_proc **pref;
196 static struct kinfo_proc *previous_procs;
197 static struct kinfo_proc **previous_pref;
198 static int previous_proc_count = 0;
199 static int previous_proc_count_max = 0;
200 static int previous_thread;
202 /* data used for recalculating pctcpu */
204 static struct timespec proc_uptime;
205 static struct timeval proc_wall_time;
206 static struct timeval previous_wall_time;
207 static uint64_t previous_interval = 0;
209 /* total number of io operations */
210 static long total_inblock;
211 static long total_oublock;
212 static long total_majflt;
214 /* these are for getting the memory statistics */
216 static int arc_enabled;
217 static int carc_enabled;
218 static int pageshift; /* log base 2 of the pagesize */
220 /* define pagetok in terms of pageshift */
222 #define pagetok(size) ((size) << pageshift)
225 #define ki_swap(kip) \
226 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
229 * Sorting orders. The first element is the default.
231 char *ordernames[] = {
232 "cpu", "size", "res", "time", "pri", "threads",
233 "total", "read", "write", "fault", "vcsw", "ivcsw",
234 "jid", "swap", "pid", NULL
237 /* Per-cpu time states */
241 static u_long cpumask;
243 static long *pcpu_cp_time;
244 static long *pcpu_cp_old;
245 static long *pcpu_cp_diff;
246 static int *pcpu_cpu_states;
248 static int compare_swap(const void *a, const void *b);
249 static int compare_jid(const void *a, const void *b);
250 static int compare_pid(const void *a, const void *b);
251 static int compare_tid(const void *a, const void *b);
252 static const char *format_nice(const struct kinfo_proc *pp);
253 static void getsysctl(const char *name, void *ptr, size_t len);
254 static int swapmode(int *retavail, int *retfree);
255 static void update_layout(void);
256 static int find_uid(uid_t needle, int *haystack);
259 find_uid(uid_t needle, int *haystack)
263 for (; i < TOP_MAX_UIDS; ++i)
264 if ((uid_t)haystack[i] == needle)
270 toggle_pcpustats(void)
278 /* Adjust display based on ncpus and the ARC state. */
286 y_swap = 4 + arc_enabled + carc_enabled;
287 y_idlecursor = 5 + arc_enabled + carc_enabled;
288 y_message = 5 + arc_enabled + carc_enabled;
289 y_header = 6 + arc_enabled + carc_enabled;
290 y_procs = 7 + arc_enabled + carc_enabled;
291 Header_lines = 7 + arc_enabled + carc_enabled;
298 y_idlecursor += ncpus - 1;
299 y_message += ncpus - 1;
300 y_header += ncpus - 1;
301 y_procs += ncpus - 1;
302 Header_lines += ncpus - 1;
307 machine_init(struct statics *statics)
309 int i, j, empty, pagesize;
314 size = sizeof(smpmode);
315 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
317 sysctlbyname("kern.smp.active", &smpmode, &size,
319 size != sizeof(smpmode))
322 size = sizeof(arc_size);
323 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
324 NULL, 0) == 0 && arc_size != 0)
326 size = sizeof(carc_en);
328 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
329 NULL, 0) == 0 && carc_en == 1)
332 namelength = MAXLOGNAME;
333 if (smpmode && namelength > SMPUNAMELEN)
334 namelength = SMPUNAMELEN;
335 else if (namelength > UPUNAMELEN)
336 namelength = UPUNAMELEN;
338 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
342 GETSYSCTL("kern.ccpu", ccpu);
344 /* this is used in calculating WCPU -- calculate it ahead of time */
345 logcpu = log(loaddouble(ccpu));
353 /* get the page size and calculate pageshift from it */
354 pagesize = getpagesize();
356 while (pagesize > 1) {
361 /* we only need the amount of log(2)1024 for our conversion */
362 pageshift -= LOG1024;
364 /* fill in the statics information */
365 statics->procstate_names = procstatenames;
366 statics->cpustate_names = cpustatenames;
367 statics->memory_names = memorynames;
369 statics->arc_names = arcnames;
371 statics->arc_names = NULL;
373 statics->carc_names = carcnames;
375 statics->carc_names = NULL;
376 statics->swap_names = swapnames;
377 statics->order_names = ordernames;
379 /* Allocate state for per-CPU stats. */
382 GETSYSCTL("kern.smp.maxcpus", maxcpu);
383 size = sizeof(long) * maxcpu * CPUSTATES;
384 times = malloc(size);
386 err(1, "malloc %zu bytes", size);
387 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
388 err(1, "sysctlbyname kern.cp_times");
389 pcpu_cp_time = calloc(1, size);
390 maxid = (size / CPUSTATES / sizeof(long)) - 1;
391 for (i = 0; i <= maxid; i++) {
393 for (j = 0; empty && j < CPUSTATES; j++) {
394 if (times[i * CPUSTATES + j] != 0)
398 cpumask |= (1ul << i);
402 size = sizeof(long) * ncpus * CPUSTATES;
403 pcpu_cp_old = calloc(1, size);
404 pcpu_cp_diff = calloc(1, size);
405 pcpu_cpu_states = calloc(1, size);
406 statics->ncpus = ncpus;
415 format_header(char *uname_field)
417 static char Header[128];
421 jidlength = TOP_JID_LEN + 1; /* +1 for extra left space. */
426 swaplength = TOP_SWAP_LEN + 1; /* +1 for extra left space */
430 switch (displaymode) {
433 * The logic of picking the right header format seems reverse
434 * here because we only want to display a THR column when
435 * "thread mode" is off (and threads are not listed as
439 (ps.thread ? smp_header : smp_header_thr) :
440 (ps.thread ? up_header : up_header_thr);
441 snprintf(Header, sizeof(Header), prehead,
442 jidlength, ps.jail ? " JID" : "",
443 namelength, namelength, uname_field,
444 swaplength, ps.swap ? " SWAP" : "",
445 ps.wcpu ? "WCPU" : "CPU");
449 snprintf(Header, sizeof(Header), prehead,
450 jidlength, ps.jail ? " JID" : "",
451 namelength, namelength, uname_field);
454 assert("displaymode must not be set to DISP_MAX");
456 cmdlengthdelta = strlen(Header) - 7;
460 static int swappgsin = -1;
461 static int swappgsout = -1;
465 get_system_info(struct system_info *si)
467 struct loadavg sysload;
469 struct timeval boottime;
470 uint64_t arc_stat, arc_stat2;
474 /* get the CPU stats */
475 size = (maxid + 1) * CPUSTATES * sizeof(long);
476 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
477 err(1, "sysctlbyname kern.cp_times");
478 GETSYSCTL("kern.cp_time", cp_time);
479 GETSYSCTL("vm.loadavg", sysload);
480 GETSYSCTL("kern.lastpid", lastpid);
482 /* convert load averages to doubles */
483 for (i = 0; i < 3; i++)
484 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
486 /* convert cp_time counts to percentages */
487 for (i = j = 0; i <= maxid; i++) {
488 if ((cpumask & (1ul << i)) == 0)
490 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
491 &pcpu_cp_time[j * CPUSTATES],
492 &pcpu_cp_old[j * CPUSTATES],
493 &pcpu_cp_diff[j * CPUSTATES]);
496 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
498 /* sum memory & swap statistics */
500 static unsigned int swap_delay = 0;
501 static int swapavail = 0;
502 static int swapfree = 0;
503 static long bufspace = 0;
504 static uint64_t nspgsin, nspgsout;
506 GETSYSCTL("vfs.bufspace", bufspace);
507 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
508 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
509 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
510 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
511 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
512 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
513 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
514 /* convert memory stats to Kbytes */
515 memory_stats[0] = pagetok(memory_stats[0]);
516 memory_stats[1] = pagetok(memory_stats[1]);
517 memory_stats[2] = pagetok(memory_stats[2]);
518 memory_stats[3] = pagetok(memory_stats[3]);
519 memory_stats[4] = bufspace / 1024;
520 memory_stats[5] = pagetok(memory_stats[5]);
521 memory_stats[6] = -1;
529 /* compute differences between old and new swap statistic */
531 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
532 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
536 swappgsout = nspgsout;
538 /* call CPU heavy swapmode() only for changes */
539 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
540 swap_stats[3] = swapmode(&swapavail, &swapfree);
541 swap_stats[0] = swapavail;
542 swap_stats[1] = swapavail - swapfree;
543 swap_stats[2] = swapfree;
550 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
551 arc_stats[0] = arc_stat >> 10;
552 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
553 arc_stats[1] = arc_stat >> 10;
554 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
555 arc_stats[2] = arc_stat >> 10;
556 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
557 arc_stats[3] = arc_stat >> 10;
558 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
559 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
560 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
561 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
562 arc_stats[5] = arc_stat >> 10;
566 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
567 carc_stats[0] = arc_stat >> 10;
568 carc_stats[2] = arc_stat >> 10; /* For ratio */
569 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
570 carc_stats[1] = arc_stat >> 10;
571 si->carc = carc_stats;
574 /* set arrays and strings */
576 si->cpustates = pcpu_cpu_states;
579 si->cpustates = cpu_states;
582 si->memory = memory_stats;
583 si->swap = swap_stats;
587 si->last_pid = lastpid;
593 * Print how long system has been up.
594 * (Found by looking getting "boottime" from the kernel)
597 mib[1] = KERN_BOOTTIME;
598 size = sizeof(boottime);
599 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
600 boottime.tv_sec != 0) {
601 si->boottime = boottime;
603 si->boottime.tv_sec = -1;
607 #define NOPROC ((void *)-1)
610 * We need to compare data from the old process entry with the new
612 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
613 * structure to cache the mapping. We also use a negative cache pointer
614 * of NOPROC to avoid duplicate lookups.
615 * XXX: this could be done when the actual processes are fetched, we do
616 * it here out of laziness.
618 static const struct kinfo_proc *
619 get_old_proc(struct kinfo_proc *pp)
621 struct kinfo_proc **oldpp, *oldp;
624 * If this is the first fetch of the kinfo_procs then we don't have
625 * any previous entries.
627 if (previous_proc_count == 0)
629 /* negative cache? */
630 if (pp->ki_udata == NOPROC)
633 if (pp->ki_udata != NULL)
634 return (pp->ki_udata);
637 * 1) look up based on pid.
638 * 2) compare process start.
639 * If we fail here, then setup a negative cache entry, otherwise
642 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
643 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
645 pp->ki_udata = NOPROC;
649 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
650 pp->ki_udata = NOPROC;
658 * Return the total amount of IO done in blocks in/out and faults.
659 * store the values individually in the pointers passed in.
662 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp,
663 long *vcsw, long *ivcsw)
665 const struct kinfo_proc *oldp;
666 static struct kinfo_proc dummy;
669 oldp = get_old_proc(pp);
671 bzero(&dummy, sizeof(dummy));
674 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
675 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
676 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
677 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
678 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
680 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
681 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
682 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
687 * If there was a previous update, use the delta in ki_runtime over
688 * the previous interval to calculate pctcpu. Otherwise, fall back
689 * to using the kernel's ki_pctcpu.
692 proc_calc_pctcpu(struct kinfo_proc *pp)
694 const struct kinfo_proc *oldp;
696 if (previous_interval != 0) {
697 oldp = get_old_proc(pp);
699 return ((double)(pp->ki_runtime - oldp->ki_runtime)
700 / previous_interval);
703 * If this process/thread was created during the previous
704 * interval, charge it's total runtime to the previous
707 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
708 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
709 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
710 return ((double)pp->ki_runtime / previous_interval);
712 return (pctdouble(pp->ki_pctcpu));
716 * Return true if this process has used any CPU time since the
720 proc_used_cpu(struct kinfo_proc *pp)
722 const struct kinfo_proc *oldp;
724 oldp = get_old_proc(pp);
726 return (PCTCPU(pp) != 0);
727 return (pp->ki_runtime != oldp->ki_runtime ||
728 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
729 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
733 * Return the total number of block in/out and faults by a process.
736 get_io_total(struct kinfo_proc *pp)
740 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
743 static struct handle handle;
746 get_process_info(struct system_info *si, struct process_select *sel,
747 int (*compare)(const void *, const void *))
752 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
755 struct kinfo_proc **prefp;
756 struct kinfo_proc *pp;
757 struct timespec previous_proc_uptime;
759 /* these are copied out of sel for speed */
769 * If thread state was toggled, don't cache the previous processes.
771 if (previous_thread != sel->thread)
773 previous_thread = sel->thread;
776 * Save the previous process info.
778 if (previous_proc_count_max < nproc) {
779 free(previous_procs);
780 previous_procs = malloc(nproc * sizeof(*previous_procs));
782 previous_pref = malloc(nproc * sizeof(*previous_pref));
783 if (previous_procs == NULL || previous_pref == NULL) {
784 (void) fprintf(stderr, "top: Out of memory.\n");
787 previous_proc_count_max = nproc;
790 for (i = 0; i < nproc; i++)
791 previous_pref[i] = &previous_procs[i];
792 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs));
793 qsort(previous_pref, nproc, sizeof(*previous_pref),
794 ps.thread ? compare_tid : compare_pid);
796 previous_proc_count = nproc;
797 previous_proc_uptime = proc_uptime;
798 previous_wall_time = proc_wall_time;
799 previous_interval = 0;
801 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
803 (void)gettimeofday(&proc_wall_time, NULL);
804 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
805 memset(&proc_uptime, 0, sizeof(proc_uptime));
806 else if (previous_proc_uptime.tv_sec != 0 &&
807 previous_proc_uptime.tv_nsec != 0) {
808 previous_interval = (proc_uptime.tv_sec -
809 previous_proc_uptime.tv_sec) * 1000000;
810 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
812 previous_interval -= 1000000;
815 previous_interval += nsec / 1000;
817 if (nproc > onproc) {
818 pref = realloc(pref, sizeof(*pref) * nproc);
819 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
822 if (pref == NULL || pbase == NULL || pcpu == NULL) {
823 (void) fprintf(stderr, "top: Out of memory.\n");
826 /* get a pointer to the states summary array */
827 si->procstates = process_states;
829 /* set up flags which define what we are going to select */
830 show_idle = sel->idle;
831 show_jid = sel->jid != -1;
832 show_self = sel->self == -1;
833 show_system = sel->system;
834 show_uid = sel->uid[0] != -1;
835 show_command = sel->command != NULL;
836 show_kidle = sel->kidle;
838 /* count up process states and get pointers to interesting procs */
844 memset((char *)process_states, 0, sizeof(process_states));
846 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
848 if (pp->ki_stat == 0)
852 if (!show_self && pp->ki_pid == sel->self)
856 if (!show_system && (pp->ki_flag & P_SYSTEM))
857 /* skip system process */
860 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
862 total_inblock += p_inblock;
863 total_oublock += p_oublock;
864 total_majflt += p_majflt;
866 process_states[(unsigned char)pp->ki_stat]++;
868 if (pp->ki_stat == SZOMB)
872 if (!show_kidle && pp->ki_tdflags & TDF_IDLETD)
873 /* skip kernel idle process */
876 PCTCPU(pp) = proc_calc_pctcpu(pp);
877 if (sel->thread && PCTCPU(pp) > 1.0)
879 if (displaymode == DISP_CPU && !show_idle &&
880 (!proc_used_cpu(pp) ||
881 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
882 /* skip idle or non-running processes */
885 if (displaymode == DISP_IO && !show_idle && p_io == 0)
886 /* skip processes that aren't doing I/O */
889 if (show_jid && pp->ki_jid != sel->jid)
890 /* skip proc. that don't belong to the selected JID */
893 if (show_uid && !find_uid(pp->ki_ruid, sel->uid))
894 /* skip proc. that don't belong to the selected UID */
901 /* if requested, sort the "interesting" processes */
903 qsort(pref, active_procs, sizeof(*pref), compare);
905 /* remember active and total counts */
906 si->p_total = total_procs;
907 si->p_pactive = pref_len = active_procs;
909 /* pass back a handle */
910 handle.next_proc = pref;
911 handle.remaining = active_procs;
912 return ((caddr_t)&handle);
915 static char fmt[512]; /* static area where result is built */
918 format_next_process(caddr_t xhandle, char *(*get_userid)(int), int flags)
920 struct kinfo_proc *pp;
921 const struct kinfo_proc *oldp;
928 struct rusage ru, *rup;
932 char jid_buf[TOP_JID_LEN + 1], swap_buf[TOP_SWAP_LEN + 1];
935 const int cmdlen = 128;
937 /* find and remember the next proc structure */
938 hp = (struct handle *)xhandle;
939 pp = *(hp->next_proc++);
942 /* get the process's command name */
943 if ((pp->ki_flag & P_INMEM) == 0) {
945 * Print swapped processes as <pname>
949 len = strlen(pp->ki_comm);
950 if (len > sizeof(pp->ki_comm) - 3)
951 len = sizeof(pp->ki_comm) - 3;
952 memmove(pp->ki_comm + 1, pp->ki_comm, len);
953 pp->ki_comm[0] = '<';
954 pp->ki_comm[len + 1] = '>';
955 pp->ki_comm[len + 2] = '\0';
959 * Convert the process's runtime from microseconds to seconds. This
960 * time includes the interrupt time although that is not wanted here.
961 * ps(1) is similarly sloppy.
963 cputime = (pp->ki_runtime + 500000) / 1000000;
965 /* calculate the base for cpu percentages */
968 /* generate "STATE" field */
969 switch (state = pp->ki_stat) {
971 if (smpmode && pp->ki_oncpu != NOCPU)
972 sprintf(status, "CPU%d", pp->ki_oncpu);
974 strcpy(status, "RUN");
977 if (pp->ki_kiflag & KI_LOCKBLOCK) {
978 sprintf(status, "*%.6s", pp->ki_lockname);
983 sprintf(status, "%.6s", pp->ki_wmesg);
988 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
989 sprintf(status, "%.6s", state_abbrev[state]);
991 sprintf(status, "?%5zu", state);
995 cmdbuf = (char *)malloc(cmdlen + 1);
996 if (cmdbuf == NULL) {
997 warn("malloc(%d)", cmdlen + 1);
1001 if (!(flags & FMT_SHOWARGS)) {
1002 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1004 snprintf(cmdbuf, cmdlen, "%s{%s%s}", pp->ki_comm,
1005 pp->ki_tdname, pp->ki_moretdname);
1007 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
1010 if (pp->ki_flag & P_SYSTEM ||
1011 pp->ki_args == NULL ||
1012 (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
1014 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1016 snprintf(cmdbuf, cmdlen,
1017 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1020 snprintf(cmdbuf, cmdlen,
1021 "[%s]", pp->ki_comm);
1024 char *src, *dst, *argbuf;
1029 argbuflen = cmdlen * 4;
1030 argbuf = (char *)malloc(argbuflen + 1);
1031 if (argbuf == NULL) {
1032 warn("malloc(%zu)", argbuflen + 1);
1039 /* Extract cmd name from argv */
1040 cmd = strrchr(*args, '/');
1046 for (; (src = *args++) != NULL; ) {
1049 len = (argbuflen - (dst - argbuf) - 1) / 4;
1051 MIN(strlen(src), len),
1052 VIS_NL | VIS_CSTYLE);
1053 while (*dst != '\0')
1055 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1056 *dst++ = ' '; /* add delimiting space */
1058 if (dst != argbuf && dst[-1] == ' ')
1062 if (strcmp(cmd, pp->ki_comm) != 0) {
1063 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1065 snprintf(cmdbuf, cmdlen,
1066 "%s (%s){%s%s}", argbuf,
1067 pp->ki_comm, pp->ki_tdname,
1070 snprintf(cmdbuf, cmdlen,
1071 "%s (%s)", argbuf, pp->ki_comm);
1073 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1075 snprintf(cmdbuf, cmdlen,
1076 "%s{%s%s}", argbuf, pp->ki_tdname,
1079 strlcpy(cmdbuf, argbuf, cmdlen);
1088 snprintf(jid_buf, sizeof(jid_buf), "%*d",
1089 jidlength - 1, pp->ki_jid);
1094 snprintf(swap_buf, sizeof(swap_buf), "%*s",
1096 format_k2(pagetok(ki_swap(pp)))); /* XXX */
1098 if (displaymode == DISP_IO) {
1099 oldp = get_old_proc(pp);
1101 ru.ru_inblock = RU(pp)->ru_inblock -
1102 RU(oldp)->ru_inblock;
1103 ru.ru_oublock = RU(pp)->ru_oublock -
1104 RU(oldp)->ru_oublock;
1105 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1106 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1107 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1112 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1113 s_tot = total_inblock + total_oublock + total_majflt;
1115 snprintf(fmt, sizeof(fmt), io_Proc_format,
1118 namelength, namelength, (*get_userid)(pp->ki_ruid),
1125 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
1126 screen_width > cmdlengthdelta ?
1127 screen_width - cmdlengthdelta : 0,
1135 /* format this entry */
1137 if (state == SRUN && pp->ki_oncpu != NOCPU)
1140 cpu = pp->ki_lastcpu;
1143 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1147 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1148 (int)(sizeof(thr_buf) - 2), pp->ki_numthreads);
1150 snprintf(fmt, sizeof(fmt), proc_fmt,
1153 namelength, namelength, (*get_userid)(pp->ki_ruid),
1155 pp->ki_pri.pri_level - PZERO,
1157 format_k2(PROCSIZE(pp)),
1158 format_k2(pagetok(pp->ki_rssize)),
1159 swaplength, swaplength, swap_buf,
1162 format_time(cputime),
1163 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1164 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1169 /* return the result */
1174 getsysctl(const char *name, void *ptr, size_t len)
1178 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1179 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1184 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1185 name, (unsigned long)len, (unsigned long)nlen);
1191 format_nice(const struct kinfo_proc *pp)
1193 const char *fifo, *kproc;
1195 static char nicebuf[4 + 1];
1197 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1198 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1199 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1204 * XXX: the kernel doesn't tell us the original rtprio and
1205 * doesn't really know what it was, so to recover it we
1206 * must be more chummy with the implementation than the
1207 * implementation is with itself. pri_user gives a
1208 * constant "base" priority, but is only initialized
1209 * properly for user threads. pri_native gives what the
1210 * kernel calls the "base" priority, but it isn't constant
1211 * since it is changed by priority propagation. pri_native
1212 * also isn't properly initialized for all threads, but it
1213 * is properly initialized for kernel realtime and idletime
1214 * threads. Thus we use pri_user for the base priority of
1215 * user threads (it is always correct) and pri_native for
1216 * the base priority of kernel realtime and idletime threads
1217 * (there is nothing better, and it is usually correct).
1219 * The field width and thus the buffer are too small for
1220 * values like "kr31F", but such values shouldn't occur,
1221 * and if they do then the tailing "F" is not displayed.
1223 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1224 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1225 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1226 kproc, rtpri, fifo);
1229 if (pp->ki_flag & P_KPROC)
1231 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1234 /* XXX: as above. */
1235 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1236 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1237 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1238 kproc, rtpri, fifo);
1246 /* comparison routines for qsort */
1249 compare_pid(const void *p1, const void *p2)
1251 const struct kinfo_proc * const *pp1 = p1;
1252 const struct kinfo_proc * const *pp2 = p2;
1254 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0)
1257 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1261 compare_tid(const void *p1, const void *p2)
1263 const struct kinfo_proc * const *pp1 = p1;
1264 const struct kinfo_proc * const *pp2 = p2;
1266 if ((*pp2)->ki_tid < 0 || (*pp1)->ki_tid < 0)
1269 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1273 * proc_compare - comparison function for "qsort"
1274 * Compares the resource consumption of two processes using five
1275 * distinct keys. The keys (in descending order of importance) are:
1276 * percent cpu, cpu ticks, state, resident set size, total virtual
1277 * memory usage. The process states are ordered as follows (from least
1278 * to most important): WAIT, zombie, sleep, stop, start, run. The
1279 * array declaration below maps a process state index into a number
1280 * that reflects this ordering.
1283 static int sorted_state[] = {
1286 1, /* ABANDONED (WAIT) */
1294 #define ORDERKEY_PCTCPU(a, b) do { \
1297 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1298 weighted_cpu(PCTCPU((a)), (a)); \
1300 diff = PCTCPU((b)) - PCTCPU((a)); \
1302 return (diff > 0 ? 1 : -1); \
1305 #define ORDERKEY_CPTICKS(a, b) do { \
1306 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1308 return (diff > 0 ? 1 : -1); \
1311 #define ORDERKEY_STATE(a, b) do { \
1312 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1314 return (diff > 0 ? 1 : -1); \
1317 #define ORDERKEY_PRIO(a, b) do { \
1318 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1320 return (diff > 0 ? 1 : -1); \
1323 #define ORDERKEY_THREADS(a, b) do { \
1324 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1326 return (diff > 0 ? 1 : -1); \
1329 #define ORDERKEY_RSSIZE(a, b) do { \
1330 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1332 return (diff > 0 ? 1 : -1); \
1335 #define ORDERKEY_MEM(a, b) do { \
1336 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1338 return (diff > 0 ? 1 : -1); \
1341 #define ORDERKEY_JID(a, b) do { \
1342 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1344 return (diff > 0 ? 1 : -1); \
1347 #define ORDERKEY_SWAP(a, b) do { \
1348 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1350 return (diff > 0 ? 1 : -1); \
1353 /* compare_cpu - the comparison function for sorting by cpu percentage */
1356 compare_cpu(const void *arg1, const void *arg2)
1358 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1359 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1361 ORDERKEY_PCTCPU(p1, p2);
1362 ORDERKEY_CPTICKS(p1, p2);
1363 ORDERKEY_STATE(p1, p2);
1364 ORDERKEY_PRIO(p1, p2);
1365 ORDERKEY_RSSIZE(p1, p2);
1366 ORDERKEY_MEM(p1, p2);
1371 /* "cpu" compare routines */
1372 static int compare_size(const void *arg1, const void *arg2);
1373 static int compare_res(const void *arg1, const void *arg2);
1374 static int compare_time(const void *arg1, const void *arg2);
1375 static int compare_prio(const void *arg1, const void *arg2);
1376 static int compare_threads(const void *arg1, const void *arg2);
1379 * "io" compare routines. Context switches aren't i/o, but are displayed
1380 * on the "io" display.
1382 static int compare_iototal(const void *arg1, const void *arg2);
1383 static int compare_ioread(const void *arg1, const void *arg2);
1384 static int compare_iowrite(const void *arg1, const void *arg2);
1385 static int compare_iofault(const void *arg1, const void *arg2);
1386 static int compare_vcsw(const void *arg1, const void *arg2);
1387 static int compare_ivcsw(const void *arg1, const void *arg2);
1389 int (*compares[])(const void *arg1, const void *arg2) = {
1407 /* compare_size - the comparison function for sorting by total memory usage */
1410 compare_size(const void *arg1, const void *arg2)
1412 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1413 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1415 ORDERKEY_MEM(p1, p2);
1416 ORDERKEY_RSSIZE(p1, p2);
1417 ORDERKEY_PCTCPU(p1, p2);
1418 ORDERKEY_CPTICKS(p1, p2);
1419 ORDERKEY_STATE(p1, p2);
1420 ORDERKEY_PRIO(p1, p2);
1425 /* compare_res - the comparison function for sorting by resident set size */
1428 compare_res(const void *arg1, const void *arg2)
1430 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1431 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1433 ORDERKEY_RSSIZE(p1, p2);
1434 ORDERKEY_MEM(p1, p2);
1435 ORDERKEY_PCTCPU(p1, p2);
1436 ORDERKEY_CPTICKS(p1, p2);
1437 ORDERKEY_STATE(p1, p2);
1438 ORDERKEY_PRIO(p1, p2);
1443 /* compare_time - the comparison function for sorting by total cpu time */
1446 compare_time(const void *arg1, const void *arg2)
1448 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1449 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1451 ORDERKEY_CPTICKS(p1, p2);
1452 ORDERKEY_PCTCPU(p1, p2);
1453 ORDERKEY_STATE(p1, p2);
1454 ORDERKEY_PRIO(p1, p2);
1455 ORDERKEY_RSSIZE(p1, p2);
1456 ORDERKEY_MEM(p1, p2);
1461 /* compare_prio - the comparison function for sorting by priority */
1464 compare_prio(const void *arg1, const void *arg2)
1466 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1467 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1469 ORDERKEY_PRIO(p1, p2);
1470 ORDERKEY_CPTICKS(p1, p2);
1471 ORDERKEY_PCTCPU(p1, p2);
1472 ORDERKEY_STATE(p1, p2);
1473 ORDERKEY_RSSIZE(p1, p2);
1474 ORDERKEY_MEM(p1, p2);
1479 /* compare_threads - the comparison function for sorting by threads */
1481 compare_threads(const void *arg1, const void *arg2)
1483 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1484 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1486 ORDERKEY_THREADS(p1, p2);
1487 ORDERKEY_PCTCPU(p1, p2);
1488 ORDERKEY_CPTICKS(p1, p2);
1489 ORDERKEY_STATE(p1, p2);
1490 ORDERKEY_PRIO(p1, p2);
1491 ORDERKEY_RSSIZE(p1, p2);
1492 ORDERKEY_MEM(p1, p2);
1497 /* compare_jid - the comparison function for sorting by jid */
1499 compare_jid(const void *arg1, const void *arg2)
1501 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1502 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1504 ORDERKEY_JID(p1, p2);
1505 ORDERKEY_PCTCPU(p1, p2);
1506 ORDERKEY_CPTICKS(p1, p2);
1507 ORDERKEY_STATE(p1, p2);
1508 ORDERKEY_PRIO(p1, p2);
1509 ORDERKEY_RSSIZE(p1, p2);
1510 ORDERKEY_MEM(p1, p2);
1515 /* compare_swap - the comparison function for sorting by swap */
1517 compare_swap(const void *arg1, const void *arg2)
1519 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1520 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1522 ORDERKEY_SWAP(p1, p2);
1523 ORDERKEY_PCTCPU(p1, p2);
1524 ORDERKEY_CPTICKS(p1, p2);
1525 ORDERKEY_STATE(p1, p2);
1526 ORDERKEY_PRIO(p1, p2);
1527 ORDERKEY_RSSIZE(p1, p2);
1528 ORDERKEY_MEM(p1, p2);
1533 /* assorted comparison functions for sorting by i/o */
1536 compare_iototal(const void *arg1, const void *arg2)
1538 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1539 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1541 return (get_io_total(p2) - get_io_total(p1));
1545 compare_ioread(const void *arg1, const void *arg2)
1547 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1548 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1549 long dummy, inp1, inp2;
1551 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1552 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1554 return (inp2 - inp1);
1558 compare_iowrite(const void *arg1, const void *arg2)
1560 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1561 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1562 long dummy, oup1, oup2;
1564 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1565 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1567 return (oup2 - oup1);
1571 compare_iofault(const void *arg1, const void *arg2)
1573 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1574 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1575 long dummy, flp1, flp2;
1577 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1578 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1580 return (flp2 - flp1);
1584 compare_vcsw(const void *arg1, const void *arg2)
1586 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1587 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1588 long dummy, flp1, flp2;
1590 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1591 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1593 return (flp2 - flp1);
1597 compare_ivcsw(const void *arg1, const void *arg2)
1599 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1;
1600 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2;
1601 long dummy, flp1, flp2;
1603 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1604 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1606 return (flp2 - flp1);
1610 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1611 * the process does not exist.
1612 * It is EXTREMELY IMPORTANT that this function work correctly.
1613 * If top runs setuid root (as in SVR4), then this function
1614 * is the only thing that stands in the way of a serious
1615 * security problem. It validates requests for the "kill"
1616 * and "renice" commands.
1623 struct kinfo_proc **prefp;
1624 struct kinfo_proc *pp;
1628 while (--cnt >= 0) {
1630 if (pp->ki_pid == (pid_t)pid)
1631 return ((int)pp->ki_ruid);
1637 swapmode(int *retavail, int *retfree)
1640 struct kvm_swap swapary[1];
1641 static int pagesize = 0;
1642 static u_long swap_maxpages = 0;
1647 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1649 n = kvm_getswapinfo(kd, swapary, 1, 0);
1650 if (n < 0 || swapary[0].ksw_total == 0)
1654 pagesize = getpagesize();
1655 if (swap_maxpages == 0)
1656 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1658 /* ksw_total contains the total size of swap all devices which may
1659 exceed the maximum swap size allocatable in the system */
1660 if ( swapary[0].ksw_total > swap_maxpages )
1661 swapary[0].ksw_total = swap_maxpages;
1663 *retavail = CONVERT(swapary[0].ksw_total);
1664 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1666 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);