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 source tree.
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 void get_localtime(struct tm *ptm)
121 localtime_r(&timer, ptm);
124 static void print_timestamp(void)
127 strftime(buf, sizeof(buf), "%x %X", &G.tmtime);
131 /* Fetch CPU statistics from /proc/stat */
132 static void get_cpu_statistics(struct stats_cpu *sc)
137 fp = xfopen_for_read("/proc/stat");
139 memset(sc, 0, sizeof(*sc));
141 while (fgets(buf, sizeof(buf), fp)) {
142 /* Does the line starts with "cpu "? */
143 if (starts_with_cpu(buf) && buf[3] == ' ') {
145 "%"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"
146 FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u",
147 &sc->cpu_user, &sc->cpu_nice, &sc->cpu_system,
148 &sc->cpu_idle, &sc->cpu_iowait, &sc->cpu_irq,
149 &sc->cpu_softirq, &sc->cpu_steal, &sc->cpu_guest);
156 static cputime_t get_smp_uptime(void)
159 char buf[sizeof(long)*3 * 2 + 4];
160 unsigned long sec, dec;
162 fp = xfopen_for_read("/proc/uptime");
164 if (fgets(buf, sizeof(buf), fp))
165 if (sscanf(buf, "%lu.%lu", &sec, &dec) != 2)
166 bb_error_msg_and_die("can't read /proc/uptime");
170 return (cputime_t)sec * G.clk_tck + dec * G.clk_tck / 100;
174 * Obtain current uptime in jiffies.
175 * Uptime is sum of individual CPUs' uptimes.
177 static cputime_t get_uptime(const struct stats_cpu *sc)
179 /* NB: Don't include cpu_guest, it is already in cpu_user */
180 return sc->cpu_user + sc->cpu_nice + sc->cpu_system + sc->cpu_idle +
181 + sc->cpu_iowait + sc->cpu_irq + sc->cpu_steal + sc->cpu_softirq;
184 static ALWAYS_INLINE cputime_t get_interval(cputime_t old, cputime_t new)
186 cputime_t itv = new - old;
188 return (itv == 0) ? 1 : itv;
191 #if CPUTIME_MAX > 0xffffffff
193 * Handle overflow conditions properly for counters which can have
194 * less bits than cputime_t, depending on the kernel version.
196 /* Surprisingly, on 32bit inlining is a size win */
197 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
199 cputime_t v = curr - prev;
201 if ((icputime_t)v < 0 /* curr < prev - counter overflow? */
202 && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
204 /* Add 33th bit set to 1 to curr, compensating for the overflow */
205 /* double shift defeats "warning: left shift count >= width of type" */
206 v += ((cputime_t)1 << 16) << 16;
211 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
217 static double percent_value(cputime_t prev, cputime_t curr, cputime_t itv)
219 return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
222 static void print_stats_cpu_struct(const struct stats_cpu *p,
223 const struct stats_cpu *c, cputime_t itv)
225 printf(" %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n",
226 percent_value(p->cpu_user , c->cpu_user , itv),
227 percent_value(p->cpu_nice , c->cpu_nice , itv),
228 percent_value(p->cpu_system + p->cpu_softirq + p->cpu_irq,
229 c->cpu_system + c->cpu_softirq + c->cpu_irq, itv),
230 percent_value(p->cpu_iowait , c->cpu_iowait , itv),
231 percent_value(p->cpu_steal , c->cpu_steal , itv),
232 percent_value(p->cpu_idle , c->cpu_idle , itv)
236 static void print_stats_dev_struct(const struct stats_dev *p,
237 const struct stats_dev *c, cputime_t itv)
241 if (option_mask32 & OPT_k)
243 else if (option_mask32 & OPT_m)
246 if (option_mask32 & OPT_z)
247 if (p->rd_ops == c->rd_ops && p->wr_ops == c->wr_ops)
250 printf("%-13s", c->dname);
251 printf(" %8.2f %12.2f %12.2f %10llu %10llu \n",
252 percent_value(p->rd_ops + p->wr_ops ,
253 /**/ c->rd_ops + c->wr_ops , itv),
254 percent_value(p->rd_sectors, c->rd_sectors, itv) / unit,
255 percent_value(p->wr_sectors, c->wr_sectors, itv) / unit,
256 (c->rd_sectors - p->rd_sectors) / unit,
257 (c->wr_sectors - p->wr_sectors) / unit);
260 static void cpu_report(const struct stats_cpu *last,
261 const struct stats_cpu *cur,
264 /* Always print a header */
265 puts("avg-cpu: %user %nice %system %iowait %steal %idle");
267 /* Print current statistics */
268 print_stats_cpu_struct(last, cur, itv);
271 static void print_devstat_header(void)
273 printf("Device: tps");
275 if (option_mask32 & OPT_m)
276 puts(" MB_read/s MB_wrtn/s MB_read MB_wrtn");
277 else if (option_mask32 & OPT_k)
278 puts(" kB_read/s kB_wrtn/s kB_read kB_wrtn");
280 puts(" Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn");
284 * Is input partition of format [sdaN]?
286 static int is_partition(const char *dev)
288 /* Ok, this is naive... */
289 return ((dev[0] - 's') | (dev[1] - 'd') | (dev[2] - 'a')) == 0 && isdigit(dev[3]);
293 * Return number of numbers on cmdline.
294 * Reasonable values are only 0 (no interval/count specified),
295 * 1 (interval specified) and 2 (both interval and count specified)
297 static int numbers_on_cmdline(int argc, char *argv[])
301 if (isdigit(argv[argc-1][0]))
303 if (argc > 2 && isdigit(argv[argc-2][0]))
309 static int is_dev_in_dlist(const char *dev)
313 /* Go through the device list */
314 for (i = 0; i < G.devlist_i; i++)
315 if (strcmp(G.dlist[i].dname, dev) == 0)
323 static void do_disk_statistics(cputime_t itv)
329 unsigned major, minor;
330 unsigned long wr_ops, dummy; /* %*lu for suppress the conversion wouldn't work */
331 unsigned long long rd_sec_or_wr_ops;
332 unsigned long long rd_sec_or_dummy, wr_sec_or_dummy, wr_sec;
335 fp = xfopen_for_read("/proc/diskstats");
337 /* Read and possibly print stats from /proc/diskstats */
338 while (fgets(buf, sizeof(buf), fp)) {
339 rc = sscanf(buf, "%u %u %s %lu %llu %llu %llu %lu %lu %llu %lu %lu %lu %lu",
340 &major, &minor, sd.dname, &sd.rd_ops,
341 &rd_sec_or_dummy, &rd_sec_or_wr_ops, &wr_sec_or_dummy,
342 &wr_ops, &dummy, &wr_sec, &dummy, &dummy, &dummy, &dummy);
347 sd.rd_sectors = rd_sec_or_wr_ops;
348 sd.wr_sectors = wr_sec;
351 sd.rd_sectors = rd_sec_or_dummy;
352 sd.wr_ops = (unsigned long)rd_sec_or_wr_ops;
353 sd.wr_sectors = wr_sec_or_dummy;
359 if (!G.devlist_i && !is_partition(sd.dname)) {
360 /* User didn't specify device */
361 if (!G.show_all && !sd.rd_ops && !sd.wr_ops) {
362 /* Don't print unused device */
365 print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
366 G.saved_stats_dev[i] = sd;
369 /* Is device in device list? */
370 if (is_dev_in_dlist(sd.dname)) {
371 /* Print current statistics */
372 print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
373 G.saved_stats_dev[i] = sd;
383 static void dev_report(cputime_t itv)
385 /* Always print a header */
386 print_devstat_header();
388 /* Fetch current disk statistics */
389 do_disk_statistics(itv);
392 static void save_to_devlist(const char *dname)
395 struct device_list *tmp = G.dlist;
397 if (strncmp(dname, "/dev/", 5) == 0)
398 /* We'll ignore prefix '/dev/' */
401 /* Go through the list */
402 for (i = 0; i < G.devlist_i; i++, tmp++)
403 if (strcmp(tmp->dname, dname) == 0)
404 /* Already in the list */
407 /* Add device name to the list */
408 strncpy(tmp->dname, dname, MAX_DEVICE_NAME - 1);
410 /* Update device list index */
414 static unsigned get_number_of_devices(void)
420 unsigned long rd_ops, wr_ops;
421 char dname[MAX_DEVICE_NAME];
423 fp = xfopen_for_read("/proc/diskstats");
425 while (fgets(buf, sizeof(buf), fp)) {
426 rv = sscanf(buf, "%*d %*d %s %lu %*u %*u %*u %lu",
427 dname, &rd_ops, &wr_ops);
428 if (rv == 2 || is_partition(dname))
431 if (!rd_ops && !wr_ops) {
443 static int number_of_ALL_on_cmdline(char **argv)
447 /* Iterate over cmd line arguments, count "ALL" */
449 if (strcmp(*argv++, "ALL") == 0)
455 //usage:#define iostat_trivial_usage
456 //usage: "[-c] [-d] [-t] [-z] [-k|-m] [ALL|BLOCKDEV...] [INTERVAL [COUNT]]"
457 //usage:#define iostat_full_usage "\n\n"
458 //usage: "Report CPU and I/O statistics\n"
459 //usage: "\nOptions:"
460 //usage: "\n -c Show CPU utilization"
461 //usage: "\n -d Show device utilization"
462 //usage: "\n -t Print current time"
463 //usage: "\n -z Omit devices with no activity"
464 //usage: "\n -k Use kb/s"
465 //usage: "\n -m Use Mb/s"
467 int iostat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
468 int iostat_main(int argc, char **argv)
471 unsigned interval = 0;
473 cputime_t global_uptime[2] = { 0 };
474 cputime_t smp_uptime[2] = { 0 };
476 struct stats_cpu stats_cur, stats_last;
480 memset(&stats_last, 0, sizeof(stats_last));
482 /* Get number of clock ticks per sec */
483 G.clk_tck = get_user_hz();
485 /* Determine number of CPUs */
486 G.total_cpus = get_cpu_count();
487 if (G.total_cpus == 0)
490 /* Parse and process arguments */
491 /* -k and -m are mutually exclusive */
492 opt_complementary = "k--m:m--k";
493 opt = getopt32(argv, "cdtzkm");
494 if (!(opt & (OPT_c + OPT_d)))
496 opt |= OPT_c + OPT_d;
501 dev_num = argc - numbers_on_cmdline(argc, argv);
502 /* We don't want to allocate space for 'ALL' */
503 dev_num -= number_of_ALL_on_cmdline(argv);
505 /* Make space for device list */
506 G.dlist = xzalloc(sizeof(G.dlist[0]) * dev_num);
508 /* Store device names into device list */
509 while (*argv && !isdigit(*argv[0])) {
510 if (strcmp(*argv, "ALL") != 0)
511 /* If not ALL, save device name */
512 save_to_devlist(*argv);
521 interval = xatoi_positive(*argv);
522 count = (interval != 0 ? -1 : 1);
525 /* Get count value */
526 count = xatoi_positive(*argv);
529 /* Allocate space for device stats */
531 G.saved_stats_dev = xzalloc(sizeof(G.saved_stats_dev[0]) *
532 (dev_num ? dev_num : get_number_of_devices())
541 /* Fill the time structure */
542 get_localtime(&G.tmtime);
544 /* Fetch current CPU statistics */
545 get_cpu_statistics(&stats_cur);
547 /* Fetch current uptime */
548 global_uptime[CURRENT] = get_uptime(&stats_cur);
551 itv = get_interval(global_uptime[LAST], global_uptime[CURRENT]);
557 cpu_report(&stats_last, &stats_cur, itv);
559 /* Separate outputs by a newline */
565 smp_uptime[CURRENT] = get_smp_uptime();
566 itv = get_interval(smp_uptime[LAST], smp_uptime[CURRENT]);
567 smp_uptime[LAST] = smp_uptime[CURRENT];
577 /* Backup current stats */
578 global_uptime[LAST] = global_uptime[CURRENT];
579 stats_last = stats_cur;
587 if (ENABLE_FEATURE_CLEAN_UP) {
590 free(G.saved_stats_dev);