mass removal of underscores from _BB_DIR_foo and _BB_SUID_foo
[platform/upstream/busybox.git] / procps / iostat.c
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
10 //applet:IF_IOSTAT(APPLET(iostat, BB_DIR_BIN, BB_SUID_DROP))
11
12 //kbuild:lib-$(CONFIG_IOSTAT) += iostat.o
13
14 //config:config IOSTAT
15 //config:       bool "iostat"
16 //config:       default y
17 //config:       help
18 //config:         Report CPU and I/O statistics
19
20 #include "libbb.h"
21 #include <sys/utsname.h>  /* Need struct utsname */
22
23 //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
24 #define debug(fmt, ...) ((void)0)
25
26 #define MAX_DEVICE_NAME 12
27 #define CURRENT          0
28 #define LAST             1
29
30 #if 1
31 typedef unsigned long long cputime_t;
32 typedef long long icputime_t;
33 # define FMT_DATA "ll"
34 # define CPUTIME_MAX (~0ULL)
35 #else
36 typedef unsigned long cputime_t;
37 typedef long icputime_t;
38 # define FMT_DATA "l"
39 # define CPUTIME_MAX (~0UL)
40 #endif
41
42 struct stats_cpu {
43         cputime_t cpu_user;
44         cputime_t cpu_nice;
45         cputime_t cpu_system;
46         cputime_t cpu_idle;
47         cputime_t cpu_iowait;
48         cputime_t cpu_steal;
49         cputime_t cpu_irq;
50         cputime_t cpu_softirq;
51         cputime_t cpu_guest;
52 };
53
54 struct stats_dev {
55         char dname[MAX_DEVICE_NAME];
56         unsigned long long rd_sectors;
57         unsigned long long wr_sectors;
58         unsigned long rd_ops;
59         unsigned long wr_ops;
60 };
61
62 /* List of devices entered on the command line */
63 struct device_list {
64         char dname[MAX_DEVICE_NAME];
65 };
66
67 /* Globals. Sort by size and access frequency. */
68 struct globals {
69         smallint show_all;
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;
75         struct tm tmtime;
76 };
77 #define G (*ptr_to_globals)
78 #define INIT_G() do { \
79         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
80 } while (0)
81
82 /* Must match option string! */
83 enum {
84         OPT_c = 1 << 0,
85         OPT_d = 1 << 1,
86         OPT_t = 1 << 2,
87         OPT_z = 1 << 3,
88         OPT_k = 1 << 4,
89         OPT_m = 1 << 5,
90 };
91
92 static ALWAYS_INLINE unsigned get_user_hz(void)
93 {
94         return sysconf(_SC_CLK_TCK);
95 }
96
97 static ALWAYS_INLINE int this_is_smp(void)
98 {
99         return (G.total_cpus > 1);
100 }
101
102 static void print_header(void)
103 {
104         char buf[16];
105         struct utsname uts;
106
107         if (uname(&uts) < 0)
108                 bb_perror_msg_and_die("uname");
109
110         strftime(buf, sizeof(buf), "%x", &G.tmtime);
111
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);
115 }
116
117 static void get_localtime(struct tm *ptm)
118 {
119         time_t timer;
120         time(&timer);
121         localtime_r(&timer, ptm);
122 }
123
124 static void print_timestamp(void)
125 {
126         char buf[20];
127         strftime(buf, sizeof(buf), "%x %X", &G.tmtime);
128         printf("%s\n", buf);
129 }
130
131 /* Fetch CPU statistics from /proc/stat */
132 static void get_cpu_statistics(struct stats_cpu *sc)
133 {
134         FILE *fp;
135         char buf[1024];
136
137         fp = xfopen_for_read("/proc/stat");
138
139         memset(sc, 0, sizeof(*sc));
140
141         while (fgets(buf, sizeof(buf), fp)) {
142                 /* Does the line starts with "cpu "? */
143                 if (starts_with_cpu(buf) && buf[3] == ' ') {
144                         sscanf(buf + 4 + 1,
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);
150                 }
151         }
152
153         fclose(fp);
154 }
155
156 static cputime_t get_smp_uptime(void)
157 {
158         FILE *fp;
159         char buf[sizeof(long)*3 * 2 + 4];
160         unsigned long sec, dec;
161
162         fp = xfopen_for_read("/proc/uptime");
163
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");
167
168         fclose(fp);
169
170         return (cputime_t)sec * G.clk_tck + dec * G.clk_tck / 100;
171 }
172
173 /*
174  * Obtain current uptime in jiffies.
175  * Uptime is sum of individual CPUs' uptimes.
176  */
177 static cputime_t get_uptime(const struct stats_cpu *sc)
178 {
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;
182 }
183
184 static ALWAYS_INLINE cputime_t get_interval(cputime_t old, cputime_t new)
185 {
186         cputime_t itv = new - old;
187
188         return (itv == 0) ? 1 : itv;
189 }
190
191 #if CPUTIME_MAX > 0xffffffff
192 /*
193  * Handle overflow conditions properly for counters which can have
194  * less bits than cputime_t, depending on the kernel version.
195  */
196 /* Surprisingly, on 32bit inlining is a size win */
197 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
198 {
199         cputime_t v = curr - prev;
200
201         if ((icputime_t)v < 0     /* curr < prev - counter overflow? */
202          && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
203         ) {
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;
207         }
208         return v;
209 }
210 #else
211 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
212 {
213         return curr - prev;
214 }
215 #endif
216
217 static double percent_value(cputime_t prev, cputime_t curr, cputime_t itv)
218 {
219         return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
220 }
221
222 static void print_stats_cpu_struct(const struct stats_cpu *p,
223                 const struct stats_cpu *c, cputime_t itv)
224 {
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)
233         );
234 }
235
236 static void print_stats_dev_struct(const struct stats_dev *p,
237                 const struct stats_dev *c, cputime_t itv)
238 {
239         int unit = 1;
240
241         if (option_mask32 & OPT_k)
242                 unit = 2;
243         else if (option_mask32 & OPT_m)
244                 unit = 2048;
245
246         if (option_mask32 & OPT_z)
247                 if (p->rd_ops == c->rd_ops && p->wr_ops == c->wr_ops)
248                         return;
249
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);
258 }
259
260 static void cpu_report(const struct stats_cpu *last,
261                 const struct stats_cpu *cur,
262                 cputime_t itv)
263 {
264         /* Always print a header */
265         puts("avg-cpu:  %user   %nice %system %iowait  %steal   %idle");
266
267         /* Print current statistics */
268         print_stats_cpu_struct(last, cur, itv);
269 }
270
271 static void print_devstat_header(void)
272 {
273         printf("Device:            tps");
274
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");
279         else
280                 puts("   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn");
281 }
282
283 /*
284  * Is input partition of format [sdaN]?
285  */
286 static int is_partition(const char *dev)
287 {
288         /* Ok, this is naive... */
289         return ((dev[0] - 's') | (dev[1] - 'd') | (dev[2] - 'a')) == 0 && isdigit(dev[3]);
290 }
291
292 /*
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)
296  */
297 static int numbers_on_cmdline(int argc, char *argv[])
298 {
299         int sum = 0;
300
301         if (isdigit(argv[argc-1][0]))
302                 sum++;
303         if (argc > 2 && isdigit(argv[argc-2][0]))
304                 sum++;
305
306         return sum;
307 }
308
309 static int is_dev_in_dlist(const char *dev)
310 {
311         int i;
312
313         /* Go through the device list */
314         for (i = 0; i < G.devlist_i; i++)
315                 if (strcmp(G.dlist[i].dname, dev) == 0)
316                         /* Found a match */
317                         return 1;
318
319         /* No match found */
320         return 0;
321 }
322
323 static void do_disk_statistics(cputime_t itv)
324 {
325         FILE *fp;
326         int rc;
327         int i = 0;
328         char buf[128];
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;
333         struct stats_dev sd;
334
335         fp = xfopen_for_read("/proc/diskstats");
336
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);
343
344                 switch (rc) {
345                 case 14:
346                         sd.wr_ops = wr_ops;
347                         sd.rd_sectors = rd_sec_or_wr_ops;
348                         sd.wr_sectors = wr_sec;
349                         break;
350                 case 7:
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;
354                         break;
355                 default:
356                         break;
357                 }
358
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 */
363                                 continue;
364                         }
365                         print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
366                         G.saved_stats_dev[i] = sd;
367                         i++;
368                 } else {
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;
374                                 i++;
375                         } else
376                                 continue;
377                 }
378         }
379
380         fclose(fp);
381 }
382
383 static void dev_report(cputime_t itv)
384 {
385         /* Always print a header */
386         print_devstat_header();
387
388         /* Fetch current disk statistics */
389         do_disk_statistics(itv);
390 }
391
392 static void save_to_devlist(const char *dname)
393 {
394         int i;
395         struct device_list *tmp = G.dlist;
396
397         if (strncmp(dname, "/dev/", 5) == 0)
398                 /* We'll ignore prefix '/dev/' */
399                 dname += 5;
400
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 */
405                         return;
406
407         /* Add device name to the list */
408         strncpy(tmp->dname, dname, MAX_DEVICE_NAME - 1);
409
410         /* Update device list index */
411         G.devlist_i++;
412 }
413
414 static unsigned get_number_of_devices(void)
415 {
416         FILE *fp;
417         char buf[128];
418         int rv;
419         unsigned n = 0;
420         unsigned long rd_ops, wr_ops;
421         char dname[MAX_DEVICE_NAME];
422
423         fp = xfopen_for_read("/proc/diskstats");
424
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))
429                         /* A partition */
430                         continue;
431                 if (!rd_ops && !wr_ops) {
432                         /* Unused device */
433                         if (!G.show_all)
434                                 continue;
435                 }
436                 n++;
437         }
438
439         fclose(fp);
440         return n;
441 }
442
443 static int number_of_ALL_on_cmdline(char **argv)
444 {
445         int alls = 0;
446
447         /* Iterate over cmd line arguments, count "ALL" */
448         while (*argv)
449                 if (strcmp(*argv++, "ALL") == 0)
450                         alls++;
451
452         return alls;
453 }
454
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"
466
467 int iostat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
468 int iostat_main(int argc, char **argv)
469 {
470         int opt, dev_num;
471         unsigned interval = 0;
472         int count;
473         cputime_t global_uptime[2] = { 0 };
474         cputime_t smp_uptime[2] = { 0 };
475         cputime_t itv;
476         struct stats_cpu stats_cur, stats_last;
477
478         INIT_G();
479
480         memset(&stats_last, 0, sizeof(stats_last));
481
482         /* Get number of clock ticks per sec */
483         G.clk_tck = get_user_hz();
484
485         /* Determine number of CPUs */
486         G.total_cpus = get_cpu_count();
487         if (G.total_cpus == 0)
488                 G.total_cpus = 1;
489
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)))
495                 /* Default is -cd */
496                 opt |= OPT_c + OPT_d;
497
498         argv += optind;
499         argc -= optind;
500
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);
504         if (dev_num > 0)
505                 /* Make space for device list */
506                 G.dlist = xzalloc(sizeof(G.dlist[0]) * dev_num);
507
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);
513                 else
514                         G.show_all = 1;
515                 argv++;
516         }
517
518         count = 1;
519         if (*argv) {
520                 /* Get interval */
521                 interval = xatoi_positive(*argv);
522                 count = (interval != 0 ? -1 : 1);
523                 argv++;
524                 if (*argv)
525                         /* Get count value */
526                         count = xatoi_positive(*argv);
527         }
528
529         /* Allocate space for device stats */
530         if (opt & OPT_d) {
531                 G.saved_stats_dev = xzalloc(sizeof(G.saved_stats_dev[0]) *
532                                 (dev_num ? dev_num : get_number_of_devices())
533                 );
534         }
535
536         /* Display header */
537         print_header();
538
539         /* Main loop */
540         for (;;) {
541                 /* Fill the time structure */
542                 get_localtime(&G.tmtime);
543
544                 /* Fetch current CPU statistics */
545                 get_cpu_statistics(&stats_cur);
546
547                 /* Fetch current uptime */
548                 global_uptime[CURRENT] = get_uptime(&stats_cur);
549
550                 /* Get interval */
551                 itv = get_interval(global_uptime[LAST], global_uptime[CURRENT]);
552
553                 if (opt & OPT_t)
554                         print_timestamp();
555
556                 if (opt & OPT_c) {
557                         cpu_report(&stats_last, &stats_cur, itv);
558                         if (opt & OPT_d)
559                                 /* Separate outputs by a newline */
560                                 bb_putchar('\n');
561                 }
562
563                 if (opt & OPT_d) {
564                         if (this_is_smp()) {
565                                 smp_uptime[CURRENT] = get_smp_uptime();
566                                 itv = get_interval(smp_uptime[LAST], smp_uptime[CURRENT]);
567                                 smp_uptime[LAST] = smp_uptime[CURRENT];
568                         }
569                         dev_report(itv);
570                 }
571
572                 if (count > 0) {
573                         if (--count == 0)
574                                 break;
575                 }
576
577                 /* Backup current stats */
578                 global_uptime[LAST] = global_uptime[CURRENT];
579                 stats_last = stats_cur;
580
581                 bb_putchar('\n');
582                 sleep(interval);
583         }
584
585         bb_putchar('\n');
586
587         if (ENABLE_FEATURE_CLEAN_UP) {
588                 free(&G);
589                 free(G.dlist);
590                 free(G.saved_stats_dev);
591         }
592
593         return EXIT_SUCCESS;
594 }