cpu plugin: add linux-specific "guest" states.
[collectd.git] / src / cpu.c
1 /**
2  * collectd - src/cpu.c
3  * Copyright (C) 2005-2014  Florian octo Forster
4  * Copyright (C) 2008       Oleg King
5  * Copyright (C) 2009       Simon Kuhnle
6  * Copyright (C) 2009       Manuel Sanmartin
7  * Copyright (C) 2013-2014  Pierre-Yves Ritschard
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU General Public License as published by the
11  * Free Software Foundation; only version 2 of the License is applicable.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
21  *
22  * Authors:
23  *   Florian octo Forster <octo at collectd.org>
24  *   Oleg King <king2 at kaluga.ru>
25  *   Simon Kuhnle <simon at blarzwurst.de>
26  *   Manuel Sanmartin
27  *   Pierre-Yves Ritschard <pyr at spootnik.org>
28  **/
29
30 #include "collectd.h"
31
32 #include "common.h"
33 #include "plugin.h"
34
35 #ifdef HAVE_MACH_KERN_RETURN_H
36 #include <mach/kern_return.h>
37 #endif
38 #ifdef HAVE_MACH_MACH_INIT_H
39 #include <mach/mach_init.h>
40 #endif
41 #ifdef HAVE_MACH_HOST_PRIV_H
42 #include <mach/host_priv.h>
43 #endif
44 #if HAVE_MACH_MACH_ERROR_H
45 #include <mach/mach_error.h>
46 #endif
47 #ifdef HAVE_MACH_PROCESSOR_INFO_H
48 #include <mach/processor_info.h>
49 #endif
50 #ifdef HAVE_MACH_PROCESSOR_H
51 #include <mach/processor.h>
52 #endif
53 #ifdef HAVE_MACH_VM_MAP_H
54 #include <mach/vm_map.h>
55 #endif
56
57 #ifdef HAVE_LIBKSTAT
58 #include <sys/sysinfo.h>
59 #endif /* HAVE_LIBKSTAT */
60
61 #if (defined(HAVE_SYSCTL) && HAVE_SYSCTL) ||                                   \
62     (defined(HAVE_SYSCTLBYNAME) && HAVE_SYSCTLBYNAME)
63 #ifdef HAVE_SYS_SYSCTL_H
64 #include <sys/sysctl.h>
65 #endif
66
67 #ifdef HAVE_SYS_DKSTAT_H
68 #include <sys/dkstat.h>
69 #endif
70
71 #if !defined(CP_USER) || !defined(CP_NICE) || !defined(CP_SYS) ||              \
72     !defined(CP_INTR) || !defined(CP_IDLE) || !defined(CPUSTATES)
73 #define CP_USER 0
74 #define CP_NICE 1
75 #define CP_SYS 2
76 #define CP_INTR 3
77 #define CP_IDLE 4
78 #define CPUSTATES 5
79 #endif
80 #endif /* HAVE_SYSCTL || HAVE_SYSCTLBYNAME */
81
82 #if HAVE_SYSCTL
83 #if defined(CTL_HW) && defined(HW_NCPU) && defined(CTL_KERN) &&                \
84     defined(KERN_CPTIME) && defined(CPUSTATES)
85 #define CAN_USE_SYSCTL 1
86 #else
87 #define CAN_USE_SYSCTL 0
88 #endif
89 #else
90 #define CAN_USE_SYSCTL 0
91 #endif
92
93 #define COLLECTD_CPU_STATE_USER 0
94 #define COLLECTD_CPU_STATE_SYSTEM 1
95 #define COLLECTD_CPU_STATE_WAIT 2
96 #define COLLECTD_CPU_STATE_NICE 3
97 #define COLLECTD_CPU_STATE_SWAP 4
98 #define COLLECTD_CPU_STATE_INTERRUPT 5
99 #define COLLECTD_CPU_STATE_SOFTIRQ 6
100 #define COLLECTD_CPU_STATE_STEAL 7
101 #define COLLECTD_CPU_STATE_GUEST 8
102 #define COLLECTD_CPU_STATE_GUEST_NICE 9
103 #define COLLECTD_CPU_STATE_IDLE 10
104 #define COLLECTD_CPU_STATE_ACTIVE 11 /* sum of (!idle) */
105 #define COLLECTD_CPU_STATE_MAX 12   /* #states */
106
107 #if HAVE_STATGRAB_H
108 #include <statgrab.h>
109 #endif
110
111 #ifdef HAVE_PERFSTAT
112 #include <libperfstat.h>
113 #include <sys/protosw.h>
114 #endif /* HAVE_PERFSTAT */
115
116 #if !PROCESSOR_CPU_LOAD_INFO && !KERNEL_LINUX && !HAVE_LIBKSTAT &&             \
117     !CAN_USE_SYSCTL && !HAVE_SYSCTLBYNAME && !HAVE_LIBSTATGRAB &&              \
118     !HAVE_PERFSTAT
119 #error "No applicable input method."
120 #endif
121
122 static const char *cpu_state_names[] = {"user", "system",    "wait",    "nice",
123                                         "swap", "interrupt", "softirq", "steal",
124                                         "guest", "guest_nice", "idle", "active"};
125
126 #ifdef PROCESSOR_CPU_LOAD_INFO
127 static mach_port_t port_host;
128 static processor_port_array_t cpu_list;
129 static mach_msg_type_number_t cpu_list_len;
130 /* #endif PROCESSOR_CPU_LOAD_INFO */
131
132 #elif defined(KERNEL_LINUX)
133 /* no variables needed */
134 /* #endif KERNEL_LINUX */
135
136 #elif defined(HAVE_LIBKSTAT)
137 /* colleague tells me that Sun doesn't sell systems with more than 100 or so
138  * CPUs.. */
139 #define MAX_NUMCPU 256
140 extern kstat_ctl_t *kc;
141 static kstat_t *ksp[MAX_NUMCPU];
142 static int numcpu;
143 /* #endif HAVE_LIBKSTAT */
144
145 #elif CAN_USE_SYSCTL
146 static int numcpu;
147 /* #endif CAN_USE_SYSCTL */
148
149 #elif defined(HAVE_SYSCTLBYNAME)
150 static int numcpu;
151 #ifdef HAVE_SYSCTL_KERN_CP_TIMES
152 static int maxcpu;
153 #endif /* HAVE_SYSCTL_KERN_CP_TIMES */
154 /* #endif HAVE_SYSCTLBYNAME */
155
156 #elif defined(HAVE_LIBSTATGRAB)
157 /* no variables needed */
158 /* #endif  HAVE_LIBSTATGRAB */
159
160 #elif defined(HAVE_PERFSTAT)
161 #define TOTAL_IDLE 0
162 #define TOTAL_USER 1
163 #define TOTAL_SYS 2
164 #define TOTAL_WAIT 3
165 #define TOTAL_STAT_NUM 4
166 static value_to_rate_state_t total_conv[TOTAL_STAT_NUM];
167 static perfstat_cpu_t *perfcpu;
168 static int numcpu;
169 static int pnumcpu;
170 #endif /* HAVE_PERFSTAT */
171
172 #define RATE_ADD(sum, val)                                                     \
173   do {                                                                         \
174     if (isnan(sum))                                                            \
175       (sum) = (val);                                                           \
176     else if (!isnan(val))                                                      \
177       (sum) += (val);                                                          \
178   } while (0)
179
180 struct cpu_state_s {
181   value_to_rate_state_t conv;
182   gauge_t rate;
183   _Bool has_value;
184 };
185 typedef struct cpu_state_s cpu_state_t;
186
187 static cpu_state_t *cpu_states = NULL;
188 static size_t cpu_states_num = 0; /* #cpu_states allocated */
189
190 /* Highest CPU number in the current iteration. Used by the dispatch logic to
191  * determine how many CPUs there were. Reset to 0 by cpu_reset(). */
192 static size_t global_cpu_num = 0;
193
194 static _Bool report_by_cpu = 1;
195 static _Bool report_by_state = 1;
196 static _Bool report_percent = 0;
197 static _Bool report_num_cpu = 0;
198
199 static const char *config_keys[] = {"ReportByCpu", "ReportByState",
200                                     "ReportNumCpu", "ValuesPercentage"};
201 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
202
203 static int cpu_config(char const *key, char const *value) /* {{{ */
204 {
205   if (strcasecmp(key, "ReportByCpu") == 0)
206     report_by_cpu = IS_TRUE(value) ? 1 : 0;
207   else if (strcasecmp(key, "ValuesPercentage") == 0)
208     report_percent = IS_TRUE(value) ? 1 : 0;
209   else if (strcasecmp(key, "ReportByState") == 0)
210     report_by_state = IS_TRUE(value) ? 1 : 0;
211   else if (strcasecmp(key, "ReportNumCpu") == 0)
212     report_num_cpu = IS_TRUE(value) ? 1 : 0;
213   else
214     return -1;
215
216   return 0;
217 } /* }}} int cpu_config */
218
219 static int init(void) {
220 #if PROCESSOR_CPU_LOAD_INFO
221   kern_return_t status;
222
223   port_host = mach_host_self();
224
225   status = host_processors(port_host, &cpu_list, &cpu_list_len);
226   if (status == KERN_INVALID_ARGUMENT) {
227     ERROR("cpu plugin: Don't have a privileged host control port. "
228           "The most common cause for this problem is "
229           "that collectd is running without root "
230           "privileges, which are required to read CPU "
231           "load information. "
232           "<https://collectd.org/bugs/22>");
233     cpu_list_len = 0;
234     return -1;
235   }
236   if (status != KERN_SUCCESS) {
237     ERROR("cpu plugin: host_processors() failed with status %d.", (int)status);
238     cpu_list_len = 0;
239     return -1;
240   }
241
242   INFO("cpu plugin: Found %i processor%s.", (int)cpu_list_len,
243        cpu_list_len == 1 ? "" : "s");
244 /* #endif PROCESSOR_CPU_LOAD_INFO */
245
246 #elif defined(HAVE_LIBKSTAT)
247   kstat_t *ksp_chain;
248
249   numcpu = 0;
250
251   if (kc == NULL)
252     return -1;
253
254   /* Solaris doesn't count linear.. *sigh* */
255   for (numcpu = 0, ksp_chain = kc->kc_chain;
256        (numcpu < MAX_NUMCPU) && (ksp_chain != NULL);
257        ksp_chain = ksp_chain->ks_next)
258     if (strncmp(ksp_chain->ks_module, "cpu_stat", 8) == 0)
259       ksp[numcpu++] = ksp_chain;
260 /* #endif HAVE_LIBKSTAT */
261
262 #elif CAN_USE_SYSCTL
263   size_t numcpu_size;
264   int mib[2] = {CTL_HW, HW_NCPU};
265   int status;
266
267   numcpu = 0;
268   numcpu_size = sizeof(numcpu);
269
270   status = sysctl(mib, STATIC_ARRAY_SIZE(mib), &numcpu, &numcpu_size, NULL, 0);
271   if (status == -1) {
272     char errbuf[1024];
273     WARNING("cpu plugin: sysctl: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
274     return -1;
275   }
276 /* #endif CAN_USE_SYSCTL */
277
278 #elif defined(HAVE_SYSCTLBYNAME)
279   size_t numcpu_size;
280
281   numcpu_size = sizeof(numcpu);
282
283   if (sysctlbyname("hw.ncpu", &numcpu, &numcpu_size, NULL, 0) < 0) {
284     char errbuf[1024];
285     WARNING("cpu plugin: sysctlbyname(hw.ncpu): %s",
286             sstrerror(errno, errbuf, sizeof(errbuf)));
287     return -1;
288   }
289
290 #ifdef HAVE_SYSCTL_KERN_CP_TIMES
291   numcpu_size = sizeof(maxcpu);
292
293   if (sysctlbyname("kern.smp.maxcpus", &maxcpu, &numcpu_size, NULL, 0) < 0) {
294     char errbuf[1024];
295     WARNING("cpu plugin: sysctlbyname(kern.smp.maxcpus): %s",
296             sstrerror(errno, errbuf, sizeof(errbuf)));
297     return -1;
298   }
299 #else
300   if (numcpu != 1)
301     NOTICE("cpu: Only one processor supported when using `sysctlbyname' (found "
302            "%i)",
303            numcpu);
304 #endif
305 /* #endif HAVE_SYSCTLBYNAME */
306
307 #elif defined(HAVE_LIBSTATGRAB)
308 /* nothing to initialize */
309 /* #endif HAVE_LIBSTATGRAB */
310
311 #elif defined(HAVE_PERFSTAT)
312 /* nothing to initialize */
313 #endif /* HAVE_PERFSTAT */
314
315   return 0;
316 } /* int init */
317
318 static void submit_value(int cpu_num, int cpu_state, const char *type,
319                          value_t value) {
320   value_list_t vl = VALUE_LIST_INIT;
321
322   vl.values = &value;
323   vl.values_len = 1;
324
325   sstrncpy(vl.plugin, "cpu", sizeof(vl.plugin));
326   sstrncpy(vl.type, type, sizeof(vl.type));
327   sstrncpy(vl.type_instance, cpu_state_names[cpu_state],
328            sizeof(vl.type_instance));
329
330   if (cpu_num >= 0) {
331     snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%i", cpu_num);
332   }
333   plugin_dispatch_values(&vl);
334 }
335
336 static void submit_percent(int cpu_num, int cpu_state, gauge_t value) {
337   /* This function is called for all known CPU states, but each read
338    * method will only report a subset. The remaining states are left as
339    * NAN and we ignore them here. */
340   if (isnan(value))
341     return;
342
343   submit_value(cpu_num, cpu_state, "percent", (value_t){.gauge = value});
344 }
345
346 static void submit_derive(int cpu_num, int cpu_state, derive_t value) {
347   submit_value(cpu_num, cpu_state, "cpu", (value_t){.derive = value});
348 }
349
350 /* Takes the zero-index number of a CPU and makes sure that the module-global
351  * cpu_states buffer is large enough. Returne ENOMEM on erorr. */
352 static int cpu_states_alloc(size_t cpu_num) /* {{{ */
353 {
354   cpu_state_t *tmp;
355   size_t sz;
356
357   sz = (((size_t)cpu_num) + 1) * COLLECTD_CPU_STATE_MAX;
358   assert(sz > 0);
359
360   /* We already have enough space. */
361   if (cpu_states_num >= sz)
362     return 0;
363
364   tmp = realloc(cpu_states, sz * sizeof(*cpu_states));
365   if (tmp == NULL) {
366     ERROR("cpu plugin: realloc failed.");
367     return ENOMEM;
368   }
369   cpu_states = tmp;
370   tmp = cpu_states + cpu_states_num;
371
372   memset(tmp, 0, (sz - cpu_states_num) * sizeof(*cpu_states));
373   cpu_states_num = sz;
374   return 0;
375 } /* }}} cpu_states_alloc */
376
377 static cpu_state_t *get_cpu_state(size_t cpu_num, size_t state) /* {{{ */
378 {
379   size_t index = ((cpu_num * COLLECTD_CPU_STATE_MAX) + state);
380
381   if (index >= cpu_states_num)
382     return NULL;
383
384   return &cpu_states[index];
385 } /* }}} cpu_state_t *get_cpu_state */
386
387 #if defined(HAVE_PERFSTAT) /* {{{ */
388 /* populate global aggregate cpu rate */
389 static int total_rate(gauge_t *sum_by_state, size_t state, derive_t d,
390                       value_to_rate_state_t *conv, cdtime_t now) {
391   gauge_t rate = NAN;
392   int status =
393       value_to_rate(&rate, (value_t){.derive = d}, DS_TYPE_DERIVE, now, conv);
394   if (status != 0)
395     return status;
396
397   sum_by_state[state] = rate;
398
399   if (state != COLLECTD_CPU_STATE_IDLE)
400     RATE_ADD(sum_by_state[COLLECTD_CPU_STATE_ACTIVE], sum_by_state[state]);
401   return 0;
402 }
403 #endif /* }}} HAVE_PERFSTAT */
404
405 /* Populates the per-CPU COLLECTD_CPU_STATE_ACTIVE rate and the global
406  * rate_by_state
407  * array. */
408 static void aggregate(gauge_t *sum_by_state) /* {{{ */
409 {
410   for (size_t state = 0; state < COLLECTD_CPU_STATE_MAX; state++)
411     sum_by_state[state] = NAN;
412
413   for (size_t cpu_num = 0; cpu_num < global_cpu_num; cpu_num++) {
414     cpu_state_t *this_cpu_states = get_cpu_state(cpu_num, 0);
415
416     this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate = NAN;
417
418     for (size_t state = 0; state < COLLECTD_CPU_STATE_ACTIVE; state++) {
419       if (!this_cpu_states[state].has_value)
420         continue;
421
422       RATE_ADD(sum_by_state[state], this_cpu_states[state].rate);
423       if (state != COLLECTD_CPU_STATE_IDLE)
424         RATE_ADD(this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate,
425                  this_cpu_states[state].rate);
426     }
427
428     if (!isnan(this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate))
429       this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].has_value = 1;
430
431     RATE_ADD(sum_by_state[COLLECTD_CPU_STATE_ACTIVE],
432              this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate);
433   }
434
435 #if defined(HAVE_PERFSTAT) /* {{{ */
436   cdtime_t now = cdtime();
437   perfstat_cpu_total_t cputotal = {0};
438
439   if (!perfstat_cpu_total(NULL, &cputotal, sizeof(cputotal), 1)) {
440     char errbuf[1024];
441     WARNING("cpu plugin: perfstat_cpu_total: %s",
442             sstrerror(errno, errbuf, sizeof(errbuf)));
443     return;
444   }
445
446   /* Reset COLLECTD_CPU_STATE_ACTIVE */
447   sum_by_state[COLLECTD_CPU_STATE_ACTIVE] = NAN;
448
449   /* Physical Processor Utilization */
450   total_rate(sum_by_state, COLLECTD_CPU_STATE_IDLE, (derive_t)cputotal.pidle,
451              &total_conv[TOTAL_IDLE], now);
452   total_rate(sum_by_state, COLLECTD_CPU_STATE_USER, (derive_t)cputotal.puser,
453              &total_conv[TOTAL_USER], now);
454   total_rate(sum_by_state, COLLECTD_CPU_STATE_SYSTEM, (derive_t)cputotal.psys,
455              &total_conv[TOTAL_SYS], now);
456   total_rate(sum_by_state, COLLECTD_CPU_STATE_WAIT, (derive_t)cputotal.pwait,
457              &total_conv[TOTAL_WAIT], now);
458 #endif /* }}} HAVE_PERFSTAT */
459 } /* }}} void aggregate */
460
461 /* Commits (dispatches) the values for one CPU or the global aggregation.
462  * cpu_num is the index of the CPU to be committed or -1 in case of the global
463  * aggregation. rates is a pointer to COLLECTD_CPU_STATE_MAX gauge_t values
464  * holding the
465  * current rate; each rate may be NAN. Calculates the percentage of each state
466  * and dispatches the metric. */
467 static void cpu_commit_one(int cpu_num, /* {{{ */
468                            gauge_t rates[static COLLECTD_CPU_STATE_MAX]) {
469   gauge_t sum;
470
471   sum = rates[COLLECTD_CPU_STATE_ACTIVE];
472   RATE_ADD(sum, rates[COLLECTD_CPU_STATE_IDLE]);
473
474   if (!report_by_state) {
475     gauge_t percent = 100.0 * rates[COLLECTD_CPU_STATE_ACTIVE] / sum;
476     submit_percent(cpu_num, COLLECTD_CPU_STATE_ACTIVE, percent);
477     return;
478   }
479
480   for (size_t state = 0; state < COLLECTD_CPU_STATE_ACTIVE; state++) {
481     gauge_t percent = 100.0 * rates[state] / sum;
482     submit_percent(cpu_num, state, percent);
483   }
484 } /* }}} void cpu_commit_one */
485
486 /* Commits the number of cores */
487 static void cpu_commit_num_cpu(gauge_t value) /* {{{ */
488 {
489   value_list_t vl = VALUE_LIST_INIT;
490
491   vl.values = &(value_t){.gauge = value};
492   vl.values_len = 1;
493
494   sstrncpy(vl.plugin, "cpu", sizeof(vl.plugin));
495   sstrncpy(vl.type, "count", sizeof(vl.type));
496
497   plugin_dispatch_values(&vl);
498 } /* }}} void cpu_commit_num_cpu */
499
500 /* Resets the internal aggregation. This is called by the read callback after
501  * each iteration / after each call to cpu_commit(). */
502 static void cpu_reset(void) /* {{{ */
503 {
504   for (size_t i = 0; i < cpu_states_num; i++)
505     cpu_states[i].has_value = 0;
506
507   global_cpu_num = 0;
508 } /* }}} void cpu_reset */
509
510 /* Legacy behavior: Dispatches the raw derive values without any aggregation. */
511 static void cpu_commit_without_aggregation(void) /* {{{ */
512 {
513   for (int state = 0; state < COLLECTD_CPU_STATE_ACTIVE; state++) {
514     for (size_t cpu_num = 0; cpu_num < global_cpu_num; cpu_num++) {
515       cpu_state_t *s = get_cpu_state(cpu_num, state);
516
517       if (!s->has_value)
518         continue;
519
520       submit_derive((int)cpu_num, (int)state, s->conv.last_value.derive);
521     }
522   }
523 } /* }}} void cpu_commit_without_aggregation */
524
525 /* Aggregates the internal state and dispatches the metrics. */
526 static void cpu_commit(void) /* {{{ */
527 {
528   gauge_t global_rates[COLLECTD_CPU_STATE_MAX] = {
529       NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN /* Batman! */
530   };
531
532   if (report_num_cpu)
533     cpu_commit_num_cpu((gauge_t)global_cpu_num);
534
535   if (report_by_state && report_by_cpu && !report_percent) {
536     cpu_commit_without_aggregation();
537     return;
538   }
539
540   aggregate(global_rates);
541
542   if (!report_by_cpu) {
543     cpu_commit_one(-1, global_rates);
544     return;
545   }
546
547   for (size_t cpu_num = 0; cpu_num < global_cpu_num; cpu_num++) {
548     cpu_state_t *this_cpu_states = get_cpu_state(cpu_num, 0);
549     gauge_t local_rates[COLLECTD_CPU_STATE_MAX] = {NAN, NAN, NAN, NAN, NAN,
550                                                    NAN, NAN, NAN, NAN, NAN,
551                                                    NAN, NAN };
552
553     for (size_t state = 0; state < COLLECTD_CPU_STATE_MAX; state++)
554       if (this_cpu_states[state].has_value)
555         local_rates[state] = this_cpu_states[state].rate;
556
557     cpu_commit_one((int)cpu_num, local_rates);
558   }
559 } /* }}} void cpu_commit */
560
561 /* Adds a derive value to the internal state. This should be used by each read
562  * function for each state. At the end of the iteration, the read function
563  * should call cpu_commit(). */
564 static int cpu_stage(size_t cpu_num, size_t state, derive_t d,
565                      cdtime_t now) /* {{{ */
566 {
567   int status;
568   cpu_state_t *s;
569   gauge_t rate = NAN;
570   value_t val = {.derive = d};
571
572   if (state >= COLLECTD_CPU_STATE_ACTIVE)
573     return EINVAL;
574
575   status = cpu_states_alloc(cpu_num);
576   if (status != 0)
577     return status;
578
579   if (global_cpu_num <= cpu_num)
580     global_cpu_num = cpu_num + 1;
581
582   s = get_cpu_state(cpu_num, state);
583
584   status = value_to_rate(&rate, val, DS_TYPE_DERIVE, now, &s->conv);
585   if (status != 0)
586     return status;
587
588   s->rate = rate;
589   s->has_value = 1;
590   return 0;
591 } /* }}} int cpu_stage */
592
593 static int cpu_read(void) {
594   cdtime_t now = cdtime();
595
596 #if PROCESSOR_CPU_LOAD_INFO /* {{{ */
597   kern_return_t status;
598
599   processor_cpu_load_info_data_t cpu_info;
600   mach_msg_type_number_t cpu_info_len;
601
602   host_t cpu_host;
603
604   for (mach_msg_type_number_t cpu = 0; cpu < cpu_list_len; cpu++) {
605     cpu_host = 0;
606     cpu_info_len = PROCESSOR_BASIC_INFO_COUNT;
607
608     status = processor_info(cpu_list[cpu], PROCESSOR_CPU_LOAD_INFO, &cpu_host,
609                             (processor_info_t)&cpu_info, &cpu_info_len);
610     if (status != KERN_SUCCESS) {
611       ERROR("cpu plugin: processor_info (PROCESSOR_CPU_LOAD_INFO) failed: %s",
612             mach_error_string(status));
613       continue;
614     }
615
616     if (cpu_info_len < CPU_STATE_MAX) {
617       ERROR("cpu plugin: processor_info returned only %i elements..",
618             cpu_info_len);
619       continue;
620     }
621
622     cpu_stage(cpu, COLLECTD_CPU_STATE_USER,
623               (derive_t)cpu_info.cpu_ticks[CPU_STATE_USER], now);
624     cpu_stage(cpu, COLLECTD_CPU_STATE_NICE,
625               (derive_t)cpu_info.cpu_ticks[CPU_STATE_NICE], now);
626     cpu_stage(cpu, COLLECTD_CPU_STATE_SYSTEM,
627               (derive_t)cpu_info.cpu_ticks[CPU_STATE_SYSTEM], now);
628     cpu_stage(cpu, COLLECTD_CPU_STATE_IDLE,
629               (derive_t)cpu_info.cpu_ticks[CPU_STATE_IDLE], now);
630   }
631 /* }}} #endif PROCESSOR_CPU_LOAD_INFO */
632
633 #elif defined(KERNEL_LINUX) /* {{{ */
634   int cpu;
635   FILE *fh;
636   char buf[1024];
637
638   char *fields[11];
639   int numfields;
640
641   if ((fh = fopen("/proc/stat", "r")) == NULL) {
642     char errbuf[1024];
643     ERROR("cpu plugin: fopen (/proc/stat) failed: %s",
644           sstrerror(errno, errbuf, sizeof(errbuf)));
645     return -1;
646   }
647
648   while (fgets(buf, 1024, fh) != NULL) {
649     if (strncmp(buf, "cpu", 3))
650       continue;
651     if ((buf[3] < '0') || (buf[3] > '9'))
652       continue;
653
654     numfields = strsplit(buf, fields, STATIC_ARRAY_SIZE(fields));
655     if (numfields < 5)
656       continue;
657
658     cpu = atoi(fields[0] + 3);
659
660     cpu_stage(cpu, COLLECTD_CPU_STATE_USER, (derive_t)atoll(fields[1]), now);
661     cpu_stage(cpu, COLLECTD_CPU_STATE_NICE, (derive_t)atoll(fields[2]), now);
662     cpu_stage(cpu, COLLECTD_CPU_STATE_SYSTEM, (derive_t)atoll(fields[3]), now);
663     cpu_stage(cpu, COLLECTD_CPU_STATE_IDLE, (derive_t)atoll(fields[4]), now);
664
665     if (numfields >= 8) {
666       cpu_stage(cpu, COLLECTD_CPU_STATE_WAIT, (derive_t)atoll(fields[5]), now);
667       cpu_stage(cpu, COLLECTD_CPU_STATE_INTERRUPT, (derive_t)atoll(fields[6]),
668                 now);
669       cpu_stage(cpu, COLLECTD_CPU_STATE_SOFTIRQ, (derive_t)atoll(fields[7]),
670                 now);
671
672       if (numfields >= 9) {
673         cpu_stage(cpu, COLLECTD_CPU_STATE_STEAL, (derive_t)atoll(fields[8]),
674                   now);
675
676         if (numfields >= 10) {
677           cpu_stage(cpu, COLLECTD_CPU_STATE_GUEST, (derive_t)atoll(fields[9]),
678                     now);
679
680           if (numfields >= 11) {
681             cpu_stage(cpu, COLLECTD_CPU_STATE_GUEST_NICE,
682                       (derive_t)atoll(fields[10]), now);
683           }
684         }
685       }
686     }
687   }
688   fclose(fh);
689 /* }}} #endif defined(KERNEL_LINUX) */
690
691 #elif defined(HAVE_LIBKSTAT) /* {{{ */
692   static cpu_stat_t cs;
693
694   if (kc == NULL)
695     return -1;
696
697   for (int cpu = 0; cpu < numcpu; cpu++) {
698     if (kstat_read(kc, ksp[cpu], &cs) == -1)
699       continue; /* error message? */
700
701     cpu_stage(ksp[cpu]->ks_instance, COLLECTD_CPU_STATE_IDLE,
702               (derive_t)cs.cpu_sysinfo.cpu[CPU_IDLE], now);
703     cpu_stage(ksp[cpu]->ks_instance, COLLECTD_CPU_STATE_USER,
704               (derive_t)cs.cpu_sysinfo.cpu[CPU_USER], now);
705     cpu_stage(ksp[cpu]->ks_instance, COLLECTD_CPU_STATE_SYSTEM,
706               (derive_t)cs.cpu_sysinfo.cpu[CPU_KERNEL], now);
707     cpu_stage(ksp[cpu]->ks_instance, COLLECTD_CPU_STATE_WAIT,
708               (derive_t)cs.cpu_sysinfo.cpu[CPU_WAIT], now);
709   }
710 /* }}} #endif defined(HAVE_LIBKSTAT) */
711
712 #elif CAN_USE_SYSCTL /* {{{ */
713   uint64_t cpuinfo[numcpu][CPUSTATES];
714   size_t cpuinfo_size;
715   int status;
716
717   if (numcpu < 1) {
718     ERROR("cpu plugin: Could not determine number of "
719           "installed CPUs using sysctl(3).");
720     return -1;
721   }
722
723   memset(cpuinfo, 0, sizeof(cpuinfo));
724
725 #if defined(KERN_CPTIME2)
726   if (numcpu > 1) {
727     for (int i = 0; i < numcpu; i++) {
728       int mib[] = {CTL_KERN, KERN_CPTIME2, i};
729
730       cpuinfo_size = sizeof(cpuinfo[0]);
731
732       status = sysctl(mib, STATIC_ARRAY_SIZE(mib), cpuinfo[i], &cpuinfo_size,
733                       NULL, 0);
734       if (status == -1) {
735         char errbuf[1024];
736         ERROR("cpu plugin: sysctl failed: %s.",
737               sstrerror(errno, errbuf, sizeof(errbuf)));
738         return -1;
739       }
740     }
741   } else
742 #endif /* defined(KERN_CPTIME2) */
743   {
744     int mib[] = {CTL_KERN, KERN_CPTIME};
745     long cpuinfo_tmp[CPUSTATES];
746
747     cpuinfo_size = sizeof(cpuinfo_tmp);
748
749     status = sysctl(mib, STATIC_ARRAY_SIZE(mib), &cpuinfo_tmp, &cpuinfo_size,
750                     NULL, 0);
751     if (status == -1) {
752       char errbuf[1024];
753       ERROR("cpu plugin: sysctl failed: %s.",
754             sstrerror(errno, errbuf, sizeof(errbuf)));
755       return -1;
756     }
757
758     for (int i = 0; i < CPUSTATES; i++) {
759       cpuinfo[0][i] = cpuinfo_tmp[i];
760     }
761   }
762
763   for (int i = 0; i < numcpu; i++) {
764     cpu_stage(i, COLLECTD_CPU_STATE_USER, (derive_t)cpuinfo[i][CP_USER], now);
765     cpu_stage(i, COLLECTD_CPU_STATE_NICE, (derive_t)cpuinfo[i][CP_NICE], now);
766     cpu_stage(i, COLLECTD_CPU_STATE_SYSTEM, (derive_t)cpuinfo[i][CP_SYS], now);
767     cpu_stage(i, COLLECTD_CPU_STATE_IDLE, (derive_t)cpuinfo[i][CP_IDLE], now);
768     cpu_stage(i, COLLECTD_CPU_STATE_INTERRUPT, (derive_t)cpuinfo[i][CP_INTR],
769               now);
770   }
771 /* }}} #endif CAN_USE_SYSCTL */
772
773 #elif defined(HAVE_SYSCTLBYNAME) && defined(HAVE_SYSCTL_KERN_CP_TIMES) /* {{{  \
774                                                                           */
775   long cpuinfo[maxcpu][CPUSTATES];
776   size_t cpuinfo_size;
777
778   memset(cpuinfo, 0, sizeof(cpuinfo));
779
780   cpuinfo_size = sizeof(cpuinfo);
781   if (sysctlbyname("kern.cp_times", &cpuinfo, &cpuinfo_size, NULL, 0) < 0) {
782     char errbuf[1024];
783     ERROR("cpu plugin: sysctlbyname failed: %s.",
784           sstrerror(errno, errbuf, sizeof(errbuf)));
785     return -1;
786   }
787
788   for (int i = 0; i < numcpu; i++) {
789     cpu_stage(i, COLLECTD_CPU_STATE_USER, (derive_t)cpuinfo[i][CP_USER], now);
790     cpu_stage(i, COLLECTD_CPU_STATE_NICE, (derive_t)cpuinfo[i][CP_NICE], now);
791     cpu_stage(i, COLLECTD_CPU_STATE_SYSTEM, (derive_t)cpuinfo[i][CP_SYS], now);
792     cpu_stage(i, COLLECTD_CPU_STATE_IDLE, (derive_t)cpuinfo[i][CP_IDLE], now);
793     cpu_stage(i, COLLECTD_CPU_STATE_INTERRUPT, (derive_t)cpuinfo[i][CP_INTR],
794               now);
795   }
796 /* }}} #endif HAVE_SYSCTL_KERN_CP_TIMES */
797
798 #elif defined(HAVE_SYSCTLBYNAME) /* {{{ */
799   long cpuinfo[CPUSTATES];
800   size_t cpuinfo_size;
801
802   cpuinfo_size = sizeof(cpuinfo);
803
804   if (sysctlbyname("kern.cp_time", &cpuinfo, &cpuinfo_size, NULL, 0) < 0) {
805     char errbuf[1024];
806     ERROR("cpu plugin: sysctlbyname failed: %s.",
807           sstrerror(errno, errbuf, sizeof(errbuf)));
808     return -1;
809   }
810
811   cpu_stage(0, COLLECTD_CPU_STATE_USER, (derive_t)cpuinfo[CP_USER], now);
812   cpu_stage(0, COLLECTD_CPU_STATE_NICE, (derive_t)cpuinfo[CP_NICE], now);
813   cpu_stage(0, COLLECTD_CPU_STATE_SYSTEM, (derive_t)cpuinfo[CP_SYS], now);
814   cpu_stage(0, COLLECTD_CPU_STATE_IDLE, (derive_t)cpuinfo[CP_IDLE], now);
815   cpu_stage(0, COLLECTD_CPU_STATE_INTERRUPT, (derive_t)cpuinfo[CP_INTR], now);
816 /* }}} #endif HAVE_SYSCTLBYNAME */
817
818 #elif defined(HAVE_LIBSTATGRAB) /* {{{ */
819   sg_cpu_stats *cs;
820   cs = sg_get_cpu_stats();
821
822   if (cs == NULL) {
823     ERROR("cpu plugin: sg_get_cpu_stats failed.");
824     return -1;
825   }
826
827   cpu_state(0, COLLECTD_CPU_STATE_IDLE, (derive_t)cs->idle);
828   cpu_state(0, COLLECTD_CPU_STATE_NICE, (derive_t)cs->nice);
829   cpu_state(0, COLLECTD_CPU_STATE_SWAP, (derive_t)cs->swap);
830   cpu_state(0, COLLECTD_CPU_STATE_SYSTEM, (derive_t)cs->kernel);
831   cpu_state(0, COLLECTD_CPU_STATE_USER, (derive_t)cs->user);
832   cpu_state(0, COLLECTD_CPU_STATE_WAIT, (derive_t)cs->iowait);
833 /* }}} #endif HAVE_LIBSTATGRAB */
834
835 #elif defined(HAVE_PERFSTAT) /* {{{ */
836   perfstat_id_t id;
837   int cpus;
838
839   numcpu = perfstat_cpu(NULL, NULL, sizeof(perfstat_cpu_t), 0);
840   if (numcpu == -1) {
841     char errbuf[1024];
842     WARNING("cpu plugin: perfstat_cpu: %s",
843             sstrerror(errno, errbuf, sizeof(errbuf)));
844     return -1;
845   }
846
847   if (pnumcpu != numcpu || perfcpu == NULL) {
848     free(perfcpu);
849     perfcpu = malloc(numcpu * sizeof(perfstat_cpu_t));
850   }
851   pnumcpu = numcpu;
852
853   id.name[0] = '\0';
854   if ((cpus = perfstat_cpu(&id, perfcpu, sizeof(perfstat_cpu_t), numcpu)) < 0) {
855     char errbuf[1024];
856     WARNING("cpu plugin: perfstat_cpu: %s",
857             sstrerror(errno, errbuf, sizeof(errbuf)));
858     return -1;
859   }
860
861   for (int i = 0; i < cpus; i++) {
862     cpu_stage(i, COLLECTD_CPU_STATE_IDLE, (derive_t)perfcpu[i].idle, now);
863     cpu_stage(i, COLLECTD_CPU_STATE_SYSTEM, (derive_t)perfcpu[i].sys, now);
864     cpu_stage(i, COLLECTD_CPU_STATE_USER, (derive_t)perfcpu[i].user, now);
865     cpu_stage(i, COLLECTD_CPU_STATE_WAIT, (derive_t)perfcpu[i].wait, now);
866   }
867 #endif                       /* }}} HAVE_PERFSTAT */
868
869   cpu_commit();
870   cpu_reset();
871   return 0;
872 }
873
874 void module_register(void) {
875   plugin_register_init("cpu", init);
876   plugin_register_config("cpu", cpu_config, config_keys, config_keys_num);
877   plugin_register_read("cpu", cpu_read);
878 } /* void module_register */