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})
22 typedef unsigned long long ullong;
24 enum { /* Preferably use powers of 2 */
25 PROC_MIN_FILE_SIZE = 256,
26 PROC_MAX_FILE_SIZE = 16 * 1024,
29 typedef struct proc_file {
35 static const char *const proc_name[] = {
36 "stat", // Must match the order of proc_file's!
45 // Sample generation flip-flop
47 // Linux 2.6? (otherwise assumes 2.4)
49 // 1 if sample delay is not an integer fraction of a second
50 smallint need_seconds;
52 const char *final_str;
56 #define first_proc_file proc_stat
57 proc_file proc_stat; // Must match the order of proc_name's!
58 proc_file proc_loadavg;
59 proc_file proc_net_dev;
60 proc_file proc_meminfo;
61 proc_file proc_diskstats;
62 proc_file proc_sys_fs_filenr;
64 #define G (*ptr_to_globals)
66 #define is26 (G.is26 )
67 #define need_seconds (G.need_seconds )
68 #define cur_outbuf (G.cur_outbuf )
69 #define final_str (G.final_str )
70 #define delta (G.delta )
71 #define deltanz (G.deltanz )
73 #define proc_stat (G.proc_stat )
74 #define proc_loadavg (G.proc_loadavg )
75 #define proc_net_dev (G.proc_net_dev )
76 #define proc_meminfo (G.proc_meminfo )
77 #define proc_diskstats (G.proc_diskstats )
78 #define proc_sys_fs_filenr (G.proc_sys_fs_filenr)
79 #define INIT_G() do { \
80 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
81 cur_outbuf = outbuf; \
83 deltanz = delta = 1000000; \
86 // We depend on this being a char[], not char* - we take sizeof() of it
87 #define outbuf bb_common_bufsiz1
89 static inline void reset_outbuf(void)
94 static inline int outbuf_count(void)
96 return cur_outbuf - outbuf;
99 static void print_outbuf(void)
101 int sz = cur_outbuf - outbuf;
103 xwrite(STDOUT_FILENO, outbuf, sz);
108 static void put(const char *s)
111 if (sz > outbuf + sizeof(outbuf) - cur_outbuf)
112 sz = outbuf + sizeof(outbuf) - cur_outbuf;
113 memcpy(cur_outbuf, s, sz);
117 static void put_c(char c)
119 if (cur_outbuf < outbuf + sizeof(outbuf))
123 static void put_question_marks(int count)
129 static void readfile_z(proc_file *pf, const char* fname)
131 // open_read_close() will do two reads in order to be sure we are at EOF,
132 // and we don't need/want that.
140 buf = xmalloc(PROC_MIN_FILE_SIZE);
141 sz = PROC_MIN_FILE_SIZE;
144 fd = xopen(fname, O_RDONLY);
146 rdsz = read(fd, buf, sz-1);
149 if (rdsz == sz-1 && sz < PROC_MAX_FILE_SIZE) {
151 buf = xrealloc(buf, sz);
160 static const char* get_file(proc_file *pf)
162 if (pf->last_gen != gen) {
164 readfile_z(pf, proc_name[pf - &first_proc_file]);
169 static ullong read_after_slash(const char *p)
173 return strtoull(p+1, NULL, 10);
176 enum conv_type { conv_decimal, conv_slash };
178 // Reads decimal values from line. Values start after key, for example:
179 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
180 // Values are stored in vec[]. arg_ptr has list of positions
181 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
182 static int vrdval(const char* p, const char* key,
183 enum conv_type conv, ullong *vec, va_list arg_ptr)
193 indexnext = va_arg(arg_ptr, int);
195 while (*p == ' ' || *p == '\t') p++;
196 if (*p == '\n' || *p == '\0') break;
198 if (indexline == indexnext) { // read this value
199 *vec++ = conv==conv_decimal ?
200 strtoull(p, NULL, 10) :
202 indexnext = va_arg(arg_ptr, int);
204 while (*p > ' ') p++; // skip over value
210 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
211 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
212 // value# start with 1
213 static int rdval(const char* p, const char* key, ullong *vec, ...)
218 va_start(arg_ptr, vec);
219 result = vrdval(p, key, conv_decimal, vec, arg_ptr);
225 // Parses files with lines like "... ... ... 3/148 ...."
226 static int rdval_loadavg(const char* p, ullong *vec, ...)
231 va_start(arg_ptr, vec);
232 result = vrdval(p, "", conv_slash, vec, arg_ptr);
238 // Parses /proc/diskstats
239 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
240 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
241 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
242 static int rdval_diskstats(const char* p, ullong *vec)
244 ullong rd = rd; // for compiler
250 while (*p == ' ' || *p == '\t') p++;
251 if (*p == '\0') break;
257 if (indexline == 6) {
258 rd = strtoull(p, NULL, 10);
259 } else if (indexline == 10) {
260 vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize)
261 vec[1] += strtoull(p, NULL, 10);
262 while (*p != '\n' && *p != '\0') p++;
265 while (*p > ' ') p++; // skip over value
270 static void scale(ullong ul)
274 /* see http://en.wikipedia.org/wiki/Tera */
275 smart_ulltoa4(ul, buf, " kmgtpezy");
283 struct s_stat *next; \
284 void (*collect)(struct a *s) FAST_FUNC; \
286 #define S_STAT_END(a) } a;
291 static void FAST_FUNC collect_literal(s_stat *s UNUSED_PARAM)
295 static s_stat* init_literal(void)
297 s_stat *s = xzalloc(sizeof(*s));
298 s->collect = collect_literal;
302 static s_stat* init_delay(const char *param)
304 delta = strtoul(param, NULL, 0) * 1000; /* param can be "" */
305 deltanz = delta > 0 ? delta : 1;
306 need_seconds = (1000000%deltanz) != 0;
310 static s_stat* init_cr(const char *param UNUSED_PARAM)
317 // user nice system idle iowait irq softirq (last 3 only in 2.6)
318 //cpu 649369 0 341297 4336769 11640 7122 1183
319 //cpuN 649369 0 341297 4336769 11640 7122 1183
320 enum { CPU_FIELDCNT = 7 };
322 ullong old[CPU_FIELDCNT];
328 static void FAST_FUNC collect_cpu(cpu_stat *s)
330 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
331 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
334 int bar_sz = s->bar_sz;
338 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
339 put_question_marks(bar_sz);
343 for (i = 0; i < CPU_FIELDCNT; i++) {
344 ullong old = s->old[i];
345 if (data[i] < old) old = data[i]; //sanitize
347 all += (data[i] -= old);
351 for (i = 0; i < CPU_FIELDCNT; i++) {
352 ullong t = bar_sz * data[i];
353 norm_all += data[i] = t / all;
357 while (norm_all < bar_sz) {
358 unsigned max = frac[0];
360 for (i = 1; i < CPU_FIELDCNT; i++) {
361 if (frac[i] > max) max = frac[i], pos = i;
363 frac[pos] = 0; //avoid bumping up same value twice
368 memset(bar, '.', bar_sz);
369 memset(bar, 'S', data[2]); bar += data[2]; //sys
370 memset(bar, 'U', data[0]); bar += data[0]; //usr
371 memset(bar, 'N', data[1]); bar += data[1]; //nice
372 memset(bar, 'D', data[4]); bar += data[4]; //iowait
373 memset(bar, 'I', data[5]); bar += data[5]; //irq
374 memset(bar, 'i', data[6]); bar += data[6]; //softirq
376 memset(bar, '?', bar_sz);
382 static s_stat* init_cpu(const char *param)
385 cpu_stat *s = xzalloc(sizeof(*s));
386 s->collect = collect_cpu;
387 sz = strtoul(param, NULL, 0); /* param can be "" */
388 if (sz < 10) sz = 10;
389 if (sz > 1000) sz = 1000;
390 s->bar = xzalloc(sz+1);
391 /*s->bar[sz] = '\0'; - xzalloc did it */
402 static void FAST_FUNC collect_int(int_stat *s)
407 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
408 put_question_marks(4);
413 if (data[0] < old) old = data[0]; //sanitize
415 scale(data[0] - old);
418 static s_stat* init_int(const char *param)
420 int_stat *s = xzalloc(sizeof(*s));
421 s->collect = collect_int;
422 if (param[0] == '\0') {
425 int n = xatoi_u(param);
436 static void FAST_FUNC collect_ctx(ctx_stat *s)
441 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
442 put_question_marks(4);
447 if (data[0] < old) old = data[0]; //sanitize
449 scale(data[0] - old);
452 static s_stat* init_ctx(const char *param UNUSED_PARAM)
454 ctx_stat *s = xzalloc(sizeof(*s));
455 s->collect = collect_ctx;
465 static void FAST_FUNC collect_blk(blk_stat *s)
471 i = rdval_diskstats(get_file(&proc_diskstats), data);
473 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
474 // Linux 2.4 reports bio in Kbytes, convert to sectors:
479 put_question_marks(9);
483 for (i=0; i<2; i++) {
484 ullong old = s->old[i];
485 if (data[i] < old) old = data[i]; //sanitize
489 scale(data[0]*512); // TODO: *sectorsize
494 static s_stat* init_blk(const char *param UNUSED_PARAM)
496 blk_stat *s = xzalloc(sizeof(*s));
497 s->collect = collect_blk;
505 S_STAT_END(fork_stat)
507 static void FAST_FUNC collect_thread_nr(fork_stat *s UNUSED_PARAM)
511 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
512 put_question_marks(4);
518 static void FAST_FUNC collect_fork(fork_stat *s)
523 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
524 put_question_marks(4);
529 if (data[0] < old) old = data[0]; //sanitize
531 scale(data[0] - old);
534 static s_stat* init_fork(const char *param)
536 fork_stat *s = xzalloc(sizeof(*s));
538 s->collect = collect_thread_nr;
540 s->collect = collect_fork;
552 static void FAST_FUNC collect_if(if_stat *s)
557 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
558 put_question_marks(10);
562 for (i=0; i<4; i++) {
563 ullong old = s->old[i];
564 if (data[i] < old) old = data[i]; //sanitize
568 put_c(data[1] ? '*' : ' ');
570 put_c(data[3] ? '*' : ' ');
574 static s_stat* init_if(const char *device)
576 if_stat *s = xzalloc(sizeof(*s));
578 if (!device || !device[0])
580 s->collect = collect_if;
583 s->device_colon = xasprintf("%s:", device);
592 // "Memory" value should not include any caches.
593 // IOW: neither "ls -laR /" nor heavy read/write activity
594 // should affect it. We'd like to also include any
595 // long-term allocated kernel-side mem, but it is hard
596 // to figure out. For now, bufs, cached & slab are
597 // counted as "free" memory
599 //MemTotal: 773280 kB
600 //MemFree: 25912 kB - genuinely free
601 //Buffers: 320672 kB - cache
602 //Cached: 146396 kB - cache
605 //Inactive: 356892 kB
608 //LowTotal: 773280 kB
610 //SwapTotal: 131064 kB
611 //SwapFree: 131064 kB
615 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
616 // but includes dentries and inodes
617 // (== can take arbitrary amount of mem)
618 //CommitLimit: 517704 kB
619 //Committed_AS: 236776 kB
620 //PageTables: 1248 kB
621 //VmallocTotal: 516052 kB
622 //VmallocUsed: 3852 kB
623 //VmallocChunk: 512096 kB
626 //Hugepagesize: 4096 kB
627 static void FAST_FUNC collect_mem(mem_stat *s)
635 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
636 put_question_marks(4);
640 scale(m_total << 10);
644 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
645 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
646 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
647 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
649 put_question_marks(4);
653 m_free += m_bufs + m_cached + m_slab;
656 scale(m_free << 10); break;
658 scale((m_total - m_free) << 10); break;
662 static s_stat* init_mem(const char *param)
664 mem_stat *s = xzalloc(sizeof(*s));
665 s->collect = collect_mem;
674 static void FAST_FUNC collect_swp(swp_stat *s UNUSED_PARAM)
678 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
679 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
681 put_question_marks(4);
684 scale((s_total[0]-s_free[0]) << 10);
687 static s_stat* init_swp(const char *param UNUSED_PARAM)
689 swp_stat *s = xzalloc(sizeof(*s));
690 s->collect = collect_swp;
698 static void FAST_FUNC collect_fd(fd_stat *s UNUSED_PARAM)
702 if (rdval(get_file(&proc_sys_fs_filenr), "", data, 1, 2)) {
703 put_question_marks(4);
707 scale(data[0] - data[1]);
710 static s_stat* init_fd(const char *param UNUSED_PARAM)
712 fd_stat *s = xzalloc(sizeof(*s));
713 s->collect = collect_fd;
721 S_STAT_END(time_stat)
723 static void FAST_FUNC collect_time(time_stat *s)
725 char buf[sizeof("12:34:56.123456")];
727 int us = tv.tv_usec + s->scale/2;
728 time_t t = tv.tv_sec;
736 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
738 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
742 static s_stat* init_time(const char *param)
745 time_stat *s = xzalloc(sizeof(*s));
747 s->collect = collect_time;
748 prec = param[0] - '0';
749 if (prec < 0) prec = 0;
750 else if (prec > 6) prec = 6;
758 static void FAST_FUNC collect_info(s_stat *s)
769 typedef s_stat* init_func(const char *param);
771 static const char options[] ALIGN1 = "ncmsfixptbdr";
772 static init_func *const init_functions[] = {
787 int nmeter_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
788 int nmeter_main(int argc, char **argv)
791 s_stat *first = NULL;
803 if (open_read_close("version", buf, sizeof(buf)-1) > 0) {
804 buf[sizeof(buf)-1] = '\0';
805 is26 = (strstr(buf, " 2.4.") == NULL);
808 // Can use argv[1] directly, but this will mess up
809 // parameters as seen by e.g. ps. Making a copy...
810 cur = xstrdup(argv[1]);
815 cur = strchr(cur, '%');
818 if (cur[1] == '%') { // %%
819 overlapping_strcpy(cur, cur + 1);
823 *cur++ = '\0'; // overwrite %
825 // format: %[foptstring]
827 p = strchr(options, cur[0]);
829 while (cur[0] != ']') {
834 *cur++ = '\0'; // overwrite [
838 while (cur[0] >= '0' && cur[0] <= '9')
842 p = strchr(options, cur[0]);
843 *cur++ = '\0'; // overwrite format char
847 s = init_functions[p-options](param);
850 /*s->next = NULL; - all initXXX funcs use xzalloc */
857 // %NNNNd or %r option. remove it from string
858 strcpy(prev + strlen(prev), cur);
865 /*s->next = NULL; - all initXXX funcs use xzalloc */
873 // Generate first samples but do not print them, they're bogus
877 gettimeofday(&tv, NULL);
878 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
882 gettimeofday(&tv, NULL);
887 // Negative delta -> no usleep at all
888 // This will hog the CPU but you can have REALLY GOOD
889 // time resolution ;)
890 // TODO: detect and avoid useless updates
891 // (like: nothing happens except time)
894 // can be commented out, will sacrifice sleep time precision a bit
895 gettimeofday(&tv, NULL);
897 rem = delta - ((ullong)tv.tv_sec*1000000 + tv.tv_usec) % deltanz;
899 rem = delta - tv.tv_usec%deltanz;
900 // Sometimes kernel wakes us up just a tiny bit earlier than asked
901 // Do not go to very short sleep in this case
902 if (rem < delta/128) {