tools/power turbostat: Support AMD Family 19h
[linux-2.6-microblaze.git] / tools / power / x86 / turbostat / turbostat.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * turbostat -- show CPU frequency and C-state residency
4  * on modern Intel and AMD processors.
5  *
6  * Copyright (c) 2013 Intel Corporation.
7  * Len Brown <len.brown@intel.com>
8  */
9
10 #define _GNU_SOURCE
11 #include MSRHEADER
12 #include INTEL_FAMILY_HEADER
13 #include <stdarg.h>
14 #include <stdio.h>
15 #include <err.h>
16 #include <unistd.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <sys/stat.h>
20 #include <sys/select.h>
21 #include <sys/resource.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <sys/time.h>
25 #include <stdlib.h>
26 #include <getopt.h>
27 #include <dirent.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <sched.h>
31 #include <time.h>
32 #include <cpuid.h>
33 #include <sys/capability.h>
34 #include <errno.h>
35 #include <math.h>
36
37 char *proc_stat = "/proc/stat";
38 FILE *outf;
39 int *fd_percpu;
40 struct timeval interval_tv = {5, 0};
41 struct timespec interval_ts = {5, 0};
42 unsigned int num_iterations;
43 unsigned int debug;
44 unsigned int quiet;
45 unsigned int shown;
46 unsigned int sums_need_wide_columns;
47 unsigned int rapl_joules;
48 unsigned int summary_only;
49 unsigned int list_header_only;
50 unsigned int dump_only;
51 unsigned int do_snb_cstates;
52 unsigned int do_knl_cstates;
53 unsigned int do_slm_cstates;
54 unsigned int use_c1_residency_msr;
55 unsigned int has_aperf;
56 unsigned int has_epb;
57 unsigned int do_irtl_snb;
58 unsigned int do_irtl_hsw;
59 unsigned int units = 1000000;   /* MHz etc */
60 unsigned int genuine_intel;
61 unsigned int authentic_amd;
62 unsigned int hygon_genuine;
63 unsigned int max_level, max_extended_level;
64 unsigned int has_invariant_tsc;
65 unsigned int do_nhm_platform_info;
66 unsigned int no_MSR_MISC_PWR_MGMT;
67 unsigned int aperf_mperf_multiplier = 1;
68 double bclk;
69 double base_hz;
70 unsigned int has_base_hz;
71 double tsc_tweak = 1.0;
72 unsigned int show_pkg_only;
73 unsigned int show_core_only;
74 char *output_buffer, *outp;
75 unsigned int do_rapl;
76 unsigned int do_dts;
77 unsigned int do_ptm;
78 unsigned long long  gfx_cur_rc6_ms;
79 unsigned long long cpuidle_cur_cpu_lpi_us;
80 unsigned long long cpuidle_cur_sys_lpi_us;
81 unsigned int gfx_cur_mhz;
82 unsigned int gfx_act_mhz;
83 unsigned int tcc_activation_temp;
84 unsigned int tcc_activation_temp_override;
85 double rapl_power_units, rapl_time_units;
86 double rapl_dram_energy_units, rapl_energy_units;
87 double rapl_joule_counter_range;
88 unsigned int do_core_perf_limit_reasons;
89 unsigned int has_automatic_cstate_conversion;
90 unsigned int do_gfx_perf_limit_reasons;
91 unsigned int do_ring_perf_limit_reasons;
92 unsigned int crystal_hz;
93 unsigned long long tsc_hz;
94 int base_cpu;
95 double discover_bclk(unsigned int family, unsigned int model);
96 unsigned int has_hwp;   /* IA32_PM_ENABLE, IA32_HWP_CAPABILITIES */
97                         /* IA32_HWP_REQUEST, IA32_HWP_STATUS */
98 unsigned int has_hwp_notify;            /* IA32_HWP_INTERRUPT */
99 unsigned int has_hwp_activity_window;   /* IA32_HWP_REQUEST[bits 41:32] */
100 unsigned int has_hwp_epp;               /* IA32_HWP_REQUEST[bits 31:24] */
101 unsigned int has_hwp_pkg;               /* IA32_HWP_REQUEST_PKG */
102 unsigned int has_misc_feature_control;
103 unsigned int first_counter_read = 1;
104 int ignore_stdin;
105
106 #define RAPL_PKG                (1 << 0)
107                                         /* 0x610 MSR_PKG_POWER_LIMIT */
108                                         /* 0x611 MSR_PKG_ENERGY_STATUS */
109 #define RAPL_PKG_PERF_STATUS    (1 << 1)
110                                         /* 0x613 MSR_PKG_PERF_STATUS */
111 #define RAPL_PKG_POWER_INFO     (1 << 2)
112                                         /* 0x614 MSR_PKG_POWER_INFO */
113
114 #define RAPL_DRAM               (1 << 3)
115                                         /* 0x618 MSR_DRAM_POWER_LIMIT */
116                                         /* 0x619 MSR_DRAM_ENERGY_STATUS */
117 #define RAPL_DRAM_PERF_STATUS   (1 << 4)
118                                         /* 0x61b MSR_DRAM_PERF_STATUS */
119 #define RAPL_DRAM_POWER_INFO    (1 << 5)
120                                         /* 0x61c MSR_DRAM_POWER_INFO */
121
122 #define RAPL_CORES_POWER_LIMIT  (1 << 6)
123                                         /* 0x638 MSR_PP0_POWER_LIMIT */
124 #define RAPL_CORE_POLICY        (1 << 7)
125                                         /* 0x63a MSR_PP0_POLICY */
126
127 #define RAPL_GFX                (1 << 8)
128                                         /* 0x640 MSR_PP1_POWER_LIMIT */
129                                         /* 0x641 MSR_PP1_ENERGY_STATUS */
130                                         /* 0x642 MSR_PP1_POLICY */
131
132 #define RAPL_CORES_ENERGY_STATUS        (1 << 9)
133                                         /* 0x639 MSR_PP0_ENERGY_STATUS */
134 #define RAPL_PER_CORE_ENERGY    (1 << 10)
135                                         /* Indicates cores energy collection is per-core,
136                                          * not per-package. */
137 #define RAPL_AMD_F17H           (1 << 11)
138                                         /* 0xc0010299 MSR_RAPL_PWR_UNIT */
139                                         /* 0xc001029a MSR_CORE_ENERGY_STAT */
140                                         /* 0xc001029b MSR_PKG_ENERGY_STAT */
141 #define RAPL_CORES (RAPL_CORES_ENERGY_STATUS | RAPL_CORES_POWER_LIMIT)
142 #define TJMAX_DEFAULT   100
143
144 /* MSRs that are not yet in the kernel-provided header. */
145 #define MSR_RAPL_PWR_UNIT       0xc0010299
146 #define MSR_CORE_ENERGY_STAT    0xc001029a
147 #define MSR_PKG_ENERGY_STAT     0xc001029b
148
149 #define MAX(a, b) ((a) > (b) ? (a) : (b))
150
151 /*
152  * buffer size used by sscanf() for added column names
153  * Usually truncated to 7 characters, but also handles 18 columns for raw 64-bit counters
154  */
155 #define NAME_BYTES 20
156 #define PATH_BYTES 128
157
158 int backwards_count;
159 char *progname;
160
161 #define CPU_SUBSET_MAXCPUS      1024    /* need to use before probe... */
162 cpu_set_t *cpu_present_set, *cpu_affinity_set, *cpu_subset;
163 size_t cpu_present_setsize, cpu_affinity_setsize, cpu_subset_size;
164 #define MAX_ADDED_COUNTERS 8
165 #define MAX_ADDED_THREAD_COUNTERS 24
166 #define BITMASK_SIZE 32
167
168 struct thread_data {
169         struct timeval tv_begin;
170         struct timeval tv_end;
171         struct timeval tv_delta;
172         unsigned long long tsc;
173         unsigned long long aperf;
174         unsigned long long mperf;
175         unsigned long long c1;
176         unsigned long long  irq_count;
177         unsigned int smi_count;
178         unsigned int cpu_id;
179         unsigned int apic_id;
180         unsigned int x2apic_id;
181         unsigned int flags;
182 #define CPU_IS_FIRST_THREAD_IN_CORE     0x2
183 #define CPU_IS_FIRST_CORE_IN_PACKAGE    0x4
184         unsigned long long counter[MAX_ADDED_THREAD_COUNTERS];
185 } *thread_even, *thread_odd;
186
187 struct core_data {
188         unsigned long long c3;
189         unsigned long long c6;
190         unsigned long long c7;
191         unsigned long long mc6_us;      /* duplicate as per-core for now, even though per module */
192         unsigned int core_temp_c;
193         unsigned int core_energy;       /* MSR_CORE_ENERGY_STAT */
194         unsigned int core_id;
195         unsigned long long counter[MAX_ADDED_COUNTERS];
196 } *core_even, *core_odd;
197
198 struct pkg_data {
199         unsigned long long pc2;
200         unsigned long long pc3;
201         unsigned long long pc6;
202         unsigned long long pc7;
203         unsigned long long pc8;
204         unsigned long long pc9;
205         unsigned long long pc10;
206         unsigned long long cpu_lpi;
207         unsigned long long sys_lpi;
208         unsigned long long pkg_wtd_core_c0;
209         unsigned long long pkg_any_core_c0;
210         unsigned long long pkg_any_gfxe_c0;
211         unsigned long long pkg_both_core_gfxe_c0;
212         long long gfx_rc6_ms;
213         unsigned int gfx_mhz;
214         unsigned int gfx_act_mhz;
215         unsigned int package_id;
216         unsigned long long energy_pkg;  /* MSR_PKG_ENERGY_STATUS */
217         unsigned long long energy_dram; /* MSR_DRAM_ENERGY_STATUS */
218         unsigned long long energy_cores;        /* MSR_PP0_ENERGY_STATUS */
219         unsigned long long energy_gfx;  /* MSR_PP1_ENERGY_STATUS */
220         unsigned long long rapl_pkg_perf_status;        /* MSR_PKG_PERF_STATUS */
221         unsigned long long rapl_dram_perf_status;       /* MSR_DRAM_PERF_STATUS */
222         unsigned int pkg_temp_c;
223         unsigned long long counter[MAX_ADDED_COUNTERS];
224 } *package_even, *package_odd;
225
226 #define ODD_COUNTERS thread_odd, core_odd, package_odd
227 #define EVEN_COUNTERS thread_even, core_even, package_even
228
229 #define GET_THREAD(thread_base, thread_no, core_no, node_no, pkg_no)          \
230         ((thread_base) +                                                      \
231          ((pkg_no) *                                                          \
232           topo.nodes_per_pkg * topo.cores_per_node * topo.threads_per_core) + \
233          ((node_no) * topo.cores_per_node * topo.threads_per_core) +          \
234          ((core_no) * topo.threads_per_core) +                                \
235          (thread_no))
236
237 #define GET_CORE(core_base, core_no, node_no, pkg_no)                   \
238         ((core_base) +                                                  \
239          ((pkg_no) *  topo.nodes_per_pkg * topo.cores_per_node) +       \
240          ((node_no) * topo.cores_per_node) +                            \
241          (core_no))
242
243
244 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
245
246 enum counter_scope {SCOPE_CPU, SCOPE_CORE, SCOPE_PACKAGE};
247 enum counter_type {COUNTER_ITEMS, COUNTER_CYCLES, COUNTER_SECONDS, COUNTER_USEC};
248 enum counter_format {FORMAT_RAW, FORMAT_DELTA, FORMAT_PERCENT};
249
250 struct msr_counter {
251         unsigned int msr_num;
252         char name[NAME_BYTES];
253         char path[PATH_BYTES];
254         unsigned int width;
255         enum counter_type type;
256         enum counter_format format;
257         struct msr_counter *next;
258         unsigned int flags;
259 #define FLAGS_HIDE      (1 << 0)
260 #define FLAGS_SHOW      (1 << 1)
261 #define SYSFS_PERCPU    (1 << 1)
262 };
263
264 /*
265  * The accumulated sum of MSR is defined as a monotonic
266  * increasing MSR, it will be accumulated periodically,
267  * despite its register's bit width.
268  */
269 enum {
270         IDX_PKG_ENERGY,
271         IDX_DRAM_ENERGY,
272         IDX_PP0_ENERGY,
273         IDX_PP1_ENERGY,
274         IDX_PKG_PERF,
275         IDX_DRAM_PERF,
276         IDX_COUNT,
277 };
278
279 int get_msr_sum(int cpu, off_t offset, unsigned long long *msr);
280
281 struct msr_sum_array {
282         /* get_msr_sum() = sum + (get_msr() - last) */
283         struct {
284                 /*The accumulated MSR value is updated by the timer*/
285                 unsigned long long sum;
286                 /*The MSR footprint recorded in last timer*/
287                 unsigned long long last;
288         } entries[IDX_COUNT];
289 };
290
291 /* The percpu MSR sum array.*/
292 struct msr_sum_array *per_cpu_msr_sum;
293
294 int idx_to_offset(int idx)
295 {
296         int offset;
297
298         switch (idx) {
299         case IDX_PKG_ENERGY:
300                 offset = MSR_PKG_ENERGY_STATUS;
301                 break;
302         case IDX_DRAM_ENERGY:
303                 offset = MSR_DRAM_ENERGY_STATUS;
304                 break;
305         case IDX_PP0_ENERGY:
306                 offset = MSR_PP0_ENERGY_STATUS;
307                 break;
308         case IDX_PP1_ENERGY:
309                 offset = MSR_PP1_ENERGY_STATUS;
310                 break;
311         case IDX_PKG_PERF:
312                 offset = MSR_PKG_PERF_STATUS;
313                 break;
314         case IDX_DRAM_PERF:
315                 offset = MSR_DRAM_PERF_STATUS;
316                 break;
317         default:
318                 offset = -1;
319         }
320         return offset;
321 }
322
323 int offset_to_idx(int offset)
324 {
325         int idx;
326
327         switch (offset) {
328         case MSR_PKG_ENERGY_STATUS:
329                 idx = IDX_PKG_ENERGY;
330                 break;
331         case MSR_DRAM_ENERGY_STATUS:
332                 idx = IDX_DRAM_ENERGY;
333                 break;
334         case MSR_PP0_ENERGY_STATUS:
335                 idx = IDX_PP0_ENERGY;
336                 break;
337         case MSR_PP1_ENERGY_STATUS:
338                 idx = IDX_PP1_ENERGY;
339                 break;
340         case MSR_PKG_PERF_STATUS:
341                 idx = IDX_PKG_PERF;
342                 break;
343         case MSR_DRAM_PERF_STATUS:
344                 idx = IDX_DRAM_PERF;
345                 break;
346         default:
347                 idx = -1;
348         }
349         return idx;
350 }
351
352 int idx_valid(int idx)
353 {
354         switch (idx) {
355         case IDX_PKG_ENERGY:
356                 return do_rapl & RAPL_PKG;
357         case IDX_DRAM_ENERGY:
358                 return do_rapl & RAPL_DRAM;
359         case IDX_PP0_ENERGY:
360                 return do_rapl & RAPL_CORES_ENERGY_STATUS;
361         case IDX_PP1_ENERGY:
362                 return do_rapl & RAPL_GFX;
363         case IDX_PKG_PERF:
364                 return do_rapl & RAPL_PKG_PERF_STATUS;
365         case IDX_DRAM_PERF:
366                 return do_rapl & RAPL_DRAM_PERF_STATUS;
367         default:
368                 return 0;
369         }
370 }
371 struct sys_counters {
372         unsigned int added_thread_counters;
373         unsigned int added_core_counters;
374         unsigned int added_package_counters;
375         struct msr_counter *tp;
376         struct msr_counter *cp;
377         struct msr_counter *pp;
378 } sys;
379
380 struct system_summary {
381         struct thread_data threads;
382         struct core_data cores;
383         struct pkg_data packages;
384 } average;
385
386 struct cpu_topology {
387         int physical_package_id;
388         int die_id;
389         int logical_cpu_id;
390         int physical_node_id;
391         int logical_node_id;    /* 0-based count within the package */
392         int physical_core_id;
393         int thread_id;
394         cpu_set_t *put_ids; /* Processing Unit/Thread IDs */
395 } *cpus;
396
397 struct topo_params {
398         int num_packages;
399         int num_die;
400         int num_cpus;
401         int num_cores;
402         int max_cpu_num;
403         int max_node_num;
404         int nodes_per_pkg;
405         int cores_per_node;
406         int threads_per_core;
407 } topo;
408
409 struct timeval tv_even, tv_odd, tv_delta;
410
411 int *irq_column_2_cpu;  /* /proc/interrupts column numbers */
412 int *irqs_per_cpu;              /* indexed by cpu_num */
413
414 void setup_all_buffers(void);
415
416 char *sys_lpi_file;
417 char *sys_lpi_file_sysfs = "/sys/devices/system/cpu/cpuidle/low_power_idle_system_residency_us";
418 char *sys_lpi_file_debugfs = "/sys/kernel/debug/pmc_core/slp_s0_residency_usec";
419
420 int cpu_is_not_present(int cpu)
421 {
422         return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
423 }
424 /*
425  * run func(thread, core, package) in topology order
426  * skip non-present cpus
427  */
428
429 int for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
430         struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
431 {
432         int retval, pkg_no, core_no, thread_no, node_no;
433
434         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
435                 for (node_no = 0; node_no < topo.nodes_per_pkg; node_no++) {
436                         for (core_no = 0; core_no < topo.cores_per_node; ++core_no) {
437                                 for (thread_no = 0; thread_no <
438                                         topo.threads_per_core; ++thread_no) {
439                                         struct thread_data *t;
440                                         struct core_data *c;
441                                         struct pkg_data *p;
442
443                                         t = GET_THREAD(thread_base, thread_no,
444                                                        core_no, node_no,
445                                                        pkg_no);
446
447                                         if (cpu_is_not_present(t->cpu_id))
448                                                 continue;
449
450                                         c = GET_CORE(core_base, core_no,
451                                                      node_no, pkg_no);
452                                         p = GET_PKG(pkg_base, pkg_no);
453
454                                         retval = func(t, c, p);
455                                         if (retval)
456                                                 return retval;
457                                 }
458                         }
459                 }
460         }
461         return 0;
462 }
463
464 int cpu_migrate(int cpu)
465 {
466         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
467         CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
468         if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1)
469                 return -1;
470         else
471                 return 0;
472 }
473 int get_msr_fd(int cpu)
474 {
475         char pathname[32];
476         int fd;
477
478         fd = fd_percpu[cpu];
479
480         if (fd)
481                 return fd;
482
483         sprintf(pathname, "/dev/cpu/%d/msr", cpu);
484         fd = open(pathname, O_RDONLY);
485         if (fd < 0)
486                 err(-1, "%s open failed, try chown or chmod +r /dev/cpu/*/msr, or run as root", pathname);
487
488         fd_percpu[cpu] = fd;
489
490         return fd;
491 }
492
493 int get_msr(int cpu, off_t offset, unsigned long long *msr)
494 {
495         ssize_t retval;
496
497         retval = pread(get_msr_fd(cpu), msr, sizeof(*msr), offset);
498
499         if (retval != sizeof *msr)
500                 err(-1, "cpu%d: msr offset 0x%llx read failed", cpu, (unsigned long long)offset);
501
502         return 0;
503 }
504
505 /*
506  * This list matches the column headers, except
507  * 1. built-in only, the sysfs counters are not here -- we learn of those at run-time
508  * 2. Core and CPU are moved to the end, we can't have strings that contain them
509  *    matching on them for --show and --hide.
510  */
511 struct msr_counter bic[] = {
512         { 0x0, "usec" },
513         { 0x0, "Time_Of_Day_Seconds" },
514         { 0x0, "Package" },
515         { 0x0, "Node" },
516         { 0x0, "Avg_MHz" },
517         { 0x0, "Busy%" },
518         { 0x0, "Bzy_MHz" },
519         { 0x0, "TSC_MHz" },
520         { 0x0, "IRQ" },
521         { 0x0, "SMI", "", 32, 0, FORMAT_DELTA, NULL},
522         { 0x0, "sysfs" },
523         { 0x0, "CPU%c1" },
524         { 0x0, "CPU%c3" },
525         { 0x0, "CPU%c6" },
526         { 0x0, "CPU%c7" },
527         { 0x0, "ThreadC" },
528         { 0x0, "CoreTmp" },
529         { 0x0, "CoreCnt" },
530         { 0x0, "PkgTmp" },
531         { 0x0, "GFX%rc6" },
532         { 0x0, "GFXMHz" },
533         { 0x0, "Pkg%pc2" },
534         { 0x0, "Pkg%pc3" },
535         { 0x0, "Pkg%pc6" },
536         { 0x0, "Pkg%pc7" },
537         { 0x0, "Pkg%pc8" },
538         { 0x0, "Pkg%pc9" },
539         { 0x0, "Pk%pc10" },
540         { 0x0, "CPU%LPI" },
541         { 0x0, "SYS%LPI" },
542         { 0x0, "PkgWatt" },
543         { 0x0, "CorWatt" },
544         { 0x0, "GFXWatt" },
545         { 0x0, "PkgCnt" },
546         { 0x0, "RAMWatt" },
547         { 0x0, "PKG_%" },
548         { 0x0, "RAM_%" },
549         { 0x0, "Pkg_J" },
550         { 0x0, "Cor_J" },
551         { 0x0, "GFX_J" },
552         { 0x0, "RAM_J" },
553         { 0x0, "Mod%c6" },
554         { 0x0, "Totl%C0" },
555         { 0x0, "Any%C0" },
556         { 0x0, "GFX%C0" },
557         { 0x0, "CPUGFX%" },
558         { 0x0, "Core" },
559         { 0x0, "CPU" },
560         { 0x0, "APIC" },
561         { 0x0, "X2APIC" },
562         { 0x0, "Die" },
563         { 0x0, "GFXAMHz" },
564 };
565
566 #define MAX_BIC (sizeof(bic) / sizeof(struct msr_counter))
567 #define BIC_USEC        (1ULL << 0)
568 #define BIC_TOD         (1ULL << 1)
569 #define BIC_Package     (1ULL << 2)
570 #define BIC_Node        (1ULL << 3)
571 #define BIC_Avg_MHz     (1ULL << 4)
572 #define BIC_Busy        (1ULL << 5)
573 #define BIC_Bzy_MHz     (1ULL << 6)
574 #define BIC_TSC_MHz     (1ULL << 7)
575 #define BIC_IRQ         (1ULL << 8)
576 #define BIC_SMI         (1ULL << 9)
577 #define BIC_sysfs       (1ULL << 10)
578 #define BIC_CPU_c1      (1ULL << 11)
579 #define BIC_CPU_c3      (1ULL << 12)
580 #define BIC_CPU_c6      (1ULL << 13)
581 #define BIC_CPU_c7      (1ULL << 14)
582 #define BIC_ThreadC     (1ULL << 15)
583 #define BIC_CoreTmp     (1ULL << 16)
584 #define BIC_CoreCnt     (1ULL << 17)
585 #define BIC_PkgTmp      (1ULL << 18)
586 #define BIC_GFX_rc6     (1ULL << 19)
587 #define BIC_GFXMHz      (1ULL << 20)
588 #define BIC_Pkgpc2      (1ULL << 21)
589 #define BIC_Pkgpc3      (1ULL << 22)
590 #define BIC_Pkgpc6      (1ULL << 23)
591 #define BIC_Pkgpc7      (1ULL << 24)
592 #define BIC_Pkgpc8      (1ULL << 25)
593 #define BIC_Pkgpc9      (1ULL << 26)
594 #define BIC_Pkgpc10     (1ULL << 27)
595 #define BIC_CPU_LPI     (1ULL << 28)
596 #define BIC_SYS_LPI     (1ULL << 29)
597 #define BIC_PkgWatt     (1ULL << 30)
598 #define BIC_CorWatt     (1ULL << 31)
599 #define BIC_GFXWatt     (1ULL << 32)
600 #define BIC_PkgCnt      (1ULL << 33)
601 #define BIC_RAMWatt     (1ULL << 34)
602 #define BIC_PKG__       (1ULL << 35)
603 #define BIC_RAM__       (1ULL << 36)
604 #define BIC_Pkg_J       (1ULL << 37)
605 #define BIC_Cor_J       (1ULL << 38)
606 #define BIC_GFX_J       (1ULL << 39)
607 #define BIC_RAM_J       (1ULL << 40)
608 #define BIC_Mod_c6      (1ULL << 41)
609 #define BIC_Totl_c0     (1ULL << 42)
610 #define BIC_Any_c0      (1ULL << 43)
611 #define BIC_GFX_c0      (1ULL << 44)
612 #define BIC_CPUGFX      (1ULL << 45)
613 #define BIC_Core        (1ULL << 46)
614 #define BIC_CPU         (1ULL << 47)
615 #define BIC_APIC        (1ULL << 48)
616 #define BIC_X2APIC      (1ULL << 49)
617 #define BIC_Die         (1ULL << 50)
618 #define BIC_GFXACTMHz   (1ULL << 51)
619
620 #define BIC_DISABLED_BY_DEFAULT (BIC_USEC | BIC_TOD | BIC_APIC | BIC_X2APIC)
621
622 unsigned long long bic_enabled = (0xFFFFFFFFFFFFFFFFULL & ~BIC_DISABLED_BY_DEFAULT);
623 unsigned long long bic_present = BIC_USEC | BIC_TOD | BIC_sysfs | BIC_APIC | BIC_X2APIC;
624
625 #define DO_BIC(COUNTER_NAME) (bic_enabled & bic_present & COUNTER_NAME)
626 #define DO_BIC_READ(COUNTER_NAME) (bic_present & COUNTER_NAME)
627 #define ENABLE_BIC(COUNTER_NAME) (bic_enabled |= COUNTER_NAME)
628 #define BIC_PRESENT(COUNTER_BIT) (bic_present |= COUNTER_BIT)
629 #define BIC_NOT_PRESENT(COUNTER_BIT) (bic_present &= ~COUNTER_BIT)
630
631
632 #define MAX_DEFERRED 16
633 char *deferred_skip_names[MAX_DEFERRED];
634 int deferred_skip_index;
635
636 /*
637  * HIDE_LIST - hide this list of counters, show the rest [default]
638  * SHOW_LIST - show this list of counters, hide the rest
639  */
640 enum show_hide_mode { SHOW_LIST, HIDE_LIST } global_show_hide_mode = HIDE_LIST;
641
642 void help(void)
643 {
644         fprintf(outf,
645         "Usage: turbostat [OPTIONS][(--interval seconds) | COMMAND ...]\n"
646         "\n"
647         "Turbostat forks the specified COMMAND and prints statistics\n"
648         "when COMMAND completes.\n"
649         "If no COMMAND is specified, turbostat wakes every 5-seconds\n"
650         "to print statistics, until interrupted.\n"
651         "  -a, --add    add a counter\n"
652         "                 eg. --add msr0x10,u64,cpu,delta,MY_TSC\n"
653         "  -c, --cpu    cpu-set limit output to summary plus cpu-set:\n"
654         "                 {core | package | j,k,l..m,n-p }\n"
655         "  -d, --debug  displays usec, Time_Of_Day_Seconds and more debugging\n"
656         "  -D, --Dump   displays the raw counter values\n"
657         "  -e, --enable [all | column]\n"
658         "               shows all or the specified disabled column\n"
659         "  -H, --hide [column|column,column,...]\n"
660         "               hide the specified column(s)\n"
661         "  -i, --interval sec.subsec\n"
662         "               Override default 5-second measurement interval\n"
663         "  -J, --Joules displays energy in Joules instead of Watts\n"
664         "  -l, --list   list column headers only\n"
665         "  -n, --num_iterations num\n"
666         "               number of the measurement iterations\n"
667         "  -o, --out file\n"
668         "               create or truncate \"file\" for all output\n"
669         "  -q, --quiet  skip decoding system configuration header\n"
670         "  -s, --show [column|column,column,...]\n"
671         "               show only the specified column(s)\n"
672         "  -S, --Summary\n"
673         "               limits output to 1-line system summary per interval\n"
674         "  -T, --TCC temperature\n"
675         "               sets the Thermal Control Circuit temperature in\n"
676         "                 degrees Celsius\n"
677         "  -h, --help   print this help message\n"
678         "  -v, --version        print version information\n"
679         "\n"
680         "For more help, run \"man turbostat\"\n");
681 }
682
683 /*
684  * bic_lookup
685  * for all the strings in comma separate name_list,
686  * set the approprate bit in return value.
687  */
688 unsigned long long bic_lookup(char *name_list, enum show_hide_mode mode)
689 {
690         int i;
691         unsigned long long retval = 0;
692
693         while (name_list) {
694                 char *comma;
695
696                 comma = strchr(name_list, ',');
697
698                 if (comma)
699                         *comma = '\0';
700
701                 if (!strcmp(name_list, "all"))
702                         return ~0;
703
704                 for (i = 0; i < MAX_BIC; ++i) {
705                         if (!strcmp(name_list, bic[i].name)) {
706                                 retval |= (1ULL << i);
707                                 break;
708                         }
709                 }
710                 if (i == MAX_BIC) {
711                         if (mode == SHOW_LIST) {
712                                 fprintf(stderr, "Invalid counter name: %s\n", name_list);
713                                 exit(-1);
714                         }
715                         deferred_skip_names[deferred_skip_index++] = name_list;
716                         if (debug)
717                                 fprintf(stderr, "deferred \"%s\"\n", name_list);
718                         if (deferred_skip_index >= MAX_DEFERRED) {
719                                 fprintf(stderr, "More than max %d un-recognized --skip options '%s'\n",
720                                         MAX_DEFERRED, name_list);
721                                 help();
722                                 exit(1);
723                         }
724                 }
725
726                 name_list = comma;
727                 if (name_list)
728                         name_list++;
729
730         }
731         return retval;
732 }
733
734
735 void print_header(char *delim)
736 {
737         struct msr_counter *mp;
738         int printed = 0;
739
740         if (DO_BIC(BIC_USEC))
741                 outp += sprintf(outp, "%susec", (printed++ ? delim : ""));
742         if (DO_BIC(BIC_TOD))
743                 outp += sprintf(outp, "%sTime_Of_Day_Seconds", (printed++ ? delim : ""));
744         if (DO_BIC(BIC_Package))
745                 outp += sprintf(outp, "%sPackage", (printed++ ? delim : ""));
746         if (DO_BIC(BIC_Die))
747                 outp += sprintf(outp, "%sDie", (printed++ ? delim : ""));
748         if (DO_BIC(BIC_Node))
749                 outp += sprintf(outp, "%sNode", (printed++ ? delim : ""));
750         if (DO_BIC(BIC_Core))
751                 outp += sprintf(outp, "%sCore", (printed++ ? delim : ""));
752         if (DO_BIC(BIC_CPU))
753                 outp += sprintf(outp, "%sCPU", (printed++ ? delim : ""));
754         if (DO_BIC(BIC_APIC))
755                 outp += sprintf(outp, "%sAPIC", (printed++ ? delim : ""));
756         if (DO_BIC(BIC_X2APIC))
757                 outp += sprintf(outp, "%sX2APIC", (printed++ ? delim : ""));
758         if (DO_BIC(BIC_Avg_MHz))
759                 outp += sprintf(outp, "%sAvg_MHz", (printed++ ? delim : ""));
760         if (DO_BIC(BIC_Busy))
761                 outp += sprintf(outp, "%sBusy%%", (printed++ ? delim : ""));
762         if (DO_BIC(BIC_Bzy_MHz))
763                 outp += sprintf(outp, "%sBzy_MHz", (printed++ ? delim : ""));
764         if (DO_BIC(BIC_TSC_MHz))
765                 outp += sprintf(outp, "%sTSC_MHz", (printed++ ? delim : ""));
766
767         if (DO_BIC(BIC_IRQ)) {
768                 if (sums_need_wide_columns)
769                         outp += sprintf(outp, "%s     IRQ", (printed++ ? delim : ""));
770                 else
771                         outp += sprintf(outp, "%sIRQ", (printed++ ? delim : ""));
772         }
773
774         if (DO_BIC(BIC_SMI))
775                 outp += sprintf(outp, "%sSMI", (printed++ ? delim : ""));
776
777         for (mp = sys.tp; mp; mp = mp->next) {
778
779                 if (mp->format == FORMAT_RAW) {
780                         if (mp->width == 64)
781                                 outp += sprintf(outp, "%s%18.18s", (printed++ ? delim : ""), mp->name);
782                         else
783                                 outp += sprintf(outp, "%s%10.10s", (printed++ ? delim : ""), mp->name);
784                 } else {
785                         if ((mp->type == COUNTER_ITEMS) && sums_need_wide_columns)
786                                 outp += sprintf(outp, "%s%8s", (printed++ ? delim : ""), mp->name);
787                         else
788                                 outp += sprintf(outp, "%s%s", (printed++ ? delim : ""), mp->name);
789                 }
790         }
791
792         if (DO_BIC(BIC_CPU_c1))
793                 outp += sprintf(outp, "%sCPU%%c1", (printed++ ? delim : ""));
794         if (DO_BIC(BIC_CPU_c3))
795                 outp += sprintf(outp, "%sCPU%%c3", (printed++ ? delim : ""));
796         if (DO_BIC(BIC_CPU_c6))
797                 outp += sprintf(outp, "%sCPU%%c6", (printed++ ? delim : ""));
798         if (DO_BIC(BIC_CPU_c7))
799                 outp += sprintf(outp, "%sCPU%%c7", (printed++ ? delim : ""));
800
801         if (DO_BIC(BIC_Mod_c6))
802                 outp += sprintf(outp, "%sMod%%c6", (printed++ ? delim : ""));
803
804         if (DO_BIC(BIC_CoreTmp))
805                 outp += sprintf(outp, "%sCoreTmp", (printed++ ? delim : ""));
806
807         if (do_rapl && !rapl_joules) {
808                 if (DO_BIC(BIC_CorWatt) && (do_rapl & RAPL_PER_CORE_ENERGY))
809                         outp += sprintf(outp, "%sCorWatt", (printed++ ? delim : ""));
810         } else if (do_rapl && rapl_joules) {
811                 if (DO_BIC(BIC_Cor_J) && (do_rapl & RAPL_PER_CORE_ENERGY))
812                         outp += sprintf(outp, "%sCor_J", (printed++ ? delim : ""));
813         }
814
815         for (mp = sys.cp; mp; mp = mp->next) {
816                 if (mp->format == FORMAT_RAW) {
817                         if (mp->width == 64)
818                                 outp += sprintf(outp, "%s%18.18s", delim, mp->name);
819                         else
820                                 outp += sprintf(outp, "%s%10.10s", delim, mp->name);
821                 } else {
822                         if ((mp->type == COUNTER_ITEMS) && sums_need_wide_columns)
823                                 outp += sprintf(outp, "%s%8s", delim, mp->name);
824                         else
825                                 outp += sprintf(outp, "%s%s", delim, mp->name);
826                 }
827         }
828
829         if (DO_BIC(BIC_PkgTmp))
830                 outp += sprintf(outp, "%sPkgTmp", (printed++ ? delim : ""));
831
832         if (DO_BIC(BIC_GFX_rc6))
833                 outp += sprintf(outp, "%sGFX%%rc6", (printed++ ? delim : ""));
834
835         if (DO_BIC(BIC_GFXMHz))
836                 outp += sprintf(outp, "%sGFXMHz", (printed++ ? delim : ""));
837
838         if (DO_BIC(BIC_GFXACTMHz))
839                 outp += sprintf(outp, "%sGFXAMHz", (printed++ ? delim : ""));
840
841         if (DO_BIC(BIC_Totl_c0))
842                 outp += sprintf(outp, "%sTotl%%C0", (printed++ ? delim : ""));
843         if (DO_BIC(BIC_Any_c0))
844                 outp += sprintf(outp, "%sAny%%C0", (printed++ ? delim : ""));
845         if (DO_BIC(BIC_GFX_c0))
846                 outp += sprintf(outp, "%sGFX%%C0", (printed++ ? delim : ""));
847         if (DO_BIC(BIC_CPUGFX))
848                 outp += sprintf(outp, "%sCPUGFX%%", (printed++ ? delim : ""));
849
850         if (DO_BIC(BIC_Pkgpc2))
851                 outp += sprintf(outp, "%sPkg%%pc2", (printed++ ? delim : ""));
852         if (DO_BIC(BIC_Pkgpc3))
853                 outp += sprintf(outp, "%sPkg%%pc3", (printed++ ? delim : ""));
854         if (DO_BIC(BIC_Pkgpc6))
855                 outp += sprintf(outp, "%sPkg%%pc6", (printed++ ? delim : ""));
856         if (DO_BIC(BIC_Pkgpc7))
857                 outp += sprintf(outp, "%sPkg%%pc7", (printed++ ? delim : ""));
858         if (DO_BIC(BIC_Pkgpc8))
859                 outp += sprintf(outp, "%sPkg%%pc8", (printed++ ? delim : ""));
860         if (DO_BIC(BIC_Pkgpc9))
861                 outp += sprintf(outp, "%sPkg%%pc9", (printed++ ? delim : ""));
862         if (DO_BIC(BIC_Pkgpc10))
863                 outp += sprintf(outp, "%sPk%%pc10", (printed++ ? delim : ""));
864         if (DO_BIC(BIC_CPU_LPI))
865                 outp += sprintf(outp, "%sCPU%%LPI", (printed++ ? delim : ""));
866         if (DO_BIC(BIC_SYS_LPI))
867                 outp += sprintf(outp, "%sSYS%%LPI", (printed++ ? delim : ""));
868
869         if (do_rapl && !rapl_joules) {
870                 if (DO_BIC(BIC_PkgWatt))
871                         outp += sprintf(outp, "%sPkgWatt", (printed++ ? delim : ""));
872                 if (DO_BIC(BIC_CorWatt) && !(do_rapl & RAPL_PER_CORE_ENERGY))
873                         outp += sprintf(outp, "%sCorWatt", (printed++ ? delim : ""));
874                 if (DO_BIC(BIC_GFXWatt))
875                         outp += sprintf(outp, "%sGFXWatt", (printed++ ? delim : ""));
876                 if (DO_BIC(BIC_RAMWatt))
877                         outp += sprintf(outp, "%sRAMWatt", (printed++ ? delim : ""));
878                 if (DO_BIC(BIC_PKG__))
879                         outp += sprintf(outp, "%sPKG_%%", (printed++ ? delim : ""));
880                 if (DO_BIC(BIC_RAM__))
881                         outp += sprintf(outp, "%sRAM_%%", (printed++ ? delim : ""));
882         } else if (do_rapl && rapl_joules) {
883                 if (DO_BIC(BIC_Pkg_J))
884                         outp += sprintf(outp, "%sPkg_J", (printed++ ? delim : ""));
885                 if (DO_BIC(BIC_Cor_J) && !(do_rapl & RAPL_PER_CORE_ENERGY))
886                         outp += sprintf(outp, "%sCor_J", (printed++ ? delim : ""));
887                 if (DO_BIC(BIC_GFX_J))
888                         outp += sprintf(outp, "%sGFX_J", (printed++ ? delim : ""));
889                 if (DO_BIC(BIC_RAM_J))
890                         outp += sprintf(outp, "%sRAM_J", (printed++ ? delim : ""));
891                 if (DO_BIC(BIC_PKG__))
892                         outp += sprintf(outp, "%sPKG_%%", (printed++ ? delim : ""));
893                 if (DO_BIC(BIC_RAM__))
894                         outp += sprintf(outp, "%sRAM_%%", (printed++ ? delim : ""));
895         }
896         for (mp = sys.pp; mp; mp = mp->next) {
897                 if (mp->format == FORMAT_RAW) {
898                         if (mp->width == 64)
899                                 outp += sprintf(outp, "%s%18.18s", delim, mp->name);
900                         else
901                                 outp += sprintf(outp, "%s%10.10s", delim, mp->name);
902                 } else {
903                         if ((mp->type == COUNTER_ITEMS) && sums_need_wide_columns)
904                                 outp += sprintf(outp, "%s%8s", delim, mp->name);
905                         else
906                                 outp += sprintf(outp, "%s%s", delim, mp->name);
907                 }
908         }
909
910         outp += sprintf(outp, "\n");
911 }
912
913 int dump_counters(struct thread_data *t, struct core_data *c,
914         struct pkg_data *p)
915 {
916         int i;
917         struct msr_counter *mp;
918
919         outp += sprintf(outp, "t %p, c %p, p %p\n", t, c, p);
920
921         if (t) {
922                 outp += sprintf(outp, "CPU: %d flags 0x%x\n",
923                         t->cpu_id, t->flags);
924                 outp += sprintf(outp, "TSC: %016llX\n", t->tsc);
925                 outp += sprintf(outp, "aperf: %016llX\n", t->aperf);
926                 outp += sprintf(outp, "mperf: %016llX\n", t->mperf);
927                 outp += sprintf(outp, "c1: %016llX\n", t->c1);
928
929                 if (DO_BIC(BIC_IRQ))
930                         outp += sprintf(outp, "IRQ: %lld\n", t->irq_count);
931                 if (DO_BIC(BIC_SMI))
932                         outp += sprintf(outp, "SMI: %d\n", t->smi_count);
933
934                 for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
935                         outp += sprintf(outp, "tADDED [%d] msr0x%x: %08llX\n",
936                                 i, mp->msr_num, t->counter[i]);
937                 }
938         }
939
940         if (c) {
941                 outp += sprintf(outp, "core: %d\n", c->core_id);
942                 outp += sprintf(outp, "c3: %016llX\n", c->c3);
943                 outp += sprintf(outp, "c6: %016llX\n", c->c6);
944                 outp += sprintf(outp, "c7: %016llX\n", c->c7);
945                 outp += sprintf(outp, "DTS: %dC\n", c->core_temp_c);
946                 outp += sprintf(outp, "Joules: %0X\n", c->core_energy);
947
948                 for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
949                         outp += sprintf(outp, "cADDED [%d] msr0x%x: %08llX\n",
950                                 i, mp->msr_num, c->counter[i]);
951                 }
952                 outp += sprintf(outp, "mc6_us: %016llX\n", c->mc6_us);
953         }
954
955         if (p) {
956                 outp += sprintf(outp, "package: %d\n", p->package_id);
957
958                 outp += sprintf(outp, "Weighted cores: %016llX\n", p->pkg_wtd_core_c0);
959                 outp += sprintf(outp, "Any cores: %016llX\n", p->pkg_any_core_c0);
960                 outp += sprintf(outp, "Any GFX: %016llX\n", p->pkg_any_gfxe_c0);
961                 outp += sprintf(outp, "CPU + GFX: %016llX\n", p->pkg_both_core_gfxe_c0);
962
963                 outp += sprintf(outp, "pc2: %016llX\n", p->pc2);
964                 if (DO_BIC(BIC_Pkgpc3))
965                         outp += sprintf(outp, "pc3: %016llX\n", p->pc3);
966                 if (DO_BIC(BIC_Pkgpc6))
967                         outp += sprintf(outp, "pc6: %016llX\n", p->pc6);
968                 if (DO_BIC(BIC_Pkgpc7))
969                         outp += sprintf(outp, "pc7: %016llX\n", p->pc7);
970                 outp += sprintf(outp, "pc8: %016llX\n", p->pc8);
971                 outp += sprintf(outp, "pc9: %016llX\n", p->pc9);
972                 outp += sprintf(outp, "pc10: %016llX\n", p->pc10);
973                 outp += sprintf(outp, "cpu_lpi: %016llX\n", p->cpu_lpi);
974                 outp += sprintf(outp, "sys_lpi: %016llX\n", p->sys_lpi);
975                 outp += sprintf(outp, "Joules PKG: %0llX\n", p->energy_pkg);
976                 outp += sprintf(outp, "Joules COR: %0llX\n", p->energy_cores);
977                 outp += sprintf(outp, "Joules GFX: %0llX\n", p->energy_gfx);
978                 outp += sprintf(outp, "Joules RAM: %0llX\n", p->energy_dram);
979                 outp += sprintf(outp, "Throttle PKG: %0llX\n",
980                         p->rapl_pkg_perf_status);
981                 outp += sprintf(outp, "Throttle RAM: %0llX\n",
982                         p->rapl_dram_perf_status);
983                 outp += sprintf(outp, "PTM: %dC\n", p->pkg_temp_c);
984
985                 for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
986                         outp += sprintf(outp, "pADDED [%d] msr0x%x: %08llX\n",
987                                 i, mp->msr_num, p->counter[i]);
988                 }
989         }
990
991         outp += sprintf(outp, "\n");
992
993         return 0;
994 }
995
996 /*
997  * column formatting convention & formats
998  */
999 int format_counters(struct thread_data *t, struct core_data *c,
1000         struct pkg_data *p)
1001 {
1002         double interval_float, tsc;
1003         char *fmt8;
1004         int i;
1005         struct msr_counter *mp;
1006         char *delim = "\t";
1007         int printed = 0;
1008
1009          /* if showing only 1st thread in core and this isn't one, bail out */
1010         if (show_core_only && !(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1011                 return 0;
1012
1013          /* if showing only 1st thread in pkg and this isn't one, bail out */
1014         if (show_pkg_only && !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1015                 return 0;
1016
1017         /*if not summary line and --cpu is used */
1018         if ((t != &average.threads) &&
1019                 (cpu_subset && !CPU_ISSET_S(t->cpu_id, cpu_subset_size, cpu_subset)))
1020                 return 0;
1021
1022         if (DO_BIC(BIC_USEC)) {
1023                 /* on each row, print how many usec each timestamp took to gather */
1024                 struct timeval tv;
1025
1026                 timersub(&t->tv_end, &t->tv_begin, &tv);
1027                 outp += sprintf(outp, "%5ld\t", tv.tv_sec * 1000000 + tv.tv_usec);
1028         }
1029
1030         /* Time_Of_Day_Seconds: on each row, print sec.usec last timestamp taken */
1031         if (DO_BIC(BIC_TOD))
1032                 outp += sprintf(outp, "%10ld.%06ld\t", t->tv_end.tv_sec, t->tv_end.tv_usec);
1033
1034         interval_float = t->tv_delta.tv_sec + t->tv_delta.tv_usec/1000000.0;
1035
1036         tsc = t->tsc * tsc_tweak;
1037
1038         /* topo columns, print blanks on 1st (average) line */
1039         if (t == &average.threads) {
1040                 if (DO_BIC(BIC_Package))
1041                         outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1042                 if (DO_BIC(BIC_Die))
1043                         outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1044                 if (DO_BIC(BIC_Node))
1045                         outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1046                 if (DO_BIC(BIC_Core))
1047                         outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1048                 if (DO_BIC(BIC_CPU))
1049                         outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1050                 if (DO_BIC(BIC_APIC))
1051                         outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1052                 if (DO_BIC(BIC_X2APIC))
1053                         outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1054         } else {
1055                 if (DO_BIC(BIC_Package)) {
1056                         if (p)
1057                                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), p->package_id);
1058                         else
1059                                 outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1060                 }
1061                 if (DO_BIC(BIC_Die)) {
1062                         if (c)
1063                                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), cpus[t->cpu_id].die_id);
1064                         else
1065                                 outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1066                 }
1067                 if (DO_BIC(BIC_Node)) {
1068                         if (t)
1069                                 outp += sprintf(outp, "%s%d",
1070                                                 (printed++ ? delim : ""),
1071                                               cpus[t->cpu_id].physical_node_id);
1072                         else
1073                                 outp += sprintf(outp, "%s-",
1074                                                 (printed++ ? delim : ""));
1075                 }
1076                 if (DO_BIC(BIC_Core)) {
1077                         if (c)
1078                                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), c->core_id);
1079                         else
1080                                 outp += sprintf(outp, "%s-", (printed++ ? delim : ""));
1081                 }
1082                 if (DO_BIC(BIC_CPU))
1083                         outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), t->cpu_id);
1084                 if (DO_BIC(BIC_APIC))
1085                         outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), t->apic_id);
1086                 if (DO_BIC(BIC_X2APIC))
1087                         outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), t->x2apic_id);
1088         }
1089
1090         if (DO_BIC(BIC_Avg_MHz))
1091                 outp += sprintf(outp, "%s%.0f", (printed++ ? delim : ""),
1092                         1.0 / units * t->aperf / interval_float);
1093
1094         if (DO_BIC(BIC_Busy))
1095                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * t->mperf/tsc);
1096
1097         if (DO_BIC(BIC_Bzy_MHz)) {
1098                 if (has_base_hz)
1099                         outp += sprintf(outp, "%s%.0f", (printed++ ? delim : ""), base_hz / units * t->aperf / t->mperf);
1100                 else
1101                         outp += sprintf(outp, "%s%.0f", (printed++ ? delim : ""),
1102                                 tsc / units * t->aperf / t->mperf / interval_float);
1103         }
1104
1105         if (DO_BIC(BIC_TSC_MHz))
1106                 outp += sprintf(outp, "%s%.0f", (printed++ ? delim : ""), 1.0 * t->tsc/units/interval_float);
1107
1108         /* IRQ */
1109         if (DO_BIC(BIC_IRQ)) {
1110                 if (sums_need_wide_columns)
1111                         outp += sprintf(outp, "%s%8lld", (printed++ ? delim : ""), t->irq_count);
1112                 else
1113                         outp += sprintf(outp, "%s%lld", (printed++ ? delim : ""), t->irq_count);
1114         }
1115
1116         /* SMI */
1117         if (DO_BIC(BIC_SMI))
1118                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), t->smi_count);
1119
1120         /* Added counters */
1121         for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1122                 if (mp->format == FORMAT_RAW) {
1123                         if (mp->width == 32)
1124                                 outp += sprintf(outp, "%s0x%08x", (printed++ ? delim : ""), (unsigned int) t->counter[i]);
1125                         else
1126                                 outp += sprintf(outp, "%s0x%016llx", (printed++ ? delim : ""), t->counter[i]);
1127                 } else if (mp->format == FORMAT_DELTA) {
1128                         if ((mp->type == COUNTER_ITEMS) && sums_need_wide_columns)
1129                                 outp += sprintf(outp, "%s%8lld", (printed++ ? delim : ""), t->counter[i]);
1130                         else
1131                                 outp += sprintf(outp, "%s%lld", (printed++ ? delim : ""), t->counter[i]);
1132                 } else if (mp->format == FORMAT_PERCENT) {
1133                         if (mp->type == COUNTER_USEC)
1134                                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), t->counter[i]/interval_float/10000);
1135                         else
1136                                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * t->counter[i]/tsc);
1137                 }
1138         }
1139
1140         /* C1 */
1141         if (DO_BIC(BIC_CPU_c1))
1142                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * t->c1/tsc);
1143
1144
1145         /* print per-core data only for 1st thread in core */
1146         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1147                 goto done;
1148
1149         if (DO_BIC(BIC_CPU_c3))
1150                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * c->c3/tsc);
1151         if (DO_BIC(BIC_CPU_c6))
1152                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * c->c6/tsc);
1153         if (DO_BIC(BIC_CPU_c7))
1154                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * c->c7/tsc);
1155
1156         /* Mod%c6 */
1157         if (DO_BIC(BIC_Mod_c6))
1158                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * c->mc6_us / tsc);
1159
1160         if (DO_BIC(BIC_CoreTmp))
1161                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), c->core_temp_c);
1162
1163         for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1164                 if (mp->format == FORMAT_RAW) {
1165                         if (mp->width == 32)
1166                                 outp += sprintf(outp, "%s0x%08x", (printed++ ? delim : ""), (unsigned int) c->counter[i]);
1167                         else
1168                                 outp += sprintf(outp, "%s0x%016llx", (printed++ ? delim : ""), c->counter[i]);
1169                 } else if (mp->format == FORMAT_DELTA) {
1170                         if ((mp->type == COUNTER_ITEMS) && sums_need_wide_columns)
1171                                 outp += sprintf(outp, "%s%8lld", (printed++ ? delim : ""), c->counter[i]);
1172                         else
1173                                 outp += sprintf(outp, "%s%lld", (printed++ ? delim : ""), c->counter[i]);
1174                 } else if (mp->format == FORMAT_PERCENT) {
1175                         outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * c->counter[i]/tsc);
1176                 }
1177         }
1178
1179         fmt8 = "%s%.2f";
1180
1181         if (DO_BIC(BIC_CorWatt) && (do_rapl & RAPL_PER_CORE_ENERGY))
1182                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), c->core_energy * rapl_energy_units / interval_float);
1183         if (DO_BIC(BIC_Cor_J) && (do_rapl & RAPL_PER_CORE_ENERGY))
1184                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), c->core_energy * rapl_energy_units);
1185
1186         /* print per-package data only for 1st core in package */
1187         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1188                 goto done;
1189
1190         /* PkgTmp */
1191         if (DO_BIC(BIC_PkgTmp))
1192                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), p->pkg_temp_c);
1193
1194         /* GFXrc6 */
1195         if (DO_BIC(BIC_GFX_rc6)) {
1196                 if (p->gfx_rc6_ms == -1) {      /* detect GFX counter reset */
1197                         outp += sprintf(outp, "%s**.**", (printed++ ? delim : ""));
1198                 } else {
1199                         outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""),
1200                                 p->gfx_rc6_ms / 10.0 / interval_float);
1201                 }
1202         }
1203
1204         /* GFXMHz */
1205         if (DO_BIC(BIC_GFXMHz))
1206                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), p->gfx_mhz);
1207
1208         /* GFXACTMHz */
1209         if (DO_BIC(BIC_GFXACTMHz))
1210                 outp += sprintf(outp, "%s%d", (printed++ ? delim : ""), p->gfx_act_mhz);
1211
1212         /* Totl%C0, Any%C0 GFX%C0 CPUGFX% */
1213         if (DO_BIC(BIC_Totl_c0))
1214                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pkg_wtd_core_c0/tsc);
1215         if (DO_BIC(BIC_Any_c0))
1216                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pkg_any_core_c0/tsc);
1217         if (DO_BIC(BIC_GFX_c0))
1218                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pkg_any_gfxe_c0/tsc);
1219         if (DO_BIC(BIC_CPUGFX))
1220                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pkg_both_core_gfxe_c0/tsc);
1221
1222         if (DO_BIC(BIC_Pkgpc2))
1223                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pc2/tsc);
1224         if (DO_BIC(BIC_Pkgpc3))
1225                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pc3/tsc);
1226         if (DO_BIC(BIC_Pkgpc6))
1227                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pc6/tsc);
1228         if (DO_BIC(BIC_Pkgpc7))
1229                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pc7/tsc);
1230         if (DO_BIC(BIC_Pkgpc8))
1231                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pc8/tsc);
1232         if (DO_BIC(BIC_Pkgpc9))
1233                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pc9/tsc);
1234         if (DO_BIC(BIC_Pkgpc10))
1235                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->pc10/tsc);
1236
1237         if (DO_BIC(BIC_CPU_LPI))
1238                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->cpu_lpi / 1000000.0 / interval_float);
1239         if (DO_BIC(BIC_SYS_LPI))
1240                 outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->sys_lpi / 1000000.0 / interval_float);
1241
1242         if (DO_BIC(BIC_PkgWatt))
1243                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_pkg * rapl_energy_units / interval_float);
1244         if (DO_BIC(BIC_CorWatt) && !(do_rapl & RAPL_PER_CORE_ENERGY))
1245                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_cores * rapl_energy_units / interval_float);
1246         if (DO_BIC(BIC_GFXWatt))
1247                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_gfx * rapl_energy_units / interval_float);
1248         if (DO_BIC(BIC_RAMWatt))
1249                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_dram * rapl_dram_energy_units / interval_float);
1250         if (DO_BIC(BIC_Pkg_J))
1251                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_pkg * rapl_energy_units);
1252         if (DO_BIC(BIC_Cor_J) && !(do_rapl & RAPL_PER_CORE_ENERGY))
1253                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_cores * rapl_energy_units);
1254         if (DO_BIC(BIC_GFX_J))
1255                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_gfx * rapl_energy_units);
1256         if (DO_BIC(BIC_RAM_J))
1257                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), p->energy_dram * rapl_dram_energy_units);
1258         if (DO_BIC(BIC_PKG__))
1259                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), 100.0 * p->rapl_pkg_perf_status * rapl_time_units / interval_float);
1260         if (DO_BIC(BIC_RAM__))
1261                 outp += sprintf(outp, fmt8, (printed++ ? delim : ""), 100.0 * p->rapl_dram_perf_status * rapl_time_units / interval_float);
1262
1263         for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
1264                 if (mp->format == FORMAT_RAW) {
1265                         if (mp->width == 32)
1266                                 outp += sprintf(outp, "%s0x%08x", (printed++ ? delim : ""), (unsigned int) p->counter[i]);
1267                         else
1268                                 outp += sprintf(outp, "%s0x%016llx", (printed++ ? delim : ""), p->counter[i]);
1269                 } else if (mp->format == FORMAT_DELTA) {
1270                         if ((mp->type == COUNTER_ITEMS) && sums_need_wide_columns)
1271                                 outp += sprintf(outp, "%s%8lld", (printed++ ? delim : ""), p->counter[i]);
1272                         else
1273                                 outp += sprintf(outp, "%s%lld", (printed++ ? delim : ""), p->counter[i]);
1274                 } else if (mp->format == FORMAT_PERCENT) {
1275                         outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), 100.0 * p->counter[i]/tsc);
1276                 }
1277         }
1278
1279 done:
1280         if (*(outp - 1) != '\n')
1281                 outp += sprintf(outp, "\n");
1282
1283         return 0;
1284 }
1285
1286 void flush_output_stdout(void)
1287 {
1288         FILE *filep;
1289
1290         if (outf == stderr)
1291                 filep = stdout;
1292         else
1293                 filep = outf;
1294
1295         fputs(output_buffer, filep);
1296         fflush(filep);
1297
1298         outp = output_buffer;
1299 }
1300 void flush_output_stderr(void)
1301 {
1302         fputs(output_buffer, outf);
1303         fflush(outf);
1304         outp = output_buffer;
1305 }
1306 void format_all_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1307 {
1308         static int printed;
1309
1310         if (!printed || !summary_only)
1311                 print_header("\t");
1312
1313         format_counters(&average.threads, &average.cores, &average.packages);
1314
1315         printed = 1;
1316
1317         if (summary_only)
1318                 return;
1319
1320         for_all_cpus(format_counters, t, c, p);
1321 }
1322
1323 #define DELTA_WRAP32(new, old)                  \
1324         old = ((((unsigned long long)new << 32) - ((unsigned long long)old << 32)) >> 32);
1325
1326 int
1327 delta_package(struct pkg_data *new, struct pkg_data *old)
1328 {
1329         int i;
1330         struct msr_counter *mp;
1331
1332
1333         if (DO_BIC(BIC_Totl_c0))
1334                 old->pkg_wtd_core_c0 = new->pkg_wtd_core_c0 - old->pkg_wtd_core_c0;
1335         if (DO_BIC(BIC_Any_c0))
1336                 old->pkg_any_core_c0 = new->pkg_any_core_c0 - old->pkg_any_core_c0;
1337         if (DO_BIC(BIC_GFX_c0))
1338                 old->pkg_any_gfxe_c0 = new->pkg_any_gfxe_c0 - old->pkg_any_gfxe_c0;
1339         if (DO_BIC(BIC_CPUGFX))
1340                 old->pkg_both_core_gfxe_c0 = new->pkg_both_core_gfxe_c0 - old->pkg_both_core_gfxe_c0;
1341
1342         old->pc2 = new->pc2 - old->pc2;
1343         if (DO_BIC(BIC_Pkgpc3))
1344                 old->pc3 = new->pc3 - old->pc3;
1345         if (DO_BIC(BIC_Pkgpc6))
1346                 old->pc6 = new->pc6 - old->pc6;
1347         if (DO_BIC(BIC_Pkgpc7))
1348                 old->pc7 = new->pc7 - old->pc7;
1349         old->pc8 = new->pc8 - old->pc8;
1350         old->pc9 = new->pc9 - old->pc9;
1351         old->pc10 = new->pc10 - old->pc10;
1352         old->cpu_lpi = new->cpu_lpi - old->cpu_lpi;
1353         old->sys_lpi = new->sys_lpi - old->sys_lpi;
1354         old->pkg_temp_c = new->pkg_temp_c;
1355
1356         /* flag an error when rc6 counter resets/wraps */
1357         if (old->gfx_rc6_ms >  new->gfx_rc6_ms)
1358                 old->gfx_rc6_ms = -1;
1359         else
1360                 old->gfx_rc6_ms = new->gfx_rc6_ms - old->gfx_rc6_ms;
1361
1362         old->gfx_mhz = new->gfx_mhz;
1363         old->gfx_act_mhz = new->gfx_act_mhz;
1364
1365         old->energy_pkg = new->energy_pkg - old->energy_pkg;
1366         old->energy_cores = new->energy_cores - old->energy_cores;
1367         old->energy_gfx = new->energy_gfx - old->energy_gfx;
1368         old->energy_dram = new->energy_dram - old->energy_dram;
1369         old->rapl_pkg_perf_status = new->rapl_pkg_perf_status - old->rapl_pkg_perf_status;
1370         old->rapl_dram_perf_status = new->rapl_dram_perf_status - old->rapl_dram_perf_status;
1371
1372         for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
1373                 if (mp->format == FORMAT_RAW)
1374                         old->counter[i] = new->counter[i];
1375                 else
1376                         old->counter[i] = new->counter[i] - old->counter[i];
1377         }
1378
1379         return 0;
1380 }
1381
1382 void
1383 delta_core(struct core_data *new, struct core_data *old)
1384 {
1385         int i;
1386         struct msr_counter *mp;
1387
1388         old->c3 = new->c3 - old->c3;
1389         old->c6 = new->c6 - old->c6;
1390         old->c7 = new->c7 - old->c7;
1391         old->core_temp_c = new->core_temp_c;
1392         old->mc6_us = new->mc6_us - old->mc6_us;
1393
1394         DELTA_WRAP32(new->core_energy, old->core_energy);
1395
1396         for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1397                 if (mp->format == FORMAT_RAW)
1398                         old->counter[i] = new->counter[i];
1399                 else
1400                         old->counter[i] = new->counter[i] - old->counter[i];
1401         }
1402 }
1403
1404 int soft_c1_residency_display(int bic)
1405 {
1406         if (!DO_BIC(BIC_CPU_c1) || use_c1_residency_msr)
1407                 return 0;
1408
1409         return DO_BIC_READ(bic);
1410 }
1411
1412 /*
1413  * old = new - old
1414  */
1415 int
1416 delta_thread(struct thread_data *new, struct thread_data *old,
1417         struct core_data *core_delta)
1418 {
1419         int i;
1420         struct msr_counter *mp;
1421
1422         /* we run cpuid just the 1st time, copy the results */
1423         if (DO_BIC(BIC_APIC))
1424                 new->apic_id = old->apic_id;
1425         if (DO_BIC(BIC_X2APIC))
1426                 new->x2apic_id = old->x2apic_id;
1427
1428         /*
1429          * the timestamps from start of measurement interval are in "old"
1430          * the timestamp from end of measurement interval are in "new"
1431          * over-write old w/ new so we can print end of interval values
1432          */
1433
1434         timersub(&new->tv_begin, &old->tv_begin, &old->tv_delta);
1435         old->tv_begin = new->tv_begin;
1436         old->tv_end = new->tv_end;
1437
1438         old->tsc = new->tsc - old->tsc;
1439
1440         /* check for TSC < 1 Mcycles over interval */
1441         if (old->tsc < (1000 * 1000))
1442                 errx(-3, "Insanely slow TSC rate, TSC stops in idle?\n"
1443                      "You can disable all c-states by booting with \"idle=poll\"\n"
1444                      "or just the deep ones with \"processor.max_cstate=1\"");
1445
1446         old->c1 = new->c1 - old->c1;
1447
1448         if (DO_BIC(BIC_Avg_MHz) || DO_BIC(BIC_Busy) || DO_BIC(BIC_Bzy_MHz) ||
1449             soft_c1_residency_display(BIC_Avg_MHz)) {
1450                 if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
1451                         old->aperf = new->aperf - old->aperf;
1452                         old->mperf = new->mperf - old->mperf;
1453                 } else {
1454                         return -1;
1455                 }
1456         }
1457
1458
1459         if (use_c1_residency_msr) {
1460                 /*
1461                  * Some models have a dedicated C1 residency MSR,
1462                  * which should be more accurate than the derivation below.
1463                  */
1464         } else {
1465                 /*
1466                  * As counter collection is not atomic,
1467                  * it is possible for mperf's non-halted cycles + idle states
1468                  * to exceed TSC's all cycles: show c1 = 0% in that case.
1469                  */
1470                 if ((old->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > (old->tsc * tsc_tweak))
1471                         old->c1 = 0;
1472                 else {
1473                         /* normal case, derive c1 */
1474                         old->c1 = (old->tsc * tsc_tweak) - old->mperf - core_delta->c3
1475                                 - core_delta->c6 - core_delta->c7;
1476                 }
1477         }
1478
1479         if (old->mperf == 0) {
1480                 if (debug > 1)
1481                         fprintf(outf, "cpu%d MPERF 0!\n", old->cpu_id);
1482                 old->mperf = 1; /* divide by 0 protection */
1483         }
1484
1485         if (DO_BIC(BIC_IRQ))
1486                 old->irq_count = new->irq_count - old->irq_count;
1487
1488         if (DO_BIC(BIC_SMI))
1489                 old->smi_count = new->smi_count - old->smi_count;
1490
1491         for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1492                 if (mp->format == FORMAT_RAW)
1493                         old->counter[i] = new->counter[i];
1494                 else
1495                         old->counter[i] = new->counter[i] - old->counter[i];
1496         }
1497         return 0;
1498 }
1499
1500 int delta_cpu(struct thread_data *t, struct core_data *c,
1501         struct pkg_data *p, struct thread_data *t2,
1502         struct core_data *c2, struct pkg_data *p2)
1503 {
1504         int retval = 0;
1505
1506         /* calculate core delta only for 1st thread in core */
1507         if (t->flags & CPU_IS_FIRST_THREAD_IN_CORE)
1508                 delta_core(c, c2);
1509
1510         /* always calculate thread delta */
1511         retval = delta_thread(t, t2, c2);       /* c2 is core delta */
1512         if (retval)
1513                 return retval;
1514
1515         /* calculate package delta only for 1st core in package */
1516         if (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)
1517                 retval = delta_package(p, p2);
1518
1519         return retval;
1520 }
1521
1522 void clear_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1523 {
1524         int i;
1525         struct msr_counter  *mp;
1526
1527         t->tv_begin.tv_sec = 0;
1528         t->tv_begin.tv_usec = 0;
1529         t->tv_end.tv_sec = 0;
1530         t->tv_end.tv_usec = 0;
1531         t->tv_delta.tv_sec = 0;
1532         t->tv_delta.tv_usec = 0;
1533
1534         t->tsc = 0;
1535         t->aperf = 0;
1536         t->mperf = 0;
1537         t->c1 = 0;
1538
1539         t->irq_count = 0;
1540         t->smi_count = 0;
1541
1542         /* tells format_counters to dump all fields from this set */
1543         t->flags = CPU_IS_FIRST_THREAD_IN_CORE | CPU_IS_FIRST_CORE_IN_PACKAGE;
1544
1545         c->c3 = 0;
1546         c->c6 = 0;
1547         c->c7 = 0;
1548         c->mc6_us = 0;
1549         c->core_temp_c = 0;
1550         c->core_energy = 0;
1551
1552         p->pkg_wtd_core_c0 = 0;
1553         p->pkg_any_core_c0 = 0;
1554         p->pkg_any_gfxe_c0 = 0;
1555         p->pkg_both_core_gfxe_c0 = 0;
1556
1557         p->pc2 = 0;
1558         if (DO_BIC(BIC_Pkgpc3))
1559                 p->pc3 = 0;
1560         if (DO_BIC(BIC_Pkgpc6))
1561                 p->pc6 = 0;
1562         if (DO_BIC(BIC_Pkgpc7))
1563                 p->pc7 = 0;
1564         p->pc8 = 0;
1565         p->pc9 = 0;
1566         p->pc10 = 0;
1567         p->cpu_lpi = 0;
1568         p->sys_lpi = 0;
1569
1570         p->energy_pkg = 0;
1571         p->energy_dram = 0;
1572         p->energy_cores = 0;
1573         p->energy_gfx = 0;
1574         p->rapl_pkg_perf_status = 0;
1575         p->rapl_dram_perf_status = 0;
1576         p->pkg_temp_c = 0;
1577
1578         p->gfx_rc6_ms = 0;
1579         p->gfx_mhz = 0;
1580         p->gfx_act_mhz = 0;
1581         for (i = 0, mp = sys.tp; mp; i++, mp = mp->next)
1582                 t->counter[i] = 0;
1583
1584         for (i = 0, mp = sys.cp; mp; i++, mp = mp->next)
1585                 c->counter[i] = 0;
1586
1587         for (i = 0, mp = sys.pp; mp; i++, mp = mp->next)
1588                 p->counter[i] = 0;
1589 }
1590 int sum_counters(struct thread_data *t, struct core_data *c,
1591         struct pkg_data *p)
1592 {
1593         int i;
1594         struct msr_counter *mp;
1595
1596         /* copy un-changing apic_id's */
1597         if (DO_BIC(BIC_APIC))
1598                 average.threads.apic_id = t->apic_id;
1599         if (DO_BIC(BIC_X2APIC))
1600                 average.threads.x2apic_id = t->x2apic_id;
1601
1602         /* remember first tv_begin */
1603         if (average.threads.tv_begin.tv_sec == 0)
1604                 average.threads.tv_begin = t->tv_begin;
1605
1606         /* remember last tv_end */
1607         average.threads.tv_end = t->tv_end;
1608
1609         average.threads.tsc += t->tsc;
1610         average.threads.aperf += t->aperf;
1611         average.threads.mperf += t->mperf;
1612         average.threads.c1 += t->c1;
1613
1614         average.threads.irq_count += t->irq_count;
1615         average.threads.smi_count += t->smi_count;
1616
1617         for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1618                 if (mp->format == FORMAT_RAW)
1619                         continue;
1620                 average.threads.counter[i] += t->counter[i];
1621         }
1622
1623         /* sum per-core values only for 1st thread in core */
1624         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1625                 return 0;
1626
1627         average.cores.c3 += c->c3;
1628         average.cores.c6 += c->c6;
1629         average.cores.c7 += c->c7;
1630         average.cores.mc6_us += c->mc6_us;
1631
1632         average.cores.core_temp_c = MAX(average.cores.core_temp_c, c->core_temp_c);
1633
1634         average.cores.core_energy += c->core_energy;
1635
1636         for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1637                 if (mp->format == FORMAT_RAW)
1638                         continue;
1639                 average.cores.counter[i] += c->counter[i];
1640         }
1641
1642         /* sum per-pkg values only for 1st core in pkg */
1643         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1644                 return 0;
1645
1646         if (DO_BIC(BIC_Totl_c0))
1647                 average.packages.pkg_wtd_core_c0 += p->pkg_wtd_core_c0;
1648         if (DO_BIC(BIC_Any_c0))
1649                 average.packages.pkg_any_core_c0 += p->pkg_any_core_c0;
1650         if (DO_BIC(BIC_GFX_c0))
1651                 average.packages.pkg_any_gfxe_c0 += p->pkg_any_gfxe_c0;
1652         if (DO_BIC(BIC_CPUGFX))
1653                 average.packages.pkg_both_core_gfxe_c0 += p->pkg_both_core_gfxe_c0;
1654
1655         average.packages.pc2 += p->pc2;
1656         if (DO_BIC(BIC_Pkgpc3))
1657                 average.packages.pc3 += p->pc3;
1658         if (DO_BIC(BIC_Pkgpc6))
1659                 average.packages.pc6 += p->pc6;
1660         if (DO_BIC(BIC_Pkgpc7))
1661                 average.packages.pc7 += p->pc7;
1662         average.packages.pc8 += p->pc8;
1663         average.packages.pc9 += p->pc9;
1664         average.packages.pc10 += p->pc10;
1665
1666         average.packages.cpu_lpi = p->cpu_lpi;
1667         average.packages.sys_lpi = p->sys_lpi;
1668
1669         average.packages.energy_pkg += p->energy_pkg;
1670         average.packages.energy_dram += p->energy_dram;
1671         average.packages.energy_cores += p->energy_cores;
1672         average.packages.energy_gfx += p->energy_gfx;
1673
1674         average.packages.gfx_rc6_ms = p->gfx_rc6_ms;
1675         average.packages.gfx_mhz = p->gfx_mhz;
1676         average.packages.gfx_act_mhz = p->gfx_act_mhz;
1677
1678         average.packages.pkg_temp_c = MAX(average.packages.pkg_temp_c, p->pkg_temp_c);
1679
1680         average.packages.rapl_pkg_perf_status += p->rapl_pkg_perf_status;
1681         average.packages.rapl_dram_perf_status += p->rapl_dram_perf_status;
1682
1683         for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
1684                 if (mp->format == FORMAT_RAW)
1685                         continue;
1686                 average.packages.counter[i] += p->counter[i];
1687         }
1688         return 0;
1689 }
1690 /*
1691  * sum the counters for all cpus in the system
1692  * compute the weighted average
1693  */
1694 void compute_average(struct thread_data *t, struct core_data *c,
1695         struct pkg_data *p)
1696 {
1697         int i;
1698         struct msr_counter *mp;
1699
1700         clear_counters(&average.threads, &average.cores, &average.packages);
1701
1702         for_all_cpus(sum_counters, t, c, p);
1703
1704         /* Use the global time delta for the average. */
1705         average.threads.tv_delta = tv_delta;
1706
1707         average.threads.tsc /= topo.num_cpus;
1708         average.threads.aperf /= topo.num_cpus;
1709         average.threads.mperf /= topo.num_cpus;
1710         average.threads.c1 /= topo.num_cpus;
1711
1712         if (average.threads.irq_count > 9999999)
1713                 sums_need_wide_columns = 1;
1714
1715         average.cores.c3 /= topo.num_cores;
1716         average.cores.c6 /= topo.num_cores;
1717         average.cores.c7 /= topo.num_cores;
1718         average.cores.mc6_us /= topo.num_cores;
1719
1720         if (DO_BIC(BIC_Totl_c0))
1721                 average.packages.pkg_wtd_core_c0 /= topo.num_packages;
1722         if (DO_BIC(BIC_Any_c0))
1723                 average.packages.pkg_any_core_c0 /= topo.num_packages;
1724         if (DO_BIC(BIC_GFX_c0))
1725                 average.packages.pkg_any_gfxe_c0 /= topo.num_packages;
1726         if (DO_BIC(BIC_CPUGFX))
1727                 average.packages.pkg_both_core_gfxe_c0 /= topo.num_packages;
1728
1729         average.packages.pc2 /= topo.num_packages;
1730         if (DO_BIC(BIC_Pkgpc3))
1731                 average.packages.pc3 /= topo.num_packages;
1732         if (DO_BIC(BIC_Pkgpc6))
1733                 average.packages.pc6 /= topo.num_packages;
1734         if (DO_BIC(BIC_Pkgpc7))
1735                 average.packages.pc7 /= topo.num_packages;
1736
1737         average.packages.pc8 /= topo.num_packages;
1738         average.packages.pc9 /= topo.num_packages;
1739         average.packages.pc10 /= topo.num_packages;
1740
1741         for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1742                 if (mp->format == FORMAT_RAW)
1743                         continue;
1744                 if (mp->type == COUNTER_ITEMS) {
1745                         if (average.threads.counter[i] > 9999999)
1746                                 sums_need_wide_columns = 1;
1747                         continue;
1748                 }
1749                 average.threads.counter[i] /= topo.num_cpus;
1750         }
1751         for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1752                 if (mp->format == FORMAT_RAW)
1753                         continue;
1754                 if (mp->type == COUNTER_ITEMS) {
1755                         if (average.cores.counter[i] > 9999999)
1756                                 sums_need_wide_columns = 1;
1757                 }
1758                 average.cores.counter[i] /= topo.num_cores;
1759         }
1760         for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
1761                 if (mp->format == FORMAT_RAW)
1762                         continue;
1763                 if (mp->type == COUNTER_ITEMS) {
1764                         if (average.packages.counter[i] > 9999999)
1765                                 sums_need_wide_columns = 1;
1766                 }
1767                 average.packages.counter[i] /= topo.num_packages;
1768         }
1769 }
1770
1771 static unsigned long long rdtsc(void)
1772 {
1773         unsigned int low, high;
1774
1775         asm volatile("rdtsc" : "=a" (low), "=d" (high));
1776
1777         return low | ((unsigned long long)high) << 32;
1778 }
1779
1780 /*
1781  * Open a file, and exit on failure
1782  */
1783 FILE *fopen_or_die(const char *path, const char *mode)
1784 {
1785         FILE *filep = fopen(path, mode);
1786
1787         if (!filep)
1788                 err(1, "%s: open failed", path);
1789         return filep;
1790 }
1791 /*
1792  * snapshot_sysfs_counter()
1793  *
1794  * return snapshot of given counter
1795  */
1796 unsigned long long snapshot_sysfs_counter(char *path)
1797 {
1798         FILE *fp;
1799         int retval;
1800         unsigned long long counter;
1801
1802         fp = fopen_or_die(path, "r");
1803
1804         retval = fscanf(fp, "%lld", &counter);
1805         if (retval != 1)
1806                 err(1, "snapshot_sysfs_counter(%s)", path);
1807
1808         fclose(fp);
1809
1810         return counter;
1811 }
1812
1813 int get_mp(int cpu, struct msr_counter *mp, unsigned long long *counterp)
1814 {
1815         if (mp->msr_num != 0) {
1816                 if (get_msr(cpu, mp->msr_num, counterp))
1817                         return -1;
1818         } else {
1819                 char path[128 + PATH_BYTES];
1820
1821                 if (mp->flags & SYSFS_PERCPU) {
1822                         sprintf(path, "/sys/devices/system/cpu/cpu%d/%s",
1823                                  cpu, mp->path);
1824
1825                         *counterp = snapshot_sysfs_counter(path);
1826                 } else {
1827                         *counterp = snapshot_sysfs_counter(mp->path);
1828                 }
1829         }
1830
1831         return 0;
1832 }
1833
1834 void get_apic_id(struct thread_data *t)
1835 {
1836         unsigned int eax, ebx, ecx, edx;
1837
1838         if (DO_BIC(BIC_APIC)) {
1839                 eax = ebx = ecx = edx = 0;
1840                 __cpuid(1, eax, ebx, ecx, edx);
1841
1842                 t->apic_id = (ebx >> 24) & 0xff;
1843         }
1844
1845         if (!DO_BIC(BIC_X2APIC))
1846                 return;
1847
1848         if (authentic_amd || hygon_genuine) {
1849                 unsigned int topology_extensions;
1850
1851                 if (max_extended_level < 0x8000001e)
1852                         return;
1853
1854                 eax = ebx = ecx = edx = 0;
1855                 __cpuid(0x80000001, eax, ebx, ecx, edx);
1856                         topology_extensions = ecx & (1 << 22);
1857
1858                 if (topology_extensions == 0)
1859                         return;
1860
1861                 eax = ebx = ecx = edx = 0;
1862                 __cpuid(0x8000001e, eax, ebx, ecx, edx);
1863
1864                 t->x2apic_id = eax;
1865                 return;
1866         }
1867
1868         if (!genuine_intel)
1869                 return;
1870
1871         if (max_level < 0xb)
1872                 return;
1873
1874         ecx = 0;
1875         __cpuid(0xb, eax, ebx, ecx, edx);
1876         t->x2apic_id = edx;
1877
1878         if (debug && (t->apic_id != (t->x2apic_id & 0xff)))
1879                 fprintf(outf, "cpu%d: BIOS BUG: apic 0x%x x2apic 0x%x\n",
1880                                 t->cpu_id, t->apic_id, t->x2apic_id);
1881 }
1882
1883 /*
1884  * get_counters(...)
1885  * migrate to cpu
1886  * acquire and record local counters for that cpu
1887  */
1888 int get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1889 {
1890         int cpu = t->cpu_id;
1891         unsigned long long msr;
1892         int aperf_mperf_retry_count = 0;
1893         struct msr_counter *mp;
1894         int i;
1895
1896         if (cpu_migrate(cpu)) {
1897                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
1898                 return -1;
1899         }
1900
1901         gettimeofday(&t->tv_begin, (struct timezone *)NULL);
1902
1903         if (first_counter_read)
1904                 get_apic_id(t);
1905 retry:
1906         t->tsc = rdtsc();       /* we are running on local CPU of interest */
1907
1908         if (DO_BIC(BIC_Avg_MHz) || DO_BIC(BIC_Busy) || DO_BIC(BIC_Bzy_MHz) ||
1909             soft_c1_residency_display(BIC_Avg_MHz)) {
1910                 unsigned long long tsc_before, tsc_between, tsc_after, aperf_time, mperf_time;
1911
1912                 /*
1913                  * The TSC, APERF and MPERF must be read together for
1914                  * APERF/MPERF and MPERF/TSC to give accurate results.
1915                  *
1916                  * Unfortunately, APERF and MPERF are read by
1917                  * individual system call, so delays may occur
1918                  * between them.  If the time to read them
1919                  * varies by a large amount, we re-read them.
1920                  */
1921
1922                 /*
1923                  * This initial dummy APERF read has been seen to
1924                  * reduce jitter in the subsequent reads.
1925                  */
1926
1927                 if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
1928                         return -3;
1929
1930                 t->tsc = rdtsc();       /* re-read close to APERF */
1931
1932                 tsc_before = t->tsc;
1933
1934                 if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
1935                         return -3;
1936
1937                 tsc_between = rdtsc();
1938
1939                 if (get_msr(cpu, MSR_IA32_MPERF, &t->mperf))
1940                         return -4;
1941
1942                 tsc_after = rdtsc();
1943
1944                 aperf_time = tsc_between - tsc_before;
1945                 mperf_time = tsc_after - tsc_between;
1946
1947                 /*
1948                  * If the system call latency to read APERF and MPERF
1949                  * differ by more than 2x, then try again.
1950                  */
1951                 if ((aperf_time > (2 * mperf_time)) || (mperf_time > (2 * aperf_time))) {
1952                         aperf_mperf_retry_count++;
1953                         if (aperf_mperf_retry_count < 5)
1954                                 goto retry;
1955                         else
1956                                 warnx("cpu%d jitter %lld %lld",
1957                                         cpu, aperf_time, mperf_time);
1958                 }
1959                 aperf_mperf_retry_count = 0;
1960
1961                 t->aperf = t->aperf * aperf_mperf_multiplier;
1962                 t->mperf = t->mperf * aperf_mperf_multiplier;
1963         }
1964
1965         if (DO_BIC(BIC_IRQ))
1966                 t->irq_count = irqs_per_cpu[cpu];
1967         if (DO_BIC(BIC_SMI)) {
1968                 if (get_msr(cpu, MSR_SMI_COUNT, &msr))
1969                         return -5;
1970                 t->smi_count = msr & 0xFFFFFFFF;
1971         }
1972         if (DO_BIC(BIC_CPU_c1) && use_c1_residency_msr) {
1973                 if (get_msr(cpu, MSR_CORE_C1_RES, &t->c1))
1974                         return -6;
1975         }
1976
1977         for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1978                 if (get_mp(cpu, mp, &t->counter[i]))
1979                         return -10;
1980         }
1981
1982         /* collect core counters only for 1st thread in core */
1983         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1984                 goto done;
1985
1986         if (DO_BIC(BIC_CPU_c3) || soft_c1_residency_display(BIC_CPU_c3)) {
1987                 if (get_msr(cpu, MSR_CORE_C3_RESIDENCY, &c->c3))
1988                         return -6;
1989         }
1990
1991         if ((DO_BIC(BIC_CPU_c6) || soft_c1_residency_display(BIC_CPU_c6)) && !do_knl_cstates) {
1992                 if (get_msr(cpu, MSR_CORE_C6_RESIDENCY, &c->c6))
1993                         return -7;
1994         } else if (do_knl_cstates || soft_c1_residency_display(BIC_CPU_c6)) {
1995                 if (get_msr(cpu, MSR_KNL_CORE_C6_RESIDENCY, &c->c6))
1996                         return -7;
1997         }
1998
1999         if (DO_BIC(BIC_CPU_c7) || soft_c1_residency_display(BIC_CPU_c7))
2000                 if (get_msr(cpu, MSR_CORE_C7_RESIDENCY, &c->c7))
2001                         return -8;
2002
2003         if (DO_BIC(BIC_Mod_c6))
2004                 if (get_msr(cpu, MSR_MODULE_C6_RES_MS, &c->mc6_us))
2005                         return -8;
2006
2007         if (DO_BIC(BIC_CoreTmp)) {
2008                 if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
2009                         return -9;
2010                 c->core_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
2011         }
2012
2013         if (do_rapl & RAPL_AMD_F17H) {
2014                 if (get_msr(cpu, MSR_CORE_ENERGY_STAT, &msr))
2015                         return -14;
2016                 c->core_energy = msr & 0xFFFFFFFF;
2017         }
2018
2019         for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
2020                 if (get_mp(cpu, mp, &c->counter[i]))
2021                         return -10;
2022         }
2023
2024         /* collect package counters only for 1st core in package */
2025         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2026                 goto done;
2027
2028         if (DO_BIC(BIC_Totl_c0)) {
2029                 if (get_msr(cpu, MSR_PKG_WEIGHTED_CORE_C0_RES, &p->pkg_wtd_core_c0))
2030                         return -10;
2031         }
2032         if (DO_BIC(BIC_Any_c0)) {
2033                 if (get_msr(cpu, MSR_PKG_ANY_CORE_C0_RES, &p->pkg_any_core_c0))
2034                         return -11;
2035         }
2036         if (DO_BIC(BIC_GFX_c0)) {
2037                 if (get_msr(cpu, MSR_PKG_ANY_GFXE_C0_RES, &p->pkg_any_gfxe_c0))
2038                         return -12;
2039         }
2040         if (DO_BIC(BIC_CPUGFX)) {
2041                 if (get_msr(cpu, MSR_PKG_BOTH_CORE_GFXE_C0_RES, &p->pkg_both_core_gfxe_c0))
2042                         return -13;
2043         }
2044         if (DO_BIC(BIC_Pkgpc3))
2045                 if (get_msr(cpu, MSR_PKG_C3_RESIDENCY, &p->pc3))
2046                         return -9;
2047         if (DO_BIC(BIC_Pkgpc6)) {
2048                 if (do_slm_cstates) {
2049                         if (get_msr(cpu, MSR_ATOM_PKG_C6_RESIDENCY, &p->pc6))
2050                                 return -10;
2051                 } else {
2052                         if (get_msr(cpu, MSR_PKG_C6_RESIDENCY, &p->pc6))
2053                                 return -10;
2054                 }
2055         }
2056
2057         if (DO_BIC(BIC_Pkgpc2))
2058                 if (get_msr(cpu, MSR_PKG_C2_RESIDENCY, &p->pc2))
2059                         return -11;
2060         if (DO_BIC(BIC_Pkgpc7))
2061                 if (get_msr(cpu, MSR_PKG_C7_RESIDENCY, &p->pc7))
2062                         return -12;
2063         if (DO_BIC(BIC_Pkgpc8))
2064                 if (get_msr(cpu, MSR_PKG_C8_RESIDENCY, &p->pc8))
2065                         return -13;
2066         if (DO_BIC(BIC_Pkgpc9))
2067                 if (get_msr(cpu, MSR_PKG_C9_RESIDENCY, &p->pc9))
2068                         return -13;
2069         if (DO_BIC(BIC_Pkgpc10))
2070                 if (get_msr(cpu, MSR_PKG_C10_RESIDENCY, &p->pc10))
2071                         return -13;
2072
2073         if (DO_BIC(BIC_CPU_LPI))
2074                 p->cpu_lpi = cpuidle_cur_cpu_lpi_us;
2075         if (DO_BIC(BIC_SYS_LPI))
2076                 p->sys_lpi = cpuidle_cur_sys_lpi_us;
2077
2078         if (do_rapl & RAPL_PKG) {
2079                 if (get_msr_sum(cpu, MSR_PKG_ENERGY_STATUS, &msr))
2080                         return -13;
2081                 p->energy_pkg = msr;
2082         }
2083         if (do_rapl & RAPL_CORES_ENERGY_STATUS) {
2084                 if (get_msr_sum(cpu, MSR_PP0_ENERGY_STATUS, &msr))
2085                         return -14;
2086                 p->energy_cores = msr;
2087         }
2088         if (do_rapl & RAPL_DRAM) {
2089                 if (get_msr_sum(cpu, MSR_DRAM_ENERGY_STATUS, &msr))
2090                         return -15;
2091                 p->energy_dram = msr;
2092         }
2093         if (do_rapl & RAPL_GFX) {
2094                 if (get_msr_sum(cpu, MSR_PP1_ENERGY_STATUS, &msr))
2095                         return -16;
2096                 p->energy_gfx = msr;
2097         }
2098         if (do_rapl & RAPL_PKG_PERF_STATUS) {
2099                 if (get_msr_sum(cpu, MSR_PKG_PERF_STATUS, &msr))
2100                         return -16;
2101                 p->rapl_pkg_perf_status = msr;
2102         }
2103         if (do_rapl & RAPL_DRAM_PERF_STATUS) {
2104                 if (get_msr_sum(cpu, MSR_DRAM_PERF_STATUS, &msr))
2105                         return -16;
2106                 p->rapl_dram_perf_status = msr;
2107         }
2108         if (do_rapl & RAPL_AMD_F17H) {
2109                 if (get_msr_sum(cpu, MSR_PKG_ENERGY_STAT, &msr))
2110                         return -13;
2111                 p->energy_pkg = msr;
2112         }
2113         if (DO_BIC(BIC_PkgTmp)) {
2114                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
2115                         return -17;
2116                 p->pkg_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
2117         }
2118
2119         if (DO_BIC(BIC_GFX_rc6))
2120                 p->gfx_rc6_ms = gfx_cur_rc6_ms;
2121
2122         if (DO_BIC(BIC_GFXMHz))
2123                 p->gfx_mhz = gfx_cur_mhz;
2124
2125         if (DO_BIC(BIC_GFXACTMHz))
2126                 p->gfx_act_mhz = gfx_act_mhz;
2127
2128         for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
2129                 if (get_mp(cpu, mp, &p->counter[i]))
2130                         return -10;
2131         }
2132 done:
2133         gettimeofday(&t->tv_end, (struct timezone *)NULL);
2134
2135         return 0;
2136 }
2137
2138 /*
2139  * MSR_PKG_CST_CONFIG_CONTROL decoding for pkg_cstate_limit:
2140  * If you change the values, note they are used both in comparisons
2141  * (>= PCL__7) and to index pkg_cstate_limit_strings[].
2142  */
2143
2144 #define PCLUKN 0 /* Unknown */
2145 #define PCLRSV 1 /* Reserved */
2146 #define PCL__0 2 /* PC0 */
2147 #define PCL__1 3 /* PC1 */
2148 #define PCL__2 4 /* PC2 */
2149 #define PCL__3 5 /* PC3 */
2150 #define PCL__4 6 /* PC4 */
2151 #define PCL__6 7 /* PC6 */
2152 #define PCL_6N 8 /* PC6 No Retention */
2153 #define PCL_6R 9 /* PC6 Retention */
2154 #define PCL__7 10 /* PC7 */
2155 #define PCL_7S 11 /* PC7 Shrink */
2156 #define PCL__8 12 /* PC8 */
2157 #define PCL__9 13 /* PC9 */
2158 #define PCL_10 14 /* PC10 */
2159 #define PCLUNL 15 /* Unlimited */
2160
2161 int pkg_cstate_limit = PCLUKN;
2162 char *pkg_cstate_limit_strings[] = { "reserved", "unknown", "pc0", "pc1", "pc2",
2163         "pc3", "pc4", "pc6", "pc6n", "pc6r", "pc7", "pc7s", "pc8", "pc9", "pc10", "unlimited"};
2164
2165 int nhm_pkg_cstate_limits[16] = {PCL__0, PCL__1, PCL__3, PCL__6, PCL__7, PCLRSV, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
2166 int snb_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCL__7, PCL_7S, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
2167 int hsw_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL__3, PCL__6, PCL__7, PCL_7S, PCL__8, PCL__9, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
2168 int slv_pkg_cstate_limits[16] = {PCL__0, PCL__1, PCLRSV, PCLRSV, PCL__4, PCLRSV, PCL__6, PCL__7, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCL__6, PCL__7};
2169 int amt_pkg_cstate_limits[16] = {PCLUNL, PCL__1, PCL__2, PCLRSV, PCLRSV, PCLRSV, PCL__6, PCL__7, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
2170 int phi_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCLRSV, PCLRSV, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
2171 int glm_pkg_cstate_limits[16] = {PCLUNL, PCL__1, PCL__3, PCL__6, PCL__7, PCL_7S, PCL__8, PCL__9, PCL_10, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
2172 int skx_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCLRSV, PCLRSV, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
2173
2174
2175 static void
2176 calculate_tsc_tweak()
2177 {
2178         tsc_tweak = base_hz / tsc_hz;
2179 }
2180
2181 static void
2182 dump_nhm_platform_info(void)
2183 {
2184         unsigned long long msr;
2185         unsigned int ratio;
2186
2187         get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
2188
2189         fprintf(outf, "cpu%d: MSR_PLATFORM_INFO: 0x%08llx\n", base_cpu, msr);
2190
2191         ratio = (msr >> 40) & 0xFF;
2192         fprintf(outf, "%d * %.1f = %.1f MHz max efficiency frequency\n",
2193                 ratio, bclk, ratio * bclk);
2194
2195         ratio = (msr >> 8) & 0xFF;
2196         fprintf(outf, "%d * %.1f = %.1f MHz base frequency\n",
2197                 ratio, bclk, ratio * bclk);
2198
2199         get_msr(base_cpu, MSR_IA32_POWER_CTL, &msr);
2200         fprintf(outf, "cpu%d: MSR_IA32_POWER_CTL: 0x%08llx (C1E auto-promotion: %sabled)\n",
2201                 base_cpu, msr, msr & 0x2 ? "EN" : "DIS");
2202
2203         return;
2204 }
2205
2206 static void
2207 dump_hsw_turbo_ratio_limits(void)
2208 {
2209         unsigned long long msr;
2210         unsigned int ratio;
2211
2212         get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT2, &msr);
2213
2214         fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT2: 0x%08llx\n", base_cpu, msr);
2215
2216         ratio = (msr >> 8) & 0xFF;
2217         if (ratio)
2218                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 18 active cores\n",
2219                         ratio, bclk, ratio * bclk);
2220
2221         ratio = (msr >> 0) & 0xFF;
2222         if (ratio)
2223                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 17 active cores\n",
2224                         ratio, bclk, ratio * bclk);
2225         return;
2226 }
2227
2228 static void
2229 dump_ivt_turbo_ratio_limits(void)
2230 {
2231         unsigned long long msr;
2232         unsigned int ratio;
2233
2234         get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT1, &msr);
2235
2236         fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT1: 0x%08llx\n", base_cpu, msr);
2237
2238         ratio = (msr >> 56) & 0xFF;
2239         if (ratio)
2240                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 16 active cores\n",
2241                         ratio, bclk, ratio * bclk);
2242
2243         ratio = (msr >> 48) & 0xFF;
2244         if (ratio)
2245                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 15 active cores\n",
2246                         ratio, bclk, ratio * bclk);
2247
2248         ratio = (msr >> 40) & 0xFF;
2249         if (ratio)
2250                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 14 active cores\n",
2251                         ratio, bclk, ratio * bclk);
2252
2253         ratio = (msr >> 32) & 0xFF;
2254         if (ratio)
2255                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 13 active cores\n",
2256                         ratio, bclk, ratio * bclk);
2257
2258         ratio = (msr >> 24) & 0xFF;
2259         if (ratio)
2260                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 12 active cores\n",
2261                         ratio, bclk, ratio * bclk);
2262
2263         ratio = (msr >> 16) & 0xFF;
2264         if (ratio)
2265                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 11 active cores\n",
2266                         ratio, bclk, ratio * bclk);
2267
2268         ratio = (msr >> 8) & 0xFF;
2269         if (ratio)
2270                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 10 active cores\n",
2271                         ratio, bclk, ratio * bclk);
2272
2273         ratio = (msr >> 0) & 0xFF;
2274         if (ratio)
2275                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 9 active cores\n",
2276                         ratio, bclk, ratio * bclk);
2277         return;
2278 }
2279 int has_turbo_ratio_group_limits(int family, int model)
2280 {
2281
2282         if (!genuine_intel)
2283                 return 0;
2284
2285         switch (model) {
2286         case INTEL_FAM6_ATOM_GOLDMONT:
2287         case INTEL_FAM6_SKYLAKE_X:
2288         case INTEL_FAM6_ATOM_GOLDMONT_D:
2289         case INTEL_FAM6_ATOM_TREMONT_D:
2290                 return 1;
2291         }
2292         return 0;
2293 }
2294
2295 static void
2296 dump_turbo_ratio_limits(int family, int model)
2297 {
2298         unsigned long long msr, core_counts;
2299         unsigned int ratio, group_size;
2300
2301         get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT, &msr);
2302         fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT: 0x%08llx\n", base_cpu, msr);
2303
2304         if (has_turbo_ratio_group_limits(family, model)) {
2305                 get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT1, &core_counts);
2306                 fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT1: 0x%08llx\n", base_cpu, core_counts);
2307         } else {
2308                 core_counts = 0x0807060504030201;
2309         }
2310
2311         ratio = (msr >> 56) & 0xFF;
2312         group_size = (core_counts >> 56) & 0xFF;
2313         if (ratio)
2314                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2315                         ratio, bclk, ratio * bclk, group_size);
2316
2317         ratio = (msr >> 48) & 0xFF;
2318         group_size = (core_counts >> 48) & 0xFF;
2319         if (ratio)
2320                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2321                         ratio, bclk, ratio * bclk, group_size);
2322
2323         ratio = (msr >> 40) & 0xFF;
2324         group_size = (core_counts >> 40) & 0xFF;
2325         if (ratio)
2326                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2327                         ratio, bclk, ratio * bclk, group_size);
2328
2329         ratio = (msr >> 32) & 0xFF;
2330         group_size = (core_counts >> 32) & 0xFF;
2331         if (ratio)
2332                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2333                         ratio, bclk, ratio * bclk, group_size);
2334
2335         ratio = (msr >> 24) & 0xFF;
2336         group_size = (core_counts >> 24) & 0xFF;
2337         if (ratio)
2338                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2339                         ratio, bclk, ratio * bclk, group_size);
2340
2341         ratio = (msr >> 16) & 0xFF;
2342         group_size = (core_counts >> 16) & 0xFF;
2343         if (ratio)
2344                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2345                         ratio, bclk, ratio * bclk, group_size);
2346
2347         ratio = (msr >> 8) & 0xFF;
2348         group_size = (core_counts >> 8) & 0xFF;
2349         if (ratio)
2350                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2351                         ratio, bclk, ratio * bclk, group_size);
2352
2353         ratio = (msr >> 0) & 0xFF;
2354         group_size = (core_counts >> 0) & 0xFF;
2355         if (ratio)
2356                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2357                         ratio, bclk, ratio * bclk, group_size);
2358         return;
2359 }
2360
2361 static void
2362 dump_atom_turbo_ratio_limits(void)
2363 {
2364         unsigned long long msr;
2365         unsigned int ratio;
2366
2367         get_msr(base_cpu, MSR_ATOM_CORE_RATIOS, &msr);
2368         fprintf(outf, "cpu%d: MSR_ATOM_CORE_RATIOS: 0x%08llx\n", base_cpu, msr & 0xFFFFFFFF);
2369
2370         ratio = (msr >> 0) & 0x3F;
2371         if (ratio)
2372                 fprintf(outf, "%d * %.1f = %.1f MHz minimum operating frequency\n",
2373                         ratio, bclk, ratio * bclk);
2374
2375         ratio = (msr >> 8) & 0x3F;
2376         if (ratio)
2377                 fprintf(outf, "%d * %.1f = %.1f MHz low frequency mode (LFM)\n",
2378                         ratio, bclk, ratio * bclk);
2379
2380         ratio = (msr >> 16) & 0x3F;
2381         if (ratio)
2382                 fprintf(outf, "%d * %.1f = %.1f MHz base frequency\n",
2383                         ratio, bclk, ratio * bclk);
2384
2385         get_msr(base_cpu, MSR_ATOM_CORE_TURBO_RATIOS, &msr);
2386         fprintf(outf, "cpu%d: MSR_ATOM_CORE_TURBO_RATIOS: 0x%08llx\n", base_cpu, msr & 0xFFFFFFFF);
2387
2388         ratio = (msr >> 24) & 0x3F;
2389         if (ratio)
2390                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 4 active cores\n",
2391                         ratio, bclk, ratio * bclk);
2392
2393         ratio = (msr >> 16) & 0x3F;
2394         if (ratio)
2395                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 3 active cores\n",
2396                         ratio, bclk, ratio * bclk);
2397
2398         ratio = (msr >> 8) & 0x3F;
2399         if (ratio)
2400                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 2 active cores\n",
2401                         ratio, bclk, ratio * bclk);
2402
2403         ratio = (msr >> 0) & 0x3F;
2404         if (ratio)
2405                 fprintf(outf, "%d * %.1f = %.1f MHz max turbo 1 active core\n",
2406                         ratio, bclk, ratio * bclk);
2407 }
2408
2409 static void
2410 dump_knl_turbo_ratio_limits(void)
2411 {
2412         const unsigned int buckets_no = 7;
2413
2414         unsigned long long msr;
2415         int delta_cores, delta_ratio;
2416         int i, b_nr;
2417         unsigned int cores[buckets_no];
2418         unsigned int ratio[buckets_no];
2419
2420         get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT, &msr);
2421
2422         fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT: 0x%08llx\n",
2423                 base_cpu, msr);
2424
2425         /**
2426          * Turbo encoding in KNL is as follows:
2427          * [0] -- Reserved
2428          * [7:1] -- Base value of number of active cores of bucket 1.
2429          * [15:8] -- Base value of freq ratio of bucket 1.
2430          * [20:16] -- +ve delta of number of active cores of bucket 2.
2431          * i.e. active cores of bucket 2 =
2432          * active cores of bucket 1 + delta
2433          * [23:21] -- Negative delta of freq ratio of bucket 2.
2434          * i.e. freq ratio of bucket 2 =
2435          * freq ratio of bucket 1 - delta
2436          * [28:24]-- +ve delta of number of active cores of bucket 3.
2437          * [31:29]-- -ve delta of freq ratio of bucket 3.
2438          * [36:32]-- +ve delta of number of active cores of bucket 4.
2439          * [39:37]-- -ve delta of freq ratio of bucket 4.
2440          * [44:40]-- +ve delta of number of active cores of bucket 5.
2441          * [47:45]-- -ve delta of freq ratio of bucket 5.
2442          * [52:48]-- +ve delta of number of active cores of bucket 6.
2443          * [55:53]-- -ve delta of freq ratio of bucket 6.
2444          * [60:56]-- +ve delta of number of active cores of bucket 7.
2445          * [63:61]-- -ve delta of freq ratio of bucket 7.
2446          */
2447
2448         b_nr = 0;
2449         cores[b_nr] = (msr & 0xFF) >> 1;
2450         ratio[b_nr] = (msr >> 8) & 0xFF;
2451
2452         for (i = 16; i < 64; i += 8) {
2453                 delta_cores = (msr >> i) & 0x1F;
2454                 delta_ratio = (msr >> (i + 5)) & 0x7;
2455
2456                 cores[b_nr + 1] = cores[b_nr] + delta_cores;
2457                 ratio[b_nr + 1] = ratio[b_nr] - delta_ratio;
2458                 b_nr++;
2459         }
2460
2461         for (i = buckets_no - 1; i >= 0; i--)
2462                 if (i > 0 ? ratio[i] != ratio[i - 1] : 1)
2463                         fprintf(outf,
2464                                 "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2465                                 ratio[i], bclk, ratio[i] * bclk, cores[i]);
2466 }
2467
2468 static void
2469 dump_nhm_cst_cfg(void)
2470 {
2471         unsigned long long msr;
2472
2473         get_msr(base_cpu, MSR_PKG_CST_CONFIG_CONTROL, &msr);
2474
2475         fprintf(outf, "cpu%d: MSR_PKG_CST_CONFIG_CONTROL: 0x%08llx", base_cpu, msr);
2476
2477         fprintf(outf, " (%s%s%s%s%slocked, pkg-cstate-limit=%d (%s)",
2478                 (msr & SNB_C3_AUTO_UNDEMOTE) ? "UNdemote-C3, " : "",
2479                 (msr & SNB_C1_AUTO_UNDEMOTE) ? "UNdemote-C1, " : "",
2480                 (msr & NHM_C3_AUTO_DEMOTE) ? "demote-C3, " : "",
2481                 (msr & NHM_C1_AUTO_DEMOTE) ? "demote-C1, " : "",
2482                 (msr & (1 << 15)) ? "" : "UN",
2483                 (unsigned int)msr & 0xF,
2484                 pkg_cstate_limit_strings[pkg_cstate_limit]);
2485
2486 #define AUTOMATIC_CSTATE_CONVERSION             (1UL << 16)
2487         if (has_automatic_cstate_conversion) {
2488                 fprintf(outf, ", automatic c-state conversion=%s",
2489                         (msr & AUTOMATIC_CSTATE_CONVERSION) ? "on" : "off");
2490         }
2491
2492         fprintf(outf, ")\n");
2493
2494         return;
2495 }
2496
2497 static void
2498 dump_config_tdp(void)
2499 {
2500         unsigned long long msr;
2501
2502         get_msr(base_cpu, MSR_CONFIG_TDP_NOMINAL, &msr);
2503         fprintf(outf, "cpu%d: MSR_CONFIG_TDP_NOMINAL: 0x%08llx", base_cpu, msr);
2504         fprintf(outf, " (base_ratio=%d)\n", (unsigned int)msr & 0xFF);
2505
2506         get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_1, &msr);
2507         fprintf(outf, "cpu%d: MSR_CONFIG_TDP_LEVEL_1: 0x%08llx (", base_cpu, msr);
2508         if (msr) {
2509                 fprintf(outf, "PKG_MIN_PWR_LVL1=%d ", (unsigned int)(msr >> 48) & 0x7FFF);
2510                 fprintf(outf, "PKG_MAX_PWR_LVL1=%d ", (unsigned int)(msr >> 32) & 0x7FFF);
2511                 fprintf(outf, "LVL1_RATIO=%d ", (unsigned int)(msr >> 16) & 0xFF);
2512                 fprintf(outf, "PKG_TDP_LVL1=%d", (unsigned int)(msr) & 0x7FFF);
2513         }
2514         fprintf(outf, ")\n");
2515
2516         get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_2, &msr);
2517         fprintf(outf, "cpu%d: MSR_CONFIG_TDP_LEVEL_2: 0x%08llx (", base_cpu, msr);
2518         if (msr) {
2519                 fprintf(outf, "PKG_MIN_PWR_LVL2=%d ", (unsigned int)(msr >> 48) & 0x7FFF);
2520                 fprintf(outf, "PKG_MAX_PWR_LVL2=%d ", (unsigned int)(msr >> 32) & 0x7FFF);
2521                 fprintf(outf, "LVL2_RATIO=%d ", (unsigned int)(msr >> 16) & 0xFF);
2522                 fprintf(outf, "PKG_TDP_LVL2=%d", (unsigned int)(msr) & 0x7FFF);
2523         }
2524         fprintf(outf, ")\n");
2525
2526         get_msr(base_cpu, MSR_CONFIG_TDP_CONTROL, &msr);
2527         fprintf(outf, "cpu%d: MSR_CONFIG_TDP_CONTROL: 0x%08llx (", base_cpu, msr);
2528         if ((msr) & 0x3)
2529                 fprintf(outf, "TDP_LEVEL=%d ", (unsigned int)(msr) & 0x3);
2530         fprintf(outf, " lock=%d", (unsigned int)(msr >> 31) & 1);
2531         fprintf(outf, ")\n");
2532
2533         get_msr(base_cpu, MSR_TURBO_ACTIVATION_RATIO, &msr);
2534         fprintf(outf, "cpu%d: MSR_TURBO_ACTIVATION_RATIO: 0x%08llx (", base_cpu, msr);
2535         fprintf(outf, "MAX_NON_TURBO_RATIO=%d", (unsigned int)(msr) & 0xFF);
2536         fprintf(outf, " lock=%d", (unsigned int)(msr >> 31) & 1);
2537         fprintf(outf, ")\n");
2538 }
2539
2540 unsigned int irtl_time_units[] = {1, 32, 1024, 32768, 1048576, 33554432, 0, 0 };
2541
2542 void print_irtl(void)
2543 {
2544         unsigned long long msr;
2545
2546         get_msr(base_cpu, MSR_PKGC3_IRTL, &msr);
2547         fprintf(outf, "cpu%d: MSR_PKGC3_IRTL: 0x%08llx (", base_cpu, msr);
2548         fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2549                 (msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2550
2551         get_msr(base_cpu, MSR_PKGC6_IRTL, &msr);
2552         fprintf(outf, "cpu%d: MSR_PKGC6_IRTL: 0x%08llx (", base_cpu, msr);
2553         fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2554                 (msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2555
2556         get_msr(base_cpu, MSR_PKGC7_IRTL, &msr);
2557         fprintf(outf, "cpu%d: MSR_PKGC7_IRTL: 0x%08llx (", base_cpu, msr);
2558         fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2559                 (msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2560
2561         if (!do_irtl_hsw)
2562                 return;
2563
2564         get_msr(base_cpu, MSR_PKGC8_IRTL, &msr);
2565         fprintf(outf, "cpu%d: MSR_PKGC8_IRTL: 0x%08llx (", base_cpu, msr);
2566         fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2567                 (msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2568
2569         get_msr(base_cpu, MSR_PKGC9_IRTL, &msr);
2570         fprintf(outf, "cpu%d: MSR_PKGC9_IRTL: 0x%08llx (", base_cpu, msr);
2571         fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2572                 (msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2573
2574         get_msr(base_cpu, MSR_PKGC10_IRTL, &msr);
2575         fprintf(outf, "cpu%d: MSR_PKGC10_IRTL: 0x%08llx (", base_cpu, msr);
2576         fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2577                 (msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2578
2579 }
2580 void free_fd_percpu(void)
2581 {
2582         int i;
2583
2584         for (i = 0; i < topo.max_cpu_num + 1; ++i) {
2585                 if (fd_percpu[i] != 0)
2586                         close(fd_percpu[i]);
2587         }
2588
2589         free(fd_percpu);
2590 }
2591
2592 void free_all_buffers(void)
2593 {
2594         int i;
2595
2596         CPU_FREE(cpu_present_set);
2597         cpu_present_set = NULL;
2598         cpu_present_setsize = 0;
2599
2600         CPU_FREE(cpu_affinity_set);
2601         cpu_affinity_set = NULL;
2602         cpu_affinity_setsize = 0;
2603
2604         free(thread_even);
2605         free(core_even);
2606         free(package_even);
2607
2608         thread_even = NULL;
2609         core_even = NULL;
2610         package_even = NULL;
2611
2612         free(thread_odd);
2613         free(core_odd);
2614         free(package_odd);
2615
2616         thread_odd = NULL;
2617         core_odd = NULL;
2618         package_odd = NULL;
2619
2620         free(output_buffer);
2621         output_buffer = NULL;
2622         outp = NULL;
2623
2624         free_fd_percpu();
2625
2626         free(irq_column_2_cpu);
2627         free(irqs_per_cpu);
2628
2629         for (i = 0; i <= topo.max_cpu_num; ++i) {
2630                 if (cpus[i].put_ids)
2631                         CPU_FREE(cpus[i].put_ids);
2632         }
2633         free(cpus);
2634 }
2635
2636
2637 /*
2638  * Parse a file containing a single int.
2639  * Return 0 if file can not be opened
2640  * Exit if file can be opened, but can not be parsed
2641  */
2642 int parse_int_file(const char *fmt, ...)
2643 {
2644         va_list args;
2645         char path[PATH_MAX];
2646         FILE *filep;
2647         int value;
2648
2649         va_start(args, fmt);
2650         vsnprintf(path, sizeof(path), fmt, args);
2651         va_end(args);
2652         filep = fopen(path, "r");
2653         if (!filep)
2654                 return 0;
2655         if (fscanf(filep, "%d", &value) != 1)
2656                 err(1, "%s: failed to parse number from file", path);
2657         fclose(filep);
2658         return value;
2659 }
2660
2661 /*
2662  * cpu_is_first_core_in_package(cpu)
2663  * return 1 if given CPU is 1st core in package
2664  */
2665 int cpu_is_first_core_in_package(int cpu)
2666 {
2667         return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
2668 }
2669
2670 int get_physical_package_id(int cpu)
2671 {
2672         return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
2673 }
2674
2675 int get_die_id(int cpu)
2676 {
2677         return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/die_id", cpu);
2678 }
2679
2680 int get_core_id(int cpu)
2681 {
2682         return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
2683 }
2684
2685 void set_node_data(void)
2686 {
2687         int pkg, node, lnode, cpu, cpux;
2688         int cpu_count;
2689
2690         /* initialize logical_node_id */
2691         for (cpu = 0; cpu <= topo.max_cpu_num; ++cpu)
2692                 cpus[cpu].logical_node_id = -1;
2693
2694         cpu_count = 0;
2695         for (pkg = 0; pkg < topo.num_packages; pkg++) {
2696                 lnode = 0;
2697                 for (cpu = 0; cpu <= topo.max_cpu_num; ++cpu) {
2698                         if (cpus[cpu].physical_package_id != pkg)
2699                                 continue;
2700                         /* find a cpu with an unset logical_node_id */
2701                         if (cpus[cpu].logical_node_id != -1)
2702                                 continue;
2703                         cpus[cpu].logical_node_id = lnode;
2704                         node = cpus[cpu].physical_node_id;
2705                         cpu_count++;
2706                         /*
2707                          * find all matching cpus on this pkg and set
2708                          * the logical_node_id
2709                          */
2710                         for (cpux = cpu; cpux <= topo.max_cpu_num; cpux++) {
2711                                 if ((cpus[cpux].physical_package_id == pkg) &&
2712                                    (cpus[cpux].physical_node_id == node)) {
2713                                         cpus[cpux].logical_node_id = lnode;
2714                                         cpu_count++;
2715                                 }
2716                         }
2717                         lnode++;
2718                         if (lnode > topo.nodes_per_pkg)
2719                                 topo.nodes_per_pkg = lnode;
2720                 }
2721                 if (cpu_count >= topo.max_cpu_num)
2722                         break;
2723         }
2724 }
2725
2726 int get_physical_node_id(struct cpu_topology *thiscpu)
2727 {
2728         char path[80];
2729         FILE *filep;
2730         int i;
2731         int cpu = thiscpu->logical_cpu_id;
2732
2733         for (i = 0; i <= topo.max_cpu_num; i++) {
2734                 sprintf(path, "/sys/devices/system/cpu/cpu%d/node%i/cpulist",
2735                         cpu, i);
2736                 filep = fopen(path, "r");
2737                 if (!filep)
2738                         continue;
2739                 fclose(filep);
2740                 return i;
2741         }
2742         return -1;
2743 }
2744
2745 int get_thread_siblings(struct cpu_topology *thiscpu)
2746 {
2747         char path[80], character;
2748         FILE *filep;
2749         unsigned long map;
2750         int so, shift, sib_core;
2751         int cpu = thiscpu->logical_cpu_id;
2752         int offset = topo.max_cpu_num + 1;
2753         size_t size;
2754         int thread_id = 0;
2755
2756         thiscpu->put_ids = CPU_ALLOC((topo.max_cpu_num + 1));
2757         if (thiscpu->thread_id < 0)
2758                 thiscpu->thread_id = thread_id++;
2759         if (!thiscpu->put_ids)
2760                 return -1;
2761
2762         size = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
2763         CPU_ZERO_S(size, thiscpu->put_ids);
2764
2765         sprintf(path,
2766                 "/sys/devices/system/cpu/cpu%d/topology/thread_siblings", cpu);
2767         filep = fopen_or_die(path, "r");
2768         do {
2769                 offset -= BITMASK_SIZE;
2770                 if (fscanf(filep, "%lx%c", &map, &character) != 2)
2771                         err(1, "%s: failed to parse file", path);
2772                 for (shift = 0; shift < BITMASK_SIZE; shift++) {
2773                         if ((map >> shift) & 0x1) {
2774                                 so = shift + offset;
2775                                 sib_core = get_core_id(so);
2776                                 if (sib_core == thiscpu->physical_core_id) {
2777                                         CPU_SET_S(so, size, thiscpu->put_ids);
2778                                         if ((so != cpu) &&
2779                                             (cpus[so].thread_id < 0))
2780                                                 cpus[so].thread_id =
2781                                                                     thread_id++;
2782                                 }
2783                         }
2784                 }
2785         } while (!strncmp(&character, ",", 1));
2786         fclose(filep);
2787
2788         return CPU_COUNT_S(size, thiscpu->put_ids);
2789 }
2790
2791 /*
2792  * run func(thread, core, package) in topology order
2793  * skip non-present cpus
2794  */
2795
2796 int for_all_cpus_2(int (func)(struct thread_data *, struct core_data *,
2797         struct pkg_data *, struct thread_data *, struct core_data *,
2798         struct pkg_data *), struct thread_data *thread_base,
2799         struct core_data *core_base, struct pkg_data *pkg_base,
2800         struct thread_data *thread_base2, struct core_data *core_base2,
2801         struct pkg_data *pkg_base2)
2802 {
2803         int retval, pkg_no, node_no, core_no, thread_no;
2804
2805         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
2806                 for (node_no = 0; node_no < topo.nodes_per_pkg; ++node_no) {
2807                         for (core_no = 0; core_no < topo.cores_per_node;
2808                              ++core_no) {
2809                                 for (thread_no = 0; thread_no <
2810                                         topo.threads_per_core; ++thread_no) {
2811                                         struct thread_data *t, *t2;
2812                                         struct core_data *c, *c2;
2813                                         struct pkg_data *p, *p2;
2814
2815                                         t = GET_THREAD(thread_base, thread_no,
2816                                                        core_no, node_no,
2817                                                        pkg_no);
2818
2819                                         if (cpu_is_not_present(t->cpu_id))
2820                                                 continue;
2821
2822                                         t2 = GET_THREAD(thread_base2, thread_no,
2823                                                         core_no, node_no,
2824                                                         pkg_no);
2825
2826                                         c = GET_CORE(core_base, core_no,
2827                                                      node_no, pkg_no);
2828                                         c2 = GET_CORE(core_base2, core_no,
2829                                                       node_no,
2830                                                       pkg_no);
2831
2832                                         p = GET_PKG(pkg_base, pkg_no);
2833                                         p2 = GET_PKG(pkg_base2, pkg_no);
2834
2835                                         retval = func(t, c, p, t2, c2, p2);
2836                                         if (retval)
2837                                                 return retval;
2838                                 }
2839                         }
2840                 }
2841         }
2842         return 0;
2843 }
2844
2845 /*
2846  * run func(cpu) on every cpu in /proc/stat
2847  * return max_cpu number
2848  */
2849 int for_all_proc_cpus(int (func)(int))
2850 {
2851         FILE *fp;
2852         int cpu_num;
2853         int retval;
2854
2855         fp = fopen_or_die(proc_stat, "r");
2856
2857         retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
2858         if (retval != 0)
2859                 err(1, "%s: failed to parse format", proc_stat);
2860
2861         while (1) {
2862                 retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
2863                 if (retval != 1)
2864                         break;
2865
2866                 retval = func(cpu_num);
2867                 if (retval) {
2868                         fclose(fp);
2869                         return(retval);
2870                 }
2871         }
2872         fclose(fp);
2873         return 0;
2874 }
2875
2876 void re_initialize(void)
2877 {
2878         free_all_buffers();
2879         setup_all_buffers();
2880         printf("turbostat: re-initialized with num_cpus %d\n", topo.num_cpus);
2881 }
2882
2883 void set_max_cpu_num(void)
2884 {
2885         FILE *filep;
2886         int base_cpu;
2887         unsigned long dummy;
2888         char pathname[64];
2889
2890         base_cpu = sched_getcpu();
2891         if (base_cpu < 0)
2892                 err(1, "cannot find calling cpu ID");
2893         sprintf(pathname,
2894                 "/sys/devices/system/cpu/cpu%d/topology/thread_siblings",
2895                 base_cpu);
2896
2897         filep = fopen_or_die(pathname, "r");
2898         topo.max_cpu_num = 0;
2899         while (fscanf(filep, "%lx,", &dummy) == 1)
2900                 topo.max_cpu_num += BITMASK_SIZE;
2901         fclose(filep);
2902         topo.max_cpu_num--; /* 0 based */
2903 }
2904
2905 /*
2906  * count_cpus()
2907  * remember the last one seen, it will be the max
2908  */
2909 int count_cpus(int cpu)
2910 {
2911         topo.num_cpus++;
2912         return 0;
2913 }
2914 int mark_cpu_present(int cpu)
2915 {
2916         CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
2917         return 0;
2918 }
2919
2920 int init_thread_id(int cpu)
2921 {
2922         cpus[cpu].thread_id = -1;
2923         return 0;
2924 }
2925
2926 /*
2927  * snapshot_proc_interrupts()
2928  *
2929  * read and record summary of /proc/interrupts
2930  *
2931  * return 1 if config change requires a restart, else return 0
2932  */
2933 int snapshot_proc_interrupts(void)
2934 {
2935         static FILE *fp;
2936         int column, retval;
2937
2938         if (fp == NULL)
2939                 fp = fopen_or_die("/proc/interrupts", "r");
2940         else
2941                 rewind(fp);
2942
2943         /* read 1st line of /proc/interrupts to get cpu* name for each column */
2944         for (column = 0; column < topo.num_cpus; ++column) {
2945                 int cpu_number;
2946
2947                 retval = fscanf(fp, " CPU%d", &cpu_number);
2948                 if (retval != 1)
2949                         break;
2950
2951                 if (cpu_number > topo.max_cpu_num) {
2952                         warn("/proc/interrupts: cpu%d: > %d", cpu_number, topo.max_cpu_num);
2953                         return 1;
2954                 }
2955
2956                 irq_column_2_cpu[column] = cpu_number;
2957                 irqs_per_cpu[cpu_number] = 0;
2958         }
2959
2960         /* read /proc/interrupt count lines and sum up irqs per cpu */
2961         while (1) {
2962                 int column;
2963                 char buf[64];
2964
2965                 retval = fscanf(fp, " %s:", buf);       /* flush irq# "N:" */
2966                 if (retval != 1)
2967                         break;
2968
2969                 /* read the count per cpu */
2970                 for (column = 0; column < topo.num_cpus; ++column) {
2971
2972                         int cpu_number, irq_count;
2973
2974                         retval = fscanf(fp, " %d", &irq_count);
2975                         if (retval != 1)
2976                                 break;
2977
2978                         cpu_number = irq_column_2_cpu[column];
2979                         irqs_per_cpu[cpu_number] += irq_count;
2980
2981                 }
2982
2983                 while (getc(fp) != '\n')
2984                         ;       /* flush interrupt description */
2985
2986         }
2987         return 0;
2988 }
2989 /*
2990  * snapshot_gfx_rc6_ms()
2991  *
2992  * record snapshot of
2993  * /sys/class/drm/card0/power/rc6_residency_ms
2994  *
2995  * return 1 if config change requires a restart, else return 0
2996  */
2997 int snapshot_gfx_rc6_ms(void)
2998 {
2999         FILE *fp;
3000         int retval;
3001
3002         fp = fopen_or_die("/sys/class/drm/card0/power/rc6_residency_ms", "r");
3003
3004         retval = fscanf(fp, "%lld", &gfx_cur_rc6_ms);
3005         if (retval != 1)
3006                 err(1, "GFX rc6");
3007
3008         fclose(fp);
3009
3010         return 0;
3011 }
3012 /*
3013  * snapshot_gfx_mhz()
3014  *
3015  * record snapshot of
3016  * /sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz
3017  *
3018  * return 1 if config change requires a restart, else return 0
3019  */
3020 int snapshot_gfx_mhz(void)
3021 {
3022         static FILE *fp;
3023         int retval;
3024
3025         if (fp == NULL)
3026                 fp = fopen_or_die("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", "r");
3027         else {
3028                 rewind(fp);
3029                 fflush(fp);
3030         }
3031
3032         retval = fscanf(fp, "%d", &gfx_cur_mhz);
3033         if (retval != 1)
3034                 err(1, "GFX MHz");
3035
3036         return 0;
3037 }
3038
3039 /*
3040  * snapshot_gfx_cur_mhz()
3041  *
3042  * record snapshot of
3043  * /sys/class/graphics/fb0/device/drm/card0/gt_act_freq_mhz
3044  *
3045  * return 1 if config change requires a restart, else return 0
3046  */
3047 int snapshot_gfx_act_mhz(void)
3048 {
3049         static FILE *fp;
3050         int retval;
3051
3052         if (fp == NULL)
3053                 fp = fopen_or_die("/sys/class/graphics/fb0/device/drm/card0/gt_act_freq_mhz", "r");
3054         else {
3055                 rewind(fp);
3056                 fflush(fp);
3057         }
3058
3059         retval = fscanf(fp, "%d", &gfx_act_mhz);
3060         if (retval != 1)
3061                 err(1, "GFX ACT MHz");
3062
3063         return 0;
3064 }
3065
3066 /*
3067  * snapshot_cpu_lpi()
3068  *
3069  * record snapshot of
3070  * /sys/devices/system/cpu/cpuidle/low_power_idle_cpu_residency_us
3071  */
3072 int snapshot_cpu_lpi_us(void)
3073 {
3074         FILE *fp;
3075         int retval;
3076
3077         fp = fopen_or_die("/sys/devices/system/cpu/cpuidle/low_power_idle_cpu_residency_us", "r");
3078
3079         retval = fscanf(fp, "%lld", &cpuidle_cur_cpu_lpi_us);
3080         if (retval != 1) {
3081                 fprintf(stderr, "Disabling Low Power Idle CPU output\n");
3082                 BIC_NOT_PRESENT(BIC_CPU_LPI);
3083                 fclose(fp);
3084                 return -1;
3085         }
3086
3087         fclose(fp);
3088
3089         return 0;
3090 }
3091 /*
3092  * snapshot_sys_lpi()
3093  *
3094  * record snapshot of sys_lpi_file
3095  */
3096 int snapshot_sys_lpi_us(void)
3097 {
3098         FILE *fp;
3099         int retval;
3100
3101         fp = fopen_or_die(sys_lpi_file, "r");
3102
3103         retval = fscanf(fp, "%lld", &cpuidle_cur_sys_lpi_us);
3104         if (retval != 1) {
3105                 fprintf(stderr, "Disabling Low Power Idle System output\n");
3106                 BIC_NOT_PRESENT(BIC_SYS_LPI);
3107                 fclose(fp);
3108                 return -1;
3109         }
3110         fclose(fp);
3111
3112         return 0;
3113 }
3114 /*
3115  * snapshot /proc and /sys files
3116  *
3117  * return 1 if configuration restart needed, else return 0
3118  */
3119 int snapshot_proc_sysfs_files(void)
3120 {
3121         if (DO_BIC(BIC_IRQ))
3122                 if (snapshot_proc_interrupts())
3123                         return 1;
3124
3125         if (DO_BIC(BIC_GFX_rc6))
3126                 snapshot_gfx_rc6_ms();
3127
3128         if (DO_BIC(BIC_GFXMHz))
3129                 snapshot_gfx_mhz();
3130
3131         if (DO_BIC(BIC_GFXACTMHz))
3132                 snapshot_gfx_act_mhz();
3133
3134         if (DO_BIC(BIC_CPU_LPI))
3135                 snapshot_cpu_lpi_us();
3136
3137         if (DO_BIC(BIC_SYS_LPI))
3138                 snapshot_sys_lpi_us();
3139
3140         return 0;
3141 }
3142
3143 int exit_requested;
3144
3145 static void signal_handler (int signal)
3146 {
3147         switch (signal) {
3148         case SIGINT:
3149                 exit_requested = 1;
3150                 if (debug)
3151                         fprintf(stderr, " SIGINT\n");
3152                 break;
3153         case SIGUSR1:
3154                 if (debug > 1)
3155                         fprintf(stderr, "SIGUSR1\n");
3156                 break;
3157         }
3158 }
3159
3160 void setup_signal_handler(void)
3161 {
3162         struct sigaction sa;
3163
3164         memset(&sa, 0, sizeof(sa));
3165
3166         sa.sa_handler = &signal_handler;
3167
3168         if (sigaction(SIGINT, &sa, NULL) < 0)
3169                 err(1, "sigaction SIGINT");
3170         if (sigaction(SIGUSR1, &sa, NULL) < 0)
3171                 err(1, "sigaction SIGUSR1");
3172 }
3173
3174 void do_sleep(void)
3175 {
3176         struct timeval tout;
3177         struct timespec rest;
3178         fd_set readfds;
3179         int retval;
3180
3181         FD_ZERO(&readfds);
3182         FD_SET(0, &readfds);
3183
3184         if (ignore_stdin) {
3185                 nanosleep(&interval_ts, NULL);
3186                 return;
3187         }
3188
3189         tout = interval_tv;
3190         retval = select(1, &readfds, NULL, NULL, &tout);
3191
3192         if (retval == 1) {
3193                 switch (getc(stdin)) {
3194                 case 'q':
3195                         exit_requested = 1;
3196                         break;
3197                 case EOF:
3198                         /*
3199                          * 'stdin' is a pipe closed on the other end. There
3200                          * won't be any further input.
3201                          */
3202                         ignore_stdin = 1;
3203                         /* Sleep the rest of the time */
3204                         rest.tv_sec = (tout.tv_sec + tout.tv_usec / 1000000);
3205                         rest.tv_nsec = (tout.tv_usec % 1000000) * 1000;
3206                         nanosleep(&rest, NULL);
3207                 }
3208         }
3209 }
3210
3211 int get_msr_sum(int cpu, off_t offset, unsigned long long *msr)
3212 {
3213         int ret, idx;
3214         unsigned long long msr_cur, msr_last;
3215
3216         if (!per_cpu_msr_sum)
3217                 return 1;
3218
3219         idx = offset_to_idx(offset);
3220         if (idx < 0)
3221                 return idx;
3222         /* get_msr_sum() = sum + (get_msr() - last) */
3223         ret = get_msr(cpu, offset, &msr_cur);
3224         if (ret)
3225                 return ret;
3226         msr_last = per_cpu_msr_sum[cpu].entries[idx].last;
3227         DELTA_WRAP32(msr_cur, msr_last);
3228         *msr = msr_last + per_cpu_msr_sum[cpu].entries[idx].sum;
3229
3230         return 0;
3231 }
3232
3233 timer_t timerid;
3234
3235 /* Timer callback, update the sum of MSRs periodically. */
3236 static int update_msr_sum(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3237 {
3238         int i, ret;
3239         int cpu = t->cpu_id;
3240
3241         for (i = IDX_PKG_ENERGY; i < IDX_COUNT; i++) {
3242                 unsigned long long msr_cur, msr_last;
3243                 int offset;
3244
3245                 if (!idx_valid(i))
3246                         continue;
3247                 offset = idx_to_offset(i);
3248                 if (offset < 0)
3249                         continue;
3250                 ret = get_msr(cpu, offset, &msr_cur);
3251                 if (ret) {
3252                         fprintf(outf, "Can not update msr(0x%x)\n", offset);
3253                         continue;
3254                 }
3255
3256                 msr_last = per_cpu_msr_sum[cpu].entries[i].last;
3257                 per_cpu_msr_sum[cpu].entries[i].last = msr_cur & 0xffffffff;
3258
3259                 DELTA_WRAP32(msr_cur, msr_last);
3260                 per_cpu_msr_sum[cpu].entries[i].sum += msr_last;
3261         }
3262         return 0;
3263 }
3264
3265 static void
3266 msr_record_handler(union sigval v)
3267 {
3268         for_all_cpus(update_msr_sum, EVEN_COUNTERS);
3269 }
3270
3271 void msr_sum_record(void)
3272 {
3273         struct itimerspec its;
3274         struct sigevent sev;
3275
3276         per_cpu_msr_sum = calloc(topo.max_cpu_num + 1, sizeof(struct msr_sum_array));
3277         if (!per_cpu_msr_sum) {
3278                 fprintf(outf, "Can not allocate memory for long time MSR.\n");
3279                 return;
3280         }
3281         /*
3282          * Signal handler might be restricted, so use thread notifier instead.
3283          */
3284         memset(&sev, 0, sizeof(struct sigevent));
3285         sev.sigev_notify = SIGEV_THREAD;
3286         sev.sigev_notify_function = msr_record_handler;
3287
3288         sev.sigev_value.sival_ptr = &timerid;
3289         if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) {
3290                 fprintf(outf, "Can not create timer.\n");
3291                 goto release_msr;
3292         }
3293
3294         its.it_value.tv_sec = 0;
3295         its.it_value.tv_nsec = 1;
3296         /*
3297          * A wraparound time has been calculated early.
3298          * Some sources state that the peak power for a
3299          * microprocessor is usually 1.5 times the TDP rating,
3300          * use 2 * TDP for safety.
3301          */
3302         its.it_interval.tv_sec = rapl_joule_counter_range / 2;
3303         its.it_interval.tv_nsec = 0;
3304
3305         if (timer_settime(timerid, 0, &its, NULL) == -1) {
3306                 fprintf(outf, "Can not set timer.\n");
3307                 goto release_timer;
3308         }
3309         return;
3310
3311  release_timer:
3312         timer_delete(timerid);
3313  release_msr:
3314         free(per_cpu_msr_sum);
3315 }
3316
3317 void turbostat_loop()
3318 {
3319         int retval;
3320         int restarted = 0;
3321         int done_iters = 0;
3322
3323         setup_signal_handler();
3324
3325 restart:
3326         restarted++;
3327
3328         snapshot_proc_sysfs_files();
3329         retval = for_all_cpus(get_counters, EVEN_COUNTERS);
3330         first_counter_read = 0;
3331         if (retval < -1) {
3332                 exit(retval);
3333         } else if (retval == -1) {
3334                 if (restarted > 1) {
3335                         exit(retval);
3336                 }
3337                 re_initialize();
3338                 goto restart;
3339         }
3340         restarted = 0;
3341         done_iters = 0;
3342         gettimeofday(&tv_even, (struct timezone *)NULL);
3343
3344         while (1) {
3345                 if (for_all_proc_cpus(cpu_is_not_present)) {
3346                         re_initialize();
3347                         goto restart;
3348                 }
3349                 do_sleep();
3350                 if (snapshot_proc_sysfs_files())
3351                         goto restart;
3352                 retval = for_all_cpus(get_counters, ODD_COUNTERS);
3353                 if (retval < -1) {
3354                         exit(retval);
3355                 } else if (retval == -1) {
3356                         re_initialize();
3357                         goto restart;
3358                 }
3359                 gettimeofday(&tv_odd, (struct timezone *)NULL);
3360                 timersub(&tv_odd, &tv_even, &tv_delta);
3361                 if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS)) {
3362                         re_initialize();
3363                         goto restart;
3364                 }
3365                 compute_average(EVEN_COUNTERS);
3366                 format_all_counters(EVEN_COUNTERS);
3367                 flush_output_stdout();
3368                 if (exit_requested)
3369                         break;
3370                 if (num_iterations && ++done_iters >= num_iterations)
3371                         break;
3372                 do_sleep();
3373                 if (snapshot_proc_sysfs_files())
3374                         goto restart;
3375                 retval = for_all_cpus(get_counters, EVEN_COUNTERS);
3376                 if (retval < -1) {
3377                         exit(retval);
3378                 } else if (retval == -1) {
3379                         re_initialize();
3380                         goto restart;
3381                 }
3382                 gettimeofday(&tv_even, (struct timezone *)NULL);
3383                 timersub(&tv_even, &tv_odd, &tv_delta);
3384                 if (for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS)) {
3385                         re_initialize();
3386                         goto restart;
3387                 }
3388                 compute_average(ODD_COUNTERS);
3389                 format_all_counters(ODD_COUNTERS);
3390                 flush_output_stdout();
3391                 if (exit_requested)
3392                         break;
3393                 if (num_iterations && ++done_iters >= num_iterations)
3394                         break;
3395         }
3396 }
3397
3398 void check_dev_msr()
3399 {
3400         struct stat sb;
3401         char pathname[32];
3402
3403         sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
3404         if (stat(pathname, &sb))
3405                 if (system("/sbin/modprobe msr > /dev/null 2>&1"))
3406                         err(-5, "no /dev/cpu/0/msr, Try \"# modprobe msr\" ");
3407 }
3408
3409 /*
3410  * check for CAP_SYS_RAWIO
3411  * return 0 on success
3412  * return 1 on fail
3413  */
3414 int check_for_cap_sys_rawio(void)
3415 {
3416         cap_t caps;
3417         cap_flag_value_t cap_flag_value;
3418
3419         caps = cap_get_proc();
3420         if (caps == NULL)
3421                 err(-6, "cap_get_proc\n");
3422
3423         if (cap_get_flag(caps, CAP_SYS_RAWIO, CAP_EFFECTIVE, &cap_flag_value))
3424                 err(-6, "cap_get\n");
3425
3426         if (cap_flag_value != CAP_SET) {
3427                 warnx("capget(CAP_SYS_RAWIO) failed,"
3428                         " try \"# setcap cap_sys_rawio=ep %s\"", progname);
3429                 return 1;
3430         }
3431
3432         if (cap_free(caps) == -1)
3433                 err(-6, "cap_free\n");
3434
3435         return 0;
3436 }
3437 void check_permissions(void)
3438 {
3439         int do_exit = 0;
3440         char pathname[32];
3441
3442         /* check for CAP_SYS_RAWIO */
3443         do_exit += check_for_cap_sys_rawio();
3444
3445         /* test file permissions */
3446         sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
3447         if (euidaccess(pathname, R_OK)) {
3448                 do_exit++;
3449                 warn("/dev/cpu/0/msr open failed, try chown or chmod +r /dev/cpu/*/msr");
3450         }
3451
3452         /* if all else fails, thell them to be root */
3453         if (do_exit)
3454                 if (getuid() != 0)
3455                         warnx("... or simply run as root");
3456
3457         if (do_exit)
3458                 exit(-6);
3459 }
3460
3461 /*
3462  * NHM adds support for additional MSRs:
3463  *
3464  * MSR_SMI_COUNT                   0x00000034
3465  *
3466  * MSR_PLATFORM_INFO               0x000000ce
3467  * MSR_PKG_CST_CONFIG_CONTROL     0x000000e2
3468  *
3469  * MSR_MISC_PWR_MGMT               0x000001aa
3470  *
3471  * MSR_PKG_C3_RESIDENCY            0x000003f8
3472  * MSR_PKG_C6_RESIDENCY            0x000003f9
3473  * MSR_CORE_C3_RESIDENCY           0x000003fc
3474  * MSR_CORE_C6_RESIDENCY           0x000003fd
3475  *
3476  * Side effect:
3477  * sets global pkg_cstate_limit to decode MSR_PKG_CST_CONFIG_CONTROL
3478  * sets has_misc_feature_control
3479  */
3480 int probe_nhm_msrs(unsigned int family, unsigned int model)
3481 {
3482         unsigned long long msr;
3483         unsigned int base_ratio;
3484         int *pkg_cstate_limits;
3485
3486         if (!genuine_intel)
3487                 return 0;
3488
3489         if (family != 6)
3490                 return 0;
3491
3492         bclk = discover_bclk(family, model);
3493
3494         switch (model) {
3495         case INTEL_FAM6_NEHALEM:        /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
3496         case INTEL_FAM6_NEHALEM_EX:     /* Nehalem-EX Xeon - Beckton */
3497                 pkg_cstate_limits = nhm_pkg_cstate_limits;
3498                 break;
3499         case INTEL_FAM6_SANDYBRIDGE:    /* SNB */
3500         case INTEL_FAM6_SANDYBRIDGE_X:  /* SNB Xeon */
3501         case INTEL_FAM6_IVYBRIDGE:      /* IVB */
3502         case INTEL_FAM6_IVYBRIDGE_X:    /* IVB Xeon */
3503                 pkg_cstate_limits = snb_pkg_cstate_limits;
3504                 has_misc_feature_control = 1;
3505                 break;
3506         case INTEL_FAM6_HASWELL:        /* HSW */
3507         case INTEL_FAM6_HASWELL_G:      /* HSW */
3508         case INTEL_FAM6_HASWELL_X:      /* HSX */
3509         case INTEL_FAM6_HASWELL_L:      /* HSW */
3510         case INTEL_FAM6_BROADWELL:      /* BDW */
3511         case INTEL_FAM6_BROADWELL_G:    /* BDW */
3512         case INTEL_FAM6_BROADWELL_X:    /* BDX */
3513         case INTEL_FAM6_SKYLAKE_L:      /* SKL */
3514         case INTEL_FAM6_CANNONLAKE_L:   /* CNL */
3515                 pkg_cstate_limits = hsw_pkg_cstate_limits;
3516                 has_misc_feature_control = 1;
3517                 break;
3518         case INTEL_FAM6_SKYLAKE_X:      /* SKX */
3519                 pkg_cstate_limits = skx_pkg_cstate_limits;
3520                 has_misc_feature_control = 1;
3521                 break;
3522         case INTEL_FAM6_ATOM_SILVERMONT:        /* BYT */
3523                 no_MSR_MISC_PWR_MGMT = 1;
3524         case INTEL_FAM6_ATOM_SILVERMONT_D:      /* AVN */
3525                 pkg_cstate_limits = slv_pkg_cstate_limits;
3526                 break;
3527         case INTEL_FAM6_ATOM_AIRMONT:   /* AMT */
3528                 pkg_cstate_limits = amt_pkg_cstate_limits;
3529                 no_MSR_MISC_PWR_MGMT = 1;
3530                 break;
3531         case INTEL_FAM6_XEON_PHI_KNL:   /* PHI */
3532                 pkg_cstate_limits = phi_pkg_cstate_limits;
3533                 break;
3534         case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
3535         case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
3536         case INTEL_FAM6_ATOM_GOLDMONT_D:        /* DNV */
3537         case INTEL_FAM6_ATOM_TREMONT:   /* EHL */
3538         case INTEL_FAM6_ATOM_TREMONT_D: /* JVL */
3539                 pkg_cstate_limits = glm_pkg_cstate_limits;
3540                 break;
3541         default:
3542                 return 0;
3543         }
3544         get_msr(base_cpu, MSR_PKG_CST_CONFIG_CONTROL, &msr);
3545         pkg_cstate_limit = pkg_cstate_limits[msr & 0xF];
3546
3547         get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
3548         base_ratio = (msr >> 8) & 0xFF;
3549
3550         base_hz = base_ratio * bclk * 1000000;
3551         has_base_hz = 1;
3552         return 1;
3553 }
3554 /*
3555  * SLV client has support for unique MSRs:
3556  *
3557  * MSR_CC6_DEMOTION_POLICY_CONFIG
3558  * MSR_MC6_DEMOTION_POLICY_CONFIG
3559  */
3560
3561 int has_slv_msrs(unsigned int family, unsigned int model)
3562 {
3563         if (!genuine_intel)
3564                 return 0;
3565
3566         switch (model) {
3567         case INTEL_FAM6_ATOM_SILVERMONT:
3568         case INTEL_FAM6_ATOM_SILVERMONT_MID:
3569         case INTEL_FAM6_ATOM_AIRMONT_MID:
3570                 return 1;
3571         }
3572         return 0;
3573 }
3574 int is_dnv(unsigned int family, unsigned int model)
3575 {
3576
3577         if (!genuine_intel)
3578                 return 0;
3579
3580         switch (model) {
3581         case INTEL_FAM6_ATOM_GOLDMONT_D:
3582                 return 1;
3583         }
3584         return 0;
3585 }
3586 int is_bdx(unsigned int family, unsigned int model)
3587 {
3588
3589         if (!genuine_intel)
3590                 return 0;
3591
3592         switch (model) {
3593         case INTEL_FAM6_BROADWELL_X:
3594                 return 1;
3595         }
3596         return 0;
3597 }
3598 int is_skx(unsigned int family, unsigned int model)
3599 {
3600
3601         if (!genuine_intel)
3602                 return 0;
3603
3604         switch (model) {
3605         case INTEL_FAM6_SKYLAKE_X:
3606                 return 1;
3607         }
3608         return 0;
3609 }
3610 int is_ehl(unsigned int family, unsigned int model)
3611 {
3612         if (!genuine_intel)
3613                 return 0;
3614
3615         switch (model) {
3616         case INTEL_FAM6_ATOM_TREMONT:
3617                 return 1;
3618         }
3619         return 0;
3620 }
3621 int is_jvl(unsigned int family, unsigned int model)
3622 {
3623         if (!genuine_intel)
3624                 return 0;
3625
3626         switch (model) {
3627         case INTEL_FAM6_ATOM_TREMONT_D:
3628                 return 1;
3629         }
3630         return 0;
3631 }
3632
3633 int has_turbo_ratio_limit(unsigned int family, unsigned int model)
3634 {
3635         if (has_slv_msrs(family, model))
3636                 return 0;
3637
3638         switch (model) {
3639         /* Nehalem compatible, but do not include turbo-ratio limit support */
3640         case INTEL_FAM6_NEHALEM_EX:     /* Nehalem-EX Xeon - Beckton */
3641         case INTEL_FAM6_XEON_PHI_KNL:   /* PHI - Knights Landing (different MSR definition) */
3642                 return 0;
3643         default:
3644                 return 1;
3645         }
3646 }
3647 int has_atom_turbo_ratio_limit(unsigned int family, unsigned int model)
3648 {
3649         if (has_slv_msrs(family, model))
3650                 return 1;
3651
3652         return 0;
3653 }
3654 int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
3655 {
3656         if (!genuine_intel)
3657                 return 0;
3658
3659         if (family != 6)
3660                 return 0;
3661
3662         switch (model) {
3663         case INTEL_FAM6_IVYBRIDGE_X:    /* IVB Xeon */
3664         case INTEL_FAM6_HASWELL_X:      /* HSW Xeon */
3665                 return 1;
3666         default:
3667                 return 0;
3668         }
3669 }
3670 int has_hsw_turbo_ratio_limit(unsigned int family, unsigned int model)
3671 {
3672         if (!genuine_intel)
3673                 return 0;
3674
3675         if (family != 6)
3676                 return 0;
3677
3678         switch (model) {
3679         case INTEL_FAM6_HASWELL_X:      /* HSW Xeon */
3680                 return 1;
3681         default:
3682                 return 0;
3683         }
3684 }
3685
3686 int has_knl_turbo_ratio_limit(unsigned int family, unsigned int model)
3687 {
3688         if (!genuine_intel)
3689                 return 0;
3690
3691         if (family != 6)
3692                 return 0;
3693
3694         switch (model) {
3695         case INTEL_FAM6_XEON_PHI_KNL:   /* Knights Landing */
3696                 return 1;
3697         default:
3698                 return 0;
3699         }
3700 }
3701 int has_glm_turbo_ratio_limit(unsigned int family, unsigned int model)
3702 {
3703         if (!genuine_intel)
3704                 return 0;
3705
3706         if (family != 6)
3707                 return 0;
3708
3709         switch (model) {
3710         case INTEL_FAM6_ATOM_GOLDMONT:
3711         case INTEL_FAM6_SKYLAKE_X:
3712                 return 1;
3713         default:
3714                 return 0;
3715         }
3716 }
3717 int has_config_tdp(unsigned int family, unsigned int model)
3718 {
3719         if (!genuine_intel)
3720                 return 0;
3721
3722         if (family != 6)
3723                 return 0;
3724
3725         switch (model) {
3726         case INTEL_FAM6_IVYBRIDGE:      /* IVB */
3727         case INTEL_FAM6_HASWELL:        /* HSW */
3728         case INTEL_FAM6_HASWELL_X:      /* HSX */
3729         case INTEL_FAM6_HASWELL_L:      /* HSW */
3730         case INTEL_FAM6_HASWELL_G:      /* HSW */
3731         case INTEL_FAM6_BROADWELL:      /* BDW */
3732         case INTEL_FAM6_BROADWELL_G:    /* BDW */
3733         case INTEL_FAM6_BROADWELL_X:    /* BDX */
3734         case INTEL_FAM6_SKYLAKE_L:      /* SKL */
3735         case INTEL_FAM6_CANNONLAKE_L:   /* CNL */
3736         case INTEL_FAM6_SKYLAKE_X:      /* SKX */
3737
3738         case INTEL_FAM6_XEON_PHI_KNL:   /* Knights Landing */
3739                 return 1;
3740         default:
3741                 return 0;
3742         }
3743 }
3744
3745 static void
3746 remove_underbar(char *s)
3747 {
3748         char *to = s;
3749
3750         while (*s) {
3751                 if (*s != '_')
3752                         *to++ = *s;
3753                 s++;
3754         }
3755
3756         *to = 0;
3757 }
3758
3759 static void
3760 dump_cstate_pstate_config_info(unsigned int family, unsigned int model)
3761 {
3762         if (!do_nhm_platform_info)
3763                 return;
3764
3765         dump_nhm_platform_info();
3766
3767         if (has_hsw_turbo_ratio_limit(family, model))
3768                 dump_hsw_turbo_ratio_limits();
3769
3770         if (has_ivt_turbo_ratio_limit(family, model))
3771                 dump_ivt_turbo_ratio_limits();
3772
3773         if (has_turbo_ratio_limit(family, model))
3774                 dump_turbo_ratio_limits(family, model);
3775
3776         if (has_atom_turbo_ratio_limit(family, model))
3777                 dump_atom_turbo_ratio_limits();
3778
3779         if (has_knl_turbo_ratio_limit(family, model))
3780                 dump_knl_turbo_ratio_limits();
3781
3782         if (has_config_tdp(family, model))
3783                 dump_config_tdp();
3784
3785         dump_nhm_cst_cfg();
3786 }
3787
3788 static void dump_sysfs_file(char *path)
3789 {
3790         FILE *input;
3791         char cpuidle_buf[64];
3792
3793         input = fopen(path, "r");
3794         if (input == NULL) {
3795                 if (debug)
3796                         fprintf(outf, "NSFOD %s\n", path);
3797                 return;
3798         }
3799         if (!fgets(cpuidle_buf, sizeof(cpuidle_buf), input))
3800                 err(1, "%s: failed to read file", path);
3801         fclose(input);
3802
3803         fprintf(outf, "%s: %s", strrchr(path, '/') + 1, cpuidle_buf);
3804 }
3805 static void
3806 dump_sysfs_cstate_config(void)
3807 {
3808         char path[64];
3809         char name_buf[16];
3810         char desc[64];
3811         FILE *input;
3812         int state;
3813         char *sp;
3814
3815         if (access("/sys/devices/system/cpu/cpuidle", R_OK)) {
3816                 fprintf(outf, "cpuidle not loaded\n");
3817                 return;
3818         }
3819
3820         dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_driver");
3821         dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_governor");
3822         dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_governor_ro");
3823
3824         for (state = 0; state < 10; ++state) {
3825
3826                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name",
3827                         base_cpu, state);
3828                 input = fopen(path, "r");
3829                 if (input == NULL)
3830                         continue;
3831                 if (!fgets(name_buf, sizeof(name_buf), input))
3832                         err(1, "%s: failed to read file", path);
3833
3834                  /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
3835                 sp = strchr(name_buf, '-');
3836                 if (!sp)
3837                         sp = strchrnul(name_buf, '\n');
3838                 *sp = '\0';
3839                 fclose(input);
3840
3841                 remove_underbar(name_buf);
3842
3843                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/desc",
3844                         base_cpu, state);
3845                 input = fopen(path, "r");
3846                 if (input == NULL)
3847                         continue;
3848                 if (!fgets(desc, sizeof(desc), input))
3849                         err(1, "%s: failed to read file", path);
3850
3851                 fprintf(outf, "cpu%d: %s: %s", base_cpu, name_buf, desc);
3852                 fclose(input);
3853         }
3854 }
3855 static void
3856 dump_sysfs_pstate_config(void)
3857 {
3858         char path[64];
3859         char driver_buf[64];
3860         char governor_buf[64];
3861         FILE *input;
3862         int turbo;
3863
3864         sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_driver",
3865                         base_cpu);
3866         input = fopen(path, "r");
3867         if (input == NULL) {
3868                 fprintf(outf, "NSFOD %s\n", path);
3869                 return;
3870         }
3871         if (!fgets(driver_buf, sizeof(driver_buf), input))
3872                 err(1, "%s: failed to read file", path);
3873         fclose(input);
3874
3875         sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor",
3876                         base_cpu);
3877         input = fopen(path, "r");
3878         if (input == NULL) {
3879                 fprintf(outf, "NSFOD %s\n", path);
3880                 return;
3881         }
3882         if (!fgets(governor_buf, sizeof(governor_buf), input))
3883                 err(1, "%s: failed to read file", path);
3884         fclose(input);
3885
3886         fprintf(outf, "cpu%d: cpufreq driver: %s", base_cpu, driver_buf);
3887         fprintf(outf, "cpu%d: cpufreq governor: %s", base_cpu, governor_buf);
3888
3889         sprintf(path, "/sys/devices/system/cpu/cpufreq/boost");
3890         input = fopen(path, "r");
3891         if (input != NULL) {
3892                 if (fscanf(input, "%d", &turbo) != 1)
3893                         err(1, "%s: failed to parse number from file", path);
3894                 fprintf(outf, "cpufreq boost: %d\n", turbo);
3895                 fclose(input);
3896         }
3897
3898         sprintf(path, "/sys/devices/system/cpu/intel_pstate/no_turbo");
3899         input = fopen(path, "r");
3900         if (input != NULL) {
3901                 if (fscanf(input, "%d", &turbo) != 1)
3902                         err(1, "%s: failed to parse number from file", path);
3903                 fprintf(outf, "cpufreq intel_pstate no_turbo: %d\n", turbo);
3904                 fclose(input);
3905         }
3906 }
3907
3908
3909 /*
3910  * print_epb()
3911  * Decode the ENERGY_PERF_BIAS MSR
3912  */
3913 int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3914 {
3915         unsigned long long msr;
3916         char *epb_string;
3917         int cpu;
3918
3919         if (!has_epb)
3920                 return 0;
3921
3922         cpu = t->cpu_id;
3923
3924         /* EPB is per-package */
3925         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3926                 return 0;
3927
3928         if (cpu_migrate(cpu)) {
3929                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3930                 return -1;
3931         }
3932
3933         if (get_msr(cpu, MSR_IA32_ENERGY_PERF_BIAS, &msr))
3934                 return 0;
3935
3936         switch (msr & 0xF) {
3937         case ENERGY_PERF_BIAS_PERFORMANCE:
3938                 epb_string = "performance";
3939                 break;
3940         case ENERGY_PERF_BIAS_NORMAL:
3941                 epb_string = "balanced";
3942                 break;
3943         case ENERGY_PERF_BIAS_POWERSAVE:
3944                 epb_string = "powersave";
3945                 break;
3946         default:
3947                 epb_string = "custom";
3948                 break;
3949         }
3950         fprintf(outf, "cpu%d: MSR_IA32_ENERGY_PERF_BIAS: 0x%08llx (%s)\n", cpu, msr, epb_string);
3951
3952         return 0;
3953 }
3954 /*
3955  * print_hwp()
3956  * Decode the MSR_HWP_CAPABILITIES
3957  */
3958 int print_hwp(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3959 {
3960         unsigned long long msr;
3961         int cpu;
3962
3963         if (!has_hwp)
3964                 return 0;
3965
3966         cpu = t->cpu_id;
3967
3968         /* MSR_HWP_CAPABILITIES is per-package */
3969         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3970                 return 0;
3971
3972         if (cpu_migrate(cpu)) {
3973                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3974                 return -1;
3975         }
3976
3977         if (get_msr(cpu, MSR_PM_ENABLE, &msr))
3978                 return 0;
3979
3980         fprintf(outf, "cpu%d: MSR_PM_ENABLE: 0x%08llx (%sHWP)\n",
3981                 cpu, msr, (msr & (1 << 0)) ? "" : "No-");
3982
3983         /* MSR_PM_ENABLE[1] == 1 if HWP is enabled and MSRs visible */
3984         if ((msr & (1 << 0)) == 0)
3985                 return 0;
3986
3987         if (get_msr(cpu, MSR_HWP_CAPABILITIES, &msr))
3988                 return 0;
3989
3990         fprintf(outf, "cpu%d: MSR_HWP_CAPABILITIES: 0x%08llx "
3991                         "(high %d guar %d eff %d low %d)\n",
3992                         cpu, msr,
3993                         (unsigned int)HWP_HIGHEST_PERF(msr),
3994                         (unsigned int)HWP_GUARANTEED_PERF(msr),
3995                         (unsigned int)HWP_MOSTEFFICIENT_PERF(msr),
3996                         (unsigned int)HWP_LOWEST_PERF(msr));
3997
3998         if (get_msr(cpu, MSR_HWP_REQUEST, &msr))
3999                 return 0;
4000
4001         fprintf(outf, "cpu%d: MSR_HWP_REQUEST: 0x%08llx "
4002                         "(min %d max %d des %d epp 0x%x window 0x%x pkg 0x%x)\n",
4003                         cpu, msr,
4004                         (unsigned int)(((msr) >> 0) & 0xff),
4005                         (unsigned int)(((msr) >> 8) & 0xff),
4006                         (unsigned int)(((msr) >> 16) & 0xff),
4007                         (unsigned int)(((msr) >> 24) & 0xff),
4008                         (unsigned int)(((msr) >> 32) & 0xff3),
4009                         (unsigned int)(((msr) >> 42) & 0x1));
4010
4011         if (has_hwp_pkg) {
4012                 if (get_msr(cpu, MSR_HWP_REQUEST_PKG, &msr))
4013                         return 0;
4014
4015                 fprintf(outf, "cpu%d: MSR_HWP_REQUEST_PKG: 0x%08llx "
4016                         "(min %d max %d des %d epp 0x%x window 0x%x)\n",
4017                         cpu, msr,
4018                         (unsigned int)(((msr) >> 0) & 0xff),
4019                         (unsigned int)(((msr) >> 8) & 0xff),
4020                         (unsigned int)(((msr) >> 16) & 0xff),
4021                         (unsigned int)(((msr) >> 24) & 0xff),
4022                         (unsigned int)(((msr) >> 32) & 0xff3));
4023         }
4024         if (has_hwp_notify) {
4025                 if (get_msr(cpu, MSR_HWP_INTERRUPT, &msr))
4026                         return 0;
4027
4028                 fprintf(outf, "cpu%d: MSR_HWP_INTERRUPT: 0x%08llx "
4029                         "(%s_Guaranteed_Perf_Change, %s_Excursion_Min)\n",
4030                         cpu, msr,
4031                         ((msr) & 0x1) ? "EN" : "Dis",
4032                         ((msr) & 0x2) ? "EN" : "Dis");
4033         }
4034         if (get_msr(cpu, MSR_HWP_STATUS, &msr))
4035                 return 0;
4036
4037         fprintf(outf, "cpu%d: MSR_HWP_STATUS: 0x%08llx "
4038                         "(%sGuaranteed_Perf_Change, %sExcursion_Min)\n",
4039                         cpu, msr,
4040                         ((msr) & 0x1) ? "" : "No-",
4041                         ((msr) & 0x2) ? "" : "No-");
4042
4043         return 0;
4044 }
4045
4046 /*
4047  * print_perf_limit()
4048  */
4049 int print_perf_limit(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4050 {
4051         unsigned long long msr;
4052         int cpu;
4053
4054         cpu = t->cpu_id;
4055
4056         /* per-package */
4057         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
4058                 return 0;
4059
4060         if (cpu_migrate(cpu)) {
4061                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
4062                 return -1;
4063         }
4064
4065         if (do_core_perf_limit_reasons) {
4066                 get_msr(cpu, MSR_CORE_PERF_LIMIT_REASONS, &msr);
4067                 fprintf(outf, "cpu%d: MSR_CORE_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4068                 fprintf(outf, " (Active: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
4069                         (msr & 1 << 15) ? "bit15, " : "",
4070                         (msr & 1 << 14) ? "bit14, " : "",
4071                         (msr & 1 << 13) ? "Transitions, " : "",
4072                         (msr & 1 << 12) ? "MultiCoreTurbo, " : "",
4073                         (msr & 1 << 11) ? "PkgPwrL2, " : "",
4074                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
4075                         (msr & 1 << 9) ? "CorePwr, " : "",
4076                         (msr & 1 << 8) ? "Amps, " : "",
4077                         (msr & 1 << 6) ? "VR-Therm, " : "",
4078                         (msr & 1 << 5) ? "Auto-HWP, " : "",
4079                         (msr & 1 << 4) ? "Graphics, " : "",
4080                         (msr & 1 << 2) ? "bit2, " : "",
4081                         (msr & 1 << 1) ? "ThermStatus, " : "",
4082                         (msr & 1 << 0) ? "PROCHOT, " : "");
4083                 fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
4084                         (msr & 1 << 31) ? "bit31, " : "",
4085                         (msr & 1 << 30) ? "bit30, " : "",
4086                         (msr & 1 << 29) ? "Transitions, " : "",
4087                         (msr & 1 << 28) ? "MultiCoreTurbo, " : "",
4088                         (msr & 1 << 27) ? "PkgPwrL2, " : "",
4089                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
4090                         (msr & 1 << 25) ? "CorePwr, " : "",
4091                         (msr & 1 << 24) ? "Amps, " : "",
4092                         (msr & 1 << 22) ? "VR-Therm, " : "",
4093                         (msr & 1 << 21) ? "Auto-HWP, " : "",
4094                         (msr & 1 << 20) ? "Graphics, " : "",
4095                         (msr & 1 << 18) ? "bit18, " : "",
4096                         (msr & 1 << 17) ? "ThermStatus, " : "",
4097                         (msr & 1 << 16) ? "PROCHOT, " : "");
4098
4099         }
4100         if (do_gfx_perf_limit_reasons) {
4101                 get_msr(cpu, MSR_GFX_PERF_LIMIT_REASONS, &msr);
4102                 fprintf(outf, "cpu%d: MSR_GFX_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4103                 fprintf(outf, " (Active: %s%s%s%s%s%s%s%s)",
4104                         (msr & 1 << 0) ? "PROCHOT, " : "",
4105                         (msr & 1 << 1) ? "ThermStatus, " : "",
4106                         (msr & 1 << 4) ? "Graphics, " : "",
4107                         (msr & 1 << 6) ? "VR-Therm, " : "",
4108                         (msr & 1 << 8) ? "Amps, " : "",
4109                         (msr & 1 << 9) ? "GFXPwr, " : "",
4110                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
4111                         (msr & 1 << 11) ? "PkgPwrL2, " : "");
4112                 fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s)\n",
4113                         (msr & 1 << 16) ? "PROCHOT, " : "",
4114                         (msr & 1 << 17) ? "ThermStatus, " : "",
4115                         (msr & 1 << 20) ? "Graphics, " : "",
4116                         (msr & 1 << 22) ? "VR-Therm, " : "",
4117                         (msr & 1 << 24) ? "Amps, " : "",
4118                         (msr & 1 << 25) ? "GFXPwr, " : "",
4119                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
4120                         (msr & 1 << 27) ? "PkgPwrL2, " : "");
4121         }
4122         if (do_ring_perf_limit_reasons) {
4123                 get_msr(cpu, MSR_RING_PERF_LIMIT_REASONS, &msr);
4124                 fprintf(outf, "cpu%d: MSR_RING_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4125                 fprintf(outf, " (Active: %s%s%s%s%s%s)",
4126                         (msr & 1 << 0) ? "PROCHOT, " : "",
4127                         (msr & 1 << 1) ? "ThermStatus, " : "",
4128                         (msr & 1 << 6) ? "VR-Therm, " : "",
4129                         (msr & 1 << 8) ? "Amps, " : "",
4130                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
4131                         (msr & 1 << 11) ? "PkgPwrL2, " : "");
4132                 fprintf(outf, " (Logged: %s%s%s%s%s%s)\n",
4133                         (msr & 1 << 16) ? "PROCHOT, " : "",
4134                         (msr & 1 << 17) ? "ThermStatus, " : "",
4135                         (msr & 1 << 22) ? "VR-Therm, " : "",
4136                         (msr & 1 << 24) ? "Amps, " : "",
4137                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
4138                         (msr & 1 << 27) ? "PkgPwrL2, " : "");
4139         }
4140         return 0;
4141 }
4142
4143 #define RAPL_POWER_GRANULARITY  0x7FFF  /* 15 bit power granularity */
4144 #define RAPL_TIME_GRANULARITY   0x3F /* 6 bit time granularity */
4145
4146 double get_tdp_intel(unsigned int model)
4147 {
4148         unsigned long long msr;
4149
4150         if (do_rapl & RAPL_PKG_POWER_INFO)
4151                 if (!get_msr(base_cpu, MSR_PKG_POWER_INFO, &msr))
4152                         return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
4153
4154         switch (model) {
4155         case INTEL_FAM6_ATOM_SILVERMONT:
4156         case INTEL_FAM6_ATOM_SILVERMONT_D:
4157                 return 30.0;
4158         default:
4159                 return 135.0;
4160         }
4161 }
4162
4163 double get_tdp_amd(unsigned int family)
4164 {
4165         /* This is the max stock TDP of HEDT/Server Fam17h+ chips */
4166         return 280.0;
4167 }
4168
4169 /*
4170  * rapl_dram_energy_units_probe()
4171  * Energy units are either hard-coded, or come from RAPL Energy Unit MSR.
4172  */
4173 static double
4174 rapl_dram_energy_units_probe(int  model, double rapl_energy_units)
4175 {
4176         /* only called for genuine_intel, family 6 */
4177
4178         switch (model) {
4179         case INTEL_FAM6_HASWELL_X:      /* HSX */
4180         case INTEL_FAM6_BROADWELL_X:    /* BDX */
4181         case INTEL_FAM6_XEON_PHI_KNL:   /* KNL */
4182                 return (rapl_dram_energy_units = 15.3 / 1000000);
4183         default:
4184                 return (rapl_energy_units);
4185         }
4186 }
4187
4188 void rapl_probe_intel(unsigned int family, unsigned int model)
4189 {
4190         unsigned long long msr;
4191         unsigned int time_unit;
4192         double tdp;
4193
4194         if (family != 6)
4195                 return;
4196
4197         switch (model) {
4198         case INTEL_FAM6_SANDYBRIDGE:
4199         case INTEL_FAM6_IVYBRIDGE:
4200         case INTEL_FAM6_HASWELL:        /* HSW */
4201         case INTEL_FAM6_HASWELL_L:      /* HSW */
4202         case INTEL_FAM6_HASWELL_G:      /* HSW */
4203         case INTEL_FAM6_BROADWELL:      /* BDW */
4204         case INTEL_FAM6_BROADWELL_G:    /* BDW */
4205                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
4206                 if (rapl_joules) {
4207                         BIC_PRESENT(BIC_Pkg_J);
4208                         BIC_PRESENT(BIC_Cor_J);
4209                         BIC_PRESENT(BIC_GFX_J);
4210                 } else {
4211                         BIC_PRESENT(BIC_PkgWatt);
4212                         BIC_PRESENT(BIC_CorWatt);
4213                         BIC_PRESENT(BIC_GFXWatt);
4214                 }
4215                 break;
4216         case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
4217         case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
4218                 do_rapl = RAPL_PKG | RAPL_PKG_POWER_INFO;
4219                 if (rapl_joules)
4220                         BIC_PRESENT(BIC_Pkg_J);
4221                 else
4222                         BIC_PRESENT(BIC_PkgWatt);
4223                 break;
4224         case INTEL_FAM6_ATOM_TREMONT:   /* EHL */
4225                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_GFX | RAPL_PKG_POWER_INFO;
4226                 if (rapl_joules) {
4227                         BIC_PRESENT(BIC_Pkg_J);
4228                         BIC_PRESENT(BIC_Cor_J);
4229                         BIC_PRESENT(BIC_RAM_J);
4230                         BIC_PRESENT(BIC_GFX_J);
4231                 } else {
4232                         BIC_PRESENT(BIC_PkgWatt);
4233                         BIC_PRESENT(BIC_CorWatt);
4234                         BIC_PRESENT(BIC_RAMWatt);
4235                         BIC_PRESENT(BIC_GFXWatt);
4236                 }
4237                 break;
4238         case INTEL_FAM6_ATOM_TREMONT_D: /* JVL */
4239                 do_rapl = RAPL_PKG | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
4240                 BIC_PRESENT(BIC_PKG__);
4241                 if (rapl_joules)
4242                         BIC_PRESENT(BIC_Pkg_J);
4243                 else
4244                         BIC_PRESENT(BIC_PkgWatt);
4245                 break;
4246         case INTEL_FAM6_SKYLAKE_L:      /* SKL */
4247         case INTEL_FAM6_CANNONLAKE_L:   /* CNL */
4248                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_GFX | RAPL_PKG_POWER_INFO;
4249                 BIC_PRESENT(BIC_PKG__);
4250                 BIC_PRESENT(BIC_RAM__);
4251                 if (rapl_joules) {
4252                         BIC_PRESENT(BIC_Pkg_J);
4253                         BIC_PRESENT(BIC_Cor_J);
4254                         BIC_PRESENT(BIC_RAM_J);
4255                         BIC_PRESENT(BIC_GFX_J);
4256                 } else {
4257                         BIC_PRESENT(BIC_PkgWatt);
4258                         BIC_PRESENT(BIC_CorWatt);
4259                         BIC_PRESENT(BIC_RAMWatt);
4260                         BIC_PRESENT(BIC_GFXWatt);
4261                 }
4262                 break;
4263         case INTEL_FAM6_HASWELL_X:      /* HSX */
4264         case INTEL_FAM6_BROADWELL_X:    /* BDX */
4265         case INTEL_FAM6_SKYLAKE_X:      /* SKX */
4266         case INTEL_FAM6_XEON_PHI_KNL:   /* KNL */
4267                 do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
4268                 BIC_PRESENT(BIC_PKG__);
4269                 BIC_PRESENT(BIC_RAM__);
4270                 if (rapl_joules) {
4271                         BIC_PRESENT(BIC_Pkg_J);
4272                         BIC_PRESENT(BIC_RAM_J);
4273                 } else {
4274                         BIC_PRESENT(BIC_PkgWatt);
4275                         BIC_PRESENT(BIC_RAMWatt);
4276                 }
4277                 break;
4278         case INTEL_FAM6_SANDYBRIDGE_X:
4279         case INTEL_FAM6_IVYBRIDGE_X:
4280                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_PKG_PERF_STATUS | RAPL_DRAM_PERF_STATUS | RAPL_PKG_POWER_INFO;
4281                 BIC_PRESENT(BIC_PKG__);
4282                 BIC_PRESENT(BIC_RAM__);
4283                 if (rapl_joules) {
4284                         BIC_PRESENT(BIC_Pkg_J);
4285                         BIC_PRESENT(BIC_Cor_J);
4286                         BIC_PRESENT(BIC_RAM_J);
4287                 } else {
4288                         BIC_PRESENT(BIC_PkgWatt);
4289                         BIC_PRESENT(BIC_CorWatt);
4290                         BIC_PRESENT(BIC_RAMWatt);
4291                 }
4292                 break;
4293         case INTEL_FAM6_ATOM_SILVERMONT:        /* BYT */
4294         case INTEL_FAM6_ATOM_SILVERMONT_D:      /* AVN */
4295                 do_rapl = RAPL_PKG | RAPL_CORES;
4296                 if (rapl_joules) {
4297                         BIC_PRESENT(BIC_Pkg_J);
4298                         BIC_PRESENT(BIC_Cor_J);
4299                 } else {
4300                         BIC_PRESENT(BIC_PkgWatt);
4301                         BIC_PRESENT(BIC_CorWatt);
4302                 }
4303                 break;
4304         case INTEL_FAM6_ATOM_GOLDMONT_D:        /* DNV */
4305                 do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO | RAPL_CORES_ENERGY_STATUS;
4306                 BIC_PRESENT(BIC_PKG__);
4307                 BIC_PRESENT(BIC_RAM__);
4308                 if (rapl_joules) {
4309                         BIC_PRESENT(BIC_Pkg_J);
4310                         BIC_PRESENT(BIC_Cor_J);
4311                         BIC_PRESENT(BIC_RAM_J);
4312                 } else {
4313                         BIC_PRESENT(BIC_PkgWatt);
4314                         BIC_PRESENT(BIC_CorWatt);
4315                         BIC_PRESENT(BIC_RAMWatt);
4316                 }
4317                 break;
4318         default:
4319                 return;
4320         }
4321
4322         /* units on package 0, verify later other packages match */
4323         if (get_msr(base_cpu, MSR_RAPL_POWER_UNIT, &msr))
4324                 return;
4325
4326         rapl_power_units = 1.0 / (1 << (msr & 0xF));
4327         if (model == INTEL_FAM6_ATOM_SILVERMONT)
4328                 rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
4329         else
4330                 rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
4331
4332         rapl_dram_energy_units = rapl_dram_energy_units_probe(model, rapl_energy_units);
4333
4334         time_unit = msr >> 16 & 0xF;
4335         if (time_unit == 0)
4336                 time_unit = 0xA;
4337
4338         rapl_time_units = 1.0 / (1 << (time_unit));
4339
4340         tdp = get_tdp_intel(model);
4341
4342         rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
4343         if (!quiet)
4344                 fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
4345 }
4346
4347 void rapl_probe_amd(unsigned int family, unsigned int model)
4348 {
4349         unsigned long long msr;
4350         unsigned int eax, ebx, ecx, edx;
4351         unsigned int has_rapl = 0;
4352         double tdp;
4353
4354         if (max_extended_level >= 0x80000007) {
4355                 __cpuid(0x80000007, eax, ebx, ecx, edx);
4356                 /* RAPL (Fam 17h+) */
4357                 has_rapl = edx & (1 << 14);
4358         }
4359
4360         if (!has_rapl || family < 0x17)
4361                 return;
4362
4363         do_rapl = RAPL_AMD_F17H | RAPL_PER_CORE_ENERGY;
4364         if (rapl_joules) {
4365                 BIC_PRESENT(BIC_Pkg_J);
4366                 BIC_PRESENT(BIC_Cor_J);
4367         } else {
4368                 BIC_PRESENT(BIC_PkgWatt);
4369                 BIC_PRESENT(BIC_CorWatt);
4370         }
4371
4372         if (get_msr(base_cpu, MSR_RAPL_PWR_UNIT, &msr))
4373                 return;
4374
4375         rapl_time_units = ldexp(1.0, -(msr >> 16 & 0xf));
4376         rapl_energy_units = ldexp(1.0, -(msr >> 8 & 0x1f));
4377         rapl_power_units = ldexp(1.0, -(msr & 0xf));
4378
4379         tdp = get_tdp_amd(family);
4380
4381         rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
4382         if (!quiet)
4383                 fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
4384 }
4385
4386 /*
4387  * rapl_probe()
4388  *
4389  * sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
4390  */
4391 void rapl_probe(unsigned int family, unsigned int model)
4392 {
4393         if (genuine_intel)
4394                 rapl_probe_intel(family, model);
4395         if (authentic_amd || hygon_genuine)
4396                 rapl_probe_amd(family, model);
4397 }
4398
4399 void perf_limit_reasons_probe(unsigned int family, unsigned int model)
4400 {
4401         if (!genuine_intel)
4402                 return;
4403
4404         if (family != 6)
4405                 return;
4406
4407         switch (model) {
4408         case INTEL_FAM6_HASWELL:        /* HSW */
4409         case INTEL_FAM6_HASWELL_L:      /* HSW */
4410         case INTEL_FAM6_HASWELL_G:      /* HSW */
4411                 do_gfx_perf_limit_reasons = 1;
4412         case INTEL_FAM6_HASWELL_X:      /* HSX */
4413                 do_core_perf_limit_reasons = 1;
4414                 do_ring_perf_limit_reasons = 1;
4415         default:
4416                 return;
4417         }
4418 }
4419
4420 void automatic_cstate_conversion_probe(unsigned int family, unsigned int model)
4421 {
4422         if (is_skx(family, model) || is_bdx(family, model))
4423                 has_automatic_cstate_conversion = 1;
4424 }
4425
4426 int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4427 {
4428         unsigned long long msr;
4429         unsigned int dts, dts2;
4430         int cpu;
4431
4432         if (!(do_dts || do_ptm))
4433                 return 0;
4434
4435         cpu = t->cpu_id;
4436
4437         /* DTS is per-core, no need to print for each thread */
4438         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
4439                 return 0;
4440
4441         if (cpu_migrate(cpu)) {
4442                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
4443                 return -1;
4444         }
4445
4446         if (do_ptm && (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
4447                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
4448                         return 0;
4449
4450                 dts = (msr >> 16) & 0x7F;
4451                 fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n",
4452                         cpu, msr, tcc_activation_temp - dts);
4453
4454                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
4455                         return 0;
4456
4457                 dts = (msr >> 16) & 0x7F;
4458                 dts2 = (msr >> 8) & 0x7F;
4459                 fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
4460                         cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
4461         }
4462
4463
4464         if (do_dts && debug) {
4465                 unsigned int resolution;
4466
4467                 if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
4468                         return 0;
4469
4470                 dts = (msr >> 16) & 0x7F;
4471                 resolution = (msr >> 27) & 0xF;
4472                 fprintf(outf, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
4473                         cpu, msr, tcc_activation_temp - dts, resolution);
4474
4475                 if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
4476                         return 0;
4477
4478                 dts = (msr >> 16) & 0x7F;
4479                 dts2 = (msr >> 8) & 0x7F;
4480                 fprintf(outf, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
4481                         cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
4482         }
4483
4484         return 0;
4485 }
4486
4487 void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
4488 {
4489         fprintf(outf, "cpu%d: %s: %sabled (%f Watts, %f sec, clamp %sabled)\n",
4490                 cpu, label,
4491                 ((msr >> 15) & 1) ? "EN" : "DIS",
4492                 ((msr >> 0) & 0x7FFF) * rapl_power_units,
4493                 (1.0 + (((msr >> 22) & 0x3)/4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
4494                 (((msr >> 16) & 1) ? "EN" : "DIS"));
4495
4496         return;
4497 }
4498
4499 int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4500 {
4501         unsigned long long msr;
4502         const char *msr_name;
4503         int cpu;
4504
4505         if (!do_rapl)
4506                 return 0;
4507
4508         /* RAPL counters are per package, so print only for 1st thread/package */
4509         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
4510                 return 0;
4511
4512         cpu = t->cpu_id;
4513         if (cpu_migrate(cpu)) {
4514                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
4515                 return -1;
4516         }
4517
4518         if (do_rapl & RAPL_AMD_F17H) {
4519                 msr_name = "MSR_RAPL_PWR_UNIT";
4520                 if (get_msr(cpu, MSR_RAPL_PWR_UNIT, &msr))
4521                         return -1;
4522         } else {
4523                 msr_name = "MSR_RAPL_POWER_UNIT";
4524                 if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
4525                         return -1;
4526         }
4527
4528         fprintf(outf, "cpu%d: %s: 0x%08llx (%f Watts, %f Joules, %f sec.)\n", cpu, msr_name, msr,
4529                 rapl_power_units, rapl_energy_units, rapl_time_units);
4530
4531         if (do_rapl & RAPL_PKG_POWER_INFO) {
4532
4533                 if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
4534                         return -5;
4535
4536
4537                 fprintf(outf, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
4538                         cpu, msr,
4539                         ((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4540                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4541                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4542                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
4543
4544         }
4545         if (do_rapl & RAPL_PKG) {
4546
4547                 if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
4548                         return -9;
4549
4550                 fprintf(outf, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
4551                         cpu, msr, (msr >> 63) & 1 ? "" : "UN");
4552
4553                 print_power_limit_msr(cpu, msr, "PKG Limit #1");
4554                 fprintf(outf, "cpu%d: PKG Limit #2: %sabled (%f Watts, %f* sec, clamp %sabled)\n",
4555                         cpu,
4556                         ((msr >> 47) & 1) ? "EN" : "DIS",
4557                         ((msr >> 32) & 0x7FFF) * rapl_power_units,
4558                         (1.0 + (((msr >> 54) & 0x3)/4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
4559                         ((msr >> 48) & 1) ? "EN" : "DIS");
4560         }
4561
4562         if (do_rapl & RAPL_DRAM_POWER_INFO) {
4563                 if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
4564                         return -6;
4565
4566                 fprintf(outf, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
4567                         cpu, msr,
4568                         ((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4569                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4570                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4571                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
4572         }
4573         if (do_rapl & RAPL_DRAM) {
4574                 if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
4575                         return -9;
4576                 fprintf(outf, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
4577                                 cpu, msr, (msr >> 31) & 1 ? "" : "UN");
4578
4579                 print_power_limit_msr(cpu, msr, "DRAM Limit");
4580         }
4581         if (do_rapl & RAPL_CORE_POLICY) {
4582                 if (get_msr(cpu, MSR_PP0_POLICY, &msr))
4583                         return -7;
4584
4585                 fprintf(outf, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
4586         }
4587         if (do_rapl & RAPL_CORES_POWER_LIMIT) {
4588                 if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
4589                         return -9;
4590                 fprintf(outf, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
4591                                 cpu, msr, (msr >> 31) & 1 ? "" : "UN");
4592                 print_power_limit_msr(cpu, msr, "Cores Limit");
4593         }
4594         if (do_rapl & RAPL_GFX) {
4595                 if (get_msr(cpu, MSR_PP1_POLICY, &msr))
4596                         return -8;
4597
4598                 fprintf(outf, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
4599
4600                 if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
4601                         return -9;
4602                 fprintf(outf, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
4603                                 cpu, msr, (msr >> 31) & 1 ? "" : "UN");
4604                 print_power_limit_msr(cpu, msr, "GFX Limit");
4605         }
4606         return 0;
4607 }
4608
4609 /*
4610  * SNB adds support for additional MSRs:
4611  *
4612  * MSR_PKG_C7_RESIDENCY            0x000003fa
4613  * MSR_CORE_C7_RESIDENCY           0x000003fe
4614  * MSR_PKG_C2_RESIDENCY            0x0000060d
4615  */
4616
4617 int has_snb_msrs(unsigned int family, unsigned int model)
4618 {
4619         if (!genuine_intel)
4620                 return 0;
4621
4622         switch (model) {
4623         case INTEL_FAM6_SANDYBRIDGE:
4624         case INTEL_FAM6_SANDYBRIDGE_X:
4625         case INTEL_FAM6_IVYBRIDGE:              /* IVB */
4626         case INTEL_FAM6_IVYBRIDGE_X:            /* IVB Xeon */
4627         case INTEL_FAM6_HASWELL:                /* HSW */
4628         case INTEL_FAM6_HASWELL_X:              /* HSW */
4629         case INTEL_FAM6_HASWELL_L:              /* HSW */
4630         case INTEL_FAM6_HASWELL_G:              /* HSW */
4631         case INTEL_FAM6_BROADWELL:              /* BDW */
4632         case INTEL_FAM6_BROADWELL_G:            /* BDW */
4633         case INTEL_FAM6_BROADWELL_X:            /* BDX */
4634         case INTEL_FAM6_SKYLAKE_L:              /* SKL */
4635         case INTEL_FAM6_CANNONLAKE_L:           /* CNL */
4636         case INTEL_FAM6_SKYLAKE_X:              /* SKX */
4637         case INTEL_FAM6_ATOM_GOLDMONT:          /* BXT */
4638         case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
4639         case INTEL_FAM6_ATOM_GOLDMONT_D:        /* DNV */
4640         case INTEL_FAM6_ATOM_TREMONT:           /* EHL */
4641         case INTEL_FAM6_ATOM_TREMONT_D:         /* JVL */
4642                 return 1;
4643         }
4644         return 0;
4645 }
4646
4647 /*
4648  * HSW ULT added support for C8/C9/C10 MSRs:
4649  *
4650  * MSR_PKG_C8_RESIDENCY         0x00000630
4651  * MSR_PKG_C9_RESIDENCY         0x00000631
4652  * MSR_PKG_C10_RESIDENCY        0x00000632
4653  *
4654  * MSR_PKGC8_IRTL               0x00000633
4655  * MSR_PKGC9_IRTL               0x00000634
4656  * MSR_PKGC10_IRTL              0x00000635
4657  *
4658  */
4659 int has_c8910_msrs(unsigned int family, unsigned int model)
4660 {
4661         if (!genuine_intel)
4662                 return 0;
4663
4664         switch (model) {
4665         case INTEL_FAM6_HASWELL_L:      /* HSW */
4666         case INTEL_FAM6_BROADWELL:      /* BDW */
4667         case INTEL_FAM6_SKYLAKE_L:      /* SKL */
4668         case INTEL_FAM6_CANNONLAKE_L:   /* CNL */
4669         case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
4670         case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
4671         case INTEL_FAM6_ATOM_TREMONT:   /* EHL */
4672                 return 1;
4673         }
4674         return 0;
4675 }
4676
4677 /*
4678  * SKL adds support for additional MSRS:
4679  *
4680  * MSR_PKG_WEIGHTED_CORE_C0_RES    0x00000658
4681  * MSR_PKG_ANY_CORE_C0_RES         0x00000659
4682  * MSR_PKG_ANY_GFXE_C0_RES         0x0000065A
4683  * MSR_PKG_BOTH_CORE_GFXE_C0_RES   0x0000065B
4684  */
4685 int has_skl_msrs(unsigned int family, unsigned int model)
4686 {
4687         if (!genuine_intel)
4688                 return 0;
4689
4690         switch (model) {
4691         case INTEL_FAM6_SKYLAKE_L:      /* SKL */
4692         case INTEL_FAM6_CANNONLAKE_L:   /* CNL */
4693                 return 1;
4694         }
4695         return 0;
4696 }
4697
4698 int is_slm(unsigned int family, unsigned int model)
4699 {
4700         if (!genuine_intel)
4701                 return 0;
4702         switch (model) {
4703         case INTEL_FAM6_ATOM_SILVERMONT:        /* BYT */
4704         case INTEL_FAM6_ATOM_SILVERMONT_D:      /* AVN */
4705                 return 1;
4706         }
4707         return 0;
4708 }
4709
4710 int is_knl(unsigned int family, unsigned int model)
4711 {
4712         if (!genuine_intel)
4713                 return 0;
4714         switch (model) {
4715         case INTEL_FAM6_XEON_PHI_KNL:   /* KNL */
4716                 return 1;
4717         }
4718         return 0;
4719 }
4720
4721 int is_cnl(unsigned int family, unsigned int model)
4722 {
4723         if (!genuine_intel)
4724                 return 0;
4725
4726         switch (model) {
4727         case INTEL_FAM6_CANNONLAKE_L: /* CNL */
4728                 return 1;
4729         }
4730
4731         return 0;
4732 }
4733
4734 unsigned int get_aperf_mperf_multiplier(unsigned int family, unsigned int model)
4735 {
4736         if (is_knl(family, model))
4737                 return 1024;
4738         return 1;
4739 }
4740
4741 #define SLM_BCLK_FREQS 5
4742 double slm_freq_table[SLM_BCLK_FREQS] = { 83.3, 100.0, 133.3, 116.7, 80.0};
4743
4744 double slm_bclk(void)
4745 {
4746         unsigned long long msr = 3;
4747         unsigned int i;
4748         double freq;
4749
4750         if (get_msr(base_cpu, MSR_FSB_FREQ, &msr))
4751                 fprintf(outf, "SLM BCLK: unknown\n");
4752
4753         i = msr & 0xf;
4754         if (i >= SLM_BCLK_FREQS) {
4755                 fprintf(outf, "SLM BCLK[%d] invalid\n", i);
4756                 i = 3;
4757         }
4758         freq = slm_freq_table[i];
4759
4760         if (!quiet)
4761                 fprintf(outf, "SLM BCLK: %.1f Mhz\n", freq);
4762
4763         return freq;
4764 }
4765
4766 double discover_bclk(unsigned int family, unsigned int model)
4767 {
4768         if (has_snb_msrs(family, model) || is_knl(family, model))
4769                 return 100.00;
4770         else if (is_slm(family, model))
4771                 return slm_bclk();
4772         else
4773                 return 133.33;
4774 }
4775
4776 /*
4777  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
4778  * the Thermal Control Circuit (TCC) activates.
4779  * This is usually equal to tjMax.
4780  *
4781  * Older processors do not have this MSR, so there we guess,
4782  * but also allow cmdline over-ride with -T.
4783  *
4784  * Several MSR temperature values are in units of degrees-C
4785  * below this value, including the Digital Thermal Sensor (DTS),
4786  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
4787  */
4788 int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4789 {
4790         unsigned long long msr;
4791         unsigned int target_c_local;
4792         int cpu;
4793
4794         /* tcc_activation_temp is used only for dts or ptm */
4795         if (!(do_dts || do_ptm))
4796                 return 0;
4797
4798         /* this is a per-package concept */
4799         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
4800                 return 0;
4801
4802         cpu = t->cpu_id;
4803         if (cpu_migrate(cpu)) {
4804                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
4805                 return -1;
4806         }
4807
4808         if (tcc_activation_temp_override != 0) {
4809                 tcc_activation_temp = tcc_activation_temp_override;
4810                 fprintf(outf, "cpu%d: Using cmdline TCC Target (%d C)\n",
4811                         cpu, tcc_activation_temp);
4812                 return 0;
4813         }
4814
4815         /* Temperature Target MSR is Nehalem and newer only */
4816         if (!do_nhm_platform_info)
4817                 goto guess;
4818
4819         if (get_msr(base_cpu, MSR_IA32_TEMPERATURE_TARGET, &msr))
4820                 goto guess;
4821
4822         target_c_local = (msr >> 16) & 0xFF;
4823
4824         if (!quiet)
4825                 fprintf(outf, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n",
4826                         cpu, msr, target_c_local);
4827
4828         if (!target_c_local)
4829                 goto guess;
4830
4831         tcc_activation_temp = target_c_local;
4832
4833         return 0;
4834
4835 guess:
4836         tcc_activation_temp = TJMAX_DEFAULT;
4837         fprintf(outf, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n",
4838                 cpu, tcc_activation_temp);
4839
4840         return 0;
4841 }
4842
4843 void decode_feature_control_msr(void)
4844 {
4845         unsigned long long msr;
4846
4847         if (!get_msr(base_cpu, MSR_IA32_FEAT_CTL, &msr))
4848                 fprintf(outf, "cpu%d: MSR_IA32_FEATURE_CONTROL: 0x%08llx (%sLocked %s)\n",
4849                         base_cpu, msr,
4850                         msr & FEAT_CTL_LOCKED ? "" : "UN-",
4851                         msr & (1 << 18) ? "SGX" : "");
4852 }
4853
4854 void decode_misc_enable_msr(void)
4855 {
4856         unsigned long long msr;
4857
4858         if (!genuine_intel)
4859                 return;
4860
4861         if (!get_msr(base_cpu, MSR_IA32_MISC_ENABLE, &msr))
4862                 fprintf(outf, "cpu%d: MSR_IA32_MISC_ENABLE: 0x%08llx (%sTCC %sEIST %sMWAIT %sPREFETCH %sTURBO)\n",
4863                         base_cpu, msr,
4864                         msr & MSR_IA32_MISC_ENABLE_TM1 ? "" : "No-",
4865                         msr & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP ? "" : "No-",
4866                         msr & MSR_IA32_MISC_ENABLE_MWAIT ? "" : "No-",
4867                         msr & MSR_IA32_MISC_ENABLE_PREFETCH_DISABLE ? "No-" : "",
4868                         msr & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ? "No-" : "");
4869 }
4870
4871 void decode_misc_feature_control(void)
4872 {
4873         unsigned long long msr;
4874
4875         if (!has_misc_feature_control)
4876                 return;
4877
4878         if (!get_msr(base_cpu, MSR_MISC_FEATURE_CONTROL, &msr))
4879                 fprintf(outf, "cpu%d: MSR_MISC_FEATURE_CONTROL: 0x%08llx (%sL2-Prefetch %sL2-Prefetch-pair %sL1-Prefetch %sL1-IP-Prefetch)\n",
4880                         base_cpu, msr,
4881                         msr & (0 << 0) ? "No-" : "",
4882                         msr & (1 << 0) ? "No-" : "",
4883                         msr & (2 << 0) ? "No-" : "",
4884                         msr & (3 << 0) ? "No-" : "");
4885 }
4886 /*
4887  * Decode MSR_MISC_PWR_MGMT
4888  *
4889  * Decode the bits according to the Nehalem documentation
4890  * bit[0] seems to continue to have same meaning going forward
4891  * bit[1] less so...
4892  */
4893 void decode_misc_pwr_mgmt_msr(void)
4894 {
4895         unsigned long long msr;
4896
4897         if (!do_nhm_platform_info)
4898                 return;
4899
4900         if (no_MSR_MISC_PWR_MGMT)
4901                 return;
4902
4903         if (!get_msr(base_cpu, MSR_MISC_PWR_MGMT, &msr))
4904                 fprintf(outf, "cpu%d: MSR_MISC_PWR_MGMT: 0x%08llx (%sable-EIST_Coordination %sable-EPB %sable-OOB)\n",
4905                         base_cpu, msr,
4906                         msr & (1 << 0) ? "DIS" : "EN",
4907                         msr & (1 << 1) ? "EN" : "DIS",
4908                         msr & (1 << 8) ? "EN" : "DIS");
4909 }
4910 /*
4911  * Decode MSR_CC6_DEMOTION_POLICY_CONFIG, MSR_MC6_DEMOTION_POLICY_CONFIG
4912  *
4913  * This MSRs are present on Silvermont processors,
4914  * Intel Atom processor E3000 series (Baytrail), and friends.
4915  */
4916 void decode_c6_demotion_policy_msr(void)
4917 {
4918         unsigned long long msr;
4919
4920         if (!get_msr(base_cpu, MSR_CC6_DEMOTION_POLICY_CONFIG, &msr))
4921                 fprintf(outf, "cpu%d: MSR_CC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-CC6-Demotion)\n",
4922                         base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
4923
4924         if (!get_msr(base_cpu, MSR_MC6_DEMOTION_POLICY_CONFIG, &msr))
4925                 fprintf(outf, "cpu%d: MSR_MC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-MC6-Demotion)\n",
4926                         base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
4927 }
4928
4929 /*
4930  * When models are the same, for the purpose of turbostat, reuse
4931  */
4932 unsigned int intel_model_duplicates(unsigned int model)
4933 {
4934
4935         switch(model) {
4936         case INTEL_FAM6_NEHALEM_EP:     /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
4937         case INTEL_FAM6_NEHALEM:        /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
4938         case 0x1F:      /* Core i7 and i5 Processor - Nehalem */
4939         case INTEL_FAM6_WESTMERE:       /* Westmere Client - Clarkdale, Arrandale */
4940         case INTEL_FAM6_WESTMERE_EP:    /* Westmere EP - Gulftown */
4941                 return INTEL_FAM6_NEHALEM;
4942
4943         case INTEL_FAM6_NEHALEM_EX:     /* Nehalem-EX Xeon - Beckton */
4944         case INTEL_FAM6_WESTMERE_EX:    /* Westmere-EX Xeon - Eagleton */
4945                 return INTEL_FAM6_NEHALEM_EX;
4946
4947         case INTEL_FAM6_XEON_PHI_KNM:
4948                 return INTEL_FAM6_XEON_PHI_KNL;
4949
4950         case INTEL_FAM6_BROADWELL_X:
4951         case INTEL_FAM6_BROADWELL_D:    /* BDX-DE */
4952                 return INTEL_FAM6_BROADWELL_X;
4953
4954         case INTEL_FAM6_SKYLAKE_L:
4955         case INTEL_FAM6_SKYLAKE:
4956         case INTEL_FAM6_KABYLAKE_L:
4957         case INTEL_FAM6_KABYLAKE:
4958         case INTEL_FAM6_COMETLAKE_L:
4959         case INTEL_FAM6_COMETLAKE:
4960                 return INTEL_FAM6_SKYLAKE_L;
4961
4962         case INTEL_FAM6_ICELAKE_L:
4963         case INTEL_FAM6_ICELAKE_NNPI:
4964         case INTEL_FAM6_TIGERLAKE_L:
4965         case INTEL_FAM6_TIGERLAKE:
4966         case INTEL_FAM6_ROCKETLAKE:
4967         case INTEL_FAM6_LAKEFIELD:
4968         case INTEL_FAM6_ALDERLAKE:
4969                 return INTEL_FAM6_CANNONLAKE_L;
4970
4971         case INTEL_FAM6_ATOM_TREMONT_L:
4972                 return INTEL_FAM6_ATOM_TREMONT;
4973
4974         case INTEL_FAM6_ICELAKE_X:
4975         case INTEL_FAM6_SAPPHIRERAPIDS_X:
4976                 return INTEL_FAM6_SKYLAKE_X;
4977         }
4978         return model;
4979 }
4980
4981 void print_dev_latency(void)
4982 {
4983         char *path = "/dev/cpu_dma_latency";
4984         int fd;
4985         int value;
4986         int retval;
4987
4988         fd = open(path, O_RDONLY);
4989         if (fd < 0) {
4990                 warn("fopen %s\n", path);
4991                 return;
4992         }
4993
4994         retval = read(fd, (void *)&value, sizeof(int));
4995         if (retval != sizeof(int)) {
4996                 warn("read %s\n", path);
4997                 close(fd);
4998                 return;
4999         }
5000         fprintf(outf, "/dev/cpu_dma_latency: %d usec (%s)\n",
5001                 value, value == 2000000000 ? "default" : "constrained");
5002
5003         close(fd);
5004 }
5005
5006 void process_cpuid()
5007 {
5008         unsigned int eax, ebx, ecx, edx;
5009         unsigned int fms, family, model, stepping, ecx_flags, edx_flags;
5010         unsigned int has_turbo;
5011
5012         eax = ebx = ecx = edx = 0;
5013
5014         __cpuid(0, max_level, ebx, ecx, edx);
5015
5016         if (ebx == 0x756e6547 && ecx == 0x6c65746e && edx == 0x49656e69)
5017                 genuine_intel = 1;
5018         else if (ebx == 0x68747541 && ecx == 0x444d4163 && edx == 0x69746e65)
5019                 authentic_amd = 1;
5020         else if (ebx == 0x6f677948 && ecx == 0x656e6975 && edx == 0x6e65476e)
5021                 hygon_genuine = 1;
5022
5023         if (!quiet)
5024                 fprintf(outf, "CPUID(0): %.4s%.4s%.4s ",
5025                         (char *)&ebx, (char *)&edx, (char *)&ecx);
5026
5027         __cpuid(1, fms, ebx, ecx, edx);
5028         family = (fms >> 8) & 0xf;
5029         model = (fms >> 4) & 0xf;
5030         stepping = fms & 0xf;
5031         if (family == 0xf)
5032                 family += (fms >> 20) & 0xff;
5033         if (family >= 6)
5034                 model += ((fms >> 16) & 0xf) << 4;
5035         ecx_flags = ecx;
5036         edx_flags = edx;
5037
5038         /*
5039          * check max extended function levels of CPUID.
5040          * This is needed to check for invariant TSC.
5041          * This check is valid for both Intel and AMD.
5042          */
5043         ebx = ecx = edx = 0;
5044         __cpuid(0x80000000, max_extended_level, ebx, ecx, edx);
5045
5046         if (!quiet) {
5047                 fprintf(outf, "0x%x CPUID levels; 0x%x xlevels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
5048                         max_level, max_extended_level, family, model, stepping, family, model, stepping);
5049                 fprintf(outf, "CPUID(1): %s %s %s %s %s %s %s %s %s %s\n",
5050                         ecx_flags & (1 << 0) ? "SSE3" : "-",
5051                         ecx_flags & (1 << 3) ? "MONITOR" : "-",
5052                         ecx_flags & (1 << 6) ? "SMX" : "-",
5053                         ecx_flags & (1 << 7) ? "EIST" : "-",
5054                         ecx_flags & (1 << 8) ? "TM2" : "-",
5055                         edx_flags & (1 << 4) ? "TSC" : "-",
5056                         edx_flags & (1 << 5) ? "MSR" : "-",
5057                         edx_flags & (1 << 22) ? "ACPI-TM" : "-",
5058                         edx_flags & (1 << 28) ? "HT" : "-",
5059                         edx_flags & (1 << 29) ? "TM" : "-");
5060         }
5061         if (genuine_intel)
5062                 model = intel_model_duplicates(model);
5063
5064         if (!(edx_flags & (1 << 5)))
5065                 errx(1, "CPUID: no MSR");
5066
5067         if (max_extended_level >= 0x80000007) {
5068
5069                 /*
5070                  * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
5071                  * this check is valid for both Intel and AMD
5072                  */
5073                 __cpuid(0x80000007, eax, ebx, ecx, edx);
5074                 has_invariant_tsc = edx & (1 << 8);
5075         }
5076
5077         /*
5078          * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
5079          * this check is valid for both Intel and AMD
5080          */
5081
5082         __cpuid(0x6, eax, ebx, ecx, edx);
5083         has_aperf = ecx & (1 << 0);
5084         if (has_aperf) {
5085                 BIC_PRESENT(BIC_Avg_MHz);
5086                 BIC_PRESENT(BIC_Busy);
5087                 BIC_PRESENT(BIC_Bzy_MHz);
5088         }
5089         do_dts = eax & (1 << 0);
5090         if (do_dts)
5091                 BIC_PRESENT(BIC_CoreTmp);
5092         has_turbo = eax & (1 << 1);
5093         do_ptm = eax & (1 << 6);
5094         if (do_ptm)
5095                 BIC_PRESENT(BIC_PkgTmp);
5096         has_hwp = eax & (1 << 7);
5097         has_hwp_notify = eax & (1 << 8);
5098         has_hwp_activity_window = eax & (1 << 9);
5099         has_hwp_epp = eax & (1 << 10);
5100         has_hwp_pkg = eax & (1 << 11);
5101         has_epb = ecx & (1 << 3);
5102
5103         if (!quiet)
5104                 fprintf(outf, "CPUID(6): %sAPERF, %sTURBO, %sDTS, %sPTM, %sHWP, "
5105                         "%sHWPnotify, %sHWPwindow, %sHWPepp, %sHWPpkg, %sEPB\n",
5106                         has_aperf ? "" : "No-",
5107                         has_turbo ? "" : "No-",
5108                         do_dts ? "" : "No-",
5109                         do_ptm ? "" : "No-",
5110                         has_hwp ? "" : "No-",
5111                         has_hwp_notify ? "" : "No-",
5112                         has_hwp_activity_window ? "" : "No-",
5113                         has_hwp_epp ? "" : "No-",
5114                         has_hwp_pkg ? "" : "No-",
5115                         has_epb ? "" : "No-");
5116
5117         if (!quiet)
5118                 decode_misc_enable_msr();
5119
5120
5121         if (max_level >= 0x7 && !quiet) {
5122                 int has_sgx;
5123
5124                 ecx = 0;
5125
5126                 __cpuid_count(0x7, 0, eax, ebx, ecx, edx);
5127
5128                 has_sgx = ebx & (1 << 2);
5129                 fprintf(outf, "CPUID(7): %sSGX\n", has_sgx ? "" : "No-");
5130
5131                 if (has_sgx)
5132                         decode_feature_control_msr();
5133         }
5134
5135         if (max_level >= 0x15) {
5136                 unsigned int eax_crystal;
5137                 unsigned int ebx_tsc;
5138
5139                 /*
5140                  * CPUID 15H TSC/Crystal ratio, possibly Crystal Hz
5141                  */
5142                 eax_crystal = ebx_tsc = crystal_hz = edx = 0;
5143                 __cpuid(0x15, eax_crystal, ebx_tsc, crystal_hz, edx);
5144
5145                 if (ebx_tsc != 0) {
5146
5147                         if (!quiet && (ebx != 0))
5148                                 fprintf(outf, "CPUID(0x15): eax_crystal: %d ebx_tsc: %d ecx_crystal_hz: %d\n",
5149                                         eax_crystal, ebx_tsc, crystal_hz);
5150
5151                         if (crystal_hz == 0)
5152                                 switch(model) {
5153                                 case INTEL_FAM6_SKYLAKE_L:      /* SKL */
5154                                         crystal_hz = 24000000;  /* 24.0 MHz */
5155                                         break;
5156                                 case INTEL_FAM6_ATOM_GOLDMONT_D:        /* DNV */
5157                                         crystal_hz = 25000000;  /* 25.0 MHz */
5158                                         break;
5159                                 case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
5160                                 case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
5161                                         crystal_hz = 19200000;  /* 19.2 MHz */
5162                                         break;
5163                                 default:
5164                                         crystal_hz = 0;
5165                         }
5166
5167                         if (crystal_hz) {
5168                                 tsc_hz =  (unsigned long long) crystal_hz * ebx_tsc / eax_crystal;
5169                                 if (!quiet)
5170                                         fprintf(outf, "TSC: %lld MHz (%d Hz * %d / %d / 1000000)\n",
5171                                                 tsc_hz / 1000000, crystal_hz, ebx_tsc,  eax_crystal);
5172                         }
5173                 }
5174         }
5175         if (max_level >= 0x16) {
5176                 unsigned int base_mhz, max_mhz, bus_mhz, edx;
5177
5178                 /*
5179                  * CPUID 16H Base MHz, Max MHz, Bus MHz
5180                  */
5181                 base_mhz = max_mhz = bus_mhz = edx = 0;
5182
5183                 __cpuid(0x16, base_mhz, max_mhz, bus_mhz, edx);
5184                 if (!quiet)
5185                         fprintf(outf, "CPUID(0x16): base_mhz: %d max_mhz: %d bus_mhz: %d\n",
5186                                 base_mhz, max_mhz, bus_mhz);
5187         }
5188
5189         if (has_aperf)
5190                 aperf_mperf_multiplier = get_aperf_mperf_multiplier(family, model);
5191
5192         BIC_PRESENT(BIC_IRQ);
5193         BIC_PRESENT(BIC_TSC_MHz);
5194
5195         if (probe_nhm_msrs(family, model)) {
5196                 do_nhm_platform_info = 1;
5197                 BIC_PRESENT(BIC_CPU_c1);
5198                 BIC_PRESENT(BIC_CPU_c3);
5199                 BIC_PRESENT(BIC_CPU_c6);
5200                 BIC_PRESENT(BIC_SMI);
5201         }
5202         do_snb_cstates = has_snb_msrs(family, model);
5203
5204         if (do_snb_cstates)
5205                 BIC_PRESENT(BIC_CPU_c7);
5206
5207         do_irtl_snb = has_snb_msrs(family, model);
5208         if (do_snb_cstates && (pkg_cstate_limit >= PCL__2))
5209                 BIC_PRESENT(BIC_Pkgpc2);
5210         if (pkg_cstate_limit >= PCL__3)
5211                 BIC_PRESENT(BIC_Pkgpc3);
5212         if (pkg_cstate_limit >= PCL__6)
5213                 BIC_PRESENT(BIC_Pkgpc6);
5214         if (do_snb_cstates && (pkg_cstate_limit >= PCL__7))
5215                 BIC_PRESENT(BIC_Pkgpc7);
5216         if (has_slv_msrs(family, model)) {
5217                 BIC_NOT_PRESENT(BIC_Pkgpc2);
5218                 BIC_NOT_PRESENT(BIC_Pkgpc3);
5219                 BIC_PRESENT(BIC_Pkgpc6);
5220                 BIC_NOT_PRESENT(BIC_Pkgpc7);
5221                 BIC_PRESENT(BIC_Mod_c6);
5222                 use_c1_residency_msr = 1;
5223         }
5224         if (is_jvl(family, model)) {
5225                 BIC_NOT_PRESENT(BIC_CPU_c3);
5226                 BIC_NOT_PRESENT(BIC_CPU_c7);
5227                 BIC_NOT_PRESENT(BIC_Pkgpc2);
5228                 BIC_NOT_PRESENT(BIC_Pkgpc3);
5229                 BIC_NOT_PRESENT(BIC_Pkgpc6);
5230                 BIC_NOT_PRESENT(BIC_Pkgpc7);
5231         }
5232         if (is_dnv(family, model)) {
5233                 BIC_PRESENT(BIC_CPU_c1);
5234                 BIC_NOT_PRESENT(BIC_CPU_c3);
5235                 BIC_NOT_PRESENT(BIC_Pkgpc3);
5236                 BIC_NOT_PRESENT(BIC_CPU_c7);
5237                 BIC_NOT_PRESENT(BIC_Pkgpc7);
5238                 use_c1_residency_msr = 1;
5239         }
5240         if (is_skx(family, model)) {
5241                 BIC_NOT_PRESENT(BIC_CPU_c3);
5242                 BIC_NOT_PRESENT(BIC_Pkgpc3);
5243                 BIC_NOT_PRESENT(BIC_CPU_c7);
5244                 BIC_NOT_PRESENT(BIC_Pkgpc7);
5245         }
5246         if (is_bdx(family, model)) {
5247                 BIC_NOT_PRESENT(BIC_CPU_c7);
5248                 BIC_NOT_PRESENT(BIC_Pkgpc7);
5249         }
5250         if (has_c8910_msrs(family, model)) {
5251                 if (pkg_cstate_limit >= PCL__8)
5252                         BIC_PRESENT(BIC_Pkgpc8);
5253                 if (pkg_cstate_limit >= PCL__9)
5254                         BIC_PRESENT(BIC_Pkgpc9);
5255                 if (pkg_cstate_limit >= PCL_10)
5256                         BIC_PRESENT(BIC_Pkgpc10);
5257         }
5258         do_irtl_hsw = has_c8910_msrs(family, model);
5259         if (has_skl_msrs(family, model)) {
5260                 BIC_PRESENT(BIC_Totl_c0);
5261                 BIC_PRESENT(BIC_Any_c0);
5262                 BIC_PRESENT(BIC_GFX_c0);
5263                 BIC_PRESENT(BIC_CPUGFX);
5264         }
5265         do_slm_cstates = is_slm(family, model);
5266         do_knl_cstates  = is_knl(family, model);
5267
5268         if (do_slm_cstates || do_knl_cstates || is_cnl(family, model) ||
5269             is_ehl(family, model))
5270                 BIC_NOT_PRESENT(BIC_CPU_c3);
5271
5272         if (!quiet)
5273                 decode_misc_pwr_mgmt_msr();
5274
5275         if (!quiet && has_slv_msrs(family, model))
5276                 decode_c6_demotion_policy_msr();
5277
5278         rapl_probe(family, model);
5279         perf_limit_reasons_probe(family, model);
5280         automatic_cstate_conversion_probe(family, model);
5281
5282         if (!quiet)
5283                 dump_cstate_pstate_config_info(family, model);
5284
5285         if (!quiet)
5286                 print_dev_latency();
5287         if (!quiet)
5288                 dump_sysfs_cstate_config();
5289         if (!quiet)
5290                 dump_sysfs_pstate_config();
5291
5292         if (has_skl_msrs(family, model))
5293                 calculate_tsc_tweak();
5294
5295         if (!access("/sys/class/drm/card0/power/rc6_residency_ms", R_OK))
5296                 BIC_PRESENT(BIC_GFX_rc6);
5297
5298         if (!access("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", R_OK))
5299                 BIC_PRESENT(BIC_GFXMHz);
5300
5301         if (!access("/sys/class/graphics/fb0/device/drm/card0/gt_act_freq_mhz", R_OK))
5302                 BIC_PRESENT(BIC_GFXACTMHz);
5303
5304         if (!access("/sys/devices/system/cpu/cpuidle/low_power_idle_cpu_residency_us", R_OK))
5305                 BIC_PRESENT(BIC_CPU_LPI);
5306         else
5307                 BIC_NOT_PRESENT(BIC_CPU_LPI);
5308
5309         if (!access(sys_lpi_file_sysfs, R_OK)) {
5310                 sys_lpi_file = sys_lpi_file_sysfs;
5311                 BIC_PRESENT(BIC_SYS_LPI);
5312         } else if (!access(sys_lpi_file_debugfs, R_OK)) {
5313                 sys_lpi_file = sys_lpi_file_debugfs;
5314                 BIC_PRESENT(BIC_SYS_LPI);
5315         } else {
5316                 sys_lpi_file_sysfs = NULL;
5317                 BIC_NOT_PRESENT(BIC_SYS_LPI);
5318         }
5319
5320         if (!quiet)
5321                 decode_misc_feature_control();
5322
5323         return;
5324 }
5325
5326 /*
5327  * in /dev/cpu/ return success for names that are numbers
5328  * ie. filter out ".", "..", "microcode".
5329  */
5330 int dir_filter(const struct dirent *dirp)
5331 {
5332         if (isdigit(dirp->d_name[0]))
5333                 return 1;
5334         else
5335                 return 0;
5336 }
5337
5338 int open_dev_cpu_msr(int dummy1)
5339 {
5340         return 0;
5341 }
5342
5343 void topology_probe()
5344 {
5345         int i;
5346         int max_core_id = 0;
5347         int max_package_id = 0;
5348         int max_die_id = 0;
5349         int max_siblings = 0;
5350
5351         /* Initialize num_cpus, max_cpu_num */
5352         set_max_cpu_num();
5353         topo.num_cpus = 0;
5354         for_all_proc_cpus(count_cpus);
5355         if (!summary_only && topo.num_cpus > 1)
5356                 BIC_PRESENT(BIC_CPU);
5357
5358         if (debug > 1)
5359                 fprintf(outf, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
5360
5361         cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
5362         if (cpus == NULL)
5363                 err(1, "calloc cpus");
5364
5365         /*
5366          * Allocate and initialize cpu_present_set
5367          */
5368         cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
5369         if (cpu_present_set == NULL)
5370                 err(3, "CPU_ALLOC");
5371         cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5372         CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
5373         for_all_proc_cpus(mark_cpu_present);
5374
5375         /*
5376          * Validate that all cpus in cpu_subset are also in cpu_present_set
5377          */
5378         for (i = 0; i < CPU_SUBSET_MAXCPUS; ++i) {
5379                 if (CPU_ISSET_S(i, cpu_subset_size, cpu_subset))
5380                         if (!CPU_ISSET_S(i, cpu_present_setsize, cpu_present_set))
5381                                 err(1, "cpu%d not present", i);
5382         }
5383
5384         /*
5385          * Allocate and initialize cpu_affinity_set
5386          */
5387         cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
5388         if (cpu_affinity_set == NULL)
5389                 err(3, "CPU_ALLOC");
5390         cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5391         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
5392
5393         for_all_proc_cpus(init_thread_id);
5394
5395         /*
5396          * For online cpus
5397          * find max_core_id, max_package_id
5398          */
5399         for (i = 0; i <= topo.max_cpu_num; ++i) {
5400                 int siblings;
5401
5402                 if (cpu_is_not_present(i)) {
5403                         if (debug > 1)
5404                                 fprintf(outf, "cpu%d NOT PRESENT\n", i);
5405                         continue;
5406                 }
5407
5408                 cpus[i].logical_cpu_id = i;
5409
5410                 /* get package information */
5411                 cpus[i].physical_package_id = get_physical_package_id(i);
5412                 if (cpus[i].physical_package_id > max_package_id)
5413                         max_package_id = cpus[i].physical_package_id;
5414
5415                 /* get die information */
5416                 cpus[i].die_id = get_die_id(i);
5417                 if (cpus[i].die_id > max_die_id)
5418                         max_die_id = cpus[i].die_id;
5419
5420                 /* get numa node information */
5421                 cpus[i].physical_node_id = get_physical_node_id(&cpus[i]);
5422                 if (cpus[i].physical_node_id > topo.max_node_num)
5423                         topo.max_node_num = cpus[i].physical_node_id;
5424
5425                 /* get core information */
5426                 cpus[i].physical_core_id = get_core_id(i);
5427                 if (cpus[i].physical_core_id > max_core_id)
5428                         max_core_id = cpus[i].physical_core_id;
5429
5430                 /* get thread information */
5431                 siblings = get_thread_siblings(&cpus[i]);
5432                 if (siblings > max_siblings)
5433                         max_siblings = siblings;
5434                 if (cpus[i].thread_id == 0)
5435                         topo.num_cores++;
5436         }
5437
5438         topo.cores_per_node = max_core_id + 1;
5439         if (debug > 1)
5440                 fprintf(outf, "max_core_id %d, sizing for %d cores per package\n",
5441                         max_core_id, topo.cores_per_node);
5442         if (!summary_only && topo.cores_per_node > 1)
5443                 BIC_PRESENT(BIC_Core);
5444
5445         topo.num_die = max_die_id + 1;
5446         if (debug > 1)
5447                 fprintf(outf, "max_die_id %d, sizing for %d die\n",
5448                                 max_die_id, topo.num_die);
5449         if (!summary_only && topo.num_die > 1)
5450                 BIC_PRESENT(BIC_Die);
5451
5452         topo.num_packages = max_package_id + 1;
5453         if (debug > 1)
5454                 fprintf(outf, "max_package_id %d, sizing for %d packages\n",
5455                         max_package_id, topo.num_packages);
5456         if (!summary_only && topo.num_packages > 1)
5457                 BIC_PRESENT(BIC_Package);
5458
5459         set_node_data();
5460         if (debug > 1)
5461                 fprintf(outf, "nodes_per_pkg %d\n", topo.nodes_per_pkg);
5462         if (!summary_only && topo.nodes_per_pkg > 1)
5463                 BIC_PRESENT(BIC_Node);
5464
5465         topo.threads_per_core = max_siblings;
5466         if (debug > 1)
5467                 fprintf(outf, "max_siblings %d\n", max_siblings);
5468
5469         if (debug < 1)
5470                 return;
5471
5472         for (i = 0; i <= topo.max_cpu_num; ++i) {
5473                 if (cpu_is_not_present(i))
5474                         continue;
5475                 fprintf(outf,
5476                         "cpu %d pkg %d die %d node %d lnode %d core %d thread %d\n",
5477                         i, cpus[i].physical_package_id, cpus[i].die_id,
5478                         cpus[i].physical_node_id,
5479                         cpus[i].logical_node_id,
5480                         cpus[i].physical_core_id,
5481                         cpus[i].thread_id);
5482         }
5483
5484 }
5485
5486 void
5487 allocate_counters(struct thread_data **t, struct core_data **c,
5488                   struct pkg_data **p)
5489 {
5490         int i;
5491         int num_cores = topo.cores_per_node * topo.nodes_per_pkg *
5492                         topo.num_packages;
5493         int num_threads = topo.threads_per_core * num_cores;
5494
5495         *t = calloc(num_threads, sizeof(struct thread_data));
5496         if (*t == NULL)
5497                 goto error;
5498
5499         for (i = 0; i < num_threads; i++)
5500                 (*t)[i].cpu_id = -1;
5501
5502         *c = calloc(num_cores, sizeof(struct core_data));
5503         if (*c == NULL)
5504                 goto error;
5505
5506         for (i = 0; i < num_cores; i++)
5507                 (*c)[i].core_id = -1;
5508
5509         *p = calloc(topo.num_packages, sizeof(struct pkg_data));
5510         if (*p == NULL)
5511                 goto error;
5512
5513         for (i = 0; i < topo.num_packages; i++)
5514                 (*p)[i].package_id = i;
5515
5516         return;
5517 error:
5518         err(1, "calloc counters");
5519 }
5520 /*
5521  * init_counter()
5522  *
5523  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
5524  */
5525 void init_counter(struct thread_data *thread_base, struct core_data *core_base,
5526         struct pkg_data *pkg_base, int cpu_id)
5527 {
5528         int pkg_id = cpus[cpu_id].physical_package_id;
5529         int node_id = cpus[cpu_id].logical_node_id;
5530         int core_id = cpus[cpu_id].physical_core_id;
5531         int thread_id = cpus[cpu_id].thread_id;
5532         struct thread_data *t;
5533         struct core_data *c;
5534         struct pkg_data *p;
5535
5536
5537         /* Workaround for systems where physical_node_id==-1
5538          * and logical_node_id==(-1 - topo.num_cpus)
5539          */
5540         if (node_id < 0)
5541                 node_id = 0;
5542
5543         t = GET_THREAD(thread_base, thread_id, core_id, node_id, pkg_id);
5544         c = GET_CORE(core_base, core_id, node_id, pkg_id);
5545         p = GET_PKG(pkg_base, pkg_id);
5546
5547         t->cpu_id = cpu_id;
5548         if (thread_id == 0) {
5549                 t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
5550                 if (cpu_is_first_core_in_package(cpu_id))
5551                         t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
5552         }
5553
5554         c->core_id = core_id;
5555         p->package_id = pkg_id;
5556 }
5557
5558
5559 int initialize_counters(int cpu_id)
5560 {
5561         init_counter(EVEN_COUNTERS, cpu_id);
5562         init_counter(ODD_COUNTERS, cpu_id);
5563         return 0;
5564 }
5565
5566 void allocate_output_buffer()
5567 {
5568         output_buffer = calloc(1, (1 + topo.num_cpus) * 2048);
5569         outp = output_buffer;
5570         if (outp == NULL)
5571                 err(-1, "calloc output buffer");
5572 }
5573 void allocate_fd_percpu(void)
5574 {
5575         fd_percpu = calloc(topo.max_cpu_num + 1, sizeof(int));
5576         if (fd_percpu == NULL)
5577                 err(-1, "calloc fd_percpu");
5578 }
5579 void allocate_irq_buffers(void)
5580 {
5581         irq_column_2_cpu = calloc(topo.num_cpus, sizeof(int));
5582         if (irq_column_2_cpu == NULL)
5583                 err(-1, "calloc %d", topo.num_cpus);
5584
5585         irqs_per_cpu = calloc(topo.max_cpu_num + 1, sizeof(int));
5586         if (irqs_per_cpu == NULL)
5587                 err(-1, "calloc %d", topo.max_cpu_num + 1);
5588 }
5589 void setup_all_buffers(void)
5590 {
5591         topology_probe();
5592         allocate_irq_buffers();
5593         allocate_fd_percpu();
5594         allocate_counters(&thread_even, &core_even, &package_even);
5595         allocate_counters(&thread_odd, &core_odd, &package_odd);
5596         allocate_output_buffer();
5597         for_all_proc_cpus(initialize_counters);
5598 }
5599
5600 void set_base_cpu(void)
5601 {
5602         base_cpu = sched_getcpu();
5603         if (base_cpu < 0)
5604                 err(-ENODEV, "No valid cpus found");
5605
5606         if (debug > 1)
5607                 fprintf(outf, "base_cpu = %d\n", base_cpu);
5608 }
5609
5610 void turbostat_init()
5611 {
5612         setup_all_buffers();
5613         set_base_cpu();
5614         check_dev_msr();
5615         check_permissions();
5616         process_cpuid();
5617
5618
5619         if (!quiet)
5620                 for_all_cpus(print_hwp, ODD_COUNTERS);
5621
5622         if (!quiet)
5623                 for_all_cpus(print_epb, ODD_COUNTERS);
5624
5625         if (!quiet)
5626                 for_all_cpus(print_perf_limit, ODD_COUNTERS);
5627
5628         if (!quiet)
5629                 for_all_cpus(print_rapl, ODD_COUNTERS);
5630
5631         for_all_cpus(set_temperature_target, ODD_COUNTERS);
5632
5633         if (!quiet)
5634                 for_all_cpus(print_thermal, ODD_COUNTERS);
5635
5636         if (!quiet && do_irtl_snb)
5637                 print_irtl();
5638 }
5639
5640 int fork_it(char **argv)
5641 {
5642         pid_t child_pid;
5643         int status;
5644
5645         snapshot_proc_sysfs_files();
5646         status = for_all_cpus(get_counters, EVEN_COUNTERS);
5647         first_counter_read = 0;
5648         if (status)
5649                 exit(status);
5650         /* clear affinity side-effect of get_counters() */
5651         sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
5652         gettimeofday(&tv_even, (struct timezone *)NULL);
5653
5654         child_pid = fork();
5655         if (!child_pid) {
5656                 /* child */
5657                 execvp(argv[0], argv);
5658                 err(errno, "exec %s", argv[0]);
5659         } else {
5660
5661                 /* parent */
5662                 if (child_pid == -1)
5663                         err(1, "fork");
5664
5665                 signal(SIGINT, SIG_IGN);
5666                 signal(SIGQUIT, SIG_IGN);
5667                 if (waitpid(child_pid, &status, 0) == -1)
5668                         err(status, "waitpid");
5669
5670                 if (WIFEXITED(status))
5671                         status = WEXITSTATUS(status);
5672         }
5673         /*
5674          * n.b. fork_it() does not check for errors from for_all_cpus()
5675          * because re-starting is problematic when forking
5676          */
5677         snapshot_proc_sysfs_files();
5678         for_all_cpus(get_counters, ODD_COUNTERS);
5679         gettimeofday(&tv_odd, (struct timezone *)NULL);
5680         timersub(&tv_odd, &tv_even, &tv_delta);
5681         if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS))
5682                 fprintf(outf, "%s: Counter reset detected\n", progname);
5683         else {
5684                 compute_average(EVEN_COUNTERS);
5685                 format_all_counters(EVEN_COUNTERS);
5686         }
5687
5688         fprintf(outf, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
5689
5690         flush_output_stderr();
5691
5692         return status;
5693 }
5694
5695 int get_and_dump_counters(void)
5696 {
5697         int status;
5698
5699         snapshot_proc_sysfs_files();
5700         status = for_all_cpus(get_counters, ODD_COUNTERS);
5701         if (status)
5702                 return status;
5703
5704         status = for_all_cpus(dump_counters, ODD_COUNTERS);
5705         if (status)
5706                 return status;
5707
5708         flush_output_stdout();
5709
5710         return status;
5711 }
5712
5713 void print_version() {
5714         fprintf(outf, "turbostat version 20.03.20"
5715                 " - Len Brown <lenb@kernel.org>\n");
5716 }
5717
5718 int add_counter(unsigned int msr_num, char *path, char *name,
5719         unsigned int width, enum counter_scope scope,
5720         enum counter_type type, enum counter_format format, int flags)
5721 {
5722         struct msr_counter *msrp;
5723
5724         msrp = calloc(1, sizeof(struct msr_counter));
5725         if (msrp == NULL) {
5726                 perror("calloc");
5727                 exit(1);
5728         }
5729
5730         msrp->msr_num = msr_num;
5731         strncpy(msrp->name, name, NAME_BYTES - 1);
5732         if (path)
5733                 strncpy(msrp->path, path, PATH_BYTES - 1);
5734         msrp->width = width;
5735         msrp->type = type;
5736         msrp->format = format;
5737         msrp->flags = flags;
5738
5739         switch (scope) {
5740
5741         case SCOPE_CPU:
5742                 msrp->next = sys.tp;
5743                 sys.tp = msrp;
5744                 sys.added_thread_counters++;
5745                 if (sys.added_thread_counters > MAX_ADDED_THREAD_COUNTERS) {
5746                         fprintf(stderr, "exceeded max %d added thread counters\n",
5747                                 MAX_ADDED_COUNTERS);
5748                         exit(-1);
5749                 }
5750                 break;
5751
5752         case SCOPE_CORE:
5753                 msrp->next = sys.cp;
5754                 sys.cp = msrp;
5755                 sys.added_core_counters++;
5756                 if (sys.added_core_counters > MAX_ADDED_COUNTERS) {
5757                         fprintf(stderr, "exceeded max %d added core counters\n",
5758                                 MAX_ADDED_COUNTERS);
5759                         exit(-1);
5760                 }
5761                 break;
5762
5763         case SCOPE_PACKAGE:
5764                 msrp->next = sys.pp;
5765                 sys.pp = msrp;
5766                 sys.added_package_counters++;
5767                 if (sys.added_package_counters > MAX_ADDED_COUNTERS) {
5768                         fprintf(stderr, "exceeded max %d added package counters\n",
5769                                 MAX_ADDED_COUNTERS);
5770                         exit(-1);
5771                 }
5772                 break;
5773         }
5774
5775         return 0;
5776 }
5777
5778 void parse_add_command(char *add_command)
5779 {
5780         int msr_num = 0;
5781         char *path = NULL;
5782         char name_buffer[NAME_BYTES] = "";
5783         int width = 64;
5784         int fail = 0;
5785         enum counter_scope scope = SCOPE_CPU;
5786         enum counter_type type = COUNTER_CYCLES;
5787         enum counter_format format = FORMAT_DELTA;
5788
5789         while (add_command) {
5790
5791                 if (sscanf(add_command, "msr0x%x", &msr_num) == 1)
5792                         goto next;
5793
5794                 if (sscanf(add_command, "msr%d", &msr_num) == 1)
5795                         goto next;
5796
5797                 if (*add_command == '/') {
5798                         path = add_command;
5799                         goto next;
5800                 }
5801
5802                 if (sscanf(add_command, "u%d", &width) == 1) {
5803                         if ((width == 32) || (width == 64))
5804                                 goto next;
5805                         width = 64;
5806                 }
5807                 if (!strncmp(add_command, "cpu", strlen("cpu"))) {
5808                         scope = SCOPE_CPU;
5809                         goto next;
5810                 }
5811                 if (!strncmp(add_command, "core", strlen("core"))) {
5812                         scope = SCOPE_CORE;
5813                         goto next;
5814                 }
5815                 if (!strncmp(add_command, "package", strlen("package"))) {
5816                         scope = SCOPE_PACKAGE;
5817                         goto next;
5818                 }
5819                 if (!strncmp(add_command, "cycles", strlen("cycles"))) {
5820                         type = COUNTER_CYCLES;
5821                         goto next;
5822                 }
5823                 if (!strncmp(add_command, "seconds", strlen("seconds"))) {
5824                         type = COUNTER_SECONDS;
5825                         goto next;
5826                 }
5827                 if (!strncmp(add_command, "usec", strlen("usec"))) {
5828                         type = COUNTER_USEC;
5829                         goto next;
5830                 }
5831                 if (!strncmp(add_command, "raw", strlen("raw"))) {
5832                         format = FORMAT_RAW;
5833                         goto next;
5834                 }
5835                 if (!strncmp(add_command, "delta", strlen("delta"))) {
5836                         format = FORMAT_DELTA;
5837                         goto next;
5838                 }
5839                 if (!strncmp(add_command, "percent", strlen("percent"))) {
5840                         format = FORMAT_PERCENT;
5841                         goto next;
5842                 }
5843
5844                 if (sscanf(add_command, "%18s,%*s", name_buffer) == 1) {        /* 18 < NAME_BYTES */
5845                         char *eos;
5846
5847                         eos = strchr(name_buffer, ',');
5848                         if (eos)
5849                                 *eos = '\0';
5850                         goto next;
5851                 }
5852
5853 next:
5854                 add_command = strchr(add_command, ',');
5855                 if (add_command) {
5856                         *add_command = '\0';
5857                         add_command++;
5858                 }
5859
5860         }
5861         if ((msr_num == 0) && (path == NULL)) {
5862                 fprintf(stderr, "--add: (msrDDD | msr0xXXX | /path_to_counter ) required\n");
5863                 fail++;
5864         }
5865
5866         /* generate default column header */
5867         if (*name_buffer == '\0') {
5868                 if (width == 32)
5869                         sprintf(name_buffer, "M0x%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
5870                 else
5871                         sprintf(name_buffer, "M0X%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
5872         }
5873
5874         if (add_counter(msr_num, path, name_buffer, width, scope, type, format, 0))
5875                 fail++;
5876
5877         if (fail) {
5878                 help();
5879                 exit(1);
5880         }
5881 }
5882
5883 int is_deferred_skip(char *name)
5884 {
5885         int i;
5886
5887         for (i = 0; i < deferred_skip_index; ++i)
5888                 if (!strcmp(name, deferred_skip_names[i]))
5889                         return 1;
5890         return 0;
5891 }
5892
5893 void probe_sysfs(void)
5894 {
5895         char path[64];
5896         char name_buf[16];
5897         FILE *input;
5898         int state;
5899         char *sp;
5900
5901         if (!DO_BIC(BIC_sysfs))
5902                 return;
5903
5904         for (state = 10; state >= 0; --state) {
5905
5906                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name",
5907                         base_cpu, state);
5908                 input = fopen(path, "r");
5909                 if (input == NULL)
5910                         continue;
5911                 if (!fgets(name_buf, sizeof(name_buf), input))
5912                         err(1, "%s: failed to read file", path);
5913
5914                  /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
5915                 sp = strchr(name_buf, '-');
5916                 if (!sp)
5917                         sp = strchrnul(name_buf, '\n');
5918                 *sp = '%';
5919                 *(sp + 1) = '\0';
5920
5921                 remove_underbar(name_buf);
5922
5923                 fclose(input);
5924
5925                 sprintf(path, "cpuidle/state%d/time", state);
5926
5927                 if (is_deferred_skip(name_buf))
5928                         continue;
5929
5930                 add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_USEC,
5931                                 FORMAT_PERCENT, SYSFS_PERCPU);
5932         }
5933
5934         for (state = 10; state >= 0; --state) {
5935
5936                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name",
5937                         base_cpu, state);
5938                 input = fopen(path, "r");
5939                 if (input == NULL)
5940                         continue;
5941                 if (!fgets(name_buf, sizeof(name_buf), input))
5942                         err(1, "%s: failed to read file", path);
5943                  /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
5944                 sp = strchr(name_buf, '-');
5945                 if (!sp)
5946                         sp = strchrnul(name_buf, '\n');
5947                 *sp = '\0';
5948                 fclose(input);
5949
5950                 remove_underbar(name_buf);
5951
5952                 sprintf(path, "cpuidle/state%d/usage", state);
5953
5954                 if (is_deferred_skip(name_buf))
5955                         continue;
5956
5957                 add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_ITEMS,
5958                                 FORMAT_DELTA, SYSFS_PERCPU);
5959         }
5960
5961 }
5962
5963
5964 /*
5965  * parse cpuset with following syntax
5966  * 1,2,4..6,8-10 and set bits in cpu_subset
5967  */
5968 void parse_cpu_command(char *optarg)
5969 {
5970         unsigned int start, end;
5971         char *next;
5972
5973         if (!strcmp(optarg, "core")) {
5974                 if (cpu_subset)
5975                         goto error;
5976                 show_core_only++;
5977                 return;
5978         }
5979         if (!strcmp(optarg, "package")) {
5980                 if (cpu_subset)
5981                         goto error;
5982                 show_pkg_only++;
5983                 return;
5984         }
5985         if (show_core_only || show_pkg_only)
5986                 goto error;
5987
5988         cpu_subset = CPU_ALLOC(CPU_SUBSET_MAXCPUS);
5989         if (cpu_subset == NULL)
5990                 err(3, "CPU_ALLOC");
5991         cpu_subset_size = CPU_ALLOC_SIZE(CPU_SUBSET_MAXCPUS);
5992
5993         CPU_ZERO_S(cpu_subset_size, cpu_subset);
5994
5995         next = optarg;
5996
5997         while (next && *next) {
5998
5999                 if (*next == '-')       /* no negative cpu numbers */
6000                         goto error;
6001
6002                 start = strtoul(next, &next, 10);
6003
6004                 if (start >= CPU_SUBSET_MAXCPUS)
6005                         goto error;
6006                 CPU_SET_S(start, cpu_subset_size, cpu_subset);
6007
6008                 if (*next == '\0')
6009                         break;
6010
6011                 if (*next == ',') {
6012                         next += 1;
6013                         continue;
6014                 }
6015
6016                 if (*next == '-') {
6017                         next += 1;      /* start range */
6018                 } else if (*next == '.') {
6019                         next += 1;
6020                         if (*next == '.')
6021                                 next += 1;      /* start range */
6022                         else
6023                                 goto error;
6024                 }
6025
6026                 end = strtoul(next, &next, 10);
6027                 if (end <= start)
6028                         goto error;
6029
6030                 while (++start <= end) {
6031                         if (start >= CPU_SUBSET_MAXCPUS)
6032                                 goto error;
6033                         CPU_SET_S(start, cpu_subset_size, cpu_subset);
6034                 }
6035
6036                 if (*next == ',')
6037                         next += 1;
6038                 else if (*next != '\0')
6039                         goto error;
6040         }
6041
6042         return;
6043
6044 error:
6045         fprintf(stderr, "\"--cpu %s\" malformed\n", optarg);
6046         help();
6047         exit(-1);
6048 }
6049
6050
6051 void cmdline(int argc, char **argv)
6052 {
6053         int opt;
6054         int option_index = 0;
6055         static struct option long_options[] = {
6056                 {"add",         required_argument,      0, 'a'},
6057                 {"cpu",         required_argument,      0, 'c'},
6058                 {"Dump",        no_argument,            0, 'D'},
6059                 {"debug",       no_argument,            0, 'd'},        /* internal, not documented */
6060                 {"enable",      required_argument,      0, 'e'},
6061                 {"interval",    required_argument,      0, 'i'},
6062                 {"num_iterations",      required_argument,      0, 'n'},
6063                 {"help",        no_argument,            0, 'h'},
6064                 {"hide",        required_argument,      0, 'H'},        // meh, -h taken by --help
6065                 {"Joules",      no_argument,            0, 'J'},
6066                 {"list",        no_argument,            0, 'l'},
6067                 {"out",         required_argument,      0, 'o'},
6068                 {"quiet",       no_argument,            0, 'q'},
6069                 {"show",        required_argument,      0, 's'},
6070                 {"Summary",     no_argument,            0, 'S'},
6071                 {"TCC",         required_argument,      0, 'T'},
6072                 {"version",     no_argument,            0, 'v' },
6073                 {0,             0,                      0,  0 }
6074         };
6075
6076         progname = argv[0];
6077
6078         while ((opt = getopt_long_only(argc, argv, "+C:c:Dde:hi:Jn:o:qST:v",
6079                                 long_options, &option_index)) != -1) {
6080                 switch (opt) {
6081                 case 'a':
6082                         parse_add_command(optarg);
6083                         break;
6084                 case 'c':
6085                         parse_cpu_command(optarg);
6086                         break;
6087                 case 'D':
6088                         dump_only++;
6089                         break;
6090                 case 'e':
6091                         /* --enable specified counter */
6092                         bic_enabled = bic_enabled | bic_lookup(optarg, SHOW_LIST);
6093                         break;
6094                 case 'd':
6095                         debug++;
6096                         ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
6097                         break;
6098                 case 'H':
6099                         /*
6100                          * --hide: do not show those specified
6101                          *  multiple invocations simply clear more bits in enabled mask
6102                          */
6103                         bic_enabled &= ~bic_lookup(optarg, HIDE_LIST);
6104                         break;
6105                 case 'h':
6106                 default:
6107                         help();
6108                         exit(1);
6109                 case 'i':
6110                         {
6111                                 double interval = strtod(optarg, NULL);
6112
6113                                 if (interval < 0.001) {
6114                                         fprintf(outf, "interval %f seconds is too small\n",
6115                                                 interval);
6116                                         exit(2);
6117                                 }
6118
6119                                 interval_tv.tv_sec = interval_ts.tv_sec = interval;
6120                                 interval_tv.tv_usec = (interval - interval_tv.tv_sec) * 1000000;
6121                                 interval_ts.tv_nsec = (interval - interval_ts.tv_sec) * 1000000000;
6122                         }
6123                         break;
6124                 case 'J':
6125                         rapl_joules++;
6126                         break;
6127                 case 'l':
6128                         ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
6129                         list_header_only++;
6130                         quiet++;
6131                         break;
6132                 case 'o':
6133                         outf = fopen_or_die(optarg, "w");
6134                         break;
6135                 case 'q':
6136                         quiet = 1;
6137                         break;
6138                 case 'n':
6139                         num_iterations = strtod(optarg, NULL);
6140
6141                         if (num_iterations <= 0) {
6142                                 fprintf(outf, "iterations %d should be positive number\n",
6143                                         num_iterations);
6144                                 exit(2);
6145                         }
6146                         break;
6147                 case 's':
6148                         /*
6149                          * --show: show only those specified
6150                          *  The 1st invocation will clear and replace the enabled mask
6151                          *  subsequent invocations can add to it.
6152                          */
6153                         if (shown == 0)
6154                                 bic_enabled = bic_lookup(optarg, SHOW_LIST);
6155                         else
6156                                 bic_enabled |= bic_lookup(optarg, SHOW_LIST);
6157                         shown = 1;
6158                         break;
6159                 case 'S':
6160                         summary_only++;
6161                         break;
6162                 case 'T':
6163                         tcc_activation_temp_override = atoi(optarg);
6164                         break;
6165                 case 'v':
6166                         print_version();
6167                         exit(0);
6168                         break;
6169                 }
6170         }
6171 }
6172
6173 int main(int argc, char **argv)
6174 {
6175         outf = stderr;
6176         cmdline(argc, argv);
6177
6178         if (!quiet)
6179                 print_version();
6180
6181         probe_sysfs();
6182
6183         turbostat_init();
6184
6185         /* dump counters and exit */
6186         if (dump_only)
6187                 return get_and_dump_counters();
6188
6189         /* list header and exit */
6190         if (list_header_only) {
6191                 print_header(",");
6192                 flush_output_stdout();
6193                 return 0;
6194         }
6195
6196         msr_sum_record();
6197         /*
6198          * if any params left, it must be a command to fork
6199          */
6200         if (argc - optind)
6201                 return fork_it(argv + optind);
6202         else
6203                 turbostat_loop();
6204
6205         return 0;
6206 }