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