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