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