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