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