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