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