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