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