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