Turbostat: Adding some comments
[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                 return -ERR_CANT_READ_PROC_STAT;
782         }
783
784         while (1) {
785                 retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
786                 if (retval != 1)
787                         break;
788
789                 retval = func(cpu_num);
790                 if (retval) {
791                         fclose(fp);
792                         return(retval);
793                 }
794         }
795         fclose(fp);
796         return 0;
797 }
798
799 /*
800  * count_cpus()
801  * remember the last one seen, it will be the max
802  */
803 static int
804 count_cpus(int cpu)
805 {
806         if (topo.max_cpu_num < cpu)
807                 topo.max_cpu_num = cpu;
808
809         topo.num_cpus += 1;
810         return 0;
811 }
812 static int
813 mark_cpu_present(int cpu)
814 {
815         CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
816         return 0;
817 }
818
819
820 static void
821 turbostat_submit (const char *plugin_instance,
822         const char *type, const char *type_instance,
823         gauge_t value)
824 {
825         value_list_t vl = VALUE_LIST_INIT;
826         value_t v;
827
828         v.gauge = value;
829         vl.values = &v;
830         vl.values_len = 1;
831         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
832         sstrncpy (vl.plugin, PLUGIN_NAME, sizeof (vl.plugin));
833         if (plugin_instance != NULL)
834                 sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
835         sstrncpy (vl.type, type, sizeof (vl.type));
836         if (type_instance != NULL)
837                 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
838
839         plugin_dispatch_values (&vl);
840 }
841
842 /*
843  * column formatting convention & formats
844  * package: "pk" 2 columns %2d
845  * core: "cor" 3 columns %3d
846  * CPU: "CPU" 3 columns %3d
847  * Pkg_W: %6.2
848  * Cor_W: %6.2
849  * GFX_W: %5.2
850  * RAM_W: %5.2
851  * GHz: "GHz" 3 columns %3.2
852  * TSC: "TSC" 3 columns %3.2
853  * SMI: "SMI" 4 columns %4d
854  * percentage " %pc3" %6.2
855  * Perf Status percentage: %5.2
856  * "CTMP" 4 columns %4d
857  */
858 static int
859 submit_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
860 {
861         char name[12];
862         double interval_float;
863
864         interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
865
866         ssnprintf(name, sizeof(name), "cpu%02d", t->cpu_id);
867
868         if (!aperf_mperf_unstable)
869                 turbostat_submit(name, "percent", "c0", 100.0 * t->mperf/t->tsc);
870         if (!aperf_mperf_unstable)
871                 turbostat_submit(name, "percent", "c1", 100.0 * t->c1/t->tsc);
872
873         /* GHz */
874         if ((!aperf_mperf_unstable) || (!(t->aperf > t->tsc || t->mperf > t->tsc)))
875                 turbostat_submit(NULL, "frequency", name, 1.0 * t->tsc / 1000000000 * t->aperf / t->mperf / interval_float);
876
877         /* SMI */
878         turbostat_submit(NULL, "current", name, t->smi_count);
879
880         /* print per-core data only for 1st thread in core */
881         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
882                 goto done;
883
884         ssnprintf(name, sizeof(name), "core%02d", c->core_id);
885
886         if (do_core_cstate & (1 << 3))
887                 turbostat_submit(name, "percent", "c3", 100.0 * c->c3/t->tsc);
888         if (do_core_cstate & (1 << 6))
889                 turbostat_submit(name, "percent", "c6", 100.0 * c->c6/t->tsc);
890         if (do_core_cstate & (1 << 7))
891                 turbostat_submit(name, "percent", "c7", 100.0 * c->c7/t->tsc);
892
893         if (do_dts)
894                 turbostat_submit(NULL, "temperature", name, c->core_temp_c);
895
896         /* print per-package data only for 1st core in package */
897         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
898                 goto done;
899
900         ssnprintf(name, sizeof(name), "pkg%02d", p->package_id);
901
902         if (do_ptm)
903                 turbostat_submit(NULL, "temperature", name, p->pkg_temp_c);
904
905         if (do_pkg_cstate & (1 << 2))
906                 turbostat_submit(name, "percent", "pc2", 100.0 * p->pc2/t->tsc);
907         if (do_pkg_cstate & (1 << 3))
908                 turbostat_submit(name, "percent", "pc3", 100.0 * p->pc3/t->tsc);
909         if (do_pkg_cstate & (1 << 6))
910                 turbostat_submit(name, "percent", "pc6", 100.0 * p->pc6/t->tsc);
911         if (do_pkg_cstate & (1 << 7))
912                 turbostat_submit(name, "percent", "pc7", 100.0 * p->pc7/t->tsc);
913         if (do_pkg_cstate & (1 << 8))
914                 turbostat_submit(name, "percent", "pc8", 100.0 * p->pc8/t->tsc);
915         if (do_pkg_cstate & (1 << 9))
916                 turbostat_submit(name, "percent", "pc9", 100.0 * p->pc9/t->tsc);
917         if (do_pkg_cstate & (1 << 10))
918                 turbostat_submit(name, "percent", "pc10", 100.0 * p->pc10/t->tsc);
919
920         if (do_rapl) {
921                 if (do_rapl & RAPL_PKG)
922                         turbostat_submit(name, "power", "Pkg_W", p->energy_pkg * rapl_energy_units / interval_float);
923                 if (do_rapl & RAPL_CORES)
924                         turbostat_submit(name, "power", "Cor_W", p->energy_cores * rapl_energy_units / interval_float);
925                 if (do_rapl & RAPL_GFX)
926                         turbostat_submit(name, "power", "GFX_W", p->energy_gfx * rapl_energy_units / interval_float);
927                 if (do_rapl & RAPL_DRAM)
928                         turbostat_submit(name, "power", "RAM_W", p->energy_dram * rapl_energy_units / interval_float);
929         }
930 done:
931         return 0;
932 }
933
934 static int
935 turbostat_read(user_data_t * not_used)
936 {
937         int ret;
938
939         if (!allocated) {
940                 if ((ret = setup_all_buffers()) < 0)
941                         return ret;
942         }
943
944         if (for_all_proc_cpus(cpu_is_not_present)) {
945                 free_all_buffers();
946                 if ((ret = setup_all_buffers()) < 0)
947                         return ret;
948                 if (for_all_proc_cpus(cpu_is_not_present))
949                         return -ERR_CPU_NOT_PRESENT;
950         }
951
952         /* Saving the scheduling affinity, as it will be modified by get_counters */
953         if (sched_getaffinity(0, cpu_saved_affinity_setsize, cpu_saved_affinity_set) != 0)
954                 return -ERR_CPU_SAVE_SCHED_AFFINITY;
955
956         if (!initialized) {
957                 if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
958                         goto out;
959                 gettimeofday(&tv_even, (struct timezone *)NULL);
960                 is_even = 1;
961                 initialized = 1;
962                 ret = 0;
963                 goto out;
964         }
965
966         if (is_even) {
967                 if ((ret = for_all_cpus(get_counters, ODD_COUNTERS)) < 0)
968                         goto out;
969                 gettimeofday(&tv_odd, (struct timezone *)NULL);
970                 is_even = 0;
971                 timersub(&tv_odd, &tv_even, &tv_delta);
972                 if ((ret = for_all_cpus_delta(ODD_COUNTERS, EVEN_COUNTERS)) < 0)
973                         goto out;
974                 if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
975                         goto out;
976         } else {
977                 if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
978                         goto out;
979                 gettimeofday(&tv_even, (struct timezone *)NULL);
980                 is_even = 1;
981                 timersub(&tv_even, &tv_odd, &tv_delta);
982                 if ((ret = for_all_cpus_delta(EVEN_COUNTERS, ODD_COUNTERS)) < 0)
983                         goto out;
984                 if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0)
985                         goto out;
986         }
987         ret = 0;
988 out:
989         /*
990          * Let's restore the affinity
991          * This might fail if the number of CPU changed, but we can't do anything in that case..
992          */
993         (void)sched_setaffinity(0, cpu_saved_affinity_setsize, cpu_saved_affinity_set);
994         return ret;
995 }
996
997 static int __attribute__((warn_unused_result))
998 check_dev_msr()
999 {
1000         struct stat sb;
1001
1002         if (stat("/dev/cpu/0/msr", &sb)) {
1003                 ERROR("no /dev/cpu/0/msr, try \"# modprobe msr\"");
1004                 return -ERR_NO_MSR;
1005         }
1006         return 0;
1007 }
1008
1009 static int __attribute__((warn_unused_result))
1010 check_super_user()
1011 {
1012         if (getuid() != 0) {
1013                 ERROR("must be root");
1014                 return -ERR_NOT_ROOT;
1015         }
1016         return 0;
1017 }
1018
1019 /*
1020  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
1021  * the Thermal Control Circuit (TCC) activates.
1022  * This is usually equal to tjMax.
1023  *
1024  * Older processors do not have this MSR, so there we guess,
1025  * but also allow conficuration over-ride with "TCCActivationTemp".
1026  *
1027  * Several MSR temperature values are in units of degrees-C
1028  * below this value, including the Digital Thermal Sensor (DTS),
1029  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
1030  */
1031 static int __attribute__((warn_unused_result))
1032 set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1033 {
1034         unsigned long long msr;
1035         unsigned int target_c_local;
1036
1037         /* tcc_activation_temp is used only for dts or ptm */
1038         if (!(do_dts || do_ptm))
1039                 return 0;
1040
1041         /* this is a per-package concept */
1042         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1043                 return 0;
1044
1045         if (tcc_activation_temp != 0) {
1046                 p->tcc_activation_temp = tcc_activation_temp;
1047                 return 0;
1048         }
1049
1050         if (get_msr(t->cpu_id, MSR_IA32_TEMPERATURE_TARGET, &msr))
1051                 goto guess;
1052
1053         target_c_local = (msr >> 16) & 0x7F;
1054
1055         if (target_c_local < 85 || target_c_local > 127)
1056                 goto guess;
1057
1058         p->tcc_activation_temp = target_c_local;
1059
1060         return 0;
1061
1062 guess:
1063         p->tcc_activation_temp = TJMAX_DEFAULT;
1064         WARNING("cpu%d: Guessing tjMax %d C, Please use TCCActivationTemp to specify",
1065                 t->cpu_id, p->tcc_activation_temp);
1066
1067         return 0;
1068 }
1069
1070 /*
1071  * Identify the functionality of the CPU
1072  */
1073 static int __attribute__((warn_unused_result))
1074 probe_cpu()
1075 {
1076         unsigned int eax, ebx, ecx, edx, max_level;
1077         unsigned int fms, family, model;
1078
1079         /* CPUID(0):
1080          * - EAX: Maximum Input Value for Basic CPUID Information
1081          * - EBX: "Genu" (0x756e6547)
1082          * - EDX: "ineI" (0x49656e69)
1083          * - ECX: "ntel" (0x6c65746e)
1084          */
1085         max_level = ebx = ecx = edx = 0;
1086         __get_cpuid(0, &max_level, &ebx, &ecx, &edx);
1087         if (ebx != 0x756e6547 && edx != 0x49656e69 && ecx != 0x6c65746e) {
1088                 ERROR("Unsupported CPU");
1089                 return -UNSUPPORTED_CPU;
1090         }
1091
1092         /* CPUID(1):
1093          * - EAX: Version Information: Type, Family, Model, and Stepping ID
1094          *  + 4-7:   Model ID
1095          *  + 8-11:  Family ID
1096          *  + 12-13: Processor type
1097          *  + 16-19: Extended Model ID
1098          *  + 20-27: Extended Family ID
1099          * - EDX: Feature Information:
1100          *  + 5: Support for MSR read/write operations
1101          */
1102         fms = ebx = ecx = edx = 0;
1103         __get_cpuid(1, &fms, &ebx, &ecx, &edx);
1104         family = (fms >> 8) & 0xf;
1105         model = (fms >> 4) & 0xf;
1106         if (family == 0xf)
1107                 family += (fms >> 20) & 0xf;
1108         if (family == 6 || family == 0xf)
1109                 model += ((fms >> 16) & 0xf) << 4;
1110         if (!(edx & (1 << 5))) {
1111                 ERROR("CPUID: no MSR");
1112                 return -ERR_NO_MSR;
1113         }
1114
1115         /*
1116          * CPUID(0x80000000):
1117          * - EAX: Maximum Input Value for Extended Function CPUID Information
1118          *
1119          * This allows us to verify if the CPUID(0x80000007) can be called
1120          *
1121          * This check is valid for both Intel and AMD.
1122          */
1123         max_level = ebx = ecx = edx = 0;
1124         __get_cpuid(0x80000000, &max_level, &ebx, &ecx, &edx);
1125         if (max_level < 0x80000007) {
1126                 ERROR("CPUID: no invariant TSC (max_level 0x%x)", max_level);
1127                 return -ERR_NO_INVARIANT_TSC;
1128         }
1129
1130         /*
1131          * CPUID(0x80000007):
1132          * - EDX:
1133          *  + 8: Invariant TSC available if set
1134          *
1135          * This check is valid for both Intel and AMD
1136          */
1137         __get_cpuid(0x80000007, &eax, &ebx, &ecx, &edx);
1138         if (!(edx & (1 << 8))) {
1139                 ERROR("No invariant TSC");
1140                 return -ERR_NO_INVARIANT_TSC;
1141         }
1142
1143         /*
1144          * CPUID(6):
1145          * - EAX:
1146          *  + 0: Digital temperature sensor is supported if set
1147          *  + 6: Package thermal management is supported if set
1148          * - ECX:
1149          *  + 0: Hardware Coordination Feedback Capability (Presence of IA32_MPERF and IA32_APERF).
1150          *  + 3: The processor supports performance-energy bias preference if set.
1151          *       It also implies the presence of a new architectural MSR called IA32_ENERGY_PERF_BIAS
1152          *
1153          * This check is valid for both Intel and AMD
1154          */
1155         __get_cpuid(0x6, &eax, &ebx, &ecx, &edx);
1156         do_dts = eax & (1 << 0);
1157         do_ptm = eax & (1 << 6);
1158         if (!(ecx & (1 << 0))) {
1159                 ERROR("No APERF");
1160                 return -ERR_NO_APERF;
1161         }
1162
1163         /*
1164          * Enable or disable C states depending on the model and family
1165          */
1166         if (family == 6) {
1167                 switch (model) {
1168                 /* Atom (partial) */
1169                 case 0x27:
1170                         do_core_cstate = 0;
1171                         do_pkg_cstate = (1 << 2) | (1 << 4) | (1 << 6);
1172                         break;
1173                 /* Silvermont */
1174                 case 0x37: /* BYT */
1175                 case 0x4A:
1176                 case 0x4D: /* AVN */
1177                 case 0x5A:
1178                 case 0x5D:
1179                         do_core_cstate = (1 << 1) | (1 << 6);
1180                         do_pkg_cstate = (1 << 6);
1181                         break;
1182                 /* Nehalem */
1183                 case 0x1A: /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
1184                 case 0x1E: /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
1185                 case 0x1F: /* Core i7 and i5 Processor - Nehalem */
1186                 case 0x2E: /* Nehalem-EX Xeon - Beckton */
1187                         do_core_cstate = (1 << 3) | (1 << 6);
1188                         do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1189                         break;
1190                 /* Westmere */
1191                 case 0x25: /* Westmere Client - Clarkdale, Arrandale */
1192                 case 0x2C: /* Westmere EP - Gulftown */
1193                 case 0x2F: /* Westmere-EX Xeon - Eagleton */
1194                         do_core_cstate = (1 << 3) | (1 << 6);
1195                         do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1196                         break;
1197                 /* Sandy Bridge */
1198                 case 0x2A: /* SNB */
1199                 case 0x2D: /* SNB Xeon */
1200                         do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1201                         do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7);
1202                         break;
1203                 /* Ivy Bridge */
1204                 case 0x3A: /* IVB */
1205                 case 0x3E: /* IVB Xeon */
1206                         do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1207                         do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1208                         break;
1209                 /* Haswell Bridge */
1210                 case 0x3C: /* HSW */
1211                 case 0x3F: /* HSW */
1212                 case 0x46: /* HSW */
1213                         do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1214                         do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1215                         break;
1216                 case 0x45: /* HSW */
1217                         do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1218                         do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10);
1219                         break;
1220                 /* Broadwel */
1221                 case 0x4F: /* BDW */
1222                 case 0x56: /* BDX-DE */
1223                         do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1224                         do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1225                         break;
1226                 case 0x3D: /* BDW */
1227                         do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7);
1228                         do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10);
1229                         break;
1230                 default:
1231                         ERROR("Unsupported CPU");
1232                 }
1233                 switch (model) {
1234                 case 0x2A:
1235                 case 0x3A:
1236                 case 0x3C:
1237                 case 0x45:
1238                 case 0x46:
1239                         do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_PKG_POWER_INFO | RAPL_GFX;
1240                         break;
1241                 case 0x3F:
1242                         do_rapl = RAPL_PKG | RAPL_PKG_POWER_INFO | RAPL_PKG_PERF_STATUS | RAPL_DRAM | RAPL_DRAM_PERF_STATUS;
1243                         break;
1244                 case 0x2D:
1245                 case 0x3E:
1246                         do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_PKG_POWER_INFO | RAPL_PKG_PERF_STATUS | RAPL_DRAM | RAPL_DRAM_PERF_STATUS;
1247                         break;
1248                 case 0x37:
1249                 case 0x4D:
1250                         do_rapl = RAPL_PKG | RAPL_CORES;
1251                         break;
1252                 default:
1253                         do_rapl = 0;
1254                 }
1255         } else {
1256                 ERROR("Unsupported CPU");
1257                 return -UNSUPPORTED_CPU;
1258         }
1259
1260         if (do_rapl) {
1261                 unsigned long msr;
1262                 if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr))
1263                         return 0;
1264
1265                 if (model == 0x37)
1266                         rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
1267                 else
1268                         rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
1269         }
1270
1271         return 0;
1272 }
1273
1274
1275
1276 static int __attribute__((warn_unused_result))
1277 topology_probe()
1278 {
1279         int i;
1280         int ret;
1281         int max_core_id = 0;
1282         int max_package_id = 0;
1283         int max_siblings = 0;
1284         struct cpu_topology {
1285                 int core_id;
1286                 int physical_package_id;
1287         } *cpus;
1288
1289         /* Initialize num_cpus, max_cpu_num */
1290         topo.num_cpus = 0;
1291         topo.max_cpu_num = 0;
1292         ret = for_all_proc_cpus(count_cpus);
1293         if (ret < 0)
1294                 return ret;
1295
1296         DEBUG("num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
1297
1298         cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
1299         if (cpus == NULL) {
1300                 ERROR("calloc cpus");
1301                 return -ERR_CALLOC;
1302         }
1303
1304         /*
1305          * Allocate and initialize cpu_present_set
1306          */
1307         cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
1308         if (cpu_present_set == NULL) {
1309                 free(cpus);
1310                 ERROR("CPU_ALLOC");
1311                 return -ERR_CPU_ALLOC;
1312         }
1313         cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
1314         CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
1315         ret = for_all_proc_cpus(mark_cpu_present);
1316         if (ret < 0) {
1317                 free(cpus);
1318                 return ret;
1319         }
1320
1321         /*
1322          * Allocate and initialize cpu_affinity_set
1323          */
1324         cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
1325         if (cpu_affinity_set == NULL) {
1326                 free(cpus);
1327                 ERROR("CPU_ALLOC");
1328                 return -ERR_CPU_ALLOC;
1329         }
1330         cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
1331         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
1332
1333
1334         /*
1335          * Allocate and initialize cpu_saved_affinity_set
1336          */
1337         cpu_saved_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
1338         if (cpu_saved_affinity_set == NULL) {
1339                 free(cpus);
1340                 ERROR("CPU_ALLOC");
1341                 return -ERR_CPU_ALLOC;
1342         }
1343         cpu_saved_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
1344         CPU_ZERO_S(cpu_saved_affinity_setsize, cpu_saved_affinity_set);
1345
1346
1347         /*
1348          * For online cpus
1349          * find max_core_id, max_package_id
1350          */
1351         for (i = 0; i <= topo.max_cpu_num; ++i) {
1352                 int siblings;
1353
1354                 if (cpu_is_not_present(i)) {
1355                         WARNING("cpu%d NOT PRESENT", i);
1356                         continue;
1357                 }
1358                 cpus[i].core_id = get_core_id(i);
1359                 if (cpus[i].core_id < 0)
1360                         return cpus[i].core_id;
1361                 if (cpus[i].core_id > max_core_id)
1362                         max_core_id = cpus[i].core_id;
1363
1364                 cpus[i].physical_package_id = get_physical_package_id(i);
1365                 if (cpus[i].physical_package_id < 0)
1366                         return cpus[i].physical_package_id;
1367                 if (cpus[i].physical_package_id > max_package_id)
1368                         max_package_id = cpus[i].physical_package_id;
1369
1370                 siblings = get_num_ht_siblings(i);
1371                 if (siblings < 0)
1372                         return siblings;
1373                 if (siblings > max_siblings)
1374                         max_siblings = siblings;
1375                 DEBUG("cpu %d pkg %d core %d\n",
1376                         i, cpus[i].physical_package_id, cpus[i].core_id);
1377         }
1378         topo.num_cores_per_pkg = max_core_id + 1;
1379         DEBUG("max_core_id %d, sizing for %d cores per package\n",
1380                 max_core_id, topo.num_cores_per_pkg);
1381
1382         topo.num_packages = max_package_id + 1;
1383         DEBUG("max_package_id %d, sizing for %d packages\n",
1384                 max_package_id, topo.num_packages);
1385
1386         topo.num_threads_per_core = max_siblings;
1387         DEBUG("max_siblings %d\n", max_siblings);
1388
1389         free(cpus);
1390         return 0;
1391 }
1392
1393 static int
1394 allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
1395 {
1396         int i;
1397
1398         *t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
1399                 topo.num_packages, sizeof(struct thread_data));
1400         if (*t == NULL)
1401                 goto error;
1402
1403         for (i = 0; i < topo.num_threads_per_core *
1404                 topo.num_cores_per_pkg * topo.num_packages; i++)
1405                 (*t)[i].cpu_id = -1;
1406
1407         *c = calloc(topo.num_cores_per_pkg * topo.num_packages,
1408                 sizeof(struct core_data));
1409         if (*c == NULL)
1410                 goto error;
1411
1412         for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
1413                 (*c)[i].core_id = -1;
1414
1415         *p = calloc(topo.num_packages, sizeof(struct pkg_data));
1416         if (*p == NULL)
1417                 goto error;
1418
1419         for (i = 0; i < topo.num_packages; i++)
1420                 (*p)[i].package_id = i;
1421
1422         return 0;
1423 error:
1424         ERROR("calloc counters");
1425         return -ERR_CALLOC;
1426 }
1427 /*
1428  * init_counter()
1429  *
1430  * set cpu_id, core_num, pkg_num
1431  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
1432  *
1433  * increment topo.num_cores when 1st core in pkg seen
1434  */
1435 static int
1436 init_counter(struct thread_data *thread_base, struct core_data *core_base,
1437         struct pkg_data *pkg_base, int thread_num, int core_num,
1438         int pkg_num, int cpu_id)
1439 {
1440         int ret;
1441         struct thread_data *t;
1442         struct core_data *c;
1443         struct pkg_data *p;
1444
1445         t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
1446         c = GET_CORE(core_base, core_num, pkg_num);
1447         p = GET_PKG(pkg_base, pkg_num);
1448
1449         t->cpu_id = cpu_id;
1450         if (thread_num == 0) {
1451                 t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
1452                 if ((ret = cpu_is_first_core_in_package(cpu_id)) < 0) {
1453                         return ret;
1454                 } else if (ret != 0) {
1455                         t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
1456                 }
1457         }
1458
1459         c->core_id = core_num;
1460         p->package_id = pkg_num;
1461
1462         return 0;
1463 }
1464
1465
1466 static int
1467 initialize_counters(int cpu_id)
1468 {
1469         int my_thread_id, my_core_id, my_package_id;
1470         int ret;
1471
1472         my_package_id = get_physical_package_id(cpu_id);
1473         if (my_package_id < 0)
1474                 return my_package_id;
1475         my_core_id = get_core_id(cpu_id);
1476         if (my_core_id < 0)
1477                 return my_core_id;
1478
1479         if ((ret = cpu_is_first_sibling_in_core(cpu_id)) < 0) {
1480                 return ret;
1481         } else if (ret != 0) {
1482                 my_thread_id = 0;
1483                 topo.num_cores++;
1484         } else {
1485                 my_thread_id = 1;
1486         }
1487
1488         ret = init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
1489         if (ret < 0)
1490                 return ret;
1491         ret = init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
1492         if (ret < 0)
1493                 return ret;
1494         ret = init_counter(DELTA_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
1495         if (ret < 0)
1496                 return ret;
1497         return 0;
1498 }
1499
1500 #define DO_OR_GOTO_ERR(something) \
1501 do {                         \
1502         ret = (something);     \
1503         if (ret < 0)         \
1504                 goto err;    \
1505 } while (0)
1506
1507 static int setup_all_buffers(void)
1508 {
1509         int ret;
1510
1511         DO_OR_GOTO_ERR(topology_probe());
1512         DO_OR_GOTO_ERR(allocate_counters(&thread_even, &core_even, &package_even));
1513         DO_OR_GOTO_ERR(allocate_counters(&thread_odd, &core_odd, &package_odd));
1514         DO_OR_GOTO_ERR(allocate_counters(&thread_delta, &core_delta, &package_delta));
1515         DO_OR_GOTO_ERR(for_all_proc_cpus(initialize_counters));
1516         DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, EVEN_COUNTERS));
1517         DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, ODD_COUNTERS));
1518
1519         allocated = 1;
1520         return 0;
1521 err:
1522         free_all_buffers();
1523         return ret;
1524 }
1525
1526 static int
1527 turbostat_init(void)
1528 {
1529         int ret;
1530
1531         DO_OR_GOTO_ERR(check_super_user());
1532         DO_OR_GOTO_ERR(probe_cpu());
1533         DO_OR_GOTO_ERR(check_dev_msr());
1534         DO_OR_GOTO_ERR(setup_all_buffers());
1535
1536         plugin_register_complex_read(NULL, PLUGIN_NAME, turbostat_read, NULL, NULL);
1537
1538         return 0;
1539 err:
1540         free_all_buffers();
1541         return ret;
1542 }
1543
1544 static const char *config_keys[] =
1545 {
1546         "TCCActivationTemp",
1547 };
1548 static const int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
1549
1550 static int
1551 turbostat_config(const char *key, const char *value)
1552 {
1553         long unsigned int tmp_val;
1554         char *end;
1555
1556         if (strcasecmp("TCCActivationTemp", key) == 0) {
1557                 tmp_val = strtoul(value, &end, 0);
1558                 if (*end != '\0' || tmp_val > UINT_MAX)
1559                         return -1;
1560                 tcc_activation_temp = (unsigned int) tmp_val;
1561         } else {
1562                 return -1;
1563         }
1564         return 0;
1565 }
1566
1567 void module_register(void);
1568 void module_register(void)
1569 {
1570         plugin_register_init(PLUGIN_NAME, turbostat_init);
1571         plugin_register_config(PLUGIN_NAME, turbostat_config, config_keys, config_keys_num);
1572 }