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