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