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