mpstat.c 24 KB

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