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 //config:config IOSTAT
11 //config: bool "iostat"
14 //config: Report CPU and I/O statistics
16 //applet:IF_IOSTAT(APPLET(iostat, BB_DIR_BIN, BB_SUID_DROP))
18 //kbuild:lib-$(CONFIG_IOSTAT) += iostat.o
21 #include <sys/utsname.h> /* struct utsname */
23 //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
24 #define debug(fmt, ...) ((void)0)
26 #define MAX_DEVICE_NAME 12
27 #define MAX_DEVICE_NAME_STR "12"
30 typedef unsigned long long cputime_t;
31 typedef long long icputime_t;
32 # define FMT_DATA "ll"
33 # define CPUTIME_MAX (~0ULL)
35 typedef unsigned long cputime_t;
36 typedef long icputime_t;
38 # define CPUTIME_MAX (~0UL)
59 cputime_t vector[N_STATS_CPU];
69 unsigned long long rd_sectors;
70 unsigned long long wr_sectors;
75 typedef struct stats_dev {
76 struct stats_dev *next;
77 char dname[MAX_DEVICE_NAME + 1];
78 stats_dev_data_t prev_data;
79 stats_dev_data_t curr_data;
82 /* Globals. Sort by size and access frequency. */
85 unsigned total_cpus; /* Number of CPUs */
86 unsigned clk_tck; /* Number of clock ticks per second */
87 llist_t *dev_name_list; /* List of devices entered on the command line */
88 stats_dev_t *stats_dev_list;
95 #define G (*ptr_to_globals)
96 #define INIT_G() do { \
97 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
102 /* Must match option string! */
112 static ALWAYS_INLINE unsigned get_user_hz(void)
114 return sysconf(_SC_CLK_TCK);
117 static ALWAYS_INLINE int this_is_smp(void)
119 return (G.total_cpus > 1);
122 static void print_header(void)
127 uname(&uts); /* never fails */
129 /* Date representation for the current locale */
130 strftime(buf, sizeof(buf), "%x", &G.tmtime);
132 printf("%s %s (%s) \t%s \t_%s_\t(%u CPU)\n\n",
133 uts.sysname, uts.release, uts.nodename,
134 buf, uts.machine, G.total_cpus);
137 static void get_localtime(struct tm *ptm)
141 localtime_r(&timer, ptm);
144 static void print_timestamp(void)
147 /* %x: date representation for the current locale */
148 /* %X: time representation for the current locale */
149 strftime(buf, sizeof(buf), "%x %X", &G.tmtime);
153 static cputime_t get_smp_uptime(void)
156 unsigned long sec, dec;
158 fp = xfopen_for_read("/proc/uptime");
160 if (fscanf(fp, "%lu.%lu", &sec, &dec) != 2)
161 bb_error_msg_and_die("can't read '%s'", "/proc/uptime");
165 return (cputime_t)sec * G.clk_tck + dec * G.clk_tck / 100;
168 /* Fetch CPU statistics from /proc/stat */
169 static void get_cpu_statistics(stats_cpu_t *sc)
174 fp = xfopen_for_read("/proc/stat");
176 memset(sc, 0, sizeof(*sc));
178 while (fgets(buf, sizeof(buf), fp)) {
182 /* Does the line start with "cpu "? */
183 if (!starts_with_cpu(buf) || buf[3] != ' ') {
187 for (i = STATS_CPU_USER; i <= STATS_CPU_GUEST; i++) {
188 ibuf = skip_whitespace(ibuf);
189 sscanf(ibuf, "%"FMT_DATA"u", &sc->vector[i]);
190 if (i != STATS_CPU_GUEST) {
191 sc->vector[GLOBAL_UPTIME] += sc->vector[i];
193 ibuf = skip_non_whitespace(ibuf);
199 sc->vector[SMP_UPTIME] = get_smp_uptime();
205 static ALWAYS_INLINE cputime_t get_interval(cputime_t old, cputime_t new)
207 cputime_t itv = new - old;
209 return (itv == 0) ? 1 : itv;
212 #if CPUTIME_MAX > 0xffffffff
214 * Handle overflow conditions properly for counters which can have
215 * less bits than cputime_t, depending on the kernel version.
217 /* Surprisingly, on 32bit inlining is a size win */
218 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
220 cputime_t v = curr - prev;
222 if ((icputime_t)v < 0 /* curr < prev - counter overflow? */
223 && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
225 /* Add 33th bit set to 1 to curr, compensating for the overflow */
226 /* double shift defeats "warning: left shift count >= width of type" */
227 v += ((cputime_t)1 << 16) << 16;
232 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
238 static double percent_value(cputime_t prev, cputime_t curr, cputime_t itv)
240 return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
243 static void print_stats_cpu_struct(stats_cpu_pair_t *stats)
245 cputime_t *p = stats->prev->vector;
246 cputime_t *c = stats->curr->vector;
247 printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
248 percent_value(p[STATS_CPU_USER] , c[STATS_CPU_USER] , stats->itv),
249 percent_value(p[STATS_CPU_NICE] , c[STATS_CPU_NICE] , stats->itv),
250 percent_value(p[STATS_CPU_SYSTEM] + p[STATS_CPU_SOFTIRQ] + p[STATS_CPU_IRQ],
251 c[STATS_CPU_SYSTEM] + c[STATS_CPU_SOFTIRQ] + c[STATS_CPU_IRQ], stats->itv),
252 percent_value(p[STATS_CPU_IOWAIT], c[STATS_CPU_IOWAIT], stats->itv),
253 percent_value(p[STATS_CPU_STEAL] , c[STATS_CPU_STEAL] , stats->itv),
254 percent_value(p[STATS_CPU_IDLE] , c[STATS_CPU_IDLE] , stats->itv)
258 static void cpu_report(stats_cpu_pair_t *stats)
260 /* Always print a header */
261 puts("avg-cpu: %user %nice %system %iowait %steal %idle");
263 /* Print current statistics */
264 print_stats_cpu_struct(stats);
267 static void print_stats_dev_struct(stats_dev_t *stats_dev, cputime_t itv)
269 stats_dev_data_t *p = &stats_dev->prev_data;
270 stats_dev_data_t *c = &stats_dev->curr_data;
271 if (option_mask32 & OPT_z)
272 if (p->rd_ops == c->rd_ops && p->wr_ops == c->wr_ops)
275 printf("%-13s %8.2f %12.2f %12.2f %10llu %10llu\n",
277 percent_value(p->rd_ops + p->wr_ops, c->rd_ops + c->wr_ops, itv),
278 percent_value(p->rd_sectors, c->rd_sectors, itv) / G.unit.div,
279 percent_value(p->wr_sectors, c->wr_sectors, itv) / G.unit.div,
280 (c->rd_sectors - p->rd_sectors) / G.unit.div,
281 (c->wr_sectors - p->wr_sectors) / G.unit.div
285 static void print_devstat_header(void)
287 printf("Device:%15s%6s%s/s%6s%s/s%6s%s%6s%s\n",
289 G.unit.str, "_read", G.unit.str, "_wrtn",
290 G.unit.str, "_read", G.unit.str, "_wrtn"
295 * Is input partition of format [sdaN]?
297 static int is_partition(const char *dev)
299 /* Ok, this is naive... */
300 return ((dev[0] - 's') | (dev[1] - 'd') | (dev[2] - 'a')) == 0 && isdigit(dev[3]);
303 static stats_dev_t *stats_dev_find_or_new(const char *dev_name)
305 stats_dev_t **curr = &G.stats_dev_list;
307 while (*curr != NULL) {
308 if (strcmp((*curr)->dname, dev_name) == 0)
310 curr = &(*curr)->next;
313 *curr = xzalloc(sizeof(stats_dev_t));
314 strncpy((*curr)->dname, dev_name, MAX_DEVICE_NAME);
318 static void stats_dev_free(stats_dev_t *stats_dev)
321 stats_dev_free(stats_dev->next);
326 static void do_disk_statistics(cputime_t itv)
329 char dev_name[MAX_DEVICE_NAME + 1];
330 unsigned long long rd_sec_or_dummy;
331 unsigned long long wr_sec_or_dummy;
332 stats_dev_data_t *curr_data;
333 stats_dev_t *stats_dev;
337 fp = xfopen_for_read("/proc/diskstats");
338 /* Read and possibly print stats from /proc/diskstats */
339 while (fgets(buf, sizeof(buf), fp)) {
340 sscanf(buf, "%*s %*s %"MAX_DEVICE_NAME_STR"s", dev_name);
341 if (G.dev_name_list) {
342 /* Is device name in list? */
343 if (!llist_find_str(G.dev_name_list, dev_name))
345 } else if (is_partition(dev_name)) {
349 stats_dev = stats_dev_find_or_new(dev_name);
350 curr_data = &stats_dev->curr_data;
352 rc = sscanf(buf, "%*s %*s %*s %lu %llu %llu %llu %lu %*s %llu",
355 &curr_data->rd_sectors,
358 &curr_data->wr_sectors);
360 curr_data->rd_sectors = rd_sec_or_dummy;
361 curr_data->wr_sectors = wr_sec_or_dummy;
362 //curr_data->rd_ops = ;
363 curr_data->wr_ops = (unsigned long)curr_data->rd_sectors;
366 if (!G.dev_name_list /* User didn't specify device */
368 && curr_data->rd_ops == 0
369 && curr_data->wr_ops == 0
371 /* Don't print unused device */
375 /* Print current statistics */
376 print_stats_dev_struct(stats_dev, itv);
377 stats_dev->prev_data = *curr_data;
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 //usage:#define iostat_trivial_usage
393 //usage: "[-c] [-d] [-t] [-z] [-k|-m] [ALL|BLOCKDEV...] [INTERVAL [COUNT]]"
394 //usage:#define iostat_full_usage "\n\n"
395 //usage: "Report CPU and I/O statistics\n"
396 //usage: "\n -c Show CPU utilization"
397 //usage: "\n -d Show device utilization"
398 //usage: "\n -t Print current time"
399 //usage: "\n -z Omit devices with no activity"
400 //usage: "\n -k Use kb/s"
401 //usage: "\n -m Use Mb/s"
403 int iostat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
404 int iostat_main(int argc UNUSED_PARAM, char **argv)
409 stats_cpu_t stats_data[2];
410 smallint current_stats;
414 memset(&stats_data, 0, sizeof(stats_data));
416 /* Get number of clock ticks per sec */
417 G.clk_tck = get_user_hz();
419 /* Determine number of CPUs */
420 G.total_cpus = get_cpu_count();
421 if (G.total_cpus == 0)
424 /* Parse and process arguments */
425 /* -k and -m are mutually exclusive */
426 opt_complementary = "k--m:m--k";
427 opt = getopt32(argv, "cdtzkm");
428 if (!(opt & (OPT_c + OPT_d)))
430 opt |= OPT_c + OPT_d;
434 /* Store device names into device list */
435 while (*argv && !isdigit(*argv[0])) {
436 if (strcmp(*argv, "ALL") != 0) {
437 /* If not ALL, save device name */
438 char *dev_name = skip_dev_pfx(*argv);
439 if (!llist_find_str(G.dev_name_list, dev_name)) {
440 llist_add_to(&G.dev_name_list, dev_name);
452 interval = xatoi_positive(*argv);
453 count = (interval != 0 ? -1 : 1);
456 /* Get count value */
457 count = xatoi_positive(*argv);
470 get_localtime(&G.tmtime);
478 stats_cpu_pair_t stats;
480 stats.prev = &stats_data[current_stats ^ 1];
481 stats.curr = &stats_data[current_stats];
483 /* Fill the time structure */
484 get_localtime(&G.tmtime);
486 /* Fetch current CPU statistics */
487 get_cpu_statistics(stats.curr);
490 stats.itv = get_interval(
491 stats.prev->vector[GLOBAL_UPTIME],
492 stats.curr->vector[GLOBAL_UPTIME]
501 /* Separate outputs by a newline */
507 stats.itv = get_interval(
508 stats.prev->vector[SMP_UPTIME],
509 stats.curr->vector[SMP_UPTIME]
512 dev_report(stats.itv);
528 if (ENABLE_FEATURE_CLEAN_UP) {
529 llist_free(G.dev_name_list, NULL);
530 stats_dev_free(G.stats_dev_list);