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