mpstat: fix/improve handling of interrupt names
[oweals/busybox.git] / procps / mpstat.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Per-processor statistics, 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_MPSTAT(APPLET(mpstat, _BB_DIR_BIN, _BB_SUID_DROP))
11
12 //kbuild:lib-$(CONFIG_MPSTAT) += mpstat.o
13
14 //config:config MPSTAT
15 //config:       bool "mpstat"
16 //config:       default y
17 //config:       help
18 //config:         Per-processor statistics
19
20 #include "libbb.h"
21 #include <sys/utsname.h>        /* struct utsname */
22
23 //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
24 #define debug(fmt, ...) ((void)0)
25
26 /* Size of /proc/interrupts line, CPU data excluded */
27 #define INTERRUPTS_LINE    64
28 /* Maximum number of interrupts */
29 #define NR_IRQS            256
30 #define NR_IRQCPU_PREALLOC 3
31 #define MAX_IRQNAME_LEN    16
32 #define MAX_PF_NAME        512
33 /* sysstat 9.0.6 uses width 8, but newer code which also prints /proc/softirqs
34  * data needs more: "interrupts" in /proc/softirqs have longer names,
35  * most are up to 8 chars, one (BLOCK_IOPOLL) is even longer.
36  * We are printing headers in the " IRQNAME/s" form, experimentally
37  * anything smaller than 10 chars looks ugly for /proc/softirqs stats.
38  */
39 #define INTRATE_SCRWIDTH   10
40 #define INTRATE_SCRWIDTH_STR "10"
41
42 /* System files */
43 #define SYSFS_DEVCPU      "/sys/devices/system/cpu"
44 #define PROCFS_STAT       "/proc/stat"
45 #define PROCFS_INTERRUPTS "/proc/interrupts"
46 #define PROCFS_SOFTIRQS   "/proc/softirqs"
47 #define PROCFS_UPTIME     "/proc/uptime"
48
49
50 #if 1
51 typedef unsigned long long data_t;
52 typedef long long idata_t;
53 #define FMT_DATA "ll"
54 #define DATA_MAX ULLONG_MAX
55 #else
56 typedef unsigned long data_t;
57 typedef long idata_t;
58 #define FMT_DATA "l"
59 #define DATA_MAX ULONG_MAX
60 #endif
61
62
63 struct stats_irqcpu {
64         unsigned interrupt;
65         char irq_name[MAX_IRQNAME_LEN];
66 };
67
68 struct stats_cpu {
69         data_t cpu_user;
70         data_t cpu_nice;
71         data_t cpu_system;
72         data_t cpu_idle;
73         data_t cpu_iowait;
74         data_t cpu_steal;
75         data_t cpu_irq;
76         data_t cpu_softirq;
77         data_t cpu_guest;
78 };
79
80 struct stats_irq {
81         data_t irq_nr;
82 };
83
84
85 /* Globals. Sort by size and access frequency. */
86 struct globals {
87         int interval;
88         int count;
89         unsigned cpu_nr;                /* Number of CPUs */
90         unsigned irqcpu_nr;             /* Number of interrupts per CPU */
91         unsigned softirqcpu_nr;         /* Number of soft interrupts per CPU */
92         unsigned options;
93         unsigned hz;
94         unsigned cpu_bitmap_len;
95         smallint p_option;
96         smallint header_done;
97         smallint avg_header_done;
98         unsigned char *cpu_bitmap;      /* Bit 0: global, bit 1: 1st proc... */
99         data_t global_uptime[3];
100         data_t per_cpu_uptime[3];
101         struct stats_cpu *st_cpu[3];
102         struct stats_irq *st_irq[3];
103         struct stats_irqcpu *st_irqcpu[3];
104         struct stats_irqcpu *st_softirqcpu[3];
105         struct tm timestamp[3];
106 };
107 #define G (*ptr_to_globals)
108 #define INIT_G() do { \
109         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
110 } while (0)
111
112 /* The selected interrupts statistics (bits in G.options) */
113 enum {
114         D_CPU      = 1 << 0,
115         D_IRQ_SUM  = 1 << 1,
116         D_IRQ_CPU  = 1 << 2,
117         D_SOFTIRQS = 1 << 3,
118 };
119
120
121 /* Does str start with "cpu"? */
122 static int starts_with_cpu(const char *str)
123 {
124         return !((str[0] - 'c') | (str[1] - 'p') | (str[2] - 'u'));
125 }
126
127 /* Is option on? */
128 static ALWAYS_INLINE int display_opt(int opt)
129 {
130         return (opt & G.options);
131 }
132
133 #if DATA_MAX > 0xffffffff
134 /*
135  * Handle overflow conditions properly for counters which can have
136  * less bits than data_t, depending on the kernel version.
137  */
138 /* Surprisingly, on 32bit inlining is a size win */
139 static ALWAYS_INLINE data_t overflow_safe_sub(data_t prev, data_t curr)
140 {
141         data_t v = curr - prev;
142
143         if ((idata_t)v < 0     /* curr < prev - counter overflow? */
144          && prev <= 0xffffffff /* kernel uses 32bit value for the counter? */
145         ) {
146                 /* Add 33th bit set to 1 to curr, compensating for the overflow */
147                 /* double shift defeats "warning: left shift count >= width of type" */
148                 v += ((data_t)1 << 16) << 16;
149         }
150         return v;
151 }
152 #else
153 static ALWAYS_INLINE data_t overflow_safe_sub(data_t prev, data_t curr)
154 {
155         return curr - prev;
156 }
157 #endif
158
159 static double percent_value(data_t prev, data_t curr, data_t itv)
160 {
161         return ((double)overflow_safe_sub(prev, curr)) / itv * 100;
162 }
163
164 static double hz_value(data_t prev, data_t curr, data_t itv)
165 {
166         return ((double)overflow_safe_sub(prev, curr)) / itv * G.hz;
167 }
168
169 static ALWAYS_INLINE data_t jiffies_diff(data_t old, data_t new)
170 {
171         data_t diff = new - old;
172         return (diff == 0) ? 1 : diff;
173 }
174
175 static int is_cpu_in_bitmap(unsigned cpu)
176 {
177         return G.cpu_bitmap[cpu >> 3] & (1 << (cpu & 7));
178 }
179
180 static void write_irqcpu_stats(struct stats_irqcpu *per_cpu_stats[],
181                 int total_irqs,
182                 data_t itv,
183                 int prev, int current,
184                 const char *prev_str, const char *current_str)
185 {
186         int j;
187         int offset, cpu;
188         struct stats_irqcpu *p0, *q0;
189
190         /* Check if number of IRQs has changed */
191         if (G.interval != 0) {
192                 for (j = 0; j <= total_irqs; j++) {
193                         p0 = &per_cpu_stats[current][j];
194                         if (p0->irq_name[0] != '\0') {
195                                 q0 = &per_cpu_stats[prev][j];
196                                 if (strcmp(p0->irq_name, q0->irq_name) != 0) {
197                                         /* Strings are different */
198                                         break;
199                                 }
200                         }
201                 }
202         }
203
204         /* Print header */
205         printf("\n%-11s  CPU", prev_str);
206         {
207                 /* A bit complex code to "buy back" space if one header is too wide.
208                  * Here's how it looks like. BLOCK_IOPOLL eating too much,
209                  * and latter headers use smaller width to compensate:
210                  * ...BLOCK/s BLOCK_IOPOLL/s TASKLET/s SCHED/s HRTIMER/s  RCU/s
211                  * ...   2.32      0.00      0.01     17.58      0.14    141.96
212                  */
213                 int expected_len = 0;
214                 int printed_len = 0;
215                 for (j = 0; j < total_irqs; j++) {
216                         p0 = &per_cpu_stats[current][j];
217                         if (p0->irq_name[0] != '\0') {
218                                 int n = (INTRATE_SCRWIDTH-3) - (printed_len - expected_len);
219                                 printed_len += printf(" %*s/s", n > 0 ? n : 0, skip_whitespace(p0->irq_name));
220                                 expected_len += INTRATE_SCRWIDTH;
221                         }
222                 }
223         }
224         bb_putchar('\n');
225
226         for (cpu = 1; cpu <= G.cpu_nr; cpu++) {
227                 /* Check if we want stats about this CPU */
228                 if (!is_cpu_in_bitmap(cpu) && G.p_option) {
229                         continue;
230                 }
231
232                 printf("%-11s %4u", current_str, cpu - 1);
233
234                 for (j = 0; j < total_irqs; j++) {
235                         /* IRQ field set only for proc 0 */
236                         p0 = &per_cpu_stats[current][j];
237
238                         /*
239                          * An empty string for irq name means that
240                          * interrupt is no longer used.
241                          */
242                         if (p0->irq_name[0] != '\0') {
243                                 offset = j;
244                                 q0 = &per_cpu_stats[prev][offset];
245
246                                 /*
247                                  * If we want stats for the time since boot
248                                  * we have p0->irq != q0->irq.
249                                  */
250                                 if (strcmp(p0->irq_name, q0->irq_name) != 0
251                                  && G.interval != 0
252                                 ) {
253                                         if (j) {
254                                                 offset = j - 1;
255                                                 q0 = &per_cpu_stats[prev][offset];
256                                         }
257                                         if (strcmp(p0->irq_name, q0->irq_name) != 0
258                                          && (j + 1 < total_irqs)
259                                         ) {
260                                                 offset = j + 1;
261                                                 q0 = &per_cpu_stats[prev][offset];
262                                         }
263                                 }
264
265                                 if (strcmp(p0->irq_name, q0->irq_name) == 0
266                                  || G.interval == 0
267                                 ) {
268                                         struct stats_irqcpu *p, *q;
269                                         p = &per_cpu_stats[current][(cpu - 1) * total_irqs + j];
270                                         q = &per_cpu_stats[prev][(cpu - 1) * total_irqs + offset];
271                                         printf("%"INTRATE_SCRWIDTH_STR".2f",
272                                                 (double)(p->interrupt - q->interrupt) / itv * G.hz);
273                                 } else {
274                                         printf("        N/A");
275                                 }
276                         }
277                 }
278                 bb_putchar('\n');
279         }
280 }
281
282 static data_t get_per_cpu_interval(const struct stats_cpu *scc,
283                 const struct stats_cpu *scp)
284 {
285         return ((scc->cpu_user + scc->cpu_nice +
286                  scc->cpu_system + scc->cpu_iowait +
287                  scc->cpu_idle + scc->cpu_steal +
288                  scc->cpu_irq + scc->cpu_softirq) -
289                 (scp->cpu_user + scp->cpu_nice +
290                  scp->cpu_system + scp->cpu_iowait +
291                  scp->cpu_idle + scp->cpu_steal +
292                  scp->cpu_irq + scp->cpu_softirq));
293 }
294
295 static void print_stats_cpu_struct(const struct stats_cpu *p,
296                 const struct stats_cpu *c,
297                 data_t itv)
298 {
299         printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
300                 percent_value(p->cpu_user - p->cpu_guest,
301                 /**/                          c->cpu_user - c->cpu_guest, itv),
302                 percent_value(p->cpu_nice   , c->cpu_nice   , itv),
303                 percent_value(p->cpu_system , c->cpu_system , itv),
304                 percent_value(p->cpu_iowait , c->cpu_iowait , itv),
305                 percent_value(p->cpu_irq    , c->cpu_irq    , itv),
306                 percent_value(p->cpu_softirq, c->cpu_softirq, itv),
307                 percent_value(p->cpu_steal  , c->cpu_steal  , itv),
308                 percent_value(p->cpu_guest  , c->cpu_guest  , itv),
309                 percent_value(p->cpu_idle   , c->cpu_idle   , itv)
310         );
311 }
312
313 static void write_stats_core(int prev, int current,
314                 const char *prev_str, const char *current_str)
315 {
316         struct stats_cpu *scc, *scp;
317         data_t itv, global_itv;
318         int cpu;
319
320         /* Compute time interval */
321         itv = global_itv = jiffies_diff(G.global_uptime[prev], G.global_uptime[current]);
322
323         /* Reduce interval to one CPU */
324         if (G.cpu_nr > 1)
325                 itv = jiffies_diff(G.per_cpu_uptime[prev], G.per_cpu_uptime[current]);
326
327         /* Print CPU stats */
328         if (display_opt(D_CPU)) {
329
330                 /* This is done exactly once */
331                 if (!G.header_done) {
332                         printf("\n%-11s  CPU    %%usr   %%nice    %%sys %%iowait    %%irq   %%soft  %%steal  %%guest   %%idle\n",
333                                 prev_str
334                         );
335                         G.header_done = 1;
336                 }
337
338                 for (cpu = 0; cpu <= G.cpu_nr; cpu++) {
339                         data_t per_cpu_itv;
340
341                         /* Print stats about this particular CPU? */
342                         if (!is_cpu_in_bitmap(cpu))
343                                 continue;
344
345                         scc = &G.st_cpu[current][cpu];
346                         scp = &G.st_cpu[prev][cpu];
347                         per_cpu_itv = global_itv;
348
349                         printf((cpu ? "%-11s %4u" : "%-11s  all"), current_str, cpu - 1);
350                         if (cpu) {
351                                 double idle;
352                                 /*
353                                  * If the CPU is offline, then it isn't in /proc/stat,
354                                  * so all values are 0.
355                                  * NB: Guest time is already included in user time.
356                                  */
357                                 if ((scc->cpu_user | scc->cpu_nice | scc->cpu_system |
358                                      scc->cpu_iowait | scc->cpu_idle | scc->cpu_steal |
359                                      scc->cpu_irq | scc->cpu_softirq) == 0
360                                 ) {
361                                         /*
362                                          * Set current struct fields to values from prev.
363                                          * iteration. Then their values won't jump from
364                                          * zero, when the CPU comes back online.
365                                          */
366                                         *scc = *scp;
367                                         idle = 0.0;
368                                         goto print_zeros;
369                                 }
370                                 /* Compute interval again for current proc */
371                                 per_cpu_itv = get_per_cpu_interval(scc, scp);
372                                 if (per_cpu_itv == 0) {
373                                         /*
374                                          * If the CPU is tickless then there is no change in CPU values
375                                          * but the sum of values is not zero.
376                                          */
377                                         idle = 100.0;
378  print_zeros:
379                                         printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
380                                                 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, idle);
381                                         continue;
382                                 }
383                         }
384                         print_stats_cpu_struct(scp, scc, per_cpu_itv);
385                 }
386         }
387
388         /* Print total number of IRQs per CPU */
389         if (display_opt(D_IRQ_SUM)) {
390
391                 /* Print average header, this is done exactly once */
392                 if (!G.avg_header_done) {
393                         printf("\n%-11s  CPU    intr/s\n", prev_str);
394                         G.avg_header_done = 1;
395                 }
396
397                 for (cpu = 0; cpu <= G.cpu_nr; cpu++) {
398                         data_t per_cpu_itv;
399
400                         /* Print stats about this CPU? */
401                         if (!is_cpu_in_bitmap(cpu))
402                                 continue;
403
404                         per_cpu_itv = itv;
405                         printf((cpu ? "%-11s %4u" : "%-11s  all"), current_str, cpu - 1);
406                         if (cpu) {
407                                 scc = &G.st_cpu[current][cpu];
408                                 scp = &G.st_cpu[prev][cpu];
409                                 /* Compute interval again for current proc */
410                                 per_cpu_itv = get_per_cpu_interval(scc, scp);
411                                 if (per_cpu_itv == 0) {
412                                         printf(" %9.2f\n", 0.0);
413                                         continue;
414                                 }
415                         }
416                         printf(" %9.2f\n", hz_value(G.st_irq[prev][cpu].irq_nr, G.st_irq[current][cpu].irq_nr, per_cpu_itv));
417                 }
418         }
419
420         if (display_opt(D_IRQ_CPU)) {
421                 write_irqcpu_stats(G.st_irqcpu, G.irqcpu_nr,
422                                 itv,
423                                 prev, current,
424                                 prev_str, current_str
425                 );
426         }
427
428         if (display_opt(D_SOFTIRQS)) {
429                 write_irqcpu_stats(G.st_softirqcpu, G.softirqcpu_nr,
430                                 itv,
431                                 prev, current,
432                                 prev_str, current_str
433                 );
434         }
435 }
436
437 /*
438  * Print the statistics
439  */
440 static void write_stats(int current)
441 {
442         char prev_time[16];
443         char curr_time[16];
444
445         strftime(prev_time, sizeof(prev_time), "%X", &G.timestamp[!current]);
446         strftime(curr_time, sizeof(curr_time), "%X", &G.timestamp[current]);
447
448         write_stats_core(!current, current, prev_time, curr_time);
449 }
450
451 static void write_stats_avg(int current)
452 {
453         write_stats_core(2, current, "Average:", "Average:");
454 }
455
456 /*
457  * Read CPU statistics
458  */
459 static void get_cpu_statistics(struct stats_cpu *cpu, data_t *up, data_t *up0)
460 {
461         FILE *fp;
462         char buf[1024];
463
464         fp = xfopen_for_read(PROCFS_STAT);
465
466         while (fgets(buf, sizeof(buf), fp)) {
467                 data_t sum;
468                 unsigned cpu_number;
469                 struct stats_cpu *cp;
470
471                 if (!starts_with_cpu(buf))
472                         continue; /* not "cpu" */
473
474                 cp = cpu; /* for "cpu " case */
475                 if (buf[3] != ' ') {
476                         /* "cpuN " */
477                         if (G.cpu_nr == 0
478                          || sscanf(buf + 3, "%u ", &cpu_number) != 1
479                          || cpu_number >= G.cpu_nr
480                         ) {
481                                 continue;
482                         }
483                         cp = &cpu[cpu_number + 1];
484                 }
485
486                 /* Read the counters, save them */
487                 /* Not all fields have to be present */
488                 memset(cp, 0, sizeof(*cp));
489                 sscanf(buf, "%*s"
490                         " %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u"
491                         " %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u"
492                         " %"FMT_DATA"u %"FMT_DATA"u %"FMT_DATA"u",
493                         &cp->cpu_user, &cp->cpu_nice, &cp->cpu_system,
494                         &cp->cpu_idle, &cp->cpu_iowait, &cp->cpu_irq,
495                         &cp->cpu_softirq, &cp->cpu_steal, &cp->cpu_guest
496                 );
497                 /*
498                  * Compute uptime in jiffies (1/HZ), it'll be the sum of
499                  * individual CPU's uptimes.
500                  * NB: We have to omit cpu_guest, because cpu_user includes it.
501                  */
502                 sum = cp->cpu_user + cp->cpu_nice + cp->cpu_system +
503                         cp->cpu_idle + cp->cpu_iowait + cp->cpu_irq +
504                         cp->cpu_softirq + cp->cpu_steal;
505
506                 if (buf[3] == ' ') {
507                         /* "cpu " */
508                         *up = sum;
509                 } else {
510                         /* "cpuN " */
511                         if (cpu_number == 0 && *up0 != 0) {
512                                 /* Compute uptime of single CPU */
513                                 *up0 = sum;
514                         }
515                 }
516         }
517         fclose(fp);
518 }
519
520 /*
521  * Read IRQs from /proc/stat
522  */
523 static void get_irqs_from_stat(struct stats_irq *irq)
524 {
525         FILE *fp;
526         char buf[1024];
527
528         fp = fopen_for_read(PROCFS_STAT);
529         if (!fp)
530                 return;
531
532         while (fgets(buf, sizeof(buf), fp)) {
533                 if (strncmp(buf, "intr ", 5) == 0)
534                         /* Read total number of IRQs since system boot */
535                         sscanf(buf + 5, "%"FMT_DATA"u", &irq->irq_nr);
536         }
537
538         fclose(fp);
539 }
540
541 /*
542  * Read stats from /proc/interrupts or /proc/softirqs
543  */
544 static void get_irqs_from_interrupts(const char *fname,
545                 struct stats_irqcpu *per_cpu_stats[],
546                 int irqs_per_cpu, int current)
547 {
548         FILE *fp;
549         struct stats_irq *irq_i;
550         struct stats_irqcpu *ic;
551         char *buf;
552         unsigned buflen;
553         unsigned cpu;
554         unsigned irq;
555         int cpu_index[G.cpu_nr];
556         int iindex;
557         int len, digit;
558
559         for (cpu = 1; cpu <= G.cpu_nr; cpu++) {
560                 irq_i = &G.st_irq[current][cpu];
561                 irq_i->irq_nr = 0;
562         }
563
564         fp = fopen_for_read(fname);
565         if (!fp)
566                 return;
567
568         buflen = INTERRUPTS_LINE + 16 * G.cpu_nr;
569         buf = xmalloc(buflen);
570
571         /* Parse header and determine, which CPUs are online */
572         iindex = 0;
573         while (fgets(buf, buflen, fp)) {
574                 char *cp, *next;
575                 next = buf;
576                 while ((cp = strstr(next, "CPU")) != NULL
577                  && iindex < G.cpu_nr
578                 ) {
579                         cpu = strtoul(cp + 3, &next, 10);
580                         cpu_index[iindex++] = cpu;
581                 }
582                 if (iindex) /* We found header */
583                         break;
584         }
585
586         irq = 0;
587         while (fgets(buf, buflen, fp)
588          && irq < irqs_per_cpu
589         ) {
590                 char *cp;
591                 /* Skip over "<irq>:" */
592                 cp = strchr(buf, ':');
593                 if (!cp)
594                         continue;
595
596                 ic = &per_cpu_stats[current][irq];
597                 len = cp - buf;
598                 if (len >= sizeof(ic->irq_name)) {
599                         len = sizeof(ic->irq_name) - 1;
600                 }
601                 safe_strncpy(ic->irq_name, buf, len + 1);
602                 //bb_error_msg("%s: irq%d:'%s' buf:'%s'", fname, irq, ic->irq_name, buf);
603                 digit = isdigit(buf[len - 1]);
604                 cp++;
605
606                 for (cpu = 0; cpu < iindex; cpu++) {
607                         char *next;
608                         ic = &per_cpu_stats[current][cpu_index[cpu] * irqs_per_cpu + irq];
609                         irq_i = &G.st_irq[current][cpu_index[cpu] + 1];
610                         ic->interrupt = strtoul(cp, &next, 10);
611                         if (digit) {
612                                 /* Do not count non-numerical IRQs */
613                                 irq_i->irq_nr += ic->interrupt;
614                         }
615                         cp = next;
616                 }
617                 irq++;
618         }
619         fclose(fp);
620         free(buf);
621
622         while (irq < irqs_per_cpu) {
623                 /* Number of interrupts per CPU has changed */
624                 ic = &per_cpu_stats[current][irq];
625                 ic->irq_name[0] = '\0'; /* False interrupt */
626                 irq++;
627         }
628 }
629
630 static void get_uptime(data_t *uptime)
631 {
632         FILE *fp;
633         char buf[sizeof(long)*3 * 2 + 4]; /* enough for long.long */
634         unsigned long uptime_sec, decimal;
635
636         fp = fopen_for_read(PROCFS_UPTIME);
637         if (!fp)
638                 return;
639         if (fgets(buf, sizeof(buf), fp)) {
640                 if (sscanf(buf, "%lu.%lu", &uptime_sec, &decimal) == 2) {
641                         *uptime = (data_t)uptime_sec * G.hz + decimal * G.hz / 100;
642                 }
643         }
644
645         fclose(fp);
646 }
647
648 static void get_localtime(struct tm *tm)
649 {
650         time_t timer;
651         time(&timer);
652         localtime_r(&timer, tm);
653 }
654
655 static void alarm_handler(int sig UNUSED_PARAM)
656 {
657         signal(SIGALRM, alarm_handler);
658         alarm(G.interval);
659 }
660
661 static void main_loop(void)
662 {
663         unsigned current;
664         unsigned cpus;
665
666         /* Read the stats */
667         if (G.cpu_nr > 1) {
668                 G.per_cpu_uptime[0] = 0;
669                 get_uptime(&G.per_cpu_uptime[0]);
670         }
671
672         get_cpu_statistics(G.st_cpu[0], &G.global_uptime[0], &G.per_cpu_uptime[0]);
673
674         if (display_opt(D_IRQ_SUM))
675                 get_irqs_from_stat(G.st_irq[0]);
676
677         if (display_opt(D_IRQ_SUM | D_IRQ_CPU))
678                 get_irqs_from_interrupts(PROCFS_INTERRUPTS, G.st_irqcpu,
679                                         G.irqcpu_nr, 0);
680
681         if (display_opt(D_SOFTIRQS))
682                 get_irqs_from_interrupts(PROCFS_SOFTIRQS, G.st_softirqcpu,
683                                         G.softirqcpu_nr, 0);
684
685         if (G.interval == 0) {
686                 /* Display since boot time */
687                 cpus = G.cpu_nr + 1;
688                 G.timestamp[1] = G.timestamp[0];
689                 memset(G.st_cpu[1], 0, sizeof(G.st_cpu[1][0]) * cpus);
690                 memset(G.st_irq[1], 0, sizeof(G.st_irq[1][0]) * cpus);
691                 memset(G.st_irqcpu[1], 0, sizeof(G.st_irqcpu[1][0]) * cpus * G.irqcpu_nr);
692                 memset(G.st_softirqcpu[1], 0, sizeof(G.st_softirqcpu[1][0]) * cpus * G.softirqcpu_nr);
693
694                 write_stats(0);
695
696                 /* And we're done */
697                 return;
698         }
699
700         /* Set a handler for SIGALRM */
701         alarm_handler(0);
702
703         /* Save the stats we already have. We need them to compute the average */
704         G.timestamp[2] = G.timestamp[0];
705         G.global_uptime[2] = G.global_uptime[0];
706         G.per_cpu_uptime[2] = G.per_cpu_uptime[0];
707         cpus = G.cpu_nr + 1;
708         memcpy(G.st_cpu[2], G.st_cpu[0], sizeof(G.st_cpu[0][0]) * cpus);
709         memcpy(G.st_irq[2], G.st_irq[0], sizeof(G.st_irq[0][0]) * cpus);
710         memcpy(G.st_irqcpu[2], G.st_irqcpu[0], sizeof(G.st_irqcpu[0][0]) * cpus * G.irqcpu_nr);
711         if (display_opt(D_SOFTIRQS)) {
712                 memcpy(G.st_softirqcpu[2], G.st_softirqcpu[0],
713                         sizeof(G.st_softirqcpu[0][0]) * cpus * G.softirqcpu_nr);
714         }
715
716         current = 1;
717         while (1) {
718                 /* Suspend until a signal is received */
719                 pause();
720
721                 /* Set structures to 0 to distinguish off/online CPUs */
722                 memset(&G.st_cpu[current][/*cpu:*/ 1], 0, sizeof(G.st_cpu[0][0]) * G.cpu_nr);
723
724                 get_localtime(&G.timestamp[current]);
725
726                 /* Read stats */
727                 if (G.cpu_nr > 1) {
728                         G.per_cpu_uptime[current] = 0;
729                         get_uptime(&G.per_cpu_uptime[current]);
730                 }
731                 get_cpu_statistics(G.st_cpu[current], &G.global_uptime[current], &G.per_cpu_uptime[current]);
732
733                 if (display_opt(D_IRQ_SUM))
734                         get_irqs_from_stat(G.st_irq[current]);
735
736                 if (display_opt(D_IRQ_SUM | D_IRQ_CPU))
737                         get_irqs_from_interrupts(PROCFS_INTERRUPTS, G.st_irqcpu,
738                                         G.irqcpu_nr, current);
739
740                 if (display_opt(D_SOFTIRQS))
741                         get_irqs_from_interrupts(PROCFS_SOFTIRQS,
742                                         G.st_softirqcpu,
743                                         G.softirqcpu_nr, current);
744
745                 write_stats(current);
746
747                 if (G.count > 0) {
748                         if (--G.count == 0)
749                                 break;
750                 }
751
752                 current ^= 1;
753         }
754
755         /* Print average statistics */
756         write_stats_avg(current);
757 }
758
759 /* Initialization */
760
761 /* Get number of clock ticks per sec */
762 static ALWAYS_INLINE unsigned get_hz(void)
763 {
764         return sysconf(_SC_CLK_TCK);
765 }
766
767 static void alloc_struct(int cpus)
768 {
769         int i;
770         for (i = 0; i < 3; i++) {
771                 G.st_cpu[i] = xzalloc(sizeof(G.st_cpu[i][0]) * cpus);
772                 G.st_irq[i] = xzalloc(sizeof(G.st_irq[i][0]) * cpus);
773                 G.st_irqcpu[i] = xzalloc(sizeof(G.st_irqcpu[i][0]) * cpus * G.irqcpu_nr);
774                 G.st_softirqcpu[i] = xzalloc(sizeof(G.st_softirqcpu[i][0]) * cpus * G.softirqcpu_nr);
775         }
776         G.cpu_bitmap_len = (cpus >> 3) + 1;
777         G.cpu_bitmap = xzalloc(G.cpu_bitmap_len);
778 }
779
780 static void print_header(struct tm *t)
781 {
782         char cur_date[16];
783         struct utsname uts;
784
785         /* Get system name, release number and hostname */
786         uname(&uts);
787
788         strftime(cur_date, sizeof(cur_date), "%x", t);
789
790         printf("%s %s (%s)\t%s\t_%s_\t(%u CPU)\n",
791                 uts.sysname, uts.release, uts.nodename, cur_date, uts.machine, G.cpu_nr);
792 }
793
794 /*
795  * Get number of processors in /sys
796  */
797 static int get_sys_cpu_nr(void)
798 {
799         DIR *dir;
800         struct dirent *d;
801         struct stat buf;
802         char line[MAX_PF_NAME];
803         int proc_nr = 0;
804
805         dir = opendir(SYSFS_DEVCPU);
806         if (!dir)
807                 return 0;       /* /sys not mounted */
808
809         /* Get current file entry */
810         while ((d = readdir(dir)) != NULL) {
811                 if (starts_with_cpu(d->d_name) && isdigit(d->d_name[3])) {
812                         snprintf(line, MAX_PF_NAME, "%s/%s", SYSFS_DEVCPU,
813                                  d->d_name);
814                         line[MAX_PF_NAME - 1] = '\0';
815                         /* Get information about file */
816                         if (stat(line, &buf) < 0)
817                                 continue;
818                         /* If found 'cpuN', we have one more processor */
819                         if (S_ISDIR(buf.st_mode))
820                                 proc_nr++;
821                 }
822         }
823
824         closedir(dir);
825         return proc_nr;
826 }
827
828 /*
829  * Get number of processors in /proc/stat
830  * Return value '0' means one CPU and non SMP kernel.
831  * Otherwise N means N processor(s) and SMP kernel.
832  */
833 static int get_proc_cpu_nr(void)
834 {
835         FILE *fp;
836         char line[256];
837         int proc_nr = -1;
838
839         fp = xfopen_for_read(PROCFS_STAT);
840         while (fgets(line, sizeof(line), fp)) {
841                 if (!starts_with_cpu(line)) {
842                         if (proc_nr >= 0)
843                                 break; /* we are past "cpuN..." lines */
844                         continue;
845                 }
846                 if (line[3] != ' ') { /* "cpuN" */
847                         int num_proc;
848                         if (sscanf(line + 3, "%u", &num_proc) == 1
849                          && num_proc > proc_nr
850                         ) {
851                                 proc_nr = num_proc;
852                         }
853                 }
854         }
855
856         fclose(fp);
857         return proc_nr + 1;
858 }
859
860 static int get_cpu_nr(void)
861 {
862         int n;
863
864         /* Try to use /sys, if possible */
865         n = get_sys_cpu_nr();
866         if (n == 0)
867                 /* Otherwise use /proc/stat */
868                 n = get_proc_cpu_nr();
869
870         return n;
871 }
872
873 /*
874  * Get number of interrupts available per processor
875  */
876 static int get_irqcpu_nr(const char *f, int max_irqs)
877 {
878         FILE *fp;
879         char *line;
880         unsigned linelen;
881         unsigned irq;
882
883         fp = fopen_for_read(f);
884         if (!fp)                /* No interrupts file */
885                 return 0;
886
887         linelen = INTERRUPTS_LINE + 16 * G.cpu_nr;
888         line = xmalloc(linelen);
889
890         irq = 0;
891         while (fgets(line, linelen, fp)
892          && irq < max_irqs
893         ) {
894                 int p = strcspn(line, ":");
895                 if ((p > 0) && (p < 16))
896                         irq++;
897         }
898
899         fclose(fp);
900         free(line);
901
902         return irq;
903 }
904
905 //usage:#define mpstat_trivial_usage
906 //usage:       "[-A] [-I SUM|CPU|ALL|SCPU] [-u] [-P num|ALL] [INTERVAL [COUNT]]"
907 //usage:#define mpstat_full_usage "\n\n"
908 //usage:       "Per-processor statistics\n"
909 //usage:     "\nOptions:"
910 //usage:     "\n        -A                      Same as -I ALL -u -P ALL"
911 //usage:     "\n        -I SUM|CPU|ALL|SCPU     Report interrupt statistics"
912 //usage:     "\n        -P num|ALL              Processor to monitor"
913 //usage:     "\n        -u                      Report CPU utilization"
914
915 int mpstat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
916 int mpstat_main(int UNUSED_PARAM argc, char **argv)
917 {
918         char *opt_irq_fmt;
919         char *opt_set_cpu;
920         int i, opt;
921         enum {
922                 OPT_ALL    = 1 << 0,    /* -A */
923                 OPT_INTS   = 1 << 1,    /* -I */
924                 OPT_SETCPU = 1 << 2,    /* -P */
925                 OPT_UTIL   = 1 << 3,    /* -u */
926         };
927
928         /* Dont buffer data if redirected to a pipe */
929         setbuf(stdout, NULL);
930
931         INIT_G();
932
933         G.interval = -1;
934
935         /* Get number of processors */
936         G.cpu_nr = get_cpu_nr();
937
938         /* Get number of clock ticks per sec */
939         G.hz = get_hz();
940
941         /* Calculate number of interrupts per processor */
942         G.irqcpu_nr = get_irqcpu_nr(PROCFS_INTERRUPTS, NR_IRQS) + NR_IRQCPU_PREALLOC;
943
944         /* Calculate number of soft interrupts per processor */
945         G.softirqcpu_nr = get_irqcpu_nr(PROCFS_SOFTIRQS, NR_IRQS) + NR_IRQCPU_PREALLOC;
946
947         /* Allocate space for structures. + 1 for global structure. */
948         alloc_struct(G.cpu_nr + 1);
949
950         /* Parse and process arguments */
951         opt = getopt32(argv, "AI:P:u", &opt_irq_fmt, &opt_set_cpu);
952         argv += optind;
953
954         if (*argv) {
955                 /* Get interval */
956                 G.interval = xatoi_u(*argv);
957                 G.count = -1;
958                 argv++;
959                 if (*argv) {
960                         /* Get count value */
961                         if (G.interval == 0)
962                                 bb_show_usage();
963                         G.count = xatoi_u(*argv);
964                         //if (*++argv)
965                         //      bb_show_usage();
966                 }
967         }
968         if (G.interval < 0)
969                 G.interval = 0;
970
971         if (opt & OPT_ALL) {
972                 G.p_option = 1;
973                 G.options |= D_CPU + D_IRQ_SUM + D_IRQ_CPU + D_SOFTIRQS;
974                 /* Select every CPU */
975                 memset(G.cpu_bitmap, 0xff, G.cpu_bitmap_len);
976         }
977
978         if (opt & OPT_INTS) {
979                 static const char v[] = {
980                         D_IRQ_CPU, D_IRQ_SUM, D_SOFTIRQS,
981                         D_IRQ_SUM + D_IRQ_CPU + D_SOFTIRQS
982                 };
983                 i = index_in_strings("CPU\0SUM\0SCPU\0ALL\0", opt_irq_fmt);
984                 if (i == -1)
985                         bb_show_usage();
986                 G.options |= v[i];
987         }
988
989         if ((opt & OPT_UTIL) /* -u? */
990          || G.options == 0  /* nothing? (use default then) */
991         ) {
992                 G.options |= D_CPU;
993         }
994
995         if (opt & OPT_SETCPU) {
996                 char *t;
997                 G.p_option = 1;
998
999                 for (t = strtok(opt_set_cpu, ","); t; t = strtok(NULL, ",")) {
1000                         if (strcmp(t, "ALL") == 0) {
1001                                 /* Select every CPU */
1002                                 memset(G.cpu_bitmap, 0xff, G.cpu_bitmap_len);
1003                         } else {
1004                                 /* Get CPU number */
1005                                 unsigned n = xatoi_u(t);
1006                                 if (n >= G.cpu_nr)
1007                                         bb_error_msg_and_die("not that many processors");
1008                                 n++;
1009                                 G.cpu_bitmap[n >> 3] |= 1 << (n & 7);
1010                         }
1011                 }
1012         }
1013
1014         if (!G.p_option)
1015                 /* Display global stats */
1016                 G.cpu_bitmap[0] = 1;
1017
1018         /* Get time */
1019         get_localtime(&G.timestamp[0]);
1020
1021         /* Display header */
1022         print_header(&G.timestamp[0]);
1023
1024         /* The main loop */
1025         main_loop();
1026
1027         if (ENABLE_FEATURE_CLEAN_UP) {
1028                 /* Clean up */
1029                 for (i = 0; i < 3; i++) {
1030                         free(G.st_cpu[i]);
1031                         free(G.st_irq[i]);
1032                         free(G.st_irqcpu[i]);
1033                         free(G.st_softirqcpu[i]);
1034                 }
1035                 free(G.cpu_bitmap);
1036                 free(&G);
1037         }
1038
1039         return EXIT_SUCCESS;
1040 }