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