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;
20 enum { PROC_FILE_SIZE = 4096 };
22 typedef struct proc_file {
28 static const char *const proc_name[] = {
29 "stat", // Must match the order of proc_file's!
38 // Sample generation flip-flop
40 // Linux 2.6? (otherwise assumes 2.4)
42 // 1 if sample delay is not an integer fraction of a second
43 smallint need_seconds;
45 const char *final_str;
49 #define first_proc_file proc_stat
50 proc_file proc_stat; // Must match the order of proc_name's!
51 proc_file proc_loadavg;
52 proc_file proc_net_dev;
53 proc_file proc_meminfo;
54 proc_file proc_diskstats;
55 proc_file proc_sys_fs_filenr;
57 #define G (*ptr_to_globals)
59 #define is26 (G.is26 )
60 #define need_seconds (G.need_seconds )
61 #define cur_outbuf (G.cur_outbuf )
62 #define final_str (G.final_str )
63 #define delta (G.delta )
64 #define deltanz (G.deltanz )
66 #define proc_stat (G.proc_stat )
67 #define proc_loadavg (G.proc_loadavg )
68 #define proc_net_dev (G.proc_net_dev )
69 #define proc_meminfo (G.proc_meminfo )
70 #define proc_diskstats (G.proc_diskstats )
71 #define proc_sys_fs_filenr (G.proc_sys_fs_filenr)
72 #define INIT_G() do { \
73 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
74 cur_outbuf = outbuf; \
76 deltanz = delta = 1000000; \
79 // We depend on this being a char[], not char* - we take sizeof() of it
80 #define outbuf bb_common_bufsiz1
82 static inline void reset_outbuf(void)
87 static inline int outbuf_count(void)
89 return cur_outbuf - outbuf;
92 static void print_outbuf(void)
94 int sz = cur_outbuf - outbuf;
96 xwrite(1, outbuf, sz);
101 static void put(const char *s)
104 if (sz > outbuf + sizeof(outbuf) - cur_outbuf)
105 sz = outbuf + sizeof(outbuf) - cur_outbuf;
106 memcpy(cur_outbuf, s, sz);
110 static void put_c(char c)
112 if (cur_outbuf < outbuf + sizeof(outbuf))
116 static void put_question_marks(int count)
122 static void readfile_z(char *buf, int sz, const char* fname)
124 // open_read_close() will do two reads in order to be sure we are at EOF,
125 // and we don't need/want that.
126 // sz = open_read_close(fname, buf, sz-1);
128 int fd = xopen(fname, O_RDONLY);
131 sz = read(fd, buf, sz-1);
132 if (sz > 0) buf[sz] = '\0';
137 static const char* get_file(proc_file *pf)
139 if (pf->last_gen != gen) {
141 // We allocate PROC_FILE_SIZE bytes. This wastes memory,
142 // but allows us to allocate only once (at first sample)
143 // per proc file, and reuse buffer for each sample
145 pf->file = xmalloc(PROC_FILE_SIZE);
146 readfile_z(pf->file, PROC_FILE_SIZE, proc_name[pf - &first_proc_file]);
151 static inline ullong read_after_slash(const char *p)
155 return strtoull(p+1, NULL, 10);
158 enum conv_type { conv_decimal, conv_slash };
160 // Reads decimal values from line. Values start after key, for example:
161 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
162 // Values are stored in vec[]. arg_ptr has list of positions
163 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
164 static int vrdval(const char* p, const char* key,
165 enum conv_type conv, ullong *vec, va_list arg_ptr)
175 indexnext = va_arg(arg_ptr, int);
177 while (*p == ' ' || *p == '\t') p++;
178 if (*p == '\n' || *p == '\0') break;
180 if (indexline == indexnext) { // read this value
181 *vec++ = conv==conv_decimal ?
182 strtoull(p, NULL, 10) :
184 indexnext = va_arg(arg_ptr, int);
186 while (*p > ' ') p++; // skip over value
192 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
193 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
194 // value# start with 1
195 static int rdval(const char* p, const char* key, ullong *vec, ...)
200 va_start(arg_ptr, vec);
201 result = vrdval(p, key, conv_decimal, vec, arg_ptr);
207 // Parses files with lines like "... ... ... 3/148 ...."
208 static int rdval_loadavg(const char* p, ullong *vec, ...)
213 va_start(arg_ptr, vec);
214 result = vrdval(p, "", conv_slash, vec, arg_ptr);
220 // Parses /proc/diskstats
221 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
222 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
223 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
224 static int rdval_diskstats(const char* p, ullong *vec)
226 ullong rd = 0; // to avoid "warning: 'rd' might be used uninitialized"
232 while (*p == ' ' || *p == '\t') p++;
233 if (*p == '\0') break;
239 if (indexline == 6) {
240 rd = strtoull(p, NULL, 10);
241 } else if (indexline == 10) {
242 vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize)
243 vec[1] += strtoull(p, NULL, 10);
244 while (*p != '\n' && *p != '\0') p++;
247 while (*p > ' ') p++; // skip over value
252 static void scale(ullong ul)
255 smart_ulltoa5(ul, buf);
262 struct s_stat *next; \
263 void (*collect)(struct a *s); \
265 #define S_STAT_END(a) } a;
270 static void collect_literal(s_stat *s)
274 static s_stat* init_literal(void)
276 s_stat *s = xmalloc(sizeof(s_stat));
277 s->collect = collect_literal;
281 static s_stat* init_delay(const char *param)
283 delta = bb_strtoi(param, NULL, 0) * 1000;
284 deltanz = delta > 0 ? delta : 1;
285 need_seconds = (1000000%deltanz) != 0;
289 static s_stat* init_cr(const char *param)
296 // user nice system idle iowait irq softirq (last 3 only in 2.6)
297 //cpu 649369 0 341297 4336769 11640 7122 1183
298 //cpuN 649369 0 341297 4336769 11640 7122 1183
299 enum { CPU_FIELDCNT = 7 };
301 ullong old[CPU_FIELDCNT];
307 static void collect_cpu(cpu_stat *s)
309 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
310 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
313 int bar_sz = s->bar_sz;
317 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
318 put_question_marks(bar_sz);
322 for (i = 0; i < CPU_FIELDCNT; i++) {
323 ullong old = s->old[i];
324 if (data[i] < old) old = data[i]; //sanitize
326 all += (data[i] -= old);
330 for (i = 0; i < CPU_FIELDCNT; i++) {
331 ullong t = bar_sz * data[i];
332 norm_all += data[i] = t / all;
336 while (norm_all < bar_sz) {
337 unsigned max = frac[0];
339 for (i = 1; i < CPU_FIELDCNT; i++) {
340 if (frac[i] > max) max = frac[i], pos = i;
342 frac[pos] = 0; //avoid bumping up same value twice
347 memset(bar, '.', bar_sz);
348 memset(bar, 'S', data[2]); bar += data[2]; //sys
349 memset(bar, 'U', data[0]); bar += data[0]; //usr
350 memset(bar, 'N', data[1]); bar += data[1]; //nice
351 memset(bar, 'D', data[4]); bar += data[4]; //iowait
352 memset(bar, 'I', data[5]); bar += data[5]; //irq
353 memset(bar, 'i', data[6]); bar += data[6]; //softirq
355 memset(bar, '?', bar_sz);
361 static s_stat* init_cpu(const char *param)
364 cpu_stat *s = xmalloc(sizeof(cpu_stat));
365 s->collect = collect_cpu;
366 sz = strtol(param, NULL, 0);
367 if (sz < 10) sz = 10;
368 if (sz > 1000) sz = 1000;
369 s->bar = xmalloc(sz+1);
381 static void collect_int(int_stat *s)
386 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
387 put_question_marks(4);
392 if (data[0] < old) old = data[0]; //sanitize
394 scale(data[0] - old);
397 static s_stat* init_int(const char *param)
399 int_stat *s = xmalloc(sizeof(int_stat));
400 s->collect = collect_int;
401 if (param[0]=='\0') {
404 int n = strtoul(param, NULL, 0);
415 static void collect_ctx(ctx_stat *s)
420 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
421 put_question_marks(4);
426 if (data[0] < old) old = data[0]; //sanitize
428 scale(data[0] - old);
431 static s_stat* init_ctx(const char *param)
433 ctx_stat *s = xmalloc(sizeof(ctx_stat));
434 s->collect = collect_ctx;
444 static void collect_blk(blk_stat *s)
450 i = rdval_diskstats(get_file(&proc_diskstats), data);
452 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
453 // Linux 2.4 reports bio in Kbytes, convert to sectors:
458 put_question_marks(9);
462 for (i=0; i<2; i++) {
463 ullong old = s->old[i];
464 if (data[i] < old) old = data[i]; //sanitize
468 scale(data[0]*512); // TODO: *sectorsize
473 static s_stat* init_blk(const char *param)
475 blk_stat *s = xmalloc(sizeof(blk_stat));
476 s->collect = collect_blk;
484 S_STAT_END(fork_stat)
486 static void collect_thread_nr(fork_stat *s)
490 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
491 put_question_marks(4);
497 static void collect_fork(fork_stat *s)
502 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
503 put_question_marks(4);
508 if (data[0] < old) old = data[0]; //sanitize
510 scale(data[0] - old);
513 static s_stat* init_fork(const char *param)
515 fork_stat *s = xmalloc(sizeof(fork_stat));
517 s->collect = collect_thread_nr;
519 s->collect = collect_fork;
531 static void collect_if(if_stat *s)
536 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
537 put_question_marks(10);
541 for (i=0; i<4; i++) {
542 ullong old = s->old[i];
543 if (data[i] < old) old = data[i]; //sanitize
547 put_c(data[1] ? '*' : ' ');
549 put_c(data[3] ? '*' : ' ');
553 static s_stat* init_if(const char *device)
555 if_stat *s = xmalloc(sizeof(if_stat));
557 if (!device || !device[0])
559 s->collect = collect_if;
562 s->device_colon = xmalloc(strlen(device)+2);
563 strcpy(s->device_colon, device);
564 strcat(s->device_colon, ":");
573 // "Memory" value should not include any caches.
574 // IOW: neither "ls -laR /" nor heavy read/write activity
575 // should affect it. We'd like to also include any
576 // long-term allocated kernel-side mem, but it is hard
577 // to figure out. For now, bufs, cached & slab are
578 // counted as "free" memory
580 //MemTotal: 773280 kB
581 //MemFree: 25912 kB - genuinely free
582 //Buffers: 320672 kB - cache
583 //Cached: 146396 kB - cache
586 //Inactive: 356892 kB
589 //LowTotal: 773280 kB
591 //SwapTotal: 131064 kB
592 //SwapFree: 131064 kB
596 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
597 // but includes dentries and inodes
598 // (== can take arbitrary amount of mem)
599 //CommitLimit: 517704 kB
600 //Committed_AS: 236776 kB
601 //PageTables: 1248 kB
602 //VmallocTotal: 516052 kB
603 //VmallocUsed: 3852 kB
604 //VmallocChunk: 512096 kB
607 //Hugepagesize: 4096 kB
608 static void collect_mem(mem_stat *s)
616 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
617 put_question_marks(4);
621 scale(m_total << 10);
625 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
626 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
627 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
628 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
630 put_question_marks(4);
634 m_free += m_bufs + m_cached + m_slab;
637 scale(m_free << 10); break;
639 scale((m_total - m_free) << 10); break;
643 static s_stat* init_mem(const char *param)
645 mem_stat *s = xmalloc(sizeof(mem_stat));
646 s->collect = collect_mem;
655 static void collect_swp(swp_stat *s)
659 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
660 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
662 put_question_marks(4);
665 scale((s_total[0]-s_free[0]) << 10);
668 static s_stat* init_swp(const char *param)
670 swp_stat *s = xmalloc(sizeof(swp_stat));
671 s->collect = collect_swp;
679 static void collect_fd(fd_stat *s)
683 if (rdval(get_file(&proc_sys_fs_filenr), "", data, 1, 2)) {
684 put_question_marks(4);
688 scale(data[0] - data[1]);
691 static s_stat* init_fd(const char *param)
693 fd_stat *s = xmalloc(sizeof(fd_stat));
694 s->collect = collect_fd;
702 S_STAT_END(time_stat)
704 static void collect_time(time_stat *s)
706 char buf[sizeof("12:34:56.123456")];
708 int us = tv.tv_usec + s->scale/2;
709 time_t t = tv.tv_sec;
717 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
719 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
723 static s_stat* init_time(const char *param)
726 time_stat *s = xmalloc(sizeof(time_stat));
728 s->collect = collect_time;
730 if (prec < 0) prec = 0;
731 else if (prec > 6) prec = 6;
739 static void collect_info(s_stat *s)
750 typedef s_stat* init_func(const char *param);
752 static const char options[] = "ncmsfixptbdr";
753 static init_func *const init_functions[] = {
768 int nmeter_main(int argc, char **argv);
769 int nmeter_main(int argc, char **argv)
772 s_stat *first = NULL;
784 if (open_read_close("version", buf, sizeof(buf)) > 0)
785 is26 = (strstr(buf, " 2.4.")==NULL);
787 // Can use argv[1] directly, but this will mess up
788 // parameters as seen by e.g. ps. Making a copy...
789 cur = xstrdup(argv[1]);
794 cur = strchr(cur, '%');
797 if (cur[1] == '%') { // %%
802 *cur++ = '\0'; // overwrite %
804 // format: %[foptstring]
806 p = strchr(options, cur[0]);
808 while (cur[0] != ']') {
813 *cur++ = '\0'; // overwrite [
817 while (cur[0] >= '0' && cur[0] <= '9')
821 p = strchr(options, cur[0]);
822 *cur++ = '\0'; // overwrite format char
826 s = init_functions[p-options](param);
836 // %NNNNd or %r option. remove it from string
837 strcpy(prev + strlen(prev), cur);
852 // Generate first samples but do not print them, they're bogus
856 gettimeofday(&tv, NULL);
857 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
861 gettimeofday(&tv, NULL);
866 // Negative delta -> no usleep at all
867 // This will hog the CPU but you can have REALLY GOOD
868 // time resolution ;)
869 // TODO: detect and avoid useless updates
870 // (like: nothing happens except time)
873 // can be commented out, will sacrifice sleep time precision a bit
874 gettimeofday(&tv, NULL);
876 rem = delta - ((ullong)tv.tv_sec*1000000 + tv.tv_usec) % deltanz;
878 rem = delta - tv.tv_usec%deltanz;
879 // Sometimes kernel wakes us up just a tiny bit earlier than asked
880 // Do not go to very short sleep in this case
881 if (rem < delta/128) {