3
0

nmeter.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. /*
  2. * Licensed under GPLv2, see file LICENSE in this source tree.
  3. *
  4. * Based on nanotop.c from floppyfw project
  5. *
  6. * Contact me: vda.linux@googlemail.com
  7. */
  8. //config:config NMETER
  9. //config: bool "nmeter (12 kb)"
  10. //config: default y
  11. //config: help
  12. //config: Prints selected system stats continuously, one line per update.
  13. //applet:IF_NMETER(APPLET(nmeter, BB_DIR_USR_BIN, BB_SUID_DROP))
  14. //kbuild:lib-$(CONFIG_NMETER) += nmeter.o
  15. //usage:#define nmeter_trivial_usage
  16. //usage: "[-d MSEC] FORMAT_STRING"
  17. //usage:#define nmeter_full_usage "\n\n"
  18. //usage: "Monitor system in real time"
  19. //usage: "\n"
  20. //usage: "\n -d MSEC Milliseconds between updates, default:1000, none:-1"
  21. //usage: "\n"
  22. //usage: "\nFormat specifiers:"
  23. //usage: "\n %Nc or %[cN] CPU. N - bar size (default 10)"
  24. //usage: "\n (displays: S:system U:user N:niced D:iowait I:irq i:softirq)"
  25. //usage: "\n %[nINTERFACE] Network INTERFACE"
  26. //usage: "\n %m Allocated memory"
  27. //usage: "\n %[md] Dirty file-backed memory"
  28. //usage: "\n %[mw] Memory being written to storage"
  29. //usage: "\n %[mf] Free memory"
  30. //usage: "\n %[mt] Total memory"
  31. //usage: "\n %s Allocated swap"
  32. //usage: "\n %f Number of used file descriptors"
  33. //usage: "\n %Ni Total/specific IRQ rate"
  34. //usage: "\n %x Context switch rate"
  35. //usage: "\n %p Forks"
  36. //usage: "\n %[pn] # of processes"
  37. //usage: "\n %b Block io"
  38. //usage: "\n %Nt Time (with N decimal points)"
  39. //usage: "\n %NT Zero-based timestamp (with N decimal points)"
  40. //usage: "\n %r Print <cr> instead of <lf> at EOL"
  41. //TODO:
  42. // simplify code
  43. // /proc/locks
  44. // /proc/stat:
  45. // disk_io: (3,0):(22272,17897,410702,4375,54750)
  46. // btime 1059401962
  47. //TODO: use sysinfo libc call/syscall, if appropriate
  48. // (faster than open/read/close):
  49. // sysinfo({uptime=15017, loads=[5728, 15040, 16480]
  50. // totalram=2107416576, freeram=211525632, sharedram=0, bufferram=157204480}
  51. // totalswap=134209536, freeswap=134209536, procs=157})
  52. #include "libbb.h"
  53. #include "common_bufsiz.h"
  54. typedef unsigned long long ullong;
  55. enum {
  56. PROC_MIN_FILE_SIZE = 256,
  57. PROC_MAX_FILE_SIZE = 64 * 1024, /* 16k was a bit too small for a 128-CPU machine */
  58. };
  59. typedef struct proc_file {
  60. char *file;
  61. int file_sz;
  62. smallint last_gen;
  63. } proc_file;
  64. static const char *const proc_name[] ALIGN_PTR = {
  65. "stat", // Must match the order of proc_file's!
  66. "loadavg",
  67. "net/dev",
  68. "meminfo",
  69. "diskstats",
  70. "sys/fs/file-nr"
  71. };
  72. struct globals {
  73. // Sample generation flip-flop
  74. smallint gen;
  75. // Linux 2.6? (otherwise assumes 2.4)
  76. smallint is26;
  77. // 1 if sample delay is not an integer fraction of a second
  78. smallint need_seconds;
  79. char final_char;
  80. char *cur_outbuf;
  81. int delta;
  82. unsigned deltanz;
  83. struct timeval tv;
  84. struct timeval start;
  85. #define first_proc_file proc_stat
  86. proc_file proc_stat; // Must match the order of proc_name's!
  87. proc_file proc_loadavg;
  88. proc_file proc_net_dev;
  89. proc_file proc_meminfo;
  90. proc_file proc_diskstats;
  91. proc_file proc_sys_fs_filenr;
  92. };
  93. #define G (*ptr_to_globals)
  94. #define gen (G.gen )
  95. #define is26 (G.is26 )
  96. #define need_seconds (G.need_seconds )
  97. #define cur_outbuf (G.cur_outbuf )
  98. #define proc_stat (G.proc_stat )
  99. #define proc_loadavg (G.proc_loadavg )
  100. #define proc_net_dev (G.proc_net_dev )
  101. #define proc_meminfo (G.proc_meminfo )
  102. #define proc_diskstats (G.proc_diskstats )
  103. #define proc_sys_fs_filenr (G.proc_sys_fs_filenr)
  104. #define outbuf bb_common_bufsiz1
  105. #define INIT_G() do { \
  106. setup_common_bufsiz(); \
  107. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  108. cur_outbuf = outbuf; \
  109. G.final_char = '\n'; \
  110. G.deltanz = G.delta = 1000000; \
  111. } while (0)
  112. static inline void reset_outbuf(void)
  113. {
  114. cur_outbuf = outbuf;
  115. }
  116. static void print_outbuf(void)
  117. {
  118. int sz = cur_outbuf - outbuf;
  119. if (sz > 0) {
  120. xwrite(STDOUT_FILENO, outbuf, sz);
  121. cur_outbuf = outbuf;
  122. }
  123. }
  124. static void put(const char *s)
  125. {
  126. char *p = cur_outbuf;
  127. int sz = outbuf + COMMON_BUFSIZE - p;
  128. while (*s && --sz >= 0)
  129. *p++ = *s++;
  130. cur_outbuf = p;
  131. }
  132. static void put_c(char c)
  133. {
  134. if (cur_outbuf < outbuf + COMMON_BUFSIZE)
  135. *cur_outbuf++ = c;
  136. }
  137. static void put_question_marks(int count)
  138. {
  139. while (count--)
  140. put_c('?');
  141. }
  142. static void readfile_z(proc_file *pf, const char* fname)
  143. {
  144. // open_read_close() will do two reads in order to be sure we are at EOF,
  145. // and we don't need/want that.
  146. int fd;
  147. int sz, rdsz;
  148. char *buf;
  149. sz = pf->file_sz;
  150. buf = pf->file;
  151. if (!buf) {
  152. buf = xmalloc(PROC_MIN_FILE_SIZE);
  153. sz = PROC_MIN_FILE_SIZE;
  154. }
  155. again:
  156. fd = xopen(fname, O_RDONLY);
  157. buf[0] = '\0';
  158. rdsz = read(fd, buf, sz-1);
  159. close(fd);
  160. if (rdsz > 0) {
  161. if (rdsz == sz-1 && sz < PROC_MAX_FILE_SIZE) {
  162. if (sz < 4 * 1024)
  163. sz *= 2;
  164. else
  165. sz += 4 * 1024;
  166. buf = xrealloc(buf, sz);
  167. goto again;
  168. }
  169. buf[rdsz] = '\0';
  170. }
  171. pf->file_sz = sz;
  172. pf->file = buf;
  173. }
  174. static const char* get_file(proc_file *pf)
  175. {
  176. if (pf->last_gen != gen) {
  177. pf->last_gen = gen;
  178. readfile_z(pf, proc_name[pf - &first_proc_file]);
  179. }
  180. return pf->file;
  181. }
  182. static ullong read_after_slash(const char *p)
  183. {
  184. p = strchr(p, '/');
  185. if (!p) return 0;
  186. return strtoull(p+1, NULL, 10);
  187. }
  188. enum conv_type {
  189. conv_decimal = 0,
  190. conv_slash = 1
  191. };
  192. // Reads decimal values from line. Values start after key, for example:
  193. // "cpu 649369 0 341297 4336769..." - key is "cpu" here.
  194. // Values are stored in vec[].
  195. // posbits is a bit list of positions we are interested in.
  196. // for example: 00100110 - we want 1st, 2nd and 5th value.
  197. // posbits.bit0 encodes conversion type.
  198. static int rdval(const char* p, const char* key, ullong *vec, long posbits)
  199. {
  200. unsigned curpos;
  201. p = strstr(p, key);
  202. if (!p) return 1;
  203. p += strlen(key);
  204. curpos = 1 << 1;
  205. while (1) {
  206. while (*p == ' ' || *p == '\t') p++;
  207. if (*p == '\n' || *p == '\0') break;
  208. if (curpos & posbits) { // read this value
  209. *vec++ = (posbits & 1) == conv_decimal ?
  210. strtoull(p, NULL, 10) :
  211. read_after_slash(p);
  212. posbits -= curpos;
  213. if (posbits <= 1)
  214. return 0;
  215. }
  216. while (*p > ' ') // skip over the value
  217. p++;
  218. curpos <<= 1;
  219. }
  220. return 0;
  221. }
  222. // Parses files with lines like "... ... ... 3/148 ...."
  223. static int rdval_loadavg(const char* p, ullong *vec, long posbits)
  224. {
  225. int result;
  226. result = rdval(p, "", vec, posbits | conv_slash);
  227. return result;
  228. }
  229. // Parses /proc/diskstats
  230. // 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14
  231. // 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
  232. // 3 1 hda1 0 0 0 0 <- ignore if only 4 fields
  233. // Linux 3.0 (maybe earlier) started printing full stats for hda1 too.
  234. // Had to add code which skips such devices.
  235. static int rdval_diskstats(const char* p, ullong *vec)
  236. {
  237. char devname[32];
  238. unsigned devname_len = 0;
  239. int value_idx = 0;
  240. vec[0] = 0;
  241. vec[1] = 0;
  242. while (1) {
  243. value_idx++;
  244. while (*p == ' ' || *p == '\t')
  245. p++;
  246. if (*p == '\0')
  247. break;
  248. if (*p == '\n') {
  249. value_idx = 0;
  250. p++;
  251. continue;
  252. }
  253. if (value_idx == 3) {
  254. char *end = strchrnul(p, ' ');
  255. /* If this a hda1-like device (same prefix as last one + digit)? */
  256. if (devname_len && strncmp(devname, p, devname_len) == 0 && isdigit(p[devname_len])) {
  257. p = end;
  258. goto skip_line; /* skip entire line */
  259. }
  260. /* It is not. Remember the name for future checks */
  261. devname_len = end - p;
  262. if (devname_len > sizeof(devname)-1)
  263. devname_len = sizeof(devname)-1;
  264. strncpy(devname, p, devname_len);
  265. /* devname[devname_len] = '\0'; - not really needed */
  266. p = end;
  267. } else
  268. if (value_idx == 6) {
  269. // TODO: *sectorsize (don't know how to find out sectorsize)
  270. vec[0] += strtoull(p, NULL, 10);
  271. } else
  272. if (value_idx == 10) {
  273. // TODO: *sectorsize (don't know how to find out sectorsize)
  274. vec[1] += strtoull(p, NULL, 10);
  275. skip_line:
  276. while (*p != '\n' && *p != '\0')
  277. p++;
  278. continue;
  279. }
  280. while ((unsigned char)(*p) > ' ') // skip over value
  281. p++;
  282. }
  283. return 0;
  284. }
  285. static void scale(ullong ul)
  286. {
  287. char buf[5];
  288. /* see http://en.wikipedia.org/wiki/Tera */
  289. smart_ulltoa4(ul, buf, " kmgtpezy")[0] = '\0';
  290. put(buf);
  291. }
  292. #define S_STAT(a) \
  293. typedef struct a { \
  294. struct s_stat *next; \
  295. void (*collect)(struct a *s) FAST_FUNC; \
  296. const char *label;
  297. #define S_STAT_END(a) } a;
  298. S_STAT(s_stat)
  299. S_STAT_END(s_stat)
  300. static void FAST_FUNC collect_literal(s_stat *s UNUSED_PARAM)
  301. {
  302. }
  303. static s_stat* init_literal(void)
  304. {
  305. s_stat *s = xzalloc(sizeof(*s));
  306. s->collect = collect_literal;
  307. return (s_stat*)s;
  308. }
  309. static s_stat* init_cr(const char *param UNUSED_PARAM)
  310. {
  311. G.final_char = '\r';
  312. return NULL;
  313. }
  314. // user nice system idle iowait irq softirq (last 3 only in 2.6)
  315. //cpu 649369 0 341297 4336769 11640 7122 1183
  316. //cpuN 649369 0 341297 4336769 11640 7122 1183
  317. enum { CPU_FIELDCNT = 7 };
  318. S_STAT(cpu_stat)
  319. ullong old[CPU_FIELDCNT];
  320. unsigned bar_sz;
  321. char bar[1];
  322. S_STAT_END(cpu_stat)
  323. static void FAST_FUNC collect_cpu(cpu_stat *s)
  324. {
  325. ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
  326. unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
  327. ullong all = 0;
  328. unsigned norm_all = 0;
  329. unsigned bar_sz = s->bar_sz;
  330. char *bar = s->bar;
  331. int i;
  332. if (rdval(get_file(&proc_stat), "cpu ", data, 0
  333. | (1 << 1)
  334. | (1 << 2)
  335. | (1 << 3)
  336. | (1 << 4)
  337. | (1 << 5)
  338. | (1 << 6)
  339. | (1 << 7))
  340. ) {
  341. put_question_marks(bar_sz);
  342. return;
  343. }
  344. for (i = 0; i < CPU_FIELDCNT; i++) {
  345. ullong old = s->old[i];
  346. if (data[i] < old) old = data[i]; //sanitize
  347. s->old[i] = data[i];
  348. all += (data[i] -= old);
  349. }
  350. if (all) {
  351. for (i = 0; i < CPU_FIELDCNT; i++) {
  352. ullong t = bar_sz * data[i];
  353. norm_all += data[i] = t / all;
  354. frac[i] = t % all;
  355. }
  356. while (norm_all < bar_sz) {
  357. unsigned max = frac[0];
  358. int pos = 0;
  359. for (i = 1; i < CPU_FIELDCNT; i++) {
  360. if (frac[i] > max) max = frac[i], pos = i;
  361. }
  362. frac[pos] = 0; //avoid bumping up same value twice
  363. data[pos]++;
  364. norm_all++;
  365. }
  366. memset(bar, '.', bar_sz);
  367. memset(bar, 'S', data[2]); bar += data[2]; //sys
  368. memset(bar, 'U', data[0]); bar += data[0]; //usr
  369. memset(bar, 'N', data[1]); bar += data[1]; //nice
  370. memset(bar, 'D', data[4]); bar += data[4]; //iowait
  371. memset(bar, 'I', data[5]); bar += data[5]; //irq
  372. memset(bar, 'i', data[6]); bar += data[6]; //softirq
  373. } else {
  374. memset(bar, '?', bar_sz);
  375. }
  376. put(s->bar);
  377. }
  378. static s_stat* init_cpu(const char *param)
  379. {
  380. int sz;
  381. cpu_stat *s;
  382. sz = param[0] ? strtoul(param, NULL, 0) : 10;
  383. if (sz <= 0) sz = 1;
  384. if (sz > 1000) sz = 1000;
  385. s = xzalloc(sizeof(*s) + sz);
  386. /*s->bar[sz] = '\0'; - xzalloc did it */
  387. s->bar_sz = sz;
  388. s->collect = collect_cpu;
  389. return (s_stat*)s;
  390. }
  391. S_STAT(int_stat)
  392. ullong old;
  393. int no;
  394. S_STAT_END(int_stat)
  395. static void FAST_FUNC collect_int(int_stat *s)
  396. {
  397. ullong data[1];
  398. ullong old;
  399. if (rdval(get_file(&proc_stat), "intr", data, 1 << s->no)) {
  400. put_question_marks(4);
  401. return;
  402. }
  403. old = s->old;
  404. if (data[0] < old) old = data[0]; //sanitize
  405. s->old = data[0];
  406. scale(data[0] - old);
  407. }
  408. static s_stat* init_int(const char *param)
  409. {
  410. int_stat *s = xzalloc(sizeof(*s));
  411. s->collect = collect_int;
  412. if (param[0] == '\0') {
  413. s->no = 1;
  414. } else {
  415. int n = xatoi_positive(param);
  416. s->no = n + 2;
  417. }
  418. return (s_stat*)s;
  419. }
  420. S_STAT(ctx_stat)
  421. ullong old;
  422. S_STAT_END(ctx_stat)
  423. static void FAST_FUNC collect_ctx(ctx_stat *s)
  424. {
  425. ullong data[1];
  426. ullong old;
  427. if (rdval(get_file(&proc_stat), "ctxt", data, 1 << 1)) {
  428. put_question_marks(4);
  429. return;
  430. }
  431. old = s->old;
  432. if (data[0] < old) old = data[0]; //sanitize
  433. s->old = data[0];
  434. scale(data[0] - old);
  435. }
  436. static s_stat* init_ctx(const char *param UNUSED_PARAM)
  437. {
  438. ctx_stat *s = xzalloc(sizeof(*s));
  439. s->collect = collect_ctx;
  440. return (s_stat*)s;
  441. }
  442. S_STAT(blk_stat)
  443. const char* lookfor;
  444. ullong old[2];
  445. S_STAT_END(blk_stat)
  446. static void FAST_FUNC collect_blk(blk_stat *s)
  447. {
  448. ullong data[2];
  449. int i;
  450. if (is26) {
  451. i = rdval_diskstats(get_file(&proc_diskstats), data);
  452. } else {
  453. i = rdval(get_file(&proc_stat), s->lookfor, data, 0
  454. | (1 << 1)
  455. | (1 << 2)
  456. );
  457. // Linux 2.4 reports bio in Kbytes, convert to sectors:
  458. data[0] *= 2;
  459. data[1] *= 2;
  460. }
  461. if (i) {
  462. put_question_marks(9);
  463. return;
  464. }
  465. for (i = 0; i < 2; i++) {
  466. ullong old = s->old[i];
  467. if (data[i] < old) old = data[i]; //sanitize
  468. s->old[i] = data[i];
  469. data[i] -= old;
  470. }
  471. scale(data[0]*512); // TODO: *sectorsize
  472. put_c(' ');
  473. scale(data[1]*512);
  474. }
  475. static s_stat* init_blk(const char *param UNUSED_PARAM)
  476. {
  477. blk_stat *s = xzalloc(sizeof(*s));
  478. s->collect = collect_blk;
  479. s->lookfor = "page";
  480. return (s_stat*)s;
  481. }
  482. S_STAT(fork_stat)
  483. ullong old;
  484. S_STAT_END(fork_stat)
  485. static void FAST_FUNC collect_thread_nr(fork_stat *s UNUSED_PARAM)
  486. {
  487. ullong data[1];
  488. if (rdval_loadavg(get_file(&proc_loadavg), data, 1 << 4)) {
  489. put_question_marks(4);
  490. return;
  491. }
  492. scale(data[0]);
  493. }
  494. static void FAST_FUNC collect_fork(fork_stat *s)
  495. {
  496. ullong data[1];
  497. ullong old;
  498. if (rdval(get_file(&proc_stat), "processes", data, 1 << 1)) {
  499. put_question_marks(4);
  500. return;
  501. }
  502. old = s->old;
  503. if (data[0] < old) old = data[0]; //sanitize
  504. s->old = data[0];
  505. scale(data[0] - old);
  506. }
  507. static s_stat* init_fork(const char *param)
  508. {
  509. fork_stat *s = xzalloc(sizeof(*s));
  510. if (*param == 'n') {
  511. s->collect = collect_thread_nr;
  512. } else {
  513. s->collect = collect_fork;
  514. }
  515. return (s_stat*)s;
  516. }
  517. S_STAT(if_stat)
  518. ullong old[4];
  519. const char *device;
  520. char *device_colon;
  521. S_STAT_END(if_stat)
  522. static void FAST_FUNC collect_if(if_stat *s)
  523. {
  524. ullong data[4];
  525. int i;
  526. if (rdval(get_file(&proc_net_dev), s->device_colon, data, 0
  527. | (1 << 1)
  528. | (1 << 3)
  529. | (1 << 9)
  530. | (1 << 11))
  531. ) {
  532. put_question_marks(10);
  533. return;
  534. }
  535. for (i = 0; i < 4; i++) {
  536. ullong old = s->old[i];
  537. if (data[i] < old) old = data[i]; //sanitize
  538. s->old[i] = data[i];
  539. data[i] -= old;
  540. }
  541. put_c(data[1] ? '*' : ' ');
  542. scale(data[0]);
  543. put_c(data[3] ? '*' : ' ');
  544. scale(data[2]);
  545. }
  546. static s_stat* init_if(const char *device)
  547. {
  548. if_stat *s = xzalloc(sizeof(*s));
  549. if (!device || !device[0])
  550. bb_show_usage();
  551. s->collect = collect_if;
  552. s->device = device;
  553. s->device_colon = xasprintf("%s:", device);
  554. return (s_stat*)s;
  555. }
  556. S_STAT(mem_stat)
  557. char opt;
  558. S_STAT_END(mem_stat)
  559. // "Memory" value should not include any caches.
  560. // IOW: neither "ls -laR /" nor heavy read/write activity
  561. // should affect it. We'd like to also include any
  562. // long-term allocated kernel-side mem, but it is hard
  563. // to figure out. For now, bufs, cached & slab are
  564. // counted as "free" memory
  565. //2.6.16:
  566. //MemTotal: 773280 kB
  567. //MemFree: 25912 kB - genuinely free
  568. //Buffers: 320672 kB - cache
  569. //Cached: 146396 kB - cache
  570. //SwapCached: 0 kB
  571. //Active: 183064 kB
  572. //Inactive: 356892 kB
  573. //HighTotal: 0 kB
  574. //HighFree: 0 kB
  575. //LowTotal: 773280 kB
  576. //LowFree: 25912 kB
  577. //SwapTotal: 131064 kB
  578. //SwapFree: 131064 kB
  579. //Dirty: 48 kB
  580. //Writeback: 0 kB
  581. //Mapped: 96620 kB
  582. //Slab: 200668 kB - takes 7 Mb on my box fresh after boot,
  583. // but includes dentries and inodes
  584. // (== can take arbitrary amount of mem)
  585. //CommitLimit: 517704 kB
  586. //Committed_AS: 236776 kB
  587. //PageTables: 1248 kB
  588. //VmallocTotal: 516052 kB
  589. //VmallocUsed: 3852 kB
  590. //VmallocChunk: 512096 kB
  591. //HugePages_Total: 0
  592. //HugePages_Free: 0
  593. //Hugepagesize: 4096 kB
  594. static void FAST_FUNC collect_mem(mem_stat *s)
  595. {
  596. ullong m_total;
  597. ullong m_free;
  598. ullong m_bufs;
  599. ullong m_cached;
  600. ullong m_slab;
  601. const char *meminfo = get_file(&proc_meminfo);
  602. if (s->opt == 'd' /* dirty page cache */
  603. || s->opt == 'w' /* under writeback */
  604. ) {
  605. m_total = 0; /* temporary reuse m_total */
  606. if (rdval(meminfo,
  607. (s->opt == 'd' ? "Dirty:" : "Writeback:"),
  608. &m_total, 1 << 1)
  609. ) {
  610. put_question_marks(4);
  611. return;
  612. }
  613. scale(m_total << 10);
  614. return;
  615. }
  616. m_total = 0;
  617. if (rdval(meminfo, "MemTotal:", &m_total, 1 << 1)) {
  618. put_question_marks(4);
  619. return;
  620. }
  621. if (s->opt == 't') {
  622. scale(m_total << 10);
  623. return;
  624. }
  625. m_free = 0;
  626. m_bufs = 0;
  627. m_cached = 0;
  628. m_slab = 0;
  629. if (rdval(meminfo, "MemFree:", &m_free , 1 << 1)
  630. || rdval(meminfo, "Buffers:", &m_bufs , 1 << 1)
  631. || rdval(meminfo, "Cached:", &m_cached, 1 << 1)
  632. || rdval(meminfo, "Slab:", &m_slab , 1 << 1)
  633. ) {
  634. put_question_marks(4);
  635. return;
  636. }
  637. m_free += m_bufs + m_cached + m_slab;
  638. switch (s->opt) {
  639. case 'f':
  640. scale(m_free << 10); break;
  641. default:
  642. scale((m_total - m_free) << 10); break;
  643. }
  644. }
  645. static s_stat* init_mem(const char *param)
  646. {
  647. mem_stat *s = xzalloc(sizeof(*s));
  648. s->collect = collect_mem;
  649. s->opt = param[0];
  650. return (s_stat*)s;
  651. }
  652. S_STAT(swp_stat)
  653. S_STAT_END(swp_stat)
  654. static void FAST_FUNC collect_swp(swp_stat *s UNUSED_PARAM)
  655. {
  656. ullong s_total[1];
  657. ullong s_free[1];
  658. if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1 << 1)
  659. || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1 << 1)
  660. ) {
  661. put_question_marks(4);
  662. return;
  663. }
  664. scale((s_total[0]-s_free[0]) << 10);
  665. }
  666. static s_stat* init_swp(const char *param UNUSED_PARAM)
  667. {
  668. swp_stat *s = xzalloc(sizeof(*s));
  669. s->collect = collect_swp;
  670. return (s_stat*)s;
  671. }
  672. S_STAT(fd_stat)
  673. S_STAT_END(fd_stat)
  674. static void FAST_FUNC collect_fd(fd_stat *s UNUSED_PARAM)
  675. {
  676. ullong data[2];
  677. if (rdval(get_file(&proc_sys_fs_filenr), "", data, 0
  678. | (1 << 1)
  679. | (1 << 2))
  680. ) {
  681. put_question_marks(4);
  682. return;
  683. }
  684. scale(data[0] - data[1]);
  685. }
  686. static s_stat* init_fd(const char *param UNUSED_PARAM)
  687. {
  688. fd_stat *s = xzalloc(sizeof(*s));
  689. s->collect = collect_fd;
  690. return (s_stat*)s;
  691. }
  692. S_STAT(time_stat)
  693. unsigned prec;
  694. unsigned scale;
  695. S_STAT_END(time_stat)
  696. static void FAST_FUNC collect_tv(time_stat *s, struct timeval *tv, int local)
  697. {
  698. char buf[sizeof("12:34:56.123456")];
  699. struct tm* tm;
  700. unsigned us = tv->tv_usec + s->scale/2;
  701. time_t t = tv->tv_sec;
  702. if (us >= 1000000) {
  703. t++;
  704. us -= 1000000;
  705. }
  706. if (local)
  707. tm = localtime(&t);
  708. else
  709. tm = gmtime(&t);
  710. sprintf(buf, "%02u:%02u:%02u", tm->tm_hour, tm->tm_min, tm->tm_sec);
  711. if (s->prec)
  712. sprintf(buf+8, ".%0*u", s->prec, us / s->scale);
  713. put(buf);
  714. }
  715. static void FAST_FUNC collect_time(time_stat *s)
  716. {
  717. collect_tv(s, &G.tv, /*local:*/ 1);
  718. }
  719. static void FAST_FUNC collect_monotonic(time_stat *s)
  720. {
  721. struct timeval tv_mono;
  722. tv_mono.tv_sec = G.tv.tv_sec - G.start.tv_sec;
  723. #if 0 /* Do we want this? */
  724. if (tv_mono.tv_sec < 0) {
  725. /* Time went backwards, reset start time to "now" */
  726. tv_mono.tv_sec = 0;
  727. G.start = G.tv;
  728. }
  729. #endif
  730. tv_mono.tv_usec = G.tv.tv_usec - G.start.tv_usec;
  731. if ((int32_t)tv_mono.tv_usec < 0) {
  732. tv_mono.tv_usec += 1000000;
  733. tv_mono.tv_sec--;
  734. }
  735. collect_tv(s, &tv_mono, /*local:*/ 0);
  736. }
  737. static s_stat* init_time(const char *param)
  738. {
  739. int prec;
  740. time_stat *s = xzalloc(sizeof(*s));
  741. s->collect = collect_time;
  742. prec = param[0] - '0';
  743. if (prec < 0) prec = 0;
  744. else if (prec > 6) prec = 6;
  745. s->prec = prec;
  746. s->scale = 1;
  747. while (prec++ < 6)
  748. s->scale *= 10;
  749. return (s_stat*)s;
  750. }
  751. static s_stat* init_monotonic(const char *param)
  752. {
  753. time_stat *s = (void*)init_time(param);
  754. s->collect = collect_monotonic;
  755. return (s_stat*)s;
  756. }
  757. static void FAST_FUNC collect_info(s_stat *s)
  758. {
  759. gen ^= 1;
  760. while (s) {
  761. put(s->label);
  762. s->collect(s);
  763. s = s->next;
  764. }
  765. }
  766. typedef s_stat* init_func(const char *param);
  767. static const char options[] ALIGN1 = "ncmsfixptTbr";
  768. static init_func *const init_functions[] ALIGN_PTR = {
  769. init_if,
  770. init_cpu,
  771. init_mem,
  772. init_swp,
  773. init_fd,
  774. init_int,
  775. init_ctx,
  776. init_fork,
  777. init_time,
  778. init_monotonic,
  779. init_blk,
  780. init_cr
  781. };
  782. int nmeter_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  783. int nmeter_main(int argc UNUSED_PARAM, char **argv)
  784. {
  785. char buf[32];
  786. s_stat *first = NULL;
  787. s_stat *last = NULL;
  788. s_stat *s;
  789. char *opt_d;
  790. char *cur, *prev;
  791. INIT_G();
  792. xchdir("/proc");
  793. if (open_read_close("version", buf, sizeof(buf)-1) > 0) {
  794. buf[sizeof(buf)-1] = '\0';
  795. is26 = (strstr(buf, " 2.4.") == NULL);
  796. }
  797. if (getopt32(argv, "d:", &opt_d)) {
  798. G.delta = xatoi(opt_d) * 1000;
  799. G.deltanz = G.delta > 0 ? G.delta : 1;
  800. need_seconds = (1000000 % G.deltanz) != 0;
  801. }
  802. argv += optind;
  803. if (!argv[0])
  804. bb_show_usage();
  805. // Can use argv[0] directly, but this will mess up
  806. // parameters as seen by e.g. ps. Making a copy...
  807. cur = xstrdup(argv[0]);
  808. while (1) {
  809. char *param, *p;
  810. prev = cur;
  811. again:
  812. cur = strchr(cur, '%');
  813. if (!cur)
  814. break;
  815. if (cur[1] == '%') { // %%
  816. overlapping_strcpy(cur, cur + 1);
  817. cur++;
  818. goto again;
  819. }
  820. *cur++ = '\0'; // overwrite %
  821. if (cur[0] == '[') {
  822. // format: %[foptstring]
  823. cur++;
  824. p = strchr(options, cur[0]);
  825. param = cur+1;
  826. while (cur[0] != ']') {
  827. if (!cur[0])
  828. bb_show_usage();
  829. cur++;
  830. }
  831. *cur++ = '\0'; // overwrite [
  832. } else {
  833. // format: %NNNNNNf
  834. param = cur;
  835. while (cur[0] >= '0' && cur[0] <= '9')
  836. cur++;
  837. if (!cur[0])
  838. bb_show_usage();
  839. p = strchr(options, cur[0]);
  840. *cur++ = '\0'; // overwrite format char
  841. }
  842. if (!p)
  843. bb_show_usage();
  844. s = init_functions[p-options](param);
  845. if (s) {
  846. s->label = prev;
  847. /*s->next = NULL; - all initXXX funcs use xzalloc */
  848. if (!first)
  849. first = s;
  850. else
  851. last->next = s;
  852. last = s;
  853. } else {
  854. // %r option. remove it from string
  855. overlapping_strcpy(prev + strlen(prev), cur);
  856. cur = prev;
  857. }
  858. }
  859. if (prev[0]) {
  860. s = init_literal();
  861. s->label = prev;
  862. /*s->next = NULL; - all initXXX funcs use xzalloc */
  863. if (!first)
  864. first = s;
  865. else
  866. last->next = s;
  867. last = s;
  868. }
  869. // Generate first samples but do not print them, they're bogus
  870. collect_info(first);
  871. reset_outbuf();
  872. if (G.delta >= 0) {
  873. xgettimeofday(&G.tv);
  874. usleep(G.delta > 1000000 ? 1000000 : G.delta - G.tv.tv_usec % G.deltanz);
  875. }
  876. xgettimeofday(&G.start);
  877. G.tv = G.start;
  878. // Move back start of monotonic time a bit, to syncronize fractionals of %T and %t:
  879. // nmeter -d500 '%6T %6t'
  880. // 00:00:00.000161 12:32:07.500161
  881. // 00:00:00.500282 12:32:08.000282
  882. // 00:00:01.000286 12:32:08.500286
  883. if (G.delta > 0)
  884. G.start.tv_usec -= (G.start.tv_usec % (unsigned)G.delta);
  885. while (1) {
  886. collect_info(first);
  887. put_c(G.final_char);
  888. print_outbuf();
  889. // Negative delta -> no usleep at all
  890. // This will hog the CPU but you can have REALLY GOOD
  891. // time resolution ;)
  892. // TODO: detect and avoid useless updates
  893. // (like: nothing happens except time)
  894. if (G.delta >= 0) {
  895. int rem;
  896. // can be commented out, will sacrifice sleep time precision a bit
  897. xgettimeofday(&G.tv);
  898. // TODO: nmeter -d10000 '%6T %6t'
  899. // 00:00:00.770333 12:34:44.770333
  900. // 00:00:06.000088 12:34:50.000088
  901. // 00:00:16.000094 12:35:00.000094
  902. // 00:00:26.000275 12:35:10.000275
  903. // we can't syncronize interval to start close to 10 seconds for both
  904. // %T and %t (as shown above), but what if there is only %T
  905. // in format string? Maybe sync _it_ instead of %t in this case?
  906. if (need_seconds)
  907. rem = G.delta - ((ullong)G.tv.tv_sec*1000000 + G.tv.tv_usec) % G.deltanz;
  908. else
  909. rem = G.delta - (unsigned)G.tv.tv_usec % G.deltanz;
  910. // Sometimes kernel wakes us up just a tiny bit earlier than asked
  911. // Do not go to very short sleep in this case
  912. if (rem < (unsigned)G.delta / 128) {
  913. rem += G.delta;
  914. }
  915. usleep(rem);
  916. }
  917. xgettimeofday(&G.tv);
  918. }
  919. /*return 0;*/
  920. }