tools/power turbostat: Do not print negative LPI residency
[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[128];
4585
4586         if (!genuine_intel)
4587                 return;
4588
4589         if (access("/sys/devices/system/cpu/intel_uncore_frequency/package_00_die_00", R_OK))
4590                 return;
4591
4592         /* Cluster level sysfs not supported yet. */
4593         if (!access("/sys/devices/system/cpu/intel_uncore_frequency/uncore00", R_OK))
4594                 return;
4595
4596         if (!access("/sys/devices/system/cpu/intel_uncore_frequency/package_00_die_00/current_freq_khz", R_OK))
4597                 BIC_PRESENT(BIC_UNCORE_MHZ);
4598
4599         if (quiet)
4600                 return;
4601
4602         for (i = 0; i < topo.num_packages; ++i) {
4603                 for (j = 0; j < topo.num_die; ++j) {
4604                         int k, l;
4605
4606                         sprintf(path, "/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/min_freq_khz",
4607                                 i, j);
4608                         k = read_sysfs_int(path);
4609                         sprintf(path, "/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/max_freq_khz",
4610                                 i, j);
4611                         l = read_sysfs_int(path);
4612                         fprintf(outf, "Uncore Frequency pkg%d die%d: %d - %d MHz ", i, j, k / 1000, l / 1000);
4613
4614                         sprintf(path,
4615                                 "/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/initial_min_freq_khz",
4616                                 i, j);
4617                         k = read_sysfs_int(path);
4618                         sprintf(path,
4619                                 "/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/initial_max_freq_khz",
4620                                 i, j);
4621                         l = read_sysfs_int(path);
4622                         fprintf(outf, "(%d - %d MHz)\n", k / 1000, l / 1000);
4623                 }
4624         }
4625 }
4626
4627 static void probe_graphics(void)
4628 {
4629         if (!access("/sys/class/drm/card0/power/rc6_residency_ms", R_OK))
4630                 BIC_PRESENT(BIC_GFX_rc6);
4631
4632         if (!access("/sys/class/drm/card0/gt_cur_freq_mhz", R_OK) ||
4633             !access("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", R_OK))
4634                 BIC_PRESENT(BIC_GFXMHz);
4635
4636         if (!access("/sys/class/drm/card0/gt_act_freq_mhz", R_OK) ||
4637             !access("/sys/class/graphics/fb0/device/drm/card0/gt_act_freq_mhz", R_OK))
4638                 BIC_PRESENT(BIC_GFXACTMHz);
4639 }
4640
4641 static void dump_sysfs_cstate_config(void)
4642 {
4643         char path[64];
4644         char name_buf[16];
4645         char desc[64];
4646         FILE *input;
4647         int state;
4648         char *sp;
4649
4650         if (access("/sys/devices/system/cpu/cpuidle", R_OK)) {
4651                 fprintf(outf, "cpuidle not loaded\n");
4652                 return;
4653         }
4654
4655         dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_driver");
4656         dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_governor");
4657         dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_governor_ro");
4658
4659         for (state = 0; state < 10; ++state) {
4660
4661                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name", base_cpu, state);
4662                 input = fopen(path, "r");
4663                 if (input == NULL)
4664                         continue;
4665                 if (!fgets(name_buf, sizeof(name_buf), input))
4666                         err(1, "%s: failed to read file", path);
4667
4668                 /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
4669                 sp = strchr(name_buf, '-');
4670                 if (!sp)
4671                         sp = strchrnul(name_buf, '\n');
4672                 *sp = '\0';
4673                 fclose(input);
4674
4675                 remove_underbar(name_buf);
4676
4677                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/desc", base_cpu, state);
4678                 input = fopen(path, "r");
4679                 if (input == NULL)
4680                         continue;
4681                 if (!fgets(desc, sizeof(desc), input))
4682                         err(1, "%s: failed to read file", path);
4683
4684                 fprintf(outf, "cpu%d: %s: %s", base_cpu, name_buf, desc);
4685                 fclose(input);
4686         }
4687 }
4688
4689 static void dump_sysfs_pstate_config(void)
4690 {
4691         char path[64];
4692         char driver_buf[64];
4693         char governor_buf[64];
4694         FILE *input;
4695         int turbo;
4696
4697         sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_driver", base_cpu);
4698         input = fopen(path, "r");
4699         if (input == NULL) {
4700                 fprintf(outf, "NSFOD %s\n", path);
4701                 return;
4702         }
4703         if (!fgets(driver_buf, sizeof(driver_buf), input))
4704                 err(1, "%s: failed to read file", path);
4705         fclose(input);
4706
4707         sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor", base_cpu);
4708         input = fopen(path, "r");
4709         if (input == NULL) {
4710                 fprintf(outf, "NSFOD %s\n", path);
4711                 return;
4712         }
4713         if (!fgets(governor_buf, sizeof(governor_buf), input))
4714                 err(1, "%s: failed to read file", path);
4715         fclose(input);
4716
4717         fprintf(outf, "cpu%d: cpufreq driver: %s", base_cpu, driver_buf);
4718         fprintf(outf, "cpu%d: cpufreq governor: %s", base_cpu, governor_buf);
4719
4720         sprintf(path, "/sys/devices/system/cpu/cpufreq/boost");
4721         input = fopen(path, "r");
4722         if (input != NULL) {
4723                 if (fscanf(input, "%d", &turbo) != 1)
4724                         err(1, "%s: failed to parse number from file", path);
4725                 fprintf(outf, "cpufreq boost: %d\n", turbo);
4726                 fclose(input);
4727         }
4728
4729         sprintf(path, "/sys/devices/system/cpu/intel_pstate/no_turbo");
4730         input = fopen(path, "r");
4731         if (input != NULL) {
4732                 if (fscanf(input, "%d", &turbo) != 1)
4733                         err(1, "%s: failed to parse number from file", path);
4734                 fprintf(outf, "cpufreq intel_pstate no_turbo: %d\n", turbo);
4735                 fclose(input);
4736         }
4737 }
4738
4739 /*
4740  * print_epb()
4741  * Decode the ENERGY_PERF_BIAS MSR
4742  */
4743 int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4744 {
4745         char *epb_string;
4746         int cpu, epb;
4747
4748         UNUSED(c);
4749         UNUSED(p);
4750
4751         if (!has_epb)
4752                 return 0;
4753
4754         cpu = t->cpu_id;
4755
4756         /* EPB is per-package */
4757         if (!is_cpu_first_thread_in_package(t, c, p))
4758                 return 0;
4759
4760         if (cpu_migrate(cpu)) {
4761                 fprintf(outf, "print_epb: Could not migrate to CPU %d\n", cpu);
4762                 return -1;
4763         }
4764
4765         epb = get_epb(cpu);
4766         if (epb < 0)
4767                 return 0;
4768
4769         switch (epb) {
4770         case ENERGY_PERF_BIAS_PERFORMANCE:
4771                 epb_string = "performance";
4772                 break;
4773         case ENERGY_PERF_BIAS_NORMAL:
4774                 epb_string = "balanced";
4775                 break;
4776         case ENERGY_PERF_BIAS_POWERSAVE:
4777                 epb_string = "powersave";
4778                 break;
4779         default:
4780                 epb_string = "custom";
4781                 break;
4782         }
4783         fprintf(outf, "cpu%d: EPB: %d (%s)\n", cpu, epb, epb_string);
4784
4785         return 0;
4786 }
4787
4788 /*
4789  * print_hwp()
4790  * Decode the MSR_HWP_CAPABILITIES
4791  */
4792 int print_hwp(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4793 {
4794         unsigned long long msr;
4795         int cpu;
4796
4797         UNUSED(c);
4798         UNUSED(p);
4799
4800         if (!has_hwp)
4801                 return 0;
4802
4803         cpu = t->cpu_id;
4804
4805         /* MSR_HWP_CAPABILITIES is per-package */
4806         if (!is_cpu_first_thread_in_package(t, c, p))
4807                 return 0;
4808
4809         if (cpu_migrate(cpu)) {
4810                 fprintf(outf, "print_hwp: Could not migrate to CPU %d\n", cpu);
4811                 return -1;
4812         }
4813
4814         if (get_msr(cpu, MSR_PM_ENABLE, &msr))
4815                 return 0;
4816
4817         fprintf(outf, "cpu%d: MSR_PM_ENABLE: 0x%08llx (%sHWP)\n", cpu, msr, (msr & (1 << 0)) ? "" : "No-");
4818
4819         /* MSR_PM_ENABLE[1] == 1 if HWP is enabled and MSRs visible */
4820         if ((msr & (1 << 0)) == 0)
4821                 return 0;
4822
4823         if (get_msr(cpu, MSR_HWP_CAPABILITIES, &msr))
4824                 return 0;
4825
4826         fprintf(outf, "cpu%d: MSR_HWP_CAPABILITIES: 0x%08llx "
4827                 "(high %d guar %d eff %d low %d)\n",
4828                 cpu, msr,
4829                 (unsigned int)HWP_HIGHEST_PERF(msr),
4830                 (unsigned int)HWP_GUARANTEED_PERF(msr),
4831                 (unsigned int)HWP_MOSTEFFICIENT_PERF(msr), (unsigned int)HWP_LOWEST_PERF(msr));
4832
4833         if (get_msr(cpu, MSR_HWP_REQUEST, &msr))
4834                 return 0;
4835
4836         fprintf(outf, "cpu%d: MSR_HWP_REQUEST: 0x%08llx "
4837                 "(min %d max %d des %d epp 0x%x window 0x%x pkg 0x%x)\n",
4838                 cpu, msr,
4839                 (unsigned int)(((msr) >> 0) & 0xff),
4840                 (unsigned int)(((msr) >> 8) & 0xff),
4841                 (unsigned int)(((msr) >> 16) & 0xff),
4842                 (unsigned int)(((msr) >> 24) & 0xff),
4843                 (unsigned int)(((msr) >> 32) & 0xff3), (unsigned int)(((msr) >> 42) & 0x1));
4844
4845         if (has_hwp_pkg) {
4846                 if (get_msr(cpu, MSR_HWP_REQUEST_PKG, &msr))
4847                         return 0;
4848
4849                 fprintf(outf, "cpu%d: MSR_HWP_REQUEST_PKG: 0x%08llx "
4850                         "(min %d max %d des %d epp 0x%x window 0x%x)\n",
4851                         cpu, msr,
4852                         (unsigned int)(((msr) >> 0) & 0xff),
4853                         (unsigned int)(((msr) >> 8) & 0xff),
4854                         (unsigned int)(((msr) >> 16) & 0xff),
4855                         (unsigned int)(((msr) >> 24) & 0xff), (unsigned int)(((msr) >> 32) & 0xff3));
4856         }
4857         if (has_hwp_notify) {
4858                 if (get_msr(cpu, MSR_HWP_INTERRUPT, &msr))
4859                         return 0;
4860
4861                 fprintf(outf, "cpu%d: MSR_HWP_INTERRUPT: 0x%08llx "
4862                         "(%s_Guaranteed_Perf_Change, %s_Excursion_Min)\n",
4863                         cpu, msr, ((msr) & 0x1) ? "EN" : "Dis", ((msr) & 0x2) ? "EN" : "Dis");
4864         }
4865         if (get_msr(cpu, MSR_HWP_STATUS, &msr))
4866                 return 0;
4867
4868         fprintf(outf, "cpu%d: MSR_HWP_STATUS: 0x%08llx "
4869                 "(%sGuaranteed_Perf_Change, %sExcursion_Min)\n",
4870                 cpu, msr, ((msr) & 0x1) ? "" : "No-", ((msr) & 0x4) ? "" : "No-");
4871
4872         return 0;
4873 }
4874
4875 /*
4876  * print_perf_limit()
4877  */
4878 int print_perf_limit(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4879 {
4880         unsigned long long msr;
4881         int cpu;
4882
4883         UNUSED(c);
4884         UNUSED(p);
4885
4886         cpu = t->cpu_id;
4887
4888         /* per-package */
4889         if (!is_cpu_first_thread_in_package(t, c, p))
4890                 return 0;
4891
4892         if (cpu_migrate(cpu)) {
4893                 fprintf(outf, "print_perf_limit: Could not migrate to CPU %d\n", cpu);
4894                 return -1;
4895         }
4896
4897         if (platform->plr_msrs & PLR_CORE) {
4898                 get_msr(cpu, MSR_CORE_PERF_LIMIT_REASONS, &msr);
4899                 fprintf(outf, "cpu%d: MSR_CORE_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4900                 fprintf(outf, " (Active: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
4901                         (msr & 1 << 15) ? "bit15, " : "",
4902                         (msr & 1 << 14) ? "bit14, " : "",
4903                         (msr & 1 << 13) ? "Transitions, " : "",
4904                         (msr & 1 << 12) ? "MultiCoreTurbo, " : "",
4905                         (msr & 1 << 11) ? "PkgPwrL2, " : "",
4906                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
4907                         (msr & 1 << 9) ? "CorePwr, " : "",
4908                         (msr & 1 << 8) ? "Amps, " : "",
4909                         (msr & 1 << 6) ? "VR-Therm, " : "",
4910                         (msr & 1 << 5) ? "Auto-HWP, " : "",
4911                         (msr & 1 << 4) ? "Graphics, " : "",
4912                         (msr & 1 << 2) ? "bit2, " : "",
4913                         (msr & 1 << 1) ? "ThermStatus, " : "", (msr & 1 << 0) ? "PROCHOT, " : "");
4914                 fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
4915                         (msr & 1 << 31) ? "bit31, " : "",
4916                         (msr & 1 << 30) ? "bit30, " : "",
4917                         (msr & 1 << 29) ? "Transitions, " : "",
4918                         (msr & 1 << 28) ? "MultiCoreTurbo, " : "",
4919                         (msr & 1 << 27) ? "PkgPwrL2, " : "",
4920                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
4921                         (msr & 1 << 25) ? "CorePwr, " : "",
4922                         (msr & 1 << 24) ? "Amps, " : "",
4923                         (msr & 1 << 22) ? "VR-Therm, " : "",
4924                         (msr & 1 << 21) ? "Auto-HWP, " : "",
4925                         (msr & 1 << 20) ? "Graphics, " : "",
4926                         (msr & 1 << 18) ? "bit18, " : "",
4927                         (msr & 1 << 17) ? "ThermStatus, " : "", (msr & 1 << 16) ? "PROCHOT, " : "");
4928
4929         }
4930         if (platform->plr_msrs & PLR_GFX) {
4931                 get_msr(cpu, MSR_GFX_PERF_LIMIT_REASONS, &msr);
4932                 fprintf(outf, "cpu%d: MSR_GFX_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4933                 fprintf(outf, " (Active: %s%s%s%s%s%s%s%s)",
4934                         (msr & 1 << 0) ? "PROCHOT, " : "",
4935                         (msr & 1 << 1) ? "ThermStatus, " : "",
4936                         (msr & 1 << 4) ? "Graphics, " : "",
4937                         (msr & 1 << 6) ? "VR-Therm, " : "",
4938                         (msr & 1 << 8) ? "Amps, " : "",
4939                         (msr & 1 << 9) ? "GFXPwr, " : "",
4940                         (msr & 1 << 10) ? "PkgPwrL1, " : "", (msr & 1 << 11) ? "PkgPwrL2, " : "");
4941                 fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s)\n",
4942                         (msr & 1 << 16) ? "PROCHOT, " : "",
4943                         (msr & 1 << 17) ? "ThermStatus, " : "",
4944                         (msr & 1 << 20) ? "Graphics, " : "",
4945                         (msr & 1 << 22) ? "VR-Therm, " : "",
4946                         (msr & 1 << 24) ? "Amps, " : "",
4947                         (msr & 1 << 25) ? "GFXPwr, " : "",
4948                         (msr & 1 << 26) ? "PkgPwrL1, " : "", (msr & 1 << 27) ? "PkgPwrL2, " : "");
4949         }
4950         if (platform->plr_msrs & PLR_RING) {
4951                 get_msr(cpu, MSR_RING_PERF_LIMIT_REASONS, &msr);
4952                 fprintf(outf, "cpu%d: MSR_RING_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4953                 fprintf(outf, " (Active: %s%s%s%s%s%s)",
4954                         (msr & 1 << 0) ? "PROCHOT, " : "",
4955                         (msr & 1 << 1) ? "ThermStatus, " : "",
4956                         (msr & 1 << 6) ? "VR-Therm, " : "",
4957                         (msr & 1 << 8) ? "Amps, " : "",
4958                         (msr & 1 << 10) ? "PkgPwrL1, " : "", (msr & 1 << 11) ? "PkgPwrL2, " : "");
4959                 fprintf(outf, " (Logged: %s%s%s%s%s%s)\n",
4960                         (msr & 1 << 16) ? "PROCHOT, " : "",
4961                         (msr & 1 << 17) ? "ThermStatus, " : "",
4962                         (msr & 1 << 22) ? "VR-Therm, " : "",
4963                         (msr & 1 << 24) ? "Amps, " : "",
4964                         (msr & 1 << 26) ? "PkgPwrL1, " : "", (msr & 1 << 27) ? "PkgPwrL2, " : "");
4965         }
4966         return 0;
4967 }
4968
4969 #define RAPL_POWER_GRANULARITY  0x7FFF  /* 15 bit power granularity */
4970 #define RAPL_TIME_GRANULARITY   0x3F    /* 6 bit time granularity */
4971
4972 double get_quirk_tdp(void)
4973 {
4974         if (platform->rapl_quirk_tdp)
4975                 return platform->rapl_quirk_tdp;
4976
4977         return 135.0;
4978 }
4979
4980 double get_tdp_intel(void)
4981 {
4982         unsigned long long msr;
4983
4984         if (platform->rapl_msrs & RAPL_PKG_POWER_INFO)
4985                 if (!get_msr(base_cpu, MSR_PKG_POWER_INFO, &msr))
4986                         return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
4987         return get_quirk_tdp();
4988 }
4989
4990 double get_tdp_amd(void)
4991 {
4992         return get_quirk_tdp();
4993 }
4994
4995 void rapl_probe_intel(void)
4996 {
4997         unsigned long long msr;
4998         unsigned int time_unit;
4999         double tdp;
5000
5001         if (rapl_joules) {
5002                 if (platform->rapl_msrs & RAPL_PKG_ENERGY_STATUS)
5003                         BIC_PRESENT(BIC_Pkg_J);
5004                 if (platform->rapl_msrs & RAPL_CORE_ENERGY_STATUS)
5005                         BIC_PRESENT(BIC_Cor_J);
5006                 if (platform->rapl_msrs & RAPL_DRAM_ENERGY_STATUS)
5007                         BIC_PRESENT(BIC_RAM_J);
5008                 if (platform->rapl_msrs & RAPL_GFX_ENERGY_STATUS)
5009                         BIC_PRESENT(BIC_GFX_J);
5010         } else {
5011                 if (platform->rapl_msrs & RAPL_PKG_ENERGY_STATUS)
5012                         BIC_PRESENT(BIC_PkgWatt);
5013                 if (platform->rapl_msrs & RAPL_CORE_ENERGY_STATUS)
5014                         BIC_PRESENT(BIC_CorWatt);
5015                 if (platform->rapl_msrs & RAPL_DRAM_ENERGY_STATUS)
5016                         BIC_PRESENT(BIC_RAMWatt);
5017                 if (platform->rapl_msrs & RAPL_GFX_ENERGY_STATUS)
5018                         BIC_PRESENT(BIC_GFXWatt);
5019         }
5020
5021         if (platform->rapl_msrs & RAPL_PKG_PERF_STATUS)
5022                 BIC_PRESENT(BIC_PKG__);
5023         if (platform->rapl_msrs & RAPL_DRAM_PERF_STATUS)
5024                 BIC_PRESENT(BIC_RAM__);
5025
5026         /* units on package 0, verify later other packages match */
5027         if (get_msr(base_cpu, MSR_RAPL_POWER_UNIT, &msr))
5028                 return;
5029
5030         rapl_power_units = 1.0 / (1 << (msr & 0xF));
5031         if (platform->has_rapl_divisor)
5032                 rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
5033         else
5034                 rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
5035
5036         if (platform->has_fixed_rapl_unit)
5037                 rapl_dram_energy_units = (15.3 / 1000000);
5038         else
5039                 rapl_dram_energy_units = rapl_energy_units;
5040
5041         time_unit = msr >> 16 & 0xF;
5042         if (time_unit == 0)
5043                 time_unit = 0xA;
5044
5045         rapl_time_units = 1.0 / (1 << (time_unit));
5046
5047         tdp = get_tdp_intel();
5048
5049         rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
5050         if (!quiet)
5051                 fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
5052 }
5053
5054 void rapl_probe_amd(void)
5055 {
5056         unsigned long long msr;
5057         double tdp;
5058
5059         if (rapl_joules) {
5060                 BIC_PRESENT(BIC_Pkg_J);
5061                 BIC_PRESENT(BIC_Cor_J);
5062         } else {
5063                 BIC_PRESENT(BIC_PkgWatt);
5064                 BIC_PRESENT(BIC_CorWatt);
5065         }
5066
5067         if (get_msr(base_cpu, MSR_RAPL_PWR_UNIT, &msr))
5068                 return;
5069
5070         rapl_time_units = ldexp(1.0, -(msr >> 16 & 0xf));
5071         rapl_energy_units = ldexp(1.0, -(msr >> 8 & 0x1f));
5072         rapl_power_units = ldexp(1.0, -(msr & 0xf));
5073
5074         tdp = get_tdp_amd();
5075
5076         rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
5077         if (!quiet)
5078                 fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
5079 }
5080
5081 void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
5082 {
5083         fprintf(outf, "cpu%d: %s: %sabled (%0.3f Watts, %f sec, clamp %sabled)\n",
5084                 cpu, label,
5085                 ((msr >> 15) & 1) ? "EN" : "DIS",
5086                 ((msr >> 0) & 0x7FFF) * rapl_power_units,
5087                 (1.0 + (((msr >> 22) & 0x3) / 4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
5088                 (((msr >> 16) & 1) ? "EN" : "DIS"));
5089
5090         return;
5091 }
5092
5093 int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
5094 {
5095         unsigned long long msr;
5096         const char *msr_name;
5097         int cpu;
5098
5099         UNUSED(c);
5100         UNUSED(p);
5101
5102         if (!platform->rapl_msrs)
5103                 return 0;
5104
5105         /* RAPL counters are per package, so print only for 1st thread/package */
5106         if (!is_cpu_first_thread_in_package(t, c, p))
5107                 return 0;
5108
5109         cpu = t->cpu_id;
5110         if (cpu_migrate(cpu)) {
5111                 fprintf(outf, "print_rapl: Could not migrate to CPU %d\n", cpu);
5112                 return -1;
5113         }
5114
5115         if (platform->rapl_msrs & RAPL_AMD_F17H) {
5116                 msr_name = "MSR_RAPL_PWR_UNIT";
5117                 if (get_msr(cpu, MSR_RAPL_PWR_UNIT, &msr))
5118                         return -1;
5119         } else {
5120                 msr_name = "MSR_RAPL_POWER_UNIT";
5121                 if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
5122                         return -1;
5123         }
5124
5125         fprintf(outf, "cpu%d: %s: 0x%08llx (%f Watts, %f Joules, %f sec.)\n", cpu, msr_name, msr,
5126                 rapl_power_units, rapl_energy_units, rapl_time_units);
5127
5128         if (platform->rapl_msrs & RAPL_PKG_POWER_INFO) {
5129
5130                 if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
5131                         return -5;
5132
5133                 fprintf(outf, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
5134                         cpu, msr,
5135                         ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
5136                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
5137                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
5138                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
5139
5140         }
5141         if (platform->rapl_msrs & RAPL_PKG) {
5142
5143                 if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
5144                         return -9;
5145
5146                 fprintf(outf, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
5147                         cpu, msr, (msr >> 63) & 1 ? "" : "UN");
5148
5149                 print_power_limit_msr(cpu, msr, "PKG Limit #1");
5150                 fprintf(outf, "cpu%d: PKG Limit #2: %sabled (%0.3f Watts, %f* sec, clamp %sabled)\n",
5151                         cpu,
5152                         ((msr >> 47) & 1) ? "EN" : "DIS",
5153                         ((msr >> 32) & 0x7FFF) * rapl_power_units,
5154                         (1.0 + (((msr >> 54) & 0x3) / 4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
5155                         ((msr >> 48) & 1) ? "EN" : "DIS");
5156
5157                 if (get_msr(cpu, MSR_VR_CURRENT_CONFIG, &msr))
5158                         return -9;
5159
5160                 fprintf(outf, "cpu%d: MSR_VR_CURRENT_CONFIG: 0x%08llx\n", cpu, msr);
5161                 fprintf(outf, "cpu%d: PKG Limit #4: %f Watts (%slocked)\n",
5162                         cpu, ((msr >> 0) & 0x1FFF) * rapl_power_units, (msr >> 31) & 1 ? "" : "UN");
5163         }
5164
5165         if (platform->rapl_msrs & RAPL_DRAM_POWER_INFO) {
5166                 if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
5167                         return -6;
5168
5169                 fprintf(outf, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
5170                         cpu, msr,
5171                         ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
5172                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
5173                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
5174                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
5175         }
5176         if (platform->rapl_msrs & RAPL_DRAM) {
5177                 if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
5178                         return -9;
5179                 fprintf(outf, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
5180                         cpu, msr, (msr >> 31) & 1 ? "" : "UN");
5181
5182                 print_power_limit_msr(cpu, msr, "DRAM Limit");
5183         }
5184         if (platform->rapl_msrs & RAPL_CORE_POLICY) {
5185                 if (get_msr(cpu, MSR_PP0_POLICY, &msr))
5186                         return -7;
5187
5188                 fprintf(outf, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
5189         }
5190         if (platform->rapl_msrs & RAPL_CORE_POWER_LIMIT) {
5191                 if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
5192                         return -9;
5193                 fprintf(outf, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
5194                         cpu, msr, (msr >> 31) & 1 ? "" : "UN");
5195                 print_power_limit_msr(cpu, msr, "Cores Limit");
5196         }
5197         if (platform->rapl_msrs & RAPL_GFX) {
5198                 if (get_msr(cpu, MSR_PP1_POLICY, &msr))
5199                         return -8;
5200
5201                 fprintf(outf, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
5202
5203                 if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
5204                         return -9;
5205                 fprintf(outf, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
5206                         cpu, msr, (msr >> 31) & 1 ? "" : "UN");
5207                 print_power_limit_msr(cpu, msr, "GFX Limit");
5208         }
5209         return 0;
5210 }
5211
5212 /*
5213  * probe_rapl()
5214  *
5215  * sets rapl_power_units, rapl_energy_units, rapl_time_units
5216  */
5217 void probe_rapl(void)
5218 {
5219         if (!platform->rapl_msrs)
5220                 return;
5221
5222         if (genuine_intel)
5223                 rapl_probe_intel();
5224         if (authentic_amd || hygon_genuine)
5225                 rapl_probe_amd();
5226
5227         if (quiet)
5228                 return;
5229
5230         for_all_cpus(print_rapl, ODD_COUNTERS);
5231 }
5232
5233 /*
5234  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
5235  * the Thermal Control Circuit (TCC) activates.
5236  * This is usually equal to tjMax.
5237  *
5238  * Older processors do not have this MSR, so there we guess,
5239  * but also allow cmdline over-ride with -T.
5240  *
5241  * Several MSR temperature values are in units of degrees-C
5242  * below this value, including the Digital Thermal Sensor (DTS),
5243  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
5244  */
5245 int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
5246 {
5247         unsigned long long msr;
5248         unsigned int tcc_default, tcc_offset;
5249         int cpu;
5250
5251         UNUSED(c);
5252         UNUSED(p);
5253
5254         /* tj_max is used only for dts or ptm */
5255         if (!(do_dts || do_ptm))
5256                 return 0;
5257
5258         /* this is a per-package concept */
5259         if (!is_cpu_first_thread_in_package(t, c, p))
5260                 return 0;
5261
5262         cpu = t->cpu_id;
5263         if (cpu_migrate(cpu)) {
5264                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
5265                 return -1;
5266         }
5267
5268         if (tj_max_override != 0) {
5269                 tj_max = tj_max_override;
5270                 fprintf(outf, "cpu%d: Using cmdline TCC Target (%d C)\n", cpu, tj_max);
5271                 return 0;
5272         }
5273
5274         /* Temperature Target MSR is Nehalem and newer only */
5275         if (!platform->has_nhm_msrs)
5276                 goto guess;
5277
5278         if (get_msr(base_cpu, MSR_IA32_TEMPERATURE_TARGET, &msr))
5279                 goto guess;
5280
5281         tcc_default = (msr >> 16) & 0xFF;
5282
5283         if (!quiet) {
5284                 int bits = platform->tcc_offset_bits;
5285                 unsigned long long enabled = 0;
5286
5287                 if (bits && !get_msr(base_cpu, MSR_PLATFORM_INFO, &enabled))
5288                         enabled = (enabled >> 30) & 1;
5289
5290                 if (bits && enabled) {
5291                         tcc_offset = (msr >> 24) & GENMASK(bits - 1, 0);
5292                         fprintf(outf, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C) (%d default - %d offset)\n",
5293                                 cpu, msr, tcc_default - tcc_offset, tcc_default, tcc_offset);
5294                 } else {
5295                         fprintf(outf, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n", cpu, msr, tcc_default);
5296                 }
5297         }
5298
5299         if (!tcc_default)
5300                 goto guess;
5301
5302         tj_max = tcc_default;
5303
5304         return 0;
5305
5306 guess:
5307         tj_max = TJMAX_DEFAULT;
5308         fprintf(outf, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n", cpu, tj_max);
5309
5310         return 0;
5311 }
5312
5313 int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
5314 {
5315         unsigned long long msr;
5316         unsigned int dts, dts2;
5317         int cpu;
5318
5319         UNUSED(c);
5320         UNUSED(p);
5321
5322         if (!(do_dts || do_ptm))
5323                 return 0;
5324
5325         cpu = t->cpu_id;
5326
5327         /* DTS is per-core, no need to print for each thread */
5328         if (!is_cpu_first_thread_in_core(t, c, p))
5329                 return 0;
5330
5331         if (cpu_migrate(cpu)) {
5332                 fprintf(outf, "print_thermal: Could not migrate to CPU %d\n", cpu);
5333                 return -1;
5334         }
5335
5336         if (do_ptm && is_cpu_first_core_in_package(t, c, p)) {
5337                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
5338                         return 0;
5339
5340                 dts = (msr >> 16) & 0x7F;
5341                 fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n", cpu, msr, tj_max - dts);
5342
5343                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
5344                         return 0;
5345
5346                 dts = (msr >> 16) & 0x7F;
5347                 dts2 = (msr >> 8) & 0x7F;
5348                 fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
5349                         cpu, msr, tj_max - dts, tj_max - dts2);
5350         }
5351
5352         if (do_dts && debug) {
5353                 unsigned int resolution;
5354
5355                 if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
5356                         return 0;
5357
5358                 dts = (msr >> 16) & 0x7F;
5359                 resolution = (msr >> 27) & 0xF;
5360                 fprintf(outf, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
5361                         cpu, msr, tj_max - dts, resolution);
5362
5363                 if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
5364                         return 0;
5365
5366                 dts = (msr >> 16) & 0x7F;
5367                 dts2 = (msr >> 8) & 0x7F;
5368                 fprintf(outf, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
5369                         cpu, msr, tj_max - dts, tj_max - dts2);
5370         }
5371
5372         return 0;
5373 }
5374
5375 void probe_thermal(void)
5376 {
5377         if (!access("/sys/devices/system/cpu/cpu0/thermal_throttle/core_throttle_count", R_OK))
5378                 BIC_PRESENT(BIC_CORE_THROT_CNT);
5379         else
5380                 BIC_NOT_PRESENT(BIC_CORE_THROT_CNT);
5381
5382         for_all_cpus(set_temperature_target, ODD_COUNTERS);
5383
5384         if (quiet)
5385                 return;
5386
5387         for_all_cpus(print_thermal, ODD_COUNTERS);
5388 }
5389
5390 int get_cpu_type(struct thread_data *t, struct core_data *c, struct pkg_data *p)
5391 {
5392         unsigned int eax, ebx, ecx, edx;
5393
5394         UNUSED(c);
5395         UNUSED(p);
5396
5397         if (!genuine_intel)
5398                 return 0;
5399
5400         if (cpu_migrate(t->cpu_id)) {
5401                 fprintf(outf, "Could not migrate to CPU %d\n", t->cpu_id);
5402                 return -1;
5403         }
5404
5405         if (max_level < 0x1a)
5406                 return 0;
5407
5408         __cpuid(0x1a, eax, ebx, ecx, edx);
5409         eax = (eax >> 24) & 0xFF;
5410         if (eax == 0x20)
5411                 t->is_atom = true;
5412         return 0;
5413 }
5414
5415 void decode_feature_control_msr(void)
5416 {
5417         unsigned long long msr;
5418
5419         if (!get_msr(base_cpu, MSR_IA32_FEAT_CTL, &msr))
5420                 fprintf(outf, "cpu%d: MSR_IA32_FEATURE_CONTROL: 0x%08llx (%sLocked %s)\n",
5421                         base_cpu, msr, msr & FEAT_CTL_LOCKED ? "" : "UN-", msr & (1 << 18) ? "SGX" : "");
5422 }
5423
5424 void decode_misc_enable_msr(void)
5425 {
5426         unsigned long long msr;
5427
5428         if (!genuine_intel)
5429                 return;
5430
5431         if (!get_msr(base_cpu, MSR_IA32_MISC_ENABLE, &msr))
5432                 fprintf(outf, "cpu%d: MSR_IA32_MISC_ENABLE: 0x%08llx (%sTCC %sEIST %sMWAIT %sPREFETCH %sTURBO)\n",
5433                         base_cpu, msr,
5434                         msr & MSR_IA32_MISC_ENABLE_TM1 ? "" : "No-",
5435                         msr & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP ? "" : "No-",
5436                         msr & MSR_IA32_MISC_ENABLE_MWAIT ? "" : "No-",
5437                         msr & MSR_IA32_MISC_ENABLE_PREFETCH_DISABLE ? "No-" : "",
5438                         msr & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ? "No-" : "");
5439 }
5440
5441 void decode_misc_feature_control(void)
5442 {
5443         unsigned long long msr;
5444
5445         if (!platform->has_msr_misc_feature_control)
5446                 return;
5447
5448         if (!get_msr(base_cpu, MSR_MISC_FEATURE_CONTROL, &msr))
5449                 fprintf(outf,
5450                         "cpu%d: MSR_MISC_FEATURE_CONTROL: 0x%08llx (%sL2-Prefetch %sL2-Prefetch-pair %sL1-Prefetch %sL1-IP-Prefetch)\n",
5451                         base_cpu, msr, msr & (0 << 0) ? "No-" : "", msr & (1 << 0) ? "No-" : "",
5452                         msr & (2 << 0) ? "No-" : "", msr & (3 << 0) ? "No-" : "");
5453 }
5454
5455 /*
5456  * Decode MSR_MISC_PWR_MGMT
5457  *
5458  * Decode the bits according to the Nehalem documentation
5459  * bit[0] seems to continue to have same meaning going forward
5460  * bit[1] less so...
5461  */
5462 void decode_misc_pwr_mgmt_msr(void)
5463 {
5464         unsigned long long msr;
5465
5466         if (!platform->has_msr_misc_pwr_mgmt)
5467                 return;
5468
5469         if (!get_msr(base_cpu, MSR_MISC_PWR_MGMT, &msr))
5470                 fprintf(outf, "cpu%d: MSR_MISC_PWR_MGMT: 0x%08llx (%sable-EIST_Coordination %sable-EPB %sable-OOB)\n",
5471                         base_cpu, msr,
5472                         msr & (1 << 0) ? "DIS" : "EN", msr & (1 << 1) ? "EN" : "DIS", msr & (1 << 8) ? "EN" : "DIS");
5473 }
5474
5475 /*
5476  * Decode MSR_CC6_DEMOTION_POLICY_CONFIG, MSR_MC6_DEMOTION_POLICY_CONFIG
5477  *
5478  * This MSRs are present on Silvermont processors,
5479  * Intel Atom processor E3000 series (Baytrail), and friends.
5480  */
5481 void decode_c6_demotion_policy_msr(void)
5482 {
5483         unsigned long long msr;
5484
5485         if (!platform->has_msr_c6_demotion_policy_config)
5486                 return;
5487
5488         if (!get_msr(base_cpu, MSR_CC6_DEMOTION_POLICY_CONFIG, &msr))
5489                 fprintf(outf, "cpu%d: MSR_CC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-CC6-Demotion)\n",
5490                         base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
5491
5492         if (!get_msr(base_cpu, MSR_MC6_DEMOTION_POLICY_CONFIG, &msr))
5493                 fprintf(outf, "cpu%d: MSR_MC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-MC6-Demotion)\n",
5494                         base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
5495 }
5496
5497 void print_dev_latency(void)
5498 {
5499         char *path = "/dev/cpu_dma_latency";
5500         int fd;
5501         int value;
5502         int retval;
5503
5504         fd = open(path, O_RDONLY);
5505         if (fd < 0) {
5506                 warnx("capget(CAP_SYS_ADMIN) failed, try \"# setcap cap_sys_admin=ep %s\"", progname);
5507                 return;
5508         }
5509
5510         retval = read(fd, (void *)&value, sizeof(int));
5511         if (retval != sizeof(int)) {
5512                 warn("read failed %s", path);
5513                 close(fd);
5514                 return;
5515         }
5516         fprintf(outf, "/dev/cpu_dma_latency: %d usec (%s)\n", value, value == 2000000000 ? "default" : "constrained");
5517
5518         close(fd);
5519 }
5520
5521 /*
5522  * Linux-perf manages the HW instructions-retired counter
5523  * by enabling when requested, and hiding rollover
5524  */
5525 void linux_perf_init(void)
5526 {
5527         if (!BIC_IS_ENABLED(BIC_IPC))
5528                 return;
5529
5530         if (access("/proc/sys/kernel/perf_event_paranoid", F_OK))
5531                 return;
5532
5533         fd_instr_count_percpu = calloc(topo.max_cpu_num + 1, sizeof(int));
5534         if (fd_instr_count_percpu == NULL)
5535                 err(-1, "calloc fd_instr_count_percpu");
5536
5537         BIC_PRESENT(BIC_IPC);
5538 }
5539
5540 void probe_cstates(void)
5541 {
5542         probe_cst_limit();
5543
5544         if (platform->supported_cstates & CC1)
5545                 BIC_PRESENT(BIC_CPU_c1);
5546
5547         if (platform->supported_cstates & CC3)
5548                 BIC_PRESENT(BIC_CPU_c3);
5549
5550         if (platform->supported_cstates & CC6)
5551                 BIC_PRESENT(BIC_CPU_c6);
5552
5553         if (platform->supported_cstates & CC7)
5554                 BIC_PRESENT(BIC_CPU_c7);
5555
5556         if (platform->supported_cstates & PC2 && (pkg_cstate_limit >= PCL__2))
5557                 BIC_PRESENT(BIC_Pkgpc2);
5558
5559         if (platform->supported_cstates & PC3 && (pkg_cstate_limit >= PCL__3))
5560                 BIC_PRESENT(BIC_Pkgpc3);
5561
5562         if (platform->supported_cstates & PC6 && (pkg_cstate_limit >= PCL__6))
5563                 BIC_PRESENT(BIC_Pkgpc6);
5564
5565         if (platform->supported_cstates & PC7 && (pkg_cstate_limit >= PCL__7))
5566                 BIC_PRESENT(BIC_Pkgpc7);
5567
5568         if (platform->supported_cstates & PC8 && (pkg_cstate_limit >= PCL__8))
5569                 BIC_PRESENT(BIC_Pkgpc8);
5570
5571         if (platform->supported_cstates & PC9 && (pkg_cstate_limit >= PCL__9))
5572                 BIC_PRESENT(BIC_Pkgpc9);
5573
5574         if (platform->supported_cstates & PC10 && (pkg_cstate_limit >= PCL_10))
5575                 BIC_PRESENT(BIC_Pkgpc10);
5576
5577         if (platform->has_msr_module_c6_res_ms)
5578                 BIC_PRESENT(BIC_Mod_c6);
5579
5580         if (platform->has_ext_cst_msrs) {
5581                 BIC_PRESENT(BIC_Totl_c0);
5582                 BIC_PRESENT(BIC_Any_c0);
5583                 BIC_PRESENT(BIC_GFX_c0);
5584                 BIC_PRESENT(BIC_CPUGFX);
5585         }
5586
5587         if (quiet)
5588                 return;
5589
5590         dump_power_ctl();
5591         dump_cst_cfg();
5592         decode_c6_demotion_policy_msr();
5593         print_dev_latency();
5594         dump_sysfs_cstate_config();
5595         print_irtl();
5596 }
5597
5598 void probe_lpi(void)
5599 {
5600         if (!access("/sys/devices/system/cpu/cpuidle/low_power_idle_cpu_residency_us", R_OK))
5601                 BIC_PRESENT(BIC_CPU_LPI);
5602         else
5603                 BIC_NOT_PRESENT(BIC_CPU_LPI);
5604
5605         if (!access(sys_lpi_file_sysfs, R_OK)) {
5606                 sys_lpi_file = sys_lpi_file_sysfs;
5607                 BIC_PRESENT(BIC_SYS_LPI);
5608         } else if (!access(sys_lpi_file_debugfs, R_OK)) {
5609                 sys_lpi_file = sys_lpi_file_debugfs;
5610                 BIC_PRESENT(BIC_SYS_LPI);
5611         } else {
5612                 sys_lpi_file_sysfs = NULL;
5613                 BIC_NOT_PRESENT(BIC_SYS_LPI);
5614         }
5615
5616 }
5617
5618 void probe_pstates(void)
5619 {
5620         probe_bclk();
5621
5622         if (quiet)
5623                 return;
5624
5625         dump_platform_info();
5626         dump_turbo_ratio_info();
5627         dump_sysfs_pstate_config();
5628         decode_misc_pwr_mgmt_msr();
5629
5630         for_all_cpus(print_hwp, ODD_COUNTERS);
5631         for_all_cpus(print_epb, ODD_COUNTERS);
5632         for_all_cpus(print_perf_limit, ODD_COUNTERS);
5633 }
5634
5635 void process_cpuid()
5636 {
5637         unsigned int eax, ebx, ecx, edx;
5638         unsigned int fms, family, model, stepping, ecx_flags, edx_flags;
5639         unsigned long long ucode_patch = 0;
5640
5641         eax = ebx = ecx = edx = 0;
5642
5643         __cpuid(0, max_level, ebx, ecx, edx);
5644
5645         if (ebx == 0x756e6547 && ecx == 0x6c65746e && edx == 0x49656e69)
5646                 genuine_intel = 1;
5647         else if (ebx == 0x68747541 && ecx == 0x444d4163 && edx == 0x69746e65)
5648                 authentic_amd = 1;
5649         else if (ebx == 0x6f677948 && ecx == 0x656e6975 && edx == 0x6e65476e)
5650                 hygon_genuine = 1;
5651
5652         if (!quiet)
5653                 fprintf(outf, "CPUID(0): %.4s%.4s%.4s 0x%x CPUID levels\n",
5654                         (char *)&ebx, (char *)&edx, (char *)&ecx, max_level);
5655
5656         __cpuid(1, fms, ebx, ecx, edx);
5657         family = (fms >> 8) & 0xf;
5658         model = (fms >> 4) & 0xf;
5659         stepping = fms & 0xf;
5660         if (family == 0xf)
5661                 family += (fms >> 20) & 0xff;
5662         if (family >= 6)
5663                 model += ((fms >> 16) & 0xf) << 4;
5664         ecx_flags = ecx;
5665         edx_flags = edx;
5666
5667         if (get_msr(sched_getcpu(), MSR_IA32_UCODE_REV, &ucode_patch))
5668                 warnx("get_msr(UCODE)");
5669
5670         /*
5671          * check max extended function levels of CPUID.
5672          * This is needed to check for invariant TSC.
5673          * This check is valid for both Intel and AMD.
5674          */
5675         ebx = ecx = edx = 0;
5676         __cpuid(0x80000000, max_extended_level, ebx, ecx, edx);
5677
5678         if (!quiet) {
5679                 fprintf(outf, "CPUID(1): family:model:stepping 0x%x:%x:%x (%d:%d:%d) microcode 0x%x\n",
5680                         family, model, stepping, family, model, stepping,
5681                         (unsigned int)((ucode_patch >> 32) & 0xFFFFFFFF));
5682                 fprintf(outf, "CPUID(0x80000000): max_extended_levels: 0x%x\n", max_extended_level);
5683                 fprintf(outf, "CPUID(1): %s %s %s %s %s %s %s %s %s %s\n",
5684                         ecx_flags & (1 << 0) ? "SSE3" : "-",
5685                         ecx_flags & (1 << 3) ? "MONITOR" : "-",
5686                         ecx_flags & (1 << 6) ? "SMX" : "-",
5687                         ecx_flags & (1 << 7) ? "EIST" : "-",
5688                         ecx_flags & (1 << 8) ? "TM2" : "-",
5689                         edx_flags & (1 << 4) ? "TSC" : "-",
5690                         edx_flags & (1 << 5) ? "MSR" : "-",
5691                         edx_flags & (1 << 22) ? "ACPI-TM" : "-",
5692                         edx_flags & (1 << 28) ? "HT" : "-", edx_flags & (1 << 29) ? "TM" : "-");
5693         }
5694
5695         probe_platform_features(family, model);
5696
5697         if (!(edx_flags & (1 << 5)))
5698                 errx(1, "CPUID: no MSR");
5699
5700         if (max_extended_level >= 0x80000007) {
5701
5702                 /*
5703                  * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
5704                  * this check is valid for both Intel and AMD
5705                  */
5706                 __cpuid(0x80000007, eax, ebx, ecx, edx);
5707                 has_invariant_tsc = edx & (1 << 8);
5708         }
5709
5710         /*
5711          * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
5712          * this check is valid for both Intel and AMD
5713          */
5714
5715         __cpuid(0x6, eax, ebx, ecx, edx);
5716         has_aperf = ecx & (1 << 0);
5717         if (has_aperf) {
5718                 BIC_PRESENT(BIC_Avg_MHz);
5719                 BIC_PRESENT(BIC_Busy);
5720                 BIC_PRESENT(BIC_Bzy_MHz);
5721         }
5722         do_dts = eax & (1 << 0);
5723         if (do_dts)
5724                 BIC_PRESENT(BIC_CoreTmp);
5725         has_turbo = eax & (1 << 1);
5726         do_ptm = eax & (1 << 6);
5727         if (do_ptm)
5728                 BIC_PRESENT(BIC_PkgTmp);
5729         has_hwp = eax & (1 << 7);
5730         has_hwp_notify = eax & (1 << 8);
5731         has_hwp_activity_window = eax & (1 << 9);
5732         has_hwp_epp = eax & (1 << 10);
5733         has_hwp_pkg = eax & (1 << 11);
5734         has_epb = ecx & (1 << 3);
5735
5736         if (!quiet)
5737                 fprintf(outf, "CPUID(6): %sAPERF, %sTURBO, %sDTS, %sPTM, %sHWP, "
5738                         "%sHWPnotify, %sHWPwindow, %sHWPepp, %sHWPpkg, %sEPB\n",
5739                         has_aperf ? "" : "No-",
5740                         has_turbo ? "" : "No-",
5741                         do_dts ? "" : "No-",
5742                         do_ptm ? "" : "No-",
5743                         has_hwp ? "" : "No-",
5744                         has_hwp_notify ? "" : "No-",
5745                         has_hwp_activity_window ? "" : "No-",
5746                         has_hwp_epp ? "" : "No-", has_hwp_pkg ? "" : "No-", has_epb ? "" : "No-");
5747
5748         if (!quiet)
5749                 decode_misc_enable_msr();
5750
5751         if (max_level >= 0x7 && !quiet) {
5752                 int has_sgx;
5753
5754                 ecx = 0;
5755
5756                 __cpuid_count(0x7, 0, eax, ebx, ecx, edx);
5757
5758                 has_sgx = ebx & (1 << 2);
5759
5760                 is_hybrid = edx & (1 << 15);
5761
5762                 fprintf(outf, "CPUID(7): %sSGX %sHybrid\n", has_sgx ? "" : "No-", is_hybrid ? "" : "No-");
5763
5764                 if (has_sgx)
5765                         decode_feature_control_msr();
5766         }
5767
5768         if (max_level >= 0x15) {
5769                 unsigned int eax_crystal;
5770                 unsigned int ebx_tsc;
5771
5772                 /*
5773                  * CPUID 15H TSC/Crystal ratio, possibly Crystal Hz
5774                  */
5775                 eax_crystal = ebx_tsc = crystal_hz = edx = 0;
5776                 __cpuid(0x15, eax_crystal, ebx_tsc, crystal_hz, edx);
5777
5778                 if (ebx_tsc != 0) {
5779                         if (!quiet && (ebx != 0))
5780                                 fprintf(outf, "CPUID(0x15): eax_crystal: %d ebx_tsc: %d ecx_crystal_hz: %d\n",
5781                                         eax_crystal, ebx_tsc, crystal_hz);
5782
5783                         if (crystal_hz == 0)
5784                                 crystal_hz = platform->crystal_freq;
5785
5786                         if (crystal_hz) {
5787                                 tsc_hz = (unsigned long long)crystal_hz *ebx_tsc / eax_crystal;
5788                                 if (!quiet)
5789                                         fprintf(outf, "TSC: %lld MHz (%d Hz * %d / %d / 1000000)\n",
5790                                                 tsc_hz / 1000000, crystal_hz, ebx_tsc, eax_crystal);
5791                         }
5792                 }
5793         }
5794         if (max_level >= 0x16) {
5795                 unsigned int base_mhz, max_mhz, bus_mhz, edx;
5796
5797                 /*
5798                  * CPUID 16H Base MHz, Max MHz, Bus MHz
5799                  */
5800                 base_mhz = max_mhz = bus_mhz = edx = 0;
5801
5802                 __cpuid(0x16, base_mhz, max_mhz, bus_mhz, edx);
5803                 if (!quiet)
5804                         fprintf(outf, "CPUID(0x16): base_mhz: %d max_mhz: %d bus_mhz: %d\n",
5805                                 base_mhz, max_mhz, bus_mhz);
5806         }
5807
5808         if (has_aperf)
5809                 aperf_mperf_multiplier = platform->need_perf_multiplier ? 1024 : 1;
5810
5811         BIC_PRESENT(BIC_IRQ);
5812         BIC_PRESENT(BIC_TSC_MHz);
5813 }
5814
5815 void probe_pm_features(void)
5816 {
5817         probe_pstates();
5818
5819         probe_cstates();
5820
5821         probe_lpi();
5822
5823         probe_intel_uncore_frequency();
5824
5825         probe_graphics();
5826
5827         probe_rapl();
5828
5829         probe_thermal();
5830
5831         if (platform->has_nhm_msrs)
5832                 BIC_PRESENT(BIC_SMI);
5833
5834         if (!quiet)
5835                 decode_misc_feature_control();
5836 }
5837
5838 /*
5839  * in /dev/cpu/ return success for names that are numbers
5840  * ie. filter out ".", "..", "microcode".
5841  */
5842 int dir_filter(const struct dirent *dirp)
5843 {
5844         if (isdigit(dirp->d_name[0]))
5845                 return 1;
5846         else
5847                 return 0;
5848 }
5849
5850 void topology_probe(bool startup)
5851 {
5852         int i;
5853         int max_core_id = 0;
5854         int max_package_id = 0;
5855         int max_die_id = 0;
5856         int max_siblings = 0;
5857
5858         /* Initialize num_cpus, max_cpu_num */
5859         set_max_cpu_num();
5860         topo.num_cpus = 0;
5861         for_all_proc_cpus(count_cpus);
5862         if (!summary_only && topo.num_cpus > 1)
5863                 BIC_PRESENT(BIC_CPU);
5864
5865         if (debug > 1)
5866                 fprintf(outf, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
5867
5868         cpus = calloc(1, (topo.max_cpu_num + 1) * sizeof(struct cpu_topology));
5869         if (cpus == NULL)
5870                 err(1, "calloc cpus");
5871
5872         /*
5873          * Allocate and initialize cpu_present_set
5874          */
5875         cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
5876         if (cpu_present_set == NULL)
5877                 err(3, "CPU_ALLOC");
5878         cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5879         CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
5880         for_all_proc_cpus(mark_cpu_present);
5881
5882         /*
5883          * Allocate and initialize cpu_effective_set
5884          */
5885         cpu_effective_set = CPU_ALLOC((topo.max_cpu_num + 1));
5886         if (cpu_effective_set == NULL)
5887                 err(3, "CPU_ALLOC");
5888         cpu_effective_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5889         CPU_ZERO_S(cpu_effective_setsize, cpu_effective_set);
5890         update_effective_set(startup);
5891
5892         /*
5893          * Allocate and initialize cpu_allowed_set
5894          */
5895         cpu_allowed_set = CPU_ALLOC((topo.max_cpu_num + 1));
5896         if (cpu_allowed_set == NULL)
5897                 err(3, "CPU_ALLOC");
5898         cpu_allowed_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5899         CPU_ZERO_S(cpu_allowed_setsize, cpu_allowed_set);
5900
5901         /*
5902          * Validate and update cpu_allowed_set.
5903          *
5904          * Make sure all cpus in cpu_subset are also in cpu_present_set during startup.
5905          * Give a warning when cpus in cpu_subset become unavailable at runtime.
5906          * Give a warning when cpus are not effective because of cgroup setting.
5907          *
5908          * cpu_allowed_set is the intersection of cpu_present_set/cpu_effective_set/cpu_subset.
5909          */
5910         for (i = 0; i < CPU_SUBSET_MAXCPUS; ++i) {
5911                 if (cpu_subset && !CPU_ISSET_S(i, cpu_subset_size, cpu_subset))
5912                         continue;
5913
5914                 if (!CPU_ISSET_S(i, cpu_present_setsize, cpu_present_set)) {
5915                         if (cpu_subset) {
5916                                 /* cpus in cpu_subset must be in cpu_present_set during startup */
5917                                 if (startup)
5918                                         err(1, "cpu%d not present", i);
5919                                 else
5920                                         fprintf(stderr, "cpu%d not present\n", i);
5921                         }
5922                         continue;
5923                 }
5924
5925                 if (CPU_COUNT_S(cpu_effective_setsize, cpu_effective_set)) {
5926                         if (!CPU_ISSET_S(i, cpu_effective_setsize, cpu_effective_set)) {
5927                                 fprintf(stderr, "cpu%d not effective\n", i);
5928                                 continue;
5929                         }
5930                 }
5931
5932                 CPU_SET_S(i, cpu_allowed_setsize, cpu_allowed_set);
5933         }
5934
5935         if (!CPU_COUNT_S(cpu_allowed_setsize, cpu_allowed_set))
5936                 err(-ENODEV, "No valid cpus found");
5937         sched_setaffinity(0, cpu_allowed_setsize, cpu_allowed_set);
5938
5939         /*
5940          * Allocate and initialize cpu_affinity_set
5941          */
5942         cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
5943         if (cpu_affinity_set == NULL)
5944                 err(3, "CPU_ALLOC");
5945         cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5946         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
5947
5948         for_all_proc_cpus(init_thread_id);
5949
5950         /*
5951          * For online cpus
5952          * find max_core_id, max_package_id
5953          */
5954         for (i = 0; i <= topo.max_cpu_num; ++i) {
5955                 int siblings;
5956
5957                 if (cpu_is_not_present(i)) {
5958                         if (debug > 1)
5959                                 fprintf(outf, "cpu%d NOT PRESENT\n", i);
5960                         continue;
5961                 }
5962
5963                 cpus[i].logical_cpu_id = i;
5964
5965                 /* get package information */
5966                 cpus[i].physical_package_id = get_physical_package_id(i);
5967                 if (cpus[i].physical_package_id > max_package_id)
5968                         max_package_id = cpus[i].physical_package_id;
5969
5970                 /* get die information */
5971                 cpus[i].die_id = get_die_id(i);
5972                 if (cpus[i].die_id > max_die_id)
5973                         max_die_id = cpus[i].die_id;
5974
5975                 /* get numa node information */
5976                 cpus[i].physical_node_id = get_physical_node_id(&cpus[i]);
5977                 if (cpus[i].physical_node_id > topo.max_node_num)
5978                         topo.max_node_num = cpus[i].physical_node_id;
5979
5980                 /* get core information */
5981                 cpus[i].physical_core_id = get_core_id(i);
5982                 if (cpus[i].physical_core_id > max_core_id)
5983                         max_core_id = cpus[i].physical_core_id;
5984
5985                 /* get thread information */
5986                 siblings = get_thread_siblings(&cpus[i]);
5987                 if (siblings > max_siblings)
5988                         max_siblings = siblings;
5989                 if (cpus[i].thread_id == 0)
5990                         topo.num_cores++;
5991         }
5992
5993         topo.cores_per_node = max_core_id + 1;
5994         if (debug > 1)
5995                 fprintf(outf, "max_core_id %d, sizing for %d cores per package\n", max_core_id, topo.cores_per_node);
5996         if (!summary_only && topo.cores_per_node > 1)
5997                 BIC_PRESENT(BIC_Core);
5998
5999         topo.num_die = max_die_id + 1;
6000         if (debug > 1)
6001                 fprintf(outf, "max_die_id %d, sizing for %d die\n", max_die_id, topo.num_die);
6002         if (!summary_only && topo.num_die > 1)
6003                 BIC_PRESENT(BIC_Die);
6004
6005         topo.num_packages = max_package_id + 1;
6006         if (debug > 1)
6007                 fprintf(outf, "max_package_id %d, sizing for %d packages\n", max_package_id, topo.num_packages);
6008         if (!summary_only && topo.num_packages > 1)
6009                 BIC_PRESENT(BIC_Package);
6010
6011         set_node_data();
6012         if (debug > 1)
6013                 fprintf(outf, "nodes_per_pkg %d\n", topo.nodes_per_pkg);
6014         if (!summary_only && topo.nodes_per_pkg > 1)
6015                 BIC_PRESENT(BIC_Node);
6016
6017         topo.threads_per_core = max_siblings;
6018         if (debug > 1)
6019                 fprintf(outf, "max_siblings %d\n", max_siblings);
6020
6021         if (debug < 1)
6022                 return;
6023
6024         for (i = 0; i <= topo.max_cpu_num; ++i) {
6025                 if (cpu_is_not_present(i))
6026                         continue;
6027                 fprintf(outf,
6028                         "cpu %d pkg %d die %d node %d lnode %d core %d thread %d\n",
6029                         i, cpus[i].physical_package_id, cpus[i].die_id,
6030                         cpus[i].physical_node_id, cpus[i].logical_node_id, cpus[i].physical_core_id, cpus[i].thread_id);
6031         }
6032
6033 }
6034
6035 void allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
6036 {
6037         int i;
6038         int num_cores = topo.cores_per_node * topo.nodes_per_pkg * topo.num_packages;
6039         int num_threads = topo.threads_per_core * num_cores;
6040
6041         *t = calloc(num_threads, sizeof(struct thread_data));
6042         if (*t == NULL)
6043                 goto error;
6044
6045         for (i = 0; i < num_threads; i++)
6046                 (*t)[i].cpu_id = -1;
6047
6048         *c = calloc(num_cores, sizeof(struct core_data));
6049         if (*c == NULL)
6050                 goto error;
6051
6052         for (i = 0; i < num_cores; i++) {
6053                 (*c)[i].core_id = -1;
6054                 (*c)[i].base_cpu = -1;
6055         }
6056
6057         *p = calloc(topo.num_packages, sizeof(struct pkg_data));
6058         if (*p == NULL)
6059                 goto error;
6060
6061         for (i = 0; i < topo.num_packages; i++) {
6062                 (*p)[i].package_id = i;
6063                 (*p)[i].base_cpu = -1;
6064         }
6065
6066         return;
6067 error:
6068         err(1, "calloc counters");
6069 }
6070
6071 /*
6072  * init_counter()
6073  *
6074  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
6075  */
6076 void init_counter(struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base, int cpu_id)
6077 {
6078         int pkg_id = cpus[cpu_id].physical_package_id;
6079         int node_id = cpus[cpu_id].logical_node_id;
6080         int core_id = cpus[cpu_id].physical_core_id;
6081         int thread_id = cpus[cpu_id].thread_id;
6082         struct thread_data *t;
6083         struct core_data *c;
6084         struct pkg_data *p;
6085
6086         /* Workaround for systems where physical_node_id==-1
6087          * and logical_node_id==(-1 - topo.num_cpus)
6088          */
6089         if (node_id < 0)
6090                 node_id = 0;
6091
6092         t = GET_THREAD(thread_base, thread_id, core_id, node_id, pkg_id);
6093         c = GET_CORE(core_base, core_id, node_id, pkg_id);
6094         p = GET_PKG(pkg_base, pkg_id);
6095
6096         t->cpu_id = cpu_id;
6097         if (!cpu_is_not_allowed(cpu_id)) {
6098                 if (c->base_cpu < 0)
6099                         c->base_cpu = t->cpu_id;
6100                 if (p->base_cpu < 0)
6101                         p->base_cpu = t->cpu_id;
6102         }
6103
6104         c->core_id = core_id;
6105         p->package_id = pkg_id;
6106 }
6107
6108 int initialize_counters(int cpu_id)
6109 {
6110         init_counter(EVEN_COUNTERS, cpu_id);
6111         init_counter(ODD_COUNTERS, cpu_id);
6112         return 0;
6113 }
6114
6115 void allocate_output_buffer()
6116 {
6117         output_buffer = calloc(1, (1 + topo.num_cpus) * 2048);
6118         outp = output_buffer;
6119         if (outp == NULL)
6120                 err(-1, "calloc output buffer");
6121 }
6122
6123 void allocate_fd_percpu(void)
6124 {
6125         fd_percpu = calloc(topo.max_cpu_num + 1, sizeof(int));
6126         if (fd_percpu == NULL)
6127                 err(-1, "calloc fd_percpu");
6128 }
6129
6130 void allocate_irq_buffers(void)
6131 {
6132         irq_column_2_cpu = calloc(topo.num_cpus, sizeof(int));
6133         if (irq_column_2_cpu == NULL)
6134                 err(-1, "calloc %d", topo.num_cpus);
6135
6136         irqs_per_cpu = calloc(topo.max_cpu_num + 1, sizeof(int));
6137         if (irqs_per_cpu == NULL)
6138                 err(-1, "calloc %d", topo.max_cpu_num + 1);
6139 }
6140
6141 int update_topo(struct thread_data *t, struct core_data *c, struct pkg_data *p)
6142 {
6143         topo.allowed_cpus++;
6144         if ((int)t->cpu_id == c->base_cpu)
6145                 topo.allowed_cores++;
6146         if ((int)t->cpu_id == p->base_cpu)
6147                 topo.allowed_packages++;
6148
6149         return 0;
6150 }
6151
6152 void topology_update(void)
6153 {
6154         topo.allowed_cpus = 0;
6155         topo.allowed_cores = 0;
6156         topo.allowed_packages = 0;
6157         for_all_cpus(update_topo, ODD_COUNTERS);
6158 }
6159
6160 void setup_all_buffers(bool startup)
6161 {
6162         topology_probe(startup);
6163         allocate_irq_buffers();
6164         allocate_fd_percpu();
6165         allocate_counters(&thread_even, &core_even, &package_even);
6166         allocate_counters(&thread_odd, &core_odd, &package_odd);
6167         allocate_output_buffer();
6168         for_all_proc_cpus(initialize_counters);
6169         topology_update();
6170 }
6171
6172 void set_base_cpu(void)
6173 {
6174         int i;
6175
6176         for (i = 0; i < topo.max_cpu_num + 1; ++i) {
6177                 if (cpu_is_not_allowed(i))
6178                         continue;
6179                 base_cpu = i;
6180                 if (debug > 1)
6181                         fprintf(outf, "base_cpu = %d\n", base_cpu);
6182                 return;
6183         }
6184         err(-ENODEV, "No valid cpus found");
6185 }
6186
6187 void turbostat_init()
6188 {
6189         setup_all_buffers(true);
6190         set_base_cpu();
6191         check_dev_msr();
6192         check_permissions();
6193         process_cpuid();
6194         probe_pm_features();
6195         linux_perf_init();
6196
6197         for_all_cpus(get_cpu_type, ODD_COUNTERS);
6198         for_all_cpus(get_cpu_type, EVEN_COUNTERS);
6199
6200         if (DO_BIC(BIC_IPC))
6201                 (void)get_instr_count_fd(base_cpu);
6202 }
6203
6204 int fork_it(char **argv)
6205 {
6206         pid_t child_pid;
6207         int status;
6208
6209         snapshot_proc_sysfs_files();
6210         status = for_all_cpus(get_counters, EVEN_COUNTERS);
6211         first_counter_read = 0;
6212         if (status)
6213                 exit(status);
6214         gettimeofday(&tv_even, (struct timezone *)NULL);
6215
6216         child_pid = fork();
6217         if (!child_pid) {
6218                 /* child */
6219                 execvp(argv[0], argv);
6220                 err(errno, "exec %s", argv[0]);
6221         } else {
6222
6223                 /* parent */
6224                 if (child_pid == -1)
6225                         err(1, "fork");
6226
6227                 signal(SIGINT, SIG_IGN);
6228                 signal(SIGQUIT, SIG_IGN);
6229                 if (waitpid(child_pid, &status, 0) == -1)
6230                         err(status, "waitpid");
6231
6232                 if (WIFEXITED(status))
6233                         status = WEXITSTATUS(status);
6234         }
6235         /*
6236          * n.b. fork_it() does not check for errors from for_all_cpus()
6237          * because re-starting is problematic when forking
6238          */
6239         snapshot_proc_sysfs_files();
6240         for_all_cpus(get_counters, ODD_COUNTERS);
6241         gettimeofday(&tv_odd, (struct timezone *)NULL);
6242         timersub(&tv_odd, &tv_even, &tv_delta);
6243         if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS))
6244                 fprintf(outf, "%s: Counter reset detected\n", progname);
6245         else {
6246                 compute_average(EVEN_COUNTERS);
6247                 format_all_counters(EVEN_COUNTERS);
6248         }
6249
6250         fprintf(outf, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec / 1000000.0);
6251
6252         flush_output_stderr();
6253
6254         return status;
6255 }
6256
6257 int get_and_dump_counters(void)
6258 {
6259         int status;
6260
6261         snapshot_proc_sysfs_files();
6262         status = for_all_cpus(get_counters, ODD_COUNTERS);
6263         if (status)
6264                 return status;
6265
6266         status = for_all_cpus(dump_counters, ODD_COUNTERS);
6267         if (status)
6268                 return status;
6269
6270         flush_output_stdout();
6271
6272         return status;
6273 }
6274
6275 void print_version()
6276 {
6277         fprintf(outf, "turbostat version 2023.11.07 - Len Brown <lenb@kernel.org>\n");
6278 }
6279
6280 #define COMMAND_LINE_SIZE 2048
6281
6282 void print_bootcmd(void)
6283 {
6284         char bootcmd[COMMAND_LINE_SIZE];
6285         FILE *fp;
6286         int ret;
6287
6288         memset(bootcmd, 0, COMMAND_LINE_SIZE);
6289         fp = fopen("/proc/cmdline", "r");
6290         if (!fp)
6291                 return;
6292
6293         ret = fread(bootcmd, sizeof(char), COMMAND_LINE_SIZE - 1, fp);
6294         if (ret) {
6295                 bootcmd[ret] = '\0';
6296                 /* the last character is already '\n' */
6297                 fprintf(outf, "Kernel command line: %s", bootcmd);
6298         }
6299
6300         fclose(fp);
6301 }
6302
6303 int add_counter(unsigned int msr_num, char *path, char *name,
6304                 unsigned int width, enum counter_scope scope,
6305                 enum counter_type type, enum counter_format format, int flags)
6306 {
6307         struct msr_counter *msrp;
6308
6309         msrp = calloc(1, sizeof(struct msr_counter));
6310         if (msrp == NULL) {
6311                 perror("calloc");
6312                 exit(1);
6313         }
6314
6315         msrp->msr_num = msr_num;
6316         strncpy(msrp->name, name, NAME_BYTES - 1);
6317         if (path)
6318                 strncpy(msrp->path, path, PATH_BYTES - 1);
6319         msrp->width = width;
6320         msrp->type = type;
6321         msrp->format = format;
6322         msrp->flags = flags;
6323
6324         switch (scope) {
6325
6326         case SCOPE_CPU:
6327                 msrp->next = sys.tp;
6328                 sys.tp = msrp;
6329                 sys.added_thread_counters++;
6330                 if (sys.added_thread_counters > MAX_ADDED_THREAD_COUNTERS) {
6331                         fprintf(stderr, "exceeded max %d added thread counters\n", MAX_ADDED_COUNTERS);
6332                         exit(-1);
6333                 }
6334                 break;
6335
6336         case SCOPE_CORE:
6337                 msrp->next = sys.cp;
6338                 sys.cp = msrp;
6339                 sys.added_core_counters++;
6340                 if (sys.added_core_counters > MAX_ADDED_COUNTERS) {
6341                         fprintf(stderr, "exceeded max %d added core counters\n", MAX_ADDED_COUNTERS);
6342                         exit(-1);
6343                 }
6344                 break;
6345
6346         case SCOPE_PACKAGE:
6347                 msrp->next = sys.pp;
6348                 sys.pp = msrp;
6349                 sys.added_package_counters++;
6350                 if (sys.added_package_counters > MAX_ADDED_COUNTERS) {
6351                         fprintf(stderr, "exceeded max %d added package counters\n", MAX_ADDED_COUNTERS);
6352                         exit(-1);
6353                 }
6354                 break;
6355         }
6356
6357         return 0;
6358 }
6359
6360 void parse_add_command(char *add_command)
6361 {
6362         int msr_num = 0;
6363         char *path = NULL;
6364         char name_buffer[NAME_BYTES] = "";
6365         int width = 64;
6366         int fail = 0;
6367         enum counter_scope scope = SCOPE_CPU;
6368         enum counter_type type = COUNTER_CYCLES;
6369         enum counter_format format = FORMAT_DELTA;
6370
6371         while (add_command) {
6372
6373                 if (sscanf(add_command, "msr0x%x", &msr_num) == 1)
6374                         goto next;
6375
6376                 if (sscanf(add_command, "msr%d", &msr_num) == 1)
6377                         goto next;
6378
6379                 if (*add_command == '/') {
6380                         path = add_command;
6381                         goto next;
6382                 }
6383
6384                 if (sscanf(add_command, "u%d", &width) == 1) {
6385                         if ((width == 32) || (width == 64))
6386                                 goto next;
6387                         width = 64;
6388                 }
6389                 if (!strncmp(add_command, "cpu", strlen("cpu"))) {
6390                         scope = SCOPE_CPU;
6391                         goto next;
6392                 }
6393                 if (!strncmp(add_command, "core", strlen("core"))) {
6394                         scope = SCOPE_CORE;
6395                         goto next;
6396                 }
6397                 if (!strncmp(add_command, "package", strlen("package"))) {
6398                         scope = SCOPE_PACKAGE;
6399                         goto next;
6400                 }
6401                 if (!strncmp(add_command, "cycles", strlen("cycles"))) {
6402                         type = COUNTER_CYCLES;
6403                         goto next;
6404                 }
6405                 if (!strncmp(add_command, "seconds", strlen("seconds"))) {
6406                         type = COUNTER_SECONDS;
6407                         goto next;
6408                 }
6409                 if (!strncmp(add_command, "usec", strlen("usec"))) {
6410                         type = COUNTER_USEC;
6411                         goto next;
6412                 }
6413                 if (!strncmp(add_command, "raw", strlen("raw"))) {
6414                         format = FORMAT_RAW;
6415                         goto next;
6416                 }
6417                 if (!strncmp(add_command, "delta", strlen("delta"))) {
6418                         format = FORMAT_DELTA;
6419                         goto next;
6420                 }
6421                 if (!strncmp(add_command, "percent", strlen("percent"))) {
6422                         format = FORMAT_PERCENT;
6423                         goto next;
6424                 }
6425
6426                 if (sscanf(add_command, "%18s,%*s", name_buffer) == 1) {        /* 18 < NAME_BYTES */
6427                         char *eos;
6428
6429                         eos = strchr(name_buffer, ',');
6430                         if (eos)
6431                                 *eos = '\0';
6432                         goto next;
6433                 }
6434
6435 next:
6436                 add_command = strchr(add_command, ',');
6437                 if (add_command) {
6438                         *add_command = '\0';
6439                         add_command++;
6440                 }
6441
6442         }
6443         if ((msr_num == 0) && (path == NULL)) {
6444                 fprintf(stderr, "--add: (msrDDD | msr0xXXX | /path_to_counter ) required\n");
6445                 fail++;
6446         }
6447
6448         /* generate default column header */
6449         if (*name_buffer == '\0') {
6450                 if (width == 32)
6451                         sprintf(name_buffer, "M0x%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
6452                 else
6453                         sprintf(name_buffer, "M0X%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
6454         }
6455
6456         if (add_counter(msr_num, path, name_buffer, width, scope, type, format, 0))
6457                 fail++;
6458
6459         if (fail) {
6460                 help();
6461                 exit(1);
6462         }
6463 }
6464
6465 int is_deferred_add(char *name)
6466 {
6467         int i;
6468
6469         for (i = 0; i < deferred_add_index; ++i)
6470                 if (!strcmp(name, deferred_add_names[i]))
6471                         return 1;
6472         return 0;
6473 }
6474
6475 int is_deferred_skip(char *name)
6476 {
6477         int i;
6478
6479         for (i = 0; i < deferred_skip_index; ++i)
6480                 if (!strcmp(name, deferred_skip_names[i]))
6481                         return 1;
6482         return 0;
6483 }
6484
6485 void probe_sysfs(void)
6486 {
6487         char path[64];
6488         char name_buf[16];
6489         FILE *input;
6490         int state;
6491         char *sp;
6492
6493         for (state = 10; state >= 0; --state) {
6494
6495                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name", base_cpu, state);
6496                 input = fopen(path, "r");
6497                 if (input == NULL)
6498                         continue;
6499                 if (!fgets(name_buf, sizeof(name_buf), input))
6500                         err(1, "%s: failed to read file", path);
6501
6502                 /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
6503                 sp = strchr(name_buf, '-');
6504                 if (!sp)
6505                         sp = strchrnul(name_buf, '\n');
6506                 *sp = '%';
6507                 *(sp + 1) = '\0';
6508
6509                 remove_underbar(name_buf);
6510
6511                 fclose(input);
6512
6513                 sprintf(path, "cpuidle/state%d/time", state);
6514
6515                 if (!DO_BIC(BIC_sysfs) && !is_deferred_add(name_buf))
6516                         continue;
6517
6518                 if (is_deferred_skip(name_buf))
6519                         continue;
6520
6521                 add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_USEC, FORMAT_PERCENT, SYSFS_PERCPU);
6522         }
6523
6524         for (state = 10; state >= 0; --state) {
6525
6526                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name", base_cpu, state);
6527                 input = fopen(path, "r");
6528                 if (input == NULL)
6529                         continue;
6530                 if (!fgets(name_buf, sizeof(name_buf), input))
6531                         err(1, "%s: failed to read file", path);
6532                 /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
6533                 sp = strchr(name_buf, '-');
6534                 if (!sp)
6535                         sp = strchrnul(name_buf, '\n');
6536                 *sp = '\0';
6537                 fclose(input);
6538
6539                 remove_underbar(name_buf);
6540
6541                 sprintf(path, "cpuidle/state%d/usage", state);
6542
6543                 if (!DO_BIC(BIC_sysfs) && !is_deferred_add(name_buf))
6544                         continue;
6545
6546                 if (is_deferred_skip(name_buf))
6547                         continue;
6548
6549                 add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_ITEMS, FORMAT_DELTA, SYSFS_PERCPU);
6550         }
6551
6552 }
6553
6554 /*
6555  * parse cpuset with following syntax
6556  * 1,2,4..6,8-10 and set bits in cpu_subset
6557  */
6558 void parse_cpu_command(char *optarg)
6559 {
6560         if (!strcmp(optarg, "core")) {
6561                 if (cpu_subset)
6562                         goto error;
6563                 show_core_only++;
6564                 return;
6565         }
6566         if (!strcmp(optarg, "package")) {
6567                 if (cpu_subset)
6568                         goto error;
6569                 show_pkg_only++;
6570                 return;
6571         }
6572         if (show_core_only || show_pkg_only)
6573                 goto error;
6574
6575         cpu_subset = CPU_ALLOC(CPU_SUBSET_MAXCPUS);
6576         if (cpu_subset == NULL)
6577                 err(3, "CPU_ALLOC");
6578         cpu_subset_size = CPU_ALLOC_SIZE(CPU_SUBSET_MAXCPUS);
6579
6580         CPU_ZERO_S(cpu_subset_size, cpu_subset);
6581
6582         if (parse_cpu_str(optarg, cpu_subset, cpu_subset_size))
6583                 goto error;
6584
6585         return;
6586
6587 error:
6588         fprintf(stderr, "\"--cpu %s\" malformed\n", optarg);
6589         help();
6590         exit(-1);
6591 }
6592
6593 void cmdline(int argc, char **argv)
6594 {
6595         int opt;
6596         int option_index = 0;
6597         static struct option long_options[] = {
6598                 { "add", required_argument, 0, 'a' },
6599                 { "cpu", required_argument, 0, 'c' },
6600                 { "Dump", no_argument, 0, 'D' },
6601                 { "debug", no_argument, 0, 'd' },       /* internal, not documented */
6602                 { "enable", required_argument, 0, 'e' },
6603                 { "interval", required_argument, 0, 'i' },
6604                 { "IPC", no_argument, 0, 'I' },
6605                 { "num_iterations", required_argument, 0, 'n' },
6606                 { "header_iterations", required_argument, 0, 'N' },
6607                 { "help", no_argument, 0, 'h' },
6608                 { "hide", required_argument, 0, 'H' },  // meh, -h taken by --help
6609                 { "Joules", no_argument, 0, 'J' },
6610                 { "list", no_argument, 0, 'l' },
6611                 { "out", required_argument, 0, 'o' },
6612                 { "quiet", no_argument, 0, 'q' },
6613                 { "show", required_argument, 0, 's' },
6614                 { "Summary", no_argument, 0, 'S' },
6615                 { "TCC", required_argument, 0, 'T' },
6616                 { "version", no_argument, 0, 'v' },
6617                 { 0, 0, 0, 0 }
6618         };
6619
6620         progname = argv[0];
6621
6622         while ((opt = getopt_long_only(argc, argv, "+C:c:Dde:hi:Jn:o:qST:v", long_options, &option_index)) != -1) {
6623                 switch (opt) {
6624                 case 'a':
6625                         parse_add_command(optarg);
6626                         break;
6627                 case 'c':
6628                         parse_cpu_command(optarg);
6629                         break;
6630                 case 'D':
6631                         dump_only++;
6632                         break;
6633                 case 'e':
6634                         /* --enable specified counter */
6635                         bic_enabled = bic_enabled | bic_lookup(optarg, SHOW_LIST);
6636                         break;
6637                 case 'd':
6638                         debug++;
6639                         ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
6640                         break;
6641                 case 'H':
6642                         /*
6643                          * --hide: do not show those specified
6644                          *  multiple invocations simply clear more bits in enabled mask
6645                          */
6646                         bic_enabled &= ~bic_lookup(optarg, HIDE_LIST);
6647                         break;
6648                 case 'h':
6649                 default:
6650                         help();
6651                         exit(1);
6652                 case 'i':
6653                         {
6654                                 double interval = strtod(optarg, NULL);
6655
6656                                 if (interval < 0.001) {
6657                                         fprintf(outf, "interval %f seconds is too small\n", interval);
6658                                         exit(2);
6659                                 }
6660
6661                                 interval_tv.tv_sec = interval_ts.tv_sec = interval;
6662                                 interval_tv.tv_usec = (interval - interval_tv.tv_sec) * 1000000;
6663                                 interval_ts.tv_nsec = (interval - interval_ts.tv_sec) * 1000000000;
6664                         }
6665                         break;
6666                 case 'J':
6667                         rapl_joules++;
6668                         break;
6669                 case 'l':
6670                         ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
6671                         list_header_only++;
6672                         quiet++;
6673                         break;
6674                 case 'o':
6675                         outf = fopen_or_die(optarg, "w");
6676                         break;
6677                 case 'q':
6678                         quiet = 1;
6679                         break;
6680                 case 'n':
6681                         num_iterations = strtod(optarg, NULL);
6682
6683                         if (num_iterations <= 0) {
6684                                 fprintf(outf, "iterations %d should be positive number\n", num_iterations);
6685                                 exit(2);
6686                         }
6687                         break;
6688                 case 'N':
6689                         header_iterations = strtod(optarg, NULL);
6690
6691                         if (header_iterations <= 0) {
6692                                 fprintf(outf, "iterations %d should be positive number\n", header_iterations);
6693                                 exit(2);
6694                         }
6695                         break;
6696                 case 's':
6697                         /*
6698                          * --show: show only those specified
6699                          *  The 1st invocation will clear and replace the enabled mask
6700                          *  subsequent invocations can add to it.
6701                          */
6702                         if (shown == 0)
6703                                 bic_enabled = bic_lookup(optarg, SHOW_LIST);
6704                         else
6705                                 bic_enabled |= bic_lookup(optarg, SHOW_LIST);
6706                         shown = 1;
6707                         break;
6708                 case 'S':
6709                         summary_only++;
6710                         break;
6711                 case 'T':
6712                         tj_max_override = atoi(optarg);
6713                         break;
6714                 case 'v':
6715                         print_version();
6716                         exit(0);
6717                         break;
6718                 }
6719         }
6720 }
6721
6722 void set_rlimit(void)
6723 {
6724         struct rlimit limit;
6725
6726         if (getrlimit(RLIMIT_NOFILE, &limit) < 0)
6727                 err(1, "Failed to get rlimit");
6728
6729         if (limit.rlim_max < MAX_NOFILE)
6730                 limit.rlim_max = MAX_NOFILE;
6731         if (limit.rlim_cur < MAX_NOFILE)
6732                 limit.rlim_cur = MAX_NOFILE;
6733
6734         if (setrlimit(RLIMIT_NOFILE, &limit) < 0)
6735                 err(1, "Failed to set rlimit");
6736 }
6737
6738 int main(int argc, char **argv)
6739 {
6740         int fd, ret;
6741
6742         fd = open("/sys/fs/cgroup/cgroup.procs", O_WRONLY);
6743         if (fd < 0)
6744                 goto skip_cgroup_setting;
6745
6746         ret = write(fd, "0\n", 2);
6747         if (ret == -1)
6748                 perror("Can't update cgroup\n");
6749
6750         close(fd);
6751
6752 skip_cgroup_setting:
6753         outf = stderr;
6754         cmdline(argc, argv);
6755
6756         if (!quiet) {
6757                 print_version();
6758                 print_bootcmd();
6759         }
6760
6761         probe_sysfs();
6762
6763         if (!getuid())
6764                 set_rlimit();
6765
6766         turbostat_init();
6767
6768         msr_sum_record();
6769
6770         /* dump counters and exit */
6771         if (dump_only)
6772                 return get_and_dump_counters();
6773
6774         /* list header and exit */
6775         if (list_header_only) {
6776                 print_header(",");
6777                 flush_output_stdout();
6778                 return 0;
6779         }
6780
6781         /*
6782          * if any params left, it must be a command to fork
6783          */
6784         if (argc - optind)
6785                 return fork_it(argv + optind);
6786         else
6787                 turbostat_loop();
6788
6789         return 0;
6790 }