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