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
9 //config: bool "nmeter (10 kb)"
12 //config: Prints selected system stats continuously, one line per update.
14 //applet:IF_NMETER(APPLET(nmeter, BB_DIR_USR_BIN, BB_SUID_DROP))
16 //kbuild:lib-$(CONFIG_NMETER) += nmeter.o
18 //usage:#define nmeter_trivial_usage
19 //usage: "[-d MSEC] FORMAT_STRING"
20 //usage:#define nmeter_full_usage "\n\n"
21 //usage: "Monitor system in real time"
23 //usage: "\n -d MSEC Milliseconds between updates, default:1000, none:-1"
25 //usage: "\nFormat specifiers:"
26 //usage: "\n %Nc or %[cN] CPU. N - bar size (default 10)"
27 //usage: "\n (displays: S:system U:user N:niced D:iowait I:irq i:softirq)"
28 //usage: "\n %[nINTERFACE] Network INTERFACE"
29 //usage: "\n %m Allocated memory"
30 //usage: "\n %[mf] Free memory"
31 //usage: "\n %[mt] Total memory"
32 //usage: "\n %s Allocated swap"
33 //usage: "\n %f Number of used file descriptors"
34 //usage: "\n %Ni Total/specific IRQ rate"
35 //usage: "\n %x Context switch rate"
36 //usage: "\n %p Forks"
37 //usage: "\n %[pn] # of processes"
38 //usage: "\n %b Block io"
39 //usage: "\n %Nt Time (with N decimal points)"
40 //usage: "\n %r Print <cr> instead of <lf> at EOL"
46 // disk_io: (3,0):(22272,17897,410702,4375,54750)
48 //TODO: use sysinfo libc call/syscall, if appropriate
49 // (faster than open/read/close):
50 // sysinfo({uptime=15017, loads=[5728, 15040, 16480]
51 // totalram=2107416576, freeram=211525632, sharedram=0, bufferram=157204480}
52 // totalswap=134209536, freeswap=134209536, procs=157})
55 #include "common_bufsiz.h"
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;
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 )
105 #define proc_stat (G.proc_stat )
106 #define proc_loadavg (G.proc_loadavg )
107 #define proc_net_dev (G.proc_net_dev )
108 #define proc_meminfo (G.proc_meminfo )
109 #define proc_diskstats (G.proc_diskstats )
110 #define proc_sys_fs_filenr (G.proc_sys_fs_filenr)
111 #define outbuf bb_common_bufsiz1
112 #define INIT_G() do { \
113 setup_common_bufsiz(); \
114 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
115 cur_outbuf = outbuf; \
116 G.final_char = '\n'; \
117 G.deltanz = G.delta = 1000000; \
120 static inline void reset_outbuf(void)
125 static inline int outbuf_count(void)
127 return cur_outbuf - outbuf;
130 static void print_outbuf(void)
132 int sz = cur_outbuf - outbuf;
134 xwrite(STDOUT_FILENO, outbuf, sz);
139 static void put(const char *s)
141 char *p = cur_outbuf;
142 int sz = outbuf + COMMON_BUFSIZE - p;
143 while (*s && --sz >= 0)
148 static void put_c(char c)
150 if (cur_outbuf < outbuf + COMMON_BUFSIZE)
154 static void put_question_marks(int count)
160 static void readfile_z(proc_file *pf, const char* fname)
162 // open_read_close() will do two reads in order to be sure we are at EOF,
163 // and we don't need/want that.
171 buf = xmalloc(PROC_MIN_FILE_SIZE);
172 sz = PROC_MIN_FILE_SIZE;
175 fd = xopen(fname, O_RDONLY);
177 rdsz = read(fd, buf, sz-1);
180 if (rdsz == sz-1 && sz < PROC_MAX_FILE_SIZE) {
182 buf = xrealloc(buf, sz);
191 static const char* get_file(proc_file *pf)
193 if (pf->last_gen != gen) {
195 readfile_z(pf, proc_name[pf - &first_proc_file]);
200 static ullong read_after_slash(const char *p)
204 return strtoull(p+1, NULL, 10);
212 // Reads decimal values from line. Values start after key, for example:
213 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
214 // Values are stored in vec[].
215 // posbits is a bit lit of positions we are interested in.
216 // for example: 00100110 - we want 1st, 2nd and 5th value.
217 // posbits.bit0 encodes conversion type.
218 static int rdval(const char* p, const char* key, ullong *vec, long posbits)
228 while (*p == ' ' || *p == '\t') p++;
229 if (*p == '\n' || *p == '\0') break;
231 if (curpos & posbits) { // read this value
232 *vec++ = (posbits & 1) == conv_decimal ?
233 strtoull(p, NULL, 10) :
239 while (*p > ' ') // skip over the value
246 // Parses files with lines like "... ... ... 3/148 ...."
247 static int rdval_loadavg(const char* p, ullong *vec, long posbits)
250 result = rdval(p, "", vec, posbits | conv_slash);
254 // Parses /proc/diskstats
255 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
256 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
257 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
258 // Linux 3.0 (maybe earlier) started printing full stats for hda1 too.
259 // Had to add code which skips such devices.
260 static int rdval_diskstats(const char* p, ullong *vec)
263 unsigned devname_len = 0;
270 while (*p == ' ' || *p == '\t')
279 if (value_idx == 3) {
280 char *end = strchrnul(p, ' ');
281 /* If this a hda1-like device (same prefix as last one + digit)? */
282 if (devname_len && strncmp(devname, p, devname_len) == 0 && isdigit(p[devname_len])) {
284 goto skip_line; /* skip entire line */
286 /* It is not. Remember the name for future checks */
287 devname_len = end - p;
288 if (devname_len > sizeof(devname)-1)
289 devname_len = sizeof(devname)-1;
290 strncpy(devname, p, devname_len);
291 /* devname[devname_len] = '\0'; - not really needed */
294 if (value_idx == 6) {
295 // TODO: *sectorsize (don't know how to find out sectorsize)
296 vec[0] += strtoull(p, NULL, 10);
298 if (value_idx == 10) {
299 // TODO: *sectorsize (don't know how to find out sectorsize)
300 vec[1] += strtoull(p, NULL, 10);
302 while (*p != '\n' && *p != '\0')
306 while ((unsigned char)(*p) > ' ') // skip over value
312 static void scale(ullong ul)
316 /* see http://en.wikipedia.org/wiki/Tera */
317 smart_ulltoa4(ul, buf, " kmgtpezy")[0] = '\0';
323 struct s_stat *next; \
324 void (*collect)(struct a *s) FAST_FUNC; \
326 #define S_STAT_END(a) } a;
331 static void FAST_FUNC collect_literal(s_stat *s UNUSED_PARAM)
335 static s_stat* init_literal(void)
337 s_stat *s = xzalloc(sizeof(*s));
338 s->collect = collect_literal;
342 static s_stat* init_cr(const char *param UNUSED_PARAM)
348 // user nice system idle iowait irq softirq (last 3 only in 2.6)
349 //cpu 649369 0 341297 4336769 11640 7122 1183
350 //cpuN 649369 0 341297 4336769 11640 7122 1183
351 enum { CPU_FIELDCNT = 7 };
353 ullong old[CPU_FIELDCNT];
358 static void FAST_FUNC collect_cpu(cpu_stat *s)
360 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
361 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
364 int bar_sz = s->bar_sz;
368 if (rdval(get_file(&proc_stat), "cpu ", data, 0
377 put_question_marks(bar_sz);
381 for (i = 0; i < CPU_FIELDCNT; i++) {
382 ullong old = s->old[i];
383 if (data[i] < old) old = data[i]; //sanitize
385 all += (data[i] -= old);
389 for (i = 0; i < CPU_FIELDCNT; i++) {
390 ullong t = bar_sz * data[i];
391 norm_all += data[i] = t / all;
395 while (norm_all < bar_sz) {
396 unsigned max = frac[0];
398 for (i = 1; i < CPU_FIELDCNT; i++) {
399 if (frac[i] > max) max = frac[i], pos = i;
401 frac[pos] = 0; //avoid bumping up same value twice
406 memset(bar, '.', bar_sz);
407 memset(bar, 'S', data[2]); bar += data[2]; //sys
408 memset(bar, 'U', data[0]); bar += data[0]; //usr
409 memset(bar, 'N', data[1]); bar += data[1]; //nice
410 memset(bar, 'D', data[4]); bar += data[4]; //iowait
411 memset(bar, 'I', data[5]); bar += data[5]; //irq
412 memset(bar, 'i', data[6]); bar += data[6]; //softirq
414 memset(bar, '?', bar_sz);
419 static s_stat* init_cpu(const char *param)
423 sz = strtoul(param, NULL, 0); /* param can be "" */
424 if (sz < 10) sz = 10;
425 if (sz > 1000) sz = 1000;
426 s = xzalloc(sizeof(*s) + sz);
427 /*s->bar[sz] = '\0'; - xzalloc did it */
429 s->collect = collect_cpu;
438 static void FAST_FUNC collect_int(int_stat *s)
443 if (rdval(get_file(&proc_stat), "intr", data, 1 << s->no)) {
444 put_question_marks(4);
449 if (data[0] < old) old = data[0]; //sanitize
451 scale(data[0] - old);
454 static s_stat* init_int(const char *param)
456 int_stat *s = xzalloc(sizeof(*s));
457 s->collect = collect_int;
458 if (param[0] == '\0') {
461 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 << 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;
499 static void FAST_FUNC collect_blk(blk_stat *s)
505 i = rdval_diskstats(get_file(&proc_diskstats), data);
507 i = rdval(get_file(&proc_stat), s->lookfor, data, 0
511 // Linux 2.4 reports bio in Kbytes, convert to sectors:
516 put_question_marks(9);
520 for (i=0; i<2; i++) {
521 ullong old = s->old[i];
522 if (data[i] < old) old = data[i]; //sanitize
526 scale(data[0]*512); // TODO: *sectorsize
531 static s_stat* init_blk(const char *param UNUSED_PARAM)
533 blk_stat *s = xzalloc(sizeof(*s));
534 s->collect = collect_blk;
541 S_STAT_END(fork_stat)
543 static void FAST_FUNC collect_thread_nr(fork_stat *s UNUSED_PARAM)
547 if (rdval_loadavg(get_file(&proc_loadavg), data, 1 << 4)) {
548 put_question_marks(4);
554 static void FAST_FUNC collect_fork(fork_stat *s)
559 if (rdval(get_file(&proc_stat), "processes", data, 1 << 1)) {
560 put_question_marks(4);
565 if (data[0] < old) old = data[0]; //sanitize
567 scale(data[0] - old);
570 static s_stat* init_fork(const char *param)
572 fork_stat *s = xzalloc(sizeof(*s));
574 s->collect = collect_thread_nr;
576 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, 0
598 put_question_marks(10);
602 for (i=0; i<4; i++) {
603 ullong old = s->old[i];
604 if (data[i] < old) old = data[i]; //sanitize
608 put_c(data[1] ? '*' : ' ');
610 put_c(data[3] ? '*' : ' ');
614 static s_stat* init_if(const char *device)
616 if_stat *s = xzalloc(sizeof(*s));
618 if (!device || !device[0])
620 s->collect = collect_if;
623 s->device_colon = xasprintf("%s:", device);
631 // "Memory" value should not include any caches.
632 // IOW: neither "ls -laR /" nor heavy read/write activity
633 // should affect it. We'd like to also include any
634 // long-term allocated kernel-side mem, but it is hard
635 // to figure out. For now, bufs, cached & slab are
636 // counted as "free" memory
638 //MemTotal: 773280 kB
639 //MemFree: 25912 kB - genuinely free
640 //Buffers: 320672 kB - cache
641 //Cached: 146396 kB - cache
644 //Inactive: 356892 kB
647 //LowTotal: 773280 kB
649 //SwapTotal: 131064 kB
650 //SwapFree: 131064 kB
654 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
655 // but includes dentries and inodes
656 // (== can take arbitrary amount of mem)
657 //CommitLimit: 517704 kB
658 //Committed_AS: 236776 kB
659 //PageTables: 1248 kB
660 //VmallocTotal: 516052 kB
661 //VmallocUsed: 3852 kB
662 //VmallocChunk: 512096 kB
665 //Hugepagesize: 4096 kB
666 static void FAST_FUNC collect_mem(mem_stat *s)
674 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1 << 1)) {
675 put_question_marks(4);
679 scale(m_total << 10);
683 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1 << 1)
684 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1 << 1)
685 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1 << 1)
686 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1 << 1)
688 put_question_marks(4);
692 m_free += m_bufs + m_cached + m_slab;
695 scale(m_free << 10); break;
697 scale((m_total - m_free) << 10); break;
701 static s_stat* init_mem(const char *param)
703 mem_stat *s = xzalloc(sizeof(*s));
704 s->collect = collect_mem;
712 static void FAST_FUNC collect_swp(swp_stat *s UNUSED_PARAM)
716 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1 << 1)
717 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1 << 1)
719 put_question_marks(4);
722 scale((s_total[0]-s_free[0]) << 10);
725 static s_stat* init_swp(const char *param UNUSED_PARAM)
727 swp_stat *s = xzalloc(sizeof(*s));
728 s->collect = collect_swp;
735 static void FAST_FUNC collect_fd(fd_stat *s UNUSED_PARAM)
739 if (rdval(get_file(&proc_sys_fs_filenr), "", data, 0
743 put_question_marks(4);
747 scale(data[0] - data[1]);
750 static s_stat* init_fd(const char *param UNUSED_PARAM)
752 fd_stat *s = xzalloc(sizeof(*s));
753 s->collect = collect_fd;
760 S_STAT_END(time_stat)
762 static void FAST_FUNC collect_time(time_stat *s)
764 char buf[sizeof("12:34:56.123456")];
766 unsigned us = tv.tv_usec + s->scale/2;
767 time_t t = tv.tv_sec;
775 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
777 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
781 static s_stat* init_time(const char *param)
784 time_stat *s = xzalloc(sizeof(*s));
786 s->collect = collect_time;
787 prec = param[0] - '0';
788 if (prec < 0) prec = 0;
789 else if (prec > 6) prec = 6;
797 static void FAST_FUNC collect_info(s_stat *s)
807 typedef s_stat* init_func(const char *param);
809 static const char options[] ALIGN1 = "ncmsfixptbr";
810 static init_func *const init_functions[] = {
824 int nmeter_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
825 int nmeter_main(int argc UNUSED_PARAM, char **argv)
828 s_stat *first = NULL;
838 if (open_read_close("version", buf, sizeof(buf)-1) > 0) {
839 buf[sizeof(buf)-1] = '\0';
840 is26 = (strstr(buf, " 2.4.") == NULL);
843 if (getopt32(argv, "d:", &opt_d)) {
844 G.delta = xatoi(opt_d) * 1000;
845 G.deltanz = G.delta > 0 ? G.delta : 1;
846 need_seconds = (1000000 % G.deltanz) != 0;
853 // Can use argv[0] directly, but this will mess up
854 // parameters as seen by e.g. ps. Making a copy...
855 cur = xstrdup(argv[0]);
860 cur = strchr(cur, '%');
863 if (cur[1] == '%') { // %%
864 overlapping_strcpy(cur, cur + 1);
868 *cur++ = '\0'; // overwrite %
870 // format: %[foptstring]
872 p = strchr(options, cur[0]);
874 while (cur[0] != ']') {
879 *cur++ = '\0'; // overwrite [
883 while (cur[0] >= '0' && cur[0] <= '9')
887 p = strchr(options, cur[0]);
888 *cur++ = '\0'; // overwrite format char
892 s = init_functions[p-options](param);
895 /*s->next = NULL; - all initXXX funcs use xzalloc */
902 // %r option. remove it from string
903 overlapping_strcpy(prev + strlen(prev), cur);
910 /*s->next = NULL; - all initXXX funcs use xzalloc */
918 // Generate first samples but do not print them, they're bogus
922 gettimeofday(&tv, NULL);
923 usleep(G.delta > 1000000 ? 1000000 : G.delta - tv.tv_usec % G.deltanz);
927 gettimeofday(&tv, NULL);
932 // Negative delta -> no usleep at all
933 // This will hog the CPU but you can have REALLY GOOD
934 // time resolution ;)
935 // TODO: detect and avoid useless updates
936 // (like: nothing happens except time)
939 // can be commented out, will sacrifice sleep time precision a bit
940 gettimeofday(&tv, NULL);
942 rem = G.delta - ((ullong)tv.tv_sec*1000000 + tv.tv_usec) % G.deltanz;
944 rem = G.delta - (unsigned)tv.tv_usec % G.deltanz;
945 // Sometimes kernel wakes us up just a tiny bit earlier than asked
946 // Do not go to very short sleep in this case
947 if (rem < (unsigned)G.delta / 128) {