iostat.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Report CPU and I/O stats, based on sysstat version 9.1.2 by Sebastien Godard
  4. *
  5. * Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. //config:config IOSTAT
  10. //config: bool "iostat (7.6 kb)"
  11. //config: default y
  12. //config: help
  13. //config: Report CPU and I/O statistics
  14. //applet:IF_IOSTAT(APPLET(iostat, BB_DIR_BIN, BB_SUID_DROP))
  15. //kbuild:lib-$(CONFIG_IOSTAT) += iostat.o
  16. #include "libbb.h"
  17. #include <sys/utsname.h> /* struct utsname */
  18. //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
  19. #define debug(fmt, ...) ((void)0)
  20. #define MAX_DEVICE_NAME 12
  21. #define MAX_DEVICE_NAME_STR "12"
  22. #if 1
  23. typedef unsigned long long cputime_t;
  24. typedef long long icputime_t;
  25. # define FMT_DATA "ll"
  26. # define CPUTIME_MAX (~0ULL)
  27. #else
  28. typedef unsigned long cputime_t;
  29. typedef long icputime_t;
  30. # define FMT_DATA "l"
  31. # define CPUTIME_MAX (~0UL)
  32. #endif
  33. enum {
  34. STATS_CPU_USER,
  35. STATS_CPU_NICE,
  36. STATS_CPU_SYSTEM,
  37. STATS_CPU_IDLE,
  38. STATS_CPU_IOWAIT,
  39. STATS_CPU_IRQ,
  40. STATS_CPU_SOFTIRQ,
  41. STATS_CPU_STEAL,
  42. STATS_CPU_GUEST,
  43. GLOBAL_UPTIME,
  44. SMP_UPTIME,
  45. N_STATS_CPU,
  46. };
  47. typedef struct {
  48. cputime_t vector[N_STATS_CPU];
  49. } stats_cpu_t;
  50. typedef struct {
  51. stats_cpu_t *prev;
  52. stats_cpu_t *curr;
  53. cputime_t itv;
  54. } stats_cpu_pair_t;
  55. typedef struct {
  56. unsigned long long rd_sectors;
  57. unsigned long long wr_sectors;
  58. unsigned long rd_ops;
  59. unsigned long wr_ops;
  60. } stats_dev_data_t;
  61. typedef struct stats_dev {
  62. struct stats_dev *next;
  63. char dname[MAX_DEVICE_NAME + 1];
  64. stats_dev_data_t prev_data;
  65. stats_dev_data_t curr_data;
  66. } stats_dev_t;
  67. /* Globals. Sort by size and access frequency. */
  68. struct globals {
  69. smallint show_all;
  70. unsigned total_cpus; /* Number of CPUs */
  71. unsigned clk_tck; /* Number of clock ticks per second */
  72. llist_t *dev_name_list; /* List of devices entered on the command line */
  73. stats_dev_t *stats_dev_list;
  74. struct tm tmtime;
  75. struct {
  76. const char *str;
  77. unsigned div;
  78. } unit;
  79. };
  80. #define G (*ptr_to_globals)
  81. #define INIT_G() do { \
  82. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  83. G.unit.str = "Blk"; \
  84. G.unit.div = 1; \
  85. } while (0)
  86. /* Must match option string! */
  87. enum {
  88. OPT_c = 1 << 0,
  89. OPT_d = 1 << 1,
  90. OPT_t = 1 << 2,
  91. OPT_z = 1 << 3,
  92. OPT_k = 1 << 4,
  93. OPT_m = 1 << 5,
  94. };
  95. static ALWAYS_INLINE int this_is_smp(void)
  96. {
  97. return (G.total_cpus > 1);
  98. }
  99. static void print_header(void)
  100. {
  101. char buf[32];
  102. struct utsname uts;
  103. uname(&uts); /* never fails */
  104. /* Date representation for the current locale */
  105. strftime(buf, sizeof(buf), "%x", &G.tmtime);
  106. printf("%s %s (%s) \t%s \t_%s_\t(%u CPU)\n\n",
  107. uts.sysname, uts.release, uts.nodename,
  108. buf, uts.machine, G.total_cpus);
  109. }
  110. static void get_localtime(struct tm *ptm)
  111. {
  112. time_t timer;
  113. time(&timer);
  114. localtime_r(&timer, ptm);
  115. }
  116. static void print_timestamp(void)
  117. {
  118. char buf[64];
  119. /* %x: date representation for the current locale */
  120. /* %X: time representation for the current locale */
  121. strftime(buf, sizeof(buf), "%x %X", &G.tmtime);
  122. puts(buf);
  123. }
  124. static cputime_t get_smp_uptime(void)
  125. {
  126. FILE *fp;
  127. unsigned long sec, dec;
  128. fp = xfopen_for_read("/proc/uptime");
  129. if (fscanf(fp, "%lu.%lu", &sec, &dec) != 2)
  130. bb_error_msg_and_die("can't read '%s'", "/proc/uptime");
  131. fclose(fp);
  132. return (cputime_t)sec * G.clk_tck + dec * G.clk_tck / 100;
  133. }
  134. /* Fetch CPU statistics from /proc/stat */
  135. static void get_cpu_statistics(stats_cpu_t *sc)
  136. {
  137. FILE *fp;
  138. char buf[1024];
  139. fp = xfopen_for_read("/proc/stat");
  140. memset(sc, 0, sizeof(*sc));
  141. while (fgets(buf, sizeof(buf), fp)) {
  142. int i;
  143. char *ibuf;
  144. /* Does the line start with "cpu "? */
  145. if (!starts_with_cpu(buf) || buf[3] != ' ') {
  146. continue;
  147. }
  148. ibuf = buf + 4;
  149. for (i = STATS_CPU_USER; i <= STATS_CPU_GUEST; i++) {
  150. ibuf = skip_whitespace(ibuf);
  151. sscanf(ibuf, "%"FMT_DATA"u", &sc->vector[i]);
  152. if (i != STATS_CPU_GUEST) {
  153. sc->vector[GLOBAL_UPTIME] += sc->vector[i];
  154. }
  155. ibuf = skip_non_whitespace(ibuf);
  156. }
  157. break;
  158. }
  159. if (this_is_smp()) {
  160. sc->vector[SMP_UPTIME] = get_smp_uptime();
  161. }
  162. fclose(fp);
  163. }
  164. static ALWAYS_INLINE cputime_t get_interval(cputime_t old, cputime_t new)
  165. {
  166. cputime_t itv = new - old;
  167. return (itv == 0) ? 1 : itv;
  168. }
  169. #if CPUTIME_MAX > 0xffffffff
  170. /*
  171. * Handle overflow conditions properly for counters which can have
  172. * less bits than cputime_t, depending on the kernel version.
  173. */
  174. /* Surprisingly, on 32bit inlining is a size win */
  175. static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
  176. {
  177. cputime_t v = curr - prev;
  178. if ((icputime_t)v < 0 /* curr < prev - counter overflow? */
  179. && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
  180. ) {
  181. /* Add 33th bit set to 1 to curr, compensating for the overflow */
  182. /* double shift defeats "warning: left shift count >= width of type" */
  183. v += ((cputime_t)1 << 16) << 16;
  184. }
  185. return v;
  186. }
  187. #else
  188. static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
  189. {
  190. return curr - prev;
  191. }
  192. #endif
  193. static double percent_value(cputime_t prev, cputime_t curr, cputime_t itv)
  194. {
  195. return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
  196. }
  197. static void print_stats_cpu_struct(stats_cpu_pair_t *stats)
  198. {
  199. cputime_t *p = stats->prev->vector;
  200. cputime_t *c = stats->curr->vector;
  201. printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  202. percent_value(p[STATS_CPU_USER] , c[STATS_CPU_USER] , stats->itv),
  203. percent_value(p[STATS_CPU_NICE] , c[STATS_CPU_NICE] , stats->itv),
  204. percent_value(p[STATS_CPU_SYSTEM] + p[STATS_CPU_SOFTIRQ] + p[STATS_CPU_IRQ],
  205. c[STATS_CPU_SYSTEM] + c[STATS_CPU_SOFTIRQ] + c[STATS_CPU_IRQ], stats->itv),
  206. percent_value(p[STATS_CPU_IOWAIT], c[STATS_CPU_IOWAIT], stats->itv),
  207. percent_value(p[STATS_CPU_STEAL] , c[STATS_CPU_STEAL] , stats->itv),
  208. percent_value(p[STATS_CPU_IDLE] , c[STATS_CPU_IDLE] , stats->itv)
  209. );
  210. }
  211. static void cpu_report(stats_cpu_pair_t *stats)
  212. {
  213. /* Always print a header */
  214. puts("avg-cpu: %user %nice %system %iowait %steal %idle");
  215. /* Print current statistics */
  216. print_stats_cpu_struct(stats);
  217. }
  218. static void print_stats_dev_struct(stats_dev_t *stats_dev, cputime_t itv)
  219. {
  220. stats_dev_data_t *p = &stats_dev->prev_data;
  221. stats_dev_data_t *c = &stats_dev->curr_data;
  222. if (option_mask32 & OPT_z)
  223. if (p->rd_ops == c->rd_ops && p->wr_ops == c->wr_ops)
  224. return;
  225. printf("%-13s %8.2f %12.2f %12.2f %10llu %10llu\n",
  226. stats_dev->dname,
  227. percent_value(p->rd_ops + p->wr_ops, c->rd_ops + c->wr_ops, itv),
  228. percent_value(p->rd_sectors, c->rd_sectors, itv) / G.unit.div,
  229. percent_value(p->wr_sectors, c->wr_sectors, itv) / G.unit.div,
  230. (c->rd_sectors - p->rd_sectors) / G.unit.div,
  231. (c->wr_sectors - p->wr_sectors) / G.unit.div
  232. );
  233. }
  234. static void print_devstat_header(void)
  235. {
  236. printf("Device:%15s%6s%s/s%6s%s/s%6s%s%6s%s\n",
  237. "tps",
  238. G.unit.str, "_read", G.unit.str, "_wrtn",
  239. G.unit.str, "_read", G.unit.str, "_wrtn"
  240. );
  241. }
  242. /*
  243. * Is input partition of format [sdaN]?
  244. */
  245. static int is_partition(const char *dev)
  246. {
  247. /* Ok, this is naive... */
  248. return ((dev[0] - 's') | (dev[1] - 'd') | (dev[2] - 'a')) == 0 && isdigit(dev[3]);
  249. }
  250. static stats_dev_t *stats_dev_find_or_new(const char *dev_name)
  251. {
  252. stats_dev_t **curr = &G.stats_dev_list;
  253. while (*curr != NULL) {
  254. if (strcmp((*curr)->dname, dev_name) == 0)
  255. return *curr;
  256. curr = &(*curr)->next;
  257. }
  258. *curr = xzalloc(sizeof(stats_dev_t));
  259. strncpy((*curr)->dname, dev_name, MAX_DEVICE_NAME);
  260. return *curr;
  261. }
  262. static void stats_dev_free(stats_dev_t *stats_dev)
  263. {
  264. if (stats_dev) {
  265. stats_dev_free(stats_dev->next);
  266. free(stats_dev);
  267. }
  268. }
  269. static void do_disk_statistics(cputime_t itv)
  270. {
  271. char buf[128];
  272. char dev_name[MAX_DEVICE_NAME + 1];
  273. unsigned long long rd_sec_or_dummy;
  274. unsigned long long wr_sec_or_dummy;
  275. stats_dev_data_t *curr_data;
  276. stats_dev_t *stats_dev;
  277. FILE *fp;
  278. int rc;
  279. fp = xfopen_for_read("/proc/diskstats");
  280. /* Read and possibly print stats from /proc/diskstats */
  281. while (fgets(buf, sizeof(buf), fp)) {
  282. sscanf(buf, "%*s %*s %"MAX_DEVICE_NAME_STR"s", dev_name);
  283. if (G.dev_name_list) {
  284. /* Is device name in list? */
  285. if (!llist_find_str(G.dev_name_list, dev_name))
  286. continue;
  287. } else if (is_partition(dev_name)) {
  288. continue;
  289. }
  290. stats_dev = stats_dev_find_or_new(dev_name);
  291. curr_data = &stats_dev->curr_data;
  292. rc = sscanf(buf, "%*s %*s %*s %lu %llu %llu %llu %lu %*s %llu",
  293. &curr_data->rd_ops,
  294. &rd_sec_or_dummy,
  295. &curr_data->rd_sectors,
  296. &wr_sec_or_dummy,
  297. &curr_data->wr_ops,
  298. &curr_data->wr_sectors);
  299. if (rc != 6) {
  300. curr_data->rd_sectors = rd_sec_or_dummy;
  301. curr_data->wr_sectors = wr_sec_or_dummy;
  302. //curr_data->rd_ops = ;
  303. curr_data->wr_ops = (unsigned long)curr_data->rd_sectors;
  304. }
  305. if (!G.dev_name_list /* User didn't specify device */
  306. && !G.show_all
  307. && curr_data->rd_ops == 0
  308. && curr_data->wr_ops == 0
  309. ) {
  310. /* Don't print unused device */
  311. continue;
  312. }
  313. /* Print current statistics */
  314. print_stats_dev_struct(stats_dev, itv);
  315. stats_dev->prev_data = *curr_data;
  316. }
  317. fclose(fp);
  318. }
  319. static void dev_report(cputime_t itv)
  320. {
  321. /* Always print a header */
  322. print_devstat_header();
  323. /* Fetch current disk statistics */
  324. do_disk_statistics(itv);
  325. }
  326. //usage:#define iostat_trivial_usage
  327. //usage: "[-c] [-d] [-t] [-z] [-k|-m] [ALL|BLOCKDEV...] [INTERVAL [COUNT]]"
  328. //usage:#define iostat_full_usage "\n\n"
  329. //usage: "Report CPU and I/O statistics\n"
  330. //usage: "\n -c Show CPU utilization"
  331. //usage: "\n -d Show device utilization"
  332. //usage: "\n -t Print current time"
  333. //usage: "\n -z Omit devices with no activity"
  334. //usage: "\n -k Use kb/s"
  335. //usage: "\n -m Use Mb/s"
  336. int iostat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  337. int iostat_main(int argc UNUSED_PARAM, char **argv)
  338. {
  339. int opt;
  340. unsigned interval;
  341. int count;
  342. stats_cpu_t stats_data[2];
  343. smallint current_stats;
  344. INIT_G();
  345. memset(&stats_data, 0, sizeof(stats_data));
  346. /* Get number of clock ticks per sec */
  347. G.clk_tck = bb_clk_tck();
  348. /* Determine number of CPUs */
  349. G.total_cpus = get_cpu_count();
  350. if (G.total_cpus == 0)
  351. G.total_cpus = 1;
  352. /* Parse and process arguments */
  353. /* -k and -m are mutually exclusive */
  354. opt = getopt32(argv, "^" "cdtzkm" "\0" "k--m:m--k");
  355. if (!(opt & (OPT_c + OPT_d)))
  356. /* Default is -cd */
  357. opt |= OPT_c + OPT_d;
  358. argv += optind;
  359. /* Store device names into device list */
  360. while (*argv && !isdigit(*argv[0])) {
  361. if (strcmp(*argv, "ALL") != 0) {
  362. /* If not ALL, save device name */
  363. char *dev_name = skip_dev_pfx(*argv);
  364. if (!llist_find_str(G.dev_name_list, dev_name)) {
  365. llist_add_to(&G.dev_name_list, dev_name);
  366. }
  367. } else {
  368. G.show_all = 1;
  369. }
  370. argv++;
  371. }
  372. interval = 0;
  373. count = 1;
  374. if (*argv) {
  375. /* Get interval */
  376. interval = xatoi_positive(*argv);
  377. count = (interval != 0 ? -1 : 1);
  378. argv++;
  379. if (*argv)
  380. /* Get count value */
  381. count = xatoi_positive(*argv);
  382. }
  383. if (opt & OPT_m) {
  384. G.unit.str = " MB";
  385. G.unit.div = 2048;
  386. }
  387. if (opt & OPT_k) {
  388. G.unit.str = " kB";
  389. G.unit.div = 2;
  390. }
  391. get_localtime(&G.tmtime);
  392. /* Display header */
  393. print_header();
  394. current_stats = 0;
  395. /* Main loop */
  396. for (;;) {
  397. stats_cpu_pair_t stats;
  398. stats.prev = &stats_data[current_stats ^ 1];
  399. stats.curr = &stats_data[current_stats];
  400. /* Fill the time structure */
  401. get_localtime(&G.tmtime);
  402. /* Fetch current CPU statistics */
  403. get_cpu_statistics(stats.curr);
  404. /* Get interval */
  405. stats.itv = get_interval(
  406. stats.prev->vector[GLOBAL_UPTIME],
  407. stats.curr->vector[GLOBAL_UPTIME]
  408. );
  409. if (opt & OPT_t)
  410. print_timestamp();
  411. if (opt & OPT_c) {
  412. cpu_report(&stats);
  413. if (opt & OPT_d)
  414. /* Separate outputs by a newline */
  415. bb_putchar('\n');
  416. }
  417. if (opt & OPT_d) {
  418. if (this_is_smp()) {
  419. stats.itv = get_interval(
  420. stats.prev->vector[SMP_UPTIME],
  421. stats.curr->vector[SMP_UPTIME]
  422. );
  423. }
  424. dev_report(stats.itv);
  425. }
  426. bb_putchar('\n');
  427. if (count > 0) {
  428. if (--count == 0)
  429. break;
  430. }
  431. /* Swap stats */
  432. current_stats ^= 1;
  433. sleep(interval);
  434. }
  435. if (ENABLE_FEATURE_CLEAN_UP) {
  436. llist_free(G.dev_name_list, NULL);
  437. stats_dev_free(G.stats_dev_list);
  438. free(&G);
  439. }
  440. return EXIT_SUCCESS;
  441. }