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