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