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