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