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