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)
18 typedef unsigned long long ullong;
19 typedef unsigned long ulong;
21 enum { proc_file_size = 4096 };
23 typedef struct proc_file {
29 static proc_file proc_stat = { "/proc/stat", -1 };
30 static proc_file proc_loadavg = { "/proc/loadavg", -1 };
31 static proc_file proc_net_dev = { "/proc/net/dev", -1 };
32 static proc_file proc_meminfo = { "/proc/meminfo", -1 };
33 static proc_file proc_diskstats = { "/proc/diskstats", -1 };
36 // Linux 2.6? (otherwise assumes 2.4)
38 static struct timeval tv;
39 static int delta = 1000000;
40 static int deltanz = 1000000;
41 static int need_seconds = 0;
42 static char *final_str = "\n";
44 // We depend on this being a char[], not char* - we take sizeof() of it
45 #define outbuf bb_common_bufsiz1
46 static char *cur_outbuf = outbuf;
49 static inline void reset_outbuf(void)
54 static inline int outbuf_count(void)
56 return cur_outbuf - outbuf;
59 static void print_outbuf(void)
61 int sz = cur_outbuf - outbuf;
68 static void put(const char *s)
71 if (sz > outbuf + sizeof(outbuf) - cur_outbuf)
72 sz = outbuf + sizeof(outbuf) - cur_outbuf;
73 memcpy(cur_outbuf, s, sz);
77 static void put_c(char c)
79 if (cur_outbuf < outbuf + sizeof(outbuf))
83 static void put_question_marks(int count)
89 static int readfile_z(char *buf, int sz, const char* fname)
92 fd = xopen(fname, O_RDONLY);
93 // We are not checking for short reads (valid only because
94 // we are reading /proc files)
95 sz = read(fd, buf, sz-1);
105 static const char* get_file(proc_file *pf)
107 if (pf->gen != gen) {
109 // We allocate proc_file_size bytes. This wastes memory,
110 // but allows us to allocate only once (at first sample)
111 // per proc file, and reuse buffer for each sample
113 pf->file = (char*)xmalloc(proc_file_size);
114 readfile_z(pf->file, proc_file_size, pf->name);
119 static inline ullong read_after_slash(const char *p)
123 return strtoull(p+1, NULL, 10);
126 enum conv_type { conv_decimal, conv_slash };
128 // Reads decimal values from line. Values start after key, for example:
129 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
130 // Values are stored in vec[]. arg_ptr has list of positions
131 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
132 static int vrdval(const char* p, const char* key,
133 enum conv_type conv, ullong *vec, va_list arg_ptr)
143 indexnext = va_arg(arg_ptr, int);
145 while (*p == ' ' || *p == '\t') p++;
146 if (*p == '\n' || *p == '\0') break;
148 if (indexline == indexnext) { // read this value
149 *vec++ = conv==conv_decimal ?
150 strtoull(p, NULL, 10) :
152 indexnext = va_arg(arg_ptr, int);
154 while (*p > ' ') p++; // skip over value
160 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
161 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
162 // value# start with 1
163 static int rdval(const char* p, const char* key, ullong *vec, ...)
168 va_start(arg_ptr, vec);
169 result = vrdval(p, key, conv_decimal, vec, arg_ptr);
175 // Parses files with lines like "... ... ... 3/148 ...."
176 static int rdval_loadavg(const char* p, ullong *vec, ...)
181 va_start(arg_ptr, vec);
182 result = vrdval(p, "", conv_slash, vec, arg_ptr);
188 // Parses /proc/diskstats
189 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
190 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
191 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
192 static int rdval_diskstats(const char* p, ullong *vec)
194 ullong rd = 0; // to avoid "warning: 'rd' might be used uninitialized"
200 while (*p == ' ' || *p == '\t') p++;
201 if (*p == '\0') break;
207 if (indexline == 6) {
208 rd = strtoull(p, NULL, 10);
209 } else if (indexline == 10) {
210 vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize)
211 vec[1] += strtoull(p, NULL, 10);
212 while (*p != '\n' && *p != '\0') p++;
215 while (*p > ' ') p++; // skip over value
220 static void scale(ullong ul)
227 if (ul > 9999*10) { // do not scale if 9999 or less
228 while (ul >= 10000) {
233 v = ul; // ullong divisions are expensive, avoid them
236 if (!idx) { // 9999 or less: use 1234 format
237 c = buf[0] = " 123456789"[v/10000];
238 if (c!=' ') fmt = "0123456789";
239 c = buf[1] = fmt[v/1000%10];
240 if (c!=' ') fmt = "0123456789";
241 buf[2] = fmt[v/100%10];
242 buf[3] = "0123456789"[v/10%10];
244 if (v>=10*10) { // scaled value is >=10: use 123M format
245 c = buf[0] = " 123456789"[v/1000];
246 if (c!=' ') fmt = "0123456789";
247 buf[1] = fmt[v/100%10];
248 buf[2] = "0123456789"[v/10%10];
249 } else { // scaled value is <10: use 1.2M format
250 buf[0] = "0123456789"[v/10];
252 buf[2] = "0123456789"[v%10];
254 // see http://en.wikipedia.org/wiki/Tera
255 buf[3] = " kMGTPEZY"[idx];
264 struct s_stat *next; \
265 void (*collect)(struct a *s); \
267 #define S_STAT_END(a) } a;
272 static void collect_literal(s_stat *s)
276 static s_stat* init_literal(void)
278 s_stat *s = xmalloc(sizeof(s_stat));
279 s->collect = collect_literal;
283 static s_stat* init_delay(const char *param)
285 delta = strtol(param, NULL, 0)*1000;
286 deltanz = delta > 0 ? delta : 1;
287 need_seconds = (1000000%deltanz) != 0;
291 static s_stat* init_cr(const char *param)
298 // user nice system idle iowait irq softirq (last 3 only in 2.6)
299 //cpu 649369 0 341297 4336769 11640 7122 1183
300 //cpuN 649369 0 341297 4336769 11640 7122 1183
301 enum { CPU_FIELDCNT = 7 };
303 ullong old[CPU_FIELDCNT];
309 static void collect_cpu(cpu_stat *s)
311 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
312 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
315 int bar_sz = s->bar_sz;
319 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
320 put_question_marks(bar_sz);
324 for (i=0; i<CPU_FIELDCNT; i++) {
325 ullong old = s->old[i];
326 if (data[i] < old) old = data[i]; //sanitize
328 all += (data[i] -= old);
332 for (i=0; i<CPU_FIELDCNT; i++) {
333 ullong t = bar_sz * data[i];
334 norm_all += data[i] = t / all;
338 while (norm_all < bar_sz) {
339 unsigned max = frac[0];
341 for (i=1; i<CPU_FIELDCNT; i++) {
342 if (frac[i] > max) max = frac[i], pos = i;
344 frac[pos] = 0; //avoid bumping up same value twice
349 memset(bar, '.', bar_sz);
350 memset(bar, 'S', data[2]); bar += data[2]; //sys
351 memset(bar, 'U', data[0]); bar += data[0]; //usr
352 memset(bar, 'N', data[1]); bar += data[1]; //nice
353 memset(bar, 'D', data[4]); bar += data[4]; //iowait
354 memset(bar, 'I', data[5]); bar += data[5]; //irq
355 memset(bar, 'i', data[6]); bar += data[6]; //softirq
357 memset(bar, '?', bar_sz);
363 static s_stat* init_cpu(const char *param)
366 cpu_stat *s = xmalloc(sizeof(cpu_stat));
367 s->collect = collect_cpu;
368 sz = strtol(param, NULL, 0);
369 if (sz < 10) sz = 10;
370 if (sz > 1000) sz = 1000;
371 s->bar = xmalloc(sz+1);
383 static void collect_int(int_stat *s)
388 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
389 put_question_marks(4);
394 if (data[0] < old) old = data[0]; //sanitize
396 scale(data[0] - old);
399 static s_stat* init_int(const char *param)
401 int_stat *s = xmalloc(sizeof(int_stat));
402 s->collect = collect_int;
403 if (param[0]=='\0') {
406 int n = strtoul(param, NULL, 0);
417 static void collect_ctx(ctx_stat *s)
422 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
423 put_question_marks(4);
428 if (data[0] < old) old = data[0]; //sanitize
430 scale(data[0] - old);
433 static s_stat* init_ctx(const char *param)
435 ctx_stat *s = xmalloc(sizeof(ctx_stat));
436 s->collect = collect_ctx;
446 static void collect_blk(blk_stat *s)
452 i = rdval_diskstats(get_file(&proc_diskstats), data);
454 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
455 // Linux 2.4 reports bio in Kbytes, convert to sectors:
460 put_question_marks(9);
464 for (i=0; i<2; i++) {
465 ullong old = s->old[i];
466 if (data[i] < old) old = data[i]; //sanitize
470 scale(data[0]*512); // TODO: *sectorsize
475 static s_stat* init_blk(const char *param)
477 blk_stat *s = xmalloc(sizeof(blk_stat));
478 s->collect = collect_blk;
486 S_STAT_END(fork_stat)
488 static void collect_thread_nr(fork_stat *s)
492 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
493 put_question_marks(4);
499 static void collect_fork(fork_stat *s)
504 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
505 put_question_marks(4);
510 if (data[0] < old) old = data[0]; //sanitize
512 scale(data[0] - old);
515 static s_stat* init_fork(const char *param)
517 fork_stat *s = xmalloc(sizeof(fork_stat));
519 s->collect = collect_thread_nr;
521 s->collect = collect_fork;
533 static void collect_if(if_stat *s)
538 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
539 put_question_marks(10);
543 for (i=0; i<4; i++) {
544 ullong old = s->old[i];
545 if (data[i] < old) old = data[i]; //sanitize
549 put_c(data[1] ? '*' : ' ');
551 put_c(data[3] ? '*' : ' ');
555 static s_stat* init_if(const char *device)
557 if_stat *s = xmalloc(sizeof(if_stat));
559 if (!device || !device[0])
561 s->collect = collect_if;
564 s->device_colon = xmalloc(strlen(device)+2);
565 strcpy(s->device_colon, device);
566 strcat(s->device_colon, ":");
575 // "Memory" value should not include any caches.
576 // IOW: neither "ls -laR /" nor heavy read/write activity
577 // should affect it. We'd like to also include any
578 // long-term allocated kernel-side mem, but it is hard
579 // to figure out. For now, bufs, cached & slab are
580 // counted as "free" memory
582 //MemTotal: 773280 kB
583 //MemFree: 25912 kB - genuinely free
584 //Buffers: 320672 kB - cache
585 //Cached: 146396 kB - cache
588 //Inactive: 356892 kB
591 //LowTotal: 773280 kB
593 //SwapTotal: 131064 kB
594 //SwapFree: 131064 kB
598 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
599 // but includes dentries and inodes
600 // (== can take arbitrary amount of mem)
601 //CommitLimit: 517704 kB
602 //Committed_AS: 236776 kB
603 //PageTables: 1248 kB
604 //VmallocTotal: 516052 kB
605 //VmallocUsed: 3852 kB
606 //VmallocChunk: 512096 kB
609 //Hugepagesize: 4096 kB
610 static void collect_mem(mem_stat *s)
618 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
619 put_question_marks(4);
623 scale(m_total << 10);
627 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
628 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
629 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
630 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
632 put_question_marks(4);
636 m_free += m_bufs + m_cached + m_slab;
639 scale(m_free << 10); break;
641 scale((m_total - m_free) << 10); break;
645 static s_stat* init_mem(const char *param)
647 mem_stat *s = xmalloc(sizeof(mem_stat));
648 s->collect = collect_mem;
657 static void collect_swp(swp_stat *s)
661 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
662 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
664 put_question_marks(4);
667 scale((s_total[0]-s_free[0]) << 10);
670 static s_stat* init_swp(const char *param)
672 swp_stat *s = xmalloc(sizeof(swp_stat));
673 s->collect = collect_swp;
681 static void collect_fd(fd_stat *s)
686 readfile_z(file, sizeof(file), "/proc/sys/fs/file-nr");
687 if (rdval(file, "", data, 1, 2)) {
688 put_question_marks(4);
692 scale(data[0] - data[1]);
695 static s_stat* init_fd(const char *param)
697 fd_stat *s = xmalloc(sizeof(fd_stat));
698 s->collect = collect_fd;
706 S_STAT_END(time_stat)
708 static void collect_time(time_stat *s)
710 char buf[sizeof("12:34:56.123456")];
712 int us = tv.tv_usec + s->scale/2;
713 time_t t = tv.tv_sec;
721 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
723 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
727 static s_stat* init_time(const char *param)
730 time_stat *s = xmalloc(sizeof(time_stat));
732 s->collect = collect_time;
734 if (prec < 0) prec = 0;
735 else if (prec > 6) prec = 6;
743 static void collect_info(s_stat *s)
754 typedef s_stat* init_func(const char *param);
756 static const char options[] = "ncmsfixptbdr";
757 static init_func* init_functions[] = {
772 int nmeter_main(int argc, char* argv[])
775 s_stat *first = NULL;
784 fd = xopen("/proc/version", O_RDONLY);
785 if (read(fd, buf, sizeof(buf)) > 0)
786 is26 = (strstr(buf, "Linux version 2.4.")==NULL);
789 // Can use argv[1] directly, but this will mess up
790 // parameters as seen by e.g. ps. Making a copy...
791 cur = xstrdup(argv[1]);
796 cur = strchr(cur, '%');
799 if (cur[1]=='%') { // %%
804 *cur++ = '\0'; // overwrite %
806 // format: %[foptstring]
808 p = strchr(options, cur[0]);
810 while (cur[0] != ']') {
815 *cur++ = '\0'; // overwrite [
819 while (cur[0] >= '0' && cur[0] <= '9')
823 p = strchr(options, cur[0]);
824 *cur++ = '\0'; // overwrite format char
828 s = init_functions[p-options](param);
838 // %NNNNd or %r option. remove it from string
839 strcpy(prev + strlen(prev), cur);
854 // Generate first samples but do not print them, they're bogus
858 gettimeofday(&tv, 0);
859 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
863 gettimeofday(&tv, 0);
868 // Negative delta -> no usleep at all
869 // This will hog the CPU but you can have REALLY GOOD
870 // time resolution ;)
871 // TODO: detect and avoid useless updates
872 // (like: nothing happens except time)
875 // can be commented out, will sacrifice sleep time precision a bit
876 gettimeofday(&tv, 0);
878 rem = delta - ((ullong)tv.tv_sec*1000000+tv.tv_usec)%deltanz;
880 rem = delta - tv.tv_usec%deltanz;
881 // Sometimes kernel wakes us up just a tiny bit earlier than asked
882 // Do not go to very short sleep in this case
883 if (rem < delta/128) {