*: s/xatoi_u/xatoi_positive/g - I got bored of mistyping xatoi_u as xatou_i
[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 tarball for details.
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 int get_number_of_cpus(void)
118 {
119 #ifdef _SC_NPROCESSORS_CONF
120         return sysconf(_SC_NPROCESSORS_CONF);
121 #else
122         char buf[128];
123         int n = 0;
124         FILE *fp;
125
126         fp = xfopen_for_read("/proc/cpuinfo");
127
128         while (fgets(buf, sizeof(buf), fp))
129                 if (strncmp(buf, "processor\t:", 11) == 0)
130                         n++;
131
132         fclose(fp);
133         return n;
134 #endif
135 }
136
137 static void get_localtime(struct tm *ptm)
138 {
139         time_t timer;
140         time(&timer);
141         localtime_r(&timer, ptm);
142 }
143
144 static void print_timestamp(void)
145 {
146         char buf[20];
147         strftime(buf, sizeof(buf), "%x %X", &G.tmtime);
148         printf("%s\n", buf);
149 }
150
151 /* Does str start with "cpu"? */
152 static int starts_with_cpu(const char *str)
153 {
154         return ((str[0] - 'c') | (str[1] - 'p') | (str[2] - 'u')) == 0;
155 }
156
157 /* Fetch CPU statistics from /proc/stat */
158 static void get_cpu_statistics(struct stats_cpu *sc)
159 {
160         FILE *fp;
161         char buf[1024];
162
163         fp = xfopen_for_read("/proc/stat");
164
165         memset(sc, 0, sizeof(*sc));
166
167         while (fgets(buf, sizeof(buf), fp)) {
168                 /* Does the line starts with "cpu "? */
169                 if (starts_with_cpu(buf) && buf[3] == ' ') {
170                         sscanf(buf + 4 + 1,
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);
176                 }
177         }
178
179         fclose(fp);
180 }
181
182 static cputime_t get_smp_uptime(void)
183 {
184         FILE *fp;
185         char buf[sizeof(long)*3 * 2 + 4];
186         unsigned long sec, dec;
187
188         fp = xfopen_for_read("/proc/uptime");
189
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");
193
194         fclose(fp);
195
196         return (cputime_t)sec * G.clk_tck + dec * G.clk_tck / 100;
197 }
198
199 /*
200  * Obtain current uptime in jiffies.
201  * Uptime is sum of individual CPUs' uptimes.
202  */
203 static cputime_t get_uptime(const struct stats_cpu *sc)
204 {
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;
208 }
209
210 static ALWAYS_INLINE cputime_t get_interval(cputime_t old, cputime_t new)
211 {
212         cputime_t itv = new - old;
213
214         return (itv == 0) ? 1 : itv;
215 }
216
217 #if CPUTIME_MAX > 0xffffffff
218 /*
219  * Handle overflow conditions properly for counters which can have
220  * less bits than cputime_t, depending on the kernel version.
221  */
222 /* Surprisingly, on 32bit inlining is a size win */
223 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
224 {
225         cputime_t v = curr - prev;
226
227         if ((icputime_t)v < 0     /* curr < prev - counter overflow? */
228          && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
229         ) {
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;
233         }
234         return v;
235 }
236 #else
237 static ALWAYS_INLINE cputime_t overflow_safe_sub(cputime_t prev, cputime_t curr)
238 {
239         return curr - prev;
240 }
241 #endif
242
243 static double percent_value(cputime_t prev, cputime_t curr, cputime_t itv)
244 {
245         return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
246 }
247
248 static void print_stats_cpu_struct(const struct stats_cpu *p,
249                 const struct stats_cpu *c, cputime_t itv)
250 {
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)
259         );
260 }
261
262 static void print_stats_dev_struct(const struct stats_dev *p,
263                 const struct stats_dev *c, cputime_t itv)
264 {
265         int unit = 1;
266
267         if (option_mask32 & OPT_k)
268                 unit = 2;
269         else if (option_mask32 & OPT_m)
270                 unit = 2048;
271
272         if (option_mask32 & OPT_z)
273                 if (p->rd_ops == c->rd_ops && p->wr_ops == c->wr_ops)
274                         return;
275
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);
284 }
285
286 static void cpu_report(const struct stats_cpu *last,
287                 const struct stats_cpu *cur,
288                 cputime_t itv)
289 {
290         /* Always print a header */
291         puts("avg-cpu:  %user   %nice %system %iowait  %steal   %idle");
292
293         /* Print current statistics */
294         print_stats_cpu_struct(last, cur, itv);
295 }
296
297 static void print_devstat_header(void)
298 {
299         printf("Device:            tps");
300
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");
305         else
306                 puts("   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn");
307 }
308
309 /*
310  * Is input partition of format [sdaN]?
311  */
312 static int is_partition(const char *dev)
313 {
314         /* Ok, this is naive... */
315         return ((dev[0] - 's') | (dev[1] - 'd') | (dev[2] - 'a')) == 0 && isdigit(dev[3]);
316 }
317
318 /*
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)
322  */
323 static int numbers_on_cmdline(int argc, char *argv[])
324 {
325         int sum = 0;
326
327         if (isdigit(argv[argc-1][0]))
328                 sum++;
329         if (argc > 2 && isdigit(argv[argc-2][0]))
330                 sum++;
331
332         return sum;
333 }
334
335 static int is_dev_in_dlist(const char *dev)
336 {
337         int i;
338
339         /* Go through the device list */
340         for (i = 0; i < G.devlist_i; i++)
341                 if (strcmp(G.dlist[i].dname, dev) == 0)
342                         /* Found a match */
343                         return 1;
344
345         /* No match found */
346         return 0;
347 }
348
349 static void do_disk_statistics(cputime_t itv)
350 {
351         FILE *fp;
352         int rc;
353         int i = 0;
354         char buf[128];
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;
359         struct stats_dev sd;
360
361         fp = xfopen_for_read("/proc/diskstats");
362
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);
369
370                 switch (rc) {
371                 case 14:
372                         sd.wr_ops = wr_ops;
373                         sd.rd_sectors = rd_sec_or_wr_ops;
374                         sd.wr_sectors = wr_sec;
375                         break;
376                 case 7:
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;
380                         break;
381                 default:
382                         break;
383                 }
384
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 */
389                                 continue;
390                         }
391                         print_stats_dev_struct(&G.saved_stats_dev[i], &sd, itv);
392                         G.saved_stats_dev[i] = sd;
393                         i++;
394                 } else {
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;
400                                 i++;
401                         } else
402                                 continue;
403                 }
404         }
405 }
406
407 static void dev_report(cputime_t itv)
408 {
409         /* Always print a header */
410         print_devstat_header();
411
412         /* Fetch current disk statistics */
413         do_disk_statistics(itv);
414 }
415
416 static void save_to_devlist(const char *dname)
417 {
418         int i;
419         struct device_list *tmp = G.dlist;
420
421         if (strncmp(dname, "/dev/", 5) == 0)
422                 /* We'll ignore prefix '/dev/' */
423                 dname += 5;
424
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 */
429                         return;
430
431         /* Add device name to the list */
432         strncpy(tmp->dname, dname, MAX_DEVICE_NAME - 1);
433
434         /* Update device list index */
435         G.devlist_i++;
436 }
437
438 static unsigned get_number_of_devices(void)
439 {
440         FILE *fp;
441         char buf[128];
442         int rv;
443         unsigned n = 0;
444         unsigned long rd_ops, wr_ops;
445         char dname[MAX_DEVICE_NAME];
446
447         fp = xfopen_for_read("/proc/diskstats");
448
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))
453                         /* A partition */
454                         continue;
455                 if (!rd_ops && !wr_ops) {
456                         /* Unused device */
457                         if (!G.show_all)
458                                 continue;
459                 }
460                 n++;
461         }
462
463         fclose(fp);
464         return n;
465 }
466
467 static int number_of_ALL_on_cmdline(char **argv)
468 {
469         int alls = 0;
470
471         /* Iterate over cmd line arguments, count "ALL" */
472         while (*argv)
473                 if (strcmp(*argv++, "ALL") == 0)
474                         alls++;
475
476         return alls;
477 }
478
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"
490
491 int iostat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
492 int iostat_main(int argc, char **argv)
493 {
494         int opt, dev_num;
495         unsigned interval = 0;
496         int count = 0;
497         cputime_t global_uptime[2] = { 0 };
498         cputime_t smp_uptime[2] = { 0 };
499         cputime_t itv;
500         struct stats_cpu stats_cur, stats_last;
501
502         INIT_G();
503
504         memset(&stats_last, 0, sizeof(stats_last));
505
506         /* Get number of clock ticks per sec */
507         G.clk_tck = get_user_hz();
508
509         /* Determine number of CPUs */
510         G.total_cpus = get_number_of_cpus();
511
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)))
517                 /* Default is -cd */
518                 opt |= OPT_c + OPT_d;
519
520         argv += optind;
521         argc -= optind;
522
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);
526         if (dev_num > 0)
527                 /* Make space for device list */
528                 G.dlist = xzalloc(sizeof(G.dlist[0]) * dev_num);
529
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);
535                 else
536                         G.show_all = 1;
537                 argv++;
538         }
539
540         if (*argv) {
541                 /* Get interval */
542                 interval = xatoi_positive(*argv);
543                 count = interval ? -1 : 1;
544                 argv++;
545                 if (*argv)
546                         /* Get count value */
547                         count = xatoi_positive(*argv);
548         }
549
550         /* Allocate space for device stats */
551         if (opt & OPT_d) {
552                 G.saved_stats_dev = xzalloc(sizeof(G.saved_stats_dev[0]) *
553                                 (dev_num ? dev_num : get_number_of_devices())
554                 );
555         }
556
557         /* Display header */
558         print_header();
559
560         /* Main loop */
561         for (;;) {
562                 /* Fill the time structure */
563                 get_localtime(&G.tmtime);
564
565                 /* Fetch current CPU statistics */
566                 get_cpu_statistics(&stats_cur);
567
568                 /* Fetch current uptime */
569                 global_uptime[CURRENT] = get_uptime(&stats_cur);
570
571                 /* Get interval */
572                 itv = get_interval(global_uptime[LAST], global_uptime[CURRENT]);
573
574                 if (opt & OPT_t)
575                         print_timestamp();
576
577                 if (opt & OPT_c) {
578                         cpu_report(&stats_last, &stats_cur, itv);
579                         if (opt & OPT_d)
580                                 /* Separate outputs by a newline */
581                                 bb_putchar('\n');
582                 }
583
584                 if (opt & OPT_d) {
585                         if (this_is_smp()) {
586                                 smp_uptime[CURRENT] = get_smp_uptime();
587                                 itv = get_interval(smp_uptime[LAST], smp_uptime[CURRENT]);
588                                 smp_uptime[LAST] = smp_uptime[CURRENT];
589                         }
590                         dev_report(itv);
591                 }
592
593                 if (count > 0) {
594                         if (--count == 0)
595                                 break;
596                 }
597
598                 /* Backup current stats */
599                 global_uptime[LAST] = global_uptime[CURRENT];
600                 stats_last = stats_cur;
601
602                 bb_putchar('\n');
603                 sleep(interval);
604         }
605
606         bb_putchar('\n');
607
608         if (ENABLE_FEATURE_CLEAN_UP) {
609                 free(&G);
610                 free(G.dlist);
611                 free(G.saved_stats_dev);
612         }
613
614         return EXIT_SUCCESS;
615 }