nmeter.c 22 KB

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