19a511152bf29a5780f41b64ffee408c650505b8
[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     case 0x6A: /* ICX Xeon */
992       do_smi = true;
993       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
994       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
995       break;
996     /* Haswell Bridge */
997     case 0x3C: /* HSW */
998     case 0x3F: /* HSW */
999     case 0x46: /* HSW */
1000       do_smi = true;
1001       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1002       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
1003       break;
1004     case 0x45: /* HSW */
1005       do_smi = true;
1006       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1007       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) |
1008                       (1 << 9) | (1 << 10);
1009       break;
1010     /* Broadwell */
1011     case 0x4F: /* BDW */
1012     case 0x56: /* BDX-DE */
1013       do_smi = true;
1014       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1015       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
1016       break;
1017     case 0x3D: /* BDW */
1018       do_smi = true;
1019       do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1020       do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) |
1021                       (1 << 9) | (1 << 10);
1022       break;
1023     default:
1024       do_smi = false;
1025       do_core_cstate = 0;
1026       do_pkg_cstate = 0;
1027       break;
1028     }
1029     switch (model) {
1030     case 0x2A: /* SNB */
1031     case 0x3A: /* IVB */
1032     case 0x3C: /* HSW */
1033     case 0x45: /* HSW */
1034     case 0x46: /* HSW */
1035     case 0x3D: /* BDW */
1036     case 0x5E: /* SKL */
1037       do_rapl = RAPL_PKG | RAPL_CORES | RAPL_GFX;
1038       break;
1039     case 0x3F: /* HSX */
1040     case 0x4F: /* BDX */
1041     case 0x56: /* BDX-DE */
1042       do_rapl = RAPL_PKG | RAPL_DRAM;
1043       do_power_fields = TURBO_PLATFORM | UFS_PLATFORM | PSTATES_PLATFORM;
1044       break;
1045     case 0x2D: /* SNB Xeon */
1046     case 0x3E: /* IVB Xeon */
1047     case 0x55: /* SKX,CLX Xeon */
1048     case 0x6A: /* ICX Xeon */
1049       do_rapl = RAPL_PKG | RAPL_CORES | RAPL_DRAM;
1050       do_power_fields = TURBO_PLATFORM | PSTATES_PLATFORM;
1051       break;
1052     case 0x37: /* BYT */
1053     case 0x4D: /* AVN */
1054       do_rapl = RAPL_PKG | RAPL_CORES;
1055       break;
1056     default:
1057       do_rapl = 0;
1058     }
1059   } else {
1060     ERROR("turbostat plugin: Unsupported CPU (family: %#x, "
1061           "model: %#x)",
1062           family, model);
1063     return -1;
1064   }
1065
1066   /* Override detected values with configuration */
1067   if (apply_config_core_cstate)
1068     do_core_cstate = config_core_cstate;
1069   if (apply_config_pkg_cstate)
1070     do_pkg_cstate = config_pkg_cstate;
1071   if (apply_config_smi)
1072     do_smi = config_smi;
1073   if (apply_config_dts)
1074     do_dts = config_dts;
1075   if (apply_config_ptm)
1076     do_ptm = config_ptm;
1077   if (apply_config_rapl)
1078     do_rapl = config_rapl;
1079
1080   if (do_rapl) {
1081     unsigned long long msr;
1082     if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr))
1083       return 0;
1084
1085     rapl_power_units = 1.0 / (1 << (msr & 0xF));
1086     if (model == 0x37)
1087       rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
1088     else
1089       rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
1090   }
1091
1092   return 0;
1093 }
1094
1095 /********************
1096  * Topology Probing *
1097  ********************/
1098
1099 /*
1100  * Read a single int from a file.
1101  */
1102 static int __attribute__((format(printf, 1, 2)))
1103 parse_int_file(const char *fmt, ...) {
1104   va_list args;
1105   char path[PATH_MAX];
1106   int len;
1107
1108   va_start(args, fmt);
1109   len = vsnprintf(path, sizeof(path), fmt, args);
1110   va_end(args);
1111   if (len < 0 || len >= PATH_MAX) {
1112     ERROR("turbostat plugin: path truncated: '%s'", path);
1113     return -1;
1114   }
1115
1116   value_t v;
1117   if (parse_value_file(path, &v, DS_TYPE_DERIVE) != 0) {
1118     ERROR("turbostat plugin: Parsing \"%s\" failed.", path);
1119     return -1;
1120   }
1121
1122   return (int)v.derive;
1123 }
1124
1125 static int get_threads_on_core(unsigned int cpu) {
1126   char path[80];
1127   FILE *filep;
1128   int sib1, sib2;
1129   int matches;
1130   char character;
1131
1132   snprintf(path, sizeof(path),
1133            "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
1134   filep = fopen(path, "r");
1135   if (!filep) {
1136     ERROR("turbostat plugin: Failed to open '%s'", path);
1137     return -1;
1138   }
1139   /*
1140    * file format:
1141    * if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4)
1142    * otherwinse 1 sibling (self).
1143    */
1144   matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2);
1145
1146   fclose(filep);
1147
1148   if (matches == 3)
1149     return 2;
1150   else
1151     return 1;
1152 }
1153
1154 /*
1155  * run func(cpu) on every cpu in /proc/stat
1156  * return max_cpu number
1157  */
1158 static int __attribute__((warn_unused_result))
1159 for_all_proc_cpus(int(func)(unsigned int)) {
1160   FILE *fp;
1161   unsigned int cpu_num;
1162   int retval;
1163
1164   fp = fopen("/proc/stat", "r");
1165   if (!fp) {
1166     ERROR("turbostat plugin: Failed to open /proc/stat");
1167     return -1;
1168   }
1169
1170   retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
1171   if (retval != 0) {
1172     ERROR("turbostat plugin: Failed to parse /proc/stat");
1173     fclose(fp);
1174     return -1;
1175   }
1176
1177   while (1) {
1178     retval =
1179         fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
1180     if (retval != 1)
1181       break;
1182
1183     retval = func(cpu_num);
1184     if (retval) {
1185       fclose(fp);
1186       return retval;
1187     }
1188   }
1189   fclose(fp);
1190   return 0;
1191 }
1192
1193 /*
1194  * Update the stored topology.max_cpu_id
1195  */
1196 static int update_max_cpu_id(unsigned int cpu) {
1197   if (topology.max_cpu_id < cpu)
1198     topology.max_cpu_id = cpu;
1199   return 0;
1200 }
1201
1202 static int mark_cpu_present(unsigned int cpu) {
1203   CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
1204   return 0;
1205 }
1206
1207 static int __attribute__((warn_unused_result))
1208 allocate_cpu_set(cpu_set_t **set, size_t *size) {
1209   *set = CPU_ALLOC(topology.max_cpu_id + 1);
1210   if (*set == NULL) {
1211     ERROR("turbostat plugin: Unable to allocate CPU state");
1212     return -1;
1213   }
1214   *size = CPU_ALLOC_SIZE(topology.max_cpu_id + 1);
1215   CPU_ZERO_S(*size, *set);
1216   return 0;
1217 }
1218
1219 /*
1220  * Build a local representation of the cpu distribution
1221  */
1222 static int __attribute__((warn_unused_result)) topology_probe(void) {
1223   int ret;
1224   unsigned int max_package_id, max_core_id, max_threads;
1225   max_package_id = max_core_id = max_threads = 0;
1226
1227   /* Clean topology */
1228   free(topology.cpus);
1229   memset(&topology, 0, sizeof(topology));
1230
1231   ret = for_all_proc_cpus(update_max_cpu_id);
1232   if (ret != 0)
1233     goto err;
1234
1235   topology.cpus =
1236       calloc(1, (topology.max_cpu_id + 1) * sizeof(struct cpu_topology));
1237   if (topology.cpus == NULL) {
1238     ERROR("turbostat plugin: Unable to allocate memory for CPU topology");
1239     return -1;
1240   }
1241
1242   ret = allocate_cpu_set(&cpu_present_set, &cpu_present_setsize);
1243   if (ret != 0)
1244     goto err;
1245   ret = allocate_cpu_set(&cpu_affinity_set, &cpu_affinity_setsize);
1246   if (ret != 0)
1247     goto err;
1248   ret = allocate_cpu_set(&cpu_saved_affinity_set, &cpu_saved_affinity_setsize);
1249   if (ret != 0)
1250     goto err;
1251
1252   ret = for_all_proc_cpus(mark_cpu_present);
1253   if (ret != 0)
1254     goto err;
1255
1256   /*
1257    * For online cpus
1258    * find max_core_id, max_package_id
1259    */
1260   for (unsigned int i = 0; i <= topology.max_cpu_id; ++i) {
1261     unsigned int num_threads;
1262     struct cpu_topology *cpu = &topology.cpus[i];
1263
1264     if (cpu_is_not_present(i)) {
1265       WARNING("turbostat plugin: cpu%d NOT PRESENT", i);
1266       continue;
1267     }
1268
1269     ret = parse_int_file(
1270         "/sys/devices/system/cpu/cpu%d/topology/physical_package_id", i);
1271     if (ret < 0)
1272       goto err;
1273     else
1274       cpu->package_id = (unsigned int)ret;
1275     if (cpu->package_id > max_package_id)
1276       max_package_id = cpu->package_id;
1277
1278     ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", i);
1279     if (ret < 0)
1280       goto err;
1281     else
1282       cpu->core_id = (unsigned int)ret;
1283     if (cpu->core_id > max_core_id)
1284       max_core_id = cpu->core_id;
1285     ret = parse_int_file(
1286         "/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", i);
1287     if (ret < 0)
1288       goto err;
1289     else if ((unsigned int)ret == i)
1290       cpu->first_core_in_package = true;
1291
1292     ret = get_threads_on_core(i);
1293     if (ret < 0)
1294       goto err;
1295     else
1296       num_threads = (unsigned int)ret;
1297     if (num_threads > max_threads)
1298       max_threads = num_threads;
1299     ret = parse_int_file(
1300         "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", i);
1301     if (ret < 0)
1302       goto err;
1303     else if ((unsigned int)ret == i)
1304       cpu->first_thread_in_core = true;
1305
1306     DEBUG("turbostat plugin: cpu %d pkg %d core %d\n", i, cpu->package_id,
1307           cpu->core_id);
1308   }
1309   /* Num is max + 1 (need to count 0) */
1310   topology.num_packages = max_package_id + 1;
1311   topology.num_cores = max_core_id + 1;
1312   topology.num_threads = max_threads;
1313
1314   return 0;
1315 err:
1316   free(topology.cpus);
1317   return ret;
1318 }
1319
1320 /************************
1321  * Main alloc/init/free *
1322  ************************/
1323
1324 static int allocate_counters(struct thread_data **threads,
1325                              struct core_data **cores,
1326                              struct pkg_data **packages) {
1327   unsigned int total_threads, total_cores;
1328
1329   if ((topology.num_threads == 0) || (topology.num_cores == 0) ||
1330       (topology.num_packages == 0)) {
1331     ERROR(
1332         "turbostat plugin: Invalid topology: %u threads, %u cores, %u packages",
1333         topology.num_threads, topology.num_cores, topology.num_packages);
1334     return -1;
1335   }
1336
1337   total_threads =
1338       topology.num_threads * topology.num_cores * topology.num_packages;
1339   *threads = calloc(total_threads, sizeof(struct thread_data));
1340   if (*threads == NULL) {
1341     ERROR("turbostat plugin: calloc failed");
1342     return -1;
1343   }
1344
1345   for (unsigned int i = 0; i < total_threads; ++i)
1346     (*threads)[i].cpu_id = topology.max_cpu_id + 1;
1347
1348   total_cores = topology.num_cores * topology.num_packages;
1349   *cores = calloc(total_cores, sizeof(struct core_data));
1350   if (*cores == NULL) {
1351     ERROR("turbostat plugin: calloc failed");
1352     sfree(*threads);
1353     return -1;
1354   }
1355
1356   *packages = calloc(topology.num_packages, sizeof(struct pkg_data));
1357   if (*packages == NULL) {
1358     ERROR("turbostat plugin: calloc failed");
1359     sfree(*cores);
1360     sfree(*threads);
1361     return -1;
1362   }
1363
1364   return 0;
1365 }
1366
1367 static void init_counter(struct thread_data *thread_base,
1368                          struct core_data *core_base, struct pkg_data *pkg_base,
1369                          unsigned int cpu_id) {
1370   struct thread_data *t;
1371   struct core_data *c;
1372   struct pkg_data *p;
1373   struct cpu_topology *cpu = &topology.cpus[cpu_id];
1374
1375   t = GET_THREAD(thread_base, !(cpu->first_thread_in_core), cpu->core_id,
1376                  cpu->package_id);
1377   c = GET_CORE(core_base, cpu->core_id, cpu->package_id);
1378   p = GET_PKG(pkg_base, cpu->package_id);
1379
1380   t->cpu_id = cpu_id;
1381   if (cpu->first_thread_in_core)
1382     t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
1383   if (cpu->first_core_in_package)
1384     t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
1385
1386   c->core_id = cpu->core_id;
1387   p->package_id = cpu->package_id;
1388 }
1389
1390 static void initialize_counters(void) {
1391   for (unsigned int cpu_id = 0; cpu_id <= topology.max_cpu_id; ++cpu_id) {
1392     if (cpu_is_not_present(cpu_id))
1393       continue;
1394     init_counter(EVEN_COUNTERS, cpu_id);
1395     init_counter(ODD_COUNTERS, cpu_id);
1396     init_counter(DELTA_COUNTERS, cpu_id);
1397   }
1398 }
1399
1400 static void free_all_buffers(void) {
1401   allocated = false;
1402   initialized = false;
1403
1404   CPU_FREE(cpu_present_set);
1405   cpu_present_set = NULL;
1406   cpu_present_setsize = 0;
1407
1408   CPU_FREE(cpu_affinity_set);
1409   cpu_affinity_set = NULL;
1410   cpu_affinity_setsize = 0;
1411
1412   CPU_FREE(cpu_saved_affinity_set);
1413   cpu_saved_affinity_set = NULL;
1414   cpu_saved_affinity_setsize = 0;
1415
1416   free(thread_even);
1417   free(core_even);
1418   free(package_even);
1419
1420   thread_even = NULL;
1421   core_even = NULL;
1422   package_even = NULL;
1423
1424   free(thread_odd);
1425   free(core_odd);
1426   free(package_odd);
1427
1428   thread_odd = NULL;
1429   core_odd = NULL;
1430   package_odd = NULL;
1431
1432   free(thread_delta);
1433   free(core_delta);
1434   free(package_delta);
1435
1436   thread_delta = NULL;
1437   core_delta = NULL;
1438   package_delta = NULL;
1439 }
1440
1441   /**********************
1442    * Collectd functions *
1443    **********************/
1444
1445 #define DO_OR_GOTO_ERR(something)                                              \
1446   do {                                                                         \
1447     ret = (something);                                                         \
1448     if (ret < 0)                                                               \
1449       goto err;                                                                \
1450   } while (0)
1451
1452 static int setup_all_buffers(void) {
1453   int ret;
1454
1455   DO_OR_GOTO_ERR(topology_probe());
1456   DO_OR_GOTO_ERR(allocate_counters(&thread_even, &core_even, &package_even));
1457   DO_OR_GOTO_ERR(allocate_counters(&thread_odd, &core_odd, &package_odd));
1458   DO_OR_GOTO_ERR(allocate_counters(&thread_delta, &core_delta, &package_delta));
1459   initialize_counters();
1460   DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, EVEN_COUNTERS));
1461   DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, ODD_COUNTERS));
1462
1463   allocated = true;
1464   return 0;
1465 err:
1466   free_all_buffers();
1467   return ret;
1468 }
1469
1470 static int save_affinity(void) {
1471   if (affinity_policy == policy_restore_affinity) {
1472     /* Try to save the scheduling affinity, as it will be modified by
1473      * get_counters().
1474      */
1475     if (sched_getaffinity(0, cpu_saved_affinity_setsize,
1476                           cpu_saved_affinity_set) != 0)
1477       return -1;
1478   }
1479
1480   return 0;
1481 }
1482
1483 static void restore_affinity(void) {
1484   /* Let's restore the affinity to the value saved in save_affinity */
1485   if (affinity_policy == policy_restore_affinity)
1486     (void)sched_setaffinity(0, cpu_saved_affinity_setsize,
1487                             cpu_saved_affinity_set);
1488   else {
1489     /* reset the affinity to all present cpus */
1490     (void)sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
1491   }
1492 }
1493
1494 static int turbostat_read(void) {
1495   int ret;
1496
1497   if (!allocated) {
1498     if ((ret = setup_all_buffers()) < 0)
1499       return ret;
1500   }
1501
1502   if (for_all_proc_cpus(cpu_is_not_present)) {
1503     free_all_buffers();
1504     if ((ret = setup_all_buffers()) < 0)
1505       return ret;
1506     if (for_all_proc_cpus(cpu_is_not_present)) {
1507       ERROR("turbostat plugin: CPU appeared just after "
1508             "initialization");
1509       return -1;
1510     }
1511   }
1512
1513   if (save_affinity() != 0) {
1514     ERROR("turbostat plugin: Unable to save the CPU affinity. Please read the "
1515           "docs about RestoreAffinityPolicy option.");
1516     return -1;
1517   }
1518
1519   if (!initialized) {
1520     if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
1521       goto out;
1522     time_even = cdtime();
1523     is_even = true;
1524     initialized = true;
1525     ret = 0;
1526     goto out;
1527   }
1528
1529   if (is_even) {
1530     if ((ret = for_all_cpus(get_counters, ODD_COUNTERS)) < 0)
1531       goto out;
1532     time_odd = cdtime();
1533     is_even = false;
1534     time_delta = time_odd - time_even;
1535     if ((ret = for_all_cpus_delta(ODD_COUNTERS, EVEN_COUNTERS)) < 0)
1536       goto out;
1537     if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
1538       goto out;
1539   } else {
1540     if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
1541       goto out;
1542     time_even = cdtime();
1543     is_even = true;
1544     time_delta = time_even - time_odd;
1545     if ((ret = for_all_cpus_delta(EVEN_COUNTERS, ODD_COUNTERS)) < 0)
1546       goto out;
1547     if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
1548       goto out;
1549   }
1550   ret = 0;
1551 out:
1552   restore_affinity();
1553
1554   return ret;
1555 }
1556
1557 static int check_permissions(void) {
1558
1559   if (getuid() == 0) {
1560     /* We have everything we need */
1561     return 0;
1562 #if !defined(HAVE_SYS_CAPABILITY_H) && !defined(CAP_SYS_RAWIO)
1563   } else {
1564     ERROR("turbostat plugin: Initialization failed: this plugin "
1565           "requires collectd to run as root");
1566     return -1;
1567   }
1568 #else  /* HAVE_SYS_CAPABILITY_H && CAP_SYS_RAWIO */
1569   }
1570
1571   int ret = 0;
1572
1573   if (check_capability(CAP_SYS_RAWIO) != 0) {
1574     WARNING("turbostat plugin: Collectd doesn't have the "
1575             "CAP_SYS_RAWIO capability. If you don't want to run "
1576             "collectd as root, try running \"setcap "
1577             "cap_sys_rawio=ep\" on collectd binary");
1578     ret = -1;
1579   }
1580
1581   if (euidaccess("/dev/cpu/0/msr", R_OK)) {
1582     WARNING("turbostat plugin: Collectd cannot open "
1583             "/dev/cpu/0/msr. If you don't want to run collectd as "
1584             "root, you need to change the ownership (chown) and "
1585             "permissions on /dev/cpu/*/msr to allow such access");
1586     ret = -1;
1587   }
1588
1589   if (ret != 0)
1590     ERROR("turbostat plugin: Initialization failed: this plugin "
1591           "requires collectd to either to run as root or give "
1592           "collectd a special capability (CAP_SYS_RAWIO) and read "
1593           "access to /dev/cpu/*/msr (see previous warnings)");
1594   return ret;
1595 #endif /* HAVE_SYS_CAPABILITY_H && CAP_SYS_RAWIO */
1596 }
1597
1598 static int turbostat_init(void) {
1599   struct stat sb;
1600   int ret;
1601
1602   if (stat("/dev/cpu/0/msr", &sb)) {
1603     ERROR("turbostat plugin: Initialization failed: /dev/cpu/0/msr "
1604           "does not exist while the CPU supports MSR. You may be "
1605           "missing the corresponding kernel module, please try '# "
1606           "modprobe msr'");
1607     return -1;
1608   }
1609
1610   DO_OR_GOTO_ERR(check_permissions());
1611
1612   DO_OR_GOTO_ERR(probe_cpu());
1613
1614   DO_OR_GOTO_ERR(setup_all_buffers());
1615
1616   plugin_register_read(PLUGIN_NAME, turbostat_read);
1617
1618   return 0;
1619 err:
1620   free_all_buffers();
1621   return ret;
1622 }
1623
1624 static int turbostat_config(const char *key, const char *value) {
1625   long unsigned int tmp_val;
1626   char *end;
1627
1628   if (strcasecmp("CoreCstates", key) == 0) {
1629     tmp_val = strtoul(value, &end, 0);
1630     if (*end != '\0' || tmp_val > UINT_MAX) {
1631       ERROR("turbostat plugin: Invalid CoreCstates '%s'", value);
1632       return -1;
1633     }
1634     config_core_cstate = (unsigned int)tmp_val;
1635     apply_config_core_cstate = true;
1636   } else if (strcasecmp("PackageCstates", key) == 0) {
1637     tmp_val = strtoul(value, &end, 0);
1638     if (*end != '\0' || tmp_val > UINT_MAX) {
1639       ERROR("turbostat plugin: Invalid PackageCstates '%s'", value);
1640       return -1;
1641     }
1642     config_pkg_cstate = (unsigned int)tmp_val;
1643     apply_config_pkg_cstate = true;
1644   } else if (strcasecmp("SystemManagementInterrupt", key) == 0) {
1645     config_smi = IS_TRUE(value);
1646     apply_config_smi = true;
1647   } else if (strcasecmp("DigitalTemperatureSensor", key) == 0) {
1648     config_dts = IS_TRUE(value);
1649     apply_config_dts = true;
1650   } else if (strcasecmp("PackageThermalManagement", key) == 0) {
1651     config_ptm = IS_TRUE(value);
1652     apply_config_ptm = true;
1653   } else if (strcasecmp("LogicalCoreNames", key) == 0) {
1654     config_lcn = IS_TRUE(value);
1655   } else if (strcasecmp("RunningAveragePowerLimit", key) == 0) {
1656     tmp_val = strtoul(value, &end, 0);
1657     if (*end != '\0' || tmp_val > UINT_MAX) {
1658       ERROR("turbostat plugin: Invalid RunningAveragePowerLimit '%s'", value);
1659       return -1;
1660     }
1661     config_rapl = (unsigned int)tmp_val;
1662     apply_config_rapl = true;
1663   } else if (strcasecmp("TCCActivationTemp", key) == 0) {
1664     tmp_val = strtoul(value, &end, 0);
1665     if (*end != '\0' || tmp_val > UINT_MAX) {
1666       ERROR("turbostat plugin: Invalid TCCActivationTemp '%s'", value);
1667       return -1;
1668     }
1669     tcc_activation_temp = (unsigned int)tmp_val;
1670   } else if (strcasecmp("RestoreAffinityPolicy", key) == 0) {
1671     if (strcasecmp("Restore", value) == 0)
1672       affinity_policy = policy_restore_affinity;
1673     else if (strcasecmp("AllCPUs", value) == 0)
1674       affinity_policy = policy_allcpus_affinity;
1675     else {
1676       ERROR("turbostat plugin: Invalid RestoreAffinityPolicy '%s'", value);
1677       return -1;
1678     }
1679   } else {
1680     ERROR("turbostat plugin: Invalid configuration option '%s'", key);
1681     return -1;
1682   }
1683   return 0;
1684 }
1685
1686 void module_register(void) {
1687   plugin_register_init(PLUGIN_NAME, turbostat_init);
1688   plugin_register_config(PLUGIN_NAME, turbostat_config, config_keys,
1689                          config_keys_num);
1690 }