2 * turbostat -- Log CPU frequency and C-state residency
3 * on modern Intel turbo-capable processors for collectd.
5 * Based on the 'turbostat' tool of the Linux kernel, found at
6 * linux/tools/power/x86/turbostat/turbostat.c:
8 * Copyright (c) 2013 Intel Corporation.
9 * Len Brown <len.brown@intel.com>
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.
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
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.
24 * Ported to collectd by Vincent Brillault <git@lerya.net>
28 * _GNU_SOURCE is required because of the following functions:
41 #include "utils_time.h"
43 #include <asm/msr-index.h>
48 #include <sys/types.h>
51 #include <sys/resource.h>
60 #include <sys/capability.h>
62 #define PLUGIN_NAME "turbostat"
65 * This tool uses the Model-Specific Registers (MSRs) present on Intel processors.
66 * The general description each of these registers, depending on the architecture,
67 * can be found in the IntelĀ® 64 and IA-32 Architectures Software Developer Manual,
68 * Volume 3 Chapter 35.
72 * If set, aperf_mperf_unstable disables a/mperf based stats.
73 * This includes: C0 & C1 states, frequency
75 * This value is automatically set if mperf or aperf go backward
77 static _Bool aperf_mperf_unstable;
80 * Bitmask of the list of core C states supported by the processor.
81 * Currently supported C-states (by this plugin): 3, 6, 7
83 static unsigned int do_core_cstate;
84 static unsigned int config_core_cstate;
85 static _Bool apply_config_core_cstate;
88 * Bitmask of the list of pacages C states supported by the processor.
89 * Currently supported C-states (by this plugin): 2, 3, 6, 7, 8, 9, 10
91 static unsigned int do_pkg_cstate;
92 static unsigned int config_pkg_cstate;
93 static _Bool apply_config_pkg_cstate;
96 * Boolean indicating if the processor supports 'I/O System-Management Interrupt counter'
99 static _Bool config_smi;
100 static _Bool apply_config_smi;
103 * Boolean indicating if the processor supports 'Digital temperature sensor'
104 * This feature enables the monitoring of the temperature of each core
106 * This feature has two limitations:
107 * - if MSR_IA32_TEMPERATURE_TARGET is not supported, the absolute temperature might be wrong
108 * - Temperatures above the tcc_activation_temp are not recorded
111 static _Bool config_dts;
112 static _Bool apply_config_dts;
115 * Boolean indicating if the processor supports 'Package thermal management'
116 * This feature allows the monitoring of the temperature of each package
118 * This feature has two limitations:
119 * - if MSR_IA32_TEMPERATURE_TARGET is not supported, the absolute temperature might be wrong
120 * - Temperatures above the tcc_activation_temp are not recorded
123 static _Bool config_ptm;
124 static _Bool apply_config_ptm;
127 * Thermal Control Circuit Activation Temperature as configured by the user.
128 * This override the automated detection via MSR_IA32_TEMPERATURE_TARGET
129 * and should only be used if the automated detection fails.
131 static unsigned int tcc_activation_temp;
133 static unsigned int do_rapl;
134 static unsigned int config_rapl;
135 static _Bool apply_config_rapl;
136 static double rapl_energy_units;
138 #define RAPL_PKG (1 << 0)
139 /* 0x610 MSR_PKG_POWER_LIMIT */
140 /* 0x611 MSR_PKG_ENERGY_STATUS */
141 #define RAPL_DRAM (1 << 1)
142 /* 0x618 MSR_DRAM_POWER_LIMIT */
143 /* 0x619 MSR_DRAM_ENERGY_STATUS */
144 /* 0x61c MSR_DRAM_POWER_INFO */
145 #define RAPL_CORES (1 << 2)
146 /* 0x638 MSR_PP0_POWER_LIMIT */
147 /* 0x639 MSR_PP0_ENERGY_STATUS */
149 #define RAPL_GFX (1 << 3)
150 /* 0x640 MSR_PP1_POWER_LIMIT */
151 /* 0x641 MSR_PP1_ENERGY_STATUS */
152 /* 0x642 MSR_PP1_POLICY */
153 #define TJMAX_DEFAULT 100
155 static cpu_set_t *cpu_present_set, *cpu_affinity_set, *cpu_saved_affinity_set;
156 static size_t cpu_present_setsize, cpu_affinity_setsize, cpu_saved_affinity_setsize;
158 static struct thread_data {
159 unsigned long long tsc;
160 unsigned long long aperf;
161 unsigned long long mperf;
162 unsigned long long c1;
163 unsigned int smi_count;
166 #define CPU_IS_FIRST_THREAD_IN_CORE 0x2
167 #define CPU_IS_FIRST_CORE_IN_PACKAGE 0x4
168 } *thread_delta, *thread_even, *thread_odd;
170 static struct core_data {
171 unsigned long long c3;
172 unsigned long long c6;
173 unsigned long long c7;
174 unsigned int core_temp_c;
175 unsigned int core_id;
176 } *core_delta, *core_even, *core_odd;
178 static struct pkg_data {
179 unsigned long long pc2;
180 unsigned long long pc3;
181 unsigned long long pc6;
182 unsigned long long pc7;
183 unsigned long long pc8;
184 unsigned long long pc9;
185 unsigned long long pc10;
186 unsigned int package_id;
187 unsigned int energy_pkg; /* MSR_PKG_ENERGY_STATUS */
188 unsigned int energy_dram; /* MSR_DRAM_ENERGY_STATUS */
189 unsigned int energy_cores; /* MSR_PP0_ENERGY_STATUS */
190 unsigned int energy_gfx; /* MSR_PP1_ENERGY_STATUS */
191 unsigned int tcc_activation_temp;
192 unsigned int pkg_temp_c;
193 } *package_delta, *package_even, *package_odd;
195 #define DELTA_COUNTERS thread_delta, core_delta, package_delta
196 #define ODD_COUNTERS thread_odd, core_odd, package_odd
197 #define EVEN_COUNTERS thread_even, core_even, package_even
198 static _Bool is_even = 1;
200 static _Bool allocated = 0;
201 static _Bool initialized = 0;
203 #define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \
205 (pkg_no) * topology.num_cores * topology.num_threads + \
206 (core_no) * topology.num_threads + \
208 #define GET_CORE(core_base, core_no, pkg_no) \
210 (pkg_no) * topology.num_cores + \
212 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
214 struct cpu_topology {
217 _Bool first_core_in_package;
218 _Bool first_thread_in_core;
221 static struct topology {
226 struct cpu_topology *cpus;
229 static cdtime_t time_even, time_odd, time_delta;
231 static const char *config_keys[] =
235 "SystemManagementInterrupt",
236 "DigitalTemperatureSensor",
237 "PackageThermalManagement",
239 "RunningAveragePowerLimit",
241 static const int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
243 /*****************************
244 * MSR Manipulation helpers *
245 *****************************/
248 * Open a MSR device for reading
249 * Can change the scheduling affinity of the current process if multiple_read is 1
251 static int __attribute__((warn_unused_result))
252 open_msr(int cpu, _Bool multiple_read)
258 * If we need to do multiple read, let's migrate to the CPU
259 * Otherwise, we would lose time calling functions on another CPU
261 * If we are not yet initialized (cpu_affinity_setsize = 0),
262 * we need to skip this optimisation.
264 if (multiple_read && cpu_affinity_setsize) {
265 CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
266 CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
267 if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1) {
268 ERROR("Turbostat plugin: Could not migrate to CPU %d", cpu);
273 ssnprintf(pathname, sizeof(pathname), "/dev/cpu/%d/msr", cpu);
274 fd = open(pathname, O_RDONLY);
276 ERROR("Turbostat plugin: failed to open %s", pathname);
283 * Read a single MSR from an open file descriptor
285 static int __attribute__((warn_unused_result))
286 read_msr(int fd, off_t offset, unsigned long long *msr)
290 retval = pread(fd, msr, sizeof *msr, offset);
292 if (retval != sizeof *msr) {
293 ERROR("Turbostat plugin: MSR offset 0x%llx read failed",
294 (unsigned long long)offset);
301 * Open a MSR device for reading, read the value asked for and close it.
302 * This call will not affect the scheduling affinity of this thread.
304 static int __attribute__((warn_unused_result))
305 get_msr(int cpu, off_t offset, unsigned long long *msr)
310 fd = open_msr(cpu, 0);
313 retval = read_msr(fd, offset, msr);
319 /********************************
320 * Raw data acquisition (1 CPU) *
321 ********************************/
324 * Read every data avalaible for a single CPU
326 * Core data is shared for all threads in one core: extracted only for the first thread
327 * Package data is shared for all core in one package: extracted only for the first thread of the first core
329 * Side effect: migrates to the targeted CPU
331 static int __attribute__((warn_unused_result))
332 get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
335 unsigned long long msr;
339 msr_fd = open_msr(cpu, 1);
343 #define READ_MSR(msr, dst) \
345 if (read_msr(msr_fd, msr, dst)) { \
346 ERROR("Turbostat plugin: Unable to read " #msr); \
352 READ_MSR(MSR_IA32_TSC, &t->tsc);
354 READ_MSR(MSR_IA32_APERF, &t->aperf);
355 READ_MSR(MSR_IA32_MPERF, &t->mperf);
358 READ_MSR(MSR_SMI_COUNT, &msr);
359 t->smi_count = msr & 0xFFFFFFFF;
362 /* collect core counters only for 1st thread in core */
363 if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE)) {
368 if (do_core_cstate & (1 << 3))
369 READ_MSR(MSR_CORE_C3_RESIDENCY, &c->c3);
370 if (do_core_cstate & (1 << 6))
371 READ_MSR(MSR_CORE_C6_RESIDENCY, &c->c6);
372 if (do_core_cstate & (1 << 7))
373 READ_MSR(MSR_CORE_C7_RESIDENCY, &c->c7);
376 READ_MSR(MSR_IA32_THERM_STATUS, &msr);
377 c->core_temp_c = p->tcc_activation_temp - ((msr >> 16) & 0x7F);
380 /* collect package counters only for 1st core in package */
381 if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
386 if (do_pkg_cstate & (1 << 2))
387 READ_MSR(MSR_PKG_C2_RESIDENCY, &p->pc2);
388 if (do_pkg_cstate & (1 << 3))
389 READ_MSR(MSR_PKG_C3_RESIDENCY, &p->pc3);
390 if (do_pkg_cstate & (1 << 6))
391 READ_MSR(MSR_PKG_C6_RESIDENCY, &p->pc6);
392 if (do_pkg_cstate & (1 << 7))
393 READ_MSR(MSR_PKG_C7_RESIDENCY, &p->pc7);
394 if (do_pkg_cstate & (1 << 8))
395 READ_MSR(MSR_PKG_C8_RESIDENCY, &p->pc8);
396 if (do_pkg_cstate & (1 << 9))
397 READ_MSR(MSR_PKG_C9_RESIDENCY, &p->pc9);
398 if (do_pkg_cstate & (1 << 10))
399 READ_MSR(MSR_PKG_C10_RESIDENCY, &p->pc10);
401 if (do_rapl & RAPL_PKG) {
402 READ_MSR(MSR_PKG_ENERGY_STATUS, &msr);
403 p->energy_pkg = msr & 0xFFFFFFFF;
405 if (do_rapl & RAPL_CORES) {
406 READ_MSR(MSR_PP0_ENERGY_STATUS, &msr);
407 p->energy_cores = msr & 0xFFFFFFFF;
409 if (do_rapl & RAPL_DRAM) {
410 READ_MSR(MSR_DRAM_ENERGY_STATUS, &msr);
411 p->energy_dram = msr & 0xFFFFFFFF;
413 if (do_rapl & RAPL_GFX) {
414 READ_MSR(MSR_PP1_ENERGY_STATUS, &msr);
415 p->energy_gfx = msr & 0xFFFFFFFF;
418 READ_MSR(MSR_IA32_PACKAGE_THERM_STATUS, &msr);
419 p->pkg_temp_c = p->tcc_activation_temp - ((msr >> 16) & 0x7F);
428 /**********************************
429 * Evaluating the changes (1 CPU) *
430 **********************************/
433 * Do delta = new - old on 32bits cyclique intergers
435 #define DELTA_WRAP32(delta, new, old) \
439 delta = 0x100000000 + new - old; \
443 * Extract the evolution old->new in delta at a package level
444 * (some are not new-delta, e.g. temperature)
447 delta_package(struct pkg_data *delta, const struct pkg_data *new, const struct pkg_data *old)
449 delta->pc2 = new->pc2 - old->pc2;
450 delta->pc3 = new->pc3 - old->pc3;
451 delta->pc6 = new->pc6 - old->pc6;
452 delta->pc7 = new->pc7 - old->pc7;
453 delta->pc8 = new->pc8 - old->pc8;
454 delta->pc9 = new->pc9 - old->pc9;
455 delta->pc10 = new->pc10 - old->pc10;
456 delta->pkg_temp_c = new->pkg_temp_c;
458 DELTA_WRAP32(delta->energy_pkg, new->energy_pkg, old->energy_pkg);
459 DELTA_WRAP32(delta->energy_cores, new->energy_cores, old->energy_cores);
460 DELTA_WRAP32(delta->energy_gfx, new->energy_gfx, old->energy_gfx);
461 DELTA_WRAP32(delta->energy_dram, new->energy_dram, old->energy_dram);
465 * Extract the evolution old->new in delta at a core level
466 * (some are not new-delta, e.g. temperature)
469 delta_core(struct core_data *delta, const struct core_data *new, const struct core_data *old)
471 delta->c3 = new->c3 - old->c3;
472 delta->c6 = new->c6 - old->c6;
473 delta->c7 = new->c7 - old->c7;
474 delta->core_temp_c = new->core_temp_c;
478 * Extract the evolution old->new in delta at a package level
479 * core_delta is required for c1 estimation (tsc - c0 - all core cstates)
481 static inline int __attribute__((warn_unused_result))
482 delta_thread(struct thread_data *delta, const struct thread_data *new, const struct thread_data *old,
483 const struct core_data *core_delta)
485 delta->tsc = new->tsc - old->tsc;
487 /* check for TSC < 1 Mcycles over interval */
488 if (delta->tsc < (1000 * 1000)) {
489 WARNING("Turbostat plugin: Insanely slow TSC rate, TSC stops "
490 "in idle? You can disable all c-states by booting with"
491 " 'idle=poll' or just the deep ones with"
492 " 'processor.max_cstate=1'");
496 delta->c1 = new->c1 - old->c1;
498 if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
499 delta->aperf = new->aperf - old->aperf;
500 delta->mperf = new->mperf - old->mperf;
502 if (!aperf_mperf_unstable) {
503 WARNING("Turbostat plugin: APERF or MPERF went "
504 "backwards. Frequency results do not cover "
505 "the entire interval. Fix this by running "
506 "Linux-2.6.30 or later.");
508 aperf_mperf_unstable = 1;
513 * As counter collection is not atomic,
514 * it is possible for mperf's non-halted cycles + idle states
515 * to exceed TSC's all cycles: show c1 = 0% in that case.
517 if ((delta->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > delta->tsc)
520 /* normal case, derive c1 */
521 delta->c1 = delta->tsc - delta->mperf - core_delta->c3
522 - core_delta->c6 - core_delta->c7;
525 if (delta->mperf == 0) {
526 WARNING("Turbostat plugin: cpu%d MPERF 0!", old->cpu_id);
527 delta->mperf = 1; /* divide by 0 protection */
531 delta->smi_count = new->smi_count - old->smi_count;
536 /**********************************
537 * Submitting the results (1 CPU) *
538 **********************************/
541 * Submit one gauge value
544 turbostat_submit (const char *plugin_instance,
545 const char *type, const char *type_instance,
548 value_list_t vl = VALUE_LIST_INIT;
554 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
555 sstrncpy (vl.plugin, PLUGIN_NAME, sizeof (vl.plugin));
556 if (plugin_instance != NULL)
557 sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
558 sstrncpy (vl.type, type, sizeof (vl.type));
559 if (type_instance != NULL)
560 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
562 plugin_dispatch_values (&vl);
566 * Submit every data for a single CPU
568 * Core data is shared for all threads in one core: submitted only for the first thread
569 * Package data is shared for all core in one package: submitted only for the first thread of the first core
572 submit_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
574 char name[DATA_MAX_NAME_LEN];
575 double interval_float;
577 interval_float = CDTIME_T_TO_DOUBLE(time_delta);
579 ssnprintf(name, sizeof(name), "cpu%02d", t->cpu_id);
581 if (!aperf_mperf_unstable)
582 turbostat_submit(name, "percent", "c0", 100.0 * t->mperf/t->tsc);
583 if (!aperf_mperf_unstable)
584 turbostat_submit(name, "percent", "c1", 100.0 * t->c1/t->tsc);
586 turbostat_submit("Average", "frequency", name, 1.0 / 1000000 * t->aperf / interval_float);
588 if ((!aperf_mperf_unstable) || (!(t->aperf > t->tsc || t->mperf > t->tsc)))
589 turbostat_submit("Buzy", "frequency", name, 1.0 * t->tsc / 1000000 * t->aperf / t->mperf / interval_float);
591 /* Sanity check (should stay stable) */
592 turbostat_submit("TSC", "gauge", name, 1.0 * t->tsc / 1000000 / interval_float);
596 turbostat_submit(NULL, "current", name, t->smi_count);
598 /* submit per-core data only for 1st thread in core */
599 if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
602 ssnprintf(name, sizeof(name), "core%02d", c->core_id);
604 if (do_core_cstate & (1 << 3))
605 turbostat_submit(name, "percent", "c3", 100.0 * c->c3/t->tsc);
606 if (do_core_cstate & (1 << 6))
607 turbostat_submit(name, "percent", "c6", 100.0 * c->c6/t->tsc);
608 if (do_core_cstate & (1 << 7))
609 turbostat_submit(name, "percent", "c7", 100.0 * c->c7/t->tsc);
612 turbostat_submit(NULL, "temperature", name, c->core_temp_c);
614 /* submit per-package data only for 1st core in package */
615 if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
618 ssnprintf(name, sizeof(name), "pkg%02d", p->package_id);
621 turbostat_submit(NULL, "temperature", name, p->pkg_temp_c);
623 if (do_pkg_cstate & (1 << 2))
624 turbostat_submit(name, "percent", "pc2", 100.0 * p->pc2/t->tsc);
625 if (do_pkg_cstate & (1 << 3))
626 turbostat_submit(name, "percent", "pc3", 100.0 * p->pc3/t->tsc);
627 if (do_pkg_cstate & (1 << 6))
628 turbostat_submit(name, "percent", "pc6", 100.0 * p->pc6/t->tsc);
629 if (do_pkg_cstate & (1 << 7))
630 turbostat_submit(name, "percent", "pc7", 100.0 * p->pc7/t->tsc);
631 if (do_pkg_cstate & (1 << 8))
632 turbostat_submit(name, "percent", "pc8", 100.0 * p->pc8/t->tsc);
633 if (do_pkg_cstate & (1 << 9))
634 turbostat_submit(name, "percent", "pc9", 100.0 * p->pc9/t->tsc);
635 if (do_pkg_cstate & (1 << 10))
636 turbostat_submit(name, "percent", "pc10", 100.0 * p->pc10/t->tsc);
639 if (do_rapl & RAPL_PKG)
640 turbostat_submit(name, "power", "Pkg_W", p->energy_pkg * rapl_energy_units / interval_float);
641 if (do_rapl & RAPL_CORES)
642 turbostat_submit(name, "power", "Cor_W", p->energy_cores * rapl_energy_units / interval_float);
643 if (do_rapl & RAPL_GFX)
644 turbostat_submit(name, "power", "GFX_W", p->energy_gfx * rapl_energy_units / interval_float);
645 if (do_rapl & RAPL_DRAM)
646 turbostat_submit(name, "power", "RAM_W", p->energy_dram * rapl_energy_units / interval_float);
653 /**********************************
654 * Looping function over all CPUs *
655 **********************************/
658 * Check if a given cpu id is in our compiled list of existing CPUs
661 cpu_is_not_present(int cpu)
663 return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
667 * Loop on all CPUs in topological order
669 * Skip non-present cpus
670 * Return the error code at the first error or 0
672 static int __attribute__((warn_unused_result))
673 for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
674 struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
676 int retval, pkg_no, core_no, thread_no;
678 for (pkg_no = 0; pkg_no < topology.num_packages; ++pkg_no) {
679 for (core_no = 0; core_no < topology.num_cores; ++core_no) {
680 for (thread_no = 0; thread_no < topology.num_threads; ++thread_no) {
681 struct thread_data *t;
685 t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
687 if (cpu_is_not_present(t->cpu_id))
690 c = GET_CORE(core_base, core_no, pkg_no);
691 p = GET_PKG(pkg_base, pkg_no);
693 retval = func(t, c, p);
703 * Dedicated loop: Extract every data evolution for all CPU
705 * Skip non-present cpus
706 * Return the error code at the first error or 0
708 * Core data is shared for all threads in one core: extracted only for the first thread
709 * Package data is shared for all core in one package: extracted only for the first thread of the first core
711 static int __attribute__((warn_unused_result))
712 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,
713 const struct thread_data *thread_old_base, const struct core_data *core_old_base, const struct pkg_data *pkg_old_base)
715 int retval, pkg_no, core_no, thread_no;
717 for (pkg_no = 0; pkg_no < topology.num_packages; ++pkg_no) {
718 for (core_no = 0; core_no < topology.num_cores; ++core_no) {
719 for (thread_no = 0; thread_no < topology.num_threads; ++thread_no) {
720 struct thread_data *t_delta;
721 const struct thread_data *t_old, *t_new;
722 struct core_data *c_delta;
724 /* Get correct pointers for threads */
725 t_delta = GET_THREAD(thread_delta, thread_no, core_no, pkg_no);
726 t_new = GET_THREAD(thread_new_base, thread_no, core_no, pkg_no);
727 t_old = GET_THREAD(thread_old_base, thread_no, core_no, pkg_no);
729 /* Skip threads that disappeared */
730 if (cpu_is_not_present(t_delta->cpu_id))
733 /* c_delta is always required for delta_thread */
734 c_delta = GET_CORE(core_delta, core_no, pkg_no);
736 /* calculate core delta only for 1st thread in core */
737 if (t_new->flags & CPU_IS_FIRST_THREAD_IN_CORE) {
738 const struct core_data *c_old, *c_new;
740 c_new = GET_CORE(core_new_base, core_no, pkg_no);
741 c_old = GET_CORE(core_old_base, core_no, pkg_no);
743 delta_core(c_delta, c_new, c_old);
746 /* Always calculate thread delta */
747 retval = delta_thread(t_delta, t_new, t_old, c_delta);
751 /* calculate package delta only for 1st core in package */
752 if (t_new->flags & CPU_IS_FIRST_CORE_IN_PACKAGE) {
753 struct pkg_data *p_delta;
754 const struct pkg_data *p_old, *p_new;
756 p_delta = GET_PKG(package_delta, pkg_no);
757 p_new = GET_PKG(pkg_new_base, pkg_no);
758 p_old = GET_PKG(pkg_old_base, pkg_no);
760 delta_package(p_delta, p_new, p_old);
774 * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
775 * the Thermal Control Circuit (TCC) activates.
776 * This is usually equal to tjMax.
778 * Older processors do not have this MSR, so there we guess,
779 * but also allow conficuration over-ride with "TCCActivationTemp".
781 * Several MSR temperature values are in units of degrees-C
782 * below this value, including the Digital Thermal Sensor (DTS),
783 * Package Thermal Management Sensor (PTM), and thermal event thresholds.
785 static int __attribute__((warn_unused_result))
786 set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
788 unsigned long long msr;
789 unsigned int target_c_local;
791 /* tcc_activation_temp is used only for dts or ptm */
792 if (!(do_dts || do_ptm))
795 /* this is a per-package concept */
796 if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
799 if (tcc_activation_temp != 0) {
800 p->tcc_activation_temp = tcc_activation_temp;
804 if (get_msr(t->cpu_id, MSR_IA32_TEMPERATURE_TARGET, &msr))
807 target_c_local = (msr >> 16) & 0xFF;
812 p->tcc_activation_temp = target_c_local;
817 p->tcc_activation_temp = TJMAX_DEFAULT;
818 WARNING("Turbostat plugin: cpu%d: Guessing tjMax %d C,"
819 " Please use TCCActivationTemp to specify it.",
820 t->cpu_id, p->tcc_activation_temp);
826 * Identify the functionality of the CPU
828 static int __attribute__((warn_unused_result))
831 unsigned int eax, ebx, ecx, edx, max_level;
832 unsigned int fms, family, model;
835 * - EAX: Maximum Input Value for Basic CPUID Information
836 * - EBX: "Genu" (0x756e6547)
837 * - EDX: "ineI" (0x49656e69)
838 * - ECX: "ntel" (0x6c65746e)
840 max_level = ebx = ecx = edx = 0;
841 __get_cpuid(0, &max_level, &ebx, &ecx, &edx);
842 if (ebx != 0x756e6547 && edx != 0x49656e69 && ecx != 0x6c65746e) {
843 ERROR("Turbostat plugin: Unsupported CPU (not Intel)");
848 * - EAX: Version Information: Type, Family, Model, and Stepping ID
851 * + 12-13: Processor type
852 * + 16-19: Extended Model ID
853 * + 20-27: Extended Family ID
854 * - EDX: Feature Information:
855 * + 5: Support for MSR read/write operations
857 fms = ebx = ecx = edx = 0;
858 __get_cpuid(1, &fms, &ebx, &ecx, &edx);
859 family = (fms >> 8) & 0xf;
860 model = (fms >> 4) & 0xf;
862 family += (fms >> 20) & 0xf;
863 if (family == 6 || family == 0xf)
864 model += ((fms >> 16) & 0xf) << 4;
865 if (!(edx & (1 << 5))) {
866 ERROR("Turbostat plugin: Unsupported CPU (no MSR support)");
873 * + 0: Digital temperature sensor is supported if set
874 * + 6: Package thermal management is supported if set
876 * + 0: Hardware Coordination Feedback Capability (Presence of IA32_MPERF and IA32_APERF).
877 * + 3: The processor supports performance-energy bias preference if set.
878 * It also implies the presence of a new architectural MSR called IA32_ENERGY_PERF_BIAS
880 * This check is valid for both Intel and AMD
882 eax = ebx = ecx = edx = 0;
883 __get_cpuid(0x6, &eax, &ebx, &ecx, &edx);
884 do_dts = eax & (1 << 0);
885 do_ptm = eax & (1 << 6);
886 if (!(ecx & (1 << 0))) {
887 ERROR("Turbostat plugin: Unsupported CPU (No APERF)");
892 * Enable or disable C states depending on the model and family
900 do_pkg_cstate = (1 << 2) | (1 << 4) | (1 << 6);
906 do_core_cstate = (1 << 1) | (1 << 6);
907 do_pkg_cstate = (1 << 6);
910 case 0x1A: /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
911 case 0x1E: /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
912 case 0x1F: /* Core i7 and i5 Processor - Nehalem */
913 case 0x2E: /* Nehalem-EX Xeon - Beckton */
915 do_core_cstate = (1 << 3) | (1 << 6);
916 do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
919 case 0x25: /* Westmere Client - Clarkdale, Arrandale */
920 case 0x2C: /* Westmere EP - Gulftown */
921 case 0x2F: /* Westmere-EX Xeon - Eagleton */
923 do_core_cstate = (1 << 3) | (1 << 6);
924 do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
928 case 0x2D: /* SNB Xeon */
930 do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
931 do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
935 case 0x3E: /* IVB Xeon */
937 do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
938 do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
945 do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
946 do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
950 do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
951 do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10);
955 case 0x56: /* BDX-DE */
957 do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
958 do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
962 do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
963 do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10);
978 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_GFX;
982 case 0x56: /* BDX-DE */
983 do_rapl = RAPL_PKG | RAPL_DRAM ;
985 case 0x2D: /* SNB Xeon */
986 case 0x3E: /* IVB Xeon */
987 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_DRAM;
991 do_rapl = RAPL_PKG | RAPL_CORES;
997 ERROR("Turbostat plugin: Unsupported CPU (family: %#x, "
998 "model: %#x)", family, model);
1002 /* Override detected values with configuration */
1003 if (apply_config_core_cstate)
1004 do_core_cstate = config_core_cstate;
1005 if (apply_config_pkg_cstate)
1006 do_pkg_cstate = config_pkg_cstate;
1007 if (apply_config_smi)
1008 do_smi = config_smi;
1009 if (apply_config_dts)
1010 do_dts = config_dts;
1011 if (apply_config_ptm)
1012 do_ptm = config_ptm;
1013 if (apply_config_rapl)
1014 do_rapl = config_rapl;
1017 unsigned long long msr;
1018 if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr))
1022 rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
1024 rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
1031 /********************
1032 * Topology Probing *
1033 ********************/
1036 * Read a single int from a file.
1038 static int __attribute__ ((format(printf,1,2)))
1039 parse_int_file(const char *fmt, ...)
1042 char path[PATH_MAX];
1046 va_start(args, fmt);
1047 len = vsnprintf(path, sizeof(path), fmt, args);
1049 if (len < 0 || len >= PATH_MAX) {
1050 ERROR("Turbostat plugin: path truncated: '%s'", path);
1054 filep = fopen(path, "r");
1056 ERROR("Turbostat plugin: Failed to open '%s'", path);
1059 if (fscanf(filep, "%d", &value) != 1) {
1060 ERROR("Turbostat plugin: Failed to parse number from '%s'", path);
1068 get_threads_on_core(int cpu)
1076 ssnprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
1077 filep = fopen(path, "r");
1079 ERROR("Turbostat plugin: Failed to open '%s'", path);
1084 * if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4)
1085 * otherwinse 1 sibling (self).
1087 matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2);
1098 * run func(cpu) on every cpu in /proc/stat
1099 * return max_cpu number
1101 static int __attribute__((warn_unused_result))
1102 for_all_proc_cpus(int (func)(int))
1108 fp = fopen("/proc/stat", "r");
1110 ERROR("Turbostat plugin: Failed to open /proc/stat");
1114 retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
1116 ERROR("Turbostat plugin: Failed to parse /proc/stat");
1122 retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
1126 retval = func(cpu_num);
1137 * Update the stored topology.max_cpu_id
1140 update_max_cpu_id(int cpu)
1142 if (topology.max_cpu_id < cpu)
1143 topology.max_cpu_id = cpu;
1148 mark_cpu_present(int cpu)
1150 CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
1154 static int __attribute__((warn_unused_result))
1155 allocate_cpu_set(cpu_set_t ** set, size_t * size) {
1156 *set = CPU_ALLOC(topology.max_cpu_id + 1);
1158 ERROR("Turbostat plugin: Unable to allocate CPU state");
1161 *size = CPU_ALLOC_SIZE(topology.max_cpu_id + 1);
1162 CPU_ZERO_S(*size, *set);
1167 * Build a local representation of the cpu distribution
1169 static int __attribute__((warn_unused_result))
1174 int max_package_id, max_core_id, max_thread_id;
1175 max_package_id = max_core_id = max_thread_id = 0;
1177 /* Clean topology */
1178 free(topology.cpus);
1179 memset(&topology, 0, sizeof(topology));
1181 ret = for_all_proc_cpus(update_max_cpu_id);
1185 topology.cpus = calloc(1, (topology.max_cpu_id + 1) * sizeof(struct cpu_topology));
1186 if (topology.cpus == NULL) {
1187 ERROR("Turbostat plugin: Unable to allocate memory for CPU topology");
1191 ret = allocate_cpu_set(&cpu_present_set, &cpu_present_setsize);
1194 ret = allocate_cpu_set(&cpu_affinity_set, &cpu_affinity_setsize);
1197 ret = allocate_cpu_set(&cpu_saved_affinity_set, &cpu_saved_affinity_setsize);
1201 ret = for_all_proc_cpus(mark_cpu_present);
1207 * find max_core_id, max_package_id
1209 for (i = 0; i <= topology.max_cpu_id; ++i) {
1211 struct cpu_topology *cpu = &topology.cpus[i];
1213 if (cpu_is_not_present(i)) {
1214 WARNING("Turbostat plugin: cpu%d NOT PRESENT", i);
1218 ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", i);
1222 cpu->package_id = ret;
1223 if (cpu->package_id > max_package_id)
1224 max_package_id = cpu->package_id;
1226 ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", i);
1231 if (cpu->core_id > max_core_id)
1232 max_core_id = cpu->core_id;
1233 ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", i);
1237 cpu->first_core_in_package = 1;
1239 ret = get_threads_on_core(i);
1244 if (num_threads > max_thread_id)
1245 max_thread_id = num_threads;
1246 ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", i);
1250 cpu->first_thread_in_core = 1;
1252 DEBUG("Turbostat plugin: cpu %d pkg %d core %d\n",
1253 i, cpu->package_id, cpu->core_id);
1255 /* Num is max + 1 (need to count 0) */
1256 topology.num_packages = max_package_id + 1;
1257 topology.num_cores = max_core_id + 1;
1258 topology.num_threads = max_thread_id + 1;
1262 free(topology.cpus);
1267 /************************
1268 * Main alloc/init/free *
1269 ************************/
1272 allocate_counters(struct thread_data **threads, struct core_data **cores, struct pkg_data **packages)
1275 int total_threads, total_cores;
1277 total_threads = topology.num_threads * topology.num_cores * topology.num_packages;
1278 *threads = calloc(total_threads, sizeof(struct thread_data));
1279 if (*threads == NULL)
1282 for (i = 0; i < total_threads; ++i)
1283 (*threads)[i].cpu_id = -1;
1285 total_cores = topology.num_cores * topology.num_packages;
1286 *cores = calloc(total_cores, sizeof(struct core_data));
1288 goto err_clean_threads;
1290 for (i = 0; i < total_cores; ++i)
1291 (*cores)[i].core_id = -1;
1293 *packages = calloc(topology.num_packages, sizeof(struct pkg_data));
1294 if (*packages == NULL)
1295 goto err_clean_cores;
1297 for (i = 0; i < topology.num_packages; i++)
1298 (*packages)[i].package_id = i;
1307 ERROR("Turbostat plugin: Failled to allocate memory for counters");
1312 init_counter(struct thread_data *thread_base, struct core_data *core_base,
1313 struct pkg_data *pkg_base, int cpu_id)
1315 struct thread_data *t;
1316 struct core_data *c;
1318 struct cpu_topology *cpu = &topology.cpus[cpu_id];
1320 t = GET_THREAD(thread_base, !(cpu->first_thread_in_core), cpu->core_id, cpu->package_id);
1321 c = GET_CORE(core_base, cpu->core_id, cpu->package_id);
1322 p = GET_PKG(pkg_base, cpu->package_id);
1325 if (cpu->first_thread_in_core)
1326 t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
1327 if (cpu->first_core_in_package)
1328 t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
1330 c->core_id = cpu->core_id;
1331 p->package_id = cpu->package_id;
1335 initialize_counters(void)
1339 for (cpu_id = 0; cpu_id <= topology.max_cpu_id; ++cpu_id) {
1340 if (cpu_is_not_present(cpu_id))
1342 init_counter(EVEN_COUNTERS, cpu_id);
1343 init_counter(ODD_COUNTERS, cpu_id);
1344 init_counter(DELTA_COUNTERS, cpu_id);
1351 free_all_buffers(void)
1356 CPU_FREE(cpu_present_set);
1357 cpu_present_set = NULL;
1358 cpu_present_set = 0;
1360 CPU_FREE(cpu_affinity_set);
1361 cpu_affinity_set = NULL;
1362 cpu_affinity_setsize = 0;
1364 CPU_FREE(cpu_saved_affinity_set);
1365 cpu_saved_affinity_set = NULL;
1366 cpu_saved_affinity_setsize = 0;
1374 package_even = NULL;
1386 free(package_delta);
1388 thread_delta = NULL;
1390 package_delta = NULL;
1394 /**********************
1395 * Collectd functions *
1396 **********************/
1398 #define DO_OR_GOTO_ERR(something) \
1400 ret = (something); \
1405 static int setup_all_buffers(void)
1409 DO_OR_GOTO_ERR(topology_probe());
1410 DO_OR_GOTO_ERR(allocate_counters(&thread_even, &core_even, &package_even));
1411 DO_OR_GOTO_ERR(allocate_counters(&thread_odd, &core_odd, &package_odd));
1412 DO_OR_GOTO_ERR(allocate_counters(&thread_delta, &core_delta, &package_delta));
1413 initialize_counters();
1414 DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, EVEN_COUNTERS));
1415 DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, ODD_COUNTERS));
1425 turbostat_read(void)
1430 if ((ret = setup_all_buffers()) < 0)
1434 if (for_all_proc_cpus(cpu_is_not_present)) {
1436 if ((ret = setup_all_buffers()) < 0)
1438 if (for_all_proc_cpus(cpu_is_not_present)) {
1439 ERROR("Turbostat plugin: CPU appeared just after "
1445 /* Saving the scheduling affinity, as it will be modified by get_counters */
1446 if (sched_getaffinity(0, cpu_saved_affinity_setsize, cpu_saved_affinity_set) != 0) {
1447 ERROR("Turbostat plugin: Unable to save the CPU affinity");
1452 if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
1454 time_even = cdtime();
1462 if ((ret = for_all_cpus(get_counters, ODD_COUNTERS)) < 0)
1464 time_odd = cdtime();
1466 time_delta = time_odd - time_even;
1467 if ((ret = for_all_cpus_delta(ODD_COUNTERS, EVEN_COUNTERS)) < 0)
1469 if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
1472 if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
1474 time_even = cdtime();
1476 time_delta = time_even - time_odd;
1477 if ((ret = for_all_cpus_delta(EVEN_COUNTERS, ODD_COUNTERS)) < 0)
1479 if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
1485 * Let's restore the affinity
1486 * This might fail if the number of CPU changed, but we can't do anything in that case..
1488 (void)sched_setaffinity(0, cpu_saved_affinity_setsize, cpu_saved_affinity_set);
1493 check_permissions(void)
1495 struct __user_cap_header_struct cap_header_data;
1496 cap_user_header_t cap_header = &cap_header_data;
1497 struct __user_cap_data_struct cap_data_data;
1498 cap_user_data_t cap_data = &cap_data_data;
1501 if (getuid() == 0) {
1502 /* We have everything we need */
1506 /* check for CAP_SYS_RAWIO */
1507 cap_header->pid = getpid();
1508 cap_header->version = _LINUX_CAPABILITY_VERSION;
1509 if (capget(cap_header, cap_data) < 0) {
1510 ERROR("Turbostat plugin: capget failed");
1514 if ((cap_data->effective & (1 << CAP_SYS_RAWIO)) == 0) {
1515 WARNING("Turbostat plugin: Collectd doesn't have the "
1516 "CAP_SYS_RAWIO capability. If you don't want to run "
1517 "collectd as root, try running \"setcap "
1518 "cap_sys_rawio=ep\" on collectd binary");
1522 if (euidaccess("/dev/cpu/0/msr", R_OK)) {
1523 WARNING("Turbostat plugin: Collectd cannot open"
1524 "/dev/cpu/0/msr. If you don't want to run collectd as "
1525 "root, you need to change the ownership (chown) and "
1526 "permissions on /dev/cpu/*/msr to allow such access");
1531 ERROR("Turbostat plugin: Initialization failed: this plugin "
1532 "requires collectd to either to run as root or give "
1533 "collectd a special capability (CAP_SYS_RAWIO) and read "
1534 "access to /dev/cpu/*/msr (see previous warnings)");
1539 turbostat_init(void)
1544 if (stat("/dev/cpu/0/msr", &sb)) {
1545 ERROR("Turbostat plugin: Initialization failed: /dev/cpu/0/msr"
1546 " does not exist while the CPU supports MSR. You may be "
1547 "missing the corresponding kernel module, please try '# "
1552 DO_OR_GOTO_ERR(check_permissions());
1554 DO_OR_GOTO_ERR(probe_cpu());
1556 DO_OR_GOTO_ERR(setup_all_buffers());
1558 plugin_register_read(PLUGIN_NAME, turbostat_read);
1567 turbostat_config(const char *key, const char *value)
1569 long unsigned int tmp_val;
1572 if (strcasecmp("CoreCstates", key) == 0) {
1573 tmp_val = strtoul(value, &end, 0);
1574 if (*end != '\0' || tmp_val > UINT_MAX) {
1575 ERROR("Turbostat plugin: Invalid CoreCstates '%s'",
1579 config_core_cstate = (unsigned int) tmp_val;
1580 apply_config_core_cstate = 1;
1581 } else if (strcasecmp("PackageCstates", key) == 0) {
1582 tmp_val = strtoul(value, &end, 0);
1583 if (*end != '\0' || tmp_val > UINT_MAX) {
1584 ERROR("Turbostat plugin: Invalid PackageCstates '%s'",
1588 config_pkg_cstate = (unsigned int) tmp_val;
1589 apply_config_pkg_cstate = 1;
1590 } else if (strcasecmp("SystemManagementInterrupt", key) == 0) {
1591 config_smi = IS_TRUE(value);
1592 apply_config_smi = 1;
1593 } else if (strcasecmp("DigitalTemperatureSensor", key) == 0) {
1594 config_dts = IS_TRUE(value);
1595 apply_config_dts = 1;
1596 } else if (strcasecmp("PackageThermalManagement", key) == 0) {
1597 config_ptm = IS_TRUE(value);
1598 apply_config_ptm = 1;
1599 } else if (strcasecmp("RunningAveragePowerLimit", key) == 0) {
1600 tmp_val = strtoul(value, &end, 0);
1601 if (*end != '\0' || tmp_val > UINT_MAX) {
1602 ERROR("Turbostat plugin: Invalid RunningAveragePowerLimit '%s'",
1606 config_rapl = (unsigned int) tmp_val;
1607 apply_config_rapl = 1;
1608 } else if (strcasecmp("TCCActivationTemp", key) == 0) {
1609 tmp_val = strtoul(value, &end, 0);
1610 if (*end != '\0' || tmp_val > UINT_MAX) {
1611 ERROR("Turbostat plugin: Invalid TCCActivationTemp '%s'",
1615 tcc_activation_temp = (unsigned int) tmp_val;
1617 ERROR("Turbostat plugin: Invalid configuration option '%s'",
1624 void module_register(void)
1626 plugin_register_init(PLUGIN_NAME, turbostat_init);
1627 plugin_register_config(PLUGIN_NAME, turbostat_config, config_keys, config_keys_num);