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
29 typedef unsigned long long cputime_t;
30 typedef long long icputime_t;
31 # define FMT_DATA "ll"
32 # define CPUTIME_MAX (~0ULL)
34 typedef unsigned long cputime_t;
35 typedef long icputime_t;
37 # define CPUTIME_MAX (~0UL)
58 cputime_t vector[N_STATS_CPU];
68 char dname[MAX_DEVICE_NAME];
69 unsigned long long rd_sectors;
70 unsigned long long wr_sectors;
75 /* Globals. Sort by size and access frequency. */
78 unsigned total_cpus; /* Number of CPUs */
79 unsigned clk_tck; /* Number of clock ticks per second */
80 llist_t *dev_list; /* List of devices entered on the command line */
81 struct stats_dev *saved_stats_dev;
88 #define G (*ptr_to_globals)
89 #define INIT_G() do { \
90 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
95 /* Must match option string! */
105 static ALWAYS_INLINE unsigned get_user_hz(void)
107 return sysconf(_SC_CLK_TCK);
110 static ALWAYS_INLINE int this_is_smp(void)
112 return (G.total_cpus > 1);
115 static void print_header(void)
120 uname(&uts); /* never fails */
122 /* Date representation for the current locale */
123 strftime(buf, sizeof(buf), "%x", &G.tmtime);
125 printf("%s %s (%s) \t%s \t_%s_\t(%u CPU)\n\n",
126 uts.sysname, uts.release, uts.nodename,
127 buf, uts.machine, G.total_cpus);
130 static void get_localtime(struct tm *ptm)
134 localtime_r(&timer, ptm);
137 static void print_timestamp(void)
140 /* %x: date representation for the current locale */
141 /* %X: time representation for the current locale */
142 strftime(buf, sizeof(buf), "%x %X", &G.tmtime);
146 static cputime_t get_smp_uptime(void)
149 unsigned long sec, dec;
151 fp = xfopen_for_read("/proc/uptime");
153 if (fscanf(fp, "%lu.%lu", &sec, &dec) != 2)
154 bb_error_msg_and_die("can't read '%s'", "/proc/uptime");
158 return (cputime_t)sec * G.clk_tck + dec * G.clk_tck / 100;
161 /* Fetch CPU statistics from /proc/stat */
162 static void get_cpu_statistics(stats_cpu_t *sc)
165 char buf[1024], *ibuf = buf + 4;
167 fp = xfopen_for_read("/proc/stat");
169 memset(sc, 0, sizeof(*sc));
171 while (fgets(buf, sizeof(buf), fp)) {
172 /* Does the line starts with "cpu "? */
173 if (!starts_with_cpu(buf) || buf[3] != ' ') {
176 for (int i = STATS_CPU_USER; i <= STATS_CPU_GUEST; i++) {
177 ibuf = skip_whitespace(ibuf);
178 sscanf(ibuf, "%"FMT_DATA"u", &sc->vector[i]);
179 if (i != STATS_CPU_GUEST) {
180 sc->vector[GLOBAL_UPTIME] += sc->vector[i];
182 ibuf = skip_non_whitespace(ibuf);
188 sc->vector[SMP_UPTIME] = get_smp_uptime();
194 static ALWAYS_INLINE cputime_t get_interval(cputime_t old, cputime_t new)
196 cputime_t itv = new - old;
198 return (itv == 0) ? 1 : itv;
201 #if CPUTIME_MAX > 0xffffffff
203 * Handle overflow conditions properly for counters which can have
204 * less bits than cputime_t, depending on the kernel version.
206 /* Surprisingly, on 32bit inlining is a size win */
207 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
209 cputime_t v = curr - prev;
211 if ((icputime_t)v < 0 /* curr < prev - counter overflow? */
212 && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
214 /* Add 33th bit set to 1 to curr, compensating for the overflow */
215 /* double shift defeats "warning: left shift count >= width of type" */
216 v += ((cputime_t)1 << 16) << 16;
221 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
227 static double percent_value(cputime_t prev, cputime_t curr, cputime_t itv)
229 return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
232 static void print_stats_cpu_struct(stats_cpu_pair_t *stats)
234 cputime_t *p = stats->prev->vector;
235 cputime_t *c = stats->curr->vector;
236 printf(" %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n",
237 percent_value(p[STATS_CPU_USER] , c[STATS_CPU_USER] , stats->itv),
238 percent_value(p[STATS_CPU_NICE] , c[STATS_CPU_NICE] , stats->itv),
239 percent_value(p[STATS_CPU_SYSTEM] + p[STATS_CPU_SOFTIRQ] + p[STATS_CPU_IRQ],
240 c[STATS_CPU_SYSTEM] + c[STATS_CPU_SOFTIRQ] + c[STATS_CPU_IRQ], stats->itv),
241 percent_value(p[STATS_CPU_IOWAIT], c[STATS_CPU_IOWAIT], stats->itv),
242 percent_value(p[STATS_CPU_STEAL] , c[STATS_CPU_STEAL] , stats->itv),
243 percent_value(p[STATS_CPU_IDLE] , c[STATS_CPU_IDLE] , stats->itv)
247 static void print_stats_dev_struct(const struct stats_dev *p,
248 const struct stats_dev *c, cputime_t itv)
250 if (option_mask32 & OPT_z)
251 if (p->rd_ops == c->rd_ops && p->wr_ops == c->wr_ops)
254 printf("%-13s %8.2f %12.2f %12.2f %10llu %10llu \n", c->dname,
255 percent_value(p->rd_ops + p->wr_ops ,
256 /**/ c->rd_ops + c->wr_ops , itv),
257 percent_value(p->rd_sectors, c->rd_sectors, itv) / G.unit.div,
258 percent_value(p->wr_sectors, c->wr_sectors, itv) / G.unit.div,
259 (c->rd_sectors - p->rd_sectors) / G.unit.div,
260 (c->wr_sectors - p->wr_sectors) / G.unit.div);
263 static void cpu_report(stats_cpu_pair_t *stats)
265 /* Always print a header */
266 puts("avg-cpu: %user %nice %system %iowait %steal %idle");
268 /* Print current statistics */
269 print_stats_cpu_struct(stats);
272 static void print_devstat_header(void)
274 printf("Device:%15s%6s%s/s%6s%s/s%6s%s%6s%s\n", "tps",
275 G.unit.str, "_read", G.unit.str, "_wrtn",
276 G.unit.str, "_read", G.unit.str, "_wrtn");
280 * Is input partition of format [sdaN]?
282 static int is_partition(const char *dev)
284 /* Ok, this is naive... */
285 return ((dev[0] - 's') | (dev[1] - 'd') | (dev[2] - 'a')) == 0 && isdigit(dev[3]);
288 static void do_disk_statistics(cputime_t itv)
294 unsigned major, minor;
295 unsigned long wr_ops, dummy; /* %*lu for suppress the conversion wouldn't work */
296 unsigned long long rd_sec_or_wr_ops;
297 unsigned long long rd_sec_or_dummy, wr_sec_or_dummy, wr_sec;
300 fp = xfopen_for_read("/proc/diskstats");
302 /* Read and possibly print stats from /proc/diskstats */
303 while (fgets(buf, sizeof(buf), fp)) {
304 rc = sscanf(buf, "%u %u %s %lu %llu %llu %llu %lu %lu %llu %lu %lu %lu %lu",
305 &major, &minor, sd.dname, &sd.rd_ops,
306 &rd_sec_or_dummy, &rd_sec_or_wr_ops, &wr_sec_or_dummy,
307 &wr_ops, &dummy, &wr_sec, &dummy, &dummy, &dummy, &dummy);
312 sd.rd_sectors = rd_sec_or_wr_ops;
313 sd.wr_sectors = wr_sec;
316 sd.rd_sectors = rd_sec_or_dummy;
317 sd.wr_ops = (unsigned long)rd_sec_or_wr_ops;
318 sd.wr_sectors = wr_sec_or_dummy;
324 if (!G.dev_list && !is_partition(sd.dname)) {
325 /* User didn't specify device */
326 if (!G.show_all && !sd.rd_ops && !sd.wr_ops) {
327 /* Don't print unused device */
330 print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
331 G.saved_stats_dev[i] = sd;
334 /* Is device in device list? */
335 if (llist_find_str(G.dev_list, sd.dname)) {
336 /* Print current statistics */
337 print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
338 G.saved_stats_dev[i] = sd;
348 static void dev_report(cputime_t itv)
350 /* Always print a header */
351 print_devstat_header();
353 /* Fetch current disk statistics */
354 do_disk_statistics(itv);
357 static unsigned get_number_of_devices(void)
363 unsigned long rd_ops, wr_ops;
364 char dname[MAX_DEVICE_NAME];
366 fp = xfopen_for_read("/proc/diskstats");
368 while (fgets(buf, sizeof(buf), fp)) {
369 rv = sscanf(buf, "%*d %*d %s %lu %*u %*u %*u %lu",
370 dname, &rd_ops, &wr_ops);
371 if (rv == 2 || is_partition(dname))
374 if (!rd_ops && !wr_ops) {
386 //usage:#define iostat_trivial_usage
387 //usage: "[-c] [-d] [-t] [-z] [-k|-m] [ALL|BLOCKDEV...] [INTERVAL [COUNT]]"
388 //usage:#define iostat_full_usage "\n\n"
389 //usage: "Report CPU and I/O statistics\n"
390 //usage: "\nOptions:"
391 //usage: "\n -c Show CPU utilization"
392 //usage: "\n -d Show device utilization"
393 //usage: "\n -t Print current time"
394 //usage: "\n -z Omit devices with no activity"
395 //usage: "\n -k Use kb/s"
396 //usage: "\n -m Use Mb/s"
398 int iostat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
399 int iostat_main(int argc UNUSED_PARAM, char **argv)
404 stats_cpu_t stats_data[2];
405 smallint current_stats;
409 memset(&stats_data, 0, sizeof(stats_data));
411 /* Get number of clock ticks per sec */
412 G.clk_tck = get_user_hz();
414 /* Determine number of CPUs */
415 G.total_cpus = get_cpu_count();
416 if (G.total_cpus == 0)
419 /* Parse and process arguments */
420 /* -k and -m are mutually exclusive */
421 opt_complementary = "k--m:m--k";
422 opt = getopt32(argv, "cdtzkm");
423 if (!(opt & (OPT_c + OPT_d)))
425 opt |= OPT_c + OPT_d;
429 /* Store device names into device list */
431 while (*argv && !isdigit(*argv[0])) {
432 if (strcmp(*argv, "ALL") != 0) {
433 /* If not ALL, save device name */
434 char *dev_name = skip_dev_pfx(*argv);
435 if (!llist_find_str(G.dev_list, dev_name)) {
436 llist_add_to(&G.dev_list, dev_name);
449 interval = xatoi_positive(*argv);
450 count = (interval != 0 ? -1 : 1);
453 /* Get count value */
454 count = xatoi_positive(*argv);
457 /* Allocate space for device stats */
459 G.saved_stats_dev = xzalloc(sizeof(G.saved_stats_dev[0]) *
460 (dev_num ? dev_num : get_number_of_devices())
474 get_localtime(&G.tmtime);
482 stats_cpu_pair_t stats;
484 stats.prev = &stats_data[current_stats ^ 1];
485 stats.curr = &stats_data[current_stats];
487 /* Fill the time structure */
488 get_localtime(&G.tmtime);
490 /* Fetch current CPU statistics */
491 get_cpu_statistics(stats.curr);
494 stats.itv = get_interval(
495 stats.prev->vector[GLOBAL_UPTIME],
496 stats.curr->vector[GLOBAL_UPTIME]
505 /* Separate outputs by a newline */
511 stats.itv = get_interval(
512 stats.prev->vector[SMP_UPTIME],
513 stats.curr->vector[SMP_UPTIME]
516 dev_report(stats.itv);
532 if (ENABLE_FEATURE_CLEAN_UP) {
533 llist_free(G.dev_list, NULL);
534 free(G.saved_stats_dev);