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 trl_msr_offset, int family, int model)
2533 {
2534 	unsigned long long msr, core_counts;
2535 	int shift;
2536 
2537 	get_msr(base_cpu, trl_msr_offset, &msr);
2538 	fprintf(outf, "cpu%d: MSR_%sTURBO_RATIO_LIMIT: 0x%08llx\n",
2539 		base_cpu, trl_msr_offset == MSR_SECONDARY_TURBO_RATIO_LIMIT ? "SECONDARY" : "", msr);
2540 
2541 	if (has_turbo_ratio_group_limits(family, model)) {
2542 		get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT1, &core_counts);
2543 		fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT1: 0x%08llx\n", base_cpu, core_counts);
2544 	} else {
2545 		core_counts = 0x0807060504030201;
2546 	}
2547 
2548 	for (shift = 56; shift >= 0; shift -= 8) {
2549 		unsigned int ratio, group_size;
2550 
2551 		ratio = (msr >> shift) & 0xFF;
2552 		group_size = (core_counts >> shift) & 0xFF;
2553 		if (ratio)
2554 			fprintf(outf, "%d * %.1f = %.1f MHz max turbo %d active cores\n",
2555 				ratio, bclk, ratio * bclk, group_size);
2556 	}
2557 
2558 	return;
2559 }
2560 
2561 static void dump_atom_turbo_ratio_limits(void)
2562 {
2563 	unsigned long long msr;
2564 	unsigned int ratio;
2565 
2566 	get_msr(base_cpu, MSR_ATOM_CORE_RATIOS, &msr);
2567 	fprintf(outf, "cpu%d: MSR_ATOM_CORE_RATIOS: 0x%08llx\n", base_cpu, msr & 0xFFFFFFFF);
2568 
2569 	ratio = (msr >> 0) & 0x3F;
2570 	if (ratio)
2571 		fprintf(outf, "%d * %.1f = %.1f MHz minimum operating frequency\n", ratio, bclk, ratio * bclk);
2572 
2573 	ratio = (msr >> 8) & 0x3F;
2574 	if (ratio)
2575 		fprintf(outf, "%d * %.1f = %.1f MHz low frequency mode (LFM)\n", ratio, bclk, ratio * bclk);
2576 
2577 	ratio = (msr >> 16) & 0x3F;
2578 	if (ratio)
2579 		fprintf(outf, "%d * %.1f = %.1f MHz base frequency\n", ratio, bclk, ratio * bclk);
2580 
2581 	get_msr(base_cpu, MSR_ATOM_CORE_TURBO_RATIOS, &msr);
2582 	fprintf(outf, "cpu%d: MSR_ATOM_CORE_TURBO_RATIOS: 0x%08llx\n", base_cpu, msr & 0xFFFFFFFF);
2583 
2584 	ratio = (msr >> 24) & 0x3F;
2585 	if (ratio)
2586 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 4 active cores\n", ratio, bclk, ratio * bclk);
2587 
2588 	ratio = (msr >> 16) & 0x3F;
2589 	if (ratio)
2590 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 3 active cores\n", ratio, bclk, ratio * bclk);
2591 
2592 	ratio = (msr >> 8) & 0x3F;
2593 	if (ratio)
2594 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 2 active cores\n", ratio, bclk, ratio * bclk);
2595 
2596 	ratio = (msr >> 0) & 0x3F;
2597 	if (ratio)
2598 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 1 active core\n", ratio, bclk, ratio * bclk);
2599 }
2600 
2601 static void dump_knl_turbo_ratio_limits(void)
2602 {
2603 	const unsigned int buckets_no = 7;
2604 
2605 	unsigned long long msr;
2606 	int delta_cores, delta_ratio;
2607 	int i, b_nr;
2608 	unsigned int cores[buckets_no];
2609 	unsigned int ratio[buckets_no];
2610 
2611 	get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT, &msr);
2612 
2613 	fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT: 0x%08llx\n", base_cpu, msr);
2614 
2615 	/*
2616 	 * Turbo encoding in KNL is as follows:
2617 	 * [0] -- Reserved
2618 	 * [7:1] -- Base value of number of active cores of bucket 1.
2619 	 * [15:8] -- Base value of freq ratio of bucket 1.
2620 	 * [20:16] -- +ve delta of number of active cores of bucket 2.
2621 	 * i.e. active cores of bucket 2 =
2622 	 * active cores of bucket 1 + delta
2623 	 * [23:21] -- Negative delta of freq ratio of bucket 2.
2624 	 * i.e. freq ratio of bucket 2 =
2625 	 * freq ratio of bucket 1 - delta
2626 	 * [28:24]-- +ve delta of number of active cores of bucket 3.
2627 	 * [31:29]-- -ve delta of freq ratio of bucket 3.
2628 	 * [36:32]-- +ve delta of number of active cores of bucket 4.
2629 	 * [39:37]-- -ve delta of freq ratio of bucket 4.
2630 	 * [44:40]-- +ve delta of number of active cores of bucket 5.
2631 	 * [47:45]-- -ve delta of freq ratio of bucket 5.
2632 	 * [52:48]-- +ve delta of number of active cores of bucket 6.
2633 	 * [55:53]-- -ve delta of freq ratio of bucket 6.
2634 	 * [60:56]-- +ve delta of number of active cores of bucket 7.
2635 	 * [63:61]-- -ve delta of freq ratio of bucket 7.
2636 	 */
2637 
2638 	b_nr = 0;
2639 	cores[b_nr] = (msr & 0xFF) >> 1;
2640 	ratio[b_nr] = (msr >> 8) & 0xFF;
2641 
2642 	for (i = 16; i < 64; i += 8) {
2643 		delta_cores = (msr >> i) & 0x1F;
2644 		delta_ratio = (msr >> (i + 5)) & 0x7;
2645 
2646 		cores[b_nr + 1] = cores[b_nr] + delta_cores;
2647 		ratio[b_nr + 1] = ratio[b_nr] - delta_ratio;
2648 		b_nr++;
2649 	}
2650 
2651 	for (i = buckets_no - 1; i >= 0; i--)
2652 		if (i > 0 ? ratio[i] != ratio[i - 1] : 1)
2653 			fprintf(outf,
2654 				"%d * %.1f = %.1f MHz max turbo %d active cores\n",
2655 				ratio[i], bclk, ratio[i] * bclk, cores[i]);
2656 }
2657 
2658 static void dump_nhm_cst_cfg(void)
2659 {
2660 	unsigned long long msr;
2661 
2662 	get_msr(base_cpu, MSR_PKG_CST_CONFIG_CONTROL, &msr);
2663 
2664 	fprintf(outf, "cpu%d: MSR_PKG_CST_CONFIG_CONTROL: 0x%08llx", base_cpu, msr);
2665 
2666 	fprintf(outf, " (%s%s%s%s%slocked, pkg-cstate-limit=%d (%s)",
2667 		(msr & SNB_C3_AUTO_UNDEMOTE) ? "UNdemote-C3, " : "",
2668 		(msr & SNB_C1_AUTO_UNDEMOTE) ? "UNdemote-C1, " : "",
2669 		(msr & NHM_C3_AUTO_DEMOTE) ? "demote-C3, " : "",
2670 		(msr & NHM_C1_AUTO_DEMOTE) ? "demote-C1, " : "",
2671 		(msr & (1 << 15)) ? "" : "UN", (unsigned int)msr & 0xF, pkg_cstate_limit_strings[pkg_cstate_limit]);
2672 
2673 #define AUTOMATIC_CSTATE_CONVERSION		(1UL << 16)
2674 	if (has_automatic_cstate_conversion) {
2675 		fprintf(outf, ", automatic c-state conversion=%s", (msr & AUTOMATIC_CSTATE_CONVERSION) ? "on" : "off");
2676 	}
2677 
2678 	fprintf(outf, ")\n");
2679 
2680 	return;
2681 }
2682 
2683 static void dump_config_tdp(void)
2684 {
2685 	unsigned long long msr;
2686 
2687 	get_msr(base_cpu, MSR_CONFIG_TDP_NOMINAL, &msr);
2688 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_NOMINAL: 0x%08llx", base_cpu, msr);
2689 	fprintf(outf, " (base_ratio=%d)\n", (unsigned int)msr & 0xFF);
2690 
2691 	get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_1, &msr);
2692 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_LEVEL_1: 0x%08llx (", base_cpu, msr);
2693 	if (msr) {
2694 		fprintf(outf, "PKG_MIN_PWR_LVL1=%d ", (unsigned int)(msr >> 48) & 0x7FFF);
2695 		fprintf(outf, "PKG_MAX_PWR_LVL1=%d ", (unsigned int)(msr >> 32) & 0x7FFF);
2696 		fprintf(outf, "LVL1_RATIO=%d ", (unsigned int)(msr >> 16) & 0xFF);
2697 		fprintf(outf, "PKG_TDP_LVL1=%d", (unsigned int)(msr) & 0x7FFF);
2698 	}
2699 	fprintf(outf, ")\n");
2700 
2701 	get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_2, &msr);
2702 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_LEVEL_2: 0x%08llx (", base_cpu, msr);
2703 	if (msr) {
2704 		fprintf(outf, "PKG_MIN_PWR_LVL2=%d ", (unsigned int)(msr >> 48) & 0x7FFF);
2705 		fprintf(outf, "PKG_MAX_PWR_LVL2=%d ", (unsigned int)(msr >> 32) & 0x7FFF);
2706 		fprintf(outf, "LVL2_RATIO=%d ", (unsigned int)(msr >> 16) & 0xFF);
2707 		fprintf(outf, "PKG_TDP_LVL2=%d", (unsigned int)(msr) & 0x7FFF);
2708 	}
2709 	fprintf(outf, ")\n");
2710 
2711 	get_msr(base_cpu, MSR_CONFIG_TDP_CONTROL, &msr);
2712 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_CONTROL: 0x%08llx (", base_cpu, msr);
2713 	if ((msr) & 0x3)
2714 		fprintf(outf, "TDP_LEVEL=%d ", (unsigned int)(msr) & 0x3);
2715 	fprintf(outf, " lock=%d", (unsigned int)(msr >> 31) & 1);
2716 	fprintf(outf, ")\n");
2717 
2718 	get_msr(base_cpu, MSR_TURBO_ACTIVATION_RATIO, &msr);
2719 	fprintf(outf, "cpu%d: MSR_TURBO_ACTIVATION_RATIO: 0x%08llx (", base_cpu, msr);
2720 	fprintf(outf, "MAX_NON_TURBO_RATIO=%d", (unsigned int)(msr) & 0xFF);
2721 	fprintf(outf, " lock=%d", (unsigned int)(msr >> 31) & 1);
2722 	fprintf(outf, ")\n");
2723 }
2724 
2725 unsigned int irtl_time_units[] = { 1, 32, 1024, 32768, 1048576, 33554432, 0, 0 };
2726 
2727 void print_irtl(void)
2728 {
2729 	unsigned long long msr;
2730 
2731 	get_msr(base_cpu, MSR_PKGC3_IRTL, &msr);
2732 	fprintf(outf, "cpu%d: MSR_PKGC3_IRTL: 0x%08llx (", base_cpu, msr);
2733 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2734 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2735 
2736 	get_msr(base_cpu, MSR_PKGC6_IRTL, &msr);
2737 	fprintf(outf, "cpu%d: MSR_PKGC6_IRTL: 0x%08llx (", base_cpu, msr);
2738 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2739 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2740 
2741 	get_msr(base_cpu, MSR_PKGC7_IRTL, &msr);
2742 	fprintf(outf, "cpu%d: MSR_PKGC7_IRTL: 0x%08llx (", base_cpu, msr);
2743 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2744 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2745 
2746 	if (!do_irtl_hsw)
2747 		return;
2748 
2749 	get_msr(base_cpu, MSR_PKGC8_IRTL, &msr);
2750 	fprintf(outf, "cpu%d: MSR_PKGC8_IRTL: 0x%08llx (", base_cpu, msr);
2751 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2752 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2753 
2754 	get_msr(base_cpu, MSR_PKGC9_IRTL, &msr);
2755 	fprintf(outf, "cpu%d: MSR_PKGC9_IRTL: 0x%08llx (", base_cpu, msr);
2756 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2757 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2758 
2759 	get_msr(base_cpu, MSR_PKGC10_IRTL, &msr);
2760 	fprintf(outf, "cpu%d: MSR_PKGC10_IRTL: 0x%08llx (", base_cpu, msr);
2761 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
2762 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
2763 
2764 }
2765 
2766 void free_fd_percpu(void)
2767 {
2768 	int i;
2769 
2770 	for (i = 0; i < topo.max_cpu_num + 1; ++i) {
2771 		if (fd_percpu[i] != 0)
2772 			close(fd_percpu[i]);
2773 	}
2774 
2775 	free(fd_percpu);
2776 }
2777 
2778 void free_all_buffers(void)
2779 {
2780 	int i;
2781 
2782 	CPU_FREE(cpu_present_set);
2783 	cpu_present_set = NULL;
2784 	cpu_present_setsize = 0;
2785 
2786 	CPU_FREE(cpu_affinity_set);
2787 	cpu_affinity_set = NULL;
2788 	cpu_affinity_setsize = 0;
2789 
2790 	free(thread_even);
2791 	free(core_even);
2792 	free(package_even);
2793 
2794 	thread_even = NULL;
2795 	core_even = NULL;
2796 	package_even = NULL;
2797 
2798 	free(thread_odd);
2799 	free(core_odd);
2800 	free(package_odd);
2801 
2802 	thread_odd = NULL;
2803 	core_odd = NULL;
2804 	package_odd = NULL;
2805 
2806 	free(output_buffer);
2807 	output_buffer = NULL;
2808 	outp = NULL;
2809 
2810 	free_fd_percpu();
2811 
2812 	free(irq_column_2_cpu);
2813 	free(irqs_per_cpu);
2814 
2815 	for (i = 0; i <= topo.max_cpu_num; ++i) {
2816 		if (cpus[i].put_ids)
2817 			CPU_FREE(cpus[i].put_ids);
2818 	}
2819 	free(cpus);
2820 }
2821 
2822 /*
2823  * Parse a file containing a single int.
2824  * Return 0 if file can not be opened
2825  * Exit if file can be opened, but can not be parsed
2826  */
2827 int parse_int_file(const char *fmt, ...)
2828 {
2829 	va_list args;
2830 	char path[PATH_MAX];
2831 	FILE *filep;
2832 	int value;
2833 
2834 	va_start(args, fmt);
2835 	vsnprintf(path, sizeof(path), fmt, args);
2836 	va_end(args);
2837 	filep = fopen(path, "r");
2838 	if (!filep)
2839 		return 0;
2840 	if (fscanf(filep, "%d", &value) != 1)
2841 		err(1, "%s: failed to parse number from file", path);
2842 	fclose(filep);
2843 	return value;
2844 }
2845 
2846 /*
2847  * cpu_is_first_core_in_package(cpu)
2848  * return 1 if given CPU is 1st core in package
2849  */
2850 int cpu_is_first_core_in_package(int cpu)
2851 {
2852 	return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
2853 }
2854 
2855 int get_physical_package_id(int cpu)
2856 {
2857 	return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
2858 }
2859 
2860 int get_die_id(int cpu)
2861 {
2862 	return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/die_id", cpu);
2863 }
2864 
2865 int get_core_id(int cpu)
2866 {
2867 	return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
2868 }
2869 
2870 void set_node_data(void)
2871 {
2872 	int pkg, node, lnode, cpu, cpux;
2873 	int cpu_count;
2874 
2875 	/* initialize logical_node_id */
2876 	for (cpu = 0; cpu <= topo.max_cpu_num; ++cpu)
2877 		cpus[cpu].logical_node_id = -1;
2878 
2879 	cpu_count = 0;
2880 	for (pkg = 0; pkg < topo.num_packages; pkg++) {
2881 		lnode = 0;
2882 		for (cpu = 0; cpu <= topo.max_cpu_num; ++cpu) {
2883 			if (cpus[cpu].physical_package_id != pkg)
2884 				continue;
2885 			/* find a cpu with an unset logical_node_id */
2886 			if (cpus[cpu].logical_node_id != -1)
2887 				continue;
2888 			cpus[cpu].logical_node_id = lnode;
2889 			node = cpus[cpu].physical_node_id;
2890 			cpu_count++;
2891 			/*
2892 			 * find all matching cpus on this pkg and set
2893 			 * the logical_node_id
2894 			 */
2895 			for (cpux = cpu; cpux <= topo.max_cpu_num; cpux++) {
2896 				if ((cpus[cpux].physical_package_id == pkg) && (cpus[cpux].physical_node_id == node)) {
2897 					cpus[cpux].logical_node_id = lnode;
2898 					cpu_count++;
2899 				}
2900 			}
2901 			lnode++;
2902 			if (lnode > topo.nodes_per_pkg)
2903 				topo.nodes_per_pkg = lnode;
2904 		}
2905 		if (cpu_count >= topo.max_cpu_num)
2906 			break;
2907 	}
2908 }
2909 
2910 int get_physical_node_id(struct cpu_topology *thiscpu)
2911 {
2912 	char path[80];
2913 	FILE *filep;
2914 	int i;
2915 	int cpu = thiscpu->logical_cpu_id;
2916 
2917 	for (i = 0; i <= topo.max_cpu_num; i++) {
2918 		sprintf(path, "/sys/devices/system/cpu/cpu%d/node%i/cpulist", cpu, i);
2919 		filep = fopen(path, "r");
2920 		if (!filep)
2921 			continue;
2922 		fclose(filep);
2923 		return i;
2924 	}
2925 	return -1;
2926 }
2927 
2928 int get_thread_siblings(struct cpu_topology *thiscpu)
2929 {
2930 	char path[80], character;
2931 	FILE *filep;
2932 	unsigned long map;
2933 	int so, shift, sib_core;
2934 	int cpu = thiscpu->logical_cpu_id;
2935 	int offset = topo.max_cpu_num + 1;
2936 	size_t size;
2937 	int thread_id = 0;
2938 
2939 	thiscpu->put_ids = CPU_ALLOC((topo.max_cpu_num + 1));
2940 	if (thiscpu->thread_id < 0)
2941 		thiscpu->thread_id = thread_id++;
2942 	if (!thiscpu->put_ids)
2943 		return -1;
2944 
2945 	size = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
2946 	CPU_ZERO_S(size, thiscpu->put_ids);
2947 
2948 	sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings", cpu);
2949 	filep = fopen(path, "r");
2950 
2951 	if (!filep) {
2952 		warnx("%s: open failed", path);
2953 		return -1;
2954 	}
2955 	do {
2956 		offset -= BITMASK_SIZE;
2957 		if (fscanf(filep, "%lx%c", &map, &character) != 2)
2958 			err(1, "%s: failed to parse file", path);
2959 		for (shift = 0; shift < BITMASK_SIZE; shift++) {
2960 			if ((map >> shift) & 0x1) {
2961 				so = shift + offset;
2962 				sib_core = get_core_id(so);
2963 				if (sib_core == thiscpu->physical_core_id) {
2964 					CPU_SET_S(so, size, thiscpu->put_ids);
2965 					if ((so != cpu) && (cpus[so].thread_id < 0))
2966 						cpus[so].thread_id = thread_id++;
2967 				}
2968 			}
2969 		}
2970 	} while (character == ',');
2971 	fclose(filep);
2972 
2973 	return CPU_COUNT_S(size, thiscpu->put_ids);
2974 }
2975 
2976 /*
2977  * run func(thread, core, package) in topology order
2978  * skip non-present cpus
2979  */
2980 
2981 int for_all_cpus_2(int (func) (struct thread_data *, struct core_data *,
2982 			       struct pkg_data *, struct thread_data *, struct core_data *,
2983 			       struct pkg_data *), struct thread_data *thread_base,
2984 		   struct core_data *core_base, struct pkg_data *pkg_base,
2985 		   struct thread_data *thread_base2, struct core_data *core_base2, struct pkg_data *pkg_base2)
2986 {
2987 	int retval, pkg_no, node_no, core_no, thread_no;
2988 
2989 	for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
2990 		for (node_no = 0; node_no < topo.nodes_per_pkg; ++node_no) {
2991 			for (core_no = 0; core_no < topo.cores_per_node; ++core_no) {
2992 				for (thread_no = 0; thread_no < topo.threads_per_core; ++thread_no) {
2993 					struct thread_data *t, *t2;
2994 					struct core_data *c, *c2;
2995 					struct pkg_data *p, *p2;
2996 
2997 					t = GET_THREAD(thread_base, thread_no, core_no, node_no, pkg_no);
2998 
2999 					if (cpu_is_not_present(t->cpu_id))
3000 						continue;
3001 
3002 					t2 = GET_THREAD(thread_base2, thread_no, core_no, node_no, pkg_no);
3003 
3004 					c = GET_CORE(core_base, core_no, node_no, pkg_no);
3005 					c2 = GET_CORE(core_base2, core_no, node_no, pkg_no);
3006 
3007 					p = GET_PKG(pkg_base, pkg_no);
3008 					p2 = GET_PKG(pkg_base2, pkg_no);
3009 
3010 					retval = func(t, c, p, t2, c2, p2);
3011 					if (retval)
3012 						return retval;
3013 				}
3014 			}
3015 		}
3016 	}
3017 	return 0;
3018 }
3019 
3020 /*
3021  * run func(cpu) on every cpu in /proc/stat
3022  * return max_cpu number
3023  */
3024 int for_all_proc_cpus(int (func) (int))
3025 {
3026 	FILE *fp;
3027 	int cpu_num;
3028 	int retval;
3029 
3030 	fp = fopen_or_die(proc_stat, "r");
3031 
3032 	retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
3033 	if (retval != 0)
3034 		err(1, "%s: failed to parse format", proc_stat);
3035 
3036 	while (1) {
3037 		retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
3038 		if (retval != 1)
3039 			break;
3040 
3041 		retval = func(cpu_num);
3042 		if (retval) {
3043 			fclose(fp);
3044 			return (retval);
3045 		}
3046 	}
3047 	fclose(fp);
3048 	return 0;
3049 }
3050 
3051 void re_initialize(void)
3052 {
3053 	free_all_buffers();
3054 	setup_all_buffers();
3055 	fprintf(outf, "turbostat: re-initialized with num_cpus %d\n", topo.num_cpus);
3056 }
3057 
3058 void set_max_cpu_num(void)
3059 {
3060 	FILE *filep;
3061 	int base_cpu;
3062 	unsigned long dummy;
3063 	char pathname[64];
3064 
3065 	base_cpu = sched_getcpu();
3066 	if (base_cpu < 0)
3067 		err(1, "cannot find calling cpu ID");
3068 	sprintf(pathname, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings", base_cpu);
3069 
3070 	filep = fopen_or_die(pathname, "r");
3071 	topo.max_cpu_num = 0;
3072 	while (fscanf(filep, "%lx,", &dummy) == 1)
3073 		topo.max_cpu_num += BITMASK_SIZE;
3074 	fclose(filep);
3075 	topo.max_cpu_num--;	/* 0 based */
3076 }
3077 
3078 /*
3079  * count_cpus()
3080  * remember the last one seen, it will be the max
3081  */
3082 int count_cpus(int cpu)
3083 {
3084 	UNUSED(cpu);
3085 
3086 	topo.num_cpus++;
3087 	return 0;
3088 }
3089 
3090 int mark_cpu_present(int cpu)
3091 {
3092 	CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
3093 	return 0;
3094 }
3095 
3096 int init_thread_id(int cpu)
3097 {
3098 	cpus[cpu].thread_id = -1;
3099 	return 0;
3100 }
3101 
3102 /*
3103  * snapshot_proc_interrupts()
3104  *
3105  * read and record summary of /proc/interrupts
3106  *
3107  * return 1 if config change requires a restart, else return 0
3108  */
3109 int snapshot_proc_interrupts(void)
3110 {
3111 	static FILE *fp;
3112 	int column, retval;
3113 
3114 	if (fp == NULL)
3115 		fp = fopen_or_die("/proc/interrupts", "r");
3116 	else
3117 		rewind(fp);
3118 
3119 	/* read 1st line of /proc/interrupts to get cpu* name for each column */
3120 	for (column = 0; column < topo.num_cpus; ++column) {
3121 		int cpu_number;
3122 
3123 		retval = fscanf(fp, " CPU%d", &cpu_number);
3124 		if (retval != 1)
3125 			break;
3126 
3127 		if (cpu_number > topo.max_cpu_num) {
3128 			warn("/proc/interrupts: cpu%d: > %d", cpu_number, topo.max_cpu_num);
3129 			return 1;
3130 		}
3131 
3132 		irq_column_2_cpu[column] = cpu_number;
3133 		irqs_per_cpu[cpu_number] = 0;
3134 	}
3135 
3136 	/* read /proc/interrupt count lines and sum up irqs per cpu */
3137 	while (1) {
3138 		int column;
3139 		char buf[64];
3140 
3141 		retval = fscanf(fp, " %s:", buf);	/* flush irq# "N:" */
3142 		if (retval != 1)
3143 			break;
3144 
3145 		/* read the count per cpu */
3146 		for (column = 0; column < topo.num_cpus; ++column) {
3147 
3148 			int cpu_number, irq_count;
3149 
3150 			retval = fscanf(fp, " %d", &irq_count);
3151 			if (retval != 1)
3152 				break;
3153 
3154 			cpu_number = irq_column_2_cpu[column];
3155 			irqs_per_cpu[cpu_number] += irq_count;
3156 
3157 		}
3158 
3159 		while (getc(fp) != '\n') ;	/* flush interrupt description */
3160 
3161 	}
3162 	return 0;
3163 }
3164 
3165 /*
3166  * snapshot_gfx_rc6_ms()
3167  *
3168  * record snapshot of
3169  * /sys/class/drm/card0/power/rc6_residency_ms
3170  *
3171  * return 1 if config change requires a restart, else return 0
3172  */
3173 int snapshot_gfx_rc6_ms(void)
3174 {
3175 	FILE *fp;
3176 	int retval;
3177 
3178 	fp = fopen_or_die("/sys/class/drm/card0/power/rc6_residency_ms", "r");
3179 
3180 	retval = fscanf(fp, "%lld", &gfx_cur_rc6_ms);
3181 	if (retval != 1)
3182 		err(1, "GFX rc6");
3183 
3184 	fclose(fp);
3185 
3186 	return 0;
3187 }
3188 
3189 /*
3190  * snapshot_gfx_mhz()
3191  *
3192  * record snapshot of
3193  * /sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz
3194  *
3195  * return 1 if config change requires a restart, else return 0
3196  */
3197 int snapshot_gfx_mhz(void)
3198 {
3199 	static FILE *fp;
3200 	int retval;
3201 
3202 	if (fp == NULL)
3203 		fp = fopen_or_die("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", "r");
3204 	else {
3205 		rewind(fp);
3206 		fflush(fp);
3207 	}
3208 
3209 	retval = fscanf(fp, "%d", &gfx_cur_mhz);
3210 	if (retval != 1)
3211 		err(1, "GFX MHz");
3212 
3213 	return 0;
3214 }
3215 
3216 /*
3217  * snapshot_gfx_cur_mhz()
3218  *
3219  * record snapshot of
3220  * /sys/class/graphics/fb0/device/drm/card0/gt_act_freq_mhz
3221  *
3222  * return 1 if config change requires a restart, else return 0
3223  */
3224 int snapshot_gfx_act_mhz(void)
3225 {
3226 	static FILE *fp;
3227 	int retval;
3228 
3229 	if (fp == NULL)
3230 		fp = fopen_or_die("/sys/class/graphics/fb0/device/drm/card0/gt_act_freq_mhz", "r");
3231 	else {
3232 		rewind(fp);
3233 		fflush(fp);
3234 	}
3235 
3236 	retval = fscanf(fp, "%d", &gfx_act_mhz);
3237 	if (retval != 1)
3238 		err(1, "GFX ACT MHz");
3239 
3240 	return 0;
3241 }
3242 
3243 /*
3244  * snapshot_cpu_lpi()
3245  *
3246  * record snapshot of
3247  * /sys/devices/system/cpu/cpuidle/low_power_idle_cpu_residency_us
3248  */
3249 int snapshot_cpu_lpi_us(void)
3250 {
3251 	FILE *fp;
3252 	int retval;
3253 
3254 	fp = fopen_or_die("/sys/devices/system/cpu/cpuidle/low_power_idle_cpu_residency_us", "r");
3255 
3256 	retval = fscanf(fp, "%lld", &cpuidle_cur_cpu_lpi_us);
3257 	if (retval != 1) {
3258 		fprintf(stderr, "Disabling Low Power Idle CPU output\n");
3259 		BIC_NOT_PRESENT(BIC_CPU_LPI);
3260 		fclose(fp);
3261 		return -1;
3262 	}
3263 
3264 	fclose(fp);
3265 
3266 	return 0;
3267 }
3268 
3269 /*
3270  * snapshot_sys_lpi()
3271  *
3272  * record snapshot of sys_lpi_file
3273  */
3274 int snapshot_sys_lpi_us(void)
3275 {
3276 	FILE *fp;
3277 	int retval;
3278 
3279 	fp = fopen_or_die(sys_lpi_file, "r");
3280 
3281 	retval = fscanf(fp, "%lld", &cpuidle_cur_sys_lpi_us);
3282 	if (retval != 1) {
3283 		fprintf(stderr, "Disabling Low Power Idle System output\n");
3284 		BIC_NOT_PRESENT(BIC_SYS_LPI);
3285 		fclose(fp);
3286 		return -1;
3287 	}
3288 	fclose(fp);
3289 
3290 	return 0;
3291 }
3292 
3293 /*
3294  * snapshot /proc and /sys files
3295  *
3296  * return 1 if configuration restart needed, else return 0
3297  */
3298 int snapshot_proc_sysfs_files(void)
3299 {
3300 	if (DO_BIC(BIC_IRQ))
3301 		if (snapshot_proc_interrupts())
3302 			return 1;
3303 
3304 	if (DO_BIC(BIC_GFX_rc6))
3305 		snapshot_gfx_rc6_ms();
3306 
3307 	if (DO_BIC(BIC_GFXMHz))
3308 		snapshot_gfx_mhz();
3309 
3310 	if (DO_BIC(BIC_GFXACTMHz))
3311 		snapshot_gfx_act_mhz();
3312 
3313 	if (DO_BIC(BIC_CPU_LPI))
3314 		snapshot_cpu_lpi_us();
3315 
3316 	if (DO_BIC(BIC_SYS_LPI))
3317 		snapshot_sys_lpi_us();
3318 
3319 	return 0;
3320 }
3321 
3322 int exit_requested;
3323 
3324 static void signal_handler(int signal)
3325 {
3326 	switch (signal) {
3327 	case SIGINT:
3328 		exit_requested = 1;
3329 		if (debug)
3330 			fprintf(stderr, " SIGINT\n");
3331 		break;
3332 	case SIGUSR1:
3333 		if (debug > 1)
3334 			fprintf(stderr, "SIGUSR1\n");
3335 		break;
3336 	}
3337 }
3338 
3339 void setup_signal_handler(void)
3340 {
3341 	struct sigaction sa;
3342 
3343 	memset(&sa, 0, sizeof(sa));
3344 
3345 	sa.sa_handler = &signal_handler;
3346 
3347 	if (sigaction(SIGINT, &sa, NULL) < 0)
3348 		err(1, "sigaction SIGINT");
3349 	if (sigaction(SIGUSR1, &sa, NULL) < 0)
3350 		err(1, "sigaction SIGUSR1");
3351 }
3352 
3353 void do_sleep(void)
3354 {
3355 	struct timeval tout;
3356 	struct timespec rest;
3357 	fd_set readfds;
3358 	int retval;
3359 
3360 	FD_ZERO(&readfds);
3361 	FD_SET(0, &readfds);
3362 
3363 	if (ignore_stdin) {
3364 		nanosleep(&interval_ts, NULL);
3365 		return;
3366 	}
3367 
3368 	tout = interval_tv;
3369 	retval = select(1, &readfds, NULL, NULL, &tout);
3370 
3371 	if (retval == 1) {
3372 		switch (getc(stdin)) {
3373 		case 'q':
3374 			exit_requested = 1;
3375 			break;
3376 		case EOF:
3377 			/*
3378 			 * 'stdin' is a pipe closed on the other end. There
3379 			 * won't be any further input.
3380 			 */
3381 			ignore_stdin = 1;
3382 			/* Sleep the rest of the time */
3383 			rest.tv_sec = (tout.tv_sec + tout.tv_usec / 1000000);
3384 			rest.tv_nsec = (tout.tv_usec % 1000000) * 1000;
3385 			nanosleep(&rest, NULL);
3386 		}
3387 	}
3388 }
3389 
3390 int get_msr_sum(int cpu, off_t offset, unsigned long long *msr)
3391 {
3392 	int ret, idx;
3393 	unsigned long long msr_cur, msr_last;
3394 
3395 	if (!per_cpu_msr_sum)
3396 		return 1;
3397 
3398 	idx = offset_to_idx(offset);
3399 	if (idx < 0)
3400 		return idx;
3401 	/* get_msr_sum() = sum + (get_msr() - last) */
3402 	ret = get_msr(cpu, offset, &msr_cur);
3403 	if (ret)
3404 		return ret;
3405 	msr_last = per_cpu_msr_sum[cpu].entries[idx].last;
3406 	DELTA_WRAP32(msr_cur, msr_last);
3407 	*msr = msr_last + per_cpu_msr_sum[cpu].entries[idx].sum;
3408 
3409 	return 0;
3410 }
3411 
3412 timer_t timerid;
3413 
3414 /* Timer callback, update the sum of MSRs periodically. */
3415 static int update_msr_sum(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3416 {
3417 	int i, ret;
3418 	int cpu = t->cpu_id;
3419 
3420 	UNUSED(c);
3421 	UNUSED(p);
3422 
3423 	for (i = IDX_PKG_ENERGY; i < IDX_COUNT; i++) {
3424 		unsigned long long msr_cur, msr_last;
3425 		off_t offset;
3426 
3427 		if (!idx_valid(i))
3428 			continue;
3429 		offset = idx_to_offset(i);
3430 		if (offset < 0)
3431 			continue;
3432 		ret = get_msr(cpu, offset, &msr_cur);
3433 		if (ret) {
3434 			fprintf(outf, "Can not update msr(0x%llx)\n", (unsigned long long)offset);
3435 			continue;
3436 		}
3437 
3438 		msr_last = per_cpu_msr_sum[cpu].entries[i].last;
3439 		per_cpu_msr_sum[cpu].entries[i].last = msr_cur & 0xffffffff;
3440 
3441 		DELTA_WRAP32(msr_cur, msr_last);
3442 		per_cpu_msr_sum[cpu].entries[i].sum += msr_last;
3443 	}
3444 	return 0;
3445 }
3446 
3447 static void msr_record_handler(union sigval v)
3448 {
3449 	UNUSED(v);
3450 
3451 	for_all_cpus(update_msr_sum, EVEN_COUNTERS);
3452 }
3453 
3454 void msr_sum_record(void)
3455 {
3456 	struct itimerspec its;
3457 	struct sigevent sev;
3458 
3459 	per_cpu_msr_sum = calloc(topo.max_cpu_num + 1, sizeof(struct msr_sum_array));
3460 	if (!per_cpu_msr_sum) {
3461 		fprintf(outf, "Can not allocate memory for long time MSR.\n");
3462 		return;
3463 	}
3464 	/*
3465 	 * Signal handler might be restricted, so use thread notifier instead.
3466 	 */
3467 	memset(&sev, 0, sizeof(struct sigevent));
3468 	sev.sigev_notify = SIGEV_THREAD;
3469 	sev.sigev_notify_function = msr_record_handler;
3470 
3471 	sev.sigev_value.sival_ptr = &timerid;
3472 	if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) {
3473 		fprintf(outf, "Can not create timer.\n");
3474 		goto release_msr;
3475 	}
3476 
3477 	its.it_value.tv_sec = 0;
3478 	its.it_value.tv_nsec = 1;
3479 	/*
3480 	 * A wraparound time has been calculated early.
3481 	 * Some sources state that the peak power for a
3482 	 * microprocessor is usually 1.5 times the TDP rating,
3483 	 * use 2 * TDP for safety.
3484 	 */
3485 	its.it_interval.tv_sec = rapl_joule_counter_range / 2;
3486 	its.it_interval.tv_nsec = 0;
3487 
3488 	if (timer_settime(timerid, 0, &its, NULL) == -1) {
3489 		fprintf(outf, "Can not set timer.\n");
3490 		goto release_timer;
3491 	}
3492 	return;
3493 
3494 release_timer:
3495 	timer_delete(timerid);
3496 release_msr:
3497 	free(per_cpu_msr_sum);
3498 }
3499 
3500 /*
3501  * set_my_sched_priority(pri)
3502  * return previous
3503  *
3504  * if non-root, do this:
3505  * # /sbin/setcap cap_sys_rawio,cap_sys_nice=+ep /usr/bin/turbostat
3506  */
3507 int set_my_sched_priority(int priority)
3508 {
3509 	int retval;
3510 	int original_priority;
3511 
3512 	errno = 0;
3513 	original_priority = getpriority(PRIO_PROCESS, 0);
3514 	if (errno && (original_priority == -1))
3515 		err(errno, "getpriority");
3516 
3517 	retval = setpriority(PRIO_PROCESS, 0, priority);
3518 	if (retval)
3519 		err(retval, "setpriority(%d)", priority);
3520 
3521 	errno = 0;
3522 	retval = getpriority(PRIO_PROCESS, 0);
3523 	if (retval != priority)
3524 		err(retval, "getpriority(%d) != setpriority(%d)", retval, priority);
3525 
3526 	return original_priority;
3527 }
3528 
3529 void turbostat_loop()
3530 {
3531 	int retval;
3532 	int restarted = 0;
3533 	unsigned int done_iters = 0;
3534 
3535 	setup_signal_handler();
3536 
3537 	/*
3538 	 * elevate own priority for interval mode
3539 	 */
3540 	set_my_sched_priority(-20);
3541 
3542 restart:
3543 	restarted++;
3544 
3545 	snapshot_proc_sysfs_files();
3546 	retval = for_all_cpus(get_counters, EVEN_COUNTERS);
3547 	first_counter_read = 0;
3548 	if (retval < -1) {
3549 		exit(retval);
3550 	} else if (retval == -1) {
3551 		if (restarted > 10) {
3552 			exit(retval);
3553 		}
3554 		re_initialize();
3555 		goto restart;
3556 	}
3557 	restarted = 0;
3558 	done_iters = 0;
3559 	gettimeofday(&tv_even, (struct timezone *)NULL);
3560 
3561 	while (1) {
3562 		if (for_all_proc_cpus(cpu_is_not_present)) {
3563 			re_initialize();
3564 			goto restart;
3565 		}
3566 		do_sleep();
3567 		if (snapshot_proc_sysfs_files())
3568 			goto restart;
3569 		retval = for_all_cpus(get_counters, ODD_COUNTERS);
3570 		if (retval < -1) {
3571 			exit(retval);
3572 		} else if (retval == -1) {
3573 			re_initialize();
3574 			goto restart;
3575 		}
3576 		gettimeofday(&tv_odd, (struct timezone *)NULL);
3577 		timersub(&tv_odd, &tv_even, &tv_delta);
3578 		if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS)) {
3579 			re_initialize();
3580 			goto restart;
3581 		}
3582 		compute_average(EVEN_COUNTERS);
3583 		format_all_counters(EVEN_COUNTERS);
3584 		flush_output_stdout();
3585 		if (exit_requested)
3586 			break;
3587 		if (num_iterations && ++done_iters >= num_iterations)
3588 			break;
3589 		do_sleep();
3590 		if (snapshot_proc_sysfs_files())
3591 			goto restart;
3592 		retval = for_all_cpus(get_counters, EVEN_COUNTERS);
3593 		if (retval < -1) {
3594 			exit(retval);
3595 		} else if (retval == -1) {
3596 			re_initialize();
3597 			goto restart;
3598 		}
3599 		gettimeofday(&tv_even, (struct timezone *)NULL);
3600 		timersub(&tv_even, &tv_odd, &tv_delta);
3601 		if (for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS)) {
3602 			re_initialize();
3603 			goto restart;
3604 		}
3605 		compute_average(ODD_COUNTERS);
3606 		format_all_counters(ODD_COUNTERS);
3607 		flush_output_stdout();
3608 		if (exit_requested)
3609 			break;
3610 		if (num_iterations && ++done_iters >= num_iterations)
3611 			break;
3612 	}
3613 }
3614 
3615 void check_dev_msr()
3616 {
3617 	struct stat sb;
3618 	char pathname[32];
3619 
3620 	sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
3621 	if (stat(pathname, &sb))
3622 		if (system("/sbin/modprobe msr > /dev/null 2>&1"))
3623 			err(-5, "no /dev/cpu/0/msr, Try \"# modprobe msr\" ");
3624 }
3625 
3626 /*
3627  * check for CAP_SYS_RAWIO
3628  * return 0 on success
3629  * return 1 on fail
3630  */
3631 int check_for_cap_sys_rawio(void)
3632 {
3633 	cap_t caps;
3634 	cap_flag_value_t cap_flag_value;
3635 
3636 	caps = cap_get_proc();
3637 	if (caps == NULL)
3638 		err(-6, "cap_get_proc\n");
3639 
3640 	if (cap_get_flag(caps, CAP_SYS_RAWIO, CAP_EFFECTIVE, &cap_flag_value))
3641 		err(-6, "cap_get\n");
3642 
3643 	if (cap_flag_value != CAP_SET) {
3644 		warnx("capget(CAP_SYS_RAWIO) failed," " try \"# setcap cap_sys_rawio=ep %s\"", progname);
3645 		return 1;
3646 	}
3647 
3648 	if (cap_free(caps) == -1)
3649 		err(-6, "cap_free\n");
3650 
3651 	return 0;
3652 }
3653 
3654 void check_permissions(void)
3655 {
3656 	int do_exit = 0;
3657 	char pathname[32];
3658 
3659 	/* check for CAP_SYS_RAWIO */
3660 	do_exit += check_for_cap_sys_rawio();
3661 
3662 	/* test file permissions */
3663 	sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
3664 	if (euidaccess(pathname, R_OK)) {
3665 		do_exit++;
3666 		warn("/dev/cpu/0/msr open failed, try chown or chmod +r /dev/cpu/*/msr");
3667 	}
3668 
3669 	/* if all else fails, thell them to be root */
3670 	if (do_exit)
3671 		if (getuid() != 0)
3672 			warnx("... or simply run as root");
3673 
3674 	if (do_exit)
3675 		exit(-6);
3676 }
3677 
3678 /*
3679  * NHM adds support for additional MSRs:
3680  *
3681  * MSR_SMI_COUNT                   0x00000034
3682  *
3683  * MSR_PLATFORM_INFO               0x000000ce
3684  * MSR_PKG_CST_CONFIG_CONTROL     0x000000e2
3685  *
3686  * MSR_MISC_PWR_MGMT               0x000001aa
3687  *
3688  * MSR_PKG_C3_RESIDENCY            0x000003f8
3689  * MSR_PKG_C6_RESIDENCY            0x000003f9
3690  * MSR_CORE_C3_RESIDENCY           0x000003fc
3691  * MSR_CORE_C6_RESIDENCY           0x000003fd
3692  *
3693  * Side effect:
3694  * sets global pkg_cstate_limit to decode MSR_PKG_CST_CONFIG_CONTROL
3695  * sets has_misc_feature_control
3696  */
3697 int probe_nhm_msrs(unsigned int family, unsigned int model)
3698 {
3699 	unsigned long long msr;
3700 	unsigned int base_ratio;
3701 	int *pkg_cstate_limits;
3702 
3703 	if (!genuine_intel)
3704 		return 0;
3705 
3706 	if (family != 6)
3707 		return 0;
3708 
3709 	bclk = discover_bclk(family, model);
3710 
3711 	switch (model) {
3712 	case INTEL_FAM6_NEHALEM:	/* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
3713 	case INTEL_FAM6_NEHALEM_EX:	/* Nehalem-EX Xeon - Beckton */
3714 		pkg_cstate_limits = nhm_pkg_cstate_limits;
3715 		break;
3716 	case INTEL_FAM6_SANDYBRIDGE:	/* SNB */
3717 	case INTEL_FAM6_SANDYBRIDGE_X:	/* SNB Xeon */
3718 	case INTEL_FAM6_IVYBRIDGE:	/* IVB */
3719 	case INTEL_FAM6_IVYBRIDGE_X:	/* IVB Xeon */
3720 		pkg_cstate_limits = snb_pkg_cstate_limits;
3721 		has_misc_feature_control = 1;
3722 		break;
3723 	case INTEL_FAM6_HASWELL:	/* HSW */
3724 	case INTEL_FAM6_HASWELL_G:	/* HSW */
3725 	case INTEL_FAM6_HASWELL_X:	/* HSX */
3726 	case INTEL_FAM6_HASWELL_L:	/* HSW */
3727 	case INTEL_FAM6_BROADWELL:	/* BDW */
3728 	case INTEL_FAM6_BROADWELL_G:	/* BDW */
3729 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
3730 	case INTEL_FAM6_SKYLAKE_L:	/* SKL */
3731 	case INTEL_FAM6_CANNONLAKE_L:	/* CNL */
3732 		pkg_cstate_limits = hsw_pkg_cstate_limits;
3733 		has_misc_feature_control = 1;
3734 		break;
3735 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
3736 		pkg_cstate_limits = skx_pkg_cstate_limits;
3737 		has_misc_feature_control = 1;
3738 		break;
3739 	case INTEL_FAM6_ICELAKE_X:	/* ICX */
3740 		pkg_cstate_limits = icx_pkg_cstate_limits;
3741 		has_misc_feature_control = 1;
3742 		break;
3743 	case INTEL_FAM6_ATOM_SILVERMONT:	/* BYT */
3744 		no_MSR_MISC_PWR_MGMT = 1;
3745 		/* FALLTHRU */
3746 	case INTEL_FAM6_ATOM_SILVERMONT_D:	/* AVN */
3747 		pkg_cstate_limits = slv_pkg_cstate_limits;
3748 		break;
3749 	case INTEL_FAM6_ATOM_AIRMONT:	/* AMT */
3750 		pkg_cstate_limits = amt_pkg_cstate_limits;
3751 		no_MSR_MISC_PWR_MGMT = 1;
3752 		break;
3753 	case INTEL_FAM6_XEON_PHI_KNL:	/* PHI */
3754 		pkg_cstate_limits = phi_pkg_cstate_limits;
3755 		break;
3756 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
3757 	case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
3758 	case INTEL_FAM6_ATOM_GOLDMONT_D:	/* DNV */
3759 	case INTEL_FAM6_ATOM_TREMONT:	/* EHL */
3760 	case INTEL_FAM6_ATOM_TREMONT_D:	/* JVL */
3761 		pkg_cstate_limits = glm_pkg_cstate_limits;
3762 		break;
3763 	default:
3764 		return 0;
3765 	}
3766 	get_msr(base_cpu, MSR_PKG_CST_CONFIG_CONTROL, &msr);
3767 	pkg_cstate_limit = pkg_cstate_limits[msr & 0xF];
3768 
3769 	get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
3770 	base_ratio = (msr >> 8) & 0xFF;
3771 
3772 	base_hz = base_ratio * bclk * 1000000;
3773 	has_base_hz = 1;
3774 	return 1;
3775 }
3776 
3777 /*
3778  * SLV client has support for unique MSRs:
3779  *
3780  * MSR_CC6_DEMOTION_POLICY_CONFIG
3781  * MSR_MC6_DEMOTION_POLICY_CONFIG
3782  */
3783 
3784 int has_slv_msrs(unsigned int family, unsigned int model)
3785 {
3786 	if (!genuine_intel)
3787 		return 0;
3788 
3789 	if (family != 6)
3790 		return 0;
3791 
3792 	switch (model) {
3793 	case INTEL_FAM6_ATOM_SILVERMONT:
3794 	case INTEL_FAM6_ATOM_SILVERMONT_MID:
3795 	case INTEL_FAM6_ATOM_AIRMONT_MID:
3796 		return 1;
3797 	}
3798 	return 0;
3799 }
3800 
3801 int is_dnv(unsigned int family, unsigned int model)
3802 {
3803 
3804 	if (!genuine_intel)
3805 		return 0;
3806 
3807 	if (family != 6)
3808 		return 0;
3809 
3810 	switch (model) {
3811 	case INTEL_FAM6_ATOM_GOLDMONT_D:
3812 		return 1;
3813 	}
3814 	return 0;
3815 }
3816 
3817 int is_bdx(unsigned int family, unsigned int model)
3818 {
3819 
3820 	if (!genuine_intel)
3821 		return 0;
3822 
3823 	if (family != 6)
3824 		return 0;
3825 
3826 	switch (model) {
3827 	case INTEL_FAM6_BROADWELL_X:
3828 		return 1;
3829 	}
3830 	return 0;
3831 }
3832 
3833 int is_skx(unsigned int family, unsigned int model)
3834 {
3835 
3836 	if (!genuine_intel)
3837 		return 0;
3838 
3839 	if (family != 6)
3840 		return 0;
3841 
3842 	switch (model) {
3843 	case INTEL_FAM6_SKYLAKE_X:
3844 		return 1;
3845 	}
3846 	return 0;
3847 }
3848 
3849 int is_icx(unsigned int family, unsigned int model)
3850 {
3851 
3852 	if (!genuine_intel)
3853 		return 0;
3854 
3855 	if (family != 6)
3856 		return 0;
3857 
3858 	switch (model) {
3859 	case INTEL_FAM6_ICELAKE_X:
3860 		return 1;
3861 	}
3862 	return 0;
3863 }
3864 
3865 int is_ehl(unsigned int family, unsigned int model)
3866 {
3867 	if (!genuine_intel)
3868 		return 0;
3869 
3870 	if (family != 6)
3871 		return 0;
3872 
3873 	switch (model) {
3874 	case INTEL_FAM6_ATOM_TREMONT:
3875 		return 1;
3876 	}
3877 	return 0;
3878 }
3879 
3880 int is_jvl(unsigned int family, unsigned int model)
3881 {
3882 	if (!genuine_intel)
3883 		return 0;
3884 
3885 	if (family != 6)
3886 		return 0;
3887 
3888 	switch (model) {
3889 	case INTEL_FAM6_ATOM_TREMONT_D:
3890 		return 1;
3891 	}
3892 	return 0;
3893 }
3894 
3895 int has_turbo_ratio_limit(unsigned int family, unsigned int model)
3896 {
3897 	if (has_slv_msrs(family, model))
3898 		return 0;
3899 
3900 	if (family != 6)
3901 		return 0;
3902 
3903 	switch (model) {
3904 		/* Nehalem compatible, but do not include turbo-ratio limit support */
3905 	case INTEL_FAM6_NEHALEM_EX:	/* Nehalem-EX Xeon - Beckton */
3906 	case INTEL_FAM6_XEON_PHI_KNL:	/* PHI - Knights Landing (different MSR definition) */
3907 		return 0;
3908 	default:
3909 		return 1;
3910 	}
3911 }
3912 
3913 int has_atom_turbo_ratio_limit(unsigned int family, unsigned int model)
3914 {
3915 	if (has_slv_msrs(family, model))
3916 		return 1;
3917 
3918 	return 0;
3919 }
3920 
3921 int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
3922 {
3923 	if (!genuine_intel)
3924 		return 0;
3925 
3926 	if (family != 6)
3927 		return 0;
3928 
3929 	switch (model) {
3930 	case INTEL_FAM6_IVYBRIDGE_X:	/* IVB Xeon */
3931 	case INTEL_FAM6_HASWELL_X:	/* HSW Xeon */
3932 		return 1;
3933 	default:
3934 		return 0;
3935 	}
3936 }
3937 
3938 int has_hsw_turbo_ratio_limit(unsigned int family, unsigned int model)
3939 {
3940 	if (!genuine_intel)
3941 		return 0;
3942 
3943 	if (family != 6)
3944 		return 0;
3945 
3946 	switch (model) {
3947 	case INTEL_FAM6_HASWELL_X:	/* HSW Xeon */
3948 		return 1;
3949 	default:
3950 		return 0;
3951 	}
3952 }
3953 
3954 int has_knl_turbo_ratio_limit(unsigned int family, unsigned int model)
3955 {
3956 	if (!genuine_intel)
3957 		return 0;
3958 
3959 	if (family != 6)
3960 		return 0;
3961 
3962 	switch (model) {
3963 	case INTEL_FAM6_XEON_PHI_KNL:	/* Knights Landing */
3964 		return 1;
3965 	default:
3966 		return 0;
3967 	}
3968 }
3969 
3970 int has_glm_turbo_ratio_limit(unsigned int family, unsigned int model)
3971 {
3972 	if (!genuine_intel)
3973 		return 0;
3974 
3975 	if (family != 6)
3976 		return 0;
3977 
3978 	switch (model) {
3979 	case INTEL_FAM6_ATOM_GOLDMONT:
3980 	case INTEL_FAM6_SKYLAKE_X:
3981 	case INTEL_FAM6_ICELAKE_X:
3982 		return 1;
3983 	default:
3984 		return 0;
3985 	}
3986 }
3987 
3988 int has_config_tdp(unsigned int family, unsigned int model)
3989 {
3990 	if (!genuine_intel)
3991 		return 0;
3992 
3993 	if (family != 6)
3994 		return 0;
3995 
3996 	switch (model) {
3997 	case INTEL_FAM6_IVYBRIDGE:	/* IVB */
3998 	case INTEL_FAM6_HASWELL:	/* HSW */
3999 	case INTEL_FAM6_HASWELL_X:	/* HSX */
4000 	case INTEL_FAM6_HASWELL_L:	/* HSW */
4001 	case INTEL_FAM6_HASWELL_G:	/* HSW */
4002 	case INTEL_FAM6_BROADWELL:	/* BDW */
4003 	case INTEL_FAM6_BROADWELL_G:	/* BDW */
4004 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
4005 	case INTEL_FAM6_SKYLAKE_L:	/* SKL */
4006 	case INTEL_FAM6_CANNONLAKE_L:	/* CNL */
4007 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
4008 	case INTEL_FAM6_ICELAKE_X:	/* ICX */
4009 
4010 	case INTEL_FAM6_XEON_PHI_KNL:	/* Knights Landing */
4011 		return 1;
4012 	default:
4013 		return 0;
4014 	}
4015 }
4016 
4017 /*
4018  * tcc_offset_bits:
4019  * 0: Tcc Offset not supported (Default)
4020  * 6: Bit 29:24 of MSR_PLATFORM_INFO
4021  * 4: Bit 27:24 of MSR_PLATFORM_INFO
4022  */
4023 void check_tcc_offset(int model)
4024 {
4025 	unsigned long long msr;
4026 
4027 	if (!genuine_intel)
4028 		return;
4029 
4030 	switch (model) {
4031 	case INTEL_FAM6_SKYLAKE_L:
4032 	case INTEL_FAM6_SKYLAKE:
4033 	case INTEL_FAM6_KABYLAKE_L:
4034 	case INTEL_FAM6_KABYLAKE:
4035 	case INTEL_FAM6_ICELAKE_L:
4036 	case INTEL_FAM6_ICELAKE:
4037 	case INTEL_FAM6_TIGERLAKE_L:
4038 	case INTEL_FAM6_TIGERLAKE:
4039 	case INTEL_FAM6_COMETLAKE:
4040 		if (!get_msr(base_cpu, MSR_PLATFORM_INFO, &msr)) {
4041 			msr = (msr >> 30) & 1;
4042 			if (msr)
4043 				tcc_offset_bits = 6;
4044 		}
4045 		return;
4046 	default:
4047 		return;
4048 	}
4049 }
4050 
4051 static void remove_underbar(char *s)
4052 {
4053 	char *to = s;
4054 
4055 	while (*s) {
4056 		if (*s != '_')
4057 			*to++ = *s;
4058 		s++;
4059 	}
4060 
4061 	*to = 0;
4062 }
4063 
4064 static void dump_cstate_pstate_config_info(unsigned int family, unsigned int model)
4065 {
4066 	if (!do_nhm_platform_info)
4067 		return;
4068 
4069 	dump_nhm_platform_info();
4070 
4071 	if (has_hsw_turbo_ratio_limit(family, model))
4072 		dump_hsw_turbo_ratio_limits();
4073 
4074 	if (has_ivt_turbo_ratio_limit(family, model))
4075 		dump_ivt_turbo_ratio_limits();
4076 
4077 	if (has_turbo_ratio_limit(family, model)) {
4078 		dump_turbo_ratio_limits(MSR_TURBO_RATIO_LIMIT, family, model);
4079 
4080 		if (is_hybrid)
4081 			dump_turbo_ratio_limits(MSR_SECONDARY_TURBO_RATIO_LIMIT, family, model);
4082 	}
4083 
4084 	if (has_atom_turbo_ratio_limit(family, model))
4085 		dump_atom_turbo_ratio_limits();
4086 
4087 	if (has_knl_turbo_ratio_limit(family, model))
4088 		dump_knl_turbo_ratio_limits();
4089 
4090 	if (has_config_tdp(family, model))
4091 		dump_config_tdp();
4092 
4093 	dump_nhm_cst_cfg();
4094 }
4095 
4096 static int read_sysfs_int(char *path)
4097 {
4098 	FILE *input;
4099 	int retval = -1;
4100 
4101 	input = fopen(path, "r");
4102 	if (input == NULL) {
4103 		if (debug)
4104 			fprintf(outf, "NSFOD %s\n", path);
4105 		return (-1);
4106 	}
4107 	if (fscanf(input, "%d", &retval) != 1)
4108 		err(1, "%s: failed to read int from file", path);
4109 	fclose(input);
4110 
4111 	return (retval);
4112 }
4113 
4114 static void dump_sysfs_file(char *path)
4115 {
4116 	FILE *input;
4117 	char cpuidle_buf[64];
4118 
4119 	input = fopen(path, "r");
4120 	if (input == NULL) {
4121 		if (debug)
4122 			fprintf(outf, "NSFOD %s\n", path);
4123 		return;
4124 	}
4125 	if (!fgets(cpuidle_buf, sizeof(cpuidle_buf), input))
4126 		err(1, "%s: failed to read file", path);
4127 	fclose(input);
4128 
4129 	fprintf(outf, "%s: %s", strrchr(path, '/') + 1, cpuidle_buf);
4130 }
4131 
4132 static void intel_uncore_frequency_probe(void)
4133 {
4134 	int i, j;
4135 	char path[128];
4136 
4137 	if (!genuine_intel)
4138 		return;
4139 
4140 	if (access("/sys/devices/system/cpu/intel_uncore_frequency/package_00_die_00", R_OK))
4141 		return;
4142 
4143 	if (!access("/sys/devices/system/cpu/intel_uncore_frequency/package_00_die_00/current_freq_khz", R_OK))
4144 		BIC_PRESENT(BIC_UNCORE_MHZ);
4145 
4146 	if (quiet)
4147 		return;
4148 
4149 	for (i = 0; i < topo.num_packages; ++i) {
4150 		for (j = 0; j < topo.num_die; ++j) {
4151 			int k, l;
4152 
4153 			sprintf(path, "/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/min_freq_khz",
4154 				i, j);
4155 			k = read_sysfs_int(path);
4156 			sprintf(path, "/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/max_freq_khz",
4157 				i, j);
4158 			l = read_sysfs_int(path);
4159 			fprintf(outf, "Uncore Frequency pkg%d die%d: %d - %d MHz ", i, j, k / 1000, l / 1000);
4160 
4161 			sprintf(path,
4162 				"/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/initial_min_freq_khz",
4163 				i, j);
4164 			k = read_sysfs_int(path);
4165 			sprintf(path,
4166 				"/sys/devices/system/cpu/intel_uncore_frequency/package_0%d_die_0%d/initial_max_freq_khz",
4167 				i, j);
4168 			l = read_sysfs_int(path);
4169 			fprintf(outf, "(%d - %d MHz)\n", k / 1000, l / 1000);
4170 		}
4171 	}
4172 }
4173 
4174 static void dump_sysfs_cstate_config(void)
4175 {
4176 	char path[64];
4177 	char name_buf[16];
4178 	char desc[64];
4179 	FILE *input;
4180 	int state;
4181 	char *sp;
4182 
4183 	if (access("/sys/devices/system/cpu/cpuidle", R_OK)) {
4184 		fprintf(outf, "cpuidle not loaded\n");
4185 		return;
4186 	}
4187 
4188 	dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_driver");
4189 	dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_governor");
4190 	dump_sysfs_file("/sys/devices/system/cpu/cpuidle/current_governor_ro");
4191 
4192 	for (state = 0; state < 10; ++state) {
4193 
4194 		sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name", base_cpu, state);
4195 		input = fopen(path, "r");
4196 		if (input == NULL)
4197 			continue;
4198 		if (!fgets(name_buf, sizeof(name_buf), input))
4199 			err(1, "%s: failed to read file", path);
4200 
4201 		/* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
4202 		sp = strchr(name_buf, '-');
4203 		if (!sp)
4204 			sp = strchrnul(name_buf, '\n');
4205 		*sp = '\0';
4206 		fclose(input);
4207 
4208 		remove_underbar(name_buf);
4209 
4210 		sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/desc", base_cpu, state);
4211 		input = fopen(path, "r");
4212 		if (input == NULL)
4213 			continue;
4214 		if (!fgets(desc, sizeof(desc), input))
4215 			err(1, "%s: failed to read file", path);
4216 
4217 		fprintf(outf, "cpu%d: %s: %s", base_cpu, name_buf, desc);
4218 		fclose(input);
4219 	}
4220 }
4221 
4222 static void dump_sysfs_pstate_config(void)
4223 {
4224 	char path[64];
4225 	char driver_buf[64];
4226 	char governor_buf[64];
4227 	FILE *input;
4228 	int turbo;
4229 
4230 	sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_driver", base_cpu);
4231 	input = fopen(path, "r");
4232 	if (input == NULL) {
4233 		fprintf(outf, "NSFOD %s\n", path);
4234 		return;
4235 	}
4236 	if (!fgets(driver_buf, sizeof(driver_buf), input))
4237 		err(1, "%s: failed to read file", path);
4238 	fclose(input);
4239 
4240 	sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor", base_cpu);
4241 	input = fopen(path, "r");
4242 	if (input == NULL) {
4243 		fprintf(outf, "NSFOD %s\n", path);
4244 		return;
4245 	}
4246 	if (!fgets(governor_buf, sizeof(governor_buf), input))
4247 		err(1, "%s: failed to read file", path);
4248 	fclose(input);
4249 
4250 	fprintf(outf, "cpu%d: cpufreq driver: %s", base_cpu, driver_buf);
4251 	fprintf(outf, "cpu%d: cpufreq governor: %s", base_cpu, governor_buf);
4252 
4253 	sprintf(path, "/sys/devices/system/cpu/cpufreq/boost");
4254 	input = fopen(path, "r");
4255 	if (input != NULL) {
4256 		if (fscanf(input, "%d", &turbo) != 1)
4257 			err(1, "%s: failed to parse number from file", path);
4258 		fprintf(outf, "cpufreq boost: %d\n", turbo);
4259 		fclose(input);
4260 	}
4261 
4262 	sprintf(path, "/sys/devices/system/cpu/intel_pstate/no_turbo");
4263 	input = fopen(path, "r");
4264 	if (input != NULL) {
4265 		if (fscanf(input, "%d", &turbo) != 1)
4266 			err(1, "%s: failed to parse number from file", path);
4267 		fprintf(outf, "cpufreq intel_pstate no_turbo: %d\n", turbo);
4268 		fclose(input);
4269 	}
4270 }
4271 
4272 /*
4273  * print_epb()
4274  * Decode the ENERGY_PERF_BIAS MSR
4275  */
4276 int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4277 {
4278 	char *epb_string;
4279 	int cpu, epb;
4280 
4281 	UNUSED(c);
4282 	UNUSED(p);
4283 
4284 	if (!has_epb)
4285 		return 0;
4286 
4287 	cpu = t->cpu_id;
4288 
4289 	/* EPB is per-package */
4290 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
4291 		return 0;
4292 
4293 	if (cpu_migrate(cpu)) {
4294 		fprintf(outf, "print_epb: Could not migrate to CPU %d\n", cpu);
4295 		return -1;
4296 	}
4297 
4298 	epb = get_epb(cpu);
4299 	if (epb < 0)
4300 		return 0;
4301 
4302 	switch (epb) {
4303 	case ENERGY_PERF_BIAS_PERFORMANCE:
4304 		epb_string = "performance";
4305 		break;
4306 	case ENERGY_PERF_BIAS_NORMAL:
4307 		epb_string = "balanced";
4308 		break;
4309 	case ENERGY_PERF_BIAS_POWERSAVE:
4310 		epb_string = "powersave";
4311 		break;
4312 	default:
4313 		epb_string = "custom";
4314 		break;
4315 	}
4316 	fprintf(outf, "cpu%d: EPB: %d (%s)\n", cpu, epb, epb_string);
4317 
4318 	return 0;
4319 }
4320 
4321 /*
4322  * print_hwp()
4323  * Decode the MSR_HWP_CAPABILITIES
4324  */
4325 int print_hwp(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4326 {
4327 	unsigned long long msr;
4328 	int cpu;
4329 
4330 	UNUSED(c);
4331 	UNUSED(p);
4332 
4333 	if (!has_hwp)
4334 		return 0;
4335 
4336 	cpu = t->cpu_id;
4337 
4338 	/* MSR_HWP_CAPABILITIES is per-package */
4339 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
4340 		return 0;
4341 
4342 	if (cpu_migrate(cpu)) {
4343 		fprintf(outf, "print_hwp: Could not migrate to CPU %d\n", cpu);
4344 		return -1;
4345 	}
4346 
4347 	if (get_msr(cpu, MSR_PM_ENABLE, &msr))
4348 		return 0;
4349 
4350 	fprintf(outf, "cpu%d: MSR_PM_ENABLE: 0x%08llx (%sHWP)\n", cpu, msr, (msr & (1 << 0)) ? "" : "No-");
4351 
4352 	/* MSR_PM_ENABLE[1] == 1 if HWP is enabled and MSRs visible */
4353 	if ((msr & (1 << 0)) == 0)
4354 		return 0;
4355 
4356 	if (get_msr(cpu, MSR_HWP_CAPABILITIES, &msr))
4357 		return 0;
4358 
4359 	fprintf(outf, "cpu%d: MSR_HWP_CAPABILITIES: 0x%08llx "
4360 		"(high %d guar %d eff %d low %d)\n",
4361 		cpu, msr,
4362 		(unsigned int)HWP_HIGHEST_PERF(msr),
4363 		(unsigned int)HWP_GUARANTEED_PERF(msr),
4364 		(unsigned int)HWP_MOSTEFFICIENT_PERF(msr), (unsigned int)HWP_LOWEST_PERF(msr));
4365 
4366 	if (get_msr(cpu, MSR_HWP_REQUEST, &msr))
4367 		return 0;
4368 
4369 	fprintf(outf, "cpu%d: MSR_HWP_REQUEST: 0x%08llx "
4370 		"(min %d max %d des %d epp 0x%x window 0x%x pkg 0x%x)\n",
4371 		cpu, msr,
4372 		(unsigned int)(((msr) >> 0) & 0xff),
4373 		(unsigned int)(((msr) >> 8) & 0xff),
4374 		(unsigned int)(((msr) >> 16) & 0xff),
4375 		(unsigned int)(((msr) >> 24) & 0xff),
4376 		(unsigned int)(((msr) >> 32) & 0xff3), (unsigned int)(((msr) >> 42) & 0x1));
4377 
4378 	if (has_hwp_pkg) {
4379 		if (get_msr(cpu, MSR_HWP_REQUEST_PKG, &msr))
4380 			return 0;
4381 
4382 		fprintf(outf, "cpu%d: MSR_HWP_REQUEST_PKG: 0x%08llx "
4383 			"(min %d max %d des %d epp 0x%x window 0x%x)\n",
4384 			cpu, msr,
4385 			(unsigned int)(((msr) >> 0) & 0xff),
4386 			(unsigned int)(((msr) >> 8) & 0xff),
4387 			(unsigned int)(((msr) >> 16) & 0xff),
4388 			(unsigned int)(((msr) >> 24) & 0xff), (unsigned int)(((msr) >> 32) & 0xff3));
4389 	}
4390 	if (has_hwp_notify) {
4391 		if (get_msr(cpu, MSR_HWP_INTERRUPT, &msr))
4392 			return 0;
4393 
4394 		fprintf(outf, "cpu%d: MSR_HWP_INTERRUPT: 0x%08llx "
4395 			"(%s_Guaranteed_Perf_Change, %s_Excursion_Min)\n",
4396 			cpu, msr, ((msr) & 0x1) ? "EN" : "Dis", ((msr) & 0x2) ? "EN" : "Dis");
4397 	}
4398 	if (get_msr(cpu, MSR_HWP_STATUS, &msr))
4399 		return 0;
4400 
4401 	fprintf(outf, "cpu%d: MSR_HWP_STATUS: 0x%08llx "
4402 		"(%sGuaranteed_Perf_Change, %sExcursion_Min)\n",
4403 		cpu, msr, ((msr) & 0x1) ? "" : "No-", ((msr) & 0x2) ? "" : "No-");
4404 
4405 	return 0;
4406 }
4407 
4408 /*
4409  * print_perf_limit()
4410  */
4411 int print_perf_limit(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4412 {
4413 	unsigned long long msr;
4414 	int cpu;
4415 
4416 	UNUSED(c);
4417 	UNUSED(p);
4418 
4419 	cpu = t->cpu_id;
4420 
4421 	/* per-package */
4422 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
4423 		return 0;
4424 
4425 	if (cpu_migrate(cpu)) {
4426 		fprintf(outf, "print_perf_limit: Could not migrate to CPU %d\n", cpu);
4427 		return -1;
4428 	}
4429 
4430 	if (do_core_perf_limit_reasons) {
4431 		get_msr(cpu, MSR_CORE_PERF_LIMIT_REASONS, &msr);
4432 		fprintf(outf, "cpu%d: MSR_CORE_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4433 		fprintf(outf, " (Active: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
4434 			(msr & 1 << 15) ? "bit15, " : "",
4435 			(msr & 1 << 14) ? "bit14, " : "",
4436 			(msr & 1 << 13) ? "Transitions, " : "",
4437 			(msr & 1 << 12) ? "MultiCoreTurbo, " : "",
4438 			(msr & 1 << 11) ? "PkgPwrL2, " : "",
4439 			(msr & 1 << 10) ? "PkgPwrL1, " : "",
4440 			(msr & 1 << 9) ? "CorePwr, " : "",
4441 			(msr & 1 << 8) ? "Amps, " : "",
4442 			(msr & 1 << 6) ? "VR-Therm, " : "",
4443 			(msr & 1 << 5) ? "Auto-HWP, " : "",
4444 			(msr & 1 << 4) ? "Graphics, " : "",
4445 			(msr & 1 << 2) ? "bit2, " : "",
4446 			(msr & 1 << 1) ? "ThermStatus, " : "", (msr & 1 << 0) ? "PROCHOT, " : "");
4447 		fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
4448 			(msr & 1 << 31) ? "bit31, " : "",
4449 			(msr & 1 << 30) ? "bit30, " : "",
4450 			(msr & 1 << 29) ? "Transitions, " : "",
4451 			(msr & 1 << 28) ? "MultiCoreTurbo, " : "",
4452 			(msr & 1 << 27) ? "PkgPwrL2, " : "",
4453 			(msr & 1 << 26) ? "PkgPwrL1, " : "",
4454 			(msr & 1 << 25) ? "CorePwr, " : "",
4455 			(msr & 1 << 24) ? "Amps, " : "",
4456 			(msr & 1 << 22) ? "VR-Therm, " : "",
4457 			(msr & 1 << 21) ? "Auto-HWP, " : "",
4458 			(msr & 1 << 20) ? "Graphics, " : "",
4459 			(msr & 1 << 18) ? "bit18, " : "",
4460 			(msr & 1 << 17) ? "ThermStatus, " : "", (msr & 1 << 16) ? "PROCHOT, " : "");
4461 
4462 	}
4463 	if (do_gfx_perf_limit_reasons) {
4464 		get_msr(cpu, MSR_GFX_PERF_LIMIT_REASONS, &msr);
4465 		fprintf(outf, "cpu%d: MSR_GFX_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4466 		fprintf(outf, " (Active: %s%s%s%s%s%s%s%s)",
4467 			(msr & 1 << 0) ? "PROCHOT, " : "",
4468 			(msr & 1 << 1) ? "ThermStatus, " : "",
4469 			(msr & 1 << 4) ? "Graphics, " : "",
4470 			(msr & 1 << 6) ? "VR-Therm, " : "",
4471 			(msr & 1 << 8) ? "Amps, " : "",
4472 			(msr & 1 << 9) ? "GFXPwr, " : "",
4473 			(msr & 1 << 10) ? "PkgPwrL1, " : "", (msr & 1 << 11) ? "PkgPwrL2, " : "");
4474 		fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s)\n",
4475 			(msr & 1 << 16) ? "PROCHOT, " : "",
4476 			(msr & 1 << 17) ? "ThermStatus, " : "",
4477 			(msr & 1 << 20) ? "Graphics, " : "",
4478 			(msr & 1 << 22) ? "VR-Therm, " : "",
4479 			(msr & 1 << 24) ? "Amps, " : "",
4480 			(msr & 1 << 25) ? "GFXPwr, " : "",
4481 			(msr & 1 << 26) ? "PkgPwrL1, " : "", (msr & 1 << 27) ? "PkgPwrL2, " : "");
4482 	}
4483 	if (do_ring_perf_limit_reasons) {
4484 		get_msr(cpu, MSR_RING_PERF_LIMIT_REASONS, &msr);
4485 		fprintf(outf, "cpu%d: MSR_RING_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
4486 		fprintf(outf, " (Active: %s%s%s%s%s%s)",
4487 			(msr & 1 << 0) ? "PROCHOT, " : "",
4488 			(msr & 1 << 1) ? "ThermStatus, " : "",
4489 			(msr & 1 << 6) ? "VR-Therm, " : "",
4490 			(msr & 1 << 8) ? "Amps, " : "",
4491 			(msr & 1 << 10) ? "PkgPwrL1, " : "", (msr & 1 << 11) ? "PkgPwrL2, " : "");
4492 		fprintf(outf, " (Logged: %s%s%s%s%s%s)\n",
4493 			(msr & 1 << 16) ? "PROCHOT, " : "",
4494 			(msr & 1 << 17) ? "ThermStatus, " : "",
4495 			(msr & 1 << 22) ? "VR-Therm, " : "",
4496 			(msr & 1 << 24) ? "Amps, " : "",
4497 			(msr & 1 << 26) ? "PkgPwrL1, " : "", (msr & 1 << 27) ? "PkgPwrL2, " : "");
4498 	}
4499 	return 0;
4500 }
4501 
4502 #define	RAPL_POWER_GRANULARITY	0x7FFF	/* 15 bit power granularity */
4503 #define	RAPL_TIME_GRANULARITY	0x3F	/* 6 bit time granularity */
4504 
4505 double get_tdp_intel(unsigned int model)
4506 {
4507 	unsigned long long msr;
4508 
4509 	if (do_rapl & RAPL_PKG_POWER_INFO)
4510 		if (!get_msr(base_cpu, MSR_PKG_POWER_INFO, &msr))
4511 			return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
4512 
4513 	switch (model) {
4514 	case INTEL_FAM6_ATOM_SILVERMONT:
4515 	case INTEL_FAM6_ATOM_SILVERMONT_D:
4516 		return 30.0;
4517 	default:
4518 		return 135.0;
4519 	}
4520 }
4521 
4522 double get_tdp_amd(unsigned int family)
4523 {
4524 	UNUSED(family);
4525 
4526 	/* This is the max stock TDP of HEDT/Server Fam17h+ chips */
4527 	return 280.0;
4528 }
4529 
4530 /*
4531  * rapl_dram_energy_units_probe()
4532  * Energy units are either hard-coded, or come from RAPL Energy Unit MSR.
4533  */
4534 static double rapl_dram_energy_units_probe(int model, double rapl_energy_units)
4535 {
4536 	/* only called for genuine_intel, family 6 */
4537 
4538 	switch (model) {
4539 	case INTEL_FAM6_HASWELL_X:	/* HSX */
4540 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
4541 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
4542 	case INTEL_FAM6_XEON_PHI_KNL:	/* KNL */
4543 	case INTEL_FAM6_ICELAKE_X:	/* ICX */
4544 		return (rapl_dram_energy_units = 15.3 / 1000000);
4545 	default:
4546 		return (rapl_energy_units);
4547 	}
4548 }
4549 
4550 void rapl_probe_intel(unsigned int family, unsigned int model)
4551 {
4552 	unsigned long long msr;
4553 	unsigned int time_unit;
4554 	double tdp;
4555 
4556 	if (family != 6)
4557 		return;
4558 
4559 	switch (model) {
4560 	case INTEL_FAM6_SANDYBRIDGE:
4561 	case INTEL_FAM6_IVYBRIDGE:
4562 	case INTEL_FAM6_HASWELL:	/* HSW */
4563 	case INTEL_FAM6_HASWELL_L:	/* HSW */
4564 	case INTEL_FAM6_HASWELL_G:	/* HSW */
4565 	case INTEL_FAM6_BROADWELL:	/* BDW */
4566 	case INTEL_FAM6_BROADWELL_G:	/* BDW */
4567 		do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
4568 		if (rapl_joules) {
4569 			BIC_PRESENT(BIC_Pkg_J);
4570 			BIC_PRESENT(BIC_Cor_J);
4571 			BIC_PRESENT(BIC_GFX_J);
4572 		} else {
4573 			BIC_PRESENT(BIC_PkgWatt);
4574 			BIC_PRESENT(BIC_CorWatt);
4575 			BIC_PRESENT(BIC_GFXWatt);
4576 		}
4577 		break;
4578 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
4579 	case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
4580 		do_rapl = RAPL_PKG | RAPL_PKG_POWER_INFO;
4581 		if (rapl_joules)
4582 			BIC_PRESENT(BIC_Pkg_J);
4583 		else
4584 			BIC_PRESENT(BIC_PkgWatt);
4585 		break;
4586 	case INTEL_FAM6_ATOM_TREMONT:	/* EHL */
4587 		do_rapl =
4588 		    RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS
4589 		    | RAPL_GFX | RAPL_PKG_POWER_INFO;
4590 		if (rapl_joules) {
4591 			BIC_PRESENT(BIC_Pkg_J);
4592 			BIC_PRESENT(BIC_Cor_J);
4593 			BIC_PRESENT(BIC_RAM_J);
4594 			BIC_PRESENT(BIC_GFX_J);
4595 		} else {
4596 			BIC_PRESENT(BIC_PkgWatt);
4597 			BIC_PRESENT(BIC_CorWatt);
4598 			BIC_PRESENT(BIC_RAMWatt);
4599 			BIC_PRESENT(BIC_GFXWatt);
4600 		}
4601 		break;
4602 	case INTEL_FAM6_ATOM_TREMONT_D:	/* JVL */
4603 		do_rapl = RAPL_PKG | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
4604 		BIC_PRESENT(BIC_PKG__);
4605 		if (rapl_joules)
4606 			BIC_PRESENT(BIC_Pkg_J);
4607 		else
4608 			BIC_PRESENT(BIC_PkgWatt);
4609 		break;
4610 	case INTEL_FAM6_SKYLAKE_L:	/* SKL */
4611 	case INTEL_FAM6_CANNONLAKE_L:	/* CNL */
4612 		do_rapl =
4613 		    RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS
4614 		    | RAPL_GFX | RAPL_PKG_POWER_INFO;
4615 		BIC_PRESENT(BIC_PKG__);
4616 		BIC_PRESENT(BIC_RAM__);
4617 		if (rapl_joules) {
4618 			BIC_PRESENT(BIC_Pkg_J);
4619 			BIC_PRESENT(BIC_Cor_J);
4620 			BIC_PRESENT(BIC_RAM_J);
4621 			BIC_PRESENT(BIC_GFX_J);
4622 		} else {
4623 			BIC_PRESENT(BIC_PkgWatt);
4624 			BIC_PRESENT(BIC_CorWatt);
4625 			BIC_PRESENT(BIC_RAMWatt);
4626 			BIC_PRESENT(BIC_GFXWatt);
4627 		}
4628 		break;
4629 	case INTEL_FAM6_HASWELL_X:	/* HSX */
4630 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
4631 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
4632 	case INTEL_FAM6_ICELAKE_X:	/* ICX */
4633 	case INTEL_FAM6_XEON_PHI_KNL:	/* KNL */
4634 		do_rapl =
4635 		    RAPL_PKG | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS |
4636 		    RAPL_PKG_POWER_INFO;
4637 		BIC_PRESENT(BIC_PKG__);
4638 		BIC_PRESENT(BIC_RAM__);
4639 		if (rapl_joules) {
4640 			BIC_PRESENT(BIC_Pkg_J);
4641 			BIC_PRESENT(BIC_RAM_J);
4642 		} else {
4643 			BIC_PRESENT(BIC_PkgWatt);
4644 			BIC_PRESENT(BIC_RAMWatt);
4645 		}
4646 		break;
4647 	case INTEL_FAM6_SANDYBRIDGE_X:
4648 	case INTEL_FAM6_IVYBRIDGE_X:
4649 		do_rapl =
4650 		    RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_PKG_PERF_STATUS |
4651 		    RAPL_DRAM_PERF_STATUS | RAPL_PKG_POWER_INFO;
4652 		BIC_PRESENT(BIC_PKG__);
4653 		BIC_PRESENT(BIC_RAM__);
4654 		if (rapl_joules) {
4655 			BIC_PRESENT(BIC_Pkg_J);
4656 			BIC_PRESENT(BIC_Cor_J);
4657 			BIC_PRESENT(BIC_RAM_J);
4658 		} else {
4659 			BIC_PRESENT(BIC_PkgWatt);
4660 			BIC_PRESENT(BIC_CorWatt);
4661 			BIC_PRESENT(BIC_RAMWatt);
4662 		}
4663 		break;
4664 	case INTEL_FAM6_ATOM_SILVERMONT:	/* BYT */
4665 	case INTEL_FAM6_ATOM_SILVERMONT_D:	/* AVN */
4666 		do_rapl = RAPL_PKG | RAPL_CORES;
4667 		if (rapl_joules) {
4668 			BIC_PRESENT(BIC_Pkg_J);
4669 			BIC_PRESENT(BIC_Cor_J);
4670 		} else {
4671 			BIC_PRESENT(BIC_PkgWatt);
4672 			BIC_PRESENT(BIC_CorWatt);
4673 		}
4674 		break;
4675 	case INTEL_FAM6_ATOM_GOLDMONT_D:	/* DNV */
4676 		do_rapl =
4677 		    RAPL_PKG | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS |
4678 		    RAPL_PKG_POWER_INFO | RAPL_CORES_ENERGY_STATUS;
4679 		BIC_PRESENT(BIC_PKG__);
4680 		BIC_PRESENT(BIC_RAM__);
4681 		if (rapl_joules) {
4682 			BIC_PRESENT(BIC_Pkg_J);
4683 			BIC_PRESENT(BIC_Cor_J);
4684 			BIC_PRESENT(BIC_RAM_J);
4685 		} else {
4686 			BIC_PRESENT(BIC_PkgWatt);
4687 			BIC_PRESENT(BIC_CorWatt);
4688 			BIC_PRESENT(BIC_RAMWatt);
4689 		}
4690 		break;
4691 	default:
4692 		return;
4693 	}
4694 
4695 	/* units on package 0, verify later other packages match */
4696 	if (get_msr(base_cpu, MSR_RAPL_POWER_UNIT, &msr))
4697 		return;
4698 
4699 	rapl_power_units = 1.0 / (1 << (msr & 0xF));
4700 	if (model == INTEL_FAM6_ATOM_SILVERMONT)
4701 		rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
4702 	else
4703 		rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
4704 
4705 	rapl_dram_energy_units = rapl_dram_energy_units_probe(model, rapl_energy_units);
4706 
4707 	time_unit = msr >> 16 & 0xF;
4708 	if (time_unit == 0)
4709 		time_unit = 0xA;
4710 
4711 	rapl_time_units = 1.0 / (1 << (time_unit));
4712 
4713 	tdp = get_tdp_intel(model);
4714 
4715 	rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
4716 	if (!quiet)
4717 		fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
4718 }
4719 
4720 void rapl_probe_amd(unsigned int family, unsigned int model)
4721 {
4722 	unsigned long long msr;
4723 	unsigned int eax, ebx, ecx, edx;
4724 	unsigned int has_rapl = 0;
4725 	double tdp;
4726 
4727 	UNUSED(model);
4728 
4729 	if (max_extended_level >= 0x80000007) {
4730 		__cpuid(0x80000007, eax, ebx, ecx, edx);
4731 		/* RAPL (Fam 17h+) */
4732 		has_rapl = edx & (1 << 14);
4733 	}
4734 
4735 	if (!has_rapl || family < 0x17)
4736 		return;
4737 
4738 	do_rapl = RAPL_AMD_F17H | RAPL_PER_CORE_ENERGY;
4739 	if (rapl_joules) {
4740 		BIC_PRESENT(BIC_Pkg_J);
4741 		BIC_PRESENT(BIC_Cor_J);
4742 	} else {
4743 		BIC_PRESENT(BIC_PkgWatt);
4744 		BIC_PRESENT(BIC_CorWatt);
4745 	}
4746 
4747 	if (get_msr(base_cpu, MSR_RAPL_PWR_UNIT, &msr))
4748 		return;
4749 
4750 	rapl_time_units = ldexp(1.0, -(msr >> 16 & 0xf));
4751 	rapl_energy_units = ldexp(1.0, -(msr >> 8 & 0x1f));
4752 	rapl_power_units = ldexp(1.0, -(msr & 0xf));
4753 
4754 	tdp = get_tdp_amd(family);
4755 
4756 	rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
4757 	if (!quiet)
4758 		fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
4759 }
4760 
4761 /*
4762  * rapl_probe()
4763  *
4764  * sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
4765  */
4766 void rapl_probe(unsigned int family, unsigned int model)
4767 {
4768 	if (genuine_intel)
4769 		rapl_probe_intel(family, model);
4770 	if (authentic_amd || hygon_genuine)
4771 		rapl_probe_amd(family, model);
4772 }
4773 
4774 void perf_limit_reasons_probe(unsigned int family, unsigned int model)
4775 {
4776 	if (!genuine_intel)
4777 		return;
4778 
4779 	if (family != 6)
4780 		return;
4781 
4782 	switch (model) {
4783 	case INTEL_FAM6_HASWELL:	/* HSW */
4784 	case INTEL_FAM6_HASWELL_L:	/* HSW */
4785 	case INTEL_FAM6_HASWELL_G:	/* HSW */
4786 		do_gfx_perf_limit_reasons = 1;
4787 		/* FALLTHRU */
4788 	case INTEL_FAM6_HASWELL_X:	/* HSX */
4789 		do_core_perf_limit_reasons = 1;
4790 		do_ring_perf_limit_reasons = 1;
4791 	default:
4792 		return;
4793 	}
4794 }
4795 
4796 void automatic_cstate_conversion_probe(unsigned int family, unsigned int model)
4797 {
4798 	if (is_skx(family, model) || is_bdx(family, model) || is_icx(family, model))
4799 		has_automatic_cstate_conversion = 1;
4800 }
4801 
4802 void prewake_cstate_probe(unsigned int family, unsigned int model)
4803 {
4804 	if (is_icx(family, model))
4805 		dis_cstate_prewake = 1;
4806 }
4807 
4808 int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4809 {
4810 	unsigned long long msr;
4811 	unsigned int dts, dts2;
4812 	int cpu;
4813 
4814 	UNUSED(c);
4815 	UNUSED(p);
4816 
4817 	if (!(do_dts || do_ptm))
4818 		return 0;
4819 
4820 	cpu = t->cpu_id;
4821 
4822 	/* DTS is per-core, no need to print for each thread */
4823 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
4824 		return 0;
4825 
4826 	if (cpu_migrate(cpu)) {
4827 		fprintf(outf, "print_thermal: Could not migrate to CPU %d\n", cpu);
4828 		return -1;
4829 	}
4830 
4831 	if (do_ptm && (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
4832 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
4833 			return 0;
4834 
4835 		dts = (msr >> 16) & 0x7F;
4836 		fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n", cpu, msr, tj_max - dts);
4837 
4838 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
4839 			return 0;
4840 
4841 		dts = (msr >> 16) & 0x7F;
4842 		dts2 = (msr >> 8) & 0x7F;
4843 		fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
4844 			cpu, msr, tj_max - dts, tj_max - dts2);
4845 	}
4846 
4847 	if (do_dts && debug) {
4848 		unsigned int resolution;
4849 
4850 		if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
4851 			return 0;
4852 
4853 		dts = (msr >> 16) & 0x7F;
4854 		resolution = (msr >> 27) & 0xF;
4855 		fprintf(outf, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
4856 			cpu, msr, tj_max - dts, resolution);
4857 
4858 		if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
4859 			return 0;
4860 
4861 		dts = (msr >> 16) & 0x7F;
4862 		dts2 = (msr >> 8) & 0x7F;
4863 		fprintf(outf, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
4864 			cpu, msr, tj_max - dts, tj_max - dts2);
4865 	}
4866 
4867 	return 0;
4868 }
4869 
4870 void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
4871 {
4872 	fprintf(outf, "cpu%d: %s: %sabled (%0.3f Watts, %f sec, clamp %sabled)\n",
4873 		cpu, label,
4874 		((msr >> 15) & 1) ? "EN" : "DIS",
4875 		((msr >> 0) & 0x7FFF) * rapl_power_units,
4876 		(1.0 + (((msr >> 22) & 0x3) / 4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
4877 		(((msr >> 16) & 1) ? "EN" : "DIS"));
4878 
4879 	return;
4880 }
4881 
4882 int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
4883 {
4884 	unsigned long long msr;
4885 	const char *msr_name;
4886 	int cpu;
4887 
4888 	UNUSED(c);
4889 	UNUSED(p);
4890 
4891 	if (!do_rapl)
4892 		return 0;
4893 
4894 	/* RAPL counters are per package, so print only for 1st thread/package */
4895 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
4896 		return 0;
4897 
4898 	cpu = t->cpu_id;
4899 	if (cpu_migrate(cpu)) {
4900 		fprintf(outf, "print_rapl: Could not migrate to CPU %d\n", cpu);
4901 		return -1;
4902 	}
4903 
4904 	if (do_rapl & RAPL_AMD_F17H) {
4905 		msr_name = "MSR_RAPL_PWR_UNIT";
4906 		if (get_msr(cpu, MSR_RAPL_PWR_UNIT, &msr))
4907 			return -1;
4908 	} else {
4909 		msr_name = "MSR_RAPL_POWER_UNIT";
4910 		if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
4911 			return -1;
4912 	}
4913 
4914 	fprintf(outf, "cpu%d: %s: 0x%08llx (%f Watts, %f Joules, %f sec.)\n", cpu, msr_name, msr,
4915 		rapl_power_units, rapl_energy_units, rapl_time_units);
4916 
4917 	if (do_rapl & RAPL_PKG_POWER_INFO) {
4918 
4919 		if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
4920 			return -5;
4921 
4922 		fprintf(outf, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
4923 			cpu, msr,
4924 			((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4925 			((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4926 			((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4927 			((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
4928 
4929 	}
4930 	if (do_rapl & RAPL_PKG) {
4931 
4932 		if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
4933 			return -9;
4934 
4935 		fprintf(outf, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
4936 			cpu, msr, (msr >> 63) & 1 ? "" : "UN");
4937 
4938 		print_power_limit_msr(cpu, msr, "PKG Limit #1");
4939 		fprintf(outf, "cpu%d: PKG Limit #2: %sabled (%0.3f Watts, %f* sec, clamp %sabled)\n",
4940 			cpu,
4941 			((msr >> 47) & 1) ? "EN" : "DIS",
4942 			((msr >> 32) & 0x7FFF) * rapl_power_units,
4943 			(1.0 + (((msr >> 54) & 0x3) / 4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
4944 			((msr >> 48) & 1) ? "EN" : "DIS");
4945 
4946 		if (get_msr(cpu, MSR_VR_CURRENT_CONFIG, &msr))
4947 			return -9;
4948 
4949 		fprintf(outf, "cpu%d: MSR_VR_CURRENT_CONFIG: 0x%08llx\n", cpu, msr);
4950 		fprintf(outf, "cpu%d: PKG Limit #4: %f Watts (%slocked)\n",
4951 			cpu, ((msr >> 0) & 0x1FFF) * rapl_power_units, (msr >> 31) & 1 ? "" : "UN");
4952 	}
4953 
4954 	if (do_rapl & RAPL_DRAM_POWER_INFO) {
4955 		if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
4956 			return -6;
4957 
4958 		fprintf(outf, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
4959 			cpu, msr,
4960 			((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4961 			((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4962 			((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
4963 			((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
4964 	}
4965 	if (do_rapl & RAPL_DRAM) {
4966 		if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
4967 			return -9;
4968 		fprintf(outf, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
4969 			cpu, msr, (msr >> 31) & 1 ? "" : "UN");
4970 
4971 		print_power_limit_msr(cpu, msr, "DRAM Limit");
4972 	}
4973 	if (do_rapl & RAPL_CORE_POLICY) {
4974 		if (get_msr(cpu, MSR_PP0_POLICY, &msr))
4975 			return -7;
4976 
4977 		fprintf(outf, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
4978 	}
4979 	if (do_rapl & RAPL_CORES_POWER_LIMIT) {
4980 		if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
4981 			return -9;
4982 		fprintf(outf, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
4983 			cpu, msr, (msr >> 31) & 1 ? "" : "UN");
4984 		print_power_limit_msr(cpu, msr, "Cores Limit");
4985 	}
4986 	if (do_rapl & RAPL_GFX) {
4987 		if (get_msr(cpu, MSR_PP1_POLICY, &msr))
4988 			return -8;
4989 
4990 		fprintf(outf, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
4991 
4992 		if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
4993 			return -9;
4994 		fprintf(outf, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
4995 			cpu, msr, (msr >> 31) & 1 ? "" : "UN");
4996 		print_power_limit_msr(cpu, msr, "GFX Limit");
4997 	}
4998 	return 0;
4999 }
5000 
5001 /*
5002  * SNB adds support for additional MSRs:
5003  *
5004  * MSR_PKG_C7_RESIDENCY            0x000003fa
5005  * MSR_CORE_C7_RESIDENCY           0x000003fe
5006  * MSR_PKG_C2_RESIDENCY            0x0000060d
5007  */
5008 
5009 int has_snb_msrs(unsigned int family, unsigned int model)
5010 {
5011 	if (!genuine_intel)
5012 		return 0;
5013 
5014 	if (family != 6)
5015 		return 0;
5016 
5017 	switch (model) {
5018 	case INTEL_FAM6_SANDYBRIDGE:
5019 	case INTEL_FAM6_SANDYBRIDGE_X:
5020 	case INTEL_FAM6_IVYBRIDGE:	/* IVB */
5021 	case INTEL_FAM6_IVYBRIDGE_X:	/* IVB Xeon */
5022 	case INTEL_FAM6_HASWELL:	/* HSW */
5023 	case INTEL_FAM6_HASWELL_X:	/* HSW */
5024 	case INTEL_FAM6_HASWELL_L:	/* HSW */
5025 	case INTEL_FAM6_HASWELL_G:	/* HSW */
5026 	case INTEL_FAM6_BROADWELL:	/* BDW */
5027 	case INTEL_FAM6_BROADWELL_G:	/* BDW */
5028 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
5029 	case INTEL_FAM6_SKYLAKE_L:	/* SKL */
5030 	case INTEL_FAM6_CANNONLAKE_L:	/* CNL */
5031 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
5032 	case INTEL_FAM6_ICELAKE_X:	/* ICX */
5033 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
5034 	case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
5035 	case INTEL_FAM6_ATOM_GOLDMONT_D:	/* DNV */
5036 	case INTEL_FAM6_ATOM_TREMONT:	/* EHL */
5037 	case INTEL_FAM6_ATOM_TREMONT_D:	/* JVL */
5038 		return 1;
5039 	}
5040 	return 0;
5041 }
5042 
5043 /*
5044  * HSW ULT added support for C8/C9/C10 MSRs:
5045  *
5046  * MSR_PKG_C8_RESIDENCY		0x00000630
5047  * MSR_PKG_C9_RESIDENCY		0x00000631
5048  * MSR_PKG_C10_RESIDENCY	0x00000632
5049  *
5050  * MSR_PKGC8_IRTL		0x00000633
5051  * MSR_PKGC9_IRTL		0x00000634
5052  * MSR_PKGC10_IRTL		0x00000635
5053  *
5054  */
5055 int has_c8910_msrs(unsigned int family, unsigned int model)
5056 {
5057 	if (!genuine_intel)
5058 		return 0;
5059 
5060 	if (family != 6)
5061 		return 0;
5062 
5063 	switch (model) {
5064 	case INTEL_FAM6_HASWELL_L:	/* HSW */
5065 	case INTEL_FAM6_BROADWELL:	/* BDW */
5066 	case INTEL_FAM6_SKYLAKE_L:	/* SKL */
5067 	case INTEL_FAM6_CANNONLAKE_L:	/* CNL */
5068 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
5069 	case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
5070 	case INTEL_FAM6_ATOM_TREMONT:	/* EHL */
5071 		return 1;
5072 	}
5073 	return 0;
5074 }
5075 
5076 /*
5077  * SKL adds support for additional MSRS:
5078  *
5079  * MSR_PKG_WEIGHTED_CORE_C0_RES    0x00000658
5080  * MSR_PKG_ANY_CORE_C0_RES         0x00000659
5081  * MSR_PKG_ANY_GFXE_C0_RES         0x0000065A
5082  * MSR_PKG_BOTH_CORE_GFXE_C0_RES   0x0000065B
5083  */
5084 int has_skl_msrs(unsigned int family, unsigned int model)
5085 {
5086 	if (!genuine_intel)
5087 		return 0;
5088 
5089 	if (family != 6)
5090 		return 0;
5091 
5092 	switch (model) {
5093 	case INTEL_FAM6_SKYLAKE_L:	/* SKL */
5094 	case INTEL_FAM6_CANNONLAKE_L:	/* CNL */
5095 		return 1;
5096 	}
5097 	return 0;
5098 }
5099 
5100 int is_slm(unsigned int family, unsigned int model)
5101 {
5102 	if (!genuine_intel)
5103 		return 0;
5104 
5105 	if (family != 6)
5106 		return 0;
5107 
5108 	switch (model) {
5109 	case INTEL_FAM6_ATOM_SILVERMONT:	/* BYT */
5110 	case INTEL_FAM6_ATOM_SILVERMONT_D:	/* AVN */
5111 		return 1;
5112 	}
5113 	return 0;
5114 }
5115 
5116 int is_knl(unsigned int family, unsigned int model)
5117 {
5118 	if (!genuine_intel)
5119 		return 0;
5120 
5121 	if (family != 6)
5122 		return 0;
5123 
5124 	switch (model) {
5125 	case INTEL_FAM6_XEON_PHI_KNL:	/* KNL */
5126 		return 1;
5127 	}
5128 	return 0;
5129 }
5130 
5131 int is_cnl(unsigned int family, unsigned int model)
5132 {
5133 	if (!genuine_intel)
5134 		return 0;
5135 
5136 	if (family != 6)
5137 		return 0;
5138 
5139 	switch (model) {
5140 	case INTEL_FAM6_CANNONLAKE_L:	/* CNL */
5141 		return 1;
5142 	}
5143 
5144 	return 0;
5145 }
5146 
5147 unsigned int get_aperf_mperf_multiplier(unsigned int family, unsigned int model)
5148 {
5149 	if (is_knl(family, model))
5150 		return 1024;
5151 	return 1;
5152 }
5153 
5154 #define SLM_BCLK_FREQS 5
5155 double slm_freq_table[SLM_BCLK_FREQS] = { 83.3, 100.0, 133.3, 116.7, 80.0 };
5156 
5157 double slm_bclk(void)
5158 {
5159 	unsigned long long msr = 3;
5160 	unsigned int i;
5161 	double freq;
5162 
5163 	if (get_msr(base_cpu, MSR_FSB_FREQ, &msr))
5164 		fprintf(outf, "SLM BCLK: unknown\n");
5165 
5166 	i = msr & 0xf;
5167 	if (i >= SLM_BCLK_FREQS) {
5168 		fprintf(outf, "SLM BCLK[%d] invalid\n", i);
5169 		i = 3;
5170 	}
5171 	freq = slm_freq_table[i];
5172 
5173 	if (!quiet)
5174 		fprintf(outf, "SLM BCLK: %.1f Mhz\n", freq);
5175 
5176 	return freq;
5177 }
5178 
5179 double discover_bclk(unsigned int family, unsigned int model)
5180 {
5181 	if (has_snb_msrs(family, model) || is_knl(family, model))
5182 		return 100.00;
5183 	else if (is_slm(family, model))
5184 		return slm_bclk();
5185 	else
5186 		return 133.33;
5187 }
5188 
5189 int get_cpu_type(struct thread_data *t, struct core_data *c, struct pkg_data *p)
5190 {
5191 	unsigned int eax, ebx, ecx, edx;
5192 
5193 	UNUSED(c);
5194 	UNUSED(p);
5195 
5196 	if (!genuine_intel)
5197 		return 0;
5198 
5199 	if (cpu_migrate(t->cpu_id)) {
5200 		fprintf(outf, "Could not migrate to CPU %d\n", t->cpu_id);
5201 		return -1;
5202 	}
5203 
5204 	if (max_level < 0x1a)
5205 		return 0;
5206 
5207 	__cpuid(0x1a, eax, ebx, ecx, edx);
5208 	eax = (eax >> 24) & 0xFF;
5209 	if (eax == 0x20)
5210 		t->is_atom = true;
5211 	return 0;
5212 }
5213 
5214 /*
5215  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
5216  * the Thermal Control Circuit (TCC) activates.
5217  * This is usually equal to tjMax.
5218  *
5219  * Older processors do not have this MSR, so there we guess,
5220  * but also allow cmdline over-ride with -T.
5221  *
5222  * Several MSR temperature values are in units of degrees-C
5223  * below this value, including the Digital Thermal Sensor (DTS),
5224  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
5225  */
5226 int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
5227 {
5228 	unsigned long long msr;
5229 	unsigned int tcc_default, tcc_offset;
5230 	int cpu;
5231 
5232 	UNUSED(c);
5233 	UNUSED(p);
5234 
5235 	/* tj_max is used only for dts or ptm */
5236 	if (!(do_dts || do_ptm))
5237 		return 0;
5238 
5239 	/* this is a per-package concept */
5240 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
5241 		return 0;
5242 
5243 	cpu = t->cpu_id;
5244 	if (cpu_migrate(cpu)) {
5245 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
5246 		return -1;
5247 	}
5248 
5249 	if (tj_max_override != 0) {
5250 		tj_max = tj_max_override;
5251 		fprintf(outf, "cpu%d: Using cmdline TCC Target (%d C)\n", cpu, tj_max);
5252 		return 0;
5253 	}
5254 
5255 	/* Temperature Target MSR is Nehalem and newer only */
5256 	if (!do_nhm_platform_info)
5257 		goto guess;
5258 
5259 	if (get_msr(base_cpu, MSR_IA32_TEMPERATURE_TARGET, &msr))
5260 		goto guess;
5261 
5262 	tcc_default = (msr >> 16) & 0xFF;
5263 
5264 	if (!quiet) {
5265 		switch (tcc_offset_bits) {
5266 		case 4:
5267 			tcc_offset = (msr >> 24) & 0xF;
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 		case 6:
5272 			tcc_offset = (msr >> 24) & 0x3F;
5273 			fprintf(outf, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C) (%d default - %d offset)\n",
5274 				cpu, msr, tcc_default - tcc_offset, tcc_default, tcc_offset);
5275 			break;
5276 		default:
5277 			fprintf(outf, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n", cpu, msr, tcc_default);
5278 			break;
5279 		}
5280 	}
5281 
5282 	if (!tcc_default)
5283 		goto guess;
5284 
5285 	tj_max = tcc_default;
5286 
5287 	return 0;
5288 
5289 guess:
5290 	tj_max = TJMAX_DEFAULT;
5291 	fprintf(outf, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n", cpu, tj_max);
5292 
5293 	return 0;
5294 }
5295 
5296 void decode_feature_control_msr(void)
5297 {
5298 	unsigned long long msr;
5299 
5300 	if (!get_msr(base_cpu, MSR_IA32_FEAT_CTL, &msr))
5301 		fprintf(outf, "cpu%d: MSR_IA32_FEATURE_CONTROL: 0x%08llx (%sLocked %s)\n",
5302 			base_cpu, msr, msr & FEAT_CTL_LOCKED ? "" : "UN-", msr & (1 << 18) ? "SGX" : "");
5303 }
5304 
5305 void decode_misc_enable_msr(void)
5306 {
5307 	unsigned long long msr;
5308 
5309 	if (!genuine_intel)
5310 		return;
5311 
5312 	if (!get_msr(base_cpu, MSR_IA32_MISC_ENABLE, &msr))
5313 		fprintf(outf, "cpu%d: MSR_IA32_MISC_ENABLE: 0x%08llx (%sTCC %sEIST %sMWAIT %sPREFETCH %sTURBO)\n",
5314 			base_cpu, msr,
5315 			msr & MSR_IA32_MISC_ENABLE_TM1 ? "" : "No-",
5316 			msr & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP ? "" : "No-",
5317 			msr & MSR_IA32_MISC_ENABLE_MWAIT ? "" : "No-",
5318 			msr & MSR_IA32_MISC_ENABLE_PREFETCH_DISABLE ? "No-" : "",
5319 			msr & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ? "No-" : "");
5320 }
5321 
5322 void decode_misc_feature_control(void)
5323 {
5324 	unsigned long long msr;
5325 
5326 	if (!has_misc_feature_control)
5327 		return;
5328 
5329 	if (!get_msr(base_cpu, MSR_MISC_FEATURE_CONTROL, &msr))
5330 		fprintf(outf,
5331 			"cpu%d: MSR_MISC_FEATURE_CONTROL: 0x%08llx (%sL2-Prefetch %sL2-Prefetch-pair %sL1-Prefetch %sL1-IP-Prefetch)\n",
5332 			base_cpu, msr, msr & (0 << 0) ? "No-" : "", msr & (1 << 0) ? "No-" : "",
5333 			msr & (2 << 0) ? "No-" : "", msr & (3 << 0) ? "No-" : "");
5334 }
5335 
5336 /*
5337  * Decode MSR_MISC_PWR_MGMT
5338  *
5339  * Decode the bits according to the Nehalem documentation
5340  * bit[0] seems to continue to have same meaning going forward
5341  * bit[1] less so...
5342  */
5343 void decode_misc_pwr_mgmt_msr(void)
5344 {
5345 	unsigned long long msr;
5346 
5347 	if (!do_nhm_platform_info)
5348 		return;
5349 
5350 	if (no_MSR_MISC_PWR_MGMT)
5351 		return;
5352 
5353 	if (!get_msr(base_cpu, MSR_MISC_PWR_MGMT, &msr))
5354 		fprintf(outf, "cpu%d: MSR_MISC_PWR_MGMT: 0x%08llx (%sable-EIST_Coordination %sable-EPB %sable-OOB)\n",
5355 			base_cpu, msr,
5356 			msr & (1 << 0) ? "DIS" : "EN", msr & (1 << 1) ? "EN" : "DIS", msr & (1 << 8) ? "EN" : "DIS");
5357 }
5358 
5359 /*
5360  * Decode MSR_CC6_DEMOTION_POLICY_CONFIG, MSR_MC6_DEMOTION_POLICY_CONFIG
5361  *
5362  * This MSRs are present on Silvermont processors,
5363  * Intel Atom processor E3000 series (Baytrail), and friends.
5364  */
5365 void decode_c6_demotion_policy_msr(void)
5366 {
5367 	unsigned long long msr;
5368 
5369 	if (!get_msr(base_cpu, MSR_CC6_DEMOTION_POLICY_CONFIG, &msr))
5370 		fprintf(outf, "cpu%d: MSR_CC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-CC6-Demotion)\n",
5371 			base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
5372 
5373 	if (!get_msr(base_cpu, MSR_MC6_DEMOTION_POLICY_CONFIG, &msr))
5374 		fprintf(outf, "cpu%d: MSR_MC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-MC6-Demotion)\n",
5375 			base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
5376 }
5377 
5378 /*
5379  * When models are the same, for the purpose of turbostat, reuse
5380  */
5381 unsigned int intel_model_duplicates(unsigned int model)
5382 {
5383 
5384 	switch (model) {
5385 	case INTEL_FAM6_NEHALEM_EP:	/* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
5386 	case INTEL_FAM6_NEHALEM:	/* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
5387 	case 0x1F:		/* Core i7 and i5 Processor - Nehalem */
5388 	case INTEL_FAM6_WESTMERE:	/* Westmere Client - Clarkdale, Arrandale */
5389 	case INTEL_FAM6_WESTMERE_EP:	/* Westmere EP - Gulftown */
5390 		return INTEL_FAM6_NEHALEM;
5391 
5392 	case INTEL_FAM6_NEHALEM_EX:	/* Nehalem-EX Xeon - Beckton */
5393 	case INTEL_FAM6_WESTMERE_EX:	/* Westmere-EX Xeon - Eagleton */
5394 		return INTEL_FAM6_NEHALEM_EX;
5395 
5396 	case INTEL_FAM6_XEON_PHI_KNM:
5397 		return INTEL_FAM6_XEON_PHI_KNL;
5398 
5399 	case INTEL_FAM6_BROADWELL_X:
5400 	case INTEL_FAM6_BROADWELL_D:	/* BDX-DE */
5401 		return INTEL_FAM6_BROADWELL_X;
5402 
5403 	case INTEL_FAM6_SKYLAKE_L:
5404 	case INTEL_FAM6_SKYLAKE:
5405 	case INTEL_FAM6_KABYLAKE_L:
5406 	case INTEL_FAM6_KABYLAKE:
5407 	case INTEL_FAM6_COMETLAKE_L:
5408 	case INTEL_FAM6_COMETLAKE:
5409 		return INTEL_FAM6_SKYLAKE_L;
5410 
5411 	case INTEL_FAM6_ICELAKE_L:
5412 	case INTEL_FAM6_ICELAKE_NNPI:
5413 	case INTEL_FAM6_TIGERLAKE_L:
5414 	case INTEL_FAM6_TIGERLAKE:
5415 	case INTEL_FAM6_ROCKETLAKE:
5416 	case INTEL_FAM6_LAKEFIELD:
5417 	case INTEL_FAM6_ALDERLAKE:
5418 	case INTEL_FAM6_ALDERLAKE_L:
5419 	case INTEL_FAM6_ALDERLAKE_N:
5420 	case INTEL_FAM6_RAPTORLAKE:
5421 	case INTEL_FAM6_RAPTORLAKE_P:
5422 		return INTEL_FAM6_CANNONLAKE_L;
5423 
5424 	case INTEL_FAM6_ATOM_TREMONT_L:
5425 		return INTEL_FAM6_ATOM_TREMONT;
5426 
5427 	case INTEL_FAM6_ICELAKE_D:
5428 	case INTEL_FAM6_SAPPHIRERAPIDS_X:
5429 		return INTEL_FAM6_ICELAKE_X;
5430 	}
5431 	return model;
5432 }
5433 
5434 void print_dev_latency(void)
5435 {
5436 	char *path = "/dev/cpu_dma_latency";
5437 	int fd;
5438 	int value;
5439 	int retval;
5440 
5441 	fd = open(path, O_RDONLY);
5442 	if (fd < 0) {
5443 		warn("fopen %s\n", path);
5444 		return;
5445 	}
5446 
5447 	retval = read(fd, (void *)&value, sizeof(int));
5448 	if (retval != sizeof(int)) {
5449 		warn("read %s\n", path);
5450 		close(fd);
5451 		return;
5452 	}
5453 	fprintf(outf, "/dev/cpu_dma_latency: %d usec (%s)\n", value, value == 2000000000 ? "default" : "constrained");
5454 
5455 	close(fd);
5456 }
5457 
5458 /*
5459  * Linux-perf manages the the HW instructions-retired counter
5460  * by enabling when requested, and hiding rollover
5461  */
5462 void linux_perf_init(void)
5463 {
5464 	if (!BIC_IS_ENABLED(BIC_IPC))
5465 		return;
5466 
5467 	if (access("/proc/sys/kernel/perf_event_paranoid", F_OK))
5468 		return;
5469 
5470 	fd_instr_count_percpu = calloc(topo.max_cpu_num + 1, sizeof(int));
5471 	if (fd_instr_count_percpu == NULL)
5472 		err(-1, "calloc fd_instr_count_percpu");
5473 
5474 	BIC_PRESENT(BIC_IPC);
5475 }
5476 
5477 void process_cpuid()
5478 {
5479 	unsigned int eax, ebx, ecx, edx;
5480 	unsigned int fms, family, model, stepping, ecx_flags, edx_flags;
5481 	unsigned int has_turbo;
5482 	unsigned long long ucode_patch = 0;
5483 
5484 	eax = ebx = ecx = edx = 0;
5485 
5486 	__cpuid(0, max_level, ebx, ecx, edx);
5487 
5488 	if (ebx == 0x756e6547 && ecx == 0x6c65746e && edx == 0x49656e69)
5489 		genuine_intel = 1;
5490 	else if (ebx == 0x68747541 && ecx == 0x444d4163 && edx == 0x69746e65)
5491 		authentic_amd = 1;
5492 	else if (ebx == 0x6f677948 && ecx == 0x656e6975 && edx == 0x6e65476e)
5493 		hygon_genuine = 1;
5494 
5495 	if (!quiet)
5496 		fprintf(outf, "CPUID(0): %.4s%.4s%.4s 0x%x CPUID levels\n",
5497 			(char *)&ebx, (char *)&edx, (char *)&ecx, max_level);
5498 
5499 	__cpuid(1, fms, ebx, ecx, edx);
5500 	family = (fms >> 8) & 0xf;
5501 	model = (fms >> 4) & 0xf;
5502 	stepping = fms & 0xf;
5503 	if (family == 0xf)
5504 		family += (fms >> 20) & 0xff;
5505 	if (family >= 6)
5506 		model += ((fms >> 16) & 0xf) << 4;
5507 	ecx_flags = ecx;
5508 	edx_flags = edx;
5509 
5510 	if (get_msr(sched_getcpu(), MSR_IA32_UCODE_REV, &ucode_patch))
5511 		warnx("get_msr(UCODE)\n");
5512 
5513 	/*
5514 	 * check max extended function levels of CPUID.
5515 	 * This is needed to check for invariant TSC.
5516 	 * This check is valid for both Intel and AMD.
5517 	 */
5518 	ebx = ecx = edx = 0;
5519 	__cpuid(0x80000000, max_extended_level, ebx, ecx, edx);
5520 
5521 	if (!quiet) {
5522 		fprintf(outf, "CPUID(1): family:model:stepping 0x%x:%x:%x (%d:%d:%d) microcode 0x%x\n",
5523 			family, model, stepping, family, model, stepping,
5524 			(unsigned int)((ucode_patch >> 32) & 0xFFFFFFFF));
5525 		fprintf(outf, "CPUID(0x80000000): max_extended_levels: 0x%x\n", max_extended_level);
5526 		fprintf(outf, "CPUID(1): %s %s %s %s %s %s %s %s %s %s\n",
5527 			ecx_flags & (1 << 0) ? "SSE3" : "-",
5528 			ecx_flags & (1 << 3) ? "MONITOR" : "-",
5529 			ecx_flags & (1 << 6) ? "SMX" : "-",
5530 			ecx_flags & (1 << 7) ? "EIST" : "-",
5531 			ecx_flags & (1 << 8) ? "TM2" : "-",
5532 			edx_flags & (1 << 4) ? "TSC" : "-",
5533 			edx_flags & (1 << 5) ? "MSR" : "-",
5534 			edx_flags & (1 << 22) ? "ACPI-TM" : "-",
5535 			edx_flags & (1 << 28) ? "HT" : "-", edx_flags & (1 << 29) ? "TM" : "-");
5536 	}
5537 	if (genuine_intel) {
5538 		model_orig = model;
5539 		model = intel_model_duplicates(model);
5540 	}
5541 
5542 	if (!(edx_flags & (1 << 5)))
5543 		errx(1, "CPUID: no MSR");
5544 
5545 	if (max_extended_level >= 0x80000007) {
5546 
5547 		/*
5548 		 * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
5549 		 * this check is valid for both Intel and AMD
5550 		 */
5551 		__cpuid(0x80000007, eax, ebx, ecx, edx);
5552 		has_invariant_tsc = edx & (1 << 8);
5553 	}
5554 
5555 	/*
5556 	 * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
5557 	 * this check is valid for both Intel and AMD
5558 	 */
5559 
5560 	__cpuid(0x6, eax, ebx, ecx, edx);
5561 	has_aperf = ecx & (1 << 0);
5562 	if (has_aperf) {
5563 		BIC_PRESENT(BIC_Avg_MHz);
5564 		BIC_PRESENT(BIC_Busy);
5565 		BIC_PRESENT(BIC_Bzy_MHz);
5566 	}
5567 	do_dts = eax & (1 << 0);
5568 	if (do_dts)
5569 		BIC_PRESENT(BIC_CoreTmp);
5570 	has_turbo = eax & (1 << 1);
5571 	do_ptm = eax & (1 << 6);
5572 	if (do_ptm)
5573 		BIC_PRESENT(BIC_PkgTmp);
5574 	has_hwp = eax & (1 << 7);
5575 	has_hwp_notify = eax & (1 << 8);
5576 	has_hwp_activity_window = eax & (1 << 9);
5577 	has_hwp_epp = eax & (1 << 10);
5578 	has_hwp_pkg = eax & (1 << 11);
5579 	has_epb = ecx & (1 << 3);
5580 
5581 	if (!quiet)
5582 		fprintf(outf, "CPUID(6): %sAPERF, %sTURBO, %sDTS, %sPTM, %sHWP, "
5583 			"%sHWPnotify, %sHWPwindow, %sHWPepp, %sHWPpkg, %sEPB\n",
5584 			has_aperf ? "" : "No-",
5585 			has_turbo ? "" : "No-",
5586 			do_dts ? "" : "No-",
5587 			do_ptm ? "" : "No-",
5588 			has_hwp ? "" : "No-",
5589 			has_hwp_notify ? "" : "No-",
5590 			has_hwp_activity_window ? "" : "No-",
5591 			has_hwp_epp ? "" : "No-", has_hwp_pkg ? "" : "No-", has_epb ? "" : "No-");
5592 
5593 	if (!quiet)
5594 		decode_misc_enable_msr();
5595 
5596 	if (max_level >= 0x7 && !quiet) {
5597 		int has_sgx;
5598 
5599 		ecx = 0;
5600 
5601 		__cpuid_count(0x7, 0, eax, ebx, ecx, edx);
5602 
5603 		has_sgx = ebx & (1 << 2);
5604 
5605 		is_hybrid = edx & (1 << 15);
5606 
5607 		fprintf(outf, "CPUID(7): %sSGX %sHybrid\n", has_sgx ? "" : "No-", is_hybrid ? "" : "No-");
5608 
5609 		if (has_sgx)
5610 			decode_feature_control_msr();
5611 	}
5612 
5613 	if (max_level >= 0x15) {
5614 		unsigned int eax_crystal;
5615 		unsigned int ebx_tsc;
5616 
5617 		/*
5618 		 * CPUID 15H TSC/Crystal ratio, possibly Crystal Hz
5619 		 */
5620 		eax_crystal = ebx_tsc = crystal_hz = edx = 0;
5621 		__cpuid(0x15, eax_crystal, ebx_tsc, crystal_hz, edx);
5622 
5623 		if (ebx_tsc != 0) {
5624 
5625 			if (!quiet && (ebx != 0))
5626 				fprintf(outf, "CPUID(0x15): eax_crystal: %d ebx_tsc: %d ecx_crystal_hz: %d\n",
5627 					eax_crystal, ebx_tsc, crystal_hz);
5628 
5629 			if (crystal_hz == 0)
5630 				switch (model) {
5631 				case INTEL_FAM6_SKYLAKE_L:	/* SKL */
5632 					crystal_hz = 24000000;	/* 24.0 MHz */
5633 					break;
5634 				case INTEL_FAM6_ATOM_GOLDMONT_D:	/* DNV */
5635 					crystal_hz = 25000000;	/* 25.0 MHz */
5636 					break;
5637 				case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
5638 				case INTEL_FAM6_ATOM_GOLDMONT_PLUS:
5639 					crystal_hz = 19200000;	/* 19.2 MHz */
5640 					break;
5641 				default:
5642 					crystal_hz = 0;
5643 				}
5644 
5645 			if (crystal_hz) {
5646 				tsc_hz = (unsigned long long)crystal_hz *ebx_tsc / eax_crystal;
5647 				if (!quiet)
5648 					fprintf(outf, "TSC: %lld MHz (%d Hz * %d / %d / 1000000)\n",
5649 						tsc_hz / 1000000, crystal_hz, ebx_tsc, eax_crystal);
5650 			}
5651 		}
5652 	}
5653 	if (max_level >= 0x16) {
5654 		unsigned int base_mhz, max_mhz, bus_mhz, edx;
5655 
5656 		/*
5657 		 * CPUID 16H Base MHz, Max MHz, Bus MHz
5658 		 */
5659 		base_mhz = max_mhz = bus_mhz = edx = 0;
5660 
5661 		__cpuid(0x16, base_mhz, max_mhz, bus_mhz, edx);
5662 		if (!quiet)
5663 			fprintf(outf, "CPUID(0x16): base_mhz: %d max_mhz: %d bus_mhz: %d\n",
5664 				base_mhz, max_mhz, bus_mhz);
5665 	}
5666 
5667 	if (has_aperf)
5668 		aperf_mperf_multiplier = get_aperf_mperf_multiplier(family, model);
5669 
5670 	BIC_PRESENT(BIC_IRQ);
5671 	BIC_PRESENT(BIC_TSC_MHz);
5672 
5673 	if (probe_nhm_msrs(family, model)) {
5674 		do_nhm_platform_info = 1;
5675 		BIC_PRESENT(BIC_CPU_c1);
5676 		BIC_PRESENT(BIC_CPU_c3);
5677 		BIC_PRESENT(BIC_CPU_c6);
5678 		BIC_PRESENT(BIC_SMI);
5679 	}
5680 	do_snb_cstates = has_snb_msrs(family, model);
5681 
5682 	if (do_snb_cstates)
5683 		BIC_PRESENT(BIC_CPU_c7);
5684 
5685 	do_irtl_snb = has_snb_msrs(family, model);
5686 	if (do_snb_cstates && (pkg_cstate_limit >= PCL__2))
5687 		BIC_PRESENT(BIC_Pkgpc2);
5688 	if (pkg_cstate_limit >= PCL__3)
5689 		BIC_PRESENT(BIC_Pkgpc3);
5690 	if (pkg_cstate_limit >= PCL__6)
5691 		BIC_PRESENT(BIC_Pkgpc6);
5692 	if (do_snb_cstates && (pkg_cstate_limit >= PCL__7))
5693 		BIC_PRESENT(BIC_Pkgpc7);
5694 	if (has_slv_msrs(family, model)) {
5695 		BIC_NOT_PRESENT(BIC_Pkgpc2);
5696 		BIC_NOT_PRESENT(BIC_Pkgpc3);
5697 		BIC_PRESENT(BIC_Pkgpc6);
5698 		BIC_NOT_PRESENT(BIC_Pkgpc7);
5699 		BIC_PRESENT(BIC_Mod_c6);
5700 		use_c1_residency_msr = 1;
5701 	}
5702 	if (is_jvl(family, model)) {
5703 		BIC_NOT_PRESENT(BIC_CPU_c3);
5704 		BIC_NOT_PRESENT(BIC_CPU_c7);
5705 		BIC_NOT_PRESENT(BIC_Pkgpc2);
5706 		BIC_NOT_PRESENT(BIC_Pkgpc3);
5707 		BIC_NOT_PRESENT(BIC_Pkgpc6);
5708 		BIC_NOT_PRESENT(BIC_Pkgpc7);
5709 	}
5710 	if (is_dnv(family, model)) {
5711 		BIC_PRESENT(BIC_CPU_c1);
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 		use_c1_residency_msr = 1;
5717 	}
5718 	if (is_skx(family, model) || is_icx(family, model)) {
5719 		BIC_NOT_PRESENT(BIC_CPU_c3);
5720 		BIC_NOT_PRESENT(BIC_Pkgpc3);
5721 		BIC_NOT_PRESENT(BIC_CPU_c7);
5722 		BIC_NOT_PRESENT(BIC_Pkgpc7);
5723 	}
5724 	if (is_bdx(family, model)) {
5725 		BIC_NOT_PRESENT(BIC_CPU_c7);
5726 		BIC_NOT_PRESENT(BIC_Pkgpc7);
5727 	}
5728 	if (has_c8910_msrs(family, model)) {
5729 		if (pkg_cstate_limit >= PCL__8)
5730 			BIC_PRESENT(BIC_Pkgpc8);
5731 		if (pkg_cstate_limit >= PCL__9)
5732 			BIC_PRESENT(BIC_Pkgpc9);
5733 		if (pkg_cstate_limit >= PCL_10)
5734 			BIC_PRESENT(BIC_Pkgpc10);
5735 	}
5736 	do_irtl_hsw = has_c8910_msrs(family, model);
5737 	if (has_skl_msrs(family, model)) {
5738 		BIC_PRESENT(BIC_Totl_c0);
5739 		BIC_PRESENT(BIC_Any_c0);
5740 		BIC_PRESENT(BIC_GFX_c0);
5741 		BIC_PRESENT(BIC_CPUGFX);
5742 	}
5743 	do_slm_cstates = is_slm(family, model);
5744 	do_knl_cstates = is_knl(family, model);
5745 
5746 	if (do_slm_cstates || do_knl_cstates || is_cnl(family, model) || is_ehl(family, model))
5747 		BIC_NOT_PRESENT(BIC_CPU_c3);
5748 
5749 	if (!quiet)
5750 		decode_misc_pwr_mgmt_msr();
5751 
5752 	if (!quiet && has_slv_msrs(family, model))
5753 		decode_c6_demotion_policy_msr();
5754 
5755 	rapl_probe(family, model);
5756 	perf_limit_reasons_probe(family, model);
5757 	automatic_cstate_conversion_probe(family, model);
5758 
5759 	check_tcc_offset(model_orig);
5760 
5761 	if (!quiet)
5762 		dump_cstate_pstate_config_info(family, model);
5763 	intel_uncore_frequency_probe();
5764 
5765 	if (!quiet)
5766 		print_dev_latency();
5767 	if (!quiet)
5768 		dump_sysfs_cstate_config();
5769 	if (!quiet)
5770 		dump_sysfs_pstate_config();
5771 
5772 	if (has_skl_msrs(family, model) || is_ehl(family, model))
5773 		calculate_tsc_tweak();
5774 
5775 	if (!access("/sys/class/drm/card0/power/rc6_residency_ms", R_OK))
5776 		BIC_PRESENT(BIC_GFX_rc6);
5777 
5778 	if (!access("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", R_OK))
5779 		BIC_PRESENT(BIC_GFXMHz);
5780 
5781 	if (!access("/sys/class/graphics/fb0/device/drm/card0/gt_act_freq_mhz", R_OK))
5782 		BIC_PRESENT(BIC_GFXACTMHz);
5783 
5784 	if (!access("/sys/devices/system/cpu/cpuidle/low_power_idle_cpu_residency_us", R_OK))
5785 		BIC_PRESENT(BIC_CPU_LPI);
5786 	else
5787 		BIC_NOT_PRESENT(BIC_CPU_LPI);
5788 
5789 	if (!access("/sys/devices/system/cpu/cpu0/thermal_throttle/core_throttle_count", R_OK))
5790 		BIC_PRESENT(BIC_CORE_THROT_CNT);
5791 	else
5792 		BIC_NOT_PRESENT(BIC_CORE_THROT_CNT);
5793 
5794 	if (!access(sys_lpi_file_sysfs, R_OK)) {
5795 		sys_lpi_file = sys_lpi_file_sysfs;
5796 		BIC_PRESENT(BIC_SYS_LPI);
5797 	} else if (!access(sys_lpi_file_debugfs, R_OK)) {
5798 		sys_lpi_file = sys_lpi_file_debugfs;
5799 		BIC_PRESENT(BIC_SYS_LPI);
5800 	} else {
5801 		sys_lpi_file_sysfs = NULL;
5802 		BIC_NOT_PRESENT(BIC_SYS_LPI);
5803 	}
5804 
5805 	if (!quiet)
5806 		decode_misc_feature_control();
5807 
5808 	return;
5809 }
5810 
5811 /*
5812  * in /dev/cpu/ return success for names that are numbers
5813  * ie. filter out ".", "..", "microcode".
5814  */
5815 int dir_filter(const struct dirent *dirp)
5816 {
5817 	if (isdigit(dirp->d_name[0]))
5818 		return 1;
5819 	else
5820 		return 0;
5821 }
5822 
5823 void topology_probe()
5824 {
5825 	int i;
5826 	int max_core_id = 0;
5827 	int max_package_id = 0;
5828 	int max_die_id = 0;
5829 	int max_siblings = 0;
5830 
5831 	/* Initialize num_cpus, max_cpu_num */
5832 	set_max_cpu_num();
5833 	topo.num_cpus = 0;
5834 	for_all_proc_cpus(count_cpus);
5835 	if (!summary_only && topo.num_cpus > 1)
5836 		BIC_PRESENT(BIC_CPU);
5837 
5838 	if (debug > 1)
5839 		fprintf(outf, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
5840 
5841 	cpus = calloc(1, (topo.max_cpu_num + 1) * sizeof(struct cpu_topology));
5842 	if (cpus == NULL)
5843 		err(1, "calloc cpus");
5844 
5845 	/*
5846 	 * Allocate and initialize cpu_present_set
5847 	 */
5848 	cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
5849 	if (cpu_present_set == NULL)
5850 		err(3, "CPU_ALLOC");
5851 	cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5852 	CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
5853 	for_all_proc_cpus(mark_cpu_present);
5854 
5855 	/*
5856 	 * Validate that all cpus in cpu_subset are also in cpu_present_set
5857 	 */
5858 	for (i = 0; i < CPU_SUBSET_MAXCPUS; ++i) {
5859 		if (CPU_ISSET_S(i, cpu_subset_size, cpu_subset))
5860 			if (!CPU_ISSET_S(i, cpu_present_setsize, cpu_present_set))
5861 				err(1, "cpu%d not present", i);
5862 	}
5863 
5864 	/*
5865 	 * Allocate and initialize cpu_affinity_set
5866 	 */
5867 	cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
5868 	if (cpu_affinity_set == NULL)
5869 		err(3, "CPU_ALLOC");
5870 	cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
5871 	CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
5872 
5873 	for_all_proc_cpus(init_thread_id);
5874 
5875 	/*
5876 	 * For online cpus
5877 	 * find max_core_id, max_package_id
5878 	 */
5879 	for (i = 0; i <= topo.max_cpu_num; ++i) {
5880 		int siblings;
5881 
5882 		if (cpu_is_not_present(i)) {
5883 			if (debug > 1)
5884 				fprintf(outf, "cpu%d NOT PRESENT\n", i);
5885 			continue;
5886 		}
5887 
5888 		cpus[i].logical_cpu_id = i;
5889 
5890 		/* get package information */
5891 		cpus[i].physical_package_id = get_physical_package_id(i);
5892 		if (cpus[i].physical_package_id > max_package_id)
5893 			max_package_id = cpus[i].physical_package_id;
5894 
5895 		/* get die information */
5896 		cpus[i].die_id = get_die_id(i);
5897 		if (cpus[i].die_id > max_die_id)
5898 			max_die_id = cpus[i].die_id;
5899 
5900 		/* get numa node information */
5901 		cpus[i].physical_node_id = get_physical_node_id(&cpus[i]);
5902 		if (cpus[i].physical_node_id > topo.max_node_num)
5903 			topo.max_node_num = cpus[i].physical_node_id;
5904 
5905 		/* get core information */
5906 		cpus[i].physical_core_id = get_core_id(i);
5907 		if (cpus[i].physical_core_id > max_core_id)
5908 			max_core_id = cpus[i].physical_core_id;
5909 
5910 		/* get thread information */
5911 		siblings = get_thread_siblings(&cpus[i]);
5912 		if (siblings > max_siblings)
5913 			max_siblings = siblings;
5914 		if (cpus[i].thread_id == 0)
5915 			topo.num_cores++;
5916 	}
5917 
5918 	topo.cores_per_node = max_core_id + 1;
5919 	if (debug > 1)
5920 		fprintf(outf, "max_core_id %d, sizing for %d cores per package\n", max_core_id, topo.cores_per_node);
5921 	if (!summary_only && topo.cores_per_node > 1)
5922 		BIC_PRESENT(BIC_Core);
5923 
5924 	topo.num_die = max_die_id + 1;
5925 	if (debug > 1)
5926 		fprintf(outf, "max_die_id %d, sizing for %d die\n", max_die_id, topo.num_die);
5927 	if (!summary_only && topo.num_die > 1)
5928 		BIC_PRESENT(BIC_Die);
5929 
5930 	topo.num_packages = max_package_id + 1;
5931 	if (debug > 1)
5932 		fprintf(outf, "max_package_id %d, sizing for %d packages\n", max_package_id, topo.num_packages);
5933 	if (!summary_only && topo.num_packages > 1)
5934 		BIC_PRESENT(BIC_Package);
5935 
5936 	set_node_data();
5937 	if (debug > 1)
5938 		fprintf(outf, "nodes_per_pkg %d\n", topo.nodes_per_pkg);
5939 	if (!summary_only && topo.nodes_per_pkg > 1)
5940 		BIC_PRESENT(BIC_Node);
5941 
5942 	topo.threads_per_core = max_siblings;
5943 	if (debug > 1)
5944 		fprintf(outf, "max_siblings %d\n", max_siblings);
5945 
5946 	if (debug < 1)
5947 		return;
5948 
5949 	for (i = 0; i <= topo.max_cpu_num; ++i) {
5950 		if (cpu_is_not_present(i))
5951 			continue;
5952 		fprintf(outf,
5953 			"cpu %d pkg %d die %d node %d lnode %d core %d thread %d\n",
5954 			i, cpus[i].physical_package_id, cpus[i].die_id,
5955 			cpus[i].physical_node_id, cpus[i].logical_node_id, cpus[i].physical_core_id, cpus[i].thread_id);
5956 	}
5957 
5958 }
5959 
5960 void allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
5961 {
5962 	int i;
5963 	int num_cores = topo.cores_per_node * topo.nodes_per_pkg * topo.num_packages;
5964 	int num_threads = topo.threads_per_core * num_cores;
5965 
5966 	*t = calloc(num_threads, sizeof(struct thread_data));
5967 	if (*t == NULL)
5968 		goto error;
5969 
5970 	for (i = 0; i < num_threads; i++)
5971 		(*t)[i].cpu_id = -1;
5972 
5973 	*c = calloc(num_cores, sizeof(struct core_data));
5974 	if (*c == NULL)
5975 		goto error;
5976 
5977 	for (i = 0; i < num_cores; i++)
5978 		(*c)[i].core_id = -1;
5979 
5980 	*p = calloc(topo.num_packages, sizeof(struct pkg_data));
5981 	if (*p == NULL)
5982 		goto error;
5983 
5984 	for (i = 0; i < topo.num_packages; i++)
5985 		(*p)[i].package_id = i;
5986 
5987 	return;
5988 error:
5989 	err(1, "calloc counters");
5990 }
5991 
5992 /*
5993  * init_counter()
5994  *
5995  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
5996  */
5997 void init_counter(struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base, int cpu_id)
5998 {
5999 	int pkg_id = cpus[cpu_id].physical_package_id;
6000 	int node_id = cpus[cpu_id].logical_node_id;
6001 	int core_id = cpus[cpu_id].physical_core_id;
6002 	int thread_id = cpus[cpu_id].thread_id;
6003 	struct thread_data *t;
6004 	struct core_data *c;
6005 	struct pkg_data *p;
6006 
6007 	/* Workaround for systems where physical_node_id==-1
6008 	 * and logical_node_id==(-1 - topo.num_cpus)
6009 	 */
6010 	if (node_id < 0)
6011 		node_id = 0;
6012 
6013 	t = GET_THREAD(thread_base, thread_id, core_id, node_id, pkg_id);
6014 	c = GET_CORE(core_base, core_id, node_id, pkg_id);
6015 	p = GET_PKG(pkg_base, pkg_id);
6016 
6017 	t->cpu_id = cpu_id;
6018 	if (thread_id == 0) {
6019 		t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
6020 		if (cpu_is_first_core_in_package(cpu_id))
6021 			t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
6022 	}
6023 
6024 	c->core_id = core_id;
6025 	p->package_id = pkg_id;
6026 }
6027 
6028 int initialize_counters(int cpu_id)
6029 {
6030 	init_counter(EVEN_COUNTERS, cpu_id);
6031 	init_counter(ODD_COUNTERS, cpu_id);
6032 	return 0;
6033 }
6034 
6035 void allocate_output_buffer()
6036 {
6037 	output_buffer = calloc(1, (1 + topo.num_cpus) * 2048);
6038 	outp = output_buffer;
6039 	if (outp == NULL)
6040 		err(-1, "calloc output buffer");
6041 }
6042 
6043 void allocate_fd_percpu(void)
6044 {
6045 	fd_percpu = calloc(topo.max_cpu_num + 1, sizeof(int));
6046 	if (fd_percpu == NULL)
6047 		err(-1, "calloc fd_percpu");
6048 }
6049 
6050 void allocate_irq_buffers(void)
6051 {
6052 	irq_column_2_cpu = calloc(topo.num_cpus, sizeof(int));
6053 	if (irq_column_2_cpu == NULL)
6054 		err(-1, "calloc %d", topo.num_cpus);
6055 
6056 	irqs_per_cpu = calloc(topo.max_cpu_num + 1, sizeof(int));
6057 	if (irqs_per_cpu == NULL)
6058 		err(-1, "calloc %d", topo.max_cpu_num + 1);
6059 }
6060 
6061 void setup_all_buffers(void)
6062 {
6063 	topology_probe();
6064 	allocate_irq_buffers();
6065 	allocate_fd_percpu();
6066 	allocate_counters(&thread_even, &core_even, &package_even);
6067 	allocate_counters(&thread_odd, &core_odd, &package_odd);
6068 	allocate_output_buffer();
6069 	for_all_proc_cpus(initialize_counters);
6070 }
6071 
6072 void set_base_cpu(void)
6073 {
6074 	base_cpu = sched_getcpu();
6075 	if (base_cpu < 0)
6076 		err(-ENODEV, "No valid cpus found");
6077 
6078 	if (debug > 1)
6079 		fprintf(outf, "base_cpu = %d\n", base_cpu);
6080 }
6081 
6082 void turbostat_init()
6083 {
6084 	setup_all_buffers();
6085 	set_base_cpu();
6086 	check_dev_msr();
6087 	check_permissions();
6088 	process_cpuid();
6089 	linux_perf_init();
6090 
6091 	if (!quiet)
6092 		for_all_cpus(print_hwp, ODD_COUNTERS);
6093 
6094 	if (!quiet)
6095 		for_all_cpus(print_epb, ODD_COUNTERS);
6096 
6097 	if (!quiet)
6098 		for_all_cpus(print_perf_limit, ODD_COUNTERS);
6099 
6100 	if (!quiet)
6101 		for_all_cpus(print_rapl, ODD_COUNTERS);
6102 
6103 	for_all_cpus(set_temperature_target, ODD_COUNTERS);
6104 
6105 	for_all_cpus(get_cpu_type, ODD_COUNTERS);
6106 	for_all_cpus(get_cpu_type, EVEN_COUNTERS);
6107 
6108 	if (!quiet)
6109 		for_all_cpus(print_thermal, ODD_COUNTERS);
6110 
6111 	if (!quiet && do_irtl_snb)
6112 		print_irtl();
6113 
6114 	if (DO_BIC(BIC_IPC))
6115 		(void)get_instr_count_fd(base_cpu);
6116 }
6117 
6118 int fork_it(char **argv)
6119 {
6120 	pid_t child_pid;
6121 	int status;
6122 
6123 	snapshot_proc_sysfs_files();
6124 	status = for_all_cpus(get_counters, EVEN_COUNTERS);
6125 	first_counter_read = 0;
6126 	if (status)
6127 		exit(status);
6128 	/* clear affinity side-effect of get_counters() */
6129 	sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
6130 	gettimeofday(&tv_even, (struct timezone *)NULL);
6131 
6132 	child_pid = fork();
6133 	if (!child_pid) {
6134 		/* child */
6135 		execvp(argv[0], argv);
6136 		err(errno, "exec %s", argv[0]);
6137 	} else {
6138 
6139 		/* parent */
6140 		if (child_pid == -1)
6141 			err(1, "fork");
6142 
6143 		signal(SIGINT, SIG_IGN);
6144 		signal(SIGQUIT, SIG_IGN);
6145 		if (waitpid(child_pid, &status, 0) == -1)
6146 			err(status, "waitpid");
6147 
6148 		if (WIFEXITED(status))
6149 			status = WEXITSTATUS(status);
6150 	}
6151 	/*
6152 	 * n.b. fork_it() does not check for errors from for_all_cpus()
6153 	 * because re-starting is problematic when forking
6154 	 */
6155 	snapshot_proc_sysfs_files();
6156 	for_all_cpus(get_counters, ODD_COUNTERS);
6157 	gettimeofday(&tv_odd, (struct timezone *)NULL);
6158 	timersub(&tv_odd, &tv_even, &tv_delta);
6159 	if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS))
6160 		fprintf(outf, "%s: Counter reset detected\n", progname);
6161 	else {
6162 		compute_average(EVEN_COUNTERS);
6163 		format_all_counters(EVEN_COUNTERS);
6164 	}
6165 
6166 	fprintf(outf, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec / 1000000.0);
6167 
6168 	flush_output_stderr();
6169 
6170 	return status;
6171 }
6172 
6173 int get_and_dump_counters(void)
6174 {
6175 	int status;
6176 
6177 	snapshot_proc_sysfs_files();
6178 	status = for_all_cpus(get_counters, ODD_COUNTERS);
6179 	if (status)
6180 		return status;
6181 
6182 	status = for_all_cpus(dump_counters, ODD_COUNTERS);
6183 	if (status)
6184 		return status;
6185 
6186 	flush_output_stdout();
6187 
6188 	return status;
6189 }
6190 
6191 void print_version()
6192 {
6193 	fprintf(outf, "turbostat version 2022.04.16 - Len Brown <lenb@kernel.org>\n");
6194 }
6195 
6196 #define COMMAND_LINE_SIZE 2048
6197 
6198 void print_bootcmd(void)
6199 {
6200 	char bootcmd[COMMAND_LINE_SIZE];
6201 	FILE *fp;
6202 	int ret;
6203 
6204 	memset(bootcmd, 0, COMMAND_LINE_SIZE);
6205 	fp = fopen("/proc/cmdline", "r");
6206 	if (!fp)
6207 		return;
6208 
6209 	ret = fread(bootcmd, sizeof(char), COMMAND_LINE_SIZE - 1, fp);
6210 	if (ret) {
6211 		bootcmd[ret] = '\0';
6212 		/* the last character is already '\n' */
6213 		fprintf(outf, "Kernel command line: %s", bootcmd);
6214 	}
6215 
6216 	fclose(fp);
6217 }
6218 
6219 int add_counter(unsigned int msr_num, char *path, char *name,
6220 		unsigned int width, enum counter_scope scope,
6221 		enum counter_type type, enum counter_format format, int flags)
6222 {
6223 	struct msr_counter *msrp;
6224 
6225 	msrp = calloc(1, sizeof(struct msr_counter));
6226 	if (msrp == NULL) {
6227 		perror("calloc");
6228 		exit(1);
6229 	}
6230 
6231 	msrp->msr_num = msr_num;
6232 	strncpy(msrp->name, name, NAME_BYTES - 1);
6233 	if (path)
6234 		strncpy(msrp->path, path, PATH_BYTES - 1);
6235 	msrp->width = width;
6236 	msrp->type = type;
6237 	msrp->format = format;
6238 	msrp->flags = flags;
6239 
6240 	switch (scope) {
6241 
6242 	case SCOPE_CPU:
6243 		msrp->next = sys.tp;
6244 		sys.tp = msrp;
6245 		sys.added_thread_counters++;
6246 		if (sys.added_thread_counters > MAX_ADDED_THREAD_COUNTERS) {
6247 			fprintf(stderr, "exceeded max %d added thread counters\n", MAX_ADDED_COUNTERS);
6248 			exit(-1);
6249 		}
6250 		break;
6251 
6252 	case SCOPE_CORE:
6253 		msrp->next = sys.cp;
6254 		sys.cp = msrp;
6255 		sys.added_core_counters++;
6256 		if (sys.added_core_counters > MAX_ADDED_COUNTERS) {
6257 			fprintf(stderr, "exceeded max %d added core counters\n", MAX_ADDED_COUNTERS);
6258 			exit(-1);
6259 		}
6260 		break;
6261 
6262 	case SCOPE_PACKAGE:
6263 		msrp->next = sys.pp;
6264 		sys.pp = msrp;
6265 		sys.added_package_counters++;
6266 		if (sys.added_package_counters > MAX_ADDED_COUNTERS) {
6267 			fprintf(stderr, "exceeded max %d added package counters\n", MAX_ADDED_COUNTERS);
6268 			exit(-1);
6269 		}
6270 		break;
6271 	}
6272 
6273 	return 0;
6274 }
6275 
6276 void parse_add_command(char *add_command)
6277 {
6278 	int msr_num = 0;
6279 	char *path = NULL;
6280 	char name_buffer[NAME_BYTES] = "";
6281 	int width = 64;
6282 	int fail = 0;
6283 	enum counter_scope scope = SCOPE_CPU;
6284 	enum counter_type type = COUNTER_CYCLES;
6285 	enum counter_format format = FORMAT_DELTA;
6286 
6287 	while (add_command) {
6288 
6289 		if (sscanf(add_command, "msr0x%x", &msr_num) == 1)
6290 			goto next;
6291 
6292 		if (sscanf(add_command, "msr%d", &msr_num) == 1)
6293 			goto next;
6294 
6295 		if (*add_command == '/') {
6296 			path = add_command;
6297 			goto next;
6298 		}
6299 
6300 		if (sscanf(add_command, "u%d", &width) == 1) {
6301 			if ((width == 32) || (width == 64))
6302 				goto next;
6303 			width = 64;
6304 		}
6305 		if (!strncmp(add_command, "cpu", strlen("cpu"))) {
6306 			scope = SCOPE_CPU;
6307 			goto next;
6308 		}
6309 		if (!strncmp(add_command, "core", strlen("core"))) {
6310 			scope = SCOPE_CORE;
6311 			goto next;
6312 		}
6313 		if (!strncmp(add_command, "package", strlen("package"))) {
6314 			scope = SCOPE_PACKAGE;
6315 			goto next;
6316 		}
6317 		if (!strncmp(add_command, "cycles", strlen("cycles"))) {
6318 			type = COUNTER_CYCLES;
6319 			goto next;
6320 		}
6321 		if (!strncmp(add_command, "seconds", strlen("seconds"))) {
6322 			type = COUNTER_SECONDS;
6323 			goto next;
6324 		}
6325 		if (!strncmp(add_command, "usec", strlen("usec"))) {
6326 			type = COUNTER_USEC;
6327 			goto next;
6328 		}
6329 		if (!strncmp(add_command, "raw", strlen("raw"))) {
6330 			format = FORMAT_RAW;
6331 			goto next;
6332 		}
6333 		if (!strncmp(add_command, "delta", strlen("delta"))) {
6334 			format = FORMAT_DELTA;
6335 			goto next;
6336 		}
6337 		if (!strncmp(add_command, "percent", strlen("percent"))) {
6338 			format = FORMAT_PERCENT;
6339 			goto next;
6340 		}
6341 
6342 		if (sscanf(add_command, "%18s,%*s", name_buffer) == 1) {	/* 18 < NAME_BYTES */
6343 			char *eos;
6344 
6345 			eos = strchr(name_buffer, ',');
6346 			if (eos)
6347 				*eos = '\0';
6348 			goto next;
6349 		}
6350 
6351 next:
6352 		add_command = strchr(add_command, ',');
6353 		if (add_command) {
6354 			*add_command = '\0';
6355 			add_command++;
6356 		}
6357 
6358 	}
6359 	if ((msr_num == 0) && (path == NULL)) {
6360 		fprintf(stderr, "--add: (msrDDD | msr0xXXX | /path_to_counter ) required\n");
6361 		fail++;
6362 	}
6363 
6364 	/* generate default column header */
6365 	if (*name_buffer == '\0') {
6366 		if (width == 32)
6367 			sprintf(name_buffer, "M0x%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
6368 		else
6369 			sprintf(name_buffer, "M0X%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
6370 	}
6371 
6372 	if (add_counter(msr_num, path, name_buffer, width, scope, type, format, 0))
6373 		fail++;
6374 
6375 	if (fail) {
6376 		help();
6377 		exit(1);
6378 	}
6379 }
6380 
6381 int is_deferred_add(char *name)
6382 {
6383 	int i;
6384 
6385 	for (i = 0; i < deferred_add_index; ++i)
6386 		if (!strcmp(name, deferred_add_names[i]))
6387 			return 1;
6388 	return 0;
6389 }
6390 
6391 int is_deferred_skip(char *name)
6392 {
6393 	int i;
6394 
6395 	for (i = 0; i < deferred_skip_index; ++i)
6396 		if (!strcmp(name, deferred_skip_names[i]))
6397 			return 1;
6398 	return 0;
6399 }
6400 
6401 void probe_sysfs(void)
6402 {
6403 	char path[64];
6404 	char name_buf[16];
6405 	FILE *input;
6406 	int state;
6407 	char *sp;
6408 
6409 	for (state = 10; state >= 0; --state) {
6410 
6411 		sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name", base_cpu, state);
6412 		input = fopen(path, "r");
6413 		if (input == NULL)
6414 			continue;
6415 		if (!fgets(name_buf, sizeof(name_buf), input))
6416 			err(1, "%s: failed to read file", path);
6417 
6418 		/* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
6419 		sp = strchr(name_buf, '-');
6420 		if (!sp)
6421 			sp = strchrnul(name_buf, '\n');
6422 		*sp = '%';
6423 		*(sp + 1) = '\0';
6424 
6425 		remove_underbar(name_buf);
6426 
6427 		fclose(input);
6428 
6429 		sprintf(path, "cpuidle/state%d/time", state);
6430 
6431 		if (!DO_BIC(BIC_sysfs) && !is_deferred_add(name_buf))
6432 			continue;
6433 
6434 		if (is_deferred_skip(name_buf))
6435 			continue;
6436 
6437 		add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_USEC, FORMAT_PERCENT, SYSFS_PERCPU);
6438 	}
6439 
6440 	for (state = 10; state >= 0; --state) {
6441 
6442 		sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name", base_cpu, state);
6443 		input = fopen(path, "r");
6444 		if (input == NULL)
6445 			continue;
6446 		if (!fgets(name_buf, sizeof(name_buf), input))
6447 			err(1, "%s: failed to read file", path);
6448 		/* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
6449 		sp = strchr(name_buf, '-');
6450 		if (!sp)
6451 			sp = strchrnul(name_buf, '\n');
6452 		*sp = '\0';
6453 		fclose(input);
6454 
6455 		remove_underbar(name_buf);
6456 
6457 		sprintf(path, "cpuidle/state%d/usage", state);
6458 
6459 		if (!DO_BIC(BIC_sysfs) && !is_deferred_add(name_buf))
6460 			continue;
6461 
6462 		if (is_deferred_skip(name_buf))
6463 			continue;
6464 
6465 		add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_ITEMS, FORMAT_DELTA, SYSFS_PERCPU);
6466 	}
6467 
6468 }
6469 
6470 /*
6471  * parse cpuset with following syntax
6472  * 1,2,4..6,8-10 and set bits in cpu_subset
6473  */
6474 void parse_cpu_command(char *optarg)
6475 {
6476 	unsigned int start, end;
6477 	char *next;
6478 
6479 	if (!strcmp(optarg, "core")) {
6480 		if (cpu_subset)
6481 			goto error;
6482 		show_core_only++;
6483 		return;
6484 	}
6485 	if (!strcmp(optarg, "package")) {
6486 		if (cpu_subset)
6487 			goto error;
6488 		show_pkg_only++;
6489 		return;
6490 	}
6491 	if (show_core_only || show_pkg_only)
6492 		goto error;
6493 
6494 	cpu_subset = CPU_ALLOC(CPU_SUBSET_MAXCPUS);
6495 	if (cpu_subset == NULL)
6496 		err(3, "CPU_ALLOC");
6497 	cpu_subset_size = CPU_ALLOC_SIZE(CPU_SUBSET_MAXCPUS);
6498 
6499 	CPU_ZERO_S(cpu_subset_size, cpu_subset);
6500 
6501 	next = optarg;
6502 
6503 	while (next && *next) {
6504 
6505 		if (*next == '-')	/* no negative cpu numbers */
6506 			goto error;
6507 
6508 		start = strtoul(next, &next, 10);
6509 
6510 		if (start >= CPU_SUBSET_MAXCPUS)
6511 			goto error;
6512 		CPU_SET_S(start, cpu_subset_size, cpu_subset);
6513 
6514 		if (*next == '\0')
6515 			break;
6516 
6517 		if (*next == ',') {
6518 			next += 1;
6519 			continue;
6520 		}
6521 
6522 		if (*next == '-') {
6523 			next += 1;	/* start range */
6524 		} else if (*next == '.') {
6525 			next += 1;
6526 			if (*next == '.')
6527 				next += 1;	/* start range */
6528 			else
6529 				goto error;
6530 		}
6531 
6532 		end = strtoul(next, &next, 10);
6533 		if (end <= start)
6534 			goto error;
6535 
6536 		while (++start <= end) {
6537 			if (start >= CPU_SUBSET_MAXCPUS)
6538 				goto error;
6539 			CPU_SET_S(start, cpu_subset_size, cpu_subset);
6540 		}
6541 
6542 		if (*next == ',')
6543 			next += 1;
6544 		else if (*next != '\0')
6545 			goto error;
6546 	}
6547 
6548 	return;
6549 
6550 error:
6551 	fprintf(stderr, "\"--cpu %s\" malformed\n", optarg);
6552 	help();
6553 	exit(-1);
6554 }
6555 
6556 void cmdline(int argc, char **argv)
6557 {
6558 	int opt;
6559 	int option_index = 0;
6560 	static struct option long_options[] = {
6561 		{ "add", required_argument, 0, 'a' },
6562 		{ "cpu", required_argument, 0, 'c' },
6563 		{ "Dump", no_argument, 0, 'D' },
6564 		{ "debug", no_argument, 0, 'd' },	/* internal, not documented */
6565 		{ "enable", required_argument, 0, 'e' },
6566 		{ "interval", required_argument, 0, 'i' },
6567 		{ "IPC", no_argument, 0, 'I' },
6568 		{ "num_iterations", required_argument, 0, 'n' },
6569 		{ "header_iterations", required_argument, 0, 'N' },
6570 		{ "help", no_argument, 0, 'h' },
6571 		{ "hide", required_argument, 0, 'H' },	// meh, -h taken by --help
6572 		{ "Joules", no_argument, 0, 'J' },
6573 		{ "list", no_argument, 0, 'l' },
6574 		{ "out", required_argument, 0, 'o' },
6575 		{ "quiet", no_argument, 0, 'q' },
6576 		{ "show", required_argument, 0, 's' },
6577 		{ "Summary", no_argument, 0, 'S' },
6578 		{ "TCC", required_argument, 0, 'T' },
6579 		{ "version", no_argument, 0, 'v' },
6580 		{ 0, 0, 0, 0 }
6581 	};
6582 
6583 	progname = argv[0];
6584 
6585 	while ((opt = getopt_long_only(argc, argv, "+C:c:Dde:hi:Jn:o:qST:v", long_options, &option_index)) != -1) {
6586 		switch (opt) {
6587 		case 'a':
6588 			parse_add_command(optarg);
6589 			break;
6590 		case 'c':
6591 			parse_cpu_command(optarg);
6592 			break;
6593 		case 'D':
6594 			dump_only++;
6595 			break;
6596 		case 'e':
6597 			/* --enable specified counter */
6598 			bic_enabled = bic_enabled | bic_lookup(optarg, SHOW_LIST);
6599 			break;
6600 		case 'd':
6601 			debug++;
6602 			ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
6603 			break;
6604 		case 'H':
6605 			/*
6606 			 * --hide: do not show those specified
6607 			 *  multiple invocations simply clear more bits in enabled mask
6608 			 */
6609 			bic_enabled &= ~bic_lookup(optarg, HIDE_LIST);
6610 			break;
6611 		case 'h':
6612 		default:
6613 			help();
6614 			exit(1);
6615 		case 'i':
6616 			{
6617 				double interval = strtod(optarg, NULL);
6618 
6619 				if (interval < 0.001) {
6620 					fprintf(outf, "interval %f seconds is too small\n", interval);
6621 					exit(2);
6622 				}
6623 
6624 				interval_tv.tv_sec = interval_ts.tv_sec = interval;
6625 				interval_tv.tv_usec = (interval - interval_tv.tv_sec) * 1000000;
6626 				interval_ts.tv_nsec = (interval - interval_ts.tv_sec) * 1000000000;
6627 			}
6628 			break;
6629 		case 'J':
6630 			rapl_joules++;
6631 			break;
6632 		case 'l':
6633 			ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
6634 			list_header_only++;
6635 			quiet++;
6636 			break;
6637 		case 'o':
6638 			outf = fopen_or_die(optarg, "w");
6639 			break;
6640 		case 'q':
6641 			quiet = 1;
6642 			break;
6643 		case 'n':
6644 			num_iterations = strtod(optarg, NULL);
6645 
6646 			if (num_iterations <= 0) {
6647 				fprintf(outf, "iterations %d should be positive number\n", num_iterations);
6648 				exit(2);
6649 			}
6650 			break;
6651 		case 'N':
6652 			header_iterations = strtod(optarg, NULL);
6653 
6654 			if (header_iterations <= 0) {
6655 				fprintf(outf, "iterations %d should be positive number\n", header_iterations);
6656 				exit(2);
6657 			}
6658 			break;
6659 		case 's':
6660 			/*
6661 			 * --show: show only those specified
6662 			 *  The 1st invocation will clear and replace the enabled mask
6663 			 *  subsequent invocations can add to it.
6664 			 */
6665 			if (shown == 0)
6666 				bic_enabled = bic_lookup(optarg, SHOW_LIST);
6667 			else
6668 				bic_enabled |= bic_lookup(optarg, SHOW_LIST);
6669 			shown = 1;
6670 			break;
6671 		case 'S':
6672 			summary_only++;
6673 			break;
6674 		case 'T':
6675 			tj_max_override = atoi(optarg);
6676 			break;
6677 		case 'v':
6678 			print_version();
6679 			exit(0);
6680 			break;
6681 		}
6682 	}
6683 }
6684 
6685 int main(int argc, char **argv)
6686 {
6687 	outf = stderr;
6688 	cmdline(argc, argv);
6689 
6690 	if (!quiet) {
6691 		print_version();
6692 		print_bootcmd();
6693 	}
6694 
6695 	probe_sysfs();
6696 
6697 	turbostat_init();
6698 
6699 	msr_sum_record();
6700 
6701 	/* dump counters and exit */
6702 	if (dump_only)
6703 		return get_and_dump_counters();
6704 
6705 	/* list header and exit */
6706 	if (list_header_only) {
6707 		print_header(",");
6708 		flush_output_stdout();
6709 		return 0;
6710 	}
6711 
6712 	/*
6713 	 * if any params left, it must be a command to fork
6714 	 */
6715 	if (argc - optind)
6716 		return fork_it(argv + optind);
6717 	else
6718 		turbostat_loop();
6719 
6720 	return 0;
6721 }
6722