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})
23 typedef unsigned long long ullong;
25 enum { PROC_FILE_SIZE = 4096 };
27 typedef struct proc_file {
33 static const char *const proc_name[] = {
34 "stat", // Must match the order of proc_file's!
43 // Sample generation flip-flop
45 // Linux 2.6? (otherwise assumes 2.4)
47 // 1 if sample delay is not an integer fraction of a second
48 smallint need_seconds;
50 const char *final_str;
54 #define first_proc_file proc_stat
55 proc_file proc_stat; // Must match the order of proc_name's!
56 proc_file proc_loadavg;
57 proc_file proc_net_dev;
58 proc_file proc_meminfo;
59 proc_file proc_diskstats;
60 proc_file proc_sys_fs_filenr;
62 #define G (*ptr_to_globals)
64 #define is26 (G.is26 )
65 #define need_seconds (G.need_seconds )
66 #define cur_outbuf (G.cur_outbuf )
67 #define final_str (G.final_str )
68 #define delta (G.delta )
69 #define deltanz (G.deltanz )
71 #define proc_stat (G.proc_stat )
72 #define proc_loadavg (G.proc_loadavg )
73 #define proc_net_dev (G.proc_net_dev )
74 #define proc_meminfo (G.proc_meminfo )
75 #define proc_diskstats (G.proc_diskstats )
76 #define proc_sys_fs_filenr (G.proc_sys_fs_filenr)
77 #define INIT_G() do { \
78 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
79 cur_outbuf = outbuf; \
81 deltanz = delta = 1000000; \
84 // We depend on this being a char[], not char* - we take sizeof() of it
85 #define outbuf bb_common_bufsiz1
87 static inline void reset_outbuf(void)
92 static inline int outbuf_count(void)
94 return cur_outbuf - outbuf;
97 static void print_outbuf(void)
99 int sz = cur_outbuf - outbuf;
101 xwrite(STDOUT_FILENO, outbuf, sz);
106 static void put(const char *s)
109 if (sz > outbuf + sizeof(outbuf) - cur_outbuf)
110 sz = outbuf + sizeof(outbuf) - cur_outbuf;
111 memcpy(cur_outbuf, s, sz);
115 static void put_c(char c)
117 if (cur_outbuf < outbuf + sizeof(outbuf))
121 static void put_question_marks(int count)
127 static void readfile_z(char *buf, int sz, const char* fname)
129 // open_read_close() will do two reads in order to be sure we are at EOF,
130 // and we don't need/want that.
131 // sz = open_read_close(fname, buf, sz-1);
133 int fd = xopen(fname, O_RDONLY);
135 sz = read(fd, buf, sz - 1);
141 static const char* get_file(proc_file *pf)
143 if (pf->last_gen != gen) {
145 // We allocate PROC_FILE_SIZE bytes. This wastes memory,
146 // but allows us to allocate only once (at first sample)
147 // per proc file, and reuse buffer for each sample
149 pf->file = xmalloc(PROC_FILE_SIZE);
150 readfile_z(pf->file, PROC_FILE_SIZE, proc_name[pf - &first_proc_file]);
155 static inline ullong read_after_slash(const char *p)
159 return strtoull(p+1, NULL, 10);
162 enum conv_type { conv_decimal, conv_slash };
164 // Reads decimal values from line. Values start after key, for example:
165 // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
166 // Values are stored in vec[]. arg_ptr has list of positions
167 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
168 static int vrdval(const char* p, const char* key,
169 enum conv_type conv, ullong *vec, va_list arg_ptr)
179 indexnext = va_arg(arg_ptr, int);
181 while (*p == ' ' || *p == '\t') p++;
182 if (*p == '\n' || *p == '\0') break;
184 if (indexline == indexnext) { // read this value
185 *vec++ = conv==conv_decimal ?
186 strtoull(p, NULL, 10) :
188 indexnext = va_arg(arg_ptr, int);
190 while (*p > ' ') p++; // skip over value
196 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
197 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
198 // value# start with 1
199 static int rdval(const char* p, const char* key, ullong *vec, ...)
204 va_start(arg_ptr, vec);
205 result = vrdval(p, key, conv_decimal, vec, arg_ptr);
211 // Parses files with lines like "... ... ... 3/148 ...."
212 static int rdval_loadavg(const char* p, ullong *vec, ...)
217 va_start(arg_ptr, vec);
218 result = vrdval(p, "", conv_slash, vec, arg_ptr);
224 // Parses /proc/diskstats
225 // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
226 // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
227 // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
228 static int rdval_diskstats(const char* p, ullong *vec)
230 ullong rd = rd; // for compiler
236 while (*p == ' ' || *p == '\t') p++;
237 if (*p == '\0') break;
243 if (indexline == 6) {
244 rd = strtoull(p, NULL, 10);
245 } else if (indexline == 10) {
246 vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize)
247 vec[1] += strtoull(p, NULL, 10);
248 while (*p != '\n' && *p != '\0') p++;
251 while (*p > ' ') p++; // skip over value
256 static void scale(ullong ul)
260 /* see http://en.wikipedia.org/wiki/Tera */
261 smart_ulltoa4(ul, buf, " kmgtpezy");
269 struct s_stat *next; \
270 void (*collect)(struct a *s); \
272 #define S_STAT_END(a) } a;
277 static void collect_literal(s_stat *s UNUSED_PARAM)
281 static s_stat* init_literal(void)
283 s_stat *s = xzalloc(sizeof(*s));
284 s->collect = collect_literal;
288 static s_stat* init_delay(const char *param)
290 delta = strtoul(param, NULL, 0) * 1000; /* param can be "" */
291 deltanz = delta > 0 ? delta : 1;
292 need_seconds = (1000000%deltanz) != 0;
296 static s_stat* init_cr(const char *param UNUSED_PARAM)
303 // user nice system idle iowait irq softirq (last 3 only in 2.6)
304 //cpu 649369 0 341297 4336769 11640 7122 1183
305 //cpuN 649369 0 341297 4336769 11640 7122 1183
306 enum { CPU_FIELDCNT = 7 };
308 ullong old[CPU_FIELDCNT];
314 static void collect_cpu(cpu_stat *s)
316 ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
317 unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
320 int bar_sz = s->bar_sz;
324 if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
325 put_question_marks(bar_sz);
329 for (i = 0; i < CPU_FIELDCNT; i++) {
330 ullong old = s->old[i];
331 if (data[i] < old) old = data[i]; //sanitize
333 all += (data[i] -= old);
337 for (i = 0; i < CPU_FIELDCNT; i++) {
338 ullong t = bar_sz * data[i];
339 norm_all += data[i] = t / all;
343 while (norm_all < bar_sz) {
344 unsigned max = frac[0];
346 for (i = 1; i < CPU_FIELDCNT; i++) {
347 if (frac[i] > max) max = frac[i], pos = i;
349 frac[pos] = 0; //avoid bumping up same value twice
354 memset(bar, '.', bar_sz);
355 memset(bar, 'S', data[2]); bar += data[2]; //sys
356 memset(bar, 'U', data[0]); bar += data[0]; //usr
357 memset(bar, 'N', data[1]); bar += data[1]; //nice
358 memset(bar, 'D', data[4]); bar += data[4]; //iowait
359 memset(bar, 'I', data[5]); bar += data[5]; //irq
360 memset(bar, 'i', data[6]); bar += data[6]; //softirq
362 memset(bar, '?', bar_sz);
368 static s_stat* init_cpu(const char *param)
371 cpu_stat *s = xzalloc(sizeof(*s));
372 s->collect = collect_cpu;
373 sz = strtoul(param, NULL, 0); /* param can be "" */
374 if (sz < 10) sz = 10;
375 if (sz > 1000) sz = 1000;
376 s->bar = xzalloc(sz+1);
377 /*s->bar[sz] = '\0'; - xzalloc did it */
388 static void collect_int(int_stat *s)
393 if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
394 put_question_marks(4);
399 if (data[0] < old) old = data[0]; //sanitize
401 scale(data[0] - old);
404 static s_stat* init_int(const char *param)
406 int_stat *s = xzalloc(sizeof(*s));
407 s->collect = collect_int;
408 if (param[0] == '\0') {
411 int n = xatoi_u(param);
422 static void collect_ctx(ctx_stat *s)
427 if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
428 put_question_marks(4);
433 if (data[0] < old) old = data[0]; //sanitize
435 scale(data[0] - old);
438 static s_stat* init_ctx(const char *param UNUSED_PARAM)
440 ctx_stat *s = xzalloc(sizeof(*s));
441 s->collect = collect_ctx;
451 static void collect_blk(blk_stat *s)
457 i = rdval_diskstats(get_file(&proc_diskstats), data);
459 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
460 // Linux 2.4 reports bio in Kbytes, convert to sectors:
465 put_question_marks(9);
469 for (i=0; i<2; i++) {
470 ullong old = s->old[i];
471 if (data[i] < old) old = data[i]; //sanitize
475 scale(data[0]*512); // TODO: *sectorsize
480 static s_stat* init_blk(const char *param UNUSED_PARAM)
482 blk_stat *s = xzalloc(sizeof(*s));
483 s->collect = collect_blk;
491 S_STAT_END(fork_stat)
493 static void collect_thread_nr(fork_stat *s UNUSED_PARAM)
497 if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
498 put_question_marks(4);
504 static void collect_fork(fork_stat *s)
509 if (rdval(get_file(&proc_stat), "processes", data, 1)) {
510 put_question_marks(4);
515 if (data[0] < old) old = data[0]; //sanitize
517 scale(data[0] - old);
520 static s_stat* init_fork(const char *param)
522 fork_stat *s = xzalloc(sizeof(*s));
524 s->collect = collect_thread_nr;
526 s->collect = collect_fork;
538 static void collect_if(if_stat *s)
543 if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
544 put_question_marks(10);
548 for (i=0; i<4; i++) {
549 ullong old = s->old[i];
550 if (data[i] < old) old = data[i]; //sanitize
554 put_c(data[1] ? '*' : ' ');
556 put_c(data[3] ? '*' : ' ');
560 static s_stat* init_if(const char *device)
562 if_stat *s = xzalloc(sizeof(*s));
564 if (!device || !device[0])
566 s->collect = collect_if;
569 s->device_colon = xasprintf("%s:", device);
578 // "Memory" value should not include any caches.
579 // IOW: neither "ls -laR /" nor heavy read/write activity
580 // should affect it. We'd like to also include any
581 // long-term allocated kernel-side mem, but it is hard
582 // to figure out. For now, bufs, cached & slab are
583 // counted as "free" memory
585 //MemTotal: 773280 kB
586 //MemFree: 25912 kB - genuinely free
587 //Buffers: 320672 kB - cache
588 //Cached: 146396 kB - cache
591 //Inactive: 356892 kB
594 //LowTotal: 773280 kB
596 //SwapTotal: 131064 kB
597 //SwapFree: 131064 kB
601 //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
602 // but includes dentries and inodes
603 // (== can take arbitrary amount of mem)
604 //CommitLimit: 517704 kB
605 //Committed_AS: 236776 kB
606 //PageTables: 1248 kB
607 //VmallocTotal: 516052 kB
608 //VmallocUsed: 3852 kB
609 //VmallocChunk: 512096 kB
612 //Hugepagesize: 4096 kB
613 static void collect_mem(mem_stat *s)
621 if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
622 put_question_marks(4);
626 scale(m_total << 10);
630 if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1)
631 || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1)
632 || rdval(proc_meminfo.file, "Cached:", &m_cached, 1)
633 || rdval(proc_meminfo.file, "Slab:", &m_slab , 1)
635 put_question_marks(4);
639 m_free += m_bufs + m_cached + m_slab;
642 scale(m_free << 10); break;
644 scale((m_total - m_free) << 10); break;
648 static s_stat* init_mem(const char *param)
650 mem_stat *s = xzalloc(sizeof(*s));
651 s->collect = collect_mem;
660 static void collect_swp(swp_stat *s UNUSED_PARAM)
664 if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
665 || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1)
667 put_question_marks(4);
670 scale((s_total[0]-s_free[0]) << 10);
673 static s_stat* init_swp(const char *param UNUSED_PARAM)
675 swp_stat *s = xzalloc(sizeof(*s));
676 s->collect = collect_swp;
684 static void collect_fd(fd_stat *s UNUSED_PARAM)
688 if (rdval(get_file(&proc_sys_fs_filenr), "", data, 1, 2)) {
689 put_question_marks(4);
693 scale(data[0] - data[1]);
696 static s_stat* init_fd(const char *param UNUSED_PARAM)
698 fd_stat *s = xzalloc(sizeof(*s));
699 s->collect = collect_fd;
707 S_STAT_END(time_stat)
709 static void collect_time(time_stat *s)
711 char buf[sizeof("12:34:56.123456")];
713 int us = tv.tv_usec + s->scale/2;
714 time_t t = tv.tv_sec;
722 sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
724 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
728 static s_stat* init_time(const char *param)
731 time_stat *s = xzalloc(sizeof(*s));
733 s->collect = collect_time;
734 prec = param[0] - '0';
735 if (prec < 0) prec = 0;
736 else if (prec > 6) prec = 6;
744 static void collect_info(s_stat *s)
755 typedef s_stat* init_func(const char *param);
757 static const char options[] ALIGN1 = "ncmsfixptbdr";
758 static init_func *const init_functions[] = {
773 int nmeter_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
774 int nmeter_main(int argc, char **argv)
777 s_stat *first = NULL;
789 if (open_read_close("version", buf, sizeof(buf)) > 0)
790 is26 = (strstr(buf, " 2.4.")==NULL);
792 // Can use argv[1] directly, but this will mess up
793 // parameters as seen by e.g. ps. Making a copy...
794 cur = xstrdup(argv[1]);
799 cur = strchr(cur, '%');
802 if (cur[1] == '%') { // %%
807 *cur++ = '\0'; // overwrite %
809 // format: %[foptstring]
811 p = strchr(options, cur[0]);
813 while (cur[0] != ']') {
818 *cur++ = '\0'; // overwrite [
822 while (cur[0] >= '0' && cur[0] <= '9')
826 p = strchr(options, cur[0]);
827 *cur++ = '\0'; // overwrite format char
831 s = init_functions[p-options](param);
834 /*s->next = NULL; - all initXXX funcs use xzalloc */
841 // %NNNNd or %r option. remove it from string
842 strcpy(prev + strlen(prev), cur);
849 /*s->next = NULL; - all initXXX funcs use xzalloc */
857 // Generate first samples but do not print them, they're bogus
861 gettimeofday(&tv, NULL);
862 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
866 gettimeofday(&tv, NULL);
871 // Negative delta -> no usleep at all
872 // This will hog the CPU but you can have REALLY GOOD
873 // time resolution ;)
874 // TODO: detect and avoid useless updates
875 // (like: nothing happens except time)
878 // can be commented out, will sacrifice sleep time precision a bit
879 gettimeofday(&tv, NULL);
881 rem = delta - ((ullong)tv.tv_sec*1000000 + tv.tv_usec) % deltanz;
883 rem = delta - tv.tv_usec%deltanz;
884 // Sometimes kernel wakes us up just a tiny bit earlier than asked
885 // Do not go to very short sleep in this case
886 if (rem < delta/128) {