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