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