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