1 /* vi: set sw=4 ts=4: */
3 * Report CPU and I/O stats, based on sysstat version 9.1.2 by Sebastien Godard
5 * Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
7 * Licensed under GPLv2, see file License in this tarball for details.
10 //applet:IF_IOSTAT(APPLET(iostat, _BB_DIR_BIN, _BB_SUID_DROP))
12 //kbuild:lib-$(CONFIG_IOSTAT) += iostat.o
14 //config:config IOSTAT
15 //config: bool "iostat"
18 //config: Report CPU and I/O statistics
21 #include <sys/utsname.h> /* Need struct utsname */
23 #define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
24 //#define debug(fmt, ...) ((void)0)
26 #define MAX_DEVICE_NAME 12
31 typedef unsigned long long cputime_t;
32 typedef long long icputime_t;
33 # define FMT_DATA "ll"
34 # define CPUTIME_MAX (~0ULL)
36 typedef unsigned long cputime_t;
37 typedef long icputime_t;
39 # define CPUTIME_MAX (~0UL)
50 cputime_t cpu_softirq;
55 char dname[MAX_DEVICE_NAME];
56 unsigned long long rd_sectors;
57 unsigned long long wr_sectors;
62 /* List of devices entered on the command line */
64 char dname[MAX_DEVICE_NAME];
67 /* Globals. Sort by size and access frequency. */
70 unsigned devlist_i; /* Index to the list of devices */
71 unsigned total_cpus; /* Number of CPUs */
72 unsigned clk_tck; /* Number of clock ticks per second */
73 struct device_list *dlist;
74 struct stats_dev *saved_stats_dev;
77 #define G (*ptr_to_globals)
78 #define INIT_G() do { \
79 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
82 /* Must match option string! */
92 static ALWAYS_INLINE unsigned get_user_hz(void)
94 return sysconf(_SC_CLK_TCK);
97 static ALWAYS_INLINE int this_is_smp(void)
99 return (G.total_cpus > 1);
102 static void print_header(void)
108 bb_perror_msg_and_die("uname");
110 strftime(buf, sizeof(buf), "%x", &G.tmtime);
112 printf("%s %s (%s) \t%s \t_%s_\t(%d CPU)\n\n",
113 uts.sysname, uts.release, uts.nodename,
114 buf, uts.machine, G.total_cpus);
117 static int get_number_of_cpus(void)
119 #ifdef _SC_NPROCESSORS_CONF
120 return sysconf(_SC_NPROCESSORS_CONF);
126 fp = xfopen_for_read("/proc/cpuinfo");
128 while (fgets(buf, sizeof(buf), fp))
129 if (strncmp(buf, "processor\t:", 11) == 0)
137 static void get_localtime(struct tm *ptm)
141 localtime_r(&timer, ptm);
144 static void print_timestamp(void)
147 strftime(buf, sizeof(buf), "%x %X", &G.tmtime);
151 /* Does str start with "cpu"? */
152 static int starts_with_cpu(const char *str)
154 return ((str[0] - 'c') | (str[1] - 'p') | (str[2] - 'u')) == 0;
157 /* Fetch CPU statistics from /proc/stat */
158 static void get_cpu_statistics(struct stats_cpu *sc)
163 fp = xfopen_for_read("/proc/stat");
165 memset(sc, 0, sizeof(*sc));
167 while (fgets(buf, sizeof(buf), fp)) {
168 /* Does the line starts with "cpu "? */
169 if (starts_with_cpu(buf) && buf[3] == ' ') {
171 "%"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"
172 FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u",
173 &sc->cpu_user, &sc->cpu_nice, &sc->cpu_system,
174 &sc->cpu_idle, &sc->cpu_iowait, &sc->cpu_irq,
175 &sc->cpu_softirq, &sc->cpu_steal, &sc->cpu_guest);
182 static cputime_t get_smp_uptime(void)
185 char buf[sizeof(long)*3 * 2 + 4];
186 unsigned long sec, dec;
188 fp = xfopen_for_read("/proc/uptime");
190 if (fgets(buf, sizeof(buf), fp))
191 if (sscanf(buf, "%lu.%lu", &sec, &dec) != 2)
192 bb_error_msg_and_die("can't read /proc/uptime");
196 return (cputime_t)sec * G.clk_tck + dec * G.clk_tck / 100;
200 * Obtain current uptime in jiffies.
201 * Uptime is sum of individual CPUs' uptimes.
203 static cputime_t get_uptime(const struct stats_cpu *sc)
205 /* NB: Don't include cpu_guest, it is already in cpu_user */
206 return sc->cpu_user + sc->cpu_nice + sc->cpu_system + sc->cpu_idle +
207 + sc->cpu_iowait + sc->cpu_irq + sc->cpu_steal + sc->cpu_softirq;
210 static ALWAYS_INLINE cputime_t get_interval(cputime_t old, cputime_t new)
212 cputime_t itv = new - old;
214 return (itv == 0) ? 1 : itv;
217 #if CPUTIME_MAX > 0xffffffff
219 * Handle overflow conditions properly for counters which can have
220 * less bits than cputime_t, depending on the kernel version.
222 /* Surprisingly, on 32bit inlining is a size win */
223 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
225 cputime_t v = curr - prev;
227 if ((icputime_t)v < 0 /* curr < prev - counter overflow? */
228 && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
230 /* Add 33th bit set to 1 to curr, compensating for the overflow */
231 /* double shift defeats "warning: left shift count >= width of type" */
232 v += ((cputime_t)1 << 16) << 16;
237 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
243 static double percent_value(cputime_t prev, cputime_t curr, cputime_t itv)
245 return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
248 static void print_stats_cpu_struct(const struct stats_cpu *p,
249 const struct stats_cpu *c, cputime_t itv)
251 printf(" %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n",
252 percent_value(p->cpu_user , c->cpu_user , itv),
253 percent_value(p->cpu_nice , c->cpu_nice , itv),
254 percent_value(p->cpu_system + p->cpu_softirq + p->cpu_irq,
255 c->cpu_system + c->cpu_softirq + c->cpu_irq, itv),
256 percent_value(p->cpu_iowait , c->cpu_iowait , itv),
257 percent_value(p->cpu_steal , c->cpu_steal , itv),
258 percent_value(p->cpu_idle , c->cpu_idle , itv)
262 static void print_stats_dev_struct(const struct stats_dev *p,
263 const struct stats_dev *c, cputime_t itv)
267 if (option_mask32 & OPT_k)
269 else if (option_mask32 & OPT_m)
272 if (option_mask32 & OPT_z)
273 if (p->rd_ops == c->rd_ops && p->wr_ops == c->wr_ops)
276 printf("%-13s", c->dname);
277 printf(" %8.2f %12.2f %12.2f %10llu %10llu \n",
278 percent_value(p->rd_ops + p->wr_ops ,
279 /**/ c->rd_ops + c->wr_ops , itv),
280 percent_value(p->rd_sectors, c->rd_sectors, itv) / unit,
281 percent_value(p->wr_sectors, c->wr_sectors, itv) / unit,
282 (c->rd_sectors - p->rd_sectors) / unit,
283 (c->wr_sectors - p->wr_sectors) / unit);
286 static void cpu_report(const struct stats_cpu *last,
287 const struct stats_cpu *cur,
290 /* Always print a header */
291 puts("avg-cpu: %user %nice %system %iowait %steal %idle");
293 /* Print current statistics */
294 print_stats_cpu_struct(last, cur, itv);
297 static void print_devstat_header(void)
299 printf("Device: tps");
301 if (option_mask32 & OPT_m)
302 puts(" MB_read/s MB_wrtn/s MB_read MB_wrtn");
303 else if (option_mask32 & OPT_k)
304 puts(" kB_read/s kB_wrtn/s kB_read kB_wrtn");
306 puts(" Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn");
310 * Is input partition of format [sdaN]?
312 static int is_partition(const char *dev)
314 /* Ok, this is naive... */
315 return ((dev[0] - 's') | (dev[1] - 'd') | (dev[2] - 'a')) == 0 && isdigit(dev[3]);
319 * Return number of numbers on cmdline.
320 * Reasonable values are only 0 (no interval/count specified),
321 * 1 (interval specified) and 2 (both interval and count specified)
323 static int numbers_on_cmdline(int argc, char *argv[])
327 if (isdigit(argv[argc-1][0]))
329 if (argc > 2 && isdigit(argv[argc-2][0]))
335 static int is_dev_in_dlist(const char *dev)
339 /* Go through the device list */
340 for (i = 0; i < G.devlist_i; i++)
341 if (strcmp(G.dlist[i].dname, dev) == 0)
349 static void do_disk_statistics(cputime_t itv)
355 unsigned major, minor;
356 unsigned long wr_ops, dummy; /* %*lu for suppres the conversion wouldn't work */
357 unsigned long long rd_sec_or_wr_ops;
358 unsigned long long rd_sec_or_dummy, wr_sec_or_dummy, wr_sec;
361 fp = xfopen_for_read("/proc/diskstats");
363 /* Read and possibly print stats from /proc/diskstats */
364 while (fgets(buf, sizeof(buf), fp)) {
365 rc = sscanf(buf, "%u %u %s %lu %llu %llu %llu %lu %lu %llu %lu %lu %lu %lu",
366 &major, &minor, sd.dname, &sd.rd_ops,
367 &rd_sec_or_dummy, &rd_sec_or_wr_ops, &wr_sec_or_dummy,
368 &wr_ops, &dummy, &wr_sec, &dummy, &dummy, &dummy, &dummy);
373 sd.rd_sectors = rd_sec_or_wr_ops;
374 sd.wr_sectors = wr_sec;
377 sd.rd_sectors = rd_sec_or_dummy;
378 sd.wr_ops = (unsigned long)rd_sec_or_wr_ops;
379 sd.wr_sectors = wr_sec_or_dummy;
385 if (!G.devlist_i && !is_partition(sd.dname)) {
386 /* User didn't specify device */
387 if (!G.show_all && !sd.rd_ops && !sd.wr_ops) {
388 /* Don't print unused device */
391 print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
392 G.saved_stats_dev[i] = sd;
395 /* Is device in device list? */
396 if (is_dev_in_dlist(sd.dname)) {
397 /* Print current statistics */
398 print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
399 G.saved_stats_dev[i] = sd;
407 static void dev_report(cputime_t itv)
409 /* Always print a header */
410 print_devstat_header();
412 /* Fetch current disk statistics */
413 do_disk_statistics(itv);
416 static void save_to_devlist(const char *dname)
419 struct device_list *tmp = G.dlist;
421 if (strncmp(dname, "/dev/", 5) == 0)
422 /* We'll ignore prefix '/dev/' */
425 /* Go through the list */
426 for (i = 0; i < G.devlist_i; i++, tmp++)
427 if (strcmp(tmp->dname, dname) == 0)
428 /* Already in the list */
431 /* Add device name to the list */
432 strncpy(tmp->dname, dname, MAX_DEVICE_NAME - 1);
434 /* Update device list index */
438 static unsigned get_number_of_devices(void)
444 unsigned long rd_ops, wr_ops;
445 char dname[MAX_DEVICE_NAME];
447 fp = xfopen_for_read("/proc/diskstats");
449 while (fgets(buf, sizeof(buf), fp)) {
450 rv = sscanf(buf, "%*d %*d %s %lu %*u %*u %*u %lu",
451 dname, &rd_ops, &wr_ops);
452 if (rv == 2 || is_partition(dname))
455 if (!rd_ops && !wr_ops) {
467 static int number_of_ALL_on_cmdline(char **argv)
471 /* Iterate over cmd line arguments, count "ALL" */
473 if (strcmp(*argv++, "ALL") == 0)
479 //usage:#define iostat_trivial_usage
480 //usage: "[-c] [-d] [-t] [-z] [-k|-m] [ALL|BLOCKDEV...] [INTERVAL [COUNT]]"
481 //usage:#define iostat_full_usage "\n\n"
482 //usage: "Report CPU and I/O statistics\n"
483 //usage: "\nOptions:"
484 //usage: "\n -c Show CPU utilization"
485 //usage: "\n -d Show device utilization"
486 //usage: "\n -t Print current time"
487 //usage: "\n -z Omit devices with no activity"
488 //usage: "\n -k Use kb/s"
489 //usage: "\n -m Use Mb/s"
491 int iostat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
492 int iostat_main(int argc, char **argv)
495 unsigned interval = 0;
497 cputime_t global_uptime[2] = { 0 };
498 cputime_t smp_uptime[2] = { 0 };
500 struct stats_cpu stats_cur, stats_last;
504 memset(&stats_last, 0, sizeof(stats_last));
506 /* Get number of clock ticks per sec */
507 G.clk_tck = get_user_hz();
509 /* Determine number of CPUs */
510 G.total_cpus = get_number_of_cpus();
512 /* Parse and process arguments */
513 /* -k and -m are mutually exclusive */
514 opt_complementary = "k--m:m--k";
515 opt = getopt32(argv, "cdtzkm");
516 if (!(opt & (OPT_c + OPT_d)))
518 opt |= OPT_c + OPT_d;
523 dev_num = argc - numbers_on_cmdline(argc, argv);
524 /* We don't want to allocate space for 'ALL' */
525 dev_num -= number_of_ALL_on_cmdline(argv);
527 /* Make space for device list */
528 G.dlist = xzalloc(sizeof(G.dlist[0]) * dev_num);
530 /* Store device names into device list */
531 while (*argv && !isdigit(*argv[0])) {
532 if (strcmp(*argv, "ALL") != 0)
533 /* If not ALL, save device name */
534 save_to_devlist(*argv);
542 interval = xatoi_u(*argv);
543 count = interval ? -1 : 1;
546 /* Get count value */
547 count = xatoi_u(*argv);
550 /* Allocate space for device stats */
552 G.saved_stats_dev = xzalloc(sizeof(G.saved_stats_dev[0]) *
553 (dev_num ? dev_num : get_number_of_devices())
562 /* Fill the time structure */
563 get_localtime(&G.tmtime);
565 /* Fetch current CPU statistics */
566 get_cpu_statistics(&stats_cur);
568 /* Fetch current uptime */
569 global_uptime[CURRENT] = get_uptime(&stats_cur);
572 itv = get_interval(global_uptime[LAST], global_uptime[CURRENT]);
578 cpu_report(&stats_last, &stats_cur, itv);
580 /* Separate outputs by a newline */
586 smp_uptime[CURRENT] = get_smp_uptime();
587 itv = get_interval(smp_uptime[LAST], smp_uptime[CURRENT]);
588 smp_uptime[LAST] = smp_uptime[CURRENT];
598 /* Backup current stats */
599 global_uptime[LAST] = global_uptime[CURRENT];
600 stats_last = stats_cur;
608 if (ENABLE_FEATURE_CLEAN_UP) {
611 free(G.saved_stats_dev);