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