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