top: add sizeof(G) check; fix style
[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 "libbb.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
62 enum { SORT_DEPTH = 3 };
63
64
65 struct globals {
66         top_status_t *top;
67         int ntop;
68 #if ENABLE_FEATURE_TOPMEM
69         smallint sort_field;
70         smallint inverted;
71 #endif
72 #if ENABLE_FEATURE_USE_TERMIOS
73         struct termios initial_settings;
74 #endif
75 #if !ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
76         cmp_funcp sort_function[1];
77 #else
78         cmp_funcp sort_function[SORT_DEPTH];
79         struct save_hist *prev_hist;
80         int prev_hist_count;
81         jiffy_counts_t jif, prev_jif;
82         /* int hist_iterations; */
83         unsigned total_pcpu;
84         /* unsigned long total_vsz; */
85 #endif
86 };
87 #define G (*(struct globals*)&bb_common_bufsiz1)
88 #define INIT_G() \
89         do { \
90                 struct G_sizecheck { \
91                         char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
92                 }; \
93         } while (0)
94 #define top              (G.top               )
95 #define ntop             (G.ntop              )
96 #define sort_field       (G.sort_field        )
97 #define inverted         (G.inverted          )
98 #define initial_settings (G.initial_settings  )
99 #define sort_function    (G.sort_function     )
100 #define prev_hist        (G.prev_hist         )
101 #define prev_hist_count  (G.prev_hist_count   )
102 #define jif              (G.jif               )
103 #define prev_jif         (G.prev_jif          )
104 #define total_pcpu       (G.total_pcpu        )
105
106
107 #define OPT_BATCH_MODE (option_mask32 & 0x4)
108
109
110 #if ENABLE_FEATURE_USE_TERMIOS
111 static int pid_sort(top_status_t *P, top_status_t *Q)
112 {
113         /* Buggy wrt pids with high bit set */
114         /* (linux pids are in [1..2^15-1]) */
115         return (Q->pid - P->pid);
116 }
117 #endif
118
119 static int mem_sort(top_status_t *P, top_status_t *Q)
120 {
121         /* We want to avoid unsigned->signed and truncation errors */
122         if (Q->vsz < P->vsz) return -1;
123         return Q->vsz != P->vsz; /* 0 if ==, 1 if > */
124 }
125
126
127 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
128
129 static int pcpu_sort(top_status_t *P, top_status_t *Q)
130 {
131         /* Buggy wrt ticks with high bit set */
132         /* Affects only processes for which ticks overflow */
133         return (int)Q->pcpu - (int)P->pcpu;
134 }
135
136 static int time_sort(top_status_t *P, top_status_t *Q)
137 {
138         /* We want to avoid unsigned->signed and truncation errors */
139         if (Q->ticks < P->ticks) return -1;
140         return Q->ticks != P->ticks; /* 0 if ==, 1 if > */
141 }
142
143 static int mult_lvl_cmp(void* a, void* b)
144 {
145         int i, cmp_val;
146
147         for (i = 0; i < SORT_DEPTH; i++) {
148                 cmp_val = (*sort_function[i])(a, b);
149                 if (cmp_val != 0)
150                         return cmp_val;
151         }
152         return 0;
153 }
154
155
156 static void get_jiffy_counts(void)
157 {
158         FILE* fp = xfopen("stat", "r");
159         prev_jif = jif;
160         if (fscanf(fp, "cpu  %lld %lld %lld %lld %lld %lld %lld %lld",
161                         &jif.usr,&jif.nic,&jif.sys,&jif.idle,
162                         &jif.iowait,&jif.irq,&jif.softirq,&jif.steal) < 4) {
163                 bb_error_msg_and_die("failed to read /proc/stat");
164         }
165         fclose(fp);
166         jif.total = jif.usr + jif.nic + jif.sys + jif.idle
167                         + jif.iowait + jif.irq + jif.softirq + jif.steal;
168         /* procps 2.x does not count iowait as busy time */
169         jif.busy = jif.total - jif.idle - jif.iowait;
170 }
171
172
173 static void do_stats(void)
174 {
175         top_status_t *cur;
176         pid_t pid;
177         int i, last_i, n;
178         struct save_hist *new_hist;
179
180         get_jiffy_counts();
181         total_pcpu = 0;
182         /* total_vsz = 0; */
183         new_hist = xmalloc(sizeof(struct save_hist)*ntop);
184         /*
185          * Make a pass through the data to get stats.
186          */
187         /* hist_iterations = 0; */
188         i = 0;
189         for (n = 0; n < ntop; n++) {
190                 cur = top + n;
191
192                 /*
193                  * Calculate time in cur process.  Time is sum of user time
194                  * and system time
195                  */
196                 pid = cur->pid;
197                 new_hist[n].ticks = cur->ticks;
198                 new_hist[n].pid = pid;
199
200                 /* find matching entry from previous pass */
201                 cur->pcpu = 0;
202                 /* do not start at index 0, continue at last used one
203                  * (brought hist_iterations from ~14000 down to 172) */
204                 last_i = i;
205                 if (prev_hist_count) do {
206                         if (prev_hist[i].pid == pid) {
207                                 cur->pcpu = cur->ticks - prev_hist[i].ticks;
208                                 total_pcpu += cur->pcpu;
209                                 break;
210                         }
211                         i = (i+1) % prev_hist_count;
212                         /* hist_iterations++; */
213                 } while (i != last_i);
214                 /* total_vsz += cur->vsz; */
215         }
216
217         /*
218          * Save cur frame's information.
219          */
220         free(prev_hist);
221         prev_hist = new_hist;
222         prev_hist_count = ntop;
223 }
224 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
225
226 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && ENABLE_FEATURE_TOP_DECIMALS
227 /* formats 7 char string (8 with terminating NUL) */
228 static char *fmt_100percent_8(char pbuf[8], unsigned value, unsigned total)
229 {
230         unsigned t;
231         if (value >= total) { /* 100% ? */
232                 strcpy(pbuf, "  100% ");
233                 return pbuf;
234         }
235         /* else generate " [N/space]N.N% " string */
236         value = 1000 * value / total;
237         t = value / 100;
238         value = value % 100;
239         pbuf[0] = ' ';
240         pbuf[1] = t ? t + '0' : ' ';
241         pbuf[2] = '0' + (value / 10);
242         pbuf[3] = '.';
243         pbuf[4] = '0' + (value % 10);
244         pbuf[5] = '%';
245         pbuf[6] = ' ';
246         pbuf[7] = '\0';
247         return pbuf;
248 }
249 #endif
250
251 static unsigned long display_header(int scr_width)
252 {
253         FILE *fp;
254         char buf[80];
255         char scrbuf[80];
256         unsigned long total, used, mfree, shared, buffers, cached;
257 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
258         unsigned total_diff;
259 #endif
260
261         /* read memory info */
262         fp = xfopen("meminfo", "r");
263
264         /*
265          * Old kernels (such as 2.4.x) had a nice summary of memory info that
266          * we could parse, however this is gone entirely in 2.6. Try parsing
267          * the old way first, and if that fails, parse each field manually.
268          *
269          * First, we read in the first line. Old kernels will have bogus
270          * strings we don't care about, whereas new kernels will start right
271          * out with MemTotal:
272          *                              -- PFM.
273          */
274         if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
275                 fgets(buf, sizeof(buf), fp);    /* skip first line */
276
277                 fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
278                         &total, &used, &mfree, &shared, &buffers, &cached);
279                 /* convert to kilobytes */
280                 used /= 1024;
281                 mfree /= 1024;
282                 shared /= 1024;
283                 buffers /= 1024;
284                 cached /= 1024;
285                 total /= 1024;
286         } else {
287                 /*
288                  * Revert to manual parsing, which incidentally already has the
289                  * sizes in kilobytes. This should be safe for both 2.4 and
290                  * 2.6.
291                  */
292
293                 fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
294
295                 /*
296                  * MemShared: is no longer present in 2.6. Report this as 0,
297                  * to maintain consistent behavior with normal procps.
298                  */
299                 if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
300                         shared = 0;
301
302                 fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
303                 fscanf(fp, "Cached: %lu %s\n", &cached, buf);
304
305                 used = total - mfree;
306         }
307         fclose(fp);
308
309         /* output memory info */
310         if (scr_width > sizeof(scrbuf))
311                 scr_width = sizeof(scrbuf);
312         snprintf(scrbuf, scr_width,
313                 "Mem: %luK used, %luK free, %luK shrd, %luK buff, %luK cached",
314                 used, mfree, shared, buffers, cached);
315         /* clear screen & go to top */
316         printf(OPT_BATCH_MODE ? "%s\n" : "\e[H\e[J%s\n", scrbuf);
317
318 #if ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS
319         /*
320          * xxx% = (jif.xxx - prev_jif.xxx) / (jif.total - prev_jif.total) * 100%
321          */
322         /* using (unsigned) casts to make operations cheaper */
323         total_diff = ((unsigned)(jif.total - prev_jif.total) ? : 1);
324 #if ENABLE_FEATURE_TOP_DECIMALS
325 /* Generated code is approx +0.3k */
326 #define CALC_STAT(xxx) char xxx[8]
327 #define SHOW_STAT(xxx) fmt_100percent_8(xxx, (unsigned)(jif.xxx - prev_jif.xxx), total_diff)
328 #define FMT "%s"
329 #else
330 #define CALC_STAT(xxx) unsigned xxx = 100 * (unsigned)(jif.xxx - prev_jif.xxx) / total_diff
331 #define SHOW_STAT(xxx) xxx
332 #define FMT "%4u%% "
333 #endif
334         { /* need block: CALC_STAT are declarations */
335                 CALC_STAT(usr);
336                 CALC_STAT(sys);
337                 CALC_STAT(nic);
338                 CALC_STAT(idle);
339                 CALC_STAT(iowait);
340                 CALC_STAT(irq);
341                 CALC_STAT(softirq);
342                 //CALC_STAT(steal);
343
344                 snprintf(scrbuf, scr_width,
345                         /* Barely fits in 79 chars when in "decimals" mode. */
346                         "CPU:"FMT"usr"FMT"sys"FMT"nice"FMT"idle"FMT"io"FMT"irq"FMT"softirq",
347                         SHOW_STAT(usr), SHOW_STAT(sys), SHOW_STAT(nic), SHOW_STAT(idle),
348                         SHOW_STAT(iowait), SHOW_STAT(irq), SHOW_STAT(softirq)
349                         //, SHOW_STAT(steal) - what is this 'steal' thing?
350                         // I doubt anyone wants to know it
351                 );
352         }
353         puts(scrbuf);
354 #undef SHOW_STAT
355 #undef CALC_STAT
356 #undef FMT
357 #endif
358
359         /* read load average as a string */
360         buf[0] = '\0';
361         open_read_close("loadavg", buf, sizeof("N.NN N.NN N.NN")-1);
362         buf[sizeof("N.NN N.NN N.NN")-1] = '\0';
363         snprintf(scrbuf, scr_width, "Load average: %s", buf);
364         puts(scrbuf);
365
366         return total;
367 }
368
369 static void display_process_list(int count, int scr_width)
370 {
371         enum {
372                 BITS_PER_INT = sizeof(int)*8
373         };
374
375         top_status_t *s = top;
376         char vsz_str_buf[8];
377         unsigned long total_memory = display_header(scr_width); /* or use total_vsz? */
378         /* xxx_shift and xxx_scale variables allow us to replace
379          * expensive divides with multiply and shift */
380         unsigned pmem_shift, pmem_scale, pmem_half;
381 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
382         unsigned pcpu_shift, pcpu_scale, pcpu_half;
383         unsigned busy_jifs;
384
385         /* what info of the processes is shown */
386         printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
387                 "  PID  PPID USER     STAT   VSZ %MEM %CPU COMMAND");
388 #else
389
390         /* !CPU_USAGE_PERCENTAGE */
391         printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width,
392                 "  PID  PPID USER     STAT   VSZ %MEM COMMAND");
393 #endif
394
395 #if ENABLE_FEATURE_TOP_DECIMALS
396 #define UPSCALE 1000
397 #define CALC_STAT(name, val) div_t name = div((val), 10)
398 #define SHOW_STAT(name) name.quot, '0'+name.rem
399 #define FMT "%3u.%c"
400 #else
401 #define UPSCALE 100
402 #define CALC_STAT(name, val) unsigned name = (val)
403 #define SHOW_STAT(name) name
404 #define FMT "%4u%%"
405 #endif
406         /*
407          * MEM% = s->vsz/MemTotal
408          */
409         pmem_shift = BITS_PER_INT-11;
410         pmem_scale = UPSCALE*(1U<<(BITS_PER_INT-11)) / total_memory;
411         /* s->vsz is in kb. we want (s->vsz * pmem_scale) to never overflow */
412         while (pmem_scale >= 512) {
413                 pmem_scale /= 4;
414                 pmem_shift -= 2;
415         }
416         pmem_half = (1U << pmem_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
417 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
418         busy_jifs = jif.busy - prev_jif.busy;
419         /* This happens if there were lots of short-lived processes
420          * between two top updates (e.g. compilation) */
421         if (total_pcpu < busy_jifs) total_pcpu = busy_jifs;
422
423         /*
424          * CPU% = s->pcpu/sum(s->pcpu) * busy_cpu_ticks/total_cpu_ticks
425          * (pcpu is delta of sys+user time between samples)
426          */
427         /* (jif.xxx - prev_jif.xxx) and s->pcpu are
428          * in 0..~64000 range (HZ*update_interval).
429          * we assume that unsigned is at least 32-bit.
430          */
431         pcpu_shift = 6;
432         pcpu_scale = (UPSCALE*64*(uint16_t)busy_jifs ? : 1);
433         while (pcpu_scale < (1U<<(BITS_PER_INT-2))) {
434                 pcpu_scale *= 4;
435                 pcpu_shift += 2;
436         }
437         pcpu_scale /= ( (uint16_t)(jif.total-prev_jif.total)*total_pcpu ? : 1);
438         /* we want (s->pcpu * pcpu_scale) to never overflow */
439         while (pcpu_scale >= 1024) {
440                 pcpu_scale /= 4;
441                 pcpu_shift -= 2;
442         }
443         pcpu_half = (1U << pcpu_shift) / (ENABLE_FEATURE_TOP_DECIMALS? 20 : 2);
444         /* printf(" pmem_scale=%u pcpu_scale=%u ", pmem_scale, pcpu_scale); */
445 #endif
446
447         scr_width += 2; /* account for leading '\n' and trailing NUL */
448         /* Ok, all preliminary data is ready, go thru the list */
449         while (count-- > 0) {
450                 char buf[scr_width];
451                 unsigned col;
452                 CALC_STAT(pmem, (s->vsz*pmem_scale + pmem_half) >> pmem_shift);
453 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
454                 CALC_STAT(pcpu, (s->pcpu*pcpu_scale + pcpu_half) >> pcpu_shift);
455 #endif
456
457                 if (s->vsz >= 100000)
458                         sprintf(vsz_str_buf, "%6ldm", s->vsz/1024);
459                 else
460                         sprintf(vsz_str_buf, "%7ld", s->vsz);
461                 // PID PPID USER STAT VSZ %MEM [%CPU] COMMAND
462                 col = snprintf(buf, scr_width,
463                                 "\n" "%5u%6u %-8.8s %s%s" FMT
464 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
465                                 FMT
466 #endif
467                                 " ",
468                                 s->pid, s->ppid, get_cached_username(s->uid),
469                                 s->state, vsz_str_buf,
470                                 SHOW_STAT(pmem)
471 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
472                                 , SHOW_STAT(pcpu)
473 #endif
474                 );
475                 if (col < scr_width)
476                         read_cmdline(buf + col, scr_width - col, s->pid, s->comm);
477                 fputs(buf, stdout);
478                 /* printf(" %d/%d %lld/%lld", s->pcpu, total_pcpu,
479                         jif.busy - prev_jif.busy, jif.total - prev_jif.total); */
480                 s++;
481         }
482         /* printf(" %d", hist_iterations); */
483         putchar(OPT_BATCH_MODE ? '\n' : '\r');
484         fflush(stdout);
485 }
486 #undef UPSCALE
487 #undef SHOW_STAT
488 #undef CALC_STAT
489 #undef FMT
490
491 static void clearmems(void)
492 {
493         clear_username_cache();
494         free(top);
495         top = NULL;
496         ntop = 0;
497 }
498
499 #if ENABLE_FEATURE_USE_TERMIOS
500 #include <termios.h>
501 #include <signal.h>
502
503 static void reset_term(void)
504 {
505         tcsetattr(0, TCSANOW, (void *) &initial_settings);
506         if (ENABLE_FEATURE_CLEAN_UP) {
507                 clearmems();
508 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
509                 free(prev_hist);
510 #endif
511         }
512 }
513
514 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
515 {
516         reset_term();
517         exit(1);
518 }
519 #endif /* FEATURE_USE_TERMIOS */
520
521 /*
522  * TOPMEM support
523  */
524
525 typedef unsigned long mem_t;
526
527 typedef struct topmem_status_t {
528         unsigned pid;
529         char comm[COMM_LEN];
530         /* vsz doesn't count /dev/xxx mappings except /dev/zero */
531         mem_t vsz     ;
532         mem_t vszrw   ;
533         mem_t rss     ;
534         mem_t rss_sh  ;
535         mem_t dirty   ;
536         mem_t dirty_sh;
537         mem_t stack   ;
538 } topmem_status_t;
539
540 enum { NUM_SORT_FIELD = 7 };
541
542 #define topmem ((topmem_status_t*)top)
543
544 #if ENABLE_FEATURE_TOPMEM
545 static int topmem_sort(char *a, char *b)
546 {
547         int n;
548         mem_t l, r;
549
550         n = offsetof(topmem_status_t, vsz) + (sort_field * sizeof(mem_t));
551         l = *(mem_t*)(a + n);
552         r = *(mem_t*)(b + n);
553 //      if (l == r) {
554 //              l = a->mapped_rw;
555 //              r = b->mapped_rw;
556 //      }
557         /* We want to avoid unsigned->signed and truncation errors */
558         /* l>r: -1, l=r: 0, l<r: 1 */
559         n = (l > r) ? -1 : (l != r);
560         return inverted ? -n : n;
561 }
562
563 /* Cut "NNNN " out of "    NNNN kb" */
564 static char *grab_number(char *str, const char *match, unsigned sz)
565 {
566         if (strncmp(str, match, sz) == 0) {
567                 str = skip_whitespace(str + sz);
568                 (skip_non_whitespace(str))[1] = '\0';
569                 return xstrdup(str);
570         }
571         return NULL;
572 }
573
574 /* display header info (meminfo / loadavg) */
575 static void display_topmem_header(int scr_width)
576 {
577         char linebuf[128];
578         int i;
579         FILE *fp;
580         union {
581                 struct {
582                         /*  1 */ char *total;
583                         /*  2 */ char *mfree;
584                         /*  3 */ char *buf;
585                         /*  4 */ char *cache;
586                         /*  5 */ char *swaptotal;
587                         /*  6 */ char *swapfree;
588                         /*  7 */ char *dirty;
589                         /*  8 */ char *mwrite;
590                         /*  9 */ char *anon;
591                         /* 10 */ char *map;
592                         /* 11 */ char *slab;
593                 };
594                 char *str[11];
595         } Z;
596 #define total     Z.total
597 #define mfree     Z.mfree
598 #define buf       Z.buf
599 #define cache     Z.cache
600 #define swaptotal Z.swaptotal
601 #define swapfree  Z.swapfree
602 #define dirty     Z.dirty
603 #define mwrite    Z.mwrite
604 #define anon      Z.anon
605 #define map       Z.map
606 #define slab      Z.slab
607 #define str       Z.str
608
609         memset(&Z, 0, sizeof(Z));
610
611         /* read memory info */
612         fp = xfopen("meminfo", "r");
613         while (fgets(linebuf, sizeof(linebuf), fp)) {
614                 char *p;
615
616 #define SCAN(match, name) \
617                 p = grab_number(linebuf, match, sizeof(match)-1); \
618                 if (p) { name = p; continue; }
619
620                 SCAN("MemTotal:", total);
621                 SCAN("MemFree:", mfree);
622                 SCAN("Buffers:", buf);
623                 SCAN("Cached:", cache);
624                 SCAN("SwapTotal:", swaptotal);
625                 SCAN("SwapFree:", swapfree);
626                 SCAN("Dirty:", dirty);
627                 SCAN("Writeback:", mwrite);
628                 SCAN("AnonPages:", anon);
629                 SCAN("Mapped:", map);
630                 SCAN("Slab:", slab);
631 #undef SCAN
632         }
633         fclose(fp);
634
635 #define S(s) (s ? s : "0")
636         snprintf(linebuf, sizeof(linebuf),
637                 "Mem %stotal %sanon %smap %sfree",
638                 S(total), S(anon), S(map), S(mfree));
639         printf(OPT_BATCH_MODE ? "%.*s\n" : "\e[H\e[J%.*s\n", scr_width, linebuf);
640
641         snprintf(linebuf, sizeof(linebuf),
642                 " %sslab %sbuf %scache %sdirty %swrite",
643                 S(slab), S(buf), S(cache), S(dirty), S(mwrite));
644         printf("%.*s\n", scr_width, linebuf);
645
646         snprintf(linebuf, sizeof(linebuf),
647                 "Swap %stotal %sfree", // TODO: % used?
648                 S(swaptotal), S(swapfree));
649         printf("%.*s\n", scr_width, linebuf);
650 #undef S
651
652         for (i = 0; i < ARRAY_SIZE(str); i++)
653                 free(str[i]);
654 #undef total
655 #undef free
656 #undef buf
657 #undef cache
658 #undef swaptotal
659 #undef swapfree
660 #undef dirty
661 #undef write
662 #undef anon
663 #undef map
664 #undef slab
665 #undef str
666 }
667
668 // Converts unsigned long long value into compact 5-char
669 // representation. Sixth char is always ' '
670 static void smart_ulltoa6(unsigned long long ul, char buf[6])
671 {
672         const char *fmt;
673         char c;
674         unsigned v, u, idx = 0;
675
676         if (ul > 99999) { // do not scale if 99999 or less
677                 ul *= 10;
678                 do {
679                         ul /= 1024;
680                         idx++;
681                 } while (ul >= 100000);
682         }
683         v = ul; // ullong divisions are expensive, avoid them
684
685         fmt = " 123456789";
686         u = v / 10;
687         v = v % 10;
688         if (!idx) {
689                 // 99999 or less: use "12345" format
690                 // u is value/10, v is last digit
691                 c = buf[0] = " 123456789"[u/1000];
692                 if (c != ' ') fmt = "0123456789";
693                 c = buf[1] = fmt[u/100%10];
694                 if (c != ' ') fmt = "0123456789";
695                 c = buf[2] = fmt[u/10%10];
696                 if (c != ' ') fmt = "0123456789";
697                 buf[3] = fmt[u%10];
698                 buf[4] = "0123456789"[v];
699         } else {
700                 // value has been scaled into 0..9999.9 range
701                 // u is value, v is 1/10ths (allows for 92.1M format)
702                 if (u >= 100) {
703                         // value is >= 100: use "1234M', " 123M" formats
704                         c = buf[0] = " 123456789"[u/1000];
705                         if (c != ' ') fmt = "0123456789";
706                         c = buf[1] = fmt[u/100%10];
707                         if (c != ' ') fmt = "0123456789";
708                         v = u % 10;
709                         u = u / 10;
710                         buf[2] = fmt[u%10];
711                 } else {
712                         // value is < 100: use "92.1M" format
713                         c = buf[0] = " 123456789"[u/10];
714                         if (c != ' ') fmt = "0123456789";
715                         buf[1] = fmt[u%10];
716                         buf[2] = '.';
717                 }
718                 buf[3] = "0123456789"[v];
719                 // see http://en.wikipedia.org/wiki/Tera
720                 buf[4] = " mgtpezy"[idx];
721         }
722         buf[5] = ' ';
723 }
724
725 static void display_topmem_process_list(int count, int scr_width)
726 {
727 #define HDR_STR "  PID   VSZ VSZRW   RSS (SHR) DIRTY (SHR) STACK"
728 #define MIN_WIDTH sizeof(HDR_STR)
729         const topmem_status_t *s = topmem;
730         char buf[scr_width | MIN_WIDTH]; /* a|b is a cheap max(a,b) */
731
732         display_topmem_header(scr_width);
733         strcpy(buf, HDR_STR " COMMAND");
734         buf[5 + sort_field * 6] = '*';
735         printf(OPT_BATCH_MODE ? "%.*s" : "\e[7m%.*s\e[0m", scr_width, buf);
736
737         while (--count >= 0) {
738                 // PID VSZ VSZRW RSS (SHR) DIRTY (SHR) COMMAND
739                 smart_ulltoa6(s->pid     , &buf[0*6]);
740                 smart_ulltoa6(s->vsz     , &buf[1*6]);
741                 smart_ulltoa6(s->vszrw   , &buf[2*6]);
742                 smart_ulltoa6(s->rss     , &buf[3*6]);
743                 smart_ulltoa6(s->rss_sh  , &buf[4*6]);
744                 smart_ulltoa6(s->dirty   , &buf[5*6]);
745                 smart_ulltoa6(s->dirty_sh, &buf[6*6]);
746                 smart_ulltoa6(s->stack   , &buf[7*6]);
747                 buf[8*6] = '\0';
748                 if (scr_width > MIN_WIDTH) {
749                         read_cmdline(&buf[8*6], scr_width - MIN_WIDTH, s->pid, s->comm);
750                 }
751                 printf("\n""%.*s", scr_width, buf);
752                 s++;
753         }
754         putchar(OPT_BATCH_MODE ? '\n' : '\r');
755         fflush(stdout);
756 #undef HDR_STR
757 #undef MIN_WIDTH
758 }
759 #else
760 void display_topmem_process_list(int count, int scr_width);
761 int topmem_sort(char *a, char *b);
762 #endif /* TOPMEM */
763
764 /*
765  * end TOPMEM support
766  */
767
768 enum {
769         TOP_MASK = 0
770                 | PSSCAN_PID
771                 | PSSCAN_PPID
772                 | PSSCAN_VSZ
773                 | PSSCAN_STIME
774                 | PSSCAN_UTIME
775                 | PSSCAN_STATE
776                 | PSSCAN_COMM
777                 | PSSCAN_UIDGID,
778         TOPMEM_MASK = 0
779                 | PSSCAN_PID
780                 | PSSCAN_SMAPS
781                 | PSSCAN_COMM,
782 };
783
784 int top_main(int argc, char **argv);
785 int top_main(int argc, char **argv)
786 {
787         int count, lines, col;
788         unsigned interval;
789         int iterations;
790         char *sinterval, *siterations;
791         SKIP_FEATURE_TOPMEM(const) unsigned scan_mask = TOP_MASK;
792 #if ENABLE_FEATURE_USE_TERMIOS
793         struct termios new_settings;
794         struct pollfd pfd[1];
795         unsigned char c;
796
797         pfd[0].fd = 0;
798         pfd[0].events = POLLIN;
799 #endif /* FEATURE_USE_TERMIOS */
800
801         INIT_G();
802
803         interval = 5; /* default update rate is 5 seconds */
804         iterations = 0; /* infinite */
805
806         /* do normal option parsing */
807         opt_complementary = "-";
808         getopt32(argv, "d:n:b", &sinterval, &siterations);
809         if (option_mask32 & 0x1) {
810                 /* Need to limit it to not overflow poll timeout */
811                 interval = xatou16(sinterval); // -d
812         }
813         if (option_mask32 & 0x2)
814                 iterations = xatoi_u(siterations); // -n
815         //if (option_mask32 & 0x4) // -b
816
817         /* change to /proc */
818         xchdir("/proc");
819 #if ENABLE_FEATURE_USE_TERMIOS
820         tcgetattr(0, (void *) &initial_settings);
821         memcpy(&new_settings, &initial_settings, sizeof(new_settings));
822         /* unbuffered input, turn off echo */
823         new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
824
825         signal(SIGTERM, sig_catcher);
826         signal(SIGINT, sig_catcher);
827         tcsetattr(0, TCSANOW, (void *) &new_settings);
828         atexit(reset_term);
829 #endif /* FEATURE_USE_TERMIOS */
830
831 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
832         sort_function[0] = pcpu_sort;
833         sort_function[1] = mem_sort;
834         sort_function[2] = time_sort;
835 #else
836         sort_function[0] = mem_sort;
837 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
838
839         while (1) {
840                 procps_status_t *p = NULL;
841
842                 lines = 24; /* default */
843                 col = 79;
844 #if ENABLE_FEATURE_USE_TERMIOS
845                 get_terminal_width_height(0, &col, &lines);
846                 if (lines < 5 || col < 10) {
847                         sleep(interval);
848                         continue;
849                 }
850 #endif /* FEATURE_USE_TERMIOS */
851                 if (!ENABLE_FEATURE_TOP_CPU_GLOBAL_PERCENTS && scan_mask == TOP_MASK)
852                         lines -= 3;
853                 else
854                         lines -= 4;
855
856                 /* read process IDs & status for all the processes */
857                 while ((p = procps_scan(p, scan_mask)) != NULL) {
858                         int n;
859                         if (scan_mask == TOP_MASK) {
860                                 n = ntop;
861                                 top = xrealloc(top, (++ntop) * sizeof(*top));
862                                 top[n].pid = p->pid;
863                                 top[n].ppid = p->ppid;
864                                 top[n].vsz = p->vsz;
865 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
866                                 top[n].ticks = p->stime + p->utime;
867 #endif
868                                 top[n].uid = p->uid;
869                                 strcpy(top[n].state, p->state);
870                                 strcpy(top[n].comm, p->comm);
871                         } else { /* TOPMEM */
872 #if ENABLE_FEATURE_TOPMEM
873                                 if (!(p->mapped_ro | p->mapped_rw))
874                                         continue; /* kernel threads are ignored */
875                                 n = ntop;
876                                 top = xrealloc(topmem, (++ntop) * sizeof(*topmem));
877                                 strcpy(topmem[n].comm, p->comm);
878                                 topmem[n].pid      = p->pid;
879                                 topmem[n].vsz      = p->mapped_rw + p->mapped_ro;
880                                 topmem[n].vszrw    = p->mapped_rw;
881                                 topmem[n].rss_sh   = p->shared_clean + p->shared_dirty;
882                                 topmem[n].rss      = p->private_clean + p->private_dirty + topmem[n].rss_sh;
883                                 topmem[n].dirty    = p->private_dirty + p->shared_dirty;
884                                 topmem[n].dirty_sh = p->shared_dirty;
885                                 topmem[n].stack    = p->stack;
886 #endif
887                         }
888                 }
889                 if (ntop == 0) {
890                         bb_error_msg_and_die("no process info in /proc");
891                 }
892
893                 if (scan_mask == TOP_MASK) {
894 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
895                         if (!prev_hist_count) {
896                                 do_stats();
897                                 usleep(100000);
898                                 clearmems();
899                                 continue;
900                         }
901                         do_stats();
902 /* TODO: we don't need to sort all 10000 processes, we need to find top 24! */
903                         qsort(top, ntop, sizeof(top_status_t), (void*)mult_lvl_cmp);
904 #else
905                         qsort(top, ntop, sizeof(top_status_t), (void*)(sort_function[0]));
906 #endif /* FEATURE_TOP_CPU_USAGE_PERCENTAGE */
907                 } else { /* TOPMEM */
908                         qsort(topmem, ntop, sizeof(topmem_status_t), (void*)topmem_sort);
909                 }
910                 count = lines;
911                 if (OPT_BATCH_MODE || count > ntop) {
912                         count = ntop;
913                 }
914                 if (scan_mask == TOP_MASK)
915                         display_process_list(count, col);
916                 else
917                         display_topmem_process_list(count, col);
918                 clearmems();
919                 if (iterations >= 0 && !--iterations)
920                         break;
921 #if !ENABLE_FEATURE_USE_TERMIOS
922                 sleep(interval);
923 #else
924                 if (poll(pfd, 1, interval * 1000) != 0) {
925                         if (read(0, &c, 1) != 1)    /* signal */
926                                 break;
927                         if (c == initial_settings.c_cc[VINTR])
928                                 break;
929                         c |= 0x20; /* lowercase */
930                         if (c == 'q')
931                                 break;
932                         if (c == 'n') {
933                                 USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
934                                 sort_function[0] = pid_sort;
935                         }
936                         if (c == 'm') {
937                                 USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
938                                 sort_function[0] = mem_sort;
939 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
940                                 sort_function[1] = pcpu_sort;
941                                 sort_function[2] = time_sort;
942 #endif
943                         }
944 #if ENABLE_FEATURE_TOP_CPU_USAGE_PERCENTAGE
945                         if (c == 'p') {
946                                 USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
947                                 sort_function[0] = pcpu_sort;
948                                 sort_function[1] = mem_sort;
949                                 sort_function[2] = time_sort;
950                         }
951                         if (c == 't') {
952                                 USE_FEATURE_TOPMEM(scan_mask = TOP_MASK;)
953                                 sort_function[0] = time_sort;
954                                 sort_function[1] = mem_sort;
955                                 sort_function[2] = pcpu_sort;
956                         }
957 #if ENABLE_FEATURE_TOPMEM
958                         if (c == 's') {
959                                 scan_mask = TOPMEM_MASK;
960                                 free(prev_hist);
961                                 prev_hist = NULL;
962                                 prev_hist_count = 0;
963                                 sort_field = (sort_field + 1) % NUM_SORT_FIELD;
964                         }
965                         if (c == 'r')
966                                 inverted ^= 1;
967 #endif
968 #endif
969                 }
970 #endif /* FEATURE_USE_TERMIOS */
971         }
972         putchar('\n');
973         return EXIT_SUCCESS;
974 }