*
* This is written specifically for the linux /proc/<PID>/stat(m)
* files format.
-
+ *
* This reads the PIDs of all processes and their status and shows
* the status of processes (first ones that fit to screen) at given
* intervals.
* (C) Eero Tamminen <oak at welho dot com>
*
* Rewritten by Vladimir Oleynik (C) 2002 <dzo@simtreas.ru>
- */
-
-/* Original code Copyrights */
-/*
+ *
+ * Sept 2008: Vineet Gupta <vineet.gupta@arc.com>
+ * Added Support for reporting SMP Information
+ * - CPU where Process was last seen running
+ * (to see effect of sched_setaffinity() etc)
+ * - CPU Time Split (idle/IO/wait etc) PER CPU
+ *
* Copyright (c) 1992 Branko Lankester
* Copyright (c) 1992 Roger Binns
* Copyright (C) 1994-1996 Charles L. Blake.
* Copyright (C) 1992-1998 Michael K. Johnson
- * May be distributed under the conditions of the
- * GNU Library General Public License
+ *
+ * Licensed under GPLv2, see file LICENSE in this tarball for details.
*/
#include "libbb.h"
unsigned uid;
char state[4];
char comm[COMM_LEN];
+#if ENABLE_FEATURE_TOP_SMP_PROCESS
+ int last_seen_on_cpu;
+#endif
} top_status_t;
typedef struct jiffy_counts_t {
- unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
+ /* Linux 2.4.x has only first four */
+ unsigned long long usr, nic, sys, idle;
+ unsigned long long iowait, irq, softirq, steal;
unsigned long long total;
unsigned long long busy;
} jiffy_counts_t;
the next. Used for finding deltas. */
typedef struct save_hist {
unsigned long ticks;
- unsigned pid;
+ pid_t pid;
} save_hist;
typedef int (*cmp_funcp)(top_status_t *P, top_status_t *Q);
smallint sort_field;
smallint inverted;
#endif
+#if ENABLE_FEATURE_TOP_SMP_CPU
+ smallint smp_cpu_info; /* one/many cpu info lines? */
+#endif
#if ENABLE_FEATURE_USE_TERMIOS
struct termios initial_settings;
#endif
cmp_funcp sort_function[SORT_DEPTH];
struct save_hist *prev_hist;
int prev_hist_count;
- jiffy_counts_t jif, prev_jif;
+ jiffy_counts_t cur_jif, prev_jif;
/* int hist_iterations; */
unsigned total_pcpu;
/* unsigned long total_vsz; */
#endif
+#if ENABLE_FEATURE_TOP_SMP_CPU
+ /* Per CPU samples: current and last */
+ jiffy_counts_t *cpu_jif, *cpu_prev_jif;
+ int num_cpus;
+#endif
+ char line_buf[80];
};
+
+enum { LINE_BUF_SIZE = COMMON_BUFSIZE - offsetof(struct globals, line_buf) };
+
#define G (*(struct globals*)&bb_common_bufsiz1)
-#define INIT_G() \
- do { \
- struct G_sizecheck { \
- char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
- }; \
- } while (0)
+#define INIT_G() do { \
+ struct G_sizecheck { \
+ char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
+ }; \
+} while (0)
#define top (G.top )
#define ntop (G.ntop )
#define sort_field (G.sort_field )
#define inverted (G.inverted )
+#define smp_cpu_info (G.smp_cpu_info )
#define initial_settings (G.initial_settings )
#define sort_function (G.sort_function )
#define prev_hist (G.prev_hist )
#define prev_hist_count (G.prev_hist_count )
-#define jif (G.jif )
+#define cur_jif (G.cur_jif )
#define prev_jif (G.prev_jif )
+#define cpu_jif (G.cpu_jif )
+#define cpu_prev_jif (G.cpu_prev_jif )
+#define num_cpus (G.num_cpus )
#define total_pcpu (G.total_pcpu )
+#define line_buf (G.line_buf )
-
-#define OPT_BATCH_MODE (option_mask32 & 0x4)
+enum {
+ OPT_d = (1 << 0),
+ OPT_n = (1 << 1),
+ OPT_b = (1 << 2),
+ OPT_EOF = (1 << 3), /* pseudo: "we saw EOF in stdin" */
+};
+#define OPT_BATCH_MODE (option_mask32 & OPT_b)
#if ENABLE_FEATURE_USE_TERMIOS
return 0;
}
+static NOINLINE int read_cpu_jiffy(FILE *fp, jiffy_counts_t *p_jif)
+{
+#if !ENABLE_FEATURE_TOP_SMP_CPU
+ static const char fmt[] = "cpu %llu %llu %llu %llu %llu %llu %llu %llu";
+#else
+ static const char fmt[] = "cp%*s %llu %llu %llu %llu %llu %llu %llu %llu";
+#endif
+ int ret;
+
+ if (!fgets(line_buf, LINE_BUF_SIZE, fp) || line_buf[0] != 'c' /* not "cpu" */)
+ return 0;
+ ret = sscanf(line_buf, fmt,
+ &p_jif->usr, &p_jif->nic, &p_jif->sys, &p_jif->idle,
+ &p_jif->iowait, &p_jif->irq, &p_jif->softirq,
+ &p_jif->steal);
+ if (ret >= 4) {
+ p_jif->total = p_jif->usr + p_jif->nic + p_jif->sys + p_jif->idle
+ + p_jif->iowait + p_jif->irq + p_jif->softirq + p_jif->steal;
+ /* procps 2.x does not count iowait as busy time */
+ p_jif->busy = p_jif->total - p_jif->idle - p_jif->iowait;
+ }
+
+ return ret;
+}
static void get_jiffy_counts(void)
{
- FILE* fp = xfopen("stat", "r");
- prev_jif = jif;
- if (fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
- &jif.usr,&jif.nic,&jif.sys,&jif.idle,
- &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
- bb_error_msg_and_die("failed to read /proc/stat");
+ FILE* fp = xfopen_for_read("stat");
+
+ /* We need to parse cumulative counts even if SMP CPU display is on,
+ * they are used to calculate per process CPU% */
+ prev_jif = cur_jif;
+ if (read_cpu_jiffy(fp, &cur_jif) < 4)
+ bb_error_msg_and_die("can't read /proc/stat");
+
+#if !ENABLE_FEATURE_TOP_SMP_CPU
+ fclose(fp);
+ return;
+#else
+ if (!smp_cpu_info) {
+ fclose(fp);
+ return;
}
+
+ if (!num_cpus) {
+ /* First time here. How many CPUs?
+ * There will be at least 1 /proc/stat line with cpu%d
+ */
+ while (1) {
+ cpu_jif = xrealloc_vector(cpu_jif, 1, num_cpus);
+ if (read_cpu_jiffy(fp, &cpu_jif[num_cpus]) <= 4)
+ break;
+ num_cpus++;
+ }
+ if (num_cpus == 0) /* /proc/stat with only "cpu ..." line?! */
+ smp_cpu_info = 0;
+
+ cpu_prev_jif = xzalloc(sizeof(cpu_prev_jif[0]) * num_cpus);
+
+ /* Otherwise the first per cpu display shows all 100% idles */
+ usleep(50000);
+ } else { /* Non first time invocation */
+ jiffy_counts_t *tmp;
+ int i;
+
+ /* First switch the sample pointers: no need to copy */
+ tmp = cpu_prev_jif;
+ cpu_prev_jif = cpu_jif;
+ cpu_jif = tmp;
+
+ /* Get the new samples */
+ for (i = 0; i < num_cpus; i++)
+ read_cpu_jiffy(fp, &cpu_jif[i]);
+ }
+#endif
fclose(fp);
- jif.total = jif.usr + jif.nic + jif.sys + jif.idle
- + jif.iowait + jif.irq + jif.softirq + jif.steal;
- /* procps 2.x does not count iowait as busy time */
- jif.busy = jif.total - jif.idle - jif.iowait;
}
-
static void do_stats(void)
{
top_status_t *cur;
get_jiffy_counts();
total_pcpu = 0;
/* total_vsz = 0; */
- new_hist = xmalloc(sizeof(struct save_hist)*ntop);
+ new_hist = xmalloc(sizeof(new_hist[0]) * ntop);
/*
* Make a pass through the data to get stats.
*/
prev_hist = new_hist;
prev_hist_count = ntop;
}
+
#endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
#if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && ENABLE_FEATURE_TOP_DECIMALS
}
#endif
-static unsigned long display_header(int scr_width)
+#if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
+static void display_cpus(int scr_width, char *scrbuf, int *lines_rem_p)
+{
+ /*
+ * xxx% = (cur_jif.xxx - prev_jif.xxx) / (cur_jif.total - prev_jif.total) * 100%
+ */
+ unsigned total_diff;
+ jiffy_counts_t *p_jif, *p_prev_jif;
+ int i;
+
+#if ENABLE_FEATURE_TOP_SMP_CPU
+ int n_cpu_lines;
+#endif
+
+ /* using (unsigned) casts to make operations cheaper */
+#define CALC_TOT_DIFF ((unsigned)(p_jif->total - p_prev_jif->total) ? : 1)
+
+#if ENABLE_FEATURE_TOP_DECIMALS
+#define CALC_STAT(xxx) char xxx[8]
+#define SHOW_STAT(xxx) fmt_100percent_8(xxx, (unsigned)(p_jif->xxx - p_prev_jif->xxx), total_diff)
+#define FMT "%s"
+#else
+#define CALC_STAT(xxx) unsigned xxx = 100 * (unsigned)(p_jif->xxx - p_prev_jif->xxx) / total_diff
+#define SHOW_STAT(xxx) xxx
+#define FMT "%4u%% "
+#endif
+
+#if !ENABLE_FEATURE_TOP_SMP_CPU
+ {
+ i = 1;
+ p_jif = &cur_jif;
+ p_prev_jif = &prev_jif;
+#else
+ /* Loop thru CPU(s) */
+ n_cpu_lines = smp_cpu_info ? num_cpus : 1;
+ if (n_cpu_lines > *lines_rem_p)
+ n_cpu_lines = *lines_rem_p;
+
+ for (i = 0; i < n_cpu_lines; i++) {
+ p_jif = &cpu_jif[i];
+ p_prev_jif = &cpu_prev_jif[i];
+#endif
+ total_diff = CALC_TOT_DIFF;
+
+ { /* Need a block: CALC_STAT are declarations */
+ CALC_STAT(usr);
+ CALC_STAT(sys);
+ CALC_STAT(nic);
+ CALC_STAT(idle);
+ CALC_STAT(iowait);
+ CALC_STAT(irq);
+ CALC_STAT(softirq);
+ /*CALC_STAT(steal);*/
+
+ snprintf(scrbuf, scr_width,
+ /* Barely fits in 79 chars when in "decimals" mode. */
+#if ENABLE_FEATURE_TOP_SMP_CPU
+ "CPU%s:"FMT"usr"FMT"sys"FMT"nic"FMT"idle"FMT"io"FMT"irq"FMT"sirq",
+ (smp_cpu_info ? utoa(i) : ""),
+#else
+ "CPU:"FMT"usr"FMT"sys"FMT"nic"FMT"idle"FMT"io"FMT"irq"FMT"sirq",
+#endif
+ SHOW_STAT(usr), SHOW_STAT(sys), SHOW_STAT(nic), SHOW_STAT(idle),
+ SHOW_STAT(iowait), SHOW_STAT(irq), SHOW_STAT(softirq)
+ /*, SHOW_STAT(steal) - what is this 'steal' thing? */
+ /* I doubt anyone wants to know it */
+ );
+ puts(scrbuf);
+ }
+ }
+#undef SHOW_STAT
+#undef CALC_STAT
+#undef FMT
+ *lines_rem_p -= i;
+}
+#else /* !ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS */
+#define display_cpus(scr_width, scrbuf, lines_rem) ((void)0)
+#endif
+
+static unsigned long display_header(int scr_width, int *lines_rem_p)
{
FILE *fp;
char buf[80];
char scrbuf[80];
unsigned long total, used, mfree, shared, buffers, cached;
-#if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
- unsigned total_diff;
-#endif
/* read memory info */
- fp = xfopen("meminfo", "r");
+ fp = xfopen_for_read("meminfo");
/*
* Old kernels (such as 2.4.x) had a nice summary of memory info that
* sizes in kilobytes. This should be safe for both 2.4 and
* 2.6.
*/
-
fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
/*
fclose(fp);
/* output memory info */
- if (scr_width > sizeof(scrbuf))
+ if (scr_width > (int)sizeof(scrbuf))
scr_width = sizeof(scrbuf);
snprintf(scrbuf, scr_width,
"Mem: %luK used, %luK free, %luK shrd, %luK buff, %luK cached",
used, mfree, shared, buffers, cached);
/* clear screen & go to top */
printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
+ (*lines_rem_p)--;
-#if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
- /*
- * xxx% = (jif.xxx - prev_jif.xxx) / (jif.total - prev_jif.total) * 100%
+ /* Display CPU time split as percentage of total time
+ * This displays either a cumulative line or one line per CPU
*/
- /* using (unsigned) casts to make operations cheaper */
- total_diff = ((unsigned)(jif.total - prev_jif.total) ? : 1);
-#if ENABLE_FEATURE_TOP_DECIMALS
-/* Generated code is approx +0.3k */
-#define CALC_STAT(xxx) char xxx[8]
-#define SHOW_STAT(xxx) fmt_100percent_8(xxx, (unsigned)(jif.xxx - prev_jif.xxx), total_diff)
-#define FMT "%s"
-#else
-#define CALC_STAT(xxx) unsigned xxx = 100 * (unsigned)(jif.xxx - prev_jif.xxx) / total_diff
-#define SHOW_STAT(xxx) xxx
-#define FMT "%4u%% "
-#endif
- { /* need block: CALC_STAT are declarations */
- CALC_STAT(usr);
- CALC_STAT(sys);
- CALC_STAT(nic);
- CALC_STAT(idle);
- CALC_STAT(iowait);
- CALC_STAT(irq);
- CALC_STAT(softirq);
- //CALC_STAT(steal);
-
- snprintf(scrbuf, scr_width,
- /* Barely fits in 79 chars when in "decimals" mode. */
- "CPU:"FMT"usr"FMT"sys"FMT"nice"FMT"idle"FMT"io"FMT"irq"FMT"softirq",
- SHOW_STAT(usr), SHOW_STAT(sys), SHOW_STAT(nic), SHOW_STAT(idle),
- SHOW_STAT(iowait), SHOW_STAT(irq), SHOW_STAT(softirq)
- //, SHOW_STAT(steal) - what is this 'steal' thing?
- // I doubt anyone wants to know it
- );
- }
- puts(scrbuf);
-#undef SHOW_STAT
-#undef CALC_STAT
-#undef FMT
-#endif
+ display_cpus(scr_width, scrbuf, lines_rem_p);
/* read load average as a string */
buf[0] = '\0';
- open_read_close("loadavg", buf, sizeof("N.NN N.NN N.NN")-1);
- buf[sizeof("N.NN N.NN N.NN")-1] = '\0';
+ open_read_close("loadavg", buf, sizeof(buf) - 1);
+ buf[sizeof(buf) - 1] = '\n';
+ *strchr(buf, '\n') = '\0';
snprintf(scrbuf, scr_width, "Load average: %s", buf);
puts(scrbuf);
+ (*lines_rem_p)--;
return total;
}
-static void display_process_list(int count, int scr_width)
+static NOINLINE void display_process_list(int lines_rem, int scr_width)
{
enum {
- BITS_PER_INT = sizeof(int)*8
+ BITS_PER_INT = sizeof(int) * 8
};
- top_status_t *s = top;
+ top_status_t *s;
char vsz_str_buf[8];
- unsigned long total_memory = display_header(scr_width); /* or use total_vsz? */
+ unsigned long total_memory = display_header(scr_width, &lines_rem); /* or use total_vsz? */
/* xxx_shift and xxx_scale variables allow us to replace
* expensive divides with multiply and shift */
unsigned pmem_shift, pmem_scale, pmem_half;
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
unsigned pcpu_shift, pcpu_scale, pcpu_half;
unsigned busy_jifs;
+#endif
/* what info of the processes is shown */
printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
- " PID PPID USER STAT VSZ %MEM %CPU COMMAND");
-#else
-
- /* !CPU_USAGE_PERCENTAGE */
- printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
- " PID PPID USER STAT VSZ %MEM COMMAND");
+ " PID PPID USER STAT VSZ %MEM"
+#if ENABLE_FEATURE_TOP_SMP_PROCESS
+ " CPU"
#endif
+#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
+ " %CPU"
+#endif
+ " COMMAND");
+ lines_rem--;
#if ENABLE_FEATURE_TOP_DECIMALS
#define UPSCALE 1000
}
pmem_half = (1U << pmem_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
- busy_jifs = jif.busy - prev_jif.busy;
+ busy_jifs = cur_jif.busy - prev_jif.busy;
/* This happens if there were lots of short-lived processes
* between two top updates (e.g. compilation) */
if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
* CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
* (pcpu is delta of sys+user time between samples)
*/
- /* (jif.xxx - prev_jif.xxx) and s->pcpu are
+ /* (cur_jif.xxx - prev_jif.xxx) and s->pcpu are
* in 0..~64000 range (HZ*update_interval).
* we assume that unsigned is at least 32-bit.
*/
pcpu_shift = 6;
- pcpu_scale = (UPSCALE*64*(uint16_t)busy_jifs ? : 1);
- while (pcpu_scale < (1U<<(BITS_PER_INT-2))) {
+ pcpu_scale = (UPSCALE*64 * (uint16_t)busy_jifs ? : 1);
+ while (pcpu_scale < (1U << (BITS_PER_INT-2))) {
pcpu_scale *= 4;
pcpu_shift += 2;
}
- pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
+ pcpu_scale /= ( (uint16_t)(cur_jif.total - prev_jif.total) * total_pcpu ? : 1);
/* we want (s->pcpu * pcpu_scale) to never overflow */
while (pcpu_scale >= 1024) {
pcpu_scale /= 4;
/* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
#endif
+ /* Ok, all preliminary data is ready, go through the list */
scr_width += 2; /* account for leading '\n' and trailing NUL */
- /* Ok, all preliminary data is ready, go thru the list */
- while (count-- > 0) {
- char buf[scr_width];
+ if (lines_rem > ntop)
+ lines_rem = ntop;
+ s = top;
+ while (--lines_rem >= 0) {
unsigned col;
CALC_STAT(pmem, (s->vsz*pmem_scale + pmem_half) >> pmem_shift);
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
sprintf(vsz_str_buf, "%6ldm", s->vsz/1024);
else
sprintf(vsz_str_buf, "%7ld", s->vsz);
- // PID PPID USER STAT VSZ %MEM [%CPU] COMMAND
- col = snprintf(buf, scr_width,
+ /* PID PPID USER STAT VSZ %MEM [%CPU] COMMAND */
+ col = snprintf(line_buf, scr_width,
"\n" "%5u%6u %-8.8s %s%s" FMT
+#if ENABLE_FEATURE_TOP_SMP_PROCESS
+ " %3d"
+#endif
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
FMT
#endif
s->pid, s->ppid, get_cached_username(s->uid),
s->state, vsz_str_buf,
SHOW_STAT(pmem)
+#if ENABLE_FEATURE_TOP_SMP_PROCESS
+ , s->last_seen_on_cpu
+#endif
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
, SHOW_STAT(pcpu)
#endif
);
- if (col < scr_width)
- read_cmdline(buf + col, scr_width - col, s->pid, s->comm);
- fputs(buf, stdout);
+ if ((int)(col + 1) < scr_width)
+ read_cmdline(line_buf + col, scr_width - col - 1, s->pid, s->comm);
+ fputs(line_buf, stdout);
/* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
- jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
+ cur_jif.busy - prev_jif.busy, cur_jif.total - prev_jif.total); */
s++;
}
/* printf(" %d", hist_iterations); */
- putchar(OPT_BATCH_MODE ? '\n' : '\r');
+ bb_putchar(OPT_BATCH_MODE ? '\n' : '\r');
fflush(stdout);
}
#undef UPSCALE
}
#if ENABLE_FEATURE_USE_TERMIOS
-#include <termios.h>
-#include <signal.h>
static void reset_term(void)
{
- tcsetattr(0, TCSANOW, (void *) &initial_settings);
+ tcsetattr_stdin_TCSANOW(&initial_settings);
if (ENABLE_FEATURE_CLEAN_UP) {
clearmems();
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
}
}
-static void sig_catcher(int sig ATTRIBUTE_UNUSED)
+static void sig_catcher(int sig UNUSED_PARAM)
{
reset_term();
- exit(1);
+ exit(EXIT_FAILURE);
}
#endif /* FEATURE_USE_TERMIOS */
#define topmem ((topmem_status_t*)top)
#if ENABLE_FEATURE_TOPMEM
+
static int topmem_sort(char *a, char *b)
{
int n;
}
/* display header info (meminfo / loadavg) */
-static void display_topmem_header(int scr_width)
+static void display_topmem_header(int scr_width, int *lines_rem_p)
{
char linebuf[128];
- int i;
+ unsigned i;
FILE *fp;
union {
struct {
/* 9 */ char *anon;
/* 10 */ char *map;
/* 11 */ char *slab;
- };
+ } u;
char *str[11];
} Z;
-#define total Z.total
-#define mfree Z.mfree
-#define buf Z.buf
-#define cache Z.cache
-#define swaptotal Z.swaptotal
-#define swapfree Z.swapfree
-#define dirty Z.dirty
-#define mwrite Z.mwrite
-#define anon Z.anon
-#define map Z.map
-#define slab Z.slab
+#define total Z.u.total
+#define mfree Z.u.mfree
+#define buf Z.u.buf
+#define cache Z.u.cache
+#define swaptotal Z.u.swaptotal
+#define swapfree Z.u.swapfree
+#define dirty Z.u.dirty
+#define mwrite Z.u.mwrite
+#define anon Z.u.anon
+#define map Z.u.map
+#define slab Z.u.slab
#define str Z.str
memset(&Z, 0, sizeof(Z));
/* read memory info */
- fp = xfopen("meminfo", "r");
+ fp = xfopen_for_read("meminfo");
while (fgets(linebuf, sizeof(linebuf), fp)) {
char *p;
}
fclose(fp);
-#define S(s) (s ? s : "0")
+#define S(s) (s ? s : "0 ")
snprintf(linebuf, sizeof(linebuf),
"Mem %stotal %sanon %smap %sfree",
S(total), S(anon), S(map), S(mfree));
"Swap %stotal %sfree", // TODO: % used?
S(swaptotal), S(swapfree));
printf("%.*s\n", scr_width, linebuf);
+
+ (*lines_rem_p) -= 3;
#undef S
for (i = 0; i < ARRAY_SIZE(str); i++)
#undef str
}
-// Converts unsigned long long value into compact 5-char
-// representation. Sixth char is always ' '
-static void smart_ulltoa6(unsigned long long ul, char buf[6])
+static void ulltoa6_and_space(unsigned long long ul, char buf[6])
{
- const char *fmt;
- char c;
- unsigned v, u, idx = 0;
-
- if (ul > 99999) { // do not scale if 99999 or less
- ul *= 10;
- do {
- ul /= 1024;
- idx++;
- } while (ul >= 100000);
- }
- v = ul; // ullong divisions are expensive, avoid them
-
- fmt = " 123456789";
- u = v / 10;
- v = v % 10;
- if (!idx) {
- // 99999 or less: use "12345" format
- // u is value/10, v is last digit
- c = buf[0] = " 123456789"[u/1000];
- if (c != ' ') fmt = "0123456789";
- c = buf[1] = fmt[u/100%10];
- if (c != ' ') fmt = "0123456789";
- c = buf[2] = fmt[u/10%10];
- if (c != ' ') fmt = "0123456789";
- buf[3] = fmt[u%10];
- buf[4] = "0123456789"[v];
- } else {
- // value has been scaled into 0..9999.9 range
- // u is value, v is 1/10ths (allows for 92.1M format)
- if (u >= 100) {
- // value is >= 100: use "1234M', " 123M" formats
- c = buf[0] = " 123456789"[u/1000];
- if (c != ' ') fmt = "0123456789";
- c = buf[1] = fmt[u/100%10];
- if (c != ' ') fmt = "0123456789";
- v = u % 10;
- u = u / 10;
- buf[2] = fmt[u%10];
- } else {
- // value is < 100: use "92.1M" format
- c = buf[0] = " 123456789"[u/10];
- if (c != ' ') fmt = "0123456789";
- buf[1] = fmt[u%10];
- buf[2] = '.';
- }
- buf[3] = "0123456789"[v];
- // see http://en.wikipedia.org/wiki/Tera
- buf[4] = " mgtpezy"[idx];
- }
+ /* see http://en.wikipedia.org/wiki/Tera */
+ smart_ulltoa5(ul, buf, " mgtpezy");
buf[5] = ' ';
}
-static void display_topmem_process_list(int count, int scr_width)
+static NOINLINE void display_topmem_process_list(int lines_rem, int scr_width)
{
#define HDR_STR " PID VSZ VSZRW RSS (SHR) DIRTY (SHR) STACK"
#define MIN_WIDTH sizeof(HDR_STR)
const topmem_status_t *s = topmem;
- char buf[scr_width | MIN_WIDTH]; /* a|b is a cheap max(a,b) */
-
- display_topmem_header(scr_width);
- strcpy(buf, HDR_STR " COMMAND");
- buf[5 + sort_field * 6] = '*';
- printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width, buf);
-
- while (--count >= 0) {
- // PID VSZ VSZRW RSS (SHR) DIRTY (SHR) COMMAND
- smart_ulltoa6(s->pid , &buf[0*6]);
- smart_ulltoa6(s->vsz , &buf[1*6]);
- smart_ulltoa6(s->vszrw , &buf[2*6]);
- smart_ulltoa6(s->rss , &buf[3*6]);
- smart_ulltoa6(s->rss_sh , &buf[4*6]);
- smart_ulltoa6(s->dirty , &buf[5*6]);
- smart_ulltoa6(s->dirty_sh, &buf[6*6]);
- smart_ulltoa6(s->stack , &buf[7*6]);
- buf[8*6] = '\0';
- if (scr_width > MIN_WIDTH) {
- read_cmdline(&buf[8*6], scr_width - MIN_WIDTH, s->pid, s->comm);
+
+ display_topmem_header(scr_width, &lines_rem);
+ strcpy(line_buf, HDR_STR " COMMAND");
+ line_buf[5 + sort_field * 6] = '*';
+ printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width, line_buf);
+ lines_rem--;
+
+ if (lines_rem > ntop)
+ lines_rem = ntop;
+ while (--lines_rem >= 0) {
+ /* PID VSZ VSZRW RSS (SHR) DIRTY (SHR) COMMAND */
+ ulltoa6_and_space(s->pid , &line_buf[0*6]);
+ ulltoa6_and_space(s->vsz , &line_buf[1*6]);
+ ulltoa6_and_space(s->vszrw , &line_buf[2*6]);
+ ulltoa6_and_space(s->rss , &line_buf[3*6]);
+ ulltoa6_and_space(s->rss_sh , &line_buf[4*6]);
+ ulltoa6_and_space(s->dirty , &line_buf[5*6]);
+ ulltoa6_and_space(s->dirty_sh, &line_buf[6*6]);
+ ulltoa6_and_space(s->stack , &line_buf[7*6]);
+ line_buf[8*6] = '\0';
+ if (scr_width > (int)MIN_WIDTH) {
+ read_cmdline(&line_buf[8*6], scr_width - MIN_WIDTH, s->pid, s->comm);
}
- printf("\n""%.*s", scr_width, buf);
+ printf("\n""%.*s", scr_width, line_buf);
s++;
}
- putchar(OPT_BATCH_MODE ? '\n' : '\r');
+ bb_putchar(OPT_BATCH_MODE ? '\n' : '\r');
fflush(stdout);
#undef HDR_STR
#undef MIN_WIDTH
}
+
#else
-void display_topmem_process_list(int count, int scr_width);
+void display_topmem_process_list(int lines_rem, int scr_width);
int topmem_sort(char *a, char *b);
#endif /* TOPMEM */
| PSSCAN_UTIME
| PSSCAN_STATE
| PSSCAN_COMM
+ | PSSCAN_CPU
| PSSCAN_UIDGID,
TOPMEM_MASK = 0
| PSSCAN_PID
| PSSCAN_COMM,
};
-int top_main(int argc, char **argv);
-int top_main(int argc, char **argv)
+int top_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+int top_main(int argc UNUSED_PARAM, char **argv)
{
- int count, lines, col;
- unsigned interval;
int iterations;
- char *sinterval, *siterations;
- SKIP_FEATURE_TOPMEM(const) unsigned scan_mask = TOP_MASK;
+ unsigned lines, col;
+ int lines_rem;
+ unsigned interval;
+ char *str_interval, *str_iterations;
+ IF_NOT_FEATURE_TOPMEM(const) unsigned scan_mask = TOP_MASK;
#if ENABLE_FEATURE_USE_TERMIOS
struct termios new_settings;
struct pollfd pfd[1];
INIT_G();
- interval = 5; /* default update rate is 5 seconds */
+ interval = 5; /* default update interval is 5 seconds */
iterations = 0; /* infinite */
+#if ENABLE_FEATURE_TOP_SMP_CPU
+ /*num_cpus = 0;*/
+ /*smp_cpu_info = 0;*/ /* to start with show aggregate */
+ cpu_jif = &cur_jif;
+ cpu_prev_jif = &prev_jif;
+#endif
- /* do normal option parsing */
+ /* all args are options; -n NUM */
opt_complementary = "-";
- getopt32(argv, "d:n:b", &sinterval, &siterations);
- if (option_mask32 & 0x1) {
+ col = getopt32(argv, "d:n:b", &str_interval, &str_iterations);
+ if (col & OPT_d) {
+ /* work around for "-d 1" -> "-d -1" done by getopt32 */
+ if (str_interval[0] == '-')
+ str_interval++;
/* Need to limit it to not overflow poll timeout */
- interval = xatou16(sinterval); // -d
+ interval = xatou16(str_interval);
+ }
+ if (col & OPT_n) {
+ if (str_iterations[0] == '-')
+ str_iterations++;
+ iterations = xatou(str_iterations);
}
- if (option_mask32 & 0x2)
- iterations = xatoi_u(siterations); // -n
- //if (option_mask32 & 0x4) // -b
/* change to /proc */
xchdir("/proc");
/* unbuffered input, turn off echo */
new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
- signal(SIGTERM, sig_catcher);
- signal(SIGINT, sig_catcher);
- tcsetattr(0, TCSANOW, (void *) &new_settings);
- atexit(reset_term);
+ bb_signals(BB_FATAL_SIGS, sig_catcher);
+ tcsetattr_stdin_TCSANOW(&new_settings);
#endif /* FEATURE_USE_TERMIOS */
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
lines = 24; /* default */
col = 79;
#if ENABLE_FEATURE_USE_TERMIOS
- get_terminal_width_height(0, &col, &lines);
+ /* We output to stdout, we need size of stdout (not stdin)! */
+ get_terminal_width_height(STDOUT_FILENO, &col, &lines);
if (lines < 5 || col < 10) {
sleep(interval);
continue;
}
#endif /* FEATURE_USE_TERMIOS */
- if (!ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && scan_mask == TOP_MASK)
- lines -= 3;
- else
- lines -= 4;
+ if (col > LINE_BUF_SIZE-2) /* +2 bytes for '\n', NUL, */
+ col = LINE_BUF_SIZE-2;
/* read process IDs & status for all the processes */
while ((p = procps_scan(p, scan_mask)) != NULL) {
int n;
if (scan_mask == TOP_MASK) {
n = ntop;
- top = xrealloc(top, (++ntop) * sizeof(*top));
+ top = xrealloc_vector(top, 6, ntop++);
top[n].pid = p->pid;
top[n].ppid = p->ppid;
top[n].vsz = p->vsz;
top[n].uid = p->uid;
strcpy(top[n].state, p->state);
strcpy(top[n].comm, p->comm);
+#if ENABLE_FEATURE_TOP_SMP_PROCESS
+ top[n].last_seen_on_cpu = p->last_seen_on_cpu;
+#endif
} else { /* TOPMEM */
#if ENABLE_FEATURE_TOPMEM
if (!(p->mapped_ro | p->mapped_rw))
continue; /* kernel threads are ignored */
n = ntop;
- top = xrealloc(topmem, (++ntop) * sizeof(*topmem));
+ /* No bug here - top and topmem are the same */
+ top = xrealloc_vector(topmem, 6, ntop++);
strcpy(topmem[n].comm, p->comm);
topmem[n].pid = p->pid;
topmem[n].vsz = p->mapped_rw + p->mapped_ro;
topmem[n].stack = p->stack;
#endif
}
- }
+ } /* end of "while we read /proc" */
if (ntop == 0) {
- bb_error_msg_and_die("no process info in /proc");
+ bb_error_msg("no process info in /proc");
+ break;
}
if (scan_mask == TOP_MASK) {
continue;
}
do_stats();
-/* TODO: we don't need to sort all 10000 processes, we need to find top 24! */
+ /* TODO: we don't need to sort all 10000 processes, we need to find top 24! */
qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
#else
qsort(top, ntop, sizeof(top_status_t), (void*)(sort_function[0]));
#endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
- } else { /* TOPMEM */
+ }
+#if ENABLE_FEATURE_TOPMEM
+ else { /* TOPMEM */
qsort(topmem, ntop, sizeof(topmem_status_t), (void*)topmem_sort);
}
- count = lines;
- if (OPT_BATCH_MODE || count > ntop) {
- count = ntop;
+#endif
+ lines_rem = lines;
+ if (OPT_BATCH_MODE) {
+ lines_rem = INT_MAX;
}
if (scan_mask == TOP_MASK)
- display_process_list(count, col);
+ display_process_list(lines_rem, col);
+#if ENABLE_FEATURE_TOPMEM
else
- display_topmem_process_list(count, col);
+ display_topmem_process_list(lines_rem, col);
+#endif
clearmems();
if (iterations >= 0 && !--iterations)
break;
#if !ENABLE_FEATURE_USE_TERMIOS
sleep(interval);
#else
- if (poll(pfd, 1, interval * 1000) != 0) {
- if (read(0, &c, 1) != 1) /* signal */
- break;
+ if (option_mask32 & (OPT_b|OPT_EOF))
+ /* batch mode, or EOF on stdin ("top </dev/null") */
+ sleep(interval);
+ else if (safe_poll(pfd, 1, interval * 1000) > 0) {
+ if (safe_read(STDIN_FILENO, &c, 1) != 1) { /* error/EOF? */
+ option_mask32 |= OPT_EOF;
+ continue;
+ }
if (c == initial_settings.c_cc[VINTR])
break;
c |= 0x20; /* lowercase */
if (c == 'q')
break;
if (c == 'n') {
- USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
+ IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
sort_function[0] = pid_sort;
}
if (c == 'm') {
- USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
+ IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
sort_function[0] = mem_sort;
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
sort_function[1] = pcpu_sort;
}
#if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
if (c == 'p') {
- USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
+ IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
sort_function[0] = pcpu_sort;
sort_function[1] = mem_sort;
sort_function[2] = time_sort;
}
if (c == 't') {
- USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
+ IF_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
sort_function[0] = time_sort;
sort_function[1] = mem_sort;
sort_function[2] = pcpu_sort;
if (c == 'r')
inverted ^= 1;
#endif
+#if ENABLE_FEATURE_TOP_SMP_CPU
+ /* procps-2.0.18 uses 'C', 3.2.7 uses '1' */
+ if (c == 'c' || c == '1') {
+ /* User wants to toggle per cpu <> aggregate */
+ if (smp_cpu_info) {
+ free(cpu_prev_jif);
+ free(cpu_jif);
+ cpu_jif = &cur_jif;
+ cpu_prev_jif = &prev_jif;
+ } else {
+ /* Prepare for xrealloc() */
+ cpu_jif = cpu_prev_jif = NULL;
+ }
+ num_cpus = 0;
+ smp_cpu_info = !smp_cpu_info;
+ get_jiffy_counts();
+ }
+#endif
#endif
}
#endif /* FEATURE_USE_TERMIOS */
- }
- putchar('\n');
+ } /* end of "while (1)" */
+
+ bb_putchar('\n');
+#if ENABLE_FEATURE_USE_TERMIOS
+ reset_term();
+#endif
return EXIT_SUCCESS;
}