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