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