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