Merge remote-tracking branch 'github/pr/2391' into collectd-5.6
[collectd.git] / src / turbostat.c
1 /*
2  * turbostat -- Log CPU frequency and C-state residency
3  * on modern Intel turbo-capable processors for collectd.
4  *
5  * Based on the 'turbostat' tool of the Linux kernel, found at
6  * linux/tools/power/x86/turbostat/turbostat.c:
7  * ----
8  * Copyright (c) 2013 Intel Corporation.
9  * Len Brown <len.brown@intel.com>
10  *
11  * This program is free software; you can redistribute it and/or modify it
12  * under the terms and conditions of the GNU General Public License,
13  * version 2, as published by the Free Software Foundation.
14  *
15  * This program is distributed in the hope it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
18  * more details.
19  *
20  * You should have received a copy of the GNU General Public License along with
21  * this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
23  * ----
24  * Ported to collectd by Vincent Brillault <git@lerya.net>
25  */
26
27 /*
28  * _GNU_SOURCE is required because of the following functions:
29  * - CPU_ISSET_S
30  * - CPU_ZERO_S
31  * - CPU_SET_S
32  * - CPU_FREE
33  * - CPU_ALLOC
34  * - CPU_ALLOC_SIZE
35  */
36 #define _GNU_SOURCE
37
38 #include "collectd.h"
39
40 #include "common.h"
41 #include "plugin.h"
42 #include "utils_time.h"
43
44 #include <asm/msr-index.h>
45 #include <cpuid.h>
46 #ifdef HAVE_SYS_CAPABILITY_H
47 #include <sys/capability.h>
48 #endif /* HAVE_SYS_CAPABILITY_H */
49
50 #define PLUGIN_NAME "turbostat"
51
52 /*
53  * This tool uses the Model-Specific Registers (MSRs) present on Intel
54  * processors.
55  * The general description each of these registers, depending on the
56  * architecture,
57  * can be found in the IntelĀ® 64 and IA-32 Architectures Software Developer
58  * Manual,
59  * Volume 3 Chapter 35.
60  */
61
62 /*
63  * If set, aperf_mperf_unstable disables a/mperf based stats.
64  * This includes: C0 & C1 states, frequency
65  *
66  * This value is automatically set if mperf or aperf go backward
67  */
68 static _Bool aperf_mperf_unstable;
69
70 /*
71  * Bitmask of the list of core C states supported by the processor.
72  * Currently supported C-states (by this plugin): 3, 6, 7
73  */
74 static unsigned int do_core_cstate;
75 static unsigned int config_core_cstate;
76 static _Bool apply_config_core_cstate;
77
78 /*
79  * Bitmask of the list of pacages C states supported by the processor.
80  * Currently supported C-states (by this plugin): 2, 3, 6, 7, 8, 9, 10
81  */
82 static unsigned int do_pkg_cstate;
83 static unsigned int config_pkg_cstate;
84 static _Bool apply_config_pkg_cstate;
85
86 /*
87  * Boolean indicating if the processor supports 'I/O System-Management Interrupt
88  * counter'
89  */
90 static _Bool do_smi;
91 static _Bool config_smi;
92 static _Bool apply_config_smi;
93
94 /*
95  * Boolean indicating if the processor supports 'Digital temperature sensor'
96  * This feature enables the monitoring of the temperature of each core
97  *
98  * This feature has two limitations:
99  *  - if MSR_IA32_TEMPERATURE_TARGET is not supported, the absolute temperature
100  * might be wrong
101  *  - Temperatures above the tcc_activation_temp are not recorded
102  */
103 static _Bool do_dts;
104 static _Bool config_dts;
105 static _Bool apply_config_dts;
106
107 /*
108  * Boolean indicating if the processor supports 'Package thermal management'
109  * This feature allows the monitoring of the temperature of each package
110  *
111  * This feature has two limitations:
112  *  - if MSR_IA32_TEMPERATURE_TARGET is not supported, the absolute temperature
113  * might be wrong
114  *  - Temperatures above the tcc_activation_temp are not recorded
115  */
116 static _Bool do_ptm;
117 static _Bool config_ptm;
118 static _Bool apply_config_ptm;
119
120 /*
121  * Thermal Control Circuit Activation Temperature as configured by the user.
122  * This override the automated detection via MSR_IA32_TEMPERATURE_TARGET
123  * and should only be used if the automated detection fails.
124  */
125 static unsigned int tcc_activation_temp;
126
127 static unsigned int do_rapl;
128 static unsigned int config_rapl;
129 static _Bool apply_config_rapl;
130 static double rapl_energy_units;
131
132 #define RAPL_PKG (1 << 0)
133 /* 0x610 MSR_PKG_POWER_LIMIT */
134 /* 0x611 MSR_PKG_ENERGY_STATUS */
135 #define RAPL_DRAM (1 << 1)
136 /* 0x618 MSR_DRAM_POWER_LIMIT */
137 /* 0x619 MSR_DRAM_ENERGY_STATUS */
138 /* 0x61c MSR_DRAM_POWER_INFO */
139 #define RAPL_CORES (1 << 2)
140 /* 0x638 MSR_PP0_POWER_LIMIT */
141 /* 0x639 MSR_PP0_ENERGY_STATUS */
142
143 #define RAPL_GFX (1 << 3)
144 /* 0x640 MSR_PP1_POWER_LIMIT */
145 /* 0x641 MSR_PP1_ENERGY_STATUS */
146 /* 0x642 MSR_PP1_POLICY */
147 #define TJMAX_DEFAULT 100
148
149 static cpu_set_t *cpu_present_set, *cpu_affinity_set, *cpu_saved_affinity_set;
150 static size_t cpu_present_setsize, cpu_affinity_setsize,
151     cpu_saved_affinity_setsize;
152
153 static struct thread_data {
154   unsigned long long tsc;
155   unsigned long long aperf;
156   unsigned long long mperf;
157   unsigned long long c1;
158   unsigned int smi_count;
159   unsigned int cpu_id;
160   unsigned int flags;
161 #define CPU_IS_FIRST_THREAD_IN_CORE 0x2
162 #define CPU_IS_FIRST_CORE_IN_PACKAGE 0x4
163 } * thread_delta, *thread_even, *thread_odd;
164
165 static struct core_data {
166   unsigned long long c3;
167   unsigned long long c6;
168   unsigned long long c7;
169   unsigned int core_temp_c;
170   unsigned int core_id;
171 } * core_delta, *core_even, *core_odd;
172
173 static struct pkg_data {
174   unsigned long long pc2;
175   unsigned long long pc3;
176   unsigned long long pc6;
177   unsigned long long pc7;
178   unsigned long long pc8;
179   unsigned long long pc9;
180   unsigned long long pc10;
181   unsigned int package_id;
182   uint32_t energy_pkg;   /* MSR_PKG_ENERGY_STATUS */
183   uint32_t energy_dram;  /* MSR_DRAM_ENERGY_STATUS */
184   uint32_t energy_cores; /* MSR_PP0_ENERGY_STATUS */
185   uint32_t energy_gfx;   /* MSR_PP1_ENERGY_STATUS */
186   unsigned int tcc_activation_temp;
187   unsigned int pkg_temp_c;
188 } * package_delta, *package_even, *package_odd;
189
190 #define DELTA_COUNTERS thread_delta, core_delta, package_delta
191 #define ODD_COUNTERS thread_odd, core_odd, package_odd
192 #define EVEN_COUNTERS thread_even, core_even, package_even
193 static _Bool is_even = 1;
194
195 static _Bool allocated = 0;
196 static _Bool initialized = 0;
197
198 #define GET_THREAD(thread_base, thread_no, core_no, pkg_no)                    \
199   (thread_base + (pkg_no)*topology.num_cores * topology.num_threads +          \
200    (core_no)*topology.num_threads + (thread_no))
201 #define GET_CORE(core_base, core_no, pkg_no)                                   \
202   (core_base + (pkg_no)*topology.num_cores + (core_no))
203 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
204
205 struct cpu_topology {
206   unsigned int package_id;
207   unsigned int core_id;
208   _Bool first_core_in_package;
209   _Bool first_thread_in_core;
210 };
211
212 static struct topology {
213   unsigned int max_cpu_id;
214   unsigned int num_packages;
215   unsigned int num_cores;
216   unsigned int num_threads;
217   struct cpu_topology *cpus;
218 } topology;
219
220 static cdtime_t time_even, time_odd, time_delta;
221
222 static const char *config_keys[] = {
223     "CoreCstates",
224     "PackageCstates",
225     "SystemManagementInterrupt",
226     "DigitalTemperatureSensor",
227     "PackageThermalManagement",
228     "TCCActivationTemp",
229     "RunningAveragePowerLimit",
230 };
231 static const int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
232
233 /*****************************
234  *  MSR Manipulation helpers *
235  *****************************/
236
237 /*
238  * Open a MSR device for reading
239  * Can change the scheduling affinity of the current process if multiple_read is
240  * 1
241  */
242 static int __attribute__((warn_unused_result))
243 open_msr(unsigned int cpu, _Bool multiple_read) {
244   char pathname[32];
245   int fd;
246
247   /*
248    * If we need to do multiple read, let's migrate to the CPU
249    * Otherwise, we would lose time calling functions on another CPU
250    *
251    * If we are not yet initialized (cpu_affinity_setsize = 0),
252    * we need to skip this optimisation.
253    */
254   if (multiple_read && cpu_affinity_setsize) {
255     CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
256     CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
257     if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1) {
258       ERROR("turbostat plugin: Could not migrate to CPU %d", cpu);
259       return -1;
260     }
261   }
262
263   ssnprintf(pathname, sizeof(pathname), "/dev/cpu/%d/msr", cpu);
264   fd = open(pathname, O_RDONLY);
265   if (fd < 0) {
266     ERROR("turbostat plugin: failed to open %s", pathname);
267     return -1;
268   }
269   return fd;
270 }
271
272 /*
273  * Read a single MSR from an open file descriptor
274  */
275 static int __attribute__((warn_unused_result))
276 read_msr(int fd, off_t offset, unsigned long long *msr) {
277   ssize_t retval;
278
279   retval = pread(fd, msr, sizeof *msr, offset);
280
281   if (retval != sizeof *msr) {
282     ERROR("turbostat plugin: MSR offset 0x%llx read failed",
283           (unsigned long long)offset);
284     return -1;
285   }
286   return 0;
287 }
288
289 /*
290  * Open a MSR device for reading, read the value asked for and close it.
291  * This call will not affect the scheduling affinity of this thread.
292  */
293 static ssize_t __attribute__((warn_unused_result))
294 get_msr(unsigned int cpu, off_t offset, unsigned long long *msr) {
295   ssize_t retval;
296   int fd;
297
298   fd = open_msr(cpu, 0);
299   if (fd < 0)
300     return fd;
301   retval = read_msr(fd, offset, msr);
302   close(fd);
303   return retval;
304 }
305
306 /********************************
307  * Raw data acquisition (1 CPU) *
308  ********************************/
309
310 /*
311  * Read every data avalaible for a single CPU
312  *
313  * Core data is shared for all threads in one core: extracted only for the first
314  * thread
315  * Package data is shared for all core in one package: extracted only for the
316  * first thread of the first core
317  *
318  * Side effect: migrates to the targeted CPU
319  */
320 static int __attribute__((warn_unused_result))
321 get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p) {
322   unsigned int cpu = t->cpu_id;
323   unsigned long long msr;
324   int msr_fd;
325   int retval = 0;
326
327   msr_fd = open_msr(cpu, 1);
328   if (msr_fd < 0)
329     return msr_fd;
330
331 #define READ_MSR(msr, dst)                                                     \
332   do {                                                                         \
333     if (read_msr(msr_fd, msr, dst)) {                                          \
334       ERROR("turbostat plugin: Unable to read " #msr);                         \
335       retval = -1;                                                             \
336       goto out;                                                                \
337     }                                                                          \
338   } while (0)
339
340   READ_MSR(MSR_IA32_TSC, &t->tsc);
341
342   READ_MSR(MSR_IA32_APERF, &t->aperf);
343   READ_MSR(MSR_IA32_MPERF, &t->mperf);
344
345   if (do_smi) {
346     READ_MSR(MSR_SMI_COUNT, &msr);
347     t->smi_count = msr & 0xFFFFFFFF;
348   }
349
350   /* collect core counters only for 1st thread in core */
351   if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE)) {
352     retval = 0;
353     goto out;
354   }
355
356   if (do_core_cstate & (1 << 3))
357     READ_MSR(MSR_CORE_C3_RESIDENCY, &c->c3);
358   if (do_core_cstate & (1 << 6))
359     READ_MSR(MSR_CORE_C6_RESIDENCY, &c->c6);
360   if (do_core_cstate & (1 << 7))
361     READ_MSR(MSR_CORE_C7_RESIDENCY, &c->c7);
362
363   if (do_dts) {
364     READ_MSR(MSR_IA32_THERM_STATUS, &msr);
365     c->core_temp_c = p->tcc_activation_temp - ((msr >> 16) & 0x7F);
366   }
367
368   /* collect package counters only for 1st core in package */
369   if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
370     retval = 0;
371     goto out;
372   }
373
374   if (do_pkg_cstate & (1 << 2))
375     READ_MSR(MSR_PKG_C2_RESIDENCY, &p->pc2);
376   if (do_pkg_cstate & (1 << 3))
377     READ_MSR(MSR_PKG_C3_RESIDENCY, &p->pc3);
378   if (do_pkg_cstate & (1 << 6))
379     READ_MSR(MSR_PKG_C6_RESIDENCY, &p->pc6);
380   if (do_pkg_cstate & (1 << 7))
381     READ_MSR(MSR_PKG_C7_RESIDENCY, &p->pc7);
382   if (do_pkg_cstate & (1 << 8))
383     READ_MSR(MSR_PKG_C8_RESIDENCY, &p->pc8);
384   if (do_pkg_cstate & (1 << 9))
385     READ_MSR(MSR_PKG_C9_RESIDENCY, &p->pc9);
386   if (do_pkg_cstate & (1 << 10))
387     READ_MSR(MSR_PKG_C10_RESIDENCY, &p->pc10);
388
389   if (do_rapl & RAPL_PKG) {
390     READ_MSR(MSR_PKG_ENERGY_STATUS, &msr);
391     p->energy_pkg = msr & 0xFFFFFFFF;
392   }
393   if (do_rapl & RAPL_CORES) {
394     READ_MSR(MSR_PP0_ENERGY_STATUS, &msr);
395     p->energy_cores = msr & 0xFFFFFFFF;
396   }
397   if (do_rapl & RAPL_DRAM) {
398     READ_MSR(MSR_DRAM_ENERGY_STATUS, &msr);
399     p->energy_dram = msr & 0xFFFFFFFF;
400   }
401   if (do_rapl & RAPL_GFX) {
402     READ_MSR(MSR_PP1_ENERGY_STATUS, &msr);
403     p->energy_gfx = msr & 0xFFFFFFFF;
404   }
405   if (do_ptm) {
406     READ_MSR(MSR_IA32_PACKAGE_THERM_STATUS, &msr);
407     p->pkg_temp_c = p->tcc_activation_temp - ((msr >> 16) & 0x7F);
408   }
409
410 out:
411   close(msr_fd);
412   return retval;
413 }
414
415 /**********************************
416  * Evaluating the changes (1 CPU) *
417  **********************************/
418
419 /*
420  * Extract the evolution old->new in delta at a package level
421  * (some are not new-delta, e.g. temperature)
422  */
423 static inline void delta_package(struct pkg_data *delta,
424                                  const struct pkg_data *new,
425                                  const struct pkg_data *old) {
426   delta->pc2 = new->pc2 - old->pc2;
427   delta->pc3 = new->pc3 - old->pc3;
428   delta->pc6 = new->pc6 - old->pc6;
429   delta->pc7 = new->pc7 - old->pc7;
430   delta->pc8 = new->pc8 - old->pc8;
431   delta->pc9 = new->pc9 - old->pc9;
432   delta->pc10 = new->pc10 - old->pc10;
433   delta->pkg_temp_c = new->pkg_temp_c;
434
435   delta->energy_pkg = new->energy_pkg - old->energy_pkg;
436   delta->energy_cores = new->energy_cores - old->energy_cores;
437   delta->energy_gfx = new->energy_gfx - old->energy_gfx;
438   delta->energy_dram = new->energy_dram - old->energy_dram;
439 }
440
441 /*
442  * Extract the evolution old->new in delta at a core level
443  * (some are not new-delta, e.g. temperature)
444  */
445 static inline void delta_core(struct core_data *delta,
446                               const struct core_data *new,
447                               const struct core_data *old) {
448   delta->c3 = new->c3 - old->c3;
449   delta->c6 = new->c6 - old->c6;
450   delta->c7 = new->c7 - old->c7;
451   delta->core_temp_c = new->core_temp_c;
452 }
453
454 /*
455  * Extract the evolution old->new in delta at a package level
456  * core_delta is required for c1 estimation (tsc - c0 - all core cstates)
457  */
458 static inline int __attribute__((warn_unused_result))
459 delta_thread(struct thread_data *delta, const struct thread_data *new,
460              const struct thread_data *old, const struct core_data *cdelta) {
461   delta->tsc = new->tsc - old->tsc;
462
463   /* check for TSC < 1 Mcycles over interval */
464   if (delta->tsc < (1000 * 1000)) {
465     WARNING("turbostat plugin: Insanely slow TSC rate, TSC stops "
466             "in idle? You can disable all c-states by booting with"
467             " 'idle=poll' or just the deep ones with"
468             " 'processor.max_cstate=1'");
469     return -1;
470   }
471
472   delta->c1 = new->c1 - old->c1;
473
474   if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
475     delta->aperf = new->aperf - old->aperf;
476     delta->mperf = new->mperf - old->mperf;
477   } else {
478     if (!aperf_mperf_unstable) {
479       WARNING("turbostat plugin: APERF or MPERF went "
480               "backwards. Frequency results do not cover "
481               "the entire interval. Fix this by running "
482               "Linux-2.6.30 or later.");
483
484       aperf_mperf_unstable = 1;
485     }
486   }
487
488   /*
489    * As counter collection is not atomic,
490    * it is possible for mperf's non-halted cycles + idle states
491    * to exceed TSC's all cycles: show c1 = 0% in that case.
492    */
493   if ((delta->mperf + cdelta->c3 + cdelta->c6 + cdelta->c7) > delta->tsc)
494     delta->c1 = 0;
495   else {
496     /* normal case, derive c1 */
497     delta->c1 =
498         delta->tsc - delta->mperf - cdelta->c3 - cdelta->c6 - cdelta->c7;
499   }
500
501   if (delta->mperf == 0) {
502     WARNING("turbostat plugin: cpu%d MPERF 0!", old->cpu_id);
503     delta->mperf = 1; /* divide by 0 protection */
504   }
505
506   if (do_smi)
507     delta->smi_count = new->smi_count - old->smi_count;
508
509   return 0;
510 }
511
512 /**********************************
513  * Submitting the results (1 CPU) *
514  **********************************/
515
516 /*
517  * Submit one gauge value
518  */
519 static void turbostat_submit(const char *plugin_instance, const char *type,
520                              const char *type_instance, gauge_t value) {
521   value_list_t vl = VALUE_LIST_INIT;
522   value_t v;
523
524   v.gauge = value;
525   vl.values = &v;
526   vl.values_len = 1;
527   sstrncpy(vl.host, hostname_g, sizeof(vl.host));
528   sstrncpy(vl.plugin, PLUGIN_NAME, sizeof(vl.plugin));
529   if (plugin_instance != NULL)
530     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
531   sstrncpy(vl.type, type, sizeof(vl.type));
532   if (type_instance != NULL)
533     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
534
535   plugin_dispatch_values(&vl);
536 }
537
538 /*
539  * Submit every data for a single CPU
540  *
541  * Core data is shared for all threads in one core: submitted only for the first
542  * thread
543  * Package data is shared for all core in one package: submitted only for the
544  * first thread of the first core
545  */
546 static int submit_counters(struct thread_data *t, struct core_data *c,
547                            struct pkg_data *p) {
548   char name[DATA_MAX_NAME_LEN];
549   double interval_float;
550
551   interval_float = CDTIME_T_TO_DOUBLE(time_delta);
552
553   ssnprintf(name, sizeof(name), "cpu%02d", t->cpu_id);
554
555   if (!aperf_mperf_unstable)
556     turbostat_submit(name, "percent", "c0", 100.0 * t->mperf / t->tsc);
557   if (!aperf_mperf_unstable)
558     turbostat_submit(name, "percent", "c1", 100.0 * t->c1 / t->tsc);
559
560   turbostat_submit(name, "frequency", "average",
561                    1.0 / 1000000 * t->aperf / interval_float);
562
563   if ((!aperf_mperf_unstable) || (!(t->aperf > t->tsc || t->mperf > t->tsc)))
564     turbostat_submit(name, "frequency", "busy", 1.0 * t->tsc / 1000000 *
565                                                     t->aperf / t->mperf /
566                                                     interval_float);
567
568   /* Sanity check (should stay stable) */
569   turbostat_submit(name, "gauge", "TSC",
570                    1.0 * t->tsc / 1000000 / interval_float);
571
572   /* SMI */
573   if (do_smi)
574     turbostat_submit(name, "count", NULL, t->smi_count);
575
576   /* submit per-core data only for 1st thread in core */
577   if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
578     goto done;
579
580   ssnprintf(name, sizeof(name), "core%02d", c->core_id);
581
582   if (do_core_cstate & (1 << 3))
583     turbostat_submit(name, "percent", "c3", 100.0 * c->c3 / t->tsc);
584   if (do_core_cstate & (1 << 6))
585     turbostat_submit(name, "percent", "c6", 100.0 * c->c6 / t->tsc);
586   if (do_core_cstate & (1 << 7))
587     turbostat_submit(name, "percent", "c7", 100.0 * c->c7 / t->tsc);
588
589   if (do_dts)
590     turbostat_submit(name, "temperature", NULL, c->core_temp_c);
591
592   /* submit per-package data only for 1st core in package */
593   if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
594     goto done;
595
596   ssnprintf(name, sizeof(name), "pkg%02d", p->package_id);
597
598   if (do_ptm)
599     turbostat_submit(name, "temperature", NULL, p->pkg_temp_c);
600
601   if (do_pkg_cstate & (1 << 2))
602     turbostat_submit(name, "percent", "pc2", 100.0 * p->pc2 / t->tsc);
603   if (do_pkg_cstate & (1 << 3))
604     turbostat_submit(name, "percent", "pc3", 100.0 * p->pc3 / t->tsc);
605   if (do_pkg_cstate & (1 << 6))
606     turbostat_submit(name, "percent", "pc6", 100.0 * p->pc6 / t->tsc);
607   if (do_pkg_cstate & (1 << 7))
608     turbostat_submit(name, "percent", "pc7", 100.0 * p->pc7 / t->tsc);
609   if (do_pkg_cstate & (1 << 8))
610     turbostat_submit(name, "percent", "pc8", 100.0 * p->pc8 / t->tsc);
611   if (do_pkg_cstate & (1 << 9))
612     turbostat_submit(name, "percent", "pc9", 100.0 * p->pc9 / t->tsc);
613   if (do_pkg_cstate & (1 << 10))
614     turbostat_submit(name, "percent", "pc10", 100.0 * p->pc10 / t->tsc);
615
616   if (do_rapl) {
617     if (do_rapl & RAPL_PKG)
618       turbostat_submit(name, "power", "pkg",
619                        p->energy_pkg * rapl_energy_units / interval_float);
620     if (do_rapl & RAPL_CORES)
621       turbostat_submit(name, "power", "cores",
622                        p->energy_cores * rapl_energy_units / interval_float);
623     if (do_rapl & RAPL_GFX)
624       turbostat_submit(name, "power", "GFX",
625                        p->energy_gfx * rapl_energy_units / interval_float);
626     if (do_rapl & RAPL_DRAM)
627       turbostat_submit(name, "power", "DRAM",
628                        p->energy_dram * rapl_energy_units / interval_float);
629   }
630 done:
631   return 0;
632 }
633
634 /**********************************
635  * Looping function over all CPUs *
636  **********************************/
637
638 /*
639  * Check if a given cpu id is in our compiled list of existing CPUs
640  */
641 static int cpu_is_not_present(unsigned int cpu) {
642   return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
643 }
644
645 /*
646  * Loop on all CPUs in topological order
647  *
648  * Skip non-present cpus
649  * Return the error code at the first error or 0
650  */
651 static int __attribute__((warn_unused_result))
652 for_all_cpus(int(func)(struct thread_data *, struct core_data *,
653                        struct pkg_data *),
654              struct thread_data *thread_base, struct core_data *core_base,
655              struct pkg_data *pkg_base) {
656   int retval;
657
658   for (unsigned int pkg_no = 0; pkg_no < topology.num_packages; ++pkg_no) {
659     for (unsigned int core_no = 0; core_no < topology.num_cores; ++core_no) {
660       for (unsigned int thread_no = 0; thread_no < topology.num_threads;
661            ++thread_no) {
662         struct thread_data *t;
663         struct core_data *c;
664         struct pkg_data *p;
665
666         t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
667
668         if (cpu_is_not_present(t->cpu_id))
669           continue;
670
671         c = GET_CORE(core_base, core_no, pkg_no);
672         p = GET_PKG(pkg_base, pkg_no);
673
674         retval = func(t, c, p);
675         if (retval)
676           return retval;
677       }
678     }
679   }
680   return 0;
681 }
682
683 /*
684  * Dedicated loop: Extract every data evolution for all CPU
685  *
686  * Skip non-present cpus
687  * Return the error code at the first error or 0
688  *
689  * Core data is shared for all threads in one core: extracted only for the first
690  * thread
691  * Package data is shared for all core in one package: extracted only for the
692  * first thread of the first core
693  */
694 static int __attribute__((warn_unused_result))
695 for_all_cpus_delta(const struct thread_data *thread_new_base,
696                    const struct core_data *core_new_base,
697                    const struct pkg_data *pkg_new_base,
698                    const struct thread_data *thread_old_base,
699                    const struct core_data *core_old_base,
700                    const struct pkg_data *pkg_old_base) {
701   int retval;
702
703   for (unsigned int pkg_no = 0; pkg_no < topology.num_packages; ++pkg_no) {
704     for (unsigned int core_no = 0; core_no < topology.num_cores; ++core_no) {
705       for (unsigned int thread_no = 0; thread_no < topology.num_threads;
706            ++thread_no) {
707         struct thread_data *t_delta;
708         const struct thread_data *t_old, *t_new;
709         struct core_data *c_delta;
710
711         /* Get correct pointers for threads */
712         t_delta = GET_THREAD(thread_delta, thread_no, core_no, pkg_no);
713         t_new = GET_THREAD(thread_new_base, thread_no, core_no, pkg_no);
714         t_old = GET_THREAD(thread_old_base, thread_no, core_no, pkg_no);
715
716         /* Skip threads that disappeared */
717         if (cpu_is_not_present(t_delta->cpu_id))
718           continue;
719
720         /* c_delta is always required for delta_thread */
721         c_delta = GET_CORE(core_delta, core_no, pkg_no);
722
723         /* calculate core delta only for 1st thread in core */
724         if (t_new->flags & CPU_IS_FIRST_THREAD_IN_CORE) {
725           const struct core_data *c_old, *c_new;
726
727           c_new = GET_CORE(core_new_base, core_no, pkg_no);
728           c_old = GET_CORE(core_old_base, core_no, pkg_no);
729
730           delta_core(c_delta, c_new, c_old);
731         }
732
733         /* Always calculate thread delta */
734         retval = delta_thread(t_delta, t_new, t_old, c_delta);
735         if (retval)
736           return retval;
737
738         /* calculate package delta only for 1st core in package */
739         if (t_new->flags & CPU_IS_FIRST_CORE_IN_PACKAGE) {
740           struct pkg_data *p_delta;
741           const struct pkg_data *p_old, *p_new;
742
743           p_delta = GET_PKG(package_delta, pkg_no);
744           p_new = GET_PKG(pkg_new_base, pkg_no);
745           p_old = GET_PKG(pkg_old_base, pkg_no);
746
747           delta_package(p_delta, p_new, p_old);
748         }
749       }
750     }
751   }
752   return 0;
753 }
754
755 /***************
756  * CPU Probing *
757  ***************/
758
759 /*
760  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
761  * the Thermal Control Circuit (TCC) activates.
762  * This is usually equal to tjMax.
763  *
764  * Older processors do not have this MSR, so there we guess,
765  * but also allow conficuration over-ride with "TCCActivationTemp".
766  *
767  * Several MSR temperature values are in units of degrees-C
768  * below this value, including the Digital Thermal Sensor (DTS),
769  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
770  */
771 static int __attribute__((warn_unused_result))
772 set_temperature_target(struct thread_data *t, struct core_data *c,
773                        struct pkg_data *p) {
774   unsigned long long msr;
775   unsigned int target_c_local;
776
777   /* tcc_activation_temp is used only for dts or ptm */
778   if (!(do_dts || do_ptm))
779     return 0;
780
781   /* this is a per-package concept */
782   if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) ||
783       !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
784     return 0;
785
786   if (tcc_activation_temp != 0) {
787     p->tcc_activation_temp = tcc_activation_temp;
788     return 0;
789   }
790
791   if (get_msr(t->cpu_id, MSR_IA32_TEMPERATURE_TARGET, &msr))
792     goto guess;
793
794   target_c_local = (msr >> 16) & 0xFF;
795
796   if (!target_c_local)
797     goto guess;
798
799   p->tcc_activation_temp = target_c_local;
800
801   return 0;
802
803 guess:
804   p->tcc_activation_temp = TJMAX_DEFAULT;
805   WARNING("turbostat plugin: cpu%d: Guessing tjMax %d C,"
806           " Please use TCCActivationTemp to specify it.",
807           t->cpu_id, p->tcc_activation_temp);
808
809   return 0;
810 }
811
812 /*
813  * Identify the functionality of the CPU
814  */
815 static int __attribute__((warn_unused_result)) probe_cpu(void) {
816   unsigned int eax, ebx, ecx, edx, max_level;
817   unsigned int fms, family, model;
818
819   /* CPUID(0):
820    * - EAX: Maximum Input Value for Basic CPUID Information
821    * - EBX: "Genu" (0x756e6547)
822    * - EDX: "ineI" (0x49656e69)
823    * - ECX: "ntel" (0x6c65746e)
824    */
825   max_level = ebx = ecx = edx = 0;
826   __get_cpuid(0, &max_level, &ebx, &ecx, &edx);
827   if (ebx != 0x756e6547 && edx != 0x49656e69 && ecx != 0x6c65746e) {
828     ERROR("turbostat plugin: Unsupported CPU (not Intel)");
829     return -1;
830   }
831
832   /* CPUID(1):
833    * - EAX: Version Information: Type, Family, Model, and Stepping ID
834    *  + 4-7:   Model ID
835    *  + 8-11:  Family ID
836    *  + 12-13: Processor type
837    *  + 16-19: Extended Model ID
838    *  + 20-27: Extended Family ID
839    * - EDX: Feature Information:
840    *  + 5: Support for MSR read/write operations
841    */
842   fms = ebx = ecx = edx = 0;
843   __get_cpuid(1, &fms, &ebx, &ecx, &edx);
844   family = (fms >> 8) & 0xf;
845   model = (fms >> 4) & 0xf;
846   if (family == 0xf)
847     family += (fms >> 20) & 0xf;
848   if (family == 6 || family == 0xf)
849     model += ((fms >> 16) & 0xf) << 4;
850   if (!(edx & (1 << 5))) {
851     ERROR("turbostat plugin: Unsupported CPU (no MSR support)");
852     return -1;
853   }
854
855   /*
856    * CPUID(6):
857    * - EAX:
858    *  + 0: Digital temperature sensor is supported if set
859    *  + 6: Package thermal management is supported if set
860    * - ECX:
861    *  + 0: Hardware Coordination Feedback Capability (Presence of IA32_MPERF and
862    * IA32_APERF).
863    *  + 3: The processor supports performance-energy bias preference if set.
864    *       It also implies the presence of a new architectural MSR called
865    * IA32_ENERGY_PERF_BIAS
866    *
867    * This check is valid for both Intel and AMD
868    */
869   eax = ebx = ecx = edx = 0;
870   __get_cpuid(0x6, &eax, &ebx, &ecx, &edx);
871   do_dts = eax & (1 << 0);
872   do_ptm = eax & (1 << 6);
873   if (!(ecx & (1 << 0))) {
874     ERROR("turbostat plugin: Unsupported CPU (No APERF)");
875     return -1;
876   }
877
878   /*
879    * Enable or disable C states depending on the model and family
880    */
881   if (family == 6) {
882     switch (model) {
883     /* Atom (partial) */
884     case 0x27:
885       do_smi = 0;
886       do_core_cstate = 0;
887       do_pkg_cstate = (1 << 2) | (1 << 4) | (1 << 6);
888       break;
889     /* Silvermont */
890     case 0x37: /* BYT */
891     case 0x4D: /* AVN */
892       do_smi = 1;
893       do_core_cstate = (1 << 1) | (1 << 6);
894       do_pkg_cstate = (1 << 6);
895       break;
896     /* Nehalem */
897     case 0x1A: /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
898     case 0x1E: /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper
899                   Forest */
900     case 0x1F: /* Core i7 and i5 Processor - Nehalem */
901     case 0x2E: /* Nehalem-EX Xeon - Beckton */
902       do_smi = 1;
903       do_core_cstate = (1 << 3) | (1 << 6);
904       do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
905       break;
906     /* Westmere */
907     case 0x25: /* Westmere Client - Clarkdale, Arrandale */
908     case 0x2C: /* Westmere EP - Gulftown */
909     case 0x2F: /* Westmere-EX Xeon - Eagleton */
910       do_smi = 1;
911       do_core_cstate = (1 << 3) | (1 << 6);
912       do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
913       break;
914     /* Sandy Bridge */
915     case 0x2A: /* SNB */
916     case 0x2D: /* SNB Xeon */
917       do_smi = 1;
918       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
919       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
920       break;
921     /* Ivy Bridge */
922     case 0x3A: /* IVB */
923     case 0x3E: /* IVB Xeon */
924       do_smi = 1;
925       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
926       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
927       break;
928     /* Haswell Bridge */
929     case 0x3C: /* HSW */
930     case 0x3F: /* HSW */
931     case 0x46: /* HSW */
932       do_smi = 1;
933       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
934       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
935       break;
936     case 0x45: /* HSW */
937       do_smi = 1;
938       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
939       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) |
940                       (1 << 9) | (1 << 10);
941       break;
942     /* Broadwel */
943     case 0x4F: /* BDW */
944     case 0x56: /* BDX-DE */
945       do_smi = 1;
946       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
947       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
948       break;
949     case 0x3D: /* BDW */
950       do_smi = 1;
951       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
952       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) |
953                       (1 << 9) | (1 << 10);
954       break;
955     default:
956       do_smi = 0;
957       do_core_cstate = 0;
958       do_pkg_cstate = 0;
959       break;
960     }
961     switch (model) {
962     case 0x2A: /* SNB */
963     case 0x3A: /* IVB */
964     case 0x3C: /* HSW */
965     case 0x45: /* HSW */
966     case 0x46: /* HSW */
967     case 0x3D: /* BDW */
968       do_rapl = RAPL_PKG | RAPL_CORES | RAPL_GFX;
969       break;
970     case 0x3F: /* HSX */
971     case 0x4F: /* BDX */
972     case 0x56: /* BDX-DE */
973       do_rapl = RAPL_PKG | RAPL_DRAM;
974       break;
975     case 0x2D: /* SNB Xeon */
976     case 0x3E: /* IVB Xeon */
977       do_rapl = RAPL_PKG | RAPL_CORES | RAPL_DRAM;
978       break;
979     case 0x37: /* BYT */
980     case 0x4D: /* AVN */
981       do_rapl = RAPL_PKG | RAPL_CORES;
982       break;
983     default:
984       do_rapl = 0;
985     }
986   } else {
987     ERROR("turbostat plugin: Unsupported CPU (family: %#x, "
988           "model: %#x)",
989           family, model);
990     return -1;
991   }
992
993   /* Override detected values with configuration */
994   if (apply_config_core_cstate)
995     do_core_cstate = config_core_cstate;
996   if (apply_config_pkg_cstate)
997     do_pkg_cstate = config_pkg_cstate;
998   if (apply_config_smi)
999     do_smi = config_smi;
1000   if (apply_config_dts)
1001     do_dts = config_dts;
1002   if (apply_config_ptm)
1003     do_ptm = config_ptm;
1004   if (apply_config_rapl)
1005     do_rapl = config_rapl;
1006
1007   if (do_rapl) {
1008     unsigned long long msr;
1009     if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr))
1010       return 0;
1011
1012     if (model == 0x37)
1013       rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
1014     else
1015       rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
1016   }
1017
1018   return 0;
1019 }
1020
1021 /********************
1022  * Topology Probing *
1023  ********************/
1024
1025 /*
1026  * Read a single int from a file.
1027  */
1028 static int __attribute__((format(printf, 1, 2)))
1029 parse_int_file(const char *fmt, ...) {
1030   va_list args;
1031   char path[PATH_MAX];
1032   FILE *filep;
1033   int len, value;
1034
1035   va_start(args, fmt);
1036   len = vsnprintf(path, sizeof(path), fmt, args);
1037   va_end(args);
1038   if (len < 0 || len >= PATH_MAX) {
1039     ERROR("turbostat plugin: path truncated: '%s'", path);
1040     return -1;
1041   }
1042
1043   filep = fopen(path, "r");
1044   if (!filep) {
1045     ERROR("turbostat plugin: Failed to open '%s'", path);
1046     return -1;
1047   }
1048   if (fscanf(filep, "%d", &value) != 1) {
1049     ERROR("turbostat plugin: Failed to parse number from '%s'", path);
1050     fclose(filep);
1051     return -1;
1052   }
1053   fclose(filep);
1054   return value;
1055 }
1056
1057 static int get_threads_on_core(unsigned int cpu) {
1058   char path[80];
1059   FILE *filep;
1060   int sib1, sib2;
1061   int matches;
1062   char character;
1063
1064   ssnprintf(path, sizeof(path),
1065             "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
1066   filep = fopen(path, "r");
1067   if (!filep) {
1068     ERROR("turbostat plugin: Failed to open '%s'", path);
1069     return -1;
1070   }
1071   /*
1072    * file format:
1073    * if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4)
1074    * otherwinse 1 sibling (self).
1075    */
1076   matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2);
1077
1078   fclose(filep);
1079
1080   if (matches == 3)
1081     return 2;
1082   else
1083     return 1;
1084 }
1085
1086 /*
1087  * run func(cpu) on every cpu in /proc/stat
1088  * return max_cpu number
1089  */
1090 static int __attribute__((warn_unused_result))
1091 for_all_proc_cpus(int(func)(unsigned int)) {
1092   FILE *fp;
1093   unsigned int cpu_num;
1094   int retval;
1095
1096   fp = fopen("/proc/stat", "r");
1097   if (!fp) {
1098     ERROR("turbostat plugin: Failed to open /proc/stat");
1099     return -1;
1100   }
1101
1102   retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
1103   if (retval != 0) {
1104     ERROR("turbostat plugin: Failed to parse /proc/stat");
1105     fclose(fp);
1106     return -1;
1107   }
1108
1109   while (1) {
1110     retval =
1111         fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
1112     if (retval != 1)
1113       break;
1114
1115     retval = func(cpu_num);
1116     if (retval) {
1117       fclose(fp);
1118       return (retval);
1119     }
1120   }
1121   fclose(fp);
1122   return 0;
1123 }
1124
1125 /*
1126  * Update the stored topology.max_cpu_id
1127  */
1128 static int update_max_cpu_id(unsigned int cpu) {
1129   if (topology.max_cpu_id < cpu)
1130     topology.max_cpu_id = cpu;
1131   return 0;
1132 }
1133
1134 static int mark_cpu_present(unsigned int cpu) {
1135   CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
1136   return 0;
1137 }
1138
1139 static int __attribute__((warn_unused_result))
1140 allocate_cpu_set(cpu_set_t **set, size_t *size) {
1141   *set = CPU_ALLOC(topology.max_cpu_id + 1);
1142   if (*set == NULL) {
1143     ERROR("turbostat plugin: Unable to allocate CPU state");
1144     return -1;
1145   }
1146   *size = CPU_ALLOC_SIZE(topology.max_cpu_id + 1);
1147   CPU_ZERO_S(*size, *set);
1148   return 0;
1149 }
1150
1151 /*
1152  * Build a local representation of the cpu distribution
1153  */
1154 static int __attribute__((warn_unused_result)) topology_probe(void) {
1155   int ret;
1156   unsigned int max_package_id, max_core_id, max_threads;
1157   max_package_id = max_core_id = max_threads = 0;
1158
1159   /* Clean topology */
1160   free(topology.cpus);
1161   memset(&topology, 0, sizeof(topology));
1162
1163   ret = for_all_proc_cpus(update_max_cpu_id);
1164   if (ret != 0)
1165     goto err;
1166
1167   topology.cpus =
1168       calloc(1, (topology.max_cpu_id + 1) * sizeof(struct cpu_topology));
1169   if (topology.cpus == NULL) {
1170     ERROR("turbostat plugin: Unable to allocate memory for CPU topology");
1171     return -1;
1172   }
1173
1174   ret = allocate_cpu_set(&cpu_present_set, &cpu_present_setsize);
1175   if (ret != 0)
1176     goto err;
1177   ret = allocate_cpu_set(&cpu_affinity_set, &cpu_affinity_setsize);
1178   if (ret != 0)
1179     goto err;
1180   ret = allocate_cpu_set(&cpu_saved_affinity_set, &cpu_saved_affinity_setsize);
1181   if (ret != 0)
1182     goto err;
1183
1184   ret = for_all_proc_cpus(mark_cpu_present);
1185   if (ret != 0)
1186     goto err;
1187
1188   /*
1189    * For online cpus
1190    * find max_core_id, max_package_id
1191    */
1192   for (unsigned int i = 0; i <= topology.max_cpu_id; ++i) {
1193     unsigned int num_threads;
1194     struct cpu_topology *cpu = &topology.cpus[i];
1195
1196     if (cpu_is_not_present(i)) {
1197       WARNING("turbostat plugin: cpu%d NOT PRESENT", i);
1198       continue;
1199     }
1200
1201     ret = parse_int_file(
1202         "/sys/devices/system/cpu/cpu%d/topology/physical_package_id", i);
1203     if (ret < 0)
1204       goto err;
1205     else
1206       cpu->package_id = (unsigned int)ret;
1207     if (cpu->package_id > max_package_id)
1208       max_package_id = cpu->package_id;
1209
1210     ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", i);
1211     if (ret < 0)
1212       goto err;
1213     else
1214       cpu->core_id = (unsigned int)ret;
1215     if (cpu->core_id > max_core_id)
1216       max_core_id = cpu->core_id;
1217     ret = parse_int_file(
1218         "/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", i);
1219     if (ret < 0)
1220       goto err;
1221     else if ((unsigned int)ret == i)
1222       cpu->first_core_in_package = 1;
1223
1224     ret = get_threads_on_core(i);
1225     if (ret < 0)
1226       goto err;
1227     else
1228       num_threads = (unsigned int)ret;
1229     if (num_threads > max_threads)
1230       max_threads = num_threads;
1231     ret = parse_int_file(
1232         "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", i);
1233     if (ret < 0)
1234       goto err;
1235     else if ((unsigned int)ret == i)
1236       cpu->first_thread_in_core = 1;
1237
1238     DEBUG("turbostat plugin: cpu %d pkg %d core %d\n", i, cpu->package_id,
1239           cpu->core_id);
1240   }
1241   /* Num is max + 1 (need to count 0) */
1242   topology.num_packages = max_package_id + 1;
1243   topology.num_cores = max_core_id + 1;
1244   topology.num_threads = max_threads;
1245
1246   return 0;
1247 err:
1248   free(topology.cpus);
1249   return ret;
1250 }
1251
1252 /************************
1253  * Main alloc/init/free *
1254  ************************/
1255
1256 static int allocate_counters(struct thread_data **threads,
1257                              struct core_data **cores,
1258                              struct pkg_data **packages) {
1259   unsigned int total_threads, total_cores;
1260
1261   if ((topology.num_threads == 0) || (topology.num_cores == 0) ||
1262       (topology.num_packages == 0)) {
1263     ERROR(
1264         "turbostat plugin: Invalid topology: %u threads, %u cores, %u packages",
1265         topology.num_threads, topology.num_cores, topology.num_packages);
1266     return -1;
1267   }
1268
1269   total_threads =
1270       topology.num_threads * topology.num_cores * topology.num_packages;
1271   *threads = calloc(total_threads, sizeof(struct thread_data));
1272   if (*threads == NULL) {
1273     ERROR("turbostat plugin: calloc failed");
1274     return -1;
1275   }
1276
1277   for (unsigned int i = 0; i < total_threads; ++i)
1278     (*threads)[i].cpu_id = topology.max_cpu_id + 1;
1279
1280   total_cores = topology.num_cores * topology.num_packages;
1281   *cores = calloc(total_cores, sizeof(struct core_data));
1282   if (*cores == NULL) {
1283     ERROR("turbostat plugin: calloc failed");
1284     sfree(threads);
1285     return -1;
1286   }
1287
1288   *packages = calloc(topology.num_packages, sizeof(struct pkg_data));
1289   if (*packages == NULL) {
1290     ERROR("turbostat plugin: calloc failed");
1291     sfree(cores);
1292     sfree(threads);
1293     return -1;
1294   }
1295
1296   return 0;
1297 }
1298
1299 static void init_counter(struct thread_data *thread_base,
1300                          struct core_data *core_base, struct pkg_data *pkg_base,
1301                          unsigned int cpu_id) {
1302   struct thread_data *t;
1303   struct core_data *c;
1304   struct pkg_data *p;
1305   struct cpu_topology *cpu = &topology.cpus[cpu_id];
1306
1307   t = GET_THREAD(thread_base, !(cpu->first_thread_in_core), cpu->core_id,
1308                  cpu->package_id);
1309   c = GET_CORE(core_base, cpu->core_id, cpu->package_id);
1310   p = GET_PKG(pkg_base, cpu->package_id);
1311
1312   t->cpu_id = cpu_id;
1313   if (cpu->first_thread_in_core)
1314     t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
1315   if (cpu->first_core_in_package)
1316     t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
1317
1318   c->core_id = cpu->core_id;
1319   p->package_id = cpu->package_id;
1320 }
1321
1322 static void initialize_counters(void) {
1323   for (unsigned int cpu_id = 0; cpu_id <= topology.max_cpu_id; ++cpu_id) {
1324     if (cpu_is_not_present(cpu_id))
1325       continue;
1326     init_counter(EVEN_COUNTERS, cpu_id);
1327     init_counter(ODD_COUNTERS, cpu_id);
1328     init_counter(DELTA_COUNTERS, cpu_id);
1329   }
1330 }
1331
1332 static void free_all_buffers(void) {
1333   allocated = 0;
1334   initialized = 0;
1335
1336   CPU_FREE(cpu_present_set);
1337   cpu_present_set = NULL;
1338   cpu_present_setsize = 0;
1339
1340   CPU_FREE(cpu_affinity_set);
1341   cpu_affinity_set = NULL;
1342   cpu_affinity_setsize = 0;
1343
1344   CPU_FREE(cpu_saved_affinity_set);
1345   cpu_saved_affinity_set = NULL;
1346   cpu_saved_affinity_setsize = 0;
1347
1348   free(thread_even);
1349   free(core_even);
1350   free(package_even);
1351
1352   thread_even = NULL;
1353   core_even = NULL;
1354   package_even = NULL;
1355
1356   free(thread_odd);
1357   free(core_odd);
1358   free(package_odd);
1359
1360   thread_odd = NULL;
1361   core_odd = NULL;
1362   package_odd = NULL;
1363
1364   free(thread_delta);
1365   free(core_delta);
1366   free(package_delta);
1367
1368   thread_delta = NULL;
1369   core_delta = NULL;
1370   package_delta = NULL;
1371 }
1372
1373 /**********************
1374  * Collectd functions *
1375  **********************/
1376
1377 #define DO_OR_GOTO_ERR(something)                                              \
1378   do {                                                                         \
1379     ret = (something);                                                         \
1380     if (ret < 0)                                                               \
1381       goto err;                                                                \
1382   } while (0)
1383
1384 static int setup_all_buffers(void) {
1385   int ret;
1386
1387   DO_OR_GOTO_ERR(topology_probe());
1388   DO_OR_GOTO_ERR(allocate_counters(&thread_even, &core_even, &package_even));
1389   DO_OR_GOTO_ERR(allocate_counters(&thread_odd, &core_odd, &package_odd));
1390   DO_OR_GOTO_ERR(allocate_counters(&thread_delta, &core_delta, &package_delta));
1391   initialize_counters();
1392   DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, EVEN_COUNTERS));
1393   DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, ODD_COUNTERS));
1394
1395   allocated = 1;
1396   return 0;
1397 err:
1398   free_all_buffers();
1399   return ret;
1400 }
1401
1402 static int turbostat_read(void) {
1403   int ret;
1404
1405   if (!allocated) {
1406     if ((ret = setup_all_buffers()) < 0)
1407       return ret;
1408   }
1409
1410   if (for_all_proc_cpus(cpu_is_not_present)) {
1411     free_all_buffers();
1412     if ((ret = setup_all_buffers()) < 0)
1413       return ret;
1414     if (for_all_proc_cpus(cpu_is_not_present)) {
1415       ERROR("turbostat plugin: CPU appeared just after "
1416             "initialization");
1417       return -1;
1418     }
1419   }
1420
1421   /* Saving the scheduling affinity, as it will be modified by get_counters */
1422   if (sched_getaffinity(0, cpu_saved_affinity_setsize,
1423                         cpu_saved_affinity_set) != 0) {
1424     ERROR("turbostat plugin: Unable to save the CPU affinity");
1425     return -1;
1426   }
1427
1428   if (!initialized) {
1429     if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
1430       goto out;
1431     time_even = cdtime();
1432     is_even = 1;
1433     initialized = 1;
1434     ret = 0;
1435     goto out;
1436   }
1437
1438   if (is_even) {
1439     if ((ret = for_all_cpus(get_counters, ODD_COUNTERS)) < 0)
1440       goto out;
1441     time_odd = cdtime();
1442     is_even = 0;
1443     time_delta = time_odd - time_even;
1444     if ((ret = for_all_cpus_delta(ODD_COUNTERS, EVEN_COUNTERS)) < 0)
1445       goto out;
1446     if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
1447       goto out;
1448   } else {
1449     if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
1450       goto out;
1451     time_even = cdtime();
1452     is_even = 1;
1453     time_delta = time_even - time_odd;
1454     if ((ret = for_all_cpus_delta(EVEN_COUNTERS, ODD_COUNTERS)) < 0)
1455       goto out;
1456     if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
1457       goto out;
1458   }
1459   ret = 0;
1460 out:
1461   /*
1462    * Let's restore the affinity
1463    * This might fail if the number of CPU changed, but we can't do anything in
1464    * that case..
1465    */
1466   (void)sched_setaffinity(0, cpu_saved_affinity_setsize,
1467                           cpu_saved_affinity_set);
1468   return ret;
1469 }
1470
1471 static int check_permissions(void) {
1472
1473   if (getuid() == 0) {
1474     /* We have everything we need */
1475     return 0;
1476 #if !defined(HAVE_SYS_CAPABILITY_H) && !defined(CAP_SYS_RAWIO)
1477   } else {
1478     ERROR("turbostat plugin: Initialization failed: this plugin "
1479           "requires collectd to run as root");
1480     return -1;
1481   }
1482 #else  /* HAVE_SYS_CAPABILITY_H && CAP_SYS_RAWIO */
1483   }
1484
1485   int ret = 0;
1486
1487   if (check_capability(CAP_SYS_RAWIO) != 0) {
1488     WARNING("turbostat plugin: Collectd doesn't have the "
1489             "CAP_SYS_RAWIO capability. If you don't want to run "
1490             "collectd as root, try running \"setcap "
1491             "cap_sys_rawio=ep\" on collectd binary");
1492     ret = -1;
1493   }
1494
1495   if (euidaccess("/dev/cpu/0/msr", R_OK)) {
1496     WARNING("turbostat plugin: Collectd cannot open "
1497             "/dev/cpu/0/msr. If you don't want to run collectd as "
1498             "root, you need to change the ownership (chown) and "
1499             "permissions on /dev/cpu/*/msr to allow such access");
1500     ret = -1;
1501   }
1502
1503   if (ret != 0)
1504     ERROR("turbostat plugin: Initialization failed: this plugin "
1505           "requires collectd to either to run as root or give "
1506           "collectd a special capability (CAP_SYS_RAWIO) and read "
1507           "access to /dev/cpu/*/msr (see previous warnings)");
1508   return ret;
1509 #endif /* HAVE_SYS_CAPABILITY_H && CAP_SYS_RAWIO */
1510 }
1511
1512 static int turbostat_init(void) {
1513   struct stat sb;
1514   int ret;
1515
1516   if (stat("/dev/cpu/0/msr", &sb)) {
1517     ERROR("turbostat plugin: Initialization failed: /dev/cpu/0/msr "
1518           "does not exist while the CPU supports MSR. You may be "
1519           "missing the corresponding kernel module, please try '# "
1520           "modprobe msr'");
1521     return -1;
1522   }
1523
1524   DO_OR_GOTO_ERR(check_permissions());
1525
1526   DO_OR_GOTO_ERR(probe_cpu());
1527
1528   DO_OR_GOTO_ERR(setup_all_buffers());
1529
1530   plugin_register_read(PLUGIN_NAME, turbostat_read);
1531
1532   return 0;
1533 err:
1534   free_all_buffers();
1535   return ret;
1536 }
1537
1538 static int turbostat_config(const char *key, const char *value) {
1539   long unsigned int tmp_val;
1540   char *end;
1541
1542   if (strcasecmp("CoreCstates", key) == 0) {
1543     tmp_val = strtoul(value, &end, 0);
1544     if (*end != '\0' || tmp_val > UINT_MAX) {
1545       ERROR("turbostat plugin: Invalid CoreCstates '%s'", value);
1546       return -1;
1547     }
1548     config_core_cstate = (unsigned int)tmp_val;
1549     apply_config_core_cstate = 1;
1550   } else if (strcasecmp("PackageCstates", key) == 0) {
1551     tmp_val = strtoul(value, &end, 0);
1552     if (*end != '\0' || tmp_val > UINT_MAX) {
1553       ERROR("turbostat plugin: Invalid PackageCstates '%s'", value);
1554       return -1;
1555     }
1556     config_pkg_cstate = (unsigned int)tmp_val;
1557     apply_config_pkg_cstate = 1;
1558   } else if (strcasecmp("SystemManagementInterrupt", key) == 0) {
1559     config_smi = IS_TRUE(value);
1560     apply_config_smi = 1;
1561   } else if (strcasecmp("DigitalTemperatureSensor", key) == 0) {
1562     config_dts = IS_TRUE(value);
1563     apply_config_dts = 1;
1564   } else if (strcasecmp("PackageThermalManagement", key) == 0) {
1565     config_ptm = IS_TRUE(value);
1566     apply_config_ptm = 1;
1567   } else if (strcasecmp("RunningAveragePowerLimit", key) == 0) {
1568     tmp_val = strtoul(value, &end, 0);
1569     if (*end != '\0' || tmp_val > UINT_MAX) {
1570       ERROR("turbostat plugin: Invalid RunningAveragePowerLimit '%s'", value);
1571       return -1;
1572     }
1573     config_rapl = (unsigned int)tmp_val;
1574     apply_config_rapl = 1;
1575   } else if (strcasecmp("TCCActivationTemp", key) == 0) {
1576     tmp_val = strtoul(value, &end, 0);
1577     if (*end != '\0' || tmp_val > UINT_MAX) {
1578       ERROR("turbostat plugin: Invalid TCCActivationTemp '%s'", value);
1579       return -1;
1580     }
1581     tcc_activation_temp = (unsigned int)tmp_val;
1582   } else {
1583     ERROR("turbostat plugin: Invalid configuration option '%s'", key);
1584     return -1;
1585   }
1586   return 0;
1587 }
1588
1589 void module_register(void) {
1590   plugin_register_init(PLUGIN_NAME, turbostat_init);
1591   plugin_register_config(PLUGIN_NAME, turbostat_config, config_keys,
1592                          config_keys_num);
1593 }