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