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