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