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