e6b59d9e1ddfe200f2e4c27b8e96cf38659bea32
[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 kernel tools by:
6  * Copyright (c) 2013 Intel Corporation.
7  * Len Brown <len.brown@intel.com>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms and conditions of the GNU General Public License,
11  * version 2, as published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
16  * more details.
17  *
18  * You should have received a copy of the GNU General Public License along with
19  * this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Ported to collectd by Vincent Brillault <git@lerya.net>
23  */
24
25 #define _GNU_SOURCE
26 #include "msr-index.h"
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdbool.h>
30 #include <err.h>
31 #include <unistd.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <sys/stat.h>
35 #include <sys/resource.h>
36 #include <fcntl.h>
37 #include <signal.h>
38 #include <sys/time.h>
39 #include <stdlib.h>
40 #include <dirent.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include <sched.h>
44 #include <cpuid.h>
45
46 #include "collectd.h"
47 #include "common.h"
48 #include "plugin.h"
49
50 #define PLUGIN_NAME "turbostat"
51
52 static const char *proc_stat = "/proc/stat";
53 static unsigned int interval_sec = 5;   /* set with -i interval_sec */
54 static unsigned int skip_c0;
55 static unsigned int skip_c1;
56 static unsigned int do_nhm_cstates;
57 static unsigned int do_snb_cstates;
58 static unsigned int do_c8_c9_c10;
59 static unsigned int do_slm_cstates;
60 static unsigned int has_aperf;
61 static unsigned int has_epb;
62 static unsigned int units = 1000000000; /* Ghz etc */
63 static unsigned int genuine_intel;
64 static unsigned int has_invariant_tsc;
65 static unsigned int do_nehalem_platform_info;
66 static int do_smi;
67 static unsigned int show_pkg;
68 static unsigned int show_core;
69 static unsigned int show_cpu;
70 static unsigned int do_rapl;
71 static unsigned int do_dts;
72 static unsigned int do_ptm;
73 static unsigned int tcc_activation_temp;
74 static unsigned int tcc_activation_temp_override;
75 static double rapl_power_units, rapl_energy_units, rapl_time_units;
76 static double rapl_joule_counter_range;
77
78 #define RAPL_PKG                (1 << 0)
79                                         /* 0x610 MSR_PKG_POWER_LIMIT */
80                                         /* 0x611 MSR_PKG_ENERGY_STATUS */
81 #define RAPL_PKG_PERF_STATUS    (1 << 1)
82                                         /* 0x613 MSR_PKG_PERF_STATUS */
83 #define RAPL_PKG_POWER_INFO     (1 << 2)
84                                         /* 0x614 MSR_PKG_POWER_INFO */
85
86 #define RAPL_DRAM               (1 << 3)
87                                         /* 0x618 MSR_DRAM_POWER_LIMIT */
88                                         /* 0x619 MSR_DRAM_ENERGY_STATUS */
89                                         /* 0x61c MSR_DRAM_POWER_INFO */
90 #define RAPL_DRAM_PERF_STATUS   (1 << 4)
91                                         /* 0x61b MSR_DRAM_PERF_STATUS */
92
93 #define RAPL_CORES              (1 << 5)
94                                         /* 0x638 MSR_PP0_POWER_LIMIT */
95                                         /* 0x639 MSR_PP0_ENERGY_STATUS */
96 #define RAPL_CORE_POLICY        (1 << 6)
97                                         /* 0x63a MSR_PP0_POLICY */
98
99
100 #define RAPL_GFX                (1 << 7)
101                                         /* 0x640 MSR_PP1_POWER_LIMIT */
102                                         /* 0x641 MSR_PP1_ENERGY_STATUS */
103                                         /* 0x642 MSR_PP1_POLICY */
104 #define TJMAX_DEFAULT   100
105
106 int aperf_mperf_unstable;
107 int backwards_count;
108 char *progname;
109
110 cpu_set_t *cpu_present_set, *cpu_affinity_set;
111 size_t cpu_present_setsize, cpu_affinity_setsize;
112
113 struct thread_data {
114         unsigned long long tsc;
115         unsigned long long aperf;
116         unsigned long long mperf;
117         unsigned long long c1;
118         unsigned int smi_count;
119         unsigned int cpu_id;
120         unsigned int flags;
121 #define CPU_IS_FIRST_THREAD_IN_CORE     0x2
122 #define CPU_IS_FIRST_CORE_IN_PACKAGE    0x4
123 } *thread_even, *thread_odd;
124
125 struct core_data {
126         unsigned long long c3;
127         unsigned long long c6;
128         unsigned long long c7;
129         unsigned int core_temp_c;
130         unsigned int core_id;
131 } *core_even, *core_odd;
132
133 struct pkg_data {
134         unsigned long long pc2;
135         unsigned long long pc3;
136         unsigned long long pc6;
137         unsigned long long pc7;
138         unsigned long long pc8;
139         unsigned long long pc9;
140         unsigned long long pc10;
141         unsigned int package_id;
142         unsigned int energy_pkg;        /* MSR_PKG_ENERGY_STATUS */
143         unsigned int energy_dram;       /* MSR_DRAM_ENERGY_STATUS */
144         unsigned int energy_cores;      /* MSR_PP0_ENERGY_STATUS */
145         unsigned int energy_gfx;        /* MSR_PP1_ENERGY_STATUS */
146         unsigned int rapl_pkg_perf_status;      /* MSR_PKG_PERF_STATUS */
147         unsigned int rapl_dram_perf_status;     /* MSR_DRAM_PERF_STATUS */
148         unsigned int pkg_temp_c;
149
150 } *package_even, *package_odd;
151
152 #define ODD_COUNTERS thread_odd, core_odd, package_odd
153 #define EVEN_COUNTERS thread_even, core_even, package_even
154 static bool is_even = true;
155
156 static bool allocated = false;
157 static bool initialized = false;
158
159 #define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \
160         (thread_base + (pkg_no) * topo.num_cores_per_pkg * \
161                 topo.num_threads_per_core + \
162                 (core_no) * topo.num_threads_per_core + (thread_no))
163 #define GET_CORE(core_base, core_no, pkg_no) \
164         (core_base + (pkg_no) * topo.num_cores_per_pkg + (core_no))
165 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
166
167 struct topo_params {
168         int num_packages;
169         int num_cpus;
170         int num_cores;
171         int max_cpu_num;
172         int num_cores_per_pkg;
173         int num_threads_per_core;
174 } topo;
175
176 struct timeval tv_even, tv_odd, tv_delta;
177
178 enum return_values {
179         OK = 0,
180         ERR_CPU_MIGRATE,
181         ERR_MSR_IA32_APERF,
182         ERR_MSR_IA32_MPERF,
183         ERR_MSR_SMI_COUNT,
184         ERR_MSR_CORE_C3_RESIDENCY,
185         ERR_MSR_CORE_C6_RESIDENCY,
186         ERR_MSR_CORE_C7_RESIDENCY,
187         ERR_MSR_IA32_THERM_STATUS,
188         ERR_MSR_PKG_C3_RESIDENCY,
189         ERR_MSR_PKG_C6_RESIDENCY,
190         ERR_MSR_PKG_C2_RESIDENCY,
191         ERR_MSR_PKG_C7_RESIDENCY,
192         ERR_MSR_PKG_C8_RESIDENCY,
193         ERR_MSR_PKG_C9_RESIDENCY,
194         ERR_MSR_PKG_C10_RESIDENCY,
195         ERR_MSR_PKG_ENERGY_STATUS,
196         ERR_MSR_PP0_ENERGY_STATUS,
197         ERR_MSR_DRAM_ENERGY_STATUS,
198         ERR_MSR_PP1_ENERGY_STATUS,
199         ERR_MSR_PKG_PERF_STATUS,
200         ERR_MSR_DRAM_PERF_STATUS,
201         ERR_MSR_IA32_PACKAGE_THERM_STATUS,
202         ERR_CPU_NOT_PRESENT,
203         ERR_NO_MSR,
204         ERR_CANT_OPEN_FILE,
205         ERR_CANT_READ_NUMBER,
206         ERR_CANT_READ_PROC_STAT,
207         ERR_NO_INVARIANT_TSC,
208         ERR_NO_APERF,
209         ERR_CALLOC,
210         ERR_CPU_ALLOC,
211         ERR_NOT_ROOT,
212 };
213
214 #define __must_check __attribute__((warn_unused_result))
215
216 static int setup_all_buffers(void);
217
218 static int
219 cpu_is_not_present(int cpu)
220 {
221         return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
222 }
223 /*
224  * run func(thread, core, package) in topology order
225  * skip non-present cpus
226  */
227
228 static int __must_check
229 for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
230         struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
231 {
232         int retval, pkg_no, core_no, thread_no;
233
234         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
235                 for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
236                         for (thread_no = 0; thread_no <
237                                 topo.num_threads_per_core; ++thread_no) {
238                                 struct thread_data *t;
239                                 struct core_data *c;
240                                 struct pkg_data *p;
241
242                                 t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
243
244                                 if (cpu_is_not_present(t->cpu_id))
245                                         continue;
246
247                                 c = GET_CORE(core_base, core_no, pkg_no);
248                                 p = GET_PKG(pkg_base, pkg_no);
249
250                                 retval = func(t, c, p);
251                                 if (retval)
252                                         return retval;
253                         }
254                 }
255         }
256         return 0;
257 }
258
259 static int __must_check
260 cpu_migrate(int cpu)
261 {
262         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
263         CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
264         if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1)
265                 return -ERR_CPU_MIGRATE;
266         else
267                 return 0;
268 }
269
270 static int __must_check
271 get_msr(int cpu, off_t offset, unsigned long long *msr)
272 {
273         ssize_t retval;
274         char pathname[32];
275         int fd;
276
277         sprintf(pathname, "/dev/cpu/%d/msr", cpu);
278         fd = open(pathname, O_RDONLY);
279         if (fd < 0)
280                 return -1;
281
282         retval = pread(fd, msr, sizeof *msr, offset);
283         close(fd);
284
285         if (retval != sizeof *msr) {
286                 ERROR ("%s offset 0x%llx read failed\n", pathname, (unsigned long long)offset);
287                 return -1;
288         }
289
290         return 0;
291 }
292
293 #define DELTA_WRAP32(new, old)                  \
294         if (new > old) {                        \
295                 old = new - old;                \
296         } else {                                \
297                 old = 0x100000000 + new - old;  \
298         }
299
300 static void
301 delta_package(struct pkg_data *new, struct pkg_data *old)
302 {
303         old->pc2 = new->pc2 - old->pc2;
304         old->pc3 = new->pc3 - old->pc3;
305         old->pc6 = new->pc6 - old->pc6;
306         old->pc7 = new->pc7 - old->pc7;
307         old->pc8 = new->pc8 - old->pc8;
308         old->pc9 = new->pc9 - old->pc9;
309         old->pc10 = new->pc10 - old->pc10;
310         old->pkg_temp_c = new->pkg_temp_c;
311
312         DELTA_WRAP32(new->energy_pkg, old->energy_pkg);
313         DELTA_WRAP32(new->energy_cores, old->energy_cores);
314         DELTA_WRAP32(new->energy_gfx, old->energy_gfx);
315         DELTA_WRAP32(new->energy_dram, old->energy_dram);
316         DELTA_WRAP32(new->rapl_pkg_perf_status, old->rapl_pkg_perf_status);
317         DELTA_WRAP32(new->rapl_dram_perf_status, old->rapl_dram_perf_status);
318 }
319
320 static void
321 delta_core(struct core_data *new, struct core_data *old)
322 {
323         old->c3 = new->c3 - old->c3;
324         old->c6 = new->c6 - old->c6;
325         old->c7 = new->c7 - old->c7;
326         old->core_temp_c = new->core_temp_c;
327 }
328
329 /*
330  * old = new - old
331  */
332 static int __must_check
333 delta_thread(struct thread_data *new, struct thread_data *old,
334         struct core_data *core_delta)
335 {
336         old->tsc = new->tsc - old->tsc;
337
338         /* check for TSC < 1 Mcycles over interval */
339         if (old->tsc < (1000 * 1000)) {
340                 WARNING("Insanely slow TSC rate, TSC stops in idle?\n"
341                         "You can disable all c-states by booting with \"idle=poll\"\n"
342                         "or just the deep ones with \"processor.max_cstate=1\"");
343                 return -1;
344         }
345
346         old->c1 = new->c1 - old->c1;
347
348         if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
349                 old->aperf = new->aperf - old->aperf;
350                 old->mperf = new->mperf - old->mperf;
351         } else {
352
353                 if (!aperf_mperf_unstable) {
354                         WARNING("%s: APERF or MPERF went backwards *\n", progname);
355                         WARNING("* Frequency results do not cover entire interval *\n");
356                         WARNING("* fix this by running Linux-2.6.30 or later *\n");
357
358                         aperf_mperf_unstable = 1;
359                 }
360                 /*
361                  * mperf delta is likely a huge "positive" number
362                  * can not use it for calculating c0 time
363                  */
364                 skip_c0 = 1;
365                 skip_c1 = 1;
366         }
367
368
369         /*
370          * As counter collection is not atomic,
371          * it is possible for mperf's non-halted cycles + idle states
372          * to exceed TSC's all cycles: show c1 = 0% in that case.
373          */
374         if ((old->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > old->tsc)
375                 old->c1 = 0;
376         else {
377                 /* normal case, derive c1 */
378                 old->c1 = old->tsc - old->mperf - core_delta->c3
379                         - core_delta->c6 - core_delta->c7;
380         }
381
382         if (old->mperf == 0) {
383                 WARNING("cpu%d MPERF 0!\n", old->cpu_id);
384                 old->mperf = 1; /* divide by 0 protection */
385         }
386
387         if (do_smi)
388                 old->smi_count = new->smi_count - old->smi_count;
389
390         return 0;
391 }
392
393 static int __must_check
394 delta_cpu(struct thread_data *t, struct core_data *c,
395         struct pkg_data *p, struct thread_data *t2,
396         struct core_data *c2, struct pkg_data *p2)
397 {
398         int ret;
399
400         /* calculate core delta only for 1st thread in core */
401         if (t->flags & CPU_IS_FIRST_THREAD_IN_CORE)
402                 delta_core(c, c2);
403
404         /* always calculate thread delta */
405         ret = delta_thread(t, t2, c2);  /* c2 is core delta */
406         if (ret != 0)
407                 return ret;
408
409         /* calculate package delta only for 1st core in package */
410         if (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)
411                 delta_package(p, p2);
412
413         return 0;
414 }
415
416 static unsigned long long
417 rdtsc(void)
418 {
419         unsigned int low, high;
420
421         asm volatile("rdtsc" : "=a" (low), "=d" (high));
422
423         return low | ((unsigned long long)high) << 32;
424 }
425
426
427 /*
428  * get_counters(...)
429  * migrate to cpu
430  * acquire and record local counters for that cpu
431  */
432 static int __must_check
433 get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
434 {
435         int cpu = t->cpu_id;
436         unsigned long long msr;
437
438         if (cpu_migrate(cpu)) {
439                 WARNING("Could not migrate to CPU %d\n", cpu);
440                 return -ERR_CPU_MIGRATE;
441         }
442
443         t->tsc = rdtsc();       /* we are running on local CPU of interest */
444
445         if (has_aperf) {
446                 if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
447                         return -ERR_MSR_IA32_APERF;
448                 if (get_msr(cpu, MSR_IA32_MPERF, &t->mperf))
449                         return -ERR_MSR_IA32_MPERF;
450         }
451
452         if (do_smi) {
453                 if (get_msr(cpu, MSR_SMI_COUNT, &msr))
454                         return -ERR_MSR_SMI_COUNT;
455                 t->smi_count = msr & 0xFFFFFFFF;
456         }
457
458         /* collect core counters only for 1st thread in core */
459         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
460                 return 0;
461
462         if (do_nhm_cstates && !do_slm_cstates) {
463                 if (get_msr(cpu, MSR_CORE_C3_RESIDENCY, &c->c3))
464                         return -ERR_MSR_CORE_C3_RESIDENCY;
465         }
466
467         if (do_nhm_cstates) {
468                 if (get_msr(cpu, MSR_CORE_C6_RESIDENCY, &c->c6))
469                         return -ERR_MSR_CORE_C6_RESIDENCY;
470         }
471
472         if (do_snb_cstates)
473                 if (get_msr(cpu, MSR_CORE_C7_RESIDENCY, &c->c7))
474                         return -ERR_MSR_CORE_C7_RESIDENCY;
475
476         if (do_dts) {
477                 if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
478                         return -ERR_MSR_IA32_THERM_STATUS;
479                 c->core_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
480         }
481
482
483         /* collect package counters only for 1st core in package */
484         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
485                 return 0;
486
487         if (do_nhm_cstates && !do_slm_cstates) {
488                 if (get_msr(cpu, MSR_PKG_C3_RESIDENCY, &p->pc3))
489                         return -ERR_MSR_PKG_C3_RESIDENCY;
490                 if (get_msr(cpu, MSR_PKG_C6_RESIDENCY, &p->pc6))
491                         return -ERR_MSR_PKG_C6_RESIDENCY;
492         }
493         if (do_snb_cstates) {
494                 if (get_msr(cpu, MSR_PKG_C2_RESIDENCY, &p->pc2))
495                         return -ERR_MSR_PKG_C2_RESIDENCY;
496                 if (get_msr(cpu, MSR_PKG_C7_RESIDENCY, &p->pc7))
497                         return -ERR_MSR_PKG_C7_RESIDENCY;
498         }
499         if (do_c8_c9_c10) {
500                 if (get_msr(cpu, MSR_PKG_C8_RESIDENCY, &p->pc8))
501                         return -ERR_MSR_PKG_C8_RESIDENCY;
502                 if (get_msr(cpu, MSR_PKG_C9_RESIDENCY, &p->pc9))
503                         return -ERR_MSR_PKG_C9_RESIDENCY;
504                 if (get_msr(cpu, MSR_PKG_C10_RESIDENCY, &p->pc10))
505                         return -ERR_MSR_PKG_C10_RESIDENCY;
506         }
507         if (do_rapl & RAPL_PKG) {
508                 if (get_msr(cpu, MSR_PKG_ENERGY_STATUS, &msr))
509                         return -ERR_MSR_PKG_ENERGY_STATUS;
510                 p->energy_pkg = msr & 0xFFFFFFFF;
511         }
512         if (do_rapl & RAPL_CORES) {
513                 if (get_msr(cpu, MSR_PP0_ENERGY_STATUS, &msr))
514                         return MSR_PP0_ENERGY_STATUS;
515                 p->energy_cores = msr & 0xFFFFFFFF;
516         }
517         if (do_rapl & RAPL_DRAM) {
518                 if (get_msr(cpu, MSR_DRAM_ENERGY_STATUS, &msr))
519                         return -ERR_MSR_DRAM_ENERGY_STATUS;
520                 p->energy_dram = msr & 0xFFFFFFFF;
521         }
522         if (do_rapl & RAPL_GFX) {
523                 if (get_msr(cpu, MSR_PP1_ENERGY_STATUS, &msr))
524                         return -ERR_MSR_PP1_ENERGY_STATUS;
525                 p->energy_gfx = msr & 0xFFFFFFFF;
526         }
527         if (do_rapl & RAPL_PKG_PERF_STATUS) {
528                 if (get_msr(cpu, MSR_PKG_PERF_STATUS, &msr))
529                         return -ERR_MSR_PKG_PERF_STATUS;
530                 p->rapl_pkg_perf_status = msr & 0xFFFFFFFF;
531         }
532         if (do_rapl & RAPL_DRAM_PERF_STATUS) {
533                 if (get_msr(cpu, MSR_DRAM_PERF_STATUS, &msr))
534                         return -ERR_MSR_DRAM_PERF_STATUS;
535                 p->rapl_dram_perf_status = msr & 0xFFFFFFFF;
536         }
537         if (do_ptm) {
538                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
539                         return -ERR_MSR_IA32_PACKAGE_THERM_STATUS;
540                 p->pkg_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
541         }
542         return 0;
543 }
544
545 static void
546 free_all_buffers(void)
547 {
548         allocated = false;
549         initialized = false;
550
551         CPU_FREE(cpu_present_set);
552         cpu_present_set = NULL;
553         cpu_present_set = 0;
554
555         CPU_FREE(cpu_affinity_set);
556         cpu_affinity_set = NULL;
557         cpu_affinity_setsize = 0;
558
559         free(thread_even);
560         free(core_even);
561         free(package_even);
562
563         thread_even = NULL;
564         core_even = NULL;
565         package_even = NULL;
566
567         free(thread_odd);
568         free(core_odd);
569         free(package_odd);
570
571         thread_odd = NULL;
572         core_odd = NULL;
573         package_odd = NULL;
574 }
575
576 /*
577  * Parse a file containing a single int.
578  */
579 static int
580 parse_int_file(const char *fmt, ...)
581 {
582         va_list args;
583         char path[PATH_MAX];
584         FILE *filep;
585         int value;
586
587         va_start(args, fmt);
588         vsnprintf(path, sizeof(path), fmt, args);
589         va_end(args);
590         filep = fopen(path, "r");
591         if (!filep) {
592                 ERROR("%s: open failed", path);
593                 return -ERR_CANT_OPEN_FILE;
594         }
595         if (fscanf(filep, "%d", &value) != 1) {
596                 ERROR("%s: failed to parse number from file", path);
597                 return -ERR_CANT_READ_NUMBER;
598         }
599         fclose(filep);
600         return value;
601 }
602
603 /*
604  * cpu_is_first_sibling_in_core(cpu)
605  * return 1 if given CPU is 1st HT sibling in the core
606  */
607 static int
608 cpu_is_first_sibling_in_core(int cpu)
609 {
610         return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
611 }
612
613 /*
614  * cpu_is_first_core_in_package(cpu)
615  * return 1 if given CPU is 1st core in package
616  */
617 static int
618 cpu_is_first_core_in_package(int cpu)
619 {
620         return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
621 }
622
623 static int
624 get_physical_package_id(int cpu)
625 {
626         return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
627 }
628
629 static int
630 get_core_id(int cpu)
631 {
632         return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
633 }
634
635 static int
636 get_num_ht_siblings(int cpu)
637 {
638         char path[80];
639         FILE *filep;
640         int sib1, sib2;
641         int matches;
642         char character;
643
644         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
645         filep = fopen(path, "r");
646         if (!filep) {
647                 ERROR("%s: open failed", path);
648                 return -ERR_CANT_OPEN_FILE;
649         }
650         /*
651          * file format:
652          * if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4)
653          * otherwinse 1 sibling (self).
654          */
655         matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2);
656
657         fclose(filep);
658
659         if (matches == 3)
660                 return 2;
661         else
662                 return 1;
663 }
664
665 /*
666  * run func(thread, core, package) in topology order
667  * skip non-present cpus
668  */
669
670
671 static int __must_check
672 for_all_cpus_2(int (func)(struct thread_data *, struct core_data *,
673         struct pkg_data *, struct thread_data *, struct core_data *,
674         struct pkg_data *), struct thread_data *thread_base,
675         struct core_data *core_base, struct pkg_data *pkg_base,
676         struct thread_data *thread_base2, struct core_data *core_base2,
677         struct pkg_data *pkg_base2)
678 {
679         int retval, pkg_no, core_no, thread_no;
680
681         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
682                 for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
683                         for (thread_no = 0; thread_no <
684                                 topo.num_threads_per_core; ++thread_no) {
685                                 struct thread_data *t, *t2;
686                                 struct core_data *c, *c2;
687                                 struct pkg_data *p, *p2;
688
689                                 t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
690
691                                 if (cpu_is_not_present(t->cpu_id))
692                                         continue;
693
694                                 t2 = GET_THREAD(thread_base2, thread_no, core_no, pkg_no);
695
696                                 c = GET_CORE(core_base, core_no, pkg_no);
697                                 c2 = GET_CORE(core_base2, core_no, pkg_no);
698
699                                 p = GET_PKG(pkg_base, pkg_no);
700                                 p2 = GET_PKG(pkg_base2, pkg_no);
701
702                                 retval = func(t, c, p, t2, c2, p2);
703                                 if (retval)
704                                         return retval;
705                         }
706                 }
707         }
708         return 0;
709 }
710
711 /*
712  * run func(cpu) on every cpu in /proc/stat
713  * return max_cpu number
714  */
715 static int __must_check
716 for_all_proc_cpus(int (func)(int))
717 {
718         FILE *fp;
719         int cpu_num;
720         int retval;
721
722         fp = fopen(proc_stat, "r");
723         if (!fp) {
724                 ERROR("%s: open failed", proc_stat);
725                 return -ERR_CANT_OPEN_FILE;
726         }
727
728         retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
729         if (retval != 0) {
730                 ERROR("%s: failed to parse format", proc_stat);
731                 return -ERR_CANT_READ_PROC_STAT;
732         }
733
734         while (1) {
735                 retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
736                 if (retval != 1)
737                         break;
738
739                 retval = func(cpu_num);
740                 if (retval) {
741                         fclose(fp);
742                         return(retval);
743                 }
744         }
745         fclose(fp);
746         return 0;
747 }
748
749 /*
750  * count_cpus()
751  * remember the last one seen, it will be the max
752  */
753 static int
754 count_cpus(int cpu)
755 {
756         if (topo.max_cpu_num < cpu)
757                 topo.max_cpu_num = cpu;
758
759         topo.num_cpus += 1;
760         return 0;
761 }
762 static int
763 mark_cpu_present(int cpu)
764 {
765         CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
766         return 0;
767 }
768
769
770 static void
771 turbostat_submit (const char *plugin_instance,
772         const char *type, const char *type_instance,
773         gauge_t value)
774 {
775         value_list_t vl = VALUE_LIST_INIT;
776         value_t v;
777
778         v.gauge = value;
779         vl.values = &v;
780         vl.values_len = 1;
781         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
782         sstrncpy (vl.plugin, PLUGIN_NAME, sizeof (vl.plugin));
783         if (plugin_instance != NULL)
784                 sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
785         sstrncpy (vl.type, type, sizeof (vl.type));
786         if (type_instance != NULL)
787                 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
788
789         plugin_dispatch_values (&vl);
790 }
791
792 /*
793  * column formatting convention & formats
794  * package: "pk" 2 columns %2d
795  * core: "cor" 3 columns %3d
796  * CPU: "CPU" 3 columns %3d
797  * Pkg_W: %6.2
798  * Cor_W: %6.2
799  * GFX_W: %5.2
800  * RAM_W: %5.2
801  * GHz: "GHz" 3 columns %3.2
802  * TSC: "TSC" 3 columns %3.2
803  * SMI: "SMI" 4 columns %4d
804  * percentage " %pc3" %6.2
805  * Perf Status percentage: %5.2
806  * "CTMP" 4 columns %4d
807  */
808 #define NAME_LEN 12
809 static int
810 submit_counters(struct thread_data *t, struct core_data *c,
811         struct pkg_data *p)
812 {
813         char name[NAME_LEN];
814         double interval_float;
815
816         interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
817
818         snprintf(name, NAME_LEN, "cpu%02d", t->cpu_id);
819
820         if (do_nhm_cstates) {
821                 if (!skip_c0)
822                         turbostat_submit(name, "percent", "c0", 100.0 * t->mperf/t->tsc);
823                 if (!skip_c1)
824                         turbostat_submit(name, "percent", "c1", 100.0 * t->c1/t->tsc);
825         }
826
827         /* GHz */
828         if (has_aperf && ((!aperf_mperf_unstable) || (!(t->aperf > t->tsc || t->mperf > t->tsc))))
829                 turbostat_submit(NULL, "frequency", name, 1.0 * t->tsc / units * t->aperf / t->mperf / interval_float);
830
831         /* SMI */
832         if (do_smi)
833                 turbostat_submit(NULL, "current", name, t->smi_count);
834
835         /* print per-core data only for 1st thread in core */
836         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
837                 goto done;
838
839         snprintf(name, NAME_LEN, "core%02d", c->core_id);
840
841         if (do_nhm_cstates && !do_slm_cstates)
842                 turbostat_submit(name, "percent", "c3", 100.0 * c->c3/t->tsc);
843         if (do_nhm_cstates)
844                 turbostat_submit(name, "percent", "c6", 100.0 * c->c6/t->tsc);
845         if (do_snb_cstates)
846                 turbostat_submit(name, "percent", "c7", 100.0 * c->c7/t->tsc);
847
848         if (do_dts)
849                 turbostat_submit(NULL, "temperature", name, c->core_temp_c);
850
851         /* print per-package data only for 1st core in package */
852         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
853                 goto done;
854
855         snprintf(name, NAME_LEN, "pkg%02d", p->package_id);
856
857         if (do_ptm)
858                 turbostat_submit(NULL, "temperature", name, p->pkg_temp_c);
859
860         if (do_snb_cstates)
861                 turbostat_submit(name, "percent", "pc2", 100.0 * p->pc2/t->tsc);
862         if (do_nhm_cstates && !do_slm_cstates)
863                 turbostat_submit(name, "percent", "pc3", 100.0 * p->pc3/t->tsc);
864         if (do_nhm_cstates && !do_slm_cstates)
865                 turbostat_submit(name, "percent", "pc6", 100.0 * p->pc6/t->tsc);
866         if (do_snb_cstates)
867                 turbostat_submit(name, "percent", "pc7", 100.0 * p->pc7/t->tsc);
868         if (do_c8_c9_c10) {
869                 turbostat_submit(name, "percent", "pc8", 100.0 * p->pc8/t->tsc);
870                 turbostat_submit(name, "percent", "pc9", 100.0 * p->pc9/t->tsc);
871                 turbostat_submit(name, "percent", "pc10", 100.0 * p->pc10/t->tsc);
872         }
873
874         if (do_rapl) {
875                 if (do_rapl & RAPL_PKG)
876                         turbostat_submit(name, "power", "Pkg_W", p->energy_pkg * rapl_energy_units / interval_float);
877                 if (do_rapl & RAPL_CORES)
878                         turbostat_submit(name, "power", "Cor_W", p->energy_cores * rapl_energy_units / interval_float);
879                 if (do_rapl & RAPL_GFX)
880                         turbostat_submit(name, "power", "GFX_W", p->energy_gfx * rapl_energy_units / interval_float);
881                 if (do_rapl & RAPL_DRAM)
882                         turbostat_submit(name, "power", "RAM_W", p->energy_dram * rapl_energy_units / interval_float);
883         }
884 done:
885         return 0;
886 }
887
888 static int
889 turbostat_read(user_data_t * not_used)
890 {
891         int ret;
892
893         if (!allocated) {
894                 if ((ret = setup_all_buffers()) < 0)
895                         return ret;
896         }
897
898         if (for_all_proc_cpus(cpu_is_not_present)) {
899                 free_all_buffers();
900                 if ((ret = setup_all_buffers()) < 0)
901                         return ret;
902                 if (for_all_proc_cpus(cpu_is_not_present))
903                         return -ERR_CPU_NOT_PRESENT;
904         }
905
906         if (!initialized) {
907                 if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
908                         return ret;
909                 gettimeofday(&tv_even, (struct timezone *)NULL);
910                 is_even = true;
911                 initialized = true;
912                 return 0;
913         }
914
915         if (is_even) {
916                 if ((ret = for_all_cpus(get_counters, ODD_COUNTERS)) < 0)
917                         return ret;
918                 gettimeofday(&tv_odd, (struct timezone *)NULL);
919                 is_even = false;
920                 timersub(&tv_odd, &tv_even, &tv_delta);
921                 if ((ret = for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS)) < 0)
922                         return ret;
923                 if ((ret = for_all_cpus(submit_counters, EVEN_COUNTERS)) < 0)
924                         return ret;
925         } else {
926                 if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0)
927                         return ret;
928                 gettimeofday(&tv_even, (struct timezone *)NULL);
929                 is_even = true;
930                 timersub(&tv_even, &tv_odd, &tv_delta);
931                 if ((ret = for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS)) < 0)
932                         return ret;
933                 if ((ret = for_all_cpus(submit_counters, ODD_COUNTERS)) < 0)
934                         return ret;
935         }
936         return 0;
937 }
938
939 static int __must_check
940 check_dev_msr()
941 {
942         struct stat sb;
943
944         if (stat("/dev/cpu/0/msr", &sb)) {
945                 ERROR("no /dev/cpu/0/msr\n"
946                         "Try \"# modprobe msr\"");
947                 return -ERR_NO_MSR;
948         }
949         return 0;
950 }
951
952 static int __must_check
953 check_super_user()
954 {
955         if (getuid() != 0) {
956                 ERROR("must be root");
957                 return -ERR_NOT_ROOT;
958         }
959         return 0;
960 }
961
962
963 #define RAPL_POWER_GRANULARITY  0x7FFF  /* 15 bit power granularity */
964 #define RAPL_TIME_GRANULARITY   0x3F /* 6 bit time granularity */
965
966 static double
967 get_tdp(unsigned int model)
968 {
969         unsigned long long msr;
970
971         if (do_rapl & RAPL_PKG_POWER_INFO)
972                 if (!get_msr(0, MSR_PKG_POWER_INFO, &msr))
973                         return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
974
975         switch (model) {
976         case 0x37:
977         case 0x4D:
978                 return 30.0;
979         default:
980                 return 135.0;
981         }
982 }
983
984
985 /*
986  * rapl_probe()
987  *
988  * sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
989  */
990 static void
991 rapl_probe(unsigned int family, unsigned int model)
992 {
993         unsigned long long msr;
994         unsigned int time_unit;
995         double tdp;
996
997         if (!genuine_intel)
998                 return;
999
1000         if (family != 6)
1001                 return;
1002
1003         switch (model) {
1004         case 0x2A:
1005         case 0x3A:
1006         case 0x3C:      /* HSW */
1007         case 0x45:      /* HSW */
1008         case 0x46:      /* HSW */
1009                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
1010                 break;
1011         case 0x3F:      /* HSX */
1012                 do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
1013                 break;
1014         case 0x2D:
1015         case 0x3E:
1016                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_PKG_PERF_STATUS | RAPL_DRAM_PERF_STATUS | RAPL_PKG_POWER_INFO;
1017                 break;
1018         case 0x37:      /* BYT */
1019         case 0x4D:      /* AVN */
1020                 do_rapl = RAPL_PKG | RAPL_CORES ;
1021                 break;
1022         default:
1023                 return;
1024         }
1025
1026         /* units on package 0, verify later other packages match */
1027         if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr))
1028                 return;
1029
1030         rapl_power_units = 1.0 / (1 << (msr & 0xF));
1031         if (model == 0x37)
1032                 rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
1033         else
1034                 rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
1035
1036         time_unit = msr >> 16 & 0xF;
1037         if (time_unit == 0)
1038                 time_unit = 0xA;
1039
1040         rapl_time_units = 1.0 / (1 << (time_unit));
1041
1042         tdp = get_tdp(model);
1043
1044         rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
1045 //      if (verbose)
1046 //              fprintf(stderr, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
1047
1048         return;
1049 }
1050
1051 static int
1052 is_snb(unsigned int family, unsigned int model)
1053 {
1054         if (!genuine_intel)
1055                 return 0;
1056
1057         switch (model) {
1058         case 0x2A:
1059         case 0x2D:
1060         case 0x3A:      /* IVB */
1061         case 0x3E:      /* IVB Xeon */
1062         case 0x3C:      /* HSW */
1063         case 0x3F:      /* HSW */
1064         case 0x45:      /* HSW */
1065         case 0x46:      /* HSW */
1066                 return 1;
1067         }
1068         return 0;
1069 }
1070
1071 static int
1072 has_c8_c9_c10(unsigned int family, unsigned int model)
1073 {
1074         if (!genuine_intel)
1075                 return 0;
1076
1077         switch (model) {
1078         case 0x45:
1079                 return 1;
1080         }
1081         return 0;
1082 }
1083
1084
1085 static int
1086 is_slm(unsigned int family, unsigned int model)
1087 {
1088         if (!genuine_intel)
1089                 return 0;
1090         switch (model) {
1091         case 0x37:      /* BYT */
1092         case 0x4D:      /* AVN */
1093                 return 1;
1094         }
1095         return 0;
1096 }
1097
1098 /*
1099  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
1100  * the Thermal Control Circuit (TCC) activates.
1101  * This is usually equal to tjMax.
1102  *
1103  * Older processors do not have this MSR, so there we guess,
1104  * but also allow cmdline over-ride with -T.
1105  *
1106  * Several MSR temperature values are in units of degrees-C
1107  * below this value, including the Digital Thermal Sensor (DTS),
1108  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
1109  */
1110 static int __must_check
1111 set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1112 {
1113         unsigned long long msr;
1114         unsigned int target_c_local;
1115         int cpu;
1116
1117         /* tcc_activation_temp is used only for dts or ptm */
1118         if (!(do_dts || do_ptm))
1119                 return 0;
1120
1121         /* this is a per-package concept */
1122         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1123                 return 0;
1124
1125         cpu = t->cpu_id;
1126         if (cpu_migrate(cpu)) {
1127                 ERROR("Could not migrate to CPU %d\n", cpu);
1128                 return -ERR_CPU_MIGRATE;
1129         }
1130
1131         if (tcc_activation_temp_override != 0) {
1132                 tcc_activation_temp = tcc_activation_temp_override;
1133                 ERROR("cpu%d: Using cmdline TCC Target (%d C)\n",
1134                         cpu, tcc_activation_temp);
1135                 return 0;
1136         }
1137
1138         /* Temperature Target MSR is Nehalem and newer only */
1139         if (!do_nehalem_platform_info)
1140                 goto guess;
1141
1142         if (get_msr(0, MSR_IA32_TEMPERATURE_TARGET, &msr))
1143                 goto guess;
1144
1145         target_c_local = (msr >> 16) & 0x7F;
1146
1147         if (target_c_local < 85 || target_c_local > 127)
1148                 goto guess;
1149
1150         tcc_activation_temp = target_c_local;
1151
1152         return 0;
1153
1154 guess:
1155         tcc_activation_temp = TJMAX_DEFAULT;
1156         WARNING("cpu%d: Guessing tjMax %d C, Please use -T to specify\n",
1157                 cpu, tcc_activation_temp);
1158
1159         return 0;
1160 }
1161
1162 static int __must_check
1163 check_cpuid()
1164 {
1165         unsigned int eax, ebx, ecx, edx, max_level;
1166         unsigned int fms, family, model;
1167
1168         eax = ebx = ecx = edx = 0;
1169
1170         __get_cpuid(0, &max_level, &ebx, &ecx, &edx);
1171
1172         if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
1173                 genuine_intel = 1;
1174
1175         fms = 0;
1176         __get_cpuid(1, &fms, &ebx, &ecx, &edx);
1177         family = (fms >> 8) & 0xf;
1178         model = (fms >> 4) & 0xf;
1179         if (family == 6 || family == 0xf)
1180                 model += ((fms >> 16) & 0xf) << 4;
1181
1182         if (!(edx & (1 << 5))) {
1183                 ERROR("CPUID: no MSR");
1184                 return -ERR_NO_MSR;
1185         }
1186
1187         /*
1188          * check max extended function levels of CPUID.
1189          * This is needed to check for invariant TSC.
1190          * This check is valid for both Intel and AMD.
1191          */
1192         ebx = ecx = edx = 0;
1193         __get_cpuid(0x80000000, &max_level, &ebx, &ecx, &edx);
1194
1195         if (max_level < 0x80000007) {
1196                 ERROR("CPUID: no invariant TSC (max_level 0x%x)", max_level);
1197                 return -ERR_NO_INVARIANT_TSC;
1198         }
1199
1200         /*
1201          * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
1202          * this check is valid for both Intel and AMD
1203          */
1204         __get_cpuid(0x80000007, &eax, &ebx, &ecx, &edx);
1205         has_invariant_tsc = edx & (1 << 8);
1206
1207         if (!has_invariant_tsc) {
1208                 ERROR("No invariant TSC");
1209                 return -ERR_NO_INVARIANT_TSC;
1210         }
1211
1212         /*
1213          * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
1214          * this check is valid for both Intel and AMD
1215          */
1216
1217         __get_cpuid(0x6, &eax, &ebx, &ecx, &edx);
1218         has_aperf = ecx & (1 << 0);
1219         do_dts = eax & (1 << 0);
1220         do_ptm = eax & (1 << 6);
1221         has_epb = ecx & (1 << 3);
1222
1223         if (!has_aperf) {
1224                 ERROR("No APERF");
1225                 return -ERR_NO_APERF;
1226         }
1227
1228         do_nehalem_platform_info = genuine_intel && has_invariant_tsc;
1229         do_nhm_cstates = genuine_intel; /* all Intel w/ non-stop TSC have NHM counters */
1230         do_smi = do_nhm_cstates;
1231         do_snb_cstates = is_snb(family, model);
1232         do_c8_c9_c10 = has_c8_c9_c10(family, model);
1233         do_slm_cstates = is_slm(family, model);
1234
1235         rapl_probe(family, model);
1236
1237         return 0;
1238 }
1239
1240
1241
1242 static int __must_check
1243 topology_probe()
1244 {
1245         int i;
1246         int ret;
1247         int max_core_id = 0;
1248         int max_package_id = 0;
1249         int max_siblings = 0;
1250         struct cpu_topology {
1251                 int core_id;
1252                 int physical_package_id;
1253         } *cpus;
1254
1255         /* Initialize num_cpus, max_cpu_num */
1256         topo.num_cpus = 0;
1257         topo.max_cpu_num = 0;
1258         ret = for_all_proc_cpus(count_cpus);
1259         if (ret < 0)
1260                 return ret;
1261         if (topo.num_cpus > 1)
1262                 show_cpu = 1;
1263
1264         DEBUG("num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
1265
1266         cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
1267         if (cpus == NULL) {
1268                 ERROR("calloc cpus");
1269                 return -ERR_CALLOC;
1270         }
1271
1272         /*
1273          * Allocate and initialize cpu_present_set
1274          */
1275         cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
1276         if (cpu_present_set == NULL) {
1277                 free(cpus);
1278                 ERROR("CPU_ALLOC");
1279                 return -ERR_CPU_ALLOC;
1280         }
1281         cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
1282         CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
1283         ret = for_all_proc_cpus(mark_cpu_present);
1284         if (ret < 0) {
1285                 free(cpus);
1286                 return ret;
1287         }
1288
1289         /*
1290          * Allocate and initialize cpu_affinity_set
1291          */
1292         cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
1293         if (cpu_affinity_set == NULL) {
1294                 free(cpus);
1295                 ERROR("CPU_ALLOC");
1296                 return -ERR_CPU_ALLOC;
1297         }
1298         cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
1299         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
1300
1301
1302         /*
1303          * For online cpus
1304          * find max_core_id, max_package_id
1305          */
1306         for (i = 0; i <= topo.max_cpu_num; ++i) {
1307                 int siblings;
1308
1309                 if (cpu_is_not_present(i)) {
1310                         //if (verbose > 1)
1311                                 fprintf(stderr, "cpu%d NOT PRESENT\n", i);
1312                         continue;
1313                 }
1314                 cpus[i].core_id = get_core_id(i);
1315                 if (cpus[i].core_id < 0)
1316                         return cpus[i].core_id;
1317                 if (cpus[i].core_id > max_core_id)
1318                         max_core_id = cpus[i].core_id;
1319
1320                 cpus[i].physical_package_id = get_physical_package_id(i);
1321                 if (cpus[i].physical_package_id < 0)
1322                         return cpus[i].physical_package_id;
1323                 if (cpus[i].physical_package_id > max_package_id)
1324                         max_package_id = cpus[i].physical_package_id;
1325
1326                 siblings = get_num_ht_siblings(i);
1327                 if (siblings < 0)
1328                         return siblings;
1329                 if (siblings > max_siblings)
1330                         max_siblings = siblings;
1331                 DEBUG("cpu %d pkg %d core %d\n",
1332                         i, cpus[i].physical_package_id, cpus[i].core_id);
1333         }
1334         topo.num_cores_per_pkg = max_core_id + 1;
1335         DEBUG("max_core_id %d, sizing for %d cores per package\n",
1336                 max_core_id, topo.num_cores_per_pkg);
1337         if (topo.num_cores_per_pkg > 1)
1338                 show_core = 1;
1339
1340         topo.num_packages = max_package_id + 1;
1341         DEBUG("max_package_id %d, sizing for %d packages\n",
1342                 max_package_id, topo.num_packages);
1343         if (topo.num_packages > 1)
1344                 show_pkg = 1;
1345
1346         topo.num_threads_per_core = max_siblings;
1347         DEBUG("max_siblings %d\n", max_siblings);
1348
1349         free(cpus);
1350         return 0;
1351 }
1352
1353 static int
1354 allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
1355 {
1356         int i;
1357
1358         *t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
1359                 topo.num_packages, sizeof(struct thread_data));
1360         if (*t == NULL)
1361                 goto error;
1362
1363         for (i = 0; i < topo.num_threads_per_core *
1364                 topo.num_cores_per_pkg * topo.num_packages; i++)
1365                 (*t)[i].cpu_id = -1;
1366
1367         *c = calloc(topo.num_cores_per_pkg * topo.num_packages,
1368                 sizeof(struct core_data));
1369         if (*c == NULL)
1370                 goto error;
1371
1372         for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
1373                 (*c)[i].core_id = -1;
1374
1375         *p = calloc(topo.num_packages, sizeof(struct pkg_data));
1376         if (*p == NULL)
1377                 goto error;
1378
1379         for (i = 0; i < topo.num_packages; i++)
1380                 (*p)[i].package_id = i;
1381
1382         return 0;
1383 error:
1384         ERROR("calloc counters");
1385         return -ERR_CALLOC;
1386 }
1387 /*
1388  * init_counter()
1389  *
1390  * set cpu_id, core_num, pkg_num
1391  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
1392  *
1393  * increment topo.num_cores when 1st core in pkg seen
1394  */
1395 static int
1396 init_counter(struct thread_data *thread_base, struct core_data *core_base,
1397         struct pkg_data *pkg_base, int thread_num, int core_num,
1398         int pkg_num, int cpu_id)
1399 {
1400         int ret;
1401         struct thread_data *t;
1402         struct core_data *c;
1403         struct pkg_data *p;
1404
1405         t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
1406         c = GET_CORE(core_base, core_num, pkg_num);
1407         p = GET_PKG(pkg_base, pkg_num);
1408
1409         t->cpu_id = cpu_id;
1410         if (thread_num == 0) {
1411                 t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
1412                 if ((ret = cpu_is_first_core_in_package(cpu_id)) < 0) {
1413                         return ret;
1414                 } else if (ret != 0) {
1415                         t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
1416                 }
1417         }
1418
1419         c->core_id = core_num;
1420         p->package_id = pkg_num;
1421
1422         return 0;
1423 }
1424
1425
1426 static int
1427 initialize_counters(int cpu_id)
1428 {
1429         int my_thread_id, my_core_id, my_package_id;
1430         int ret;
1431
1432         my_package_id = get_physical_package_id(cpu_id);
1433         if (my_package_id < 0)
1434                 return my_package_id;
1435         my_core_id = get_core_id(cpu_id);
1436         if (my_core_id < 0)
1437                 return my_core_id;
1438
1439         if ((ret = cpu_is_first_sibling_in_core(cpu_id)) < 0) {
1440                 return ret;
1441         } else if (ret != 0) {
1442                 my_thread_id = 0;
1443                 topo.num_cores++;
1444         } else {
1445                 my_thread_id = 1;
1446         }
1447
1448         ret = init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
1449         if (ret < 0)
1450                 return ret;
1451         ret = init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
1452         if (ret < 0)
1453                 return ret;
1454         return 0;
1455 }
1456
1457 #define DO_OR_GOTO_ERR(something) \
1458 do {                         \
1459         ret = (something);     \
1460         if (ret < 0)         \
1461                 goto err;    \
1462 } while (0)
1463
1464 static int setup_all_buffers(void)
1465 {
1466         int ret;
1467
1468         DO_OR_GOTO_ERR(topology_probe());
1469         DO_OR_GOTO_ERR(allocate_counters(&thread_even, &core_even, &package_even));
1470         DO_OR_GOTO_ERR(allocate_counters(&thread_odd, &core_odd, &package_odd));
1471         DO_OR_GOTO_ERR(for_all_proc_cpus(initialize_counters));
1472
1473         allocated = true;
1474         return 0;
1475 err:
1476         free_all_buffers();
1477         return ret;
1478 }
1479
1480 static int
1481 turbostat_init(void)
1482 {
1483         int ret;
1484         struct timespec ts;
1485
1486         DO_OR_GOTO_ERR(check_cpuid());
1487         DO_OR_GOTO_ERR(check_dev_msr());
1488         DO_OR_GOTO_ERR(check_super_user());
1489         DO_OR_GOTO_ERR(setup_all_buffers());
1490         DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, EVEN_COUNTERS));
1491
1492         ts.tv_sec = interval_sec;
1493         ts.tv_nsec = 0;
1494
1495         plugin_register_complex_read(NULL, PLUGIN_NAME, turbostat_read, &ts, NULL);
1496
1497         return 0;
1498 err:
1499         free_all_buffers();
1500         return ret;
1501 }
1502
1503 static const char *config_keys[] =
1504 {
1505         "Interval",
1506 };
1507 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
1508
1509 static int
1510 turbostat_config(const char *key, const char *value)
1511 {
1512         if (strcasecmp("Interval", key) == 0)
1513                 interval_sec = atoi(value);
1514         else
1515                 return -1;
1516         return 0;
1517 }
1518
1519 void module_register(void);
1520 void module_register(void)
1521 {
1522         plugin_register_init(PLUGIN_NAME, turbostat_init);
1523         plugin_register_config(PLUGIN_NAME, turbostat_config, config_keys, config_keys_num);
1524 }