2 * Licensed under GPLv2, see file LICENSE in this source tree.
4 * Based on nanotop.c from floppyfw project
6 * Contact me: vda.linux@googlemail.com
10 //config: bool "nmeter"
13 //config: Prints selected system stats continuously, one line per update.
15 //applet:IF_NMETER(APPLET(nmeter, BB_DIR_USR_BIN, BB_SUID_DROP))
17 //kbuild:lib-$(CONFIG_NMETER) += nmeter.o
19 //usage:#define nmeter_trivial_usage
20 //usage: "[-d MSEC] FORMAT_STRING"
21 //usage:#define nmeter_full_usage "\n\n"
22 //usage: "Monitor system in real time"
24 //usage: "\n -d MSEC Milliseconds between updates (default:1000)"
26 //usage: "\nFormat specifiers:"
27 //usage: "\n %Nc or %[cN] Monitor CPU. N - bar size (default:10)"
28 //usage: "\n (displays: S:system U:user N:niced D:iowait I:irq i:softirq)"
29 //usage: "\n %[niface] Monitor network interface 'iface'"
30 //usage: "\n %m Monitor allocated memory"
31 //usage: "\n %[mf] Monitor free memory"
32 //usage: "\n %[mt] Monitor total memory"
33 //usage: "\n %s Monitor allocated swap"
34 //usage: "\n %f Monitor number of used file descriptors"
35 //usage: "\n %Ni Monitor total/specific IRQ rate"
36 //usage: "\n %x Monitor context switch rate"
37 //usage: "\n %p Monitor forks"
38 //usage: "\n %[pn] Monitor # of processes"
39 //usage: "\n %b Monitor block io"
40 //usage: "\n %Nt Show time (with N decimal points)"
41 //usage: "\n %r Print <cr> instead of <lf> at EOL"
47 // disk_io: (3,0):(22272,17897,410702,4375,54750)
49 //TODO: use sysinfo libc call/syscall, if appropriate
50 // (faster than open/read/close):
51 // sysinfo({uptime=15017, loads=[5728, 15040, 16480]
52 // totalram=2107416576, freeram=211525632, sharedram=0, bufferram=157204480}
53 // totalswap=134209536, freeswap=134209536, procs=157})
57 typedef unsigned long long ullong;
59 enum { /* Preferably use powers of 2 */
60 PROC_MIN_FILE_SIZE = 256,
61 PROC_MAX_FILE_SIZE = 16 * 1024,
64 typedef struct proc_file {
70 static const char *const proc_name[] = {
71 "stat", // Must match the order of proc_file's!
80 // Sample generation flip-flop
82 // Linux 2.6? (otherwise assumes 2.4)
84 // 1 if sample delay is not an integer fraction of a second
85 smallint need_seconds;
87 const char *final_str;
91 #define first_proc_file proc_stat
92 proc_file proc_stat; // Must match the order of proc_name's!
93 proc_file proc_loadavg;
94 proc_file proc_net_dev;
95 proc_file proc_meminfo;
96 proc_file proc_diskstats;
97 proc_file proc_sys_fs_filenr;
99 #define G (*ptr_to_globals)
101 #define is26 (G.is26 )
102 #define need_seconds (G.need_seconds )
103 #define cur_outbuf (G.cur_outbuf )
104 #define final_str (G.final_str )
105 #define delta (G.delta )
106 #define deltanz (G.deltanz )
108 #define proc_stat (G.proc_stat )
109 #define proc_loadavg (G.proc_loadavg )
110 #define proc_net_dev (G.proc_net_dev )
111 #define proc_meminfo (G.proc_meminfo )
112 #define proc_diskstats (G.proc_diskstats )
113 #define proc_sys_fs_filenr (G.proc_sys_fs_filenr)
114 #define INIT_G() do { \
115 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
116 cur_outbuf = outbuf; \
118 deltanz = delta = 1000000; \
121 // We depend on this being a char[], not char* - we take sizeof() of it
122 #define outbuf bb_common_bufsiz1
124 static inline void reset_outbuf(void)
129 static inline int outbuf_count(void)
131 return cur_outbuf - outbuf;
134 static void print_outbuf(void)
136 int sz = cur_outbuf - outbuf;
138 xwrite(STDOUT_FILENO, outbuf, sz);
143 static void put(const char *s)
146 if (sz > outbuf + sizeof(outbuf) - cur_outbuf)
147 sz = outbuf + sizeof(outbuf) - cur_outbuf;
148 memcpy(cur_outbuf, s, sz);
152 static void put_c(char c)
154 if (cur_outbuf < outbuf + sizeof(outbuf))
158 static void put_question_marks(int count)
164 static void readfile_z(proc_file *pf, const char* fname)
166 // open_read_close() will do two reads in order to be sure we are at EOF,
167 // and we don't need/want that.
175 buf = xmalloc(PROC_MIN_FILE_SIZE);
176 sz = PROC_MIN_FILE_SIZE;
179 fd = xopen(fname, O_RDONLY);
181 rdsz = read(fd, buf, sz-1);
184 if (rdsz == sz-1 && sz < PROC_MAX_FILE_SIZE) {
186 buf = xrealloc(buf, sz);
195 static const char* get_file(proc_file *pf)
197 if (pf->last_gen != gen) {
199 readfile_z(pf, proc_name[pf - &first_proc_file]);
204 static ullong read_after_slash(const char *p)
208 return strtoull(p+1, NULL, 10);
211 enum conv_type { conv_decimal, conv_slash };
213 // Reads decimal values from line. Values start after key, for example:
214 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
215 // Values are stored in vec[]. arg_ptr has list of positions
216 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
217 static int vrdval(const char* p, const char* key,
218 enum conv_type conv, ullong *vec, va_list arg_ptr)
228 indexnext = va_arg(arg_ptr, int);
230 while (*p == ' ' || *p == '\t') p++;
231 if (*p == '\n' || *p == '\0') break;
233 if (indexline == indexnext) { // read this value
234 *vec++ = conv==conv_decimal ?
235 strtoull(p, NULL, 10) :
237 indexnext = va_arg(arg_ptr, int);
239 while (*p > ' ') p++; // skip over value
245 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
246 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
247 // value# start with 1
248 static int rdval(const char* p, const char* key, ullong *vec, ...)
253 va_start(arg_ptr, vec);
254 result = vrdval(p, key, conv_decimal, vec, arg_ptr);
260 // Parses files with lines like "... ... ... 3/148 ...."
261 static int rdval_loadavg(const char* p, ullong *vec, ...)
266 va_start(arg_ptr, vec);
267 result = vrdval(p, "", conv_slash, vec, arg_ptr);
273 // Parses /proc/diskstats
274 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
275 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
276 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
277 static int rdval_diskstats(const char* p, ullong *vec)
279 ullong rd = rd; // for compiler
285 while (*p == ' ' || *p == '\t') p++;
286 if (*p == '\0') break;
292 if (indexline == 6) {
293 rd = strtoull(p, NULL, 10);
294 } else if (indexline == 10) {
295 vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize)
296 vec[1] += strtoull(p, NULL, 10);
297 while (*p != '\n' && *p != '\0') p++;
300 while (*p > ' ') p++; // skip over value
305 static void scale(ullong ul)
309 /* see http://en.wikipedia.org/wiki/Tera */
310 smart_ulltoa4(ul, buf, " kmgtpezy");
318 struct s_stat *next; \
319 void (*collect)(struct a *s) FAST_FUNC; \
321 #define S_STAT_END(a) } a;
326 static void FAST_FUNC collect_literal(s_stat *s UNUSED_PARAM)
330 static s_stat* init_literal(void)
332 s_stat *s = xzalloc(sizeof(*s));
333 s->collect = collect_literal;
337 static s_stat* init_delay(const char *param)
339 delta = strtoul(param, NULL, 0) * 1000; /* param can be "" */
340 deltanz = delta > 0 ? delta : 1;
341 need_seconds = (1000000%deltanz) != 0;
345 static s_stat* init_cr(const char *param UNUSED_PARAM)
352 // user nice system idle iowait irq softirq (last 3 only in 2.6)
353 //cpu 649369 0 341297 4336769 11640 7122 1183
354 //cpuN 649369 0 341297 4336769 11640 7122 1183
355 enum { CPU_FIELDCNT = 7 };
357 ullong old[CPU_FIELDCNT];
363 static void FAST_FUNC collect_cpu(cpu_stat *s)
365 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
366 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
369 int bar_sz = s->bar_sz;
373 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
374 put_question_marks(bar_sz);
378 for (i = 0; i < CPU_FIELDCNT; i++) {
379 ullong old = s->old[i];
380 if (data[i] < old) old = data[i]; //sanitize
382 all += (data[i] -= old);
386 for (i = 0; i < CPU_FIELDCNT; i++) {
387 ullong t = bar_sz * data[i];
388 norm_all += data[i] = t / all;
392 while (norm_all < bar_sz) {
393 unsigned max = frac[0];
395 for (i = 1; i < CPU_FIELDCNT; i++) {
396 if (frac[i] > max) max = frac[i], pos = i;
398 frac[pos] = 0; //avoid bumping up same value twice
403 memset(bar, '.', bar_sz);
404 memset(bar, 'S', data[2]); bar += data[2]; //sys
405 memset(bar, 'U', data[0]); bar += data[0]; //usr
406 memset(bar, 'N', data[1]); bar += data[1]; //nice
407 memset(bar, 'D', data[4]); bar += data[4]; //iowait
408 memset(bar, 'I', data[5]); bar += data[5]; //irq
409 memset(bar, 'i', data[6]); bar += data[6]; //softirq
411 memset(bar, '?', bar_sz);
417 static s_stat* init_cpu(const char *param)
420 cpu_stat *s = xzalloc(sizeof(*s));
421 s->collect = collect_cpu;
422 sz = strtoul(param, NULL, 0); /* param can be "" */
423 if (sz < 10) sz = 10;
424 if (sz > 1000) sz = 1000;
425 s->bar = xzalloc(sz+1);
426 /*s->bar[sz] = '\0'; - xzalloc did it */
437 static void FAST_FUNC collect_int(int_stat *s)
442 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
443 put_question_marks(4);
448 if (data[0] < old) old = data[0]; //sanitize
450 scale(data[0] - old);
453 static s_stat* init_int(const char *param)
455 int_stat *s = xzalloc(sizeof(*s));
456 s->collect = collect_int;
457 if (param[0] == '\0') {
460 int n = xatoi_positive(param);
471 static void FAST_FUNC collect_ctx(ctx_stat *s)
476 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
477 put_question_marks(4);
482 if (data[0] < old) old = data[0]; //sanitize
484 scale(data[0] - old);
487 static s_stat* init_ctx(const char *param UNUSED_PARAM)
489 ctx_stat *s = xzalloc(sizeof(*s));
490 s->collect = collect_ctx;
500 static void FAST_FUNC collect_blk(blk_stat *s)
506 i = rdval_diskstats(get_file(&proc_diskstats), data);
508 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
509 // Linux 2.4 reports bio in Kbytes, convert to sectors:
514 put_question_marks(9);
518 for (i=0; i<2; i++) {
519 ullong old = s->old[i];
520 if (data[i] < old) old = data[i]; //sanitize
524 scale(data[0]*512); // TODO: *sectorsize
529 static s_stat* init_blk(const char *param UNUSED_PARAM)
531 blk_stat *s = xzalloc(sizeof(*s));
532 s->collect = collect_blk;
540 S_STAT_END(fork_stat)
542 static void FAST_FUNC collect_thread_nr(fork_stat *s UNUSED_PARAM)
546 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
547 put_question_marks(4);
553 static void FAST_FUNC collect_fork(fork_stat *s)
558 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
559 put_question_marks(4);
564 if (data[0] < old) old = data[0]; //sanitize
566 scale(data[0] - old);
569 static s_stat* init_fork(const char *param)
571 fork_stat *s = xzalloc(sizeof(*s));
573 s->collect = collect_thread_nr;
575 s->collect = collect_fork;
587 static void FAST_FUNC collect_if(if_stat *s)
592 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
593 put_question_marks(10);
597 for (i=0; i<4; i++) {
598 ullong old = s->old[i];
599 if (data[i] < old) old = data[i]; //sanitize
603 put_c(data[1] ? '*' : ' ');
605 put_c(data[3] ? '*' : ' ');
609 static s_stat* init_if(const char *device)
611 if_stat *s = xzalloc(sizeof(*s));
613 if (!device || !device[0])
615 s->collect = collect_if;
618 s->device_colon = xasprintf("%s:", device);
627 // "Memory" value should not include any caches.
628 // IOW: neither "ls -laR /" nor heavy read/write activity
629 // should affect it. We'd like to also include any
630 // long-term allocated kernel-side mem, but it is hard
631 // to figure out. For now, bufs, cached & slab are
632 // counted as "free" memory
634 //MemTotal: 773280 kB
635 //MemFree: 25912 kB - genuinely free
636 //Buffers: 320672 kB - cache
637 //Cached: 146396 kB - cache
640 //Inactive: 356892 kB
643 //LowTotal: 773280 kB
645 //SwapTotal: 131064 kB
646 //SwapFree: 131064 kB
650 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
651 // but includes dentries and inodes
652 // (== can take arbitrary amount of mem)
653 //CommitLimit: 517704 kB
654 //Committed_AS: 236776 kB
655 //PageTables: 1248 kB
656 //VmallocTotal: 516052 kB
657 //VmallocUsed: 3852 kB
658 //VmallocChunk: 512096 kB
661 //Hugepagesize: 4096 kB
662 static void FAST_FUNC collect_mem(mem_stat *s)
670 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
671 put_question_marks(4);
675 scale(m_total << 10);
679 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
680 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
681 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
682 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
684 put_question_marks(4);
688 m_free += m_bufs + m_cached + m_slab;
691 scale(m_free << 10); break;
693 scale((m_total - m_free) << 10); break;
697 static s_stat* init_mem(const char *param)
699 mem_stat *s = xzalloc(sizeof(*s));
700 s->collect = collect_mem;
709 static void FAST_FUNC collect_swp(swp_stat *s UNUSED_PARAM)
713 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
714 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
716 put_question_marks(4);
719 scale((s_total[0]-s_free[0]) << 10);
722 static s_stat* init_swp(const char *param UNUSED_PARAM)
724 swp_stat *s = xzalloc(sizeof(*s));
725 s->collect = collect_swp;
733 static void FAST_FUNC collect_fd(fd_stat *s UNUSED_PARAM)
737 if (rdval(get_file(&proc_sys_fs_filenr), "", data, 1, 2)) {
738 put_question_marks(4);
742 scale(data[0] - data[1]);
745 static s_stat* init_fd(const char *param UNUSED_PARAM)
747 fd_stat *s = xzalloc(sizeof(*s));
748 s->collect = collect_fd;
756 S_STAT_END(time_stat)
758 static void FAST_FUNC collect_time(time_stat *s)
760 char buf[sizeof("12:34:56.123456")];
762 int us = tv.tv_usec + s->scale/2;
763 time_t t = tv.tv_sec;
771 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
773 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
777 static s_stat* init_time(const char *param)
780 time_stat *s = xzalloc(sizeof(*s));
782 s->collect = collect_time;
783 prec = param[0] - '0';
784 if (prec < 0) prec = 0;
785 else if (prec > 6) prec = 6;
793 static void FAST_FUNC collect_info(s_stat *s)
804 typedef s_stat* init_func(const char *param);
806 // Deprecated %NNNd is to be removed, -d MSEC supersedes it
807 static const char options[] ALIGN1 = "ncmsfixptbdr";
808 static init_func *const init_functions[] = {
823 int nmeter_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
824 int nmeter_main(int argc UNUSED_PARAM, char **argv)
827 s_stat *first = NULL;
837 if (open_read_close("version", buf, sizeof(buf)-1) > 0) {
838 buf[sizeof(buf)-1] = '\0';
839 is26 = (strstr(buf, " 2.4.") == NULL);
842 if (getopt32(argv, "d:", &opt_d))
849 // Can use argv[0] directly, but this will mess up
850 // parameters as seen by e.g. ps. Making a copy...
851 cur = xstrdup(argv[0]);
856 cur = strchr(cur, '%');
859 if (cur[1] == '%') { // %%
860 overlapping_strcpy(cur, cur + 1);
864 *cur++ = '\0'; // overwrite %
866 // format: %[foptstring]
868 p = strchr(options, cur[0]);
870 while (cur[0] != ']') {
875 *cur++ = '\0'; // overwrite [
879 while (cur[0] >= '0' && cur[0] <= '9')
883 p = strchr(options, cur[0]);
884 *cur++ = '\0'; // overwrite format char
888 s = init_functions[p-options](param);
891 /*s->next = NULL; - all initXXX funcs use xzalloc */
898 // %NNNNd or %r option. remove it from string
899 strcpy(prev + strlen(prev), cur);
906 /*s->next = NULL; - all initXXX funcs use xzalloc */
914 // Generate first samples but do not print them, they're bogus
918 gettimeofday(&tv, NULL);
919 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
923 gettimeofday(&tv, NULL);
928 // Negative delta -> no usleep at all
929 // This will hog the CPU but you can have REALLY GOOD
930 // time resolution ;)
931 // TODO: detect and avoid useless updates
932 // (like: nothing happens except time)
935 // can be commented out, will sacrifice sleep time precision a bit
936 gettimeofday(&tv, NULL);
938 rem = delta - ((ullong)tv.tv_sec*1000000 + tv.tv_usec) % deltanz;
940 rem = delta - tv.tv_usec%deltanz;
941 // Sometimes kernel wakes us up just a tiny bit earlier than asked
942 // Do not go to very short sleep in this case
943 if (rem < delta/128) {