iostat.c 12 KB

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