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>
14 * Eitan Adler <eadler@FreeBSD.org>
19 #include <sys/errno.h>
20 #include <sys/fcntl.h>
21 #include <sys/param.h>
22 #include <sys/priority.h>
24 #include <sys/resource.h>
25 #include <sys/sysctl.h>
51 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
52 #define SMPUNAMELEN 13
55 extern struct timeval timeout;
57 enum displaymodes displaymode;
58 static int namelength = 8;
59 /* TOP_JID_LEN based on max of 999999 */
61 #define TOP_SWAP_LEN 6
63 static int swaplength;
64 static int cmdlengthdelta;
66 /* get_process_info passes back a handle. This is what it looks like: */
69 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
70 int remaining; /* number of pointers remaining */
74 /* define what weighted cpu is. */
75 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \
76 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu))))
78 /* what we consider to be process size: */
79 #define PROCSIZE(pp) ((pp)->ki_size / 1024)
81 #define RU(pp) (&(pp)->ki_rusage)
83 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt)
85 #define PCTCPU(pp) (pcpu[pp - pbase])
88 * These definitions control the format of the per-process area
91 static const char io_header[] =
92 " PID%*s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND";
94 static const char io_Proc_format[] =
95 "%5d%*s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s";
97 static const char smp_header_thr_and_pid[] =
98 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
99 static const char smp_header_tid_only[] =
100 " THR%*s %-*.*s " "PRI NICE SIZE RES%*s STATE C TIME %7s COMMAND";
102 static const char smp_Proc_format[] =
103 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s %2d%7s %6.2f%% %.*s";
105 static char up_header_thr_and_pid[] =
106 " PID%*s %-*.*s THR PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
107 static char up_header_tid_only[] =
108 " THR%*s %-*.*s " "PRI NICE SIZE RES%*s STATE TIME %7s COMMAND";
110 static char up_Proc_format[] =
111 "%5d%*s %-*.*s %s%3d %4s%7s %6s%*.*s %-6.6s%.0d%7s %6.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 static const char *state_abbrev[] = {
119 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK"
125 /* values that we stash away in _init and use in later routines */
127 static double logcpu;
129 /* these are retrieved from the kernel in _init */
131 static load_avg ccpu;
133 /* these are used in the get_ functions */
137 /* these are for calculating cpu state percentages */
139 static long cp_time[CPUSTATES];
140 static long cp_old[CPUSTATES];
141 static long cp_diff[CPUSTATES];
143 /* these are for detailing the process states */
145 static const char *procstatenames[] = {
146 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
147 " zombie, ", " waiting, ", " lock, ",
150 static int process_states[nitems(procstatenames)];
152 /* these are for detailing the cpu states */
154 static int cpu_states[CPUSTATES];
155 static const char *cpustatenames[] = {
156 "user", "nice", "system", "interrupt", "idle", NULL
159 /* these are for detailing the memory statistics */
161 static const char *memorynames[] = {
162 "K Active, ", "K Inact, ", "K Laundry, ", "K Wired, ", "K Buf, ",
165 static int memory_stats[nitems(memorynames)];
167 static const char *arcnames[] = {
168 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other",
171 static int arc_stats[nitems(arcnames)];
173 static const char *carcnames[] = {
174 "K Compressed, ", "K Uncompressed, ", ":1 Ratio, ",
177 static int carc_stats[nitems(carcnames)];
179 static const char *swapnames[] = {
180 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
183 static int swap_stats[nitems(swapnames)];
186 /* these are for keeping track of the proc array */
189 static int onproc = -1;
191 static struct kinfo_proc *pbase;
192 static struct kinfo_proc **pref;
193 static struct kinfo_proc *previous_procs;
194 static struct kinfo_proc **previous_pref;
195 static int previous_proc_count = 0;
196 static int previous_proc_count_max = 0;
197 static int previous_thread;
199 /* data used for recalculating pctcpu */
201 static struct timespec proc_uptime;
202 static struct timeval proc_wall_time;
203 static struct timeval previous_wall_time;
204 static uint64_t previous_interval = 0;
206 /* total number of io operations */
207 static long total_inblock;
208 static long total_oublock;
209 static long total_majflt;
211 /* these are for getting the memory statistics */
213 static int arc_enabled;
214 static int carc_enabled;
215 static int pageshift; /* log base 2 of the pagesize */
217 /* define pagetok in terms of pageshift */
219 #define pagetok(size) ((size) << pageshift)
222 #define ki_swap(kip) \
223 ((kip)->ki_swrss > (kip)->ki_rssize ? (kip)->ki_swrss - (kip)->ki_rssize : 0)
226 * Sorting orders. The first element is the default.
228 static const char *ordernames[] = {
229 "cpu", "size", "res", "time", "pri", "threads",
230 "total", "read", "write", "fault", "vcsw", "ivcsw",
231 "jid", "swap", "pid", NULL
234 /* Per-cpu time states */
238 static unsigned long cpumask;
240 static long *pcpu_cp_time;
241 static long *pcpu_cp_old;
242 static long *pcpu_cp_diff;
243 static int *pcpu_cpu_states;
245 static int compare_swap(const void *a, const void *b);
246 static int compare_jid(const void *a, const void *b);
247 static int compare_pid(const void *a, const void *b);
248 static int compare_tid(const void *a, const void *b);
249 static const char *format_nice(const struct kinfo_proc *pp);
250 static void getsysctl(const char *name, void *ptr, size_t len);
251 static int swapmode(int *retavail, int *retfree);
252 static void update_layout(void);
253 static int find_uid(uid_t needle, int *haystack);
256 find_uid(uid_t needle, int *haystack)
260 for (; i < TOP_MAX_UIDS; ++i)
261 if ((uid_t)haystack[i] == needle)
267 toggle_pcpustats(void)
275 /* Adjust display based on ncpus and the ARC state. */
283 y_swap = 4 + arc_enabled + carc_enabled;
284 y_idlecursor = 5 + arc_enabled + carc_enabled;
285 y_message = 5 + arc_enabled + carc_enabled;
286 y_header = 6 + arc_enabled + carc_enabled;
287 y_procs = 7 + arc_enabled + carc_enabled;
288 Header_lines = 7 + arc_enabled + carc_enabled;
295 y_idlecursor += ncpus - 1;
296 y_message += ncpus - 1;
297 y_header += ncpus - 1;
298 y_procs += ncpus - 1;
299 Header_lines += ncpus - 1;
304 machine_init(struct statics *statics)
306 int i, j, empty, pagesize;
311 size = sizeof(smpmode);
312 if ((sysctlbyname("machdep.smp_active", &smpmode, &size,
314 sysctlbyname("kern.smp.active", &smpmode, &size,
316 size != sizeof(smpmode))
319 size = sizeof(arc_size);
320 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size,
321 NULL, 0) == 0 && arc_size != 0)
323 size = sizeof(carc_en);
325 sysctlbyname("vfs.zfs.compressed_arc_enabled", &carc_en, &size,
326 NULL, 0) == 0 && carc_en == 1)
329 namelength = MAXLOGNAME;
330 if (smpmode && namelength > SMPUNAMELEN)
331 namelength = SMPUNAMELEN;
332 else if (namelength > UPUNAMELEN)
333 namelength = UPUNAMELEN;
335 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
339 GETSYSCTL("kern.ccpu", ccpu);
341 /* this is used in calculating WCPU -- calculate it ahead of time */
342 logcpu = log(loaddouble(ccpu));
350 /* get the page size and calculate pageshift from it */
351 pagesize = getpagesize();
353 while (pagesize > 1) {
358 /* we only need the amount of log(2)1024 for our conversion */
359 pageshift -= LOG1024;
361 /* fill in the statics information */
362 statics->procstate_names = procstatenames;
363 statics->cpustate_names = cpustatenames;
364 statics->memory_names = memorynames;
366 statics->arc_names = arcnames;
368 statics->arc_names = NULL;
370 statics->carc_names = carcnames;
372 statics->carc_names = NULL;
373 statics->swap_names = swapnames;
374 statics->order_names = ordernames;
376 /* Allocate state for per-CPU stats. */
379 GETSYSCTL("kern.smp.maxcpus", maxcpu);
380 times = calloc(maxcpu * CPUSTATES, sizeof(long));
382 err(1, "calloc for kern.smp.maxcpus");
383 size = sizeof(long) * maxcpu * CPUSTATES;
384 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1)
385 err(1, "sysctlbyname kern.cp_times");
386 pcpu_cp_time = calloc(1, size);
387 maxid = (size / CPUSTATES / sizeof(long)) - 1;
388 for (i = 0; i <= maxid; i++) {
390 for (j = 0; empty && j < CPUSTATES; j++) {
391 if (times[i * CPUSTATES + j] != 0)
395 cpumask |= (1ul << i);
400 pcpu_cp_old = calloc(ncpus * CPUSTATES, sizeof(long));
401 pcpu_cp_diff = calloc(ncpus * CPUSTATES, sizeof(long));
402 pcpu_cpu_states = calloc(ncpus * CPUSTATES, sizeof(int));
403 statics->ncpus = ncpus;
412 format_header(const char *uname_field)
414 static char Header[128];
418 jidlength = TOP_JID_LEN + 1; /* +1 for extra left space. */
423 swaplength = TOP_SWAP_LEN + 1; /* +1 for extra left space */
427 switch (displaymode) {
430 * The logic of picking the right header format seems reverse
431 * here because we only want to display a THR column when
432 * "thread mode" is off (and threads are not listed as
436 (ps.thread_id ? smp_header_tid_only : smp_header_thr_and_pid) :
437 (ps.thread_id ? up_header_tid_only : up_header_thr_and_pid);
438 snprintf(Header, sizeof(Header), prehead,
439 jidlength, ps.jail ? " JID" : "",
440 namelength, namelength, uname_field,
441 swaplength, ps.swap ? " SWAP" : "",
442 ps.wcpu ? "WCPU" : "CPU");
446 snprintf(Header, sizeof(Header), prehead,
447 jidlength, ps.jail ? " JID" : "",
448 namelength, namelength, uname_field);
451 assert("displaymode must not be set to DISP_MAX");
453 cmdlengthdelta = strlen(Header) - 7;
457 static int swappgsin = -1;
458 static int swappgsout = -1;
462 get_system_info(struct system_info *si)
464 struct loadavg sysload;
466 struct timeval boottime;
467 uint64_t arc_stat, arc_stat2;
471 /* get the CPU stats */
472 size = (maxid + 1) * CPUSTATES * sizeof(long);
473 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1)
474 err(1, "sysctlbyname kern.cp_times");
475 GETSYSCTL("kern.cp_time", cp_time);
476 GETSYSCTL("vm.loadavg", sysload);
477 GETSYSCTL("kern.lastpid", lastpid);
479 /* convert load averages to doubles */
480 for (i = 0; i < 3; i++)
481 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale;
483 /* convert cp_time counts to percentages */
484 for (i = j = 0; i <= maxid; i++) {
485 if ((cpumask & (1ul << i)) == 0)
487 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES],
488 &pcpu_cp_time[j * CPUSTATES],
489 &pcpu_cp_old[j * CPUSTATES],
490 &pcpu_cp_diff[j * CPUSTATES]);
493 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff);
495 /* sum memory & swap statistics */
497 static unsigned int swap_delay = 0;
498 static int swapavail = 0;
499 static int swapfree = 0;
500 static long bufspace = 0;
501 static uint64_t nspgsin, nspgsout;
503 GETSYSCTL("vfs.bufspace", bufspace);
504 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]);
505 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]);
506 GETSYSCTL("vm.stats.vm.v_laundry_count", memory_stats[2]);
507 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[3]);
508 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]);
509 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin);
510 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout);
511 /* convert memory stats to Kbytes */
512 memory_stats[0] = pagetok(memory_stats[0]);
513 memory_stats[1] = pagetok(memory_stats[1]);
514 memory_stats[2] = pagetok(memory_stats[2]);
515 memory_stats[3] = pagetok(memory_stats[3]);
516 memory_stats[4] = bufspace / 1024;
517 memory_stats[5] = pagetok(memory_stats[5]);
518 memory_stats[6] = -1;
526 /* compute differences between old and new swap statistic */
528 swap_stats[4] = pagetok(((nspgsin - swappgsin)));
529 swap_stats[5] = pagetok(((nspgsout - swappgsout)));
533 swappgsout = nspgsout;
535 /* call CPU heavy swapmode() only for changes */
536 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
537 swap_stats[3] = swapmode(&swapavail, &swapfree);
538 swap_stats[0] = swapavail;
539 swap_stats[1] = swapavail - swapfree;
540 swap_stats[2] = swapfree;
547 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat);
548 arc_stats[0] = arc_stat >> 10;
549 GETSYSCTL("vfs.zfs.mfu_size", arc_stat);
550 arc_stats[1] = arc_stat >> 10;
551 GETSYSCTL("vfs.zfs.mru_size", arc_stat);
552 arc_stats[2] = arc_stat >> 10;
553 GETSYSCTL("vfs.zfs.anon_size", arc_stat);
554 arc_stats[3] = arc_stat >> 10;
555 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat);
556 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2);
557 arc_stats[4] = (arc_stat + arc_stat2) >> 10;
558 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat);
559 arc_stats[5] = arc_stat >> 10;
563 GETSYSCTL("kstat.zfs.misc.arcstats.compressed_size", arc_stat);
564 carc_stats[0] = arc_stat >> 10;
565 carc_stats[2] = arc_stat >> 10; /* For ratio */
566 GETSYSCTL("kstat.zfs.misc.arcstats.uncompressed_size", arc_stat);
567 carc_stats[1] = arc_stat >> 10;
568 si->carc = carc_stats;
571 /* set arrays and strings */
573 si->cpustates = pcpu_cpu_states;
576 si->cpustates = cpu_states;
579 si->memory = memory_stats;
580 si->swap = swap_stats;
584 si->last_pid = lastpid;
590 * Print how long system has been up.
591 * (Found by looking getting "boottime" from the kernel)
594 mib[1] = KERN_BOOTTIME;
595 size = sizeof(boottime);
596 if (sysctl(mib, nitems(mib), &boottime, &size, NULL, 0) != -1 &&
597 boottime.tv_sec != 0) {
598 si->boottime = boottime;
600 si->boottime.tv_sec = -1;
604 #define NOPROC ((void *)-1)
607 * We need to compare data from the old process entry with the new
609 * To facilitate doing this quickly we stash a pointer in the kinfo_proc
610 * structure to cache the mapping. We also use a negative cache pointer
611 * of NOPROC to avoid duplicate lookups.
612 * XXX: this could be done when the actual processes are fetched, we do
613 * it here out of laziness.
615 static const struct kinfo_proc *
616 get_old_proc(struct kinfo_proc *pp)
618 const struct kinfo_proc * const *oldpp, *oldp;
621 * If this is the first fetch of the kinfo_procs then we don't have
622 * any previous entries.
624 if (previous_proc_count == 0)
626 /* negative cache? */
627 if (pp->ki_udata == NOPROC)
630 if (pp->ki_udata != NULL)
631 return (pp->ki_udata);
634 * 1) look up based on pid.
635 * 2) compare process start.
636 * If we fail here, then setup a negative cache entry, otherwise
639 oldpp = bsearch(&pp, previous_pref, previous_proc_count,
640 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid);
642 pp->ki_udata = NOPROC;
646 if (memcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) {
647 pp->ki_udata = NOPROC;
655 * Return the total amount of IO done in blocks in/out and faults.
656 * store the values individually in the pointers passed in.
659 get_io_stats(const struct kinfo_proc *pp, long *inp, long *oup, long *flp,
660 long *vcsw, long *ivcsw)
662 const struct kinfo_proc *oldp;
663 static struct kinfo_proc dummy;
666 oldp = get_old_proc(pp);
668 memset(&dummy, 0, sizeof(dummy));
671 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock;
672 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock;
673 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
674 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
675 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
677 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) +
678 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) +
679 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt);
684 * If there was a previous update, use the delta in ki_runtime over
685 * the previous interval to calculate pctcpu. Otherwise, fall back
686 * to using the kernel's ki_pctcpu.
689 proc_calc_pctcpu(struct kinfo_proc *pp)
691 const struct kinfo_proc *oldp;
693 if (previous_interval != 0) {
694 oldp = get_old_proc(pp);
696 return ((double)(pp->ki_runtime - oldp->ki_runtime)
697 / previous_interval);
700 * If this process/thread was created during the previous
701 * interval, charge it's total runtime to the previous
704 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec ||
705 (pp->ki_start.tv_sec == previous_wall_time.tv_sec &&
706 pp->ki_start.tv_usec >= previous_wall_time.tv_usec))
707 return ((double)pp->ki_runtime / previous_interval);
709 return (pctdouble(pp->ki_pctcpu));
713 * Return true if this process has used any CPU time since the
717 proc_used_cpu(struct kinfo_proc *pp)
719 const struct kinfo_proc *oldp;
721 oldp = get_old_proc(pp);
723 return (PCTCPU(pp) != 0);
724 return (pp->ki_runtime != oldp->ki_runtime ||
725 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw ||
726 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw);
730 * Return the total number of block in/out and faults by a process.
733 get_io_total(const struct kinfo_proc *pp)
737 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy));
740 static struct handle handle;
743 get_process_info(struct system_info *si, struct process_select *sel,
744 int (*compare)(const void *, const void *))
749 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw;
752 struct kinfo_proc **prefp;
753 struct kinfo_proc *pp;
754 struct timespec previous_proc_uptime;
757 * If thread state was toggled, don't cache the previous processes.
759 if (previous_thread != sel->thread)
761 previous_thread = sel->thread;
764 * Save the previous process info.
766 if (previous_proc_count_max < nproc) {
767 free(previous_procs);
768 previous_procs = calloc(nproc, sizeof(*previous_procs));
770 previous_pref = calloc(nproc, sizeof(*previous_pref));
771 if (previous_procs == NULL || previous_pref == NULL) {
772 fprintf(stderr, "top: Out of memory.\n");
773 quit(TOP_EX_SYS_ERROR);
775 previous_proc_count_max = nproc;
778 for (i = 0; i < nproc; i++)
779 previous_pref[i] = &previous_procs[i];
780 memcpy(previous_procs, pbase, nproc * sizeof(*previous_procs));
781 qsort(previous_pref, nproc, sizeof(*previous_pref),
782 ps.thread ? compare_tid : compare_pid);
784 previous_proc_count = nproc;
785 previous_proc_uptime = proc_uptime;
786 previous_wall_time = proc_wall_time;
787 previous_interval = 0;
789 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC,
791 gettimeofday(&proc_wall_time, NULL);
792 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0)
793 memset(&proc_uptime, 0, sizeof(proc_uptime));
794 else if (previous_proc_uptime.tv_sec != 0 &&
795 previous_proc_uptime.tv_nsec != 0) {
796 previous_interval = (proc_uptime.tv_sec -
797 previous_proc_uptime.tv_sec) * 1000000;
798 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec;
800 previous_interval -= 1000000;
803 previous_interval += nsec / 1000;
805 if (nproc > onproc) {
806 pref = realloc(pref, sizeof(*pref) * nproc);
807 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc);
810 if (pref == NULL || pbase == NULL || pcpu == NULL) {
811 fprintf(stderr, "top: Out of memory.\n");
812 quit(TOP_EX_SYS_ERROR);
814 /* get a pointer to the states summary array */
815 si->procstates = process_states;
817 /* count up process states and get pointers to interesting procs */
823 memset(process_states, 0, sizeof(process_states));
825 for (pp = pbase, i = 0; i < nproc; pp++, i++) {
827 if (pp->ki_stat == 0)
831 if (!sel->self && pp->ki_pid == mypid)
835 if (!sel->system && (pp->ki_flag & P_SYSTEM))
836 /* skip system process */
839 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt,
841 total_inblock += p_inblock;
842 total_oublock += p_oublock;
843 total_majflt += p_majflt;
845 process_states[(unsigned char)pp->ki_stat]++;
847 if (pp->ki_stat == SZOMB)
851 if (!sel->kidle && pp->ki_tdflags & TDF_IDLETD)
852 /* skip kernel idle process */
855 PCTCPU(pp) = proc_calc_pctcpu(pp);
856 if (sel->thread && PCTCPU(pp) > 1.0)
858 if (displaymode == DISP_CPU && !sel->idle &&
859 (!proc_used_cpu(pp) ||
860 pp->ki_stat == SSTOP || pp->ki_stat == SIDL))
861 /* skip idle or non-running processes */
864 if (displaymode == DISP_IO && !sel->idle && p_io == 0)
865 /* skip processes that aren't doing I/O */
868 if (sel->jid != -1 && pp->ki_jid != sel->jid)
869 /* skip proc. that don't belong to the selected JID */
872 if (sel->uid[0] != -1 && !find_uid(pp->ki_ruid, sel->uid))
873 /* skip proc. that don't belong to the selected UID */
876 if (sel->pid != -1 && pp->ki_pid != sel->pid)
883 /* if requested, sort the "interesting" processes */
885 qsort(pref, active_procs, sizeof(*pref), compare);
887 /* remember active and total counts */
888 si->p_total = total_procs;
889 si->p_pactive = pref_len = active_procs;
891 /* pass back a handle */
892 handle.next_proc = pref;
893 handle.remaining = active_procs;
897 static char fmt[512]; /* static area where result is built */
900 format_next_process(void* xhandle, char *(*get_userid)(int), int flags)
902 struct kinfo_proc *pp;
903 const struct kinfo_proc *oldp;
910 struct rusage ru, *rup;
912 const char *proc_fmt;
914 char jid_buf[TOP_JID_LEN + 1], swap_buf[TOP_SWAP_LEN + 1];
917 const int cmdlen = 128;
919 /* find and remember the next proc structure */
920 hp = (struct handle *)xhandle;
921 pp = *(hp->next_proc++);
924 /* get the process's command name */
925 if ((pp->ki_flag & P_INMEM) == 0) {
927 * Print swapped processes as <pname>
931 len = strlen(pp->ki_comm);
932 if (len > sizeof(pp->ki_comm) - 3)
933 len = sizeof(pp->ki_comm) - 3;
934 memmove(pp->ki_comm + 1, pp->ki_comm, len);
935 pp->ki_comm[0] = '<';
936 pp->ki_comm[len + 1] = '>';
937 pp->ki_comm[len + 2] = '\0';
941 * Convert the process's runtime from microseconds to seconds. This
942 * time includes the interrupt time although that is not wanted here.
943 * ps(1) is similarly sloppy.
945 cputime = (pp->ki_runtime + 500000) / 1000000;
947 /* calculate the base for cpu percentages */
950 /* generate "STATE" field */
951 switch (state = pp->ki_stat) {
953 if (smpmode && pp->ki_oncpu != NOCPU)
954 sprintf(status, "CPU%d", pp->ki_oncpu);
956 strcpy(status, "RUN");
959 if (pp->ki_kiflag & KI_LOCKBLOCK) {
960 sprintf(status, "*%.6s", pp->ki_lockname);
965 sprintf(status, "%.6s", pp->ki_wmesg);
969 if (state < nitems(state_abbrev)) {
970 sprintf(status, "%.6s", state_abbrev[state]);
972 sprintf(status, "?%5zu", state);
977 cmdbuf = calloc(cmdlen + 1, 1);
978 if (cmdbuf == NULL) {
979 warn("calloc(%d)", cmdlen + 1);
983 if (!(flags & FMT_SHOWARGS)) {
984 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
986 snprintf(cmdbuf, cmdlen, "%s{%s%s}", pp->ki_comm,
987 pp->ki_tdname, pp->ki_moretdname);
989 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm);
992 if (pp->ki_flag & P_SYSTEM ||
993 pp->ki_args == NULL ||
994 (args = kvm_getargv(kd, pp, cmdlen)) == NULL ||
996 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
998 snprintf(cmdbuf, cmdlen,
999 "[%s{%s%s}]", pp->ki_comm, pp->ki_tdname,
1002 snprintf(cmdbuf, cmdlen,
1003 "[%s]", pp->ki_comm);
1012 argbuflen = cmdlen * 4;
1013 argbuf = calloc(argbuflen + 1, 1);
1014 if (argbuf == NULL) {
1015 warn("calloc(%zu)", argbuflen + 1);
1022 /* Extract cmd name from argv */
1023 cmd = strrchr(*args, '/');
1029 for (; (src = *args++) != NULL; ) {
1032 len = (argbuflen - (dst - argbuf) - 1) / 4;
1034 MIN(strlen(src), len),
1035 VIS_NL | VIS_CSTYLE);
1036 while (*dst != '\0')
1038 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0)
1039 *dst++ = ' '; /* add delimiting space */
1041 if (dst != argbuf && dst[-1] == ' ')
1045 if (strcmp(cmd, pp->ki_comm) != 0) {
1046 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1048 snprintf(cmdbuf, cmdlen,
1049 "%s (%s){%s%s}", argbuf,
1050 pp->ki_comm, pp->ki_tdname,
1053 snprintf(cmdbuf, cmdlen,
1054 "%s (%s)", argbuf, pp->ki_comm);
1056 if (ps.thread && pp->ki_flag & P_HADTHREADS &&
1058 snprintf(cmdbuf, cmdlen,
1059 "%s{%s%s}", argbuf, pp->ki_tdname,
1062 strlcpy(cmdbuf, argbuf, cmdlen);
1071 snprintf(jid_buf, sizeof(jid_buf), "%*d",
1072 jidlength - 1, pp->ki_jid);
1077 snprintf(swap_buf, sizeof(swap_buf), "%*s",
1079 format_k2(pagetok(ki_swap(pp)))); /* XXX */
1081 if (displaymode == DISP_IO) {
1082 oldp = get_old_proc(pp);
1084 ru.ru_inblock = RU(pp)->ru_inblock -
1085 RU(oldp)->ru_inblock;
1086 ru.ru_oublock = RU(pp)->ru_oublock -
1087 RU(oldp)->ru_oublock;
1088 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt;
1089 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw;
1090 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw;
1095 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt;
1096 s_tot = total_inblock + total_oublock + total_majflt;
1098 snprintf(fmt, sizeof(fmt), io_Proc_format,
1101 namelength, namelength, (*get_userid)(pp->ki_ruid),
1108 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot),
1109 screen_width > cmdlengthdelta ?
1110 screen_width - cmdlengthdelta : 0,
1118 /* format this entry */
1120 if (state == SRUN && pp->ki_oncpu != NOCPU)
1123 cpu = pp->ki_lastcpu;
1126 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format;
1130 snprintf(thr_buf, sizeof(thr_buf), "%*d ",
1131 (int)(sizeof(thr_buf) - 2), pp->ki_numthreads);
1133 snprintf(fmt, sizeof(fmt), proc_fmt,
1134 (ps.thread) ? pp->ki_tid : pp->ki_pid,
1136 namelength, namelength, (*get_userid)(pp->ki_ruid),
1138 pp->ki_pri.pri_level - PZERO,
1140 format_k2(PROCSIZE(pp)),
1141 format_k2(pagetok(pp->ki_rssize)),
1142 swaplength, swaplength, swap_buf,
1145 format_time(cputime),
1146 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct,
1147 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0,
1152 /* return the result */
1157 getsysctl(const char *name, void *ptr, size_t len)
1161 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1162 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name,
1164 quit(TOP_EX_SYS_ERROR);
1167 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n",
1168 name, (unsigned long)len, (unsigned long)nlen);
1169 quit(TOP_EX_SYS_ERROR);
1174 format_nice(const struct kinfo_proc *pp)
1176 const char *fifo, *kproc;
1178 static char nicebuf[4 + 1];
1180 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F";
1181 kproc = (pp->ki_flag & P_KPROC) ? "k" : "";
1182 switch (PRI_BASE(pp->ki_pri.pri_class)) {
1187 * XXX: the kernel doesn't tell us the original rtprio and
1188 * doesn't really know what it was, so to recover it we
1189 * must be more chummy with the implementation than the
1190 * implementation is with itself. pri_user gives a
1191 * constant "base" priority, but is only initialized
1192 * properly for user threads. pri_native gives what the
1193 * kernel calls the "base" priority, but it isn't constant
1194 * since it is changed by priority propagation. pri_native
1195 * also isn't properly initialized for all threads, but it
1196 * is properly initialized for kernel realtime and idletime
1197 * threads. Thus we use pri_user for the base priority of
1198 * user threads (it is always correct) and pri_native for
1199 * the base priority of kernel realtime and idletime threads
1200 * (there is nothing better, and it is usually correct).
1202 * The field width and thus the buffer are too small for
1203 * values like "kr31F", but such values shouldn't occur,
1204 * and if they do then the tailing "F" is not displayed.
1206 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1207 pp->ki_pri.pri_user) - PRI_MIN_REALTIME;
1208 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s",
1209 kproc, rtpri, fifo);
1212 if (pp->ki_flag & P_KPROC)
1214 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO);
1217 /* XXX: as above. */
1218 rtpri = ((pp->ki_flag & P_KPROC) ? pp->ki_pri.pri_native :
1219 pp->ki_pri.pri_user) - PRI_MIN_IDLE;
1220 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s",
1221 kproc, rtpri, fifo);
1229 /* comparison routines for qsort */
1232 compare_pid(const void *p1, const void *p2)
1234 const struct kinfo_proc * const *pp1 = p1;
1235 const struct kinfo_proc * const *pp2 = p2;
1237 assert((*pp2)->ki_pid >= 0 && (*pp1)->ki_pid >= 0);
1239 return ((*pp1)->ki_pid - (*pp2)->ki_pid);
1243 compare_tid(const void *p1, const void *p2)
1245 const struct kinfo_proc * const *pp1 = p1;
1246 const struct kinfo_proc * const *pp2 = p2;
1248 assert((*pp2)->ki_tid >= 0 && (*pp1)->ki_tid >= 0);
1250 return ((*pp1)->ki_tid - (*pp2)->ki_tid);
1254 * proc_compare - comparison function for "qsort"
1255 * Compares the resource consumption of two processes using five
1256 * distinct keys. The keys (in descending order of importance) are:
1257 * percent cpu, cpu ticks, state, resident set size, total virtual
1258 * memory usage. The process states are ordered as follows (from least
1259 * to most important): WAIT, zombie, sleep, stop, start, run. The
1260 * array declaration below maps a process state index into a number
1261 * that reflects this ordering.
1264 static int sorted_state[] = {
1267 1, /* ABANDONED (WAIT) */
1275 #define ORDERKEY_PCTCPU(a, b) do { \
1278 diff = weighted_cpu(PCTCPU((b)), (b)) - \
1279 weighted_cpu(PCTCPU((a)), (a)); \
1281 diff = PCTCPU((b)) - PCTCPU((a)); \
1283 return (diff > 0 ? 1 : -1); \
1286 #define ORDERKEY_CPTICKS(a, b) do { \
1287 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \
1289 return (diff > 0 ? 1 : -1); \
1292 #define ORDERKEY_STATE(a, b) do { \
1293 int diff = sorted_state[(unsigned char)(b)->ki_stat] - sorted_state[(unsigned char)(a)->ki_stat]; \
1295 return (diff > 0 ? 1 : -1); \
1298 #define ORDERKEY_PRIO(a, b) do { \
1299 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \
1301 return (diff > 0 ? 1 : -1); \
1304 #define ORDERKEY_THREADS(a, b) do { \
1305 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \
1307 return (diff > 0 ? 1 : -1); \
1310 #define ORDERKEY_RSSIZE(a, b) do { \
1311 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \
1313 return (diff > 0 ? 1 : -1); \
1316 #define ORDERKEY_MEM(a, b) do { \
1317 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \
1319 return (diff > 0 ? 1 : -1); \
1322 #define ORDERKEY_JID(a, b) do { \
1323 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \
1325 return (diff > 0 ? 1 : -1); \
1328 #define ORDERKEY_SWAP(a, b) do { \
1329 int diff = (int)ki_swap(b) - (int)ki_swap(a); \
1331 return (diff > 0 ? 1 : -1); \
1334 /* compare_cpu - the comparison function for sorting by cpu percentage */
1337 compare_cpu(const void *arg1, const void *arg2)
1339 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1340 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1342 ORDERKEY_PCTCPU(p1, p2);
1343 ORDERKEY_CPTICKS(p1, p2);
1344 ORDERKEY_STATE(p1, p2);
1345 ORDERKEY_PRIO(p1, p2);
1346 ORDERKEY_RSSIZE(p1, p2);
1347 ORDERKEY_MEM(p1, p2);
1352 /* compare_size - the comparison function for sorting by total memory usage */
1355 compare_size(const void *arg1, const void *arg2)
1357 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1358 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1360 ORDERKEY_MEM(p1, p2);
1361 ORDERKEY_RSSIZE(p1, p2);
1362 ORDERKEY_PCTCPU(p1, p2);
1363 ORDERKEY_CPTICKS(p1, p2);
1364 ORDERKEY_STATE(p1, p2);
1365 ORDERKEY_PRIO(p1, p2);
1370 /* compare_res - the comparison function for sorting by resident set size */
1373 compare_res(const void *arg1, const void *arg2)
1375 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1376 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1378 ORDERKEY_RSSIZE(p1, p2);
1379 ORDERKEY_MEM(p1, p2);
1380 ORDERKEY_PCTCPU(p1, p2);
1381 ORDERKEY_CPTICKS(p1, p2);
1382 ORDERKEY_STATE(p1, p2);
1383 ORDERKEY_PRIO(p1, p2);
1388 /* compare_time - the comparison function for sorting by total cpu time */
1391 compare_time(const void *arg1, const void *arg2)
1393 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1394 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *) arg2;
1396 ORDERKEY_CPTICKS(p1, p2);
1397 ORDERKEY_PCTCPU(p1, p2);
1398 ORDERKEY_STATE(p1, p2);
1399 ORDERKEY_PRIO(p1, p2);
1400 ORDERKEY_RSSIZE(p1, p2);
1401 ORDERKEY_MEM(p1, p2);
1406 /* compare_prio - the comparison function for sorting by priority */
1409 compare_prio(const void *arg1, const void *arg2)
1411 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1412 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1414 ORDERKEY_PRIO(p1, p2);
1415 ORDERKEY_CPTICKS(p1, p2);
1416 ORDERKEY_PCTCPU(p1, p2);
1417 ORDERKEY_STATE(p1, p2);
1418 ORDERKEY_RSSIZE(p1, p2);
1419 ORDERKEY_MEM(p1, p2);
1424 /* compare_threads - the comparison function for sorting by threads */
1426 compare_threads(const void *arg1, const void *arg2)
1428 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1429 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1431 ORDERKEY_THREADS(p1, p2);
1432 ORDERKEY_PCTCPU(p1, p2);
1433 ORDERKEY_CPTICKS(p1, p2);
1434 ORDERKEY_STATE(p1, p2);
1435 ORDERKEY_PRIO(p1, p2);
1436 ORDERKEY_RSSIZE(p1, p2);
1437 ORDERKEY_MEM(p1, p2);
1442 /* compare_jid - the comparison function for sorting by jid */
1444 compare_jid(const void *arg1, const void *arg2)
1446 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1447 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1449 ORDERKEY_JID(p1, p2);
1450 ORDERKEY_PCTCPU(p1, p2);
1451 ORDERKEY_CPTICKS(p1, p2);
1452 ORDERKEY_STATE(p1, p2);
1453 ORDERKEY_PRIO(p1, p2);
1454 ORDERKEY_RSSIZE(p1, p2);
1455 ORDERKEY_MEM(p1, p2);
1460 /* compare_swap - the comparison function for sorting by swap */
1462 compare_swap(const void *arg1, const void *arg2)
1464 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1465 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1467 ORDERKEY_SWAP(p1, p2);
1468 ORDERKEY_PCTCPU(p1, p2);
1469 ORDERKEY_CPTICKS(p1, p2);
1470 ORDERKEY_STATE(p1, p2);
1471 ORDERKEY_PRIO(p1, p2);
1472 ORDERKEY_RSSIZE(p1, p2);
1473 ORDERKEY_MEM(p1, p2);
1478 /* assorted comparison functions for sorting by i/o */
1481 compare_iototal(const void *arg1, const void *arg2)
1483 const struct kinfo_proc * const p1 = *(const struct kinfo_proc * const *)arg1;
1484 const struct kinfo_proc * const p2 = *(const struct kinfo_proc * const *)arg2;
1486 return (get_io_total(p2) - get_io_total(p1));
1490 compare_ioread(const void *arg1, const void *arg2)
1492 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1493 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1494 long dummy, inp1, inp2;
1496 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy);
1497 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy);
1499 return (inp2 - inp1);
1503 compare_iowrite(const void *arg1, const void *arg2)
1505 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1506 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1507 long dummy, oup1, oup2;
1509 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy);
1510 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy);
1512 return (oup2 - oup1);
1516 compare_iofault(const void *arg1, const void *arg2)
1518 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1519 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1520 long dummy, flp1, flp2;
1522 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy);
1523 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy);
1525 return (flp2 - flp1);
1529 compare_vcsw(const void *arg1, const void *arg2)
1531 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1532 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1533 long dummy, flp1, flp2;
1535 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy);
1536 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy);
1538 return (flp2 - flp1);
1542 compare_ivcsw(const void *arg1, const void *arg2)
1544 const struct kinfo_proc *p1 = *(const struct kinfo_proc * const *)arg1;
1545 const struct kinfo_proc *p2 = *(const struct kinfo_proc * const *)arg2;
1546 long dummy, flp1, flp2;
1548 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1);
1549 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2);
1551 return (flp2 - flp1);
1554 int (*compares[])(const void *arg1, const void *arg2) = {
1574 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1575 * the process does not exist.
1582 struct kinfo_proc **prefp;
1583 struct kinfo_proc *pp;
1587 while (--cnt >= 0) {
1589 if (pp->ki_pid == (pid_t)pid)
1590 return ((int)pp->ki_ruid);
1596 swapmode(int *retavail, int *retfree)
1599 struct kvm_swap swapary[1];
1600 static int pagesize = 0;
1601 static unsigned long swap_maxpages = 0;
1606 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
1608 n = kvm_getswapinfo(kd, swapary, 1, 0);
1609 if (n < 0 || swapary[0].ksw_total == 0)
1613 pagesize = getpagesize();
1614 if (swap_maxpages == 0)
1615 GETSYSCTL("vm.swap_maxpages", swap_maxpages);
1617 /* ksw_total contains the total size of swap all devices which may
1618 exceed the maximum swap size allocatable in the system */
1619 if ( swapary[0].ksw_total > swap_maxpages )
1620 swapary[0].ksw_total = swap_maxpages;
1622 *retavail = CONVERT(swapary[0].ksw_total);
1623 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
1625 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total);