1 /* vi: set sw=4 ts=4: */
3 * A tiny 'top' utility.
5 * This is written specifically for the linux /proc/<PID>/stat(m)
8 * This reads the PIDs of all processes and their status and shows
9 * the status of processes (first ones that fit to screen) at given
13 * - At startup this changes to /proc, all the reads are then
16 * (C) Eero Tamminen <oak at welho dot com>
18 * Rewritten by Vladimir Oleynik (C) 2002 <dzo@simtreas.ru>
21 /* Original code Copyrights */
23 * Copyright (c) 1992 Branko Lankester
24 * Copyright (c) 1992 Roger Binns
25 * Copyright (C) 1994-1996 Charles L. Blake.
26 * Copyright (C) 1992-1998 Michael K. Johnson
27 * May be distributed under the conditions of the
28 * GNU Library General Public License
33 typedef int (*cmp_t)(procps_status_t *P, procps_status_t *Q);
35 static procps_status_t *top; /* Hehe */
37 #define OPT_BATCH_MODE (option_mask32 & 0x4)
39 #ifdef CONFIG_FEATURE_USE_TERMIOS
40 static int pid_sort(procps_status_t *P, procps_status_t *Q)
42 return (Q->pid - P->pid);
46 static int mem_sort(procps_status_t *P, procps_status_t *Q)
48 return (int)(Q->rss - P->rss);
51 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
54 static cmp_t sort_function[sort_depth];
56 static int pcpu_sort(procps_status_t *P, procps_status_t *Q)
58 return (Q->pcpu - P->pcpu);
61 static int time_sort(procps_status_t *P, procps_status_t *Q)
63 return (int)((Q->stime + Q->utime) - (P->stime + P->utime));
66 static int mult_lvl_cmp(void* a, void* b) {
69 for (i = 0; i < sort_depth; i++) {
70 cmp_val = (*sort_function[i])(a, b);
77 /* This structure stores some critical information from one frame to
78 the next. Mostly used for sorting. */
85 * Calculates percent cpu usage for each task.
88 static struct save_hist *prev_hist;
89 static int prev_hist_count;
90 /* static int hist_iterations; */
93 static unsigned total_pcpu;
94 /* static unsigned long total_rss; */
97 unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
98 unsigned long long total;
99 unsigned long long busy;
101 static struct jiffy_counts jif, prev_jif;
103 static void get_jiffy_counts(void)
105 FILE* fp = xfopen("stat", "r");
107 if (fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
108 &jif.usr,&jif.nic,&jif.sys,&jif.idle,
109 &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
110 bb_error_msg_and_die("failed to read /proc/stat");
113 jif.total = jif.usr + jif.nic + jif.sys + jif.idle
114 + jif.iowait + jif.irq + jif.softirq + jif.steal;
115 /* procps 2.x does not count iowait as busy time */
116 jif.busy = jif.total - jif.idle - jif.iowait;
119 static void do_stats(void)
121 procps_status_t *cur;
123 int total_time, i, last_i, n;
124 struct save_hist *new_hist;
129 new_hist = xmalloc(sizeof(struct save_hist)*ntop);
131 * Make a pass through the data to get stats.
133 /* hist_iterations = 0; */
135 for (n = 0; n < ntop; n++) {
139 * Calculate time in cur process. Time is sum of user time
143 total_time = cur->stime + cur->utime;
144 new_hist[n].ticks = total_time;
145 new_hist[n].pid = pid;
147 /* find matching entry from previous pass */
149 /* do not start at index 0, continue at last used one
150 * (brought hist_iterations from ~14000 down to 172) */
152 if (prev_hist_count) do {
153 if (prev_hist[i].pid == pid) {
154 cur->pcpu = total_time - prev_hist[i].ticks;
157 i = (i+1) % prev_hist_count;
158 /* hist_iterations++; */
159 } while (i != last_i);
160 total_pcpu += cur->pcpu;
161 /* total_rss += cur->rss; */
165 * Save cur frame's information.
168 prev_hist = new_hist;
169 prev_hist_count = ntop;
172 static cmp_t sort_function;
173 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
175 /* display generic info (meminfo / loadavg) */
176 static unsigned long display_generic(int scr_width)
182 unsigned long total, used, mfree, shared, buffers, cached;
183 unsigned int needs_conversion = 1;
185 /* read memory info */
186 fp = xfopen("meminfo", "r");
189 * Old kernels (such as 2.4.x) had a nice summary of memory info that
190 * we could parse, however this is gone entirely in 2.6. Try parsing
191 * the old way first, and if that fails, parse each field manually.
193 * First, we read in the first line. Old kernels will have bogus
194 * strings we don't care about, whereas new kernels will start right
198 if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
199 fgets(buf, sizeof(buf), fp); /* skip first line */
201 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
202 &total, &used, &mfree, &shared, &buffers, &cached);
205 * Revert to manual parsing, which incidentally already has the
206 * sizes in kilobytes. This should be safe for both 2.4 and
209 needs_conversion = 0;
211 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
214 * MemShared: is no longer present in 2.6. Report this as 0,
215 * to maintain consistent behavior with normal procps.
217 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
220 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
221 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
223 used = total - mfree;
227 /* read load average as a string */
229 open_read_close("loadavg", buf, sizeof(buf));
230 end = strchr(buf, ' ');
231 if (end) end = strchr(end+1, ' ');
232 if (end) end = strchr(end+1, ' ');
233 if (end) *end = '\0';
235 if (needs_conversion) {
236 /* convert to kilobytes */
245 /* output memory info and load average */
246 /* clear screen & go to top */
247 if (scr_width > sizeof(scrbuf))
248 scr_width = sizeof(scrbuf);
249 snprintf(scrbuf, scr_width,
250 "Mem: %ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached",
251 used, mfree, shared, buffers, cached);
253 printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
255 snprintf(scrbuf, scr_width, "Load average: %s", buf);
256 printf("%s\n", scrbuf);
262 /* display process statuses */
263 static void display_status(int count, int scr_width)
266 bits_per_int = sizeof(int)*8
269 procps_status_t *s = top;
271 unsigned long total_memory = display_generic(scr_width); /* or use total_rss? */
272 unsigned pmem_shift, pmem_scale;
274 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
275 unsigned pcpu_shift, pcpu_scale;
277 /* what info of the processes is shown */
278 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
279 " PID USER STATUS RSS PPID %CPU %MEM COMMAND");
281 sizeof( " PID USER STATUS RSS PPID %CPU %MEM C")
283 printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
284 " PID USER STATUS RSS PPID %MEM COMMAND");
286 sizeof( " PID USER STATUS RSS PPID %MEM C")
290 * MEM% = s->rss/MemTotal
292 pmem_shift = bits_per_int-11;
293 pmem_scale = 1000*(1U<<(bits_per_int-11)) / total_memory;
294 /* s->rss is in kb. we want (s->rss * pmem_scale) to never overflow */
295 while (pmem_scale >= 512) {
299 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
301 * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
302 * (pcpu is delta of sys+user time between samples)
304 /* (jif.xxx - prev_jif.xxx) and s->pcpu are
305 * in 0..~64000 range (HZ*update_interval).
306 * we assume that unsigned is at least 32-bit.
309 pcpu_scale = (1000*64*(uint16_t)(jif.busy-prev_jif.busy) ? : 1);
310 while (pcpu_scale < (1U<<(bits_per_int-2))) {
314 pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
315 /* we want (s->pcpu * pcpu_scale) to never overflow */
316 while (pcpu_scale >= 1024) {
320 /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
322 while (count-- > 0) {
323 div_t pmem = div((s->rss*pmem_scale) >> pmem_shift, 10);
324 int col = scr_width+1;
325 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(div_t pcpu;)
327 if (s->rss >= 100*1024)
328 sprintf(rss_str_buf, "%6ldM", s->rss/1024);
330 sprintf(rss_str_buf, "%7ld", s->rss);
331 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu = div((s->pcpu*pcpu_scale) >> pcpu_shift, 10);)
332 col -= printf("\n%5u %-8s %s %s%6u%3u.%c" \
333 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE("%3u.%c") " ",
334 (unsigned)s->pid, s->user, s->state, rss_str_buf, (unsigned)s->ppid,
335 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu.quot, '0'+pcpu.rem,)
336 pmem.quot, '0'+pmem.rem);
338 printf("%.*s", col, s->short_cmd);
339 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
340 jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
343 /* printf(" %d", hist_iterations); */
344 putchar(OPT_BATCH_MODE ? '\n' : '\r');
348 static void clearmems(void)
355 #ifdef CONFIG_FEATURE_USE_TERMIOS
360 static struct termios initial_settings;
362 static void reset_term(void)
364 tcsetattr(0, TCSANOW, (void *) &initial_settings);
365 #ifdef CONFIG_FEATURE_CLEAN_UP
367 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
370 #endif /* CONFIG_FEATURE_CLEAN_UP */
373 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
378 #endif /* CONFIG_FEATURE_USE_TERMIOS */
381 int top_main(int argc, char **argv)
383 int count, lines, col;
384 unsigned interval = 5; /* default update rate is 5 seconds */
385 unsigned iterations = UINT_MAX; /* 2^32 iterations by default :) */
386 char *sinterval, *siterations;
387 #ifdef CONFIG_FEATURE_USE_TERMIOS
388 struct termios new_settings;
392 #endif /* CONFIG_FEATURE_USE_TERMIOS */
394 /* do normal option parsing */
396 opt_complementary = "-";
397 getopt32(argc, argv, "d:n:b",
398 &sinterval, &siterations);
399 if (option_mask32 & 0x1) interval = xatou(sinterval); // -d
400 if (option_mask32 & 0x2) iterations = xatou(siterations); // -n
401 //if (option_mask32 & 0x4) // -b
403 /* change to /proc */
405 #ifdef CONFIG_FEATURE_USE_TERMIOS
406 tcgetattr(0, (void *) &initial_settings);
407 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
408 /* unbuffered input, turn off echo */
409 new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
411 signal(SIGTERM, sig_catcher);
412 signal(SIGINT, sig_catcher);
413 tcsetattr(0, TCSANOW, (void *) &new_settings);
415 #endif /* CONFIG_FEATURE_USE_TERMIOS */
417 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
418 sort_function[0] = pcpu_sort;
419 sort_function[1] = mem_sort;
420 sort_function[2] = time_sort;
422 sort_function = mem_sort;
423 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
428 /* Default to 25 lines - 5 lines for status */
431 #ifdef CONFIG_FEATURE_USE_TERMIOS
432 get_terminal_width_height(0, &col, &lines);
433 if (lines < 5 || col < MIN_WIDTH) {
438 #endif /* CONFIG_FEATURE_USE_TERMIOS */
440 /* read process IDs & status for all the processes */
441 while ((p = procps_scan(0)) != 0) {
444 top = xrealloc(top, (++ntop)*sizeof(procps_status_t));
445 memcpy(top + n, p, sizeof(procps_status_t));
448 bb_error_msg_and_die("can't find process info in /proc");
450 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
451 if (!prev_hist_count) {
458 qsort(top, ntop, sizeof(procps_status_t), (void*)mult_lvl_cmp);
460 qsort(top, ntop, sizeof(procps_status_t), (void*)sort_function);
461 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
463 if (OPT_BATCH_MODE || count > ntop) {
466 /* show status for each of the processes */
467 display_status(count, col);
468 #ifdef CONFIG_FEATURE_USE_TERMIOS
469 tv.tv_sec = interval;
473 select(1, &readfds, NULL, NULL, &tv);
474 if (FD_ISSET(0, &readfds)) {
475 if (read(0, &c, 1) <= 0) { /* signal */
478 if (c == 'q' || c == initial_settings.c_cc[VINTR])
481 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
482 sort_function[0] = mem_sort;
483 sort_function[1] = pcpu_sort;
484 sort_function[2] = time_sort;
486 sort_function = mem_sort;
489 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
491 sort_function[0] = pcpu_sort;
492 sort_function[1] = mem_sort;
493 sort_function[2] = time_sort;
496 sort_function[0] = time_sort;
497 sort_function[1] = mem_sort;
498 sort_function[2] = pcpu_sort;
502 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
503 sort_function[0] = pid_sort;
505 sort_function = pid_sort;
513 #endif /* CONFIG_FEATURE_USE_TERMIOS */
516 if (ENABLE_FEATURE_CLEAN_UP)