be8ac195b54b5e6d3bbb4008a51bafa0f47db528
[platform/upstream/busybox.git] / procps / top.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * A tiny 'top' utility.
4  *
5  * This is written specifically for the linux /proc/<PID>/stat(m)
6  * files format.
7
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
10  * intervals.
11  *
12  * NOTES:
13  * - At startup this changes to /proc, all the reads are then
14  *   relative to that.
15  *
16  * (C) Eero Tamminen <oak at welho dot com>
17  *
18  * Rewritten by Vladimir Oleynik (C) 2002 <dzo@simtreas.ru>
19  */
20
21 /* Original code Copyrights */
22 /*
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
29  */
30
31 #include "busybox.h"
32
33 typedef int (*cmp_t)(procps_status_t *P, procps_status_t *Q);
34
35 static procps_status_t *top;   /* Hehe */
36 static int ntop;
37 static unsigned option_mask;
38 #define OPT_BATCH_MODE (option_mask & 0x4)
39
40 #ifdef CONFIG_FEATURE_USE_TERMIOS
41 static int pid_sort(procps_status_t *P, procps_status_t *Q)
42 {
43         return (Q->pid - P->pid);
44 }
45 #endif
46
47 static int mem_sort(procps_status_t *P, procps_status_t *Q)
48 {
49         return (int)(Q->rss - P->rss);
50 }
51
52 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
53
54 #define sort_depth 3
55 static cmp_t sort_function[sort_depth];
56
57 static int pcpu_sort(procps_status_t *P, procps_status_t *Q)
58 {
59         return (Q->pcpu - P->pcpu);
60 }
61
62 static int time_sort(procps_status_t *P, procps_status_t *Q)
63 {
64         return (int)((Q->stime + Q->utime) - (P->stime + P->utime));
65 }
66
67 static int mult_lvl_cmp(void* a, void* b) {
68         int i, cmp_val;
69
70         for (i = 0; i < sort_depth; i++) {
71                 cmp_val = (*sort_function[i])(a, b);
72                 if (cmp_val != 0)
73                         return cmp_val;
74         }
75         return 0;
76 }
77
78 /* This structure stores some critical information from one frame to
79    the next. Mostly used for sorting. */
80 struct save_hist {
81         int ticks;
82         int pid;
83 };
84
85 /*
86  * Calculates percent cpu usage for each task.
87  */
88
89 static struct save_hist *prev_hist;
90 static int prev_hist_count;
91 /* static int hist_iterations; */
92
93
94 static unsigned total_pcpu;
95 /* static unsigned long total_rss; */
96
97 struct jiffy_counts {
98         unsigned long long usr,nic,sys,idle,iowait,irq,softirq,steal;
99         unsigned long long total;
100         unsigned long long busy;
101 };
102 static struct jiffy_counts jif, prev_jif;
103
104 static void get_jiffy_counts(void)
105 {
106         FILE* fp = xfopen("stat", "r");
107         prev_jif = jif;
108         if (fscanf(fp, "cpu  %lld %lld %lld %lld %lld %lld %lld %lld",
109                         &jif.usr,&jif.nic,&jif.sys,&jif.idle,
110                         &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
111                 bb_error_msg_and_die("failed to read /proc/stat");
112         }
113         fclose(fp);
114         jif.total = jif.usr + jif.nic + jif.sys + jif.idle
115                         + jif.iowait + jif.irq + jif.softirq + jif.steal;
116         /* procps 2.x does not count iowait as busy time */
117         jif.busy = jif.total - jif.idle - jif.iowait;
118 }
119
120 static void do_stats(void)
121 {
122         procps_status_t *cur;
123         int pid, total_time, i, last_i, n;
124         struct save_hist *new_hist;
125
126         get_jiffy_counts();
127         total_pcpu = 0;
128         /* total_rss = 0; */
129         new_hist = xmalloc(sizeof(struct save_hist)*ntop);
130         /*
131          * Make a pass through the data to get stats.
132          */
133         /* hist_iterations = 0; */
134         i = 0;
135         for (n = 0; n < ntop; n++) {
136                 cur = top + n;
137
138                 /*
139                  * Calculate time in cur process.  Time is sum of user time
140                  * and system time
141                  */
142                 pid = cur->pid;
143                 total_time = cur->stime + cur->utime;
144                 new_hist[n].ticks = total_time;
145                 new_hist[n].pid = pid;
146
147                 /* find matching entry from previous pass */
148                 cur->pcpu = 0;
149                 /* do not start at index 0, continue at last used one
150                  * (brought hist_iterations from ~14000 down to 172) */
151                 last_i = i;
152                 if (prev_hist_count) do {
153                         if (prev_hist[i].pid == pid) {
154                                 cur->pcpu = total_time - prev_hist[i].ticks;
155                                 break;
156                         }
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; */
162         }
163
164         /*
165          * Save cur frame's information.
166          */
167         free(prev_hist);
168         prev_hist = new_hist;
169         prev_hist_count = ntop;
170 }
171 #else
172 static cmp_t sort_function;
173 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
174
175 /* display generic info (meminfo / loadavg) */
176 static unsigned long display_generic(int scr_width)
177 {
178         FILE *fp;
179         char buf[80];
180         char scrbuf[80];
181         char *end;
182         unsigned long total, used, mfree, shared, buffers, cached;
183         unsigned int needs_conversion = 1;
184
185         /* read memory info */
186         fp = xfopen("meminfo", "r");
187
188         /*
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.
192          *
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
195          * out with MemTotal:
196          *                              -- PFM.
197          */
198         if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
199                 fgets(buf, sizeof(buf), fp);    /* skip first line */
200
201                 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
202                    &total, &used, &mfree, &shared, &buffers, &cached);
203         } else {
204                 /*
205                  * Revert to manual parsing, which incidentally already has the
206                  * sizes in kilobytes. This should be safe for both 2.4 and
207                  * 2.6.
208                  */
209                 needs_conversion = 0;
210
211                 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
212
213                 /*
214                  * MemShared: is no longer present in 2.6. Report this as 0,
215                  * to maintain consistent behavior with normal procps.
216                  */
217                 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
218                         shared = 0;
219
220                 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
221                 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
222
223                 used = total - mfree;
224         }
225         fclose(fp);
226
227         /* read load average as a string */
228         fp = xfopen("loadavg", "r");
229         buf[0] = '\0';
230         fgets(buf, sizeof(buf), fp);
231         end = strchr(buf, ' ');
232         if (end) end = strchr(end+1, ' ');
233         if (end) end = strchr(end+1, ' ');
234         if (end) *end = '\0';
235         fclose(fp);
236
237         if (needs_conversion) {
238                 /* convert to kilobytes */
239                 used /= 1024;
240                 mfree /= 1024;
241                 shared /= 1024;
242                 buffers /= 1024;
243                 cached /= 1024;
244                 total /= 1024;
245         }
246
247         /* output memory info and load average */
248         /* clear screen & go to top */
249         if (scr_width > sizeof(scrbuf))
250                 scr_width = sizeof(scrbuf);
251         snprintf(scrbuf, scr_width,
252                 "Mem: %ldK used, %ldK free, %ldK shrd, %ldK buff, %ldK cached",
253                 used, mfree, shared, buffers, cached);
254
255         printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
256     
257         snprintf(scrbuf, scr_width,
258                 "Load average: %s", buf);
259         printf("%s\n", scrbuf);
260
261         return total;
262 }
263
264
265 /* display process statuses */
266 static void display_status(int count, int scr_width)
267 {
268         enum {
269                 bits_per_int = sizeof(int)*8
270         };
271
272         procps_status_t *s = top;
273         char rss_str_buf[8];
274         unsigned long total_memory = display_generic(scr_width); /* or use total_rss? */
275         unsigned pmem_shift, pmem_scale;
276
277 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
278         unsigned pcpu_shift, pcpu_scale;
279
280         /* what info of the processes is shown */
281         printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
282                 "  PID USER     STATUS   RSS  PPID %CPU %MEM COMMAND");
283 #define MIN_WIDTH \
284         sizeof( "  PID USER     STATUS   RSS  PPID %CPU %MEM C")
285 #else
286         printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
287                 "  PID USER     STATUS   RSS  PPID %MEM COMMAND");
288 #define MIN_WIDTH \
289         sizeof( "  PID USER     STATUS   RSS  PPID %MEM C")
290 #endif
291
292         /*
293          * MEM% = s->rss/MemTotal
294          */
295         pmem_shift = bits_per_int-11;
296         pmem_scale = 1000*(1U<<(bits_per_int-11)) / total_memory;
297         /* s->rss is in kb. we want (s->rss * pmem_scale) to never overflow */
298         while (pmem_scale >= 512) {
299                 pmem_scale /= 4;
300                 pmem_shift -= 2;
301         }
302 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
303         /*
304          * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
305          * (pcpu is delta of sys+user time between samples)
306          */
307         /* (jif.xxx - prev_jif.xxx) and s->pcpu are
308          * in 0..~64000 range (HZ*update_interval).
309          * we assume that unsigned is at least 32-bit.
310          */
311         pcpu_shift = 6;
312         pcpu_scale = (1000*64*(uint16_t)(jif.busy-prev_jif.busy) ? : 1);
313         while (pcpu_scale < (1U<<(bits_per_int-2))) {
314                 pcpu_scale *= 4;
315                 pcpu_shift += 2;
316         }
317         pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
318         /* we want (s->pcpu * pcpu_scale) to never overflow */
319         while (pcpu_scale >= 1024) {
320                 pcpu_scale /= 4;
321                 pcpu_shift -= 2;
322         }
323         /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
324 #endif
325         if (OPT_BATCH_MODE) count--;
326         while (count-- > 0) {
327                 div_t pmem = div((s->rss*pmem_scale) >> pmem_shift, 10);
328                 int col = scr_width+1;
329                 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(div_t pcpu;)
330
331                 if (s->rss >= 100*1024)
332                         sprintf(rss_str_buf, "%6ldM", s->rss/1024);
333                 else
334                         sprintf(rss_str_buf, "%7ld", s->rss);
335                 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu = div((s->pcpu*pcpu_scale) >> pcpu_shift, 10);)
336                 col -= printf("\n%5d %-8s %s  %s%6d%3u.%c" \
337                                 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE("%3u.%c") " ",
338                                 s->pid, s->user, s->state, rss_str_buf, s->ppid,
339                                 USE_FEATURE_TOP_CPU_USAGE_PERCENTAGE(pcpu.quot, '0'+pcpu.rem,)
340                                 pmem.quot, '0'+pmem.rem);
341                 if (col>0)
342                         printf("%.*s", col, s->short_cmd);
343                 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
344                         jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
345                 s++;
346         }
347         /* printf(" %d", hist_iterations); */
348         putchar(OPT_BATCH_MODE ? '\n' : '\r');
349         fflush(stdout);
350 }
351
352 static void clearmems(void)
353 {
354         free(top);
355         top = 0;
356         ntop = 0;
357 }
358
359 #ifdef CONFIG_FEATURE_USE_TERMIOS
360 #include <termios.h>
361 #include <signal.h>
362
363
364 static struct termios initial_settings;
365
366 static void reset_term(void)
367 {
368         tcsetattr(0, TCSANOW, (void *) &initial_settings);
369 #ifdef CONFIG_FEATURE_CLEAN_UP
370         clearmems();
371 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
372         free(prev_hist);
373 #endif
374 #endif /* CONFIG_FEATURE_CLEAN_UP */
375 }
376
377 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
378 {
379         reset_term();
380         exit(1);
381 }
382 #endif /* CONFIG_FEATURE_USE_TERMIOS */
383
384
385 int top_main(int argc, char **argv)
386 {
387         int count, lines, col;
388         int interval = 5; /* default update rate is 5 seconds */
389         int iterations = -1; /* 2^32 iterations by default :) */
390         char *sinterval, *siterations;
391 #ifdef CONFIG_FEATURE_USE_TERMIOS
392         struct termios new_settings;
393         struct timeval tv;
394         fd_set readfds;
395         unsigned char c;
396 #endif /* CONFIG_FEATURE_USE_TERMIOS */
397
398         /* do normal option parsing */
399         interval = 5;
400         bb_opt_complementally = "-";
401         option_mask = bb_getopt_ulflags(argc, argv, "d:n:b", 
402                 &sinterval, &siterations);
403         if (option_mask & 0x1) interval = atoi(sinterval); // -d
404         if (option_mask & 0x2) iterations = atoi(siterations); // -n
405         //if (option_mask & 0x4) // -b
406
407         /* change to /proc */
408         xchdir("/proc");
409 #ifdef CONFIG_FEATURE_USE_TERMIOS
410         tcgetattr(0, (void *) &initial_settings);
411         memcpy(&new_settings, &initial_settings, sizeof(struct termios));
412         /* unbuffered input, turn off echo */
413         new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
414
415         signal(SIGTERM, sig_catcher);
416         signal(SIGINT, sig_catcher);
417         tcsetattr(0, TCSANOW, (void *) &new_settings);
418         atexit(reset_term);
419 #endif /* CONFIG_FEATURE_USE_TERMIOS */
420
421 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
422         sort_function[0] = pcpu_sort;
423         sort_function[1] = mem_sort;
424         sort_function[2] = time_sort;
425 #else
426         sort_function = mem_sort;
427 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
428
429         while (1) {
430                 procps_status_t *p;
431
432                 /* Default to 25 lines - 5 lines for status */
433                 lines = 24 - 3;
434                 col = 79;
435 #ifdef CONFIG_FEATURE_USE_TERMIOS
436                 get_terminal_width_height(0, &col, &lines);
437                 if (lines < 5 || col < MIN_WIDTH) {
438                         sleep(interval);
439                         continue;
440                 }
441                 lines -= 3;
442 #endif /* CONFIG_FEATURE_USE_TERMIOS */
443
444                 /* read process IDs & status for all the processes */
445                 while ((p = procps_scan(0)) != 0) {
446                         int n = ntop;
447
448                         top = xrealloc(top, (++ntop)*sizeof(procps_status_t));
449                         memcpy(top + n, p, sizeof(procps_status_t));
450                 }
451                 if (ntop == 0) {
452                         bb_error_msg_and_die("Can't find process info in /proc");
453                 }
454 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
455                 if (!prev_hist_count) {
456                         do_stats();
457                         sleep(1);
458                         clearmems();
459                         continue;
460                 }
461                 do_stats();
462                 qsort(top, ntop, sizeof(procps_status_t), (void*)mult_lvl_cmp);
463 #else
464                 qsort(top, ntop, sizeof(procps_status_t), (void*)sort_function);
465 #endif /* CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE */
466                 count = lines;
467                 if (count > ntop) {
468                         count = ntop;
469                 }
470                 /* show status for each of the processes */
471                 display_status(count, col);
472 #ifdef CONFIG_FEATURE_USE_TERMIOS
473                 tv.tv_sec = interval;
474                 tv.tv_usec = 0;
475                 FD_ZERO(&readfds);
476                 FD_SET(0, &readfds);
477                 select(1, &readfds, NULL, NULL, &tv);
478                 if (FD_ISSET(0, &readfds)) {
479                         if (read(0, &c, 1) <= 0) {   /* signal */
480                                 return EXIT_FAILURE;
481                         }
482                         if (c == 'q' || c == initial_settings.c_cc[VINTR])
483                                 break;
484                         if (c == 'M') {
485 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
486                                 sort_function[0] = mem_sort;
487                                 sort_function[1] = pcpu_sort;
488                                 sort_function[2] = time_sort;
489 #else
490                                 sort_function = mem_sort;
491 #endif
492                         }
493 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
494                         if (c == 'P') {
495                                 sort_function[0] = pcpu_sort;
496                                 sort_function[1] = mem_sort;
497                                 sort_function[2] = time_sort;
498                         }
499                         if (c == 'T') {
500                                 sort_function[0] = time_sort;
501                                 sort_function[1] = mem_sort;
502                                 sort_function[2] = pcpu_sort;
503                         }
504 #endif
505                         if (c == 'N') {
506 #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE
507                                 sort_function[0] = pid_sort;
508 #else
509                                 sort_function = pid_sort;
510 #endif
511                         }
512                 }
513                 if (!--iterations)
514                         break;
515 #else
516                 sleep(interval);
517 #endif /* CONFIG_FEATURE_USE_TERMIOS */
518                 clearmems();
519         }
520         if (ENABLE_FEATURE_CLEAN_UP)
521                 clearmems();
522         putchar('\n');
523         return EXIT_SUCCESS;
524 }