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