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