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