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)
218 smart_ulltoa5(ul, buf);
225 struct s_stat *next; \
226 void (*collect)(struct a *s); \
228 #define S_STAT_END(a) } a;
233 static void collect_literal(s_stat *s)
237 static s_stat* init_literal(void)
239 s_stat *s = xmalloc(sizeof(s_stat));
240 s->collect = collect_literal;
244 static s_stat* init_delay(const char *param)
246 delta = strtol(param, NULL, 0)*1000;
247 deltanz = delta > 0 ? delta : 1;
248 need_seconds = (1000000%deltanz) != 0;
252 static s_stat* init_cr(const char *param)
259 // user nice system idle iowait irq softirq (last 3 only in 2.6)
260 //cpu 649369 0 341297 4336769 11640 7122 1183
261 //cpuN 649369 0 341297 4336769 11640 7122 1183
262 enum { CPU_FIELDCNT = 7 };
264 ullong old[CPU_FIELDCNT];
270 static void collect_cpu(cpu_stat *s)
272 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
273 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
276 int bar_sz = s->bar_sz;
280 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
281 put_question_marks(bar_sz);
285 for (i=0; i<CPU_FIELDCNT; i++) {
286 ullong old = s->old[i];
287 if (data[i] < old) old = data[i]; //sanitize
289 all += (data[i] -= old);
293 for (i=0; i<CPU_FIELDCNT; i++) {
294 ullong t = bar_sz * data[i];
295 norm_all += data[i] = t / all;
299 while (norm_all < bar_sz) {
300 unsigned max = frac[0];
302 for (i=1; i<CPU_FIELDCNT; i++) {
303 if (frac[i] > max) max = frac[i], pos = i;
305 frac[pos] = 0; //avoid bumping up same value twice
310 memset(bar, '.', bar_sz);
311 memset(bar, 'S', data[2]); bar += data[2]; //sys
312 memset(bar, 'U', data[0]); bar += data[0]; //usr
313 memset(bar, 'N', data[1]); bar += data[1]; //nice
314 memset(bar, 'D', data[4]); bar += data[4]; //iowait
315 memset(bar, 'I', data[5]); bar += data[5]; //irq
316 memset(bar, 'i', data[6]); bar += data[6]; //softirq
318 memset(bar, '?', bar_sz);
324 static s_stat* init_cpu(const char *param)
327 cpu_stat *s = xmalloc(sizeof(cpu_stat));
328 s->collect = collect_cpu;
329 sz = strtol(param, NULL, 0);
330 if (sz < 10) sz = 10;
331 if (sz > 1000) sz = 1000;
332 s->bar = xmalloc(sz+1);
344 static void collect_int(int_stat *s)
349 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
350 put_question_marks(4);
355 if (data[0] < old) old = data[0]; //sanitize
357 scale(data[0] - old);
360 static s_stat* init_int(const char *param)
362 int_stat *s = xmalloc(sizeof(int_stat));
363 s->collect = collect_int;
364 if (param[0]=='\0') {
367 int n = strtoul(param, NULL, 0);
378 static void collect_ctx(ctx_stat *s)
383 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
384 put_question_marks(4);
389 if (data[0] < old) old = data[0]; //sanitize
391 scale(data[0] - old);
394 static s_stat* init_ctx(const char *param)
396 ctx_stat *s = xmalloc(sizeof(ctx_stat));
397 s->collect = collect_ctx;
407 static void collect_blk(blk_stat *s)
413 i = rdval_diskstats(get_file(&proc_diskstats), data);
415 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
416 // Linux 2.4 reports bio in Kbytes, convert to sectors:
421 put_question_marks(9);
425 for (i=0; i<2; i++) {
426 ullong old = s->old[i];
427 if (data[i] < old) old = data[i]; //sanitize
431 scale(data[0]*512); // TODO: *sectorsize
436 static s_stat* init_blk(const char *param)
438 blk_stat *s = xmalloc(sizeof(blk_stat));
439 s->collect = collect_blk;
447 S_STAT_END(fork_stat)
449 static void collect_thread_nr(fork_stat *s)
453 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
454 put_question_marks(4);
460 static void collect_fork(fork_stat *s)
465 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
466 put_question_marks(4);
471 if (data[0] < old) old = data[0]; //sanitize
473 scale(data[0] - old);
476 static s_stat* init_fork(const char *param)
478 fork_stat *s = xmalloc(sizeof(fork_stat));
480 s->collect = collect_thread_nr;
482 s->collect = collect_fork;
494 static void collect_if(if_stat *s)
499 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
500 put_question_marks(10);
504 for (i=0; i<4; i++) {
505 ullong old = s->old[i];
506 if (data[i] < old) old = data[i]; //sanitize
510 put_c(data[1] ? '*' : ' ');
512 put_c(data[3] ? '*' : ' ');
516 static s_stat* init_if(const char *device)
518 if_stat *s = xmalloc(sizeof(if_stat));
520 if (!device || !device[0])
522 s->collect = collect_if;
525 s->device_colon = xmalloc(strlen(device)+2);
526 strcpy(s->device_colon, device);
527 strcat(s->device_colon, ":");
536 // "Memory" value should not include any caches.
537 // IOW: neither "ls -laR /" nor heavy read/write activity
538 // should affect it. We'd like to also include any
539 // long-term allocated kernel-side mem, but it is hard
540 // to figure out. For now, bufs, cached & slab are
541 // counted as "free" memory
543 //MemTotal: 773280 kB
544 //MemFree: 25912 kB - genuinely free
545 //Buffers: 320672 kB - cache
546 //Cached: 146396 kB - cache
549 //Inactive: 356892 kB
552 //LowTotal: 773280 kB
554 //SwapTotal: 131064 kB
555 //SwapFree: 131064 kB
559 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
560 // but includes dentries and inodes
561 // (== can take arbitrary amount of mem)
562 //CommitLimit: 517704 kB
563 //Committed_AS: 236776 kB
564 //PageTables: 1248 kB
565 //VmallocTotal: 516052 kB
566 //VmallocUsed: 3852 kB
567 //VmallocChunk: 512096 kB
570 //Hugepagesize: 4096 kB
571 static void collect_mem(mem_stat *s)
579 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
580 put_question_marks(4);
584 scale(m_total << 10);
588 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
589 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
590 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
591 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
593 put_question_marks(4);
597 m_free += m_bufs + m_cached + m_slab;
600 scale(m_free << 10); break;
602 scale((m_total - m_free) << 10); break;
606 static s_stat* init_mem(const char *param)
608 mem_stat *s = xmalloc(sizeof(mem_stat));
609 s->collect = collect_mem;
618 static void collect_swp(swp_stat *s)
622 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
623 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
625 put_question_marks(4);
628 scale((s_total[0]-s_free[0]) << 10);
631 static s_stat* init_swp(const char *param)
633 swp_stat *s = xmalloc(sizeof(swp_stat));
634 s->collect = collect_swp;
642 static void collect_fd(fd_stat *s)
647 readfile_z(file, sizeof(file), "/proc/sys/fs/file-nr");
648 if (rdval(file, "", data, 1, 2)) {
649 put_question_marks(4);
653 scale(data[0] - data[1]);
656 static s_stat* init_fd(const char *param)
658 fd_stat *s = xmalloc(sizeof(fd_stat));
659 s->collect = collect_fd;
667 S_STAT_END(time_stat)
669 static void collect_time(time_stat *s)
671 char buf[sizeof("12:34:56.123456")];
673 int us = tv.tv_usec + s->scale/2;
674 time_t t = tv.tv_sec;
682 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
684 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
688 static s_stat* init_time(const char *param)
691 time_stat *s = xmalloc(sizeof(time_stat));
693 s->collect = collect_time;
695 if (prec < 0) prec = 0;
696 else if (prec > 6) prec = 6;
704 static void collect_info(s_stat *s)
715 typedef s_stat* init_func(const char *param);
717 static const char options[] = "ncmsfixptbdr";
718 static init_func* init_functions[] = {
733 int nmeter_main(int argc, char* argv[])
736 s_stat *first = NULL;
744 if (open_read_close("/proc/version", buf, sizeof(buf)) > 0)
745 is26 = (strstr(buf, " 2.4.")==NULL);
747 // Can use argv[1] directly, but this will mess up
748 // parameters as seen by e.g. ps. Making a copy...
749 cur = xstrdup(argv[1]);
754 cur = strchr(cur, '%');
757 if (cur[1]=='%') { // %%
762 *cur++ = '\0'; // overwrite %
764 // format: %[foptstring]
766 p = strchr(options, cur[0]);
768 while (cur[0] != ']') {
773 *cur++ = '\0'; // overwrite [
777 while (cur[0] >= '0' && cur[0] <= '9')
781 p = strchr(options, cur[0]);
782 *cur++ = '\0'; // overwrite format char
786 s = init_functions[p-options](param);
796 // %NNNNd or %r option. remove it from string
797 strcpy(prev + strlen(prev), cur);
812 // Generate first samples but do not print them, they're bogus
816 gettimeofday(&tv, 0);
817 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
821 gettimeofday(&tv, 0);
826 // Negative delta -> no usleep at all
827 // This will hog the CPU but you can have REALLY GOOD
828 // time resolution ;)
829 // TODO: detect and avoid useless updates
830 // (like: nothing happens except time)
833 // can be commented out, will sacrifice sleep time precision a bit
834 gettimeofday(&tv, 0);
836 rem = delta - ((ullong)tv.tv_sec*1000000+tv.tv_usec)%deltanz;
838 rem = delta - tv.tv_usec%deltanz;
839 // Sometimes kernel wakes us up just a tiny bit earlier than asked
840 // Do not go to very short sleep in this case
841 if (rem < delta/128) {