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