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