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