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)
91 sz = open_read_close(fname, buf, sz-1);
100 static const char* get_file(proc_file *pf)
102 if (pf->gen != gen) {
104 // We allocate proc_file_size bytes. This wastes memory,
105 // but allows us to allocate only once (at first sample)
106 // per proc file, and reuse buffer for each sample
108 pf->file = (char*)xmalloc(proc_file_size);
109 readfile_z(pf->file, proc_file_size, pf->name);
114 static inline ullong read_after_slash(const char *p)
118 return strtoull(p+1, NULL, 10);
121 enum conv_type { conv_decimal, conv_slash };
123 // Reads decimal values from line. Values start after key, for example:
124 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
125 // Values are stored in vec[]. arg_ptr has list of positions
126 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
127 static int vrdval(const char* p, const char* key,
128 enum conv_type conv, ullong *vec, va_list arg_ptr)
138 indexnext = va_arg(arg_ptr, int);
140 while (*p == ' ' || *p == '\t') p++;
141 if (*p == '\n' || *p == '\0') break;
143 if (indexline == indexnext) { // read this value
144 *vec++ = conv==conv_decimal ?
145 strtoull(p, NULL, 10) :
147 indexnext = va_arg(arg_ptr, int);
149 while (*p > ' ') p++; // skip over value
155 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
156 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
157 // value# start with 1
158 static int rdval(const char* p, const char* key, ullong *vec, ...)
163 va_start(arg_ptr, vec);
164 result = vrdval(p, key, conv_decimal, vec, arg_ptr);
170 // Parses files with lines like "... ... ... 3/148 ...."
171 static int rdval_loadavg(const char* p, ullong *vec, ...)
176 va_start(arg_ptr, vec);
177 result = vrdval(p, "", conv_slash, vec, arg_ptr);
183 // Parses /proc/diskstats
184 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
185 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
186 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
187 static int rdval_diskstats(const char* p, ullong *vec)
189 ullong rd = 0; // to avoid "warning: 'rd' might be used uninitialized"
195 while (*p == ' ' || *p == '\t') p++;
196 if (*p == '\0') break;
202 if (indexline == 6) {
203 rd = strtoull(p, NULL, 10);
204 } else if (indexline == 10) {
205 vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize)
206 vec[1] += strtoull(p, NULL, 10);
207 while (*p != '\n' && *p != '\0') p++;
210 while (*p > ' ') p++; // skip over value
215 static void scale(ullong ul)
222 if (ul > 9999*10) { // do not scale if 9999 or less
223 while (ul >= 10000) {
228 v = ul; // ullong divisions are expensive, avoid them
231 if (!idx) { // 9999 or less: use 1234 format
232 c = buf[0] = " 123456789"[v/10000];
233 if (c!=' ') fmt = "0123456789";
234 c = buf[1] = fmt[v/1000%10];
235 if (c!=' ') fmt = "0123456789";
236 buf[2] = fmt[v/100%10];
237 buf[3] = "0123456789"[v/10%10];
239 if (v>=10*10) { // scaled value is >=10: use 123M format
240 c = buf[0] = " 123456789"[v/1000];
241 if (c!=' ') fmt = "0123456789";
242 buf[1] = fmt[v/100%10];
243 buf[2] = "0123456789"[v/10%10];
244 } else { // scaled value is <10: use 1.2M format
245 buf[0] = "0123456789"[v/10];
247 buf[2] = "0123456789"[v%10];
249 // see http://en.wikipedia.org/wiki/Tera
250 buf[3] = " kMGTPEZY"[idx];
259 struct s_stat *next; \
260 void (*collect)(struct a *s); \
262 #define S_STAT_END(a) } a;
267 static void collect_literal(s_stat *s)
271 static s_stat* init_literal(void)
273 s_stat *s = xmalloc(sizeof(s_stat));
274 s->collect = collect_literal;
278 static s_stat* init_delay(const char *param)
280 delta = strtol(param, NULL, 0)*1000;
281 deltanz = delta > 0 ? delta : 1;
282 need_seconds = (1000000%deltanz) != 0;
286 static s_stat* init_cr(const char *param)
293 // user nice system idle iowait irq softirq (last 3 only in 2.6)
294 //cpu 649369 0 341297 4336769 11640 7122 1183
295 //cpuN 649369 0 341297 4336769 11640 7122 1183
296 enum { CPU_FIELDCNT = 7 };
298 ullong old[CPU_FIELDCNT];
304 static void collect_cpu(cpu_stat *s)
306 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
307 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
310 int bar_sz = s->bar_sz;
314 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
315 put_question_marks(bar_sz);
319 for (i=0; i<CPU_FIELDCNT; i++) {
320 ullong old = s->old[i];
321 if (data[i] < old) old = data[i]; //sanitize
323 all += (data[i] -= old);
327 for (i=0; i<CPU_FIELDCNT; i++) {
328 ullong t = bar_sz * data[i];
329 norm_all += data[i] = t / all;
333 while (norm_all < bar_sz) {
334 unsigned max = frac[0];
336 for (i=1; i<CPU_FIELDCNT; i++) {
337 if (frac[i] > max) max = frac[i], pos = i;
339 frac[pos] = 0; //avoid bumping up same value twice
344 memset(bar, '.', bar_sz);
345 memset(bar, 'S', data[2]); bar += data[2]; //sys
346 memset(bar, 'U', data[0]); bar += data[0]; //usr
347 memset(bar, 'N', data[1]); bar += data[1]; //nice
348 memset(bar, 'D', data[4]); bar += data[4]; //iowait
349 memset(bar, 'I', data[5]); bar += data[5]; //irq
350 memset(bar, 'i', data[6]); bar += data[6]; //softirq
352 memset(bar, '?', bar_sz);
358 static s_stat* init_cpu(const char *param)
361 cpu_stat *s = xmalloc(sizeof(cpu_stat));
362 s->collect = collect_cpu;
363 sz = strtol(param, NULL, 0);
364 if (sz < 10) sz = 10;
365 if (sz > 1000) sz = 1000;
366 s->bar = xmalloc(sz+1);
378 static void collect_int(int_stat *s)
383 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
384 put_question_marks(4);
389 if (data[0] < old) old = data[0]; //sanitize
391 scale(data[0] - old);
394 static s_stat* init_int(const char *param)
396 int_stat *s = xmalloc(sizeof(int_stat));
397 s->collect = collect_int;
398 if (param[0]=='\0') {
401 int n = strtoul(param, NULL, 0);
412 static void collect_ctx(ctx_stat *s)
417 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
418 put_question_marks(4);
423 if (data[0] < old) old = data[0]; //sanitize
425 scale(data[0] - old);
428 static s_stat* init_ctx(const char *param)
430 ctx_stat *s = xmalloc(sizeof(ctx_stat));
431 s->collect = collect_ctx;
441 static void collect_blk(blk_stat *s)
447 i = rdval_diskstats(get_file(&proc_diskstats), data);
449 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
450 // Linux 2.4 reports bio in Kbytes, convert to sectors:
455 put_question_marks(9);
459 for (i=0; i<2; i++) {
460 ullong old = s->old[i];
461 if (data[i] < old) old = data[i]; //sanitize
465 scale(data[0]*512); // TODO: *sectorsize
470 static s_stat* init_blk(const char *param)
472 blk_stat *s = xmalloc(sizeof(blk_stat));
473 s->collect = collect_blk;
481 S_STAT_END(fork_stat)
483 static void collect_thread_nr(fork_stat *s)
487 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
488 put_question_marks(4);
494 static void collect_fork(fork_stat *s)
499 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
500 put_question_marks(4);
505 if (data[0] < old) old = data[0]; //sanitize
507 scale(data[0] - old);
510 static s_stat* init_fork(const char *param)
512 fork_stat *s = xmalloc(sizeof(fork_stat));
514 s->collect = collect_thread_nr;
516 s->collect = collect_fork;
528 static void collect_if(if_stat *s)
533 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
534 put_question_marks(10);
538 for (i=0; i<4; i++) {
539 ullong old = s->old[i];
540 if (data[i] < old) old = data[i]; //sanitize
544 put_c(data[1] ? '*' : ' ');
546 put_c(data[3] ? '*' : ' ');
550 static s_stat* init_if(const char *device)
552 if_stat *s = xmalloc(sizeof(if_stat));
554 if (!device || !device[0])
556 s->collect = collect_if;
559 s->device_colon = xmalloc(strlen(device)+2);
560 strcpy(s->device_colon, device);
561 strcat(s->device_colon, ":");
570 // "Memory" value should not include any caches.
571 // IOW: neither "ls -laR /" nor heavy read/write activity
572 // should affect it. We'd like to also include any
573 // long-term allocated kernel-side mem, but it is hard
574 // to figure out. For now, bufs, cached & slab are
575 // counted as "free" memory
577 //MemTotal: 773280 kB
578 //MemFree: 25912 kB - genuinely free
579 //Buffers: 320672 kB - cache
580 //Cached: 146396 kB - cache
583 //Inactive: 356892 kB
586 //LowTotal: 773280 kB
588 //SwapTotal: 131064 kB
589 //SwapFree: 131064 kB
593 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
594 // but includes dentries and inodes
595 // (== can take arbitrary amount of mem)
596 //CommitLimit: 517704 kB
597 //Committed_AS: 236776 kB
598 //PageTables: 1248 kB
599 //VmallocTotal: 516052 kB
600 //VmallocUsed: 3852 kB
601 //VmallocChunk: 512096 kB
604 //Hugepagesize: 4096 kB
605 static void collect_mem(mem_stat *s)
613 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
614 put_question_marks(4);
618 scale(m_total << 10);
622 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
623 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
624 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
625 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
627 put_question_marks(4);
631 m_free += m_bufs + m_cached + m_slab;
634 scale(m_free << 10); break;
636 scale((m_total - m_free) << 10); break;
640 static s_stat* init_mem(const char *param)
642 mem_stat *s = xmalloc(sizeof(mem_stat));
643 s->collect = collect_mem;
652 static void collect_swp(swp_stat *s)
656 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
657 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
659 put_question_marks(4);
662 scale((s_total[0]-s_free[0]) << 10);
665 static s_stat* init_swp(const char *param)
667 swp_stat *s = xmalloc(sizeof(swp_stat));
668 s->collect = collect_swp;
676 static void collect_fd(fd_stat *s)
681 readfile_z(file, sizeof(file), "/proc/sys/fs/file-nr");
682 if (rdval(file, "", data, 1, 2)) {
683 put_question_marks(4);
687 scale(data[0] - data[1]);
690 static s_stat* init_fd(const char *param)
692 fd_stat *s = xmalloc(sizeof(fd_stat));
693 s->collect = collect_fd;
701 S_STAT_END(time_stat)
703 static void collect_time(time_stat *s)
705 char buf[sizeof("12:34:56.123456")];
707 int us = tv.tv_usec + s->scale/2;
708 time_t t = tv.tv_sec;
716 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
718 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
722 static s_stat* init_time(const char *param)
725 time_stat *s = xmalloc(sizeof(time_stat));
727 s->collect = collect_time;
729 if (prec < 0) prec = 0;
730 else if (prec > 6) prec = 6;
738 static void collect_info(s_stat *s)
749 typedef s_stat* init_func(const char *param);
751 static const char options[] = "ncmsfixptbdr";
752 static init_func* init_functions[] = {
767 int nmeter_main(int argc, char* argv[])
770 s_stat *first = NULL;
778 if (open_read_close("/proc/version", buf, sizeof(buf)) > 0)
779 is26 = (strstr(buf, " 2.4.")==NULL);
781 // Can use argv[1] directly, but this will mess up
782 // parameters as seen by e.g. ps. Making a copy...
783 cur = xstrdup(argv[1]);
788 cur = strchr(cur, '%');
791 if (cur[1]=='%') { // %%
796 *cur++ = '\0'; // overwrite %
798 // format: %[foptstring]
800 p = strchr(options, cur[0]);
802 while (cur[0] != ']') {
807 *cur++ = '\0'; // overwrite [
811 while (cur[0] >= '0' && cur[0] <= '9')
815 p = strchr(options, cur[0]);
816 *cur++ = '\0'; // overwrite format char
820 s = init_functions[p-options](param);
830 // %NNNNd or %r option. remove it from string
831 strcpy(prev + strlen(prev), cur);
846 // Generate first samples but do not print them, they're bogus
850 gettimeofday(&tv, 0);
851 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
855 gettimeofday(&tv, 0);
860 // Negative delta -> no usleep at all
861 // This will hog the CPU but you can have REALLY GOOD
862 // time resolution ;)
863 // TODO: detect and avoid useless updates
864 // (like: nothing happens except time)
867 // can be commented out, will sacrifice sleep time precision a bit
868 gettimeofday(&tv, 0);
870 rem = delta - ((ullong)tv.tv_sec*1000000+tv.tv_usec)%deltanz;
872 rem = delta - tv.tv_usec%deltanz;
873 // Sometimes kernel wakes us up just a tiny bit earlier than asked
874 // Do not go to very short sleep in this case
875 if (rem < delta/128) {