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