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