2 ** Licensed under the GPL v2, see the file LICENSE in this tarball
4 ** Based on nanotop.c from floppyfw project
6 ** Contact me: vda.linux@googlemail.com */
12 // disk_io: (3,0):(22272,17897,410702,4375,54750)
14 //TODO: use sysinfo libc call/syscall, if appropriate
15 // (faster than open/read/close):
16 // sysinfo({uptime=15017, loads=[5728, 15040, 16480]
17 // totalram=2107416576, freeram=211525632, sharedram=0, bufferram=157204480}
18 // totalswap=134209536, freeswap=134209536, procs=157})
23 typedef unsigned long long ullong;
25 enum { PROC_FILE_SIZE = 4096 };
27 typedef struct proc_file {
33 static const char *const proc_name[] = {
34 "stat", // Must match the order of proc_file's!
43 // Sample generation flip-flop
45 // Linux 2.6? (otherwise assumes 2.4)
47 // 1 if sample delay is not an integer fraction of a second
48 smallint need_seconds;
50 const char *final_str;
54 #define first_proc_file proc_stat
55 proc_file proc_stat; // Must match the order of proc_name's!
56 proc_file proc_loadavg;
57 proc_file proc_net_dev;
58 proc_file proc_meminfo;
59 proc_file proc_diskstats;
60 proc_file proc_sys_fs_filenr;
62 #define G (*ptr_to_globals)
64 #define is26 (G.is26 )
65 #define need_seconds (G.need_seconds )
66 #define cur_outbuf (G.cur_outbuf )
67 #define final_str (G.final_str )
68 #define delta (G.delta )
69 #define deltanz (G.deltanz )
71 #define proc_stat (G.proc_stat )
72 #define proc_loadavg (G.proc_loadavg )
73 #define proc_net_dev (G.proc_net_dev )
74 #define proc_meminfo (G.proc_meminfo )
75 #define proc_diskstats (G.proc_diskstats )
76 #define proc_sys_fs_filenr (G.proc_sys_fs_filenr)
77 #define INIT_G() do { \
78 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
79 cur_outbuf = outbuf; \
81 deltanz = delta = 1000000; \
84 // We depend on this being a char[], not char* - we take sizeof() of it
85 #define outbuf bb_common_bufsiz1
87 static inline void reset_outbuf(void)
92 static inline int outbuf_count(void)
94 return cur_outbuf - outbuf;
97 static void print_outbuf(void)
99 int sz = cur_outbuf - outbuf;
101 xwrite(STDOUT_FILENO, outbuf, sz);
106 static void put(const char *s)
109 if (sz > outbuf + sizeof(outbuf) - cur_outbuf)
110 sz = outbuf + sizeof(outbuf) - cur_outbuf;
111 memcpy(cur_outbuf, s, sz);
115 static void put_c(char c)
117 if (cur_outbuf < outbuf + sizeof(outbuf))
121 static void put_question_marks(int count)
127 static void readfile_z(char *buf, int sz, const char* fname)
129 // open_read_close() will do two reads in order to be sure we are at EOF,
130 // and we don't need/want that.
131 // sz = open_read_close(fname, buf, sz-1);
133 int fd = xopen(fname, O_RDONLY);
136 sz = read(fd, buf, sz-1);
137 if (sz > 0) buf[sz] = '\0';
142 static const char* get_file(proc_file *pf)
144 if (pf->last_gen != gen) {
146 // We allocate PROC_FILE_SIZE bytes. This wastes memory,
147 // but allows us to allocate only once (at first sample)
148 // per proc file, and reuse buffer for each sample
150 pf->file = xmalloc(PROC_FILE_SIZE);
151 readfile_z(pf->file, PROC_FILE_SIZE, proc_name[pf - &first_proc_file]);
156 static inline ullong read_after_slash(const char *p)
160 return strtoull(p+1, NULL, 10);
163 enum conv_type { conv_decimal, conv_slash };
165 // Reads decimal values from line. Values start after key, for example:
166 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
167 // Values are stored in vec[]. arg_ptr has list of positions
168 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
169 static int vrdval(const char* p, const char* key,
170 enum conv_type conv, ullong *vec, va_list arg_ptr)
180 indexnext = va_arg(arg_ptr, int);
182 while (*p == ' ' || *p == '\t') p++;
183 if (*p == '\n' || *p == '\0') break;
185 if (indexline == indexnext) { // read this value
186 *vec++ = conv==conv_decimal ?
187 strtoull(p, NULL, 10) :
189 indexnext = va_arg(arg_ptr, int);
191 while (*p > ' ') p++; // skip over value
197 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
198 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
199 // value# start with 1
200 static int rdval(const char* p, const char* key, ullong *vec, ...)
205 va_start(arg_ptr, vec);
206 result = vrdval(p, key, conv_decimal, vec, arg_ptr);
212 // Parses files with lines like "... ... ... 3/148 ...."
213 static int rdval_loadavg(const char* p, ullong *vec, ...)
218 va_start(arg_ptr, vec);
219 result = vrdval(p, "", conv_slash, vec, arg_ptr);
225 // Parses /proc/diskstats
226 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
227 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
228 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
229 static int rdval_diskstats(const char* p, ullong *vec)
231 ullong rd = 0; // to avoid "warning: 'rd' might be used uninitialized"
237 while (*p == ' ' || *p == '\t') p++;
238 if (*p == '\0') break;
244 if (indexline == 6) {
245 rd = strtoull(p, NULL, 10);
246 } else if (indexline == 10) {
247 vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize)
248 vec[1] += strtoull(p, NULL, 10);
249 while (*p != '\n' && *p != '\0') p++;
252 while (*p > ' ') p++; // skip over value
257 static void scale(ullong ul)
261 /* see http://en.wikipedia.org/wiki/Tera */
262 smart_ulltoa4(ul, buf, " kmgtpezy");
270 struct s_stat *next; \
271 void (*collect)(struct a *s); \
273 #define S_STAT_END(a) } a;
278 static void collect_literal(s_stat *s ATTRIBUTE_UNUSED)
282 static s_stat* init_literal(void)
284 s_stat *s = xmalloc(sizeof(s_stat));
285 s->collect = collect_literal;
289 static s_stat* init_delay(const char *param)
291 delta = bb_strtoi(param, NULL, 0) * 1000;
292 deltanz = delta > 0 ? delta : 1;
293 need_seconds = (1000000%deltanz) != 0;
297 static s_stat* init_cr(const char *param ATTRIBUTE_UNUSED)
304 // user nice system idle iowait irq softirq (last 3 only in 2.6)
305 //cpu 649369 0 341297 4336769 11640 7122 1183
306 //cpuN 649369 0 341297 4336769 11640 7122 1183
307 enum { CPU_FIELDCNT = 7 };
309 ullong old[CPU_FIELDCNT];
315 static void collect_cpu(cpu_stat *s)
317 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
318 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
321 int bar_sz = s->bar_sz;
325 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
326 put_question_marks(bar_sz);
330 for (i = 0; i < CPU_FIELDCNT; i++) {
331 ullong old = s->old[i];
332 if (data[i] < old) old = data[i]; //sanitize
334 all += (data[i] -= old);
338 for (i = 0; i < CPU_FIELDCNT; i++) {
339 ullong t = bar_sz * data[i];
340 norm_all += data[i] = t / all;
344 while (norm_all < bar_sz) {
345 unsigned max = frac[0];
347 for (i = 1; i < CPU_FIELDCNT; i++) {
348 if (frac[i] > max) max = frac[i], pos = i;
350 frac[pos] = 0; //avoid bumping up same value twice
355 memset(bar, '.', bar_sz);
356 memset(bar, 'S', data[2]); bar += data[2]; //sys
357 memset(bar, 'U', data[0]); bar += data[0]; //usr
358 memset(bar, 'N', data[1]); bar += data[1]; //nice
359 memset(bar, 'D', data[4]); bar += data[4]; //iowait
360 memset(bar, 'I', data[5]); bar += data[5]; //irq
361 memset(bar, 'i', data[6]); bar += data[6]; //softirq
363 memset(bar, '?', bar_sz);
369 static s_stat* init_cpu(const char *param)
372 cpu_stat *s = xmalloc(sizeof(cpu_stat));
373 s->collect = collect_cpu;
374 sz = strtol(param, NULL, 0);
375 if (sz < 10) sz = 10;
376 if (sz > 1000) sz = 1000;
377 s->bar = xmalloc(sz+1);
389 static void collect_int(int_stat *s)
394 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
395 put_question_marks(4);
400 if (data[0] < old) old = data[0]; //sanitize
402 scale(data[0] - old);
405 static s_stat* init_int(const char *param)
407 int_stat *s = xmalloc(sizeof(int_stat));
408 s->collect = collect_int;
409 if (param[0]=='\0') {
412 int n = strtoul(param, NULL, 0);
423 static void collect_ctx(ctx_stat *s)
428 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
429 put_question_marks(4);
434 if (data[0] < old) old = data[0]; //sanitize
436 scale(data[0] - old);
439 static s_stat* init_ctx(const char *param ATTRIBUTE_UNUSED)
441 ctx_stat *s = xmalloc(sizeof(ctx_stat));
442 s->collect = collect_ctx;
452 static void collect_blk(blk_stat *s)
458 i = rdval_diskstats(get_file(&proc_diskstats), data);
460 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
461 // Linux 2.4 reports bio in Kbytes, convert to sectors:
466 put_question_marks(9);
470 for (i=0; i<2; i++) {
471 ullong old = s->old[i];
472 if (data[i] < old) old = data[i]; //sanitize
476 scale(data[0]*512); // TODO: *sectorsize
481 static s_stat* init_blk(const char *param ATTRIBUTE_UNUSED)
483 blk_stat *s = xmalloc(sizeof(blk_stat));
484 s->collect = collect_blk;
492 S_STAT_END(fork_stat)
494 static void collect_thread_nr(fork_stat *s ATTRIBUTE_UNUSED)
498 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
499 put_question_marks(4);
505 static void collect_fork(fork_stat *s)
510 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
511 put_question_marks(4);
516 if (data[0] < old) old = data[0]; //sanitize
518 scale(data[0] - old);
521 static s_stat* init_fork(const char *param)
523 fork_stat *s = xmalloc(sizeof(fork_stat));
525 s->collect = collect_thread_nr;
527 s->collect = collect_fork;
539 static void collect_if(if_stat *s)
544 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
545 put_question_marks(10);
549 for (i=0; i<4; i++) {
550 ullong old = s->old[i];
551 if (data[i] < old) old = data[i]; //sanitize
555 put_c(data[1] ? '*' : ' ');
557 put_c(data[3] ? '*' : ' ');
561 static s_stat* init_if(const char *device)
563 if_stat *s = xmalloc(sizeof(if_stat));
565 if (!device || !device[0])
567 s->collect = collect_if;
570 s->device_colon = xmalloc(strlen(device)+2);
571 strcpy(s->device_colon, device);
572 strcat(s->device_colon, ":");
581 // "Memory" value should not include any caches.
582 // IOW: neither "ls -laR /" nor heavy read/write activity
583 // should affect it. We'd like to also include any
584 // long-term allocated kernel-side mem, but it is hard
585 // to figure out. For now, bufs, cached & slab are
586 // counted as "free" memory
588 //MemTotal: 773280 kB
589 //MemFree: 25912 kB - genuinely free
590 //Buffers: 320672 kB - cache
591 //Cached: 146396 kB - cache
594 //Inactive: 356892 kB
597 //LowTotal: 773280 kB
599 //SwapTotal: 131064 kB
600 //SwapFree: 131064 kB
604 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
605 // but includes dentries and inodes
606 // (== can take arbitrary amount of mem)
607 //CommitLimit: 517704 kB
608 //Committed_AS: 236776 kB
609 //PageTables: 1248 kB
610 //VmallocTotal: 516052 kB
611 //VmallocUsed: 3852 kB
612 //VmallocChunk: 512096 kB
615 //Hugepagesize: 4096 kB
616 static void collect_mem(mem_stat *s)
624 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
625 put_question_marks(4);
629 scale(m_total << 10);
633 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
634 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
635 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
636 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
638 put_question_marks(4);
642 m_free += m_bufs + m_cached + m_slab;
645 scale(m_free << 10); break;
647 scale((m_total - m_free) << 10); break;
651 static s_stat* init_mem(const char *param)
653 mem_stat *s = xmalloc(sizeof(mem_stat));
654 s->collect = collect_mem;
663 static void collect_swp(swp_stat *s ATTRIBUTE_UNUSED)
667 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
668 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
670 put_question_marks(4);
673 scale((s_total[0]-s_free[0]) << 10);
676 static s_stat* init_swp(const char *param ATTRIBUTE_UNUSED)
678 swp_stat *s = xmalloc(sizeof(swp_stat));
679 s->collect = collect_swp;
687 static void collect_fd(fd_stat *s ATTRIBUTE_UNUSED)
691 if (rdval(get_file(&proc_sys_fs_filenr), "", data, 1, 2)) {
692 put_question_marks(4);
696 scale(data[0] - data[1]);
699 static s_stat* init_fd(const char *param ATTRIBUTE_UNUSED)
701 fd_stat *s = xmalloc(sizeof(fd_stat));
702 s->collect = collect_fd;
710 S_STAT_END(time_stat)
712 static void collect_time(time_stat *s)
714 char buf[sizeof("12:34:56.123456")];
716 int us = tv.tv_usec + s->scale/2;
717 time_t t = tv.tv_sec;
725 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
727 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
731 static s_stat* init_time(const char *param)
734 time_stat *s = xmalloc(sizeof(time_stat));
736 s->collect = collect_time;
738 if (prec < 0) prec = 0;
739 else if (prec > 6) prec = 6;
747 static void collect_info(s_stat *s)
758 typedef s_stat* init_func(const char *param);
760 static const char options[] ALIGN1 = "ncmsfixptbdr";
761 static init_func *const init_functions[] = {
776 int nmeter_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
777 int nmeter_main(int argc, char **argv)
780 s_stat *first = NULL;
792 if (open_read_close("version", buf, sizeof(buf)) > 0)
793 is26 = (strstr(buf, " 2.4.")==NULL);
795 // Can use argv[1] directly, but this will mess up
796 // parameters as seen by e.g. ps. Making a copy...
797 cur = xstrdup(argv[1]);
802 cur = strchr(cur, '%');
805 if (cur[1] == '%') { // %%
810 *cur++ = '\0'; // overwrite %
812 // format: %[foptstring]
814 p = strchr(options, cur[0]);
816 while (cur[0] != ']') {
821 *cur++ = '\0'; // overwrite [
825 while (cur[0] >= '0' && cur[0] <= '9')
829 p = strchr(options, cur[0]);
830 *cur++ = '\0'; // overwrite format char
834 s = init_functions[p-options](param);
844 // %NNNNd or %r option. remove it from string
845 strcpy(prev + strlen(prev), cur);
860 // Generate first samples but do not print them, they're bogus
864 gettimeofday(&tv, NULL);
865 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
869 gettimeofday(&tv, NULL);
874 // Negative delta -> no usleep at all
875 // This will hog the CPU but you can have REALLY GOOD
876 // time resolution ;)
877 // TODO: detect and avoid useless updates
878 // (like: nothing happens except time)
881 // can be commented out, will sacrifice sleep time precision a bit
882 gettimeofday(&tv, NULL);
884 rem = delta - ((ullong)tv.tv_sec*1000000 + tv.tv_usec) % deltanz;
886 rem = delta - tv.tv_usec%deltanz;
887 // Sometimes kernel wakes us up just a tiny bit earlier than asked
888 // Do not go to very short sleep in this case
889 if (rem < delta/128) {