nmeter.c 21 KB

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