1 /*
2  * turbostat -- show CPU frequency and C-state residency
3  * on modern Intel turbo-capable processors.
4  *
5  * Copyright (c) 2013 Intel Corporation.
6  * Len Brown <len.brown@intel.com>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms and conditions of the GNU General Public License,
10  * version 2, as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21 
22 #define _GNU_SOURCE
23 #include MSRHEADER
24 #include INTEL_FAMILY_HEADER
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <err.h>
28 #include <unistd.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <sys/stat.h>
32 #include <sys/resource.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <sys/time.h>
36 #include <stdlib.h>
37 #include <getopt.h>
38 #include <dirent.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include <sched.h>
42 #include <time.h>
43 #include <cpuid.h>
44 #include <linux/capability.h>
45 #include <errno.h>
46 
47 char *proc_stat = "/proc/stat";
48 FILE *outf;
49 int *fd_percpu;
50 struct timespec interval_ts = {5, 0};
51 unsigned int debug;
52 unsigned int rapl_joules;
53 unsigned int summary_only;
54 unsigned int dump_only;
55 unsigned int do_snb_cstates;
56 unsigned int do_knl_cstates;
57 unsigned int do_pc2;
58 unsigned int do_pc3;
59 unsigned int do_pc6;
60 unsigned int do_pc7;
61 unsigned int do_c8_c9_c10;
62 unsigned int do_skl_residency;
63 unsigned int do_slm_cstates;
64 unsigned int use_c1_residency_msr;
65 unsigned int has_aperf;
66 unsigned int has_epb;
67 unsigned int do_irtl_snb;
68 unsigned int do_irtl_hsw;
69 unsigned int units = 1000000;	/* MHz etc */
70 unsigned int genuine_intel;
71 unsigned int has_invariant_tsc;
72 unsigned int do_nhm_platform_info;
73 unsigned int no_MSR_MISC_PWR_MGMT;
74 unsigned int aperf_mperf_multiplier = 1;
75 double bclk;
76 double base_hz;
77 unsigned int has_base_hz;
78 double tsc_tweak = 1.0;
79 unsigned int show_pkg_only;
80 unsigned int show_core_only;
81 char *output_buffer, *outp;
82 unsigned int do_rapl;
83 unsigned int do_dts;
84 unsigned int do_ptm;
85 unsigned long long  gfx_cur_rc6_ms;
86 unsigned int gfx_cur_mhz;
87 unsigned int tcc_activation_temp;
88 unsigned int tcc_activation_temp_override;
89 double rapl_power_units, rapl_time_units;
90 double rapl_dram_energy_units, rapl_energy_units;
91 double rapl_joule_counter_range;
92 unsigned int do_core_perf_limit_reasons;
93 unsigned int do_gfx_perf_limit_reasons;
94 unsigned int do_ring_perf_limit_reasons;
95 unsigned int crystal_hz;
96 unsigned long long tsc_hz;
97 int base_cpu;
98 double discover_bclk(unsigned int family, unsigned int model);
99 unsigned int has_hwp;	/* IA32_PM_ENABLE, IA32_HWP_CAPABILITIES */
100 			/* IA32_HWP_REQUEST, IA32_HWP_STATUS */
101 unsigned int has_hwp_notify;		/* IA32_HWP_INTERRUPT */
102 unsigned int has_hwp_activity_window;	/* IA32_HWP_REQUEST[bits 41:32] */
103 unsigned int has_hwp_epp;		/* IA32_HWP_REQUEST[bits 31:24] */
104 unsigned int has_hwp_pkg;		/* IA32_HWP_REQUEST_PKG */
105 unsigned int has_misc_feature_control;
106 
107 #define RAPL_PKG		(1 << 0)
108 					/* 0x610 MSR_PKG_POWER_LIMIT */
109 					/* 0x611 MSR_PKG_ENERGY_STATUS */
110 #define RAPL_PKG_PERF_STATUS	(1 << 1)
111 					/* 0x613 MSR_PKG_PERF_STATUS */
112 #define RAPL_PKG_POWER_INFO	(1 << 2)
113 					/* 0x614 MSR_PKG_POWER_INFO */
114 
115 #define RAPL_DRAM		(1 << 3)
116 					/* 0x618 MSR_DRAM_POWER_LIMIT */
117 					/* 0x619 MSR_DRAM_ENERGY_STATUS */
118 #define RAPL_DRAM_PERF_STATUS	(1 << 4)
119 					/* 0x61b MSR_DRAM_PERF_STATUS */
120 #define RAPL_DRAM_POWER_INFO	(1 << 5)
121 					/* 0x61c MSR_DRAM_POWER_INFO */
122 
123 #define RAPL_CORES_POWER_LIMIT	(1 << 6)
124 					/* 0x638 MSR_PP0_POWER_LIMIT */
125 #define RAPL_CORE_POLICY	(1 << 7)
126 					/* 0x63a MSR_PP0_POLICY */
127 
128 #define RAPL_GFX		(1 << 8)
129 					/* 0x640 MSR_PP1_POWER_LIMIT */
130 					/* 0x641 MSR_PP1_ENERGY_STATUS */
131 					/* 0x642 MSR_PP1_POLICY */
132 
133 #define RAPL_CORES_ENERGY_STATUS	(1 << 9)
134 					/* 0x639 MSR_PP0_ENERGY_STATUS */
135 #define RAPL_CORES (RAPL_CORES_ENERGY_STATUS | RAPL_CORES_POWER_LIMIT)
136 #define	TJMAX_DEFAULT	100
137 
138 #define MAX(a, b) ((a) > (b) ? (a) : (b))
139 
140 /*
141  * buffer size used by sscanf() for added column names
142  * Usually truncated to 7 characters, but also handles 18 columns for raw 64-bit counters
143  */
144 #define	NAME_BYTES 20
145 
146 int backwards_count;
147 char *progname;
148 
149 cpu_set_t *cpu_present_set, *cpu_affinity_set;
150 size_t cpu_present_setsize, cpu_affinity_setsize;
151 #define MAX_ADDED_COUNTERS 16
152 
153 struct thread_data {
154 	unsigned long long tsc;
155 	unsigned long long aperf;
156 	unsigned long long mperf;
157 	unsigned long long c1;
158 	unsigned int irq_count;
159 	unsigned int smi_count;
160 	unsigned int cpu_id;
161 	unsigned int flags;
162 #define CPU_IS_FIRST_THREAD_IN_CORE	0x2
163 #define CPU_IS_FIRST_CORE_IN_PACKAGE	0x4
164 	unsigned long long counter[MAX_ADDED_COUNTERS];
165 } *thread_even, *thread_odd;
166 
167 struct core_data {
168 	unsigned long long c3;
169 	unsigned long long c6;
170 	unsigned long long c7;
171 	unsigned long long mc6_us;	/* duplicate as per-core for now, even though per module */
172 	unsigned int core_temp_c;
173 	unsigned int core_id;
174 	unsigned long long counter[MAX_ADDED_COUNTERS];
175 } *core_even, *core_odd;
176 
177 struct pkg_data {
178 	unsigned long long pc2;
179 	unsigned long long pc3;
180 	unsigned long long pc6;
181 	unsigned long long pc7;
182 	unsigned long long pc8;
183 	unsigned long long pc9;
184 	unsigned long long pc10;
185 	unsigned long long pkg_wtd_core_c0;
186 	unsigned long long pkg_any_core_c0;
187 	unsigned long long pkg_any_gfxe_c0;
188 	unsigned long long pkg_both_core_gfxe_c0;
189 	long long gfx_rc6_ms;
190 	unsigned int gfx_mhz;
191 	unsigned int package_id;
192 	unsigned int energy_pkg;	/* MSR_PKG_ENERGY_STATUS */
193 	unsigned int energy_dram;	/* MSR_DRAM_ENERGY_STATUS */
194 	unsigned int energy_cores;	/* MSR_PP0_ENERGY_STATUS */
195 	unsigned int energy_gfx;	/* MSR_PP1_ENERGY_STATUS */
196 	unsigned int rapl_pkg_perf_status;	/* MSR_PKG_PERF_STATUS */
197 	unsigned int rapl_dram_perf_status;	/* MSR_DRAM_PERF_STATUS */
198 	unsigned int pkg_temp_c;
199 	unsigned long long counter[MAX_ADDED_COUNTERS];
200 } *package_even, *package_odd;
201 
202 #define ODD_COUNTERS thread_odd, core_odd, package_odd
203 #define EVEN_COUNTERS thread_even, core_even, package_even
204 
205 #define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \
206 	(thread_base + (pkg_no) * topo.num_cores_per_pkg * \
207 		topo.num_threads_per_core + \
208 		(core_no) * topo.num_threads_per_core + (thread_no))
209 #define GET_CORE(core_base, core_no, pkg_no) \
210 	(core_base + (pkg_no) * topo.num_cores_per_pkg + (core_no))
211 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
212 
213 enum counter_scope {SCOPE_CPU, SCOPE_CORE, SCOPE_PACKAGE};
214 enum counter_type {COUNTER_CYCLES, COUNTER_SECONDS};
215 enum counter_format {FORMAT_RAW, FORMAT_DELTA, FORMAT_PERCENT};
216 
217 struct msr_counter {
218 	unsigned int msr_num;
219 	char name[NAME_BYTES];
220 	unsigned int width;
221 	enum counter_type type;
222 	enum counter_format format;
223 	struct msr_counter *next;
224 	unsigned int flags;
225 #define	FLAGS_HIDE	(1 << 0)
226 #define	FLAGS_SHOW	(1 << 1)
227 };
228 
229 struct sys_counters {
230 	unsigned int added_thread_counters;
231 	unsigned int added_core_counters;
232 	unsigned int added_package_counters;
233 	struct msr_counter *tp;
234 	struct msr_counter *cp;
235 	struct msr_counter *pp;
236 } sys;
237 
238 struct system_summary {
239 	struct thread_data threads;
240 	struct core_data cores;
241 	struct pkg_data packages;
242 } average;
243 
244 
245 struct topo_params {
246 	int num_packages;
247 	int num_cpus;
248 	int num_cores;
249 	int max_cpu_num;
250 	int num_cores_per_pkg;
251 	int num_threads_per_core;
252 } topo;
253 
254 struct timeval tv_even, tv_odd, tv_delta;
255 
256 int *irq_column_2_cpu;	/* /proc/interrupts column numbers */
257 int *irqs_per_cpu;		/* indexed by cpu_num */
258 
259 void setup_all_buffers(void);
260 
261 int cpu_is_not_present(int cpu)
262 {
263 	return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
264 }
265 /*
266  * run func(thread, core, package) in topology order
267  * skip non-present cpus
268  */
269 
270 int for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
271 	struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
272 {
273 	int retval, pkg_no, core_no, thread_no;
274 
275 	for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
276 		for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
277 			for (thread_no = 0; thread_no <
278 				topo.num_threads_per_core; ++thread_no) {
279 				struct thread_data *t;
280 				struct core_data *c;
281 				struct pkg_data *p;
282 
283 				t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
284 
285 				if (cpu_is_not_present(t->cpu_id))
286 					continue;
287 
288 				c = GET_CORE(core_base, core_no, pkg_no);
289 				p = GET_PKG(pkg_base, pkg_no);
290 
291 				retval = func(t, c, p);
292 				if (retval)
293 					return retval;
294 			}
295 		}
296 	}
297 	return 0;
298 }
299 
300 int cpu_migrate(int cpu)
301 {
302 	CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
303 	CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
304 	if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1)
305 		return -1;
306 	else
307 		return 0;
308 }
309 int get_msr_fd(int cpu)
310 {
311 	char pathname[32];
312 	int fd;
313 
314 	fd = fd_percpu[cpu];
315 
316 	if (fd)
317 		return fd;
318 
319 	sprintf(pathname, "/dev/cpu/%d/msr", cpu);
320 	fd = open(pathname, O_RDONLY);
321 	if (fd < 0)
322 		err(-1, "%s open failed, try chown or chmod +r /dev/cpu/*/msr, or run as root", pathname);
323 
324 	fd_percpu[cpu] = fd;
325 
326 	return fd;
327 }
328 
329 int get_msr(int cpu, off_t offset, unsigned long long *msr)
330 {
331 	ssize_t retval;
332 
333 	retval = pread(get_msr_fd(cpu), msr, sizeof(*msr), offset);
334 
335 	if (retval != sizeof *msr)
336 		err(-1, "cpu%d: msr offset 0x%llx read failed", cpu, (unsigned long long)offset);
337 
338 	return 0;
339 }
340 
341 /*
342  * Each string in this array is compared in --show and --hide cmdline.
343  * Thus, strings that are proper sub-sets must follow their more specific peers.
344  */
345 struct msr_counter bic[] = {
346 	{ 0x0, "Package" },
347 	{ 0x0, "Avg_MHz" },
348 	{ 0x0, "Bzy_MHz" },
349 	{ 0x0, "TSC_MHz" },
350 	{ 0x0, "IRQ" },
351 	{ 0x0, "SMI", 32, 0, FORMAT_DELTA, NULL},
352 	{ 0x0, "Busy%" },
353 	{ 0x0, "CPU%c1" },
354 	{ 0x0, "CPU%c3" },
355 	{ 0x0, "CPU%c6" },
356 	{ 0x0, "CPU%c7" },
357 	{ 0x0, "ThreadC" },
358 	{ 0x0, "CoreTmp" },
359 	{ 0x0, "CoreCnt" },
360 	{ 0x0, "PkgTmp" },
361 	{ 0x0, "GFX%rc6" },
362 	{ 0x0, "GFXMHz" },
363 	{ 0x0, "Pkg%pc2" },
364 	{ 0x0, "Pkg%pc3" },
365 	{ 0x0, "Pkg%pc6" },
366 	{ 0x0, "Pkg%pc7" },
367 	{ 0x0, "PkgWatt" },
368 	{ 0x0, "CorWatt" },
369 	{ 0x0, "GFXWatt" },
370 	{ 0x0, "PkgCnt" },
371 	{ 0x0, "RAMWatt" },
372 	{ 0x0, "PKG_%" },
373 	{ 0x0, "RAM_%" },
374 	{ 0x0, "Pkg_J" },
375 	{ 0x0, "Cor_J" },
376 	{ 0x0, "GFX_J" },
377 	{ 0x0, "RAM_J" },
378 	{ 0x0, "Core" },
379 	{ 0x0, "CPU" },
380 	{ 0x0, "Mod%c6" },
381 };
382 
383 #define MAX_BIC (sizeof(bic) / sizeof(struct msr_counter))
384 #define	BIC_Package	(1ULL << 0)
385 #define	BIC_Avg_MHz	(1ULL << 1)
386 #define	BIC_Bzy_MHz	(1ULL << 2)
387 #define	BIC_TSC_MHz	(1ULL << 3)
388 #define	BIC_IRQ		(1ULL << 4)
389 #define	BIC_SMI		(1ULL << 5)
390 #define	BIC_Busy	(1ULL << 6)
391 #define	BIC_CPU_c1	(1ULL << 7)
392 #define	BIC_CPU_c3	(1ULL << 8)
393 #define	BIC_CPU_c6	(1ULL << 9)
394 #define	BIC_CPU_c7	(1ULL << 10)
395 #define	BIC_ThreadC	(1ULL << 11)
396 #define	BIC_CoreTmp	(1ULL << 12)
397 #define	BIC_CoreCnt	(1ULL << 13)
398 #define	BIC_PkgTmp	(1ULL << 14)
399 #define	BIC_GFX_rc6	(1ULL << 15)
400 #define	BIC_GFXMHz	(1ULL << 16)
401 #define	BIC_Pkgpc2	(1ULL << 17)
402 #define	BIC_Pkgpc3	(1ULL << 18)
403 #define	BIC_Pkgpc6	(1ULL << 19)
404 #define	BIC_Pkgpc7	(1ULL << 20)
405 #define	BIC_PkgWatt	(1ULL << 21)
406 #define	BIC_CorWatt	(1ULL << 22)
407 #define	BIC_GFXWatt	(1ULL << 23)
408 #define	BIC_PkgCnt	(1ULL << 24)
409 #define	BIC_RAMWatt	(1ULL << 27)
410 #define	BIC_PKG__	(1ULL << 28)
411 #define	BIC_RAM__	(1ULL << 29)
412 #define	BIC_Pkg_J	(1ULL << 30)
413 #define	BIC_Cor_J	(1ULL << 31)
414 #define	BIC_GFX_J	(1ULL << 30)
415 #define	BIC_RAM_J	(1ULL << 31)
416 #define	BIC_Core	(1ULL << 32)
417 #define	BIC_CPU		(1ULL << 33)
418 #define	BIC_Mod_c6	(1ULL << 34)
419 
420 unsigned long long bic_enabled = 0xFFFFFFFFFFFFFFFFULL;
421 unsigned long long bic_present;
422 
423 #define DO_BIC(COUNTER_NAME) (bic_enabled & bic_present & COUNTER_NAME)
424 #define BIC_PRESENT(COUNTER_BIT) (bic_present |= COUNTER_BIT)
425 
426 /*
427  * bic_lookup
428  * for all the strings in comma separate name_list,
429  * set the approprate bit in return value.
430  */
431 unsigned long long bic_lookup(char *name_list)
432 {
433 	int i;
434 	unsigned long long retval = 0;
435 
436 	while (name_list) {
437 		char *comma;
438 
439 		comma = strchr(name_list, ',');
440 
441 		if (comma)
442 			*comma = '\0';
443 
444 		for (i = 0; i < MAX_BIC; ++i) {
445 			if (!strcmp(name_list, bic[i].name)) {
446 				retval |= (1ULL << i);
447 				break;
448 			}
449 		}
450 		if (i == MAX_BIC) {
451 			fprintf(stderr, "Invalid counter name: %s\n", name_list);
452 			exit(-1);
453 		}
454 
455 		name_list = comma;
456 		if (name_list)
457 			name_list++;
458 
459 	}
460 	return retval;
461 }
462 
463 void print_header(void)
464 {
465 	struct msr_counter *mp;
466 
467 	if (DO_BIC(BIC_Package))
468 		outp += sprintf(outp, "\tPackage");
469 	if (DO_BIC(BIC_Core))
470 		outp += sprintf(outp, "\tCore");
471 	if (DO_BIC(BIC_CPU))
472 		outp += sprintf(outp, "\tCPU");
473 	if (DO_BIC(BIC_Avg_MHz))
474 		outp += sprintf(outp, "\tAvg_MHz");
475 	if (DO_BIC(BIC_Busy))
476 		outp += sprintf(outp, "\tBusy%%");
477 	if (DO_BIC(BIC_Bzy_MHz))
478 		outp += sprintf(outp, "\tBzy_MHz");
479 	if (DO_BIC(BIC_TSC_MHz))
480 		outp += sprintf(outp, "\tTSC_MHz");
481 
482 	if (!debug)
483 		goto done;
484 
485 	if (DO_BIC(BIC_IRQ))
486 		outp += sprintf(outp, "\tIRQ");
487 	if (DO_BIC(BIC_SMI))
488 		outp += sprintf(outp, "\tSMI");
489 
490 	if (DO_BIC(BIC_CPU_c1))
491 		outp += sprintf(outp, "\tCPU%%c1");
492 
493 	for (mp = sys.tp; mp; mp = mp->next) {
494 		if (mp->format == FORMAT_RAW) {
495 			if (mp->width == 64)
496 				outp += sprintf(outp, "\t%18.18s", mp->name);
497 			else
498 				outp += sprintf(outp, "\t%10.10s", mp->name);
499 		} else {
500 			outp += sprintf(outp, "\t%-7.7s", mp->name);
501 		}
502 	}
503 
504 	if (DO_BIC(BIC_CPU_c3) && !do_slm_cstates && !do_knl_cstates)
505 		outp += sprintf(outp, "\tCPU%%c3");
506 	if (DO_BIC(BIC_CPU_c6))
507 		outp += sprintf(outp, "\tCPU%%c6");
508 	if (DO_BIC(BIC_CPU_c7))
509 		outp += sprintf(outp, "\tCPU%%c7");
510 
511 	if (DO_BIC(BIC_Mod_c6))
512 		outp += sprintf(outp, "\tMod%%c6");
513 
514 	if (DO_BIC(BIC_CoreTmp))
515 		outp += sprintf(outp, "\tCoreTmp");
516 
517 	for (mp = sys.cp; mp; mp = mp->next) {
518 		if (mp->format == FORMAT_RAW) {
519 			if (mp->width == 64)
520 				outp += sprintf(outp, "\t%18.18s", mp->name);
521 			else
522 				outp += sprintf(outp, "\t%10.10s", mp->name);
523 		} else {
524 			outp += sprintf(outp, "\t%-7.7s", mp->name);
525 		}
526 	}
527 
528 	if (DO_BIC(BIC_PkgTmp))
529 		outp += sprintf(outp, "\tPkgTmp");
530 
531 	if (DO_BIC(BIC_GFX_rc6))
532 		outp += sprintf(outp, "\tGFX%%rc6");
533 
534 	if (DO_BIC(BIC_GFXMHz))
535 		outp += sprintf(outp, "\tGFXMHz");
536 
537 	if (do_skl_residency) {
538 		outp += sprintf(outp, "\tTotl%%C0");
539 		outp += sprintf(outp, "\tAny%%C0");
540 		outp += sprintf(outp, "\tGFX%%C0");
541 		outp += sprintf(outp, "\tCPUGFX%%");
542 	}
543 
544 	if (do_pc2)
545 		outp += sprintf(outp, "\tPkg%%pc2");
546 	if (do_pc3)
547 		outp += sprintf(outp, "\tPkg%%pc3");
548 	if (do_pc6)
549 		outp += sprintf(outp, "\tPkg%%pc6");
550 	if (do_pc7)
551 		outp += sprintf(outp, "\tPkg%%pc7");
552 	if (do_c8_c9_c10) {
553 		outp += sprintf(outp, "\tPkg%%pc8");
554 		outp += sprintf(outp, "\tPkg%%pc9");
555 		outp += sprintf(outp, "\tPk%%pc10");
556 	}
557 
558 	if (do_rapl && !rapl_joules) {
559 		if (DO_BIC(BIC_PkgWatt))
560 			outp += sprintf(outp, "\tPkgWatt");
561 		if (DO_BIC(BIC_CorWatt))
562 			outp += sprintf(outp, "\tCorWatt");
563 		if (DO_BIC(BIC_GFXWatt))
564 			outp += sprintf(outp, "\tGFXWatt");
565 		if (DO_BIC(BIC_RAMWatt))
566 			outp += sprintf(outp, "\tRAMWatt");
567 		if (DO_BIC(BIC_PKG__))
568 			outp += sprintf(outp, "\tPKG_%%");
569 		if (DO_BIC(BIC_RAM__))
570 			outp += sprintf(outp, "\tRAM_%%");
571 	} else if (do_rapl && rapl_joules) {
572 		if (DO_BIC(BIC_Pkg_J))
573 			outp += sprintf(outp, "\tPkg_J");
574 		if (DO_BIC(BIC_Cor_J))
575 			outp += sprintf(outp, "\tCor_J");
576 		if (DO_BIC(BIC_GFX_J))
577 			outp += sprintf(outp, "\tGFX_J");
578 		if (DO_BIC(BIC_RAM_J))
579 			outp += sprintf(outp, "\tRAM_J");
580 		if (DO_BIC(BIC_PKG__))
581 			outp += sprintf(outp, "\tPKG_%%");
582 		if (DO_BIC(BIC_RAM__))
583 			outp += sprintf(outp, "\tRAM_%%");
584 	}
585 	for (mp = sys.pp; mp; mp = mp->next) {
586 		if (mp->format == FORMAT_RAW) {
587 			if (mp->width == 64)
588 				outp += sprintf(outp, "\t%18.18s", mp->name);
589 			else
590 				outp += sprintf(outp, "\t%10.10s", mp->name);
591 		} else {
592 			outp += sprintf(outp, "\t%-7.7s", mp->name);
593 		}
594 	}
595 
596 done:
597 	outp += sprintf(outp, "\n");
598 }
599 
600 int dump_counters(struct thread_data *t, struct core_data *c,
601 	struct pkg_data *p)
602 {
603 	int i;
604 	struct msr_counter *mp;
605 
606 	outp += sprintf(outp, "t %p, c %p, p %p\n", t, c, p);
607 
608 	if (t) {
609 		outp += sprintf(outp, "CPU: %d flags 0x%x\n",
610 			t->cpu_id, t->flags);
611 		outp += sprintf(outp, "TSC: %016llX\n", t->tsc);
612 		outp += sprintf(outp, "aperf: %016llX\n", t->aperf);
613 		outp += sprintf(outp, "mperf: %016llX\n", t->mperf);
614 		outp += sprintf(outp, "c1: %016llX\n", t->c1);
615 
616 		if (DO_BIC(BIC_IRQ))
617 			outp += sprintf(outp, "IRQ: %08X\n", t->irq_count);
618 		if (DO_BIC(BIC_SMI))
619 			outp += sprintf(outp, "SMI: %08X\n", t->smi_count);
620 
621 		for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
622 			outp += sprintf(outp, "tADDED [%d] msr0x%x: %08llX\n",
623 				i, mp->msr_num, t->counter[i]);
624 		}
625 	}
626 
627 	if (c) {
628 		outp += sprintf(outp, "core: %d\n", c->core_id);
629 		outp += sprintf(outp, "c3: %016llX\n", c->c3);
630 		outp += sprintf(outp, "c6: %016llX\n", c->c6);
631 		outp += sprintf(outp, "c7: %016llX\n", c->c7);
632 		outp += sprintf(outp, "DTS: %dC\n", c->core_temp_c);
633 
634 		for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
635 			outp += sprintf(outp, "cADDED [%d] msr0x%x: %08llX\n",
636 				i, mp->msr_num, c->counter[i]);
637 		}
638 		outp += sprintf(outp, "mc6_us: %016llX\n", c->mc6_us);
639 	}
640 
641 	if (p) {
642 		outp += sprintf(outp, "package: %d\n", p->package_id);
643 
644 		outp += sprintf(outp, "Weighted cores: %016llX\n", p->pkg_wtd_core_c0);
645 		outp += sprintf(outp, "Any cores: %016llX\n", p->pkg_any_core_c0);
646 		outp += sprintf(outp, "Any GFX: %016llX\n", p->pkg_any_gfxe_c0);
647 		outp += sprintf(outp, "CPU + GFX: %016llX\n", p->pkg_both_core_gfxe_c0);
648 
649 		outp += sprintf(outp, "pc2: %016llX\n", p->pc2);
650 		if (do_pc3)
651 			outp += sprintf(outp, "pc3: %016llX\n", p->pc3);
652 		if (do_pc6)
653 			outp += sprintf(outp, "pc6: %016llX\n", p->pc6);
654 		if (do_pc7)
655 			outp += sprintf(outp, "pc7: %016llX\n", p->pc7);
656 		outp += sprintf(outp, "pc8: %016llX\n", p->pc8);
657 		outp += sprintf(outp, "pc9: %016llX\n", p->pc9);
658 		outp += sprintf(outp, "pc10: %016llX\n", p->pc10);
659 		outp += sprintf(outp, "Joules PKG: %0X\n", p->energy_pkg);
660 		outp += sprintf(outp, "Joules COR: %0X\n", p->energy_cores);
661 		outp += sprintf(outp, "Joules GFX: %0X\n", p->energy_gfx);
662 		outp += sprintf(outp, "Joules RAM: %0X\n", p->energy_dram);
663 		outp += sprintf(outp, "Throttle PKG: %0X\n",
664 			p->rapl_pkg_perf_status);
665 		outp += sprintf(outp, "Throttle RAM: %0X\n",
666 			p->rapl_dram_perf_status);
667 		outp += sprintf(outp, "PTM: %dC\n", p->pkg_temp_c);
668 
669 		for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
670 			outp += sprintf(outp, "pADDED [%d] msr0x%x: %08llX\n",
671 				i, mp->msr_num, p->counter[i]);
672 		}
673 	}
674 
675 	outp += sprintf(outp, "\n");
676 
677 	return 0;
678 }
679 
680 /*
681  * column formatting convention & formats
682  */
683 int format_counters(struct thread_data *t, struct core_data *c,
684 	struct pkg_data *p)
685 {
686 	double interval_float;
687 	char *fmt8;
688 	int i;
689 	struct msr_counter *mp;
690 
691 	 /* if showing only 1st thread in core and this isn't one, bail out */
692 	if (show_core_only && !(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
693 		return 0;
694 
695 	 /* if showing only 1st thread in pkg and this isn't one, bail out */
696 	if (show_pkg_only && !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
697 		return 0;
698 
699 	interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
700 
701 	/* topo columns, print blanks on 1st (average) line */
702 	if (t == &average.threads) {
703 		if (DO_BIC(BIC_Package))
704 			outp += sprintf(outp, "\t-");
705 		if (DO_BIC(BIC_Core))
706 			outp += sprintf(outp, "\t-");
707 		if (DO_BIC(BIC_CPU))
708 			outp += sprintf(outp, "\t-");
709 	} else {
710 		if (DO_BIC(BIC_Package)) {
711 			if (p)
712 				outp += sprintf(outp, "\t%d", p->package_id);
713 			else
714 				outp += sprintf(outp, "\t-");
715 		}
716 		if (DO_BIC(BIC_Core)) {
717 			if (c)
718 				outp += sprintf(outp, "\t%d", c->core_id);
719 			else
720 				outp += sprintf(outp, "\t-");
721 		}
722 		if (DO_BIC(BIC_CPU))
723 			outp += sprintf(outp, "\t%d", t->cpu_id);
724 	}
725 
726 	if (DO_BIC(BIC_Avg_MHz))
727 		outp += sprintf(outp, "\t%.0f",
728 			1.0 / units * t->aperf / interval_float);
729 
730 	if (DO_BIC(BIC_Busy))
731 		outp += sprintf(outp, "\t%.2f", 100.0 * t->mperf/t->tsc/tsc_tweak);
732 
733 	if (DO_BIC(BIC_Bzy_MHz)) {
734 		if (has_base_hz)
735 			outp += sprintf(outp, "\t%.0f", base_hz / units * t->aperf / t->mperf);
736 		else
737 			outp += sprintf(outp, "\t%.0f",
738 				1.0 * t->tsc / units * t->aperf / t->mperf / interval_float);
739 	}
740 
741 	if (DO_BIC(BIC_TSC_MHz))
742 		outp += sprintf(outp, "\t%.0f", 1.0 * t->tsc/units/interval_float);
743 
744 	if (!debug)
745 		goto done;
746 
747 	/* IRQ */
748 	if (DO_BIC(BIC_IRQ))
749 		outp += sprintf(outp, "\t%d", t->irq_count);
750 
751 	/* SMI */
752 	if (DO_BIC(BIC_SMI))
753 		outp += sprintf(outp, "\t%d", t->smi_count);
754 
755 	/* C1 */
756 	if (DO_BIC(BIC_CPU_c1))
757 		outp += sprintf(outp, "\t%.2f", 100.0 * t->c1/t->tsc);
758 
759 	/* Added counters */
760 	for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
761 		if (mp->format == FORMAT_RAW) {
762 			if (mp->width == 32)
763 				outp += sprintf(outp, "\t0x%08lx", (unsigned long) t->counter[i]);
764 			else
765 				outp += sprintf(outp, "\t0x%016llx", t->counter[i]);
766 		} else if (mp->format == FORMAT_DELTA) {
767 			outp += sprintf(outp, "\t%lld", t->counter[i]);
768 		} else if (mp->format == FORMAT_PERCENT) {
769 			outp += sprintf(outp, "\t%.2f", 100.0 * t->counter[i]/t->tsc);
770 		}
771 	}
772 
773 	/* print per-core data only for 1st thread in core */
774 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
775 		goto done;
776 
777 	if (DO_BIC(BIC_CPU_c3) && !do_slm_cstates && !do_knl_cstates)
778 		outp += sprintf(outp, "\t%.2f", 100.0 * c->c3/t->tsc);
779 	if (DO_BIC(BIC_CPU_c6))
780 		outp += sprintf(outp, "\t%.2f", 100.0 * c->c6/t->tsc);
781 	if (DO_BIC(BIC_CPU_c7))
782 		outp += sprintf(outp, "\t%.2f", 100.0 * c->c7/t->tsc);
783 
784 	/* Mod%c6 */
785 	if (DO_BIC(BIC_Mod_c6))
786 		outp += sprintf(outp, "\t%.2f", 100.0 * c->mc6_us / t->tsc);
787 
788 	if (DO_BIC(BIC_CoreTmp))
789 		outp += sprintf(outp, "\t%d", c->core_temp_c);
790 
791 	for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
792 		if (mp->format == FORMAT_RAW) {
793 			if (mp->width == 32)
794 				outp += sprintf(outp, "\t0x%08lx", (unsigned long) c->counter[i]);
795 			else
796 				outp += sprintf(outp, "\t0x%016llx", c->counter[i]);
797 		} else if (mp->format == FORMAT_DELTA) {
798 			outp += sprintf(outp, "\t%lld", c->counter[i]);
799 		} else if (mp->format == FORMAT_PERCENT) {
800 			outp += sprintf(outp, "\t%.2f", 100.0 * c->counter[i]/t->tsc);
801 		}
802 	}
803 
804 	/* print per-package data only for 1st core in package */
805 	if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
806 		goto done;
807 
808 	/* PkgTmp */
809 	if (DO_BIC(BIC_PkgTmp))
810 		outp += sprintf(outp, "\t%d", p->pkg_temp_c);
811 
812 	/* GFXrc6 */
813 	if (DO_BIC(BIC_GFX_rc6)) {
814 		if (p->gfx_rc6_ms == -1) {	/* detect GFX counter reset */
815 			outp += sprintf(outp, "\t**.**");
816 		} else {
817 			outp += sprintf(outp, "\t%.2f",
818 				p->gfx_rc6_ms / 10.0 / interval_float);
819 		}
820 	}
821 
822 	/* GFXMHz */
823 	if (DO_BIC(BIC_GFXMHz))
824 		outp += sprintf(outp, "\t%d", p->gfx_mhz);
825 
826 	/* Totl%C0, Any%C0 GFX%C0 CPUGFX% */
827 	if (do_skl_residency) {
828 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pkg_wtd_core_c0/t->tsc);
829 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pkg_any_core_c0/t->tsc);
830 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pkg_any_gfxe_c0/t->tsc);
831 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pkg_both_core_gfxe_c0/t->tsc);
832 	}
833 
834 	if (do_pc2)
835 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pc2/t->tsc);
836 	if (do_pc3)
837 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pc3/t->tsc);
838 	if (do_pc6)
839 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pc6/t->tsc);
840 	if (do_pc7)
841 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pc7/t->tsc);
842 	if (do_c8_c9_c10) {
843 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pc8/t->tsc);
844 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pc9/t->tsc);
845 		outp += sprintf(outp, "\t%.2f", 100.0 * p->pc10/t->tsc);
846 	}
847 
848 	/*
849  	 * If measurement interval exceeds minimum RAPL Joule Counter range,
850  	 * indicate that results are suspect by printing "**" in fraction place.
851  	 */
852 	if (interval_float < rapl_joule_counter_range)
853 		fmt8 = "\t%.2f";
854 	else
855 		fmt8 = "%6.0f**";
856 
857 	if (DO_BIC(BIC_PkgWatt))
858 		outp += sprintf(outp, fmt8, p->energy_pkg * rapl_energy_units / interval_float);
859 	if (DO_BIC(BIC_CorWatt))
860 		outp += sprintf(outp, fmt8, p->energy_cores * rapl_energy_units / interval_float);
861 	if (DO_BIC(BIC_GFXWatt))
862 		outp += sprintf(outp, fmt8, p->energy_gfx * rapl_energy_units / interval_float);
863 	if (DO_BIC(BIC_RAMWatt))
864 		outp += sprintf(outp, fmt8, p->energy_dram * rapl_dram_energy_units / interval_float);
865 	if (DO_BIC(BIC_Pkg_J))
866 		outp += sprintf(outp, fmt8, p->energy_pkg * rapl_energy_units);
867 	if (DO_BIC(BIC_Cor_J))
868 		outp += sprintf(outp, fmt8, p->energy_cores * rapl_energy_units);
869 	if (DO_BIC(BIC_GFX_J))
870 		outp += sprintf(outp, fmt8, p->energy_gfx * rapl_energy_units);
871 	if (DO_BIC(BIC_RAM_J))
872 		outp += sprintf(outp, fmt8, p->energy_dram * rapl_dram_energy_units);
873 	if (DO_BIC(BIC_PKG__))
874 		outp += sprintf(outp, fmt8, 100.0 * p->rapl_pkg_perf_status * rapl_time_units / interval_float);
875 	if (DO_BIC(BIC_RAM__))
876 		outp += sprintf(outp, fmt8, 100.0 * p->rapl_dram_perf_status * rapl_time_units / interval_float);
877 
878 	for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
879 		if (mp->format == FORMAT_RAW) {
880 			if (mp->width == 32)
881 				outp += sprintf(outp, "\t0x%08lx", (unsigned long) p->counter[i]);
882 			else
883 				outp += sprintf(outp, "\t0x%016llx", p->counter[i]);
884 		} else if (mp->format == FORMAT_DELTA) {
885 			outp += sprintf(outp, "\t%lld", p->counter[i]);
886 		} else if (mp->format == FORMAT_PERCENT) {
887 			outp += sprintf(outp, "\t%.2f", 100.0 * p->counter[i]/t->tsc);
888 		}
889 	}
890 
891 done:
892 	outp += sprintf(outp, "\n");
893 
894 	return 0;
895 }
896 
897 void flush_output_stdout(void)
898 {
899 	FILE *filep;
900 
901 	if (outf == stderr)
902 		filep = stdout;
903 	else
904 		filep = outf;
905 
906 	fputs(output_buffer, filep);
907 	fflush(filep);
908 
909 	outp = output_buffer;
910 }
911 void flush_output_stderr(void)
912 {
913 	fputs(output_buffer, outf);
914 	fflush(outf);
915 	outp = output_buffer;
916 }
917 void format_all_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
918 {
919 	static int printed;
920 
921 	if (!printed || !summary_only)
922 		print_header();
923 
924 	if (topo.num_cpus > 1)
925 		format_counters(&average.threads, &average.cores,
926 			&average.packages);
927 
928 	printed = 1;
929 
930 	if (summary_only)
931 		return;
932 
933 	for_all_cpus(format_counters, t, c, p);
934 }
935 
936 #define DELTA_WRAP32(new, old)			\
937 	if (new > old) {			\
938 		old = new - old;		\
939 	} else {				\
940 		old = 0x100000000 + new - old;	\
941 	}
942 
943 int
944 delta_package(struct pkg_data *new, struct pkg_data *old)
945 {
946 	int i;
947 	struct msr_counter *mp;
948 
949 	if (do_skl_residency) {
950 		old->pkg_wtd_core_c0 = new->pkg_wtd_core_c0 - old->pkg_wtd_core_c0;
951 		old->pkg_any_core_c0 = new->pkg_any_core_c0 - old->pkg_any_core_c0;
952 		old->pkg_any_gfxe_c0 = new->pkg_any_gfxe_c0 - old->pkg_any_gfxe_c0;
953 		old->pkg_both_core_gfxe_c0 = new->pkg_both_core_gfxe_c0 - old->pkg_both_core_gfxe_c0;
954 	}
955 	old->pc2 = new->pc2 - old->pc2;
956 	if (do_pc3)
957 		old->pc3 = new->pc3 - old->pc3;
958 	if (do_pc6)
959 		old->pc6 = new->pc6 - old->pc6;
960 	if (do_pc7)
961 		old->pc7 = new->pc7 - old->pc7;
962 	old->pc8 = new->pc8 - old->pc8;
963 	old->pc9 = new->pc9 - old->pc9;
964 	old->pc10 = new->pc10 - old->pc10;
965 	old->pkg_temp_c = new->pkg_temp_c;
966 
967 	/* flag an error when rc6 counter resets/wraps */
968 	if (old->gfx_rc6_ms >  new->gfx_rc6_ms)
969 		old->gfx_rc6_ms = -1;
970 	else
971 		old->gfx_rc6_ms = new->gfx_rc6_ms - old->gfx_rc6_ms;
972 
973 	old->gfx_mhz = new->gfx_mhz;
974 
975 	DELTA_WRAP32(new->energy_pkg, old->energy_pkg);
976 	DELTA_WRAP32(new->energy_cores, old->energy_cores);
977 	DELTA_WRAP32(new->energy_gfx, old->energy_gfx);
978 	DELTA_WRAP32(new->energy_dram, old->energy_dram);
979 	DELTA_WRAP32(new->rapl_pkg_perf_status, old->rapl_pkg_perf_status);
980 	DELTA_WRAP32(new->rapl_dram_perf_status, old->rapl_dram_perf_status);
981 
982 	for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
983 		if (mp->format == FORMAT_RAW)
984 			old->counter[i] = new->counter[i];
985 		else
986 			old->counter[i] = new->counter[i] - old->counter[i];
987 	}
988 
989 	return 0;
990 }
991 
992 void
993 delta_core(struct core_data *new, struct core_data *old)
994 {
995 	int i;
996 	struct msr_counter *mp;
997 
998 	old->c3 = new->c3 - old->c3;
999 	old->c6 = new->c6 - old->c6;
1000 	old->c7 = new->c7 - old->c7;
1001 	old->core_temp_c = new->core_temp_c;
1002 	old->mc6_us = new->mc6_us - old->mc6_us;
1003 
1004 	for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1005 		if (mp->format == FORMAT_RAW)
1006 			old->counter[i] = new->counter[i];
1007 		else
1008 			old->counter[i] = new->counter[i] - old->counter[i];
1009 	}
1010 }
1011 
1012 /*
1013  * old = new - old
1014  */
1015 int
1016 delta_thread(struct thread_data *new, struct thread_data *old,
1017 	struct core_data *core_delta)
1018 {
1019 	int i;
1020 	struct msr_counter *mp;
1021 
1022 	old->tsc = new->tsc - old->tsc;
1023 
1024 	/* check for TSC < 1 Mcycles over interval */
1025 	if (old->tsc < (1000 * 1000))
1026 		errx(-3, "Insanely slow TSC rate, TSC stops in idle?\n"
1027 		     "You can disable all c-states by booting with \"idle=poll\"\n"
1028 		     "or just the deep ones with \"processor.max_cstate=1\"");
1029 
1030 	old->c1 = new->c1 - old->c1;
1031 
1032 	if (DO_BIC(BIC_Avg_MHz) || DO_BIC(BIC_Busy) || DO_BIC(BIC_Bzy_MHz)) {
1033 		if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
1034 			old->aperf = new->aperf - old->aperf;
1035 			old->mperf = new->mperf - old->mperf;
1036 		} else {
1037 			return -1;
1038 		}
1039 	}
1040 
1041 
1042 	if (use_c1_residency_msr) {
1043 		/*
1044 		 * Some models have a dedicated C1 residency MSR,
1045 		 * which should be more accurate than the derivation below.
1046 		 */
1047 	} else {
1048 		/*
1049 		 * As counter collection is not atomic,
1050 		 * it is possible for mperf's non-halted cycles + idle states
1051 		 * to exceed TSC's all cycles: show c1 = 0% in that case.
1052 		 */
1053 		if ((old->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > old->tsc)
1054 			old->c1 = 0;
1055 		else {
1056 			/* normal case, derive c1 */
1057 			old->c1 = old->tsc - old->mperf - core_delta->c3
1058 				- core_delta->c6 - core_delta->c7;
1059 		}
1060 	}
1061 
1062 	if (old->mperf == 0) {
1063 		if (debug > 1)
1064 			fprintf(outf, "cpu%d MPERF 0!\n", old->cpu_id);
1065 		old->mperf = 1;	/* divide by 0 protection */
1066 	}
1067 
1068 	if (DO_BIC(BIC_IRQ))
1069 		old->irq_count = new->irq_count - old->irq_count;
1070 
1071 	if (DO_BIC(BIC_SMI))
1072 		old->smi_count = new->smi_count - old->smi_count;
1073 
1074 	for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1075 		if (mp->format == FORMAT_RAW)
1076 			old->counter[i] = new->counter[i];
1077 		else
1078 			old->counter[i] = new->counter[i] - old->counter[i];
1079 	}
1080 	return 0;
1081 }
1082 
1083 int delta_cpu(struct thread_data *t, struct core_data *c,
1084 	struct pkg_data *p, struct thread_data *t2,
1085 	struct core_data *c2, struct pkg_data *p2)
1086 {
1087 	int retval = 0;
1088 
1089 	/* calculate core delta only for 1st thread in core */
1090 	if (t->flags & CPU_IS_FIRST_THREAD_IN_CORE)
1091 		delta_core(c, c2);
1092 
1093 	/* always calculate thread delta */
1094 	retval = delta_thread(t, t2, c2);	/* c2 is core delta */
1095 	if (retval)
1096 		return retval;
1097 
1098 	/* calculate package delta only for 1st core in package */
1099 	if (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)
1100 		retval = delta_package(p, p2);
1101 
1102 	return retval;
1103 }
1104 
1105 void clear_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1106 {
1107 	int i;
1108 	struct msr_counter  *mp;
1109 
1110 	t->tsc = 0;
1111 	t->aperf = 0;
1112 	t->mperf = 0;
1113 	t->c1 = 0;
1114 
1115 	t->irq_count = 0;
1116 	t->smi_count = 0;
1117 
1118 	/* tells format_counters to dump all fields from this set */
1119 	t->flags = CPU_IS_FIRST_THREAD_IN_CORE | CPU_IS_FIRST_CORE_IN_PACKAGE;
1120 
1121 	c->c3 = 0;
1122 	c->c6 = 0;
1123 	c->c7 = 0;
1124 	c->mc6_us = 0;
1125 	c->core_temp_c = 0;
1126 
1127 	p->pkg_wtd_core_c0 = 0;
1128 	p->pkg_any_core_c0 = 0;
1129 	p->pkg_any_gfxe_c0 = 0;
1130 	p->pkg_both_core_gfxe_c0 = 0;
1131 
1132 	p->pc2 = 0;
1133 	if (do_pc3)
1134 		p->pc3 = 0;
1135 	if (do_pc6)
1136 		p->pc6 = 0;
1137 	if (do_pc7)
1138 		p->pc7 = 0;
1139 	p->pc8 = 0;
1140 	p->pc9 = 0;
1141 	p->pc10 = 0;
1142 
1143 	p->energy_pkg = 0;
1144 	p->energy_dram = 0;
1145 	p->energy_cores = 0;
1146 	p->energy_gfx = 0;
1147 	p->rapl_pkg_perf_status = 0;
1148 	p->rapl_dram_perf_status = 0;
1149 	p->pkg_temp_c = 0;
1150 
1151 	p->gfx_rc6_ms = 0;
1152 	p->gfx_mhz = 0;
1153 	for (i = 0, mp = sys.tp; mp; i++, mp = mp->next)
1154 		t->counter[i] = 0;
1155 
1156 	for (i = 0, mp = sys.cp; mp; i++, mp = mp->next)
1157 		c->counter[i] = 0;
1158 
1159 	for (i = 0, mp = sys.pp; mp; i++, mp = mp->next)
1160 		p->counter[i] = 0;
1161 }
1162 int sum_counters(struct thread_data *t, struct core_data *c,
1163 	struct pkg_data *p)
1164 {
1165 	int i;
1166 	struct msr_counter *mp;
1167 
1168 	average.threads.tsc += t->tsc;
1169 	average.threads.aperf += t->aperf;
1170 	average.threads.mperf += t->mperf;
1171 	average.threads.c1 += t->c1;
1172 
1173 	average.threads.irq_count += t->irq_count;
1174 	average.threads.smi_count += t->smi_count;
1175 
1176 	for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1177 		if (mp->format == FORMAT_RAW)
1178 			continue;
1179 		average.threads.counter[i] += t->counter[i];
1180 	}
1181 
1182 	/* sum per-core values only for 1st thread in core */
1183 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1184 		return 0;
1185 
1186 	average.cores.c3 += c->c3;
1187 	average.cores.c6 += c->c6;
1188 	average.cores.c7 += c->c7;
1189 	average.cores.mc6_us += c->mc6_us;
1190 
1191 	average.cores.core_temp_c = MAX(average.cores.core_temp_c, c->core_temp_c);
1192 
1193 	for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1194 		if (mp->format == FORMAT_RAW)
1195 			continue;
1196 		average.cores.counter[i] += c->counter[i];
1197 	}
1198 
1199 	/* sum per-pkg values only for 1st core in pkg */
1200 	if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1201 		return 0;
1202 
1203 	if (do_skl_residency) {
1204 		average.packages.pkg_wtd_core_c0 += p->pkg_wtd_core_c0;
1205 		average.packages.pkg_any_core_c0 += p->pkg_any_core_c0;
1206 		average.packages.pkg_any_gfxe_c0 += p->pkg_any_gfxe_c0;
1207 		average.packages.pkg_both_core_gfxe_c0 += p->pkg_both_core_gfxe_c0;
1208 	}
1209 
1210 	average.packages.pc2 += p->pc2;
1211 	if (do_pc3)
1212 		average.packages.pc3 += p->pc3;
1213 	if (do_pc6)
1214 		average.packages.pc6 += p->pc6;
1215 	if (do_pc7)
1216 		average.packages.pc7 += p->pc7;
1217 	average.packages.pc8 += p->pc8;
1218 	average.packages.pc9 += p->pc9;
1219 	average.packages.pc10 += p->pc10;
1220 
1221 	average.packages.energy_pkg += p->energy_pkg;
1222 	average.packages.energy_dram += p->energy_dram;
1223 	average.packages.energy_cores += p->energy_cores;
1224 	average.packages.energy_gfx += p->energy_gfx;
1225 
1226 	average.packages.gfx_rc6_ms = p->gfx_rc6_ms;
1227 	average.packages.gfx_mhz = p->gfx_mhz;
1228 
1229 	average.packages.pkg_temp_c = MAX(average.packages.pkg_temp_c, p->pkg_temp_c);
1230 
1231 	average.packages.rapl_pkg_perf_status += p->rapl_pkg_perf_status;
1232 	average.packages.rapl_dram_perf_status += p->rapl_dram_perf_status;
1233 
1234 	for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
1235 		if (mp->format == FORMAT_RAW)
1236 			continue;
1237 		average.packages.counter[i] += p->counter[i];
1238 	}
1239 	return 0;
1240 }
1241 /*
1242  * sum the counters for all cpus in the system
1243  * compute the weighted average
1244  */
1245 void compute_average(struct thread_data *t, struct core_data *c,
1246 	struct pkg_data *p)
1247 {
1248 	int i;
1249 	struct msr_counter *mp;
1250 
1251 	clear_counters(&average.threads, &average.cores, &average.packages);
1252 
1253 	for_all_cpus(sum_counters, t, c, p);
1254 
1255 	average.threads.tsc /= topo.num_cpus;
1256 	average.threads.aperf /= topo.num_cpus;
1257 	average.threads.mperf /= topo.num_cpus;
1258 	average.threads.c1 /= topo.num_cpus;
1259 
1260 	average.cores.c3 /= topo.num_cores;
1261 	average.cores.c6 /= topo.num_cores;
1262 	average.cores.c7 /= topo.num_cores;
1263 	average.cores.mc6_us /= topo.num_cores;
1264 
1265 	if (do_skl_residency) {
1266 		average.packages.pkg_wtd_core_c0 /= topo.num_packages;
1267 		average.packages.pkg_any_core_c0 /= topo.num_packages;
1268 		average.packages.pkg_any_gfxe_c0 /= topo.num_packages;
1269 		average.packages.pkg_both_core_gfxe_c0 /= topo.num_packages;
1270 	}
1271 
1272 	average.packages.pc2 /= topo.num_packages;
1273 	if (do_pc3)
1274 		average.packages.pc3 /= topo.num_packages;
1275 	if (do_pc6)
1276 		average.packages.pc6 /= topo.num_packages;
1277 	if (do_pc7)
1278 		average.packages.pc7 /= topo.num_packages;
1279 
1280 	average.packages.pc8 /= topo.num_packages;
1281 	average.packages.pc9 /= topo.num_packages;
1282 	average.packages.pc10 /= topo.num_packages;
1283 
1284 	for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1285 		if (mp->format == FORMAT_RAW)
1286 			continue;
1287 		average.threads.counter[i] /= topo.num_cpus;
1288 	}
1289 	for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1290 		if (mp->format == FORMAT_RAW)
1291 			continue;
1292 		average.cores.counter[i] /= topo.num_cores;
1293 	}
1294 	for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
1295 		if (mp->format == FORMAT_RAW)
1296 			continue;
1297 		average.packages.counter[i] /= topo.num_packages;
1298 	}
1299 }
1300 
1301 static unsigned long long rdtsc(void)
1302 {
1303 	unsigned int low, high;
1304 
1305 	asm volatile("rdtsc" : "=a" (low), "=d" (high));
1306 
1307 	return low | ((unsigned long long)high) << 32;
1308 }
1309 
1310 /*
1311  * get_counters(...)
1312  * migrate to cpu
1313  * acquire and record local counters for that cpu
1314  */
1315 int get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1316 {
1317 	int cpu = t->cpu_id;
1318 	unsigned long long msr;
1319 	int aperf_mperf_retry_count = 0;
1320 	struct msr_counter *mp;
1321 	int i;
1322 
1323 	if (cpu_migrate(cpu)) {
1324 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
1325 		return -1;
1326 	}
1327 
1328 retry:
1329 	t->tsc = rdtsc();	/* we are running on local CPU of interest */
1330 
1331 	if (DO_BIC(BIC_Avg_MHz) || DO_BIC(BIC_Busy) || DO_BIC(BIC_Bzy_MHz)) {
1332 		unsigned long long tsc_before, tsc_between, tsc_after, aperf_time, mperf_time;
1333 
1334 		/*
1335 		 * The TSC, APERF and MPERF must be read together for
1336 		 * APERF/MPERF and MPERF/TSC to give accurate results.
1337 		 *
1338 		 * Unfortunately, APERF and MPERF are read by
1339 		 * individual system call, so delays may occur
1340 		 * between them.  If the time to read them
1341 		 * varies by a large amount, we re-read them.
1342 		 */
1343 
1344 		/*
1345 		 * This initial dummy APERF read has been seen to
1346 		 * reduce jitter in the subsequent reads.
1347 		 */
1348 
1349 		if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
1350 			return -3;
1351 
1352 		t->tsc = rdtsc();	/* re-read close to APERF */
1353 
1354 		tsc_before = t->tsc;
1355 
1356 		if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
1357 			return -3;
1358 
1359 		tsc_between = rdtsc();
1360 
1361 		if (get_msr(cpu, MSR_IA32_MPERF, &t->mperf))
1362 			return -4;
1363 
1364 		tsc_after = rdtsc();
1365 
1366 		aperf_time = tsc_between - tsc_before;
1367 		mperf_time = tsc_after - tsc_between;
1368 
1369 		/*
1370 		 * If the system call latency to read APERF and MPERF
1371 		 * differ by more than 2x, then try again.
1372 		 */
1373 		if ((aperf_time > (2 * mperf_time)) || (mperf_time > (2 * aperf_time))) {
1374 			aperf_mperf_retry_count++;
1375 			if (aperf_mperf_retry_count < 5)
1376 				goto retry;
1377 			else
1378 				warnx("cpu%d jitter %lld %lld",
1379 					cpu, aperf_time, mperf_time);
1380 		}
1381 		aperf_mperf_retry_count = 0;
1382 
1383 		t->aperf = t->aperf * aperf_mperf_multiplier;
1384 		t->mperf = t->mperf * aperf_mperf_multiplier;
1385 	}
1386 
1387 	if (DO_BIC(BIC_IRQ))
1388 		t->irq_count = irqs_per_cpu[cpu];
1389 	if (DO_BIC(BIC_SMI)) {
1390 		if (get_msr(cpu, MSR_SMI_COUNT, &msr))
1391 			return -5;
1392 		t->smi_count = msr & 0xFFFFFFFF;
1393 	}
1394 	if (DO_BIC(BIC_CPU_c1) && use_c1_residency_msr) {
1395 		if (get_msr(cpu, MSR_CORE_C1_RES, &t->c1))
1396 			return -6;
1397 	}
1398 
1399 	for (i = 0, mp = sys.tp; mp; i++, mp = mp->next) {
1400 		if (get_msr(cpu, mp->msr_num, &t->counter[i]))
1401 			return -10;
1402 	}
1403 
1404 
1405 	/* collect core counters only for 1st thread in core */
1406 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1407 		return 0;
1408 
1409 	if (DO_BIC(BIC_CPU_c3) && !do_slm_cstates && !do_knl_cstates) {
1410 		if (get_msr(cpu, MSR_CORE_C3_RESIDENCY, &c->c3))
1411 			return -6;
1412 	}
1413 
1414 	if (DO_BIC(BIC_CPU_c6) && !do_knl_cstates) {
1415 		if (get_msr(cpu, MSR_CORE_C6_RESIDENCY, &c->c6))
1416 			return -7;
1417 	} else if (do_knl_cstates) {
1418 		if (get_msr(cpu, MSR_KNL_CORE_C6_RESIDENCY, &c->c6))
1419 			return -7;
1420 	}
1421 
1422 	if (DO_BIC(BIC_CPU_c7))
1423 		if (get_msr(cpu, MSR_CORE_C7_RESIDENCY, &c->c7))
1424 			return -8;
1425 
1426 	if (DO_BIC(BIC_Mod_c6))
1427 		if (get_msr(cpu, MSR_MODULE_C6_RES_MS, &c->mc6_us))
1428 			return -8;
1429 
1430 	if (DO_BIC(BIC_CoreTmp)) {
1431 		if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
1432 			return -9;
1433 		c->core_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
1434 	}
1435 
1436 	for (i = 0, mp = sys.cp; mp; i++, mp = mp->next) {
1437 		if (get_msr(cpu, mp->msr_num, &c->counter[i]))
1438 			return -10;
1439 	}
1440 
1441 	/* collect package counters only for 1st core in package */
1442 	if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1443 		return 0;
1444 
1445 	if (do_skl_residency) {
1446 		if (get_msr(cpu, MSR_PKG_WEIGHTED_CORE_C0_RES, &p->pkg_wtd_core_c0))
1447 			return -10;
1448 		if (get_msr(cpu, MSR_PKG_ANY_CORE_C0_RES, &p->pkg_any_core_c0))
1449 			return -11;
1450 		if (get_msr(cpu, MSR_PKG_ANY_GFXE_C0_RES, &p->pkg_any_gfxe_c0))
1451 			return -12;
1452 		if (get_msr(cpu, MSR_PKG_BOTH_CORE_GFXE_C0_RES, &p->pkg_both_core_gfxe_c0))
1453 			return -13;
1454 	}
1455 	if (do_pc3)
1456 		if (get_msr(cpu, MSR_PKG_C3_RESIDENCY, &p->pc3))
1457 			return -9;
1458 	if (do_pc6) {
1459 		if (do_slm_cstates) {
1460 			if (get_msr(cpu, MSR_ATOM_PKG_C6_RESIDENCY, &p->pc6))
1461 				return -10;
1462 		} else {
1463 			if (get_msr(cpu, MSR_PKG_C6_RESIDENCY, &p->pc6))
1464 				return -10;
1465 		}
1466 	}
1467 
1468 	if (do_pc2)
1469 		if (get_msr(cpu, MSR_PKG_C2_RESIDENCY, &p->pc2))
1470 			return -11;
1471 	if (do_pc7)
1472 		if (get_msr(cpu, MSR_PKG_C7_RESIDENCY, &p->pc7))
1473 			return -12;
1474 	if (do_c8_c9_c10) {
1475 		if (get_msr(cpu, MSR_PKG_C8_RESIDENCY, &p->pc8))
1476 			return -13;
1477 		if (get_msr(cpu, MSR_PKG_C9_RESIDENCY, &p->pc9))
1478 			return -13;
1479 		if (get_msr(cpu, MSR_PKG_C10_RESIDENCY, &p->pc10))
1480 			return -13;
1481 	}
1482 	if (do_rapl & RAPL_PKG) {
1483 		if (get_msr(cpu, MSR_PKG_ENERGY_STATUS, &msr))
1484 			return -13;
1485 		p->energy_pkg = msr & 0xFFFFFFFF;
1486 	}
1487 	if (do_rapl & RAPL_CORES_ENERGY_STATUS) {
1488 		if (get_msr(cpu, MSR_PP0_ENERGY_STATUS, &msr))
1489 			return -14;
1490 		p->energy_cores = msr & 0xFFFFFFFF;
1491 	}
1492 	if (do_rapl & RAPL_DRAM) {
1493 		if (get_msr(cpu, MSR_DRAM_ENERGY_STATUS, &msr))
1494 			return -15;
1495 		p->energy_dram = msr & 0xFFFFFFFF;
1496 	}
1497 	if (do_rapl & RAPL_GFX) {
1498 		if (get_msr(cpu, MSR_PP1_ENERGY_STATUS, &msr))
1499 			return -16;
1500 		p->energy_gfx = msr & 0xFFFFFFFF;
1501 	}
1502 	if (do_rapl & RAPL_PKG_PERF_STATUS) {
1503 		if (get_msr(cpu, MSR_PKG_PERF_STATUS, &msr))
1504 			return -16;
1505 		p->rapl_pkg_perf_status = msr & 0xFFFFFFFF;
1506 	}
1507 	if (do_rapl & RAPL_DRAM_PERF_STATUS) {
1508 		if (get_msr(cpu, MSR_DRAM_PERF_STATUS, &msr))
1509 			return -16;
1510 		p->rapl_dram_perf_status = msr & 0xFFFFFFFF;
1511 	}
1512 	if (DO_BIC(BIC_PkgTmp)) {
1513 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
1514 			return -17;
1515 		p->pkg_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
1516 	}
1517 
1518 	if (DO_BIC(BIC_GFX_rc6))
1519 		p->gfx_rc6_ms = gfx_cur_rc6_ms;
1520 
1521 	if (DO_BIC(BIC_GFXMHz))
1522 		p->gfx_mhz = gfx_cur_mhz;
1523 
1524 	for (i = 0, mp = sys.pp; mp; i++, mp = mp->next) {
1525 		if (get_msr(cpu, mp->msr_num, &p->counter[i]))
1526 			return -10;
1527 	}
1528 
1529 	return 0;
1530 }
1531 
1532 /*
1533  * MSR_PKG_CST_CONFIG_CONTROL decoding for pkg_cstate_limit:
1534  * If you change the values, note they are used both in comparisons
1535  * (>= PCL__7) and to index pkg_cstate_limit_strings[].
1536  */
1537 
1538 #define PCLUKN 0 /* Unknown */
1539 #define PCLRSV 1 /* Reserved */
1540 #define PCL__0 2 /* PC0 */
1541 #define PCL__1 3 /* PC1 */
1542 #define PCL__2 4 /* PC2 */
1543 #define PCL__3 5 /* PC3 */
1544 #define PCL__4 6 /* PC4 */
1545 #define PCL__6 7 /* PC6 */
1546 #define PCL_6N 8 /* PC6 No Retention */
1547 #define PCL_6R 9 /* PC6 Retention */
1548 #define PCL__7 10 /* PC7 */
1549 #define PCL_7S 11 /* PC7 Shrink */
1550 #define PCL__8 12 /* PC8 */
1551 #define PCL__9 13 /* PC9 */
1552 #define PCLUNL 14 /* Unlimited */
1553 
1554 int pkg_cstate_limit = PCLUKN;
1555 char *pkg_cstate_limit_strings[] = { "reserved", "unknown", "pc0", "pc1", "pc2",
1556 	"pc3", "pc4", "pc6", "pc6n", "pc6r", "pc7", "pc7s", "pc8", "pc9", "unlimited"};
1557 
1558 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};
1559 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};
1560 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};
1561 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};
1562 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};
1563 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};
1564 int bxt_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1565 int skx_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1566 
1567 
1568 static void
1569 calculate_tsc_tweak()
1570 {
1571 	tsc_tweak = base_hz / tsc_hz;
1572 }
1573 
1574 static void
1575 dump_nhm_platform_info(void)
1576 {
1577 	unsigned long long msr;
1578 	unsigned int ratio;
1579 
1580 	get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
1581 
1582 	fprintf(outf, "cpu%d: MSR_PLATFORM_INFO: 0x%08llx\n", base_cpu, msr);
1583 
1584 	ratio = (msr >> 40) & 0xFF;
1585 	fprintf(outf, "%d * %.1f = %.1f MHz max efficiency frequency\n",
1586 		ratio, bclk, ratio * bclk);
1587 
1588 	ratio = (msr >> 8) & 0xFF;
1589 	fprintf(outf, "%d * %.1f = %.1f MHz base frequency\n",
1590 		ratio, bclk, ratio * bclk);
1591 
1592 	get_msr(base_cpu, MSR_IA32_POWER_CTL, &msr);
1593 	fprintf(outf, "cpu%d: MSR_IA32_POWER_CTL: 0x%08llx (C1E auto-promotion: %sabled)\n",
1594 		base_cpu, msr, msr & 0x2 ? "EN" : "DIS");
1595 
1596 	return;
1597 }
1598 
1599 static void
1600 dump_hsw_turbo_ratio_limits(void)
1601 {
1602 	unsigned long long msr;
1603 	unsigned int ratio;
1604 
1605 	get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT2, &msr);
1606 
1607 	fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT2: 0x%08llx\n", base_cpu, msr);
1608 
1609 	ratio = (msr >> 8) & 0xFF;
1610 	if (ratio)
1611 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 18 active cores\n",
1612 			ratio, bclk, ratio * bclk);
1613 
1614 	ratio = (msr >> 0) & 0xFF;
1615 	if (ratio)
1616 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 17 active cores\n",
1617 			ratio, bclk, ratio * bclk);
1618 	return;
1619 }
1620 
1621 static void
1622 dump_ivt_turbo_ratio_limits(void)
1623 {
1624 	unsigned long long msr;
1625 	unsigned int ratio;
1626 
1627 	get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT1, &msr);
1628 
1629 	fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT1: 0x%08llx\n", base_cpu, msr);
1630 
1631 	ratio = (msr >> 56) & 0xFF;
1632 	if (ratio)
1633 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 16 active cores\n",
1634 			ratio, bclk, ratio * bclk);
1635 
1636 	ratio = (msr >> 48) & 0xFF;
1637 	if (ratio)
1638 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 15 active cores\n",
1639 			ratio, bclk, ratio * bclk);
1640 
1641 	ratio = (msr >> 40) & 0xFF;
1642 	if (ratio)
1643 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 14 active cores\n",
1644 			ratio, bclk, ratio * bclk);
1645 
1646 	ratio = (msr >> 32) & 0xFF;
1647 	if (ratio)
1648 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 13 active cores\n",
1649 			ratio, bclk, ratio * bclk);
1650 
1651 	ratio = (msr >> 24) & 0xFF;
1652 	if (ratio)
1653 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 12 active cores\n",
1654 			ratio, bclk, ratio * bclk);
1655 
1656 	ratio = (msr >> 16) & 0xFF;
1657 	if (ratio)
1658 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 11 active cores\n",
1659 			ratio, bclk, ratio * bclk);
1660 
1661 	ratio = (msr >> 8) & 0xFF;
1662 	if (ratio)
1663 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 10 active cores\n",
1664 			ratio, bclk, ratio * bclk);
1665 
1666 	ratio = (msr >> 0) & 0xFF;
1667 	if (ratio)
1668 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 9 active cores\n",
1669 			ratio, bclk, ratio * bclk);
1670 	return;
1671 }
1672 
1673 static void
1674 dump_nhm_turbo_ratio_limits(void)
1675 {
1676 	unsigned long long msr;
1677 	unsigned int ratio;
1678 
1679 	get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT, &msr);
1680 
1681 	fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT: 0x%08llx\n", base_cpu, msr);
1682 
1683 	ratio = (msr >> 56) & 0xFF;
1684 	if (ratio)
1685 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 8 active cores\n",
1686 			ratio, bclk, ratio * bclk);
1687 
1688 	ratio = (msr >> 48) & 0xFF;
1689 	if (ratio)
1690 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 7 active cores\n",
1691 			ratio, bclk, ratio * bclk);
1692 
1693 	ratio = (msr >> 40) & 0xFF;
1694 	if (ratio)
1695 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 6 active cores\n",
1696 			ratio, bclk, ratio * bclk);
1697 
1698 	ratio = (msr >> 32) & 0xFF;
1699 	if (ratio)
1700 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 5 active cores\n",
1701 			ratio, bclk, ratio * bclk);
1702 
1703 	ratio = (msr >> 24) & 0xFF;
1704 	if (ratio)
1705 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 4 active cores\n",
1706 			ratio, bclk, ratio * bclk);
1707 
1708 	ratio = (msr >> 16) & 0xFF;
1709 	if (ratio)
1710 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 3 active cores\n",
1711 			ratio, bclk, ratio * bclk);
1712 
1713 	ratio = (msr >> 8) & 0xFF;
1714 	if (ratio)
1715 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 2 active cores\n",
1716 			ratio, bclk, ratio * bclk);
1717 
1718 	ratio = (msr >> 0) & 0xFF;
1719 	if (ratio)
1720 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 1 active cores\n",
1721 			ratio, bclk, ratio * bclk);
1722 	return;
1723 }
1724 
1725 static void
1726 dump_atom_turbo_ratio_limits(void)
1727 {
1728 	unsigned long long msr;
1729 	unsigned int ratio;
1730 
1731 	get_msr(base_cpu, MSR_ATOM_CORE_RATIOS, &msr);
1732 	fprintf(outf, "cpu%d: MSR_ATOM_CORE_RATIOS: 0x%08llx\n", base_cpu, msr & 0xFFFFFFFF);
1733 
1734 	ratio = (msr >> 0) & 0x3F;
1735 	if (ratio)
1736 		fprintf(outf, "%d * %.1f = %.1f MHz minimum operating frequency\n",
1737 			ratio, bclk, ratio * bclk);
1738 
1739 	ratio = (msr >> 8) & 0x3F;
1740 	if (ratio)
1741 		fprintf(outf, "%d * %.1f = %.1f MHz low frequency mode (LFM)\n",
1742 			ratio, bclk, ratio * bclk);
1743 
1744 	ratio = (msr >> 16) & 0x3F;
1745 	if (ratio)
1746 		fprintf(outf, "%d * %.1f = %.1f MHz base frequency\n",
1747 			ratio, bclk, ratio * bclk);
1748 
1749 	get_msr(base_cpu, MSR_ATOM_CORE_TURBO_RATIOS, &msr);
1750 	fprintf(outf, "cpu%d: MSR_ATOM_CORE_TURBO_RATIOS: 0x%08llx\n", base_cpu, msr & 0xFFFFFFFF);
1751 
1752 	ratio = (msr >> 24) & 0x3F;
1753 	if (ratio)
1754 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 4 active cores\n",
1755 			ratio, bclk, ratio * bclk);
1756 
1757 	ratio = (msr >> 16) & 0x3F;
1758 	if (ratio)
1759 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 3 active cores\n",
1760 			ratio, bclk, ratio * bclk);
1761 
1762 	ratio = (msr >> 8) & 0x3F;
1763 	if (ratio)
1764 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 2 active cores\n",
1765 			ratio, bclk, ratio * bclk);
1766 
1767 	ratio = (msr >> 0) & 0x3F;
1768 	if (ratio)
1769 		fprintf(outf, "%d * %.1f = %.1f MHz max turbo 1 active core\n",
1770 			ratio, bclk, ratio * bclk);
1771 }
1772 
1773 static void
1774 dump_knl_turbo_ratio_limits(void)
1775 {
1776 	const unsigned int buckets_no = 7;
1777 
1778 	unsigned long long msr;
1779 	int delta_cores, delta_ratio;
1780 	int i, b_nr;
1781 	unsigned int cores[buckets_no];
1782 	unsigned int ratio[buckets_no];
1783 
1784 	get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT, &msr);
1785 
1786 	fprintf(outf, "cpu%d: MSR_TURBO_RATIO_LIMIT: 0x%08llx\n",
1787 		base_cpu, msr);
1788 
1789 	/**
1790 	 * Turbo encoding in KNL is as follows:
1791 	 * [0] -- Reserved
1792 	 * [7:1] -- Base value of number of active cores of bucket 1.
1793 	 * [15:8] -- Base value of freq ratio of bucket 1.
1794 	 * [20:16] -- +ve delta of number of active cores of bucket 2.
1795 	 * i.e. active cores of bucket 2 =
1796 	 * active cores of bucket 1 + delta
1797 	 * [23:21] -- Negative delta of freq ratio of bucket 2.
1798 	 * i.e. freq ratio of bucket 2 =
1799 	 * freq ratio of bucket 1 - delta
1800 	 * [28:24]-- +ve delta of number of active cores of bucket 3.
1801 	 * [31:29]-- -ve delta of freq ratio of bucket 3.
1802 	 * [36:32]-- +ve delta of number of active cores of bucket 4.
1803 	 * [39:37]-- -ve delta of freq ratio of bucket 4.
1804 	 * [44:40]-- +ve delta of number of active cores of bucket 5.
1805 	 * [47:45]-- -ve delta of freq ratio of bucket 5.
1806 	 * [52:48]-- +ve delta of number of active cores of bucket 6.
1807 	 * [55:53]-- -ve delta of freq ratio of bucket 6.
1808 	 * [60:56]-- +ve delta of number of active cores of bucket 7.
1809 	 * [63:61]-- -ve delta of freq ratio of bucket 7.
1810 	 */
1811 
1812 	b_nr = 0;
1813 	cores[b_nr] = (msr & 0xFF) >> 1;
1814 	ratio[b_nr] = (msr >> 8) & 0xFF;
1815 
1816 	for (i = 16; i < 64; i += 8) {
1817 		delta_cores = (msr >> i) & 0x1F;
1818 		delta_ratio = (msr >> (i + 5)) & 0x7;
1819 
1820 		cores[b_nr + 1] = cores[b_nr] + delta_cores;
1821 		ratio[b_nr + 1] = ratio[b_nr] - delta_ratio;
1822 		b_nr++;
1823 	}
1824 
1825 	for (i = buckets_no - 1; i >= 0; i--)
1826 		if (i > 0 ? ratio[i] != ratio[i - 1] : 1)
1827 			fprintf(outf,
1828 				"%d * %.1f = %.1f MHz max turbo %d active cores\n",
1829 				ratio[i], bclk, ratio[i] * bclk, cores[i]);
1830 }
1831 
1832 static void
1833 dump_nhm_cst_cfg(void)
1834 {
1835 	unsigned long long msr;
1836 
1837 	get_msr(base_cpu, MSR_PKG_CST_CONFIG_CONTROL, &msr);
1838 
1839 #define SNB_C1_AUTO_UNDEMOTE              (1UL << 27)
1840 #define SNB_C3_AUTO_UNDEMOTE              (1UL << 28)
1841 
1842 	fprintf(outf, "cpu%d: MSR_PKG_CST_CONFIG_CONTROL: 0x%08llx", base_cpu, msr);
1843 
1844 	fprintf(outf, " (%s%s%s%s%slocked: pkg-cstate-limit=%d: %s)\n",
1845 		(msr & SNB_C3_AUTO_UNDEMOTE) ? "UNdemote-C3, " : "",
1846 		(msr & SNB_C1_AUTO_UNDEMOTE) ? "UNdemote-C1, " : "",
1847 		(msr & NHM_C3_AUTO_DEMOTE) ? "demote-C3, " : "",
1848 		(msr & NHM_C1_AUTO_DEMOTE) ? "demote-C1, " : "",
1849 		(msr & (1 << 15)) ? "" : "UN",
1850 		(unsigned int)msr & 0xF,
1851 		pkg_cstate_limit_strings[pkg_cstate_limit]);
1852 	return;
1853 }
1854 
1855 static void
1856 dump_config_tdp(void)
1857 {
1858 	unsigned long long msr;
1859 
1860 	get_msr(base_cpu, MSR_CONFIG_TDP_NOMINAL, &msr);
1861 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_NOMINAL: 0x%08llx", base_cpu, msr);
1862 	fprintf(outf, " (base_ratio=%d)\n", (unsigned int)msr & 0xFF);
1863 
1864 	get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_1, &msr);
1865 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_LEVEL_1: 0x%08llx (", base_cpu, msr);
1866 	if (msr) {
1867 		fprintf(outf, "PKG_MIN_PWR_LVL1=%d ", (unsigned int)(msr >> 48) & 0x7FFF);
1868 		fprintf(outf, "PKG_MAX_PWR_LVL1=%d ", (unsigned int)(msr >> 32) & 0x7FFF);
1869 		fprintf(outf, "LVL1_RATIO=%d ", (unsigned int)(msr >> 16) & 0xFF);
1870 		fprintf(outf, "PKG_TDP_LVL1=%d", (unsigned int)(msr) & 0x7FFF);
1871 	}
1872 	fprintf(outf, ")\n");
1873 
1874 	get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_2, &msr);
1875 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_LEVEL_2: 0x%08llx (", base_cpu, msr);
1876 	if (msr) {
1877 		fprintf(outf, "PKG_MIN_PWR_LVL2=%d ", (unsigned int)(msr >> 48) & 0x7FFF);
1878 		fprintf(outf, "PKG_MAX_PWR_LVL2=%d ", (unsigned int)(msr >> 32) & 0x7FFF);
1879 		fprintf(outf, "LVL2_RATIO=%d ", (unsigned int)(msr >> 16) & 0xFF);
1880 		fprintf(outf, "PKG_TDP_LVL2=%d", (unsigned int)(msr) & 0x7FFF);
1881 	}
1882 	fprintf(outf, ")\n");
1883 
1884 	get_msr(base_cpu, MSR_CONFIG_TDP_CONTROL, &msr);
1885 	fprintf(outf, "cpu%d: MSR_CONFIG_TDP_CONTROL: 0x%08llx (", base_cpu, msr);
1886 	if ((msr) & 0x3)
1887 		fprintf(outf, "TDP_LEVEL=%d ", (unsigned int)(msr) & 0x3);
1888 	fprintf(outf, " lock=%d", (unsigned int)(msr >> 31) & 1);
1889 	fprintf(outf, ")\n");
1890 
1891 	get_msr(base_cpu, MSR_TURBO_ACTIVATION_RATIO, &msr);
1892 	fprintf(outf, "cpu%d: MSR_TURBO_ACTIVATION_RATIO: 0x%08llx (", base_cpu, msr);
1893 	fprintf(outf, "MAX_NON_TURBO_RATIO=%d", (unsigned int)(msr) & 0xFF);
1894 	fprintf(outf, " lock=%d", (unsigned int)(msr >> 31) & 1);
1895 	fprintf(outf, ")\n");
1896 }
1897 
1898 unsigned int irtl_time_units[] = {1, 32, 1024, 32768, 1048576, 33554432, 0, 0 };
1899 
1900 void print_irtl(void)
1901 {
1902 	unsigned long long msr;
1903 
1904 	get_msr(base_cpu, MSR_PKGC3_IRTL, &msr);
1905 	fprintf(outf, "cpu%d: MSR_PKGC3_IRTL: 0x%08llx (", base_cpu, msr);
1906 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
1907 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
1908 
1909 	get_msr(base_cpu, MSR_PKGC6_IRTL, &msr);
1910 	fprintf(outf, "cpu%d: MSR_PKGC6_IRTL: 0x%08llx (", base_cpu, msr);
1911 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
1912 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
1913 
1914 	get_msr(base_cpu, MSR_PKGC7_IRTL, &msr);
1915 	fprintf(outf, "cpu%d: MSR_PKGC7_IRTL: 0x%08llx (", base_cpu, msr);
1916 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
1917 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
1918 
1919 	if (!do_irtl_hsw)
1920 		return;
1921 
1922 	get_msr(base_cpu, MSR_PKGC8_IRTL, &msr);
1923 	fprintf(outf, "cpu%d: MSR_PKGC8_IRTL: 0x%08llx (", base_cpu, msr);
1924 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
1925 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
1926 
1927 	get_msr(base_cpu, MSR_PKGC9_IRTL, &msr);
1928 	fprintf(outf, "cpu%d: MSR_PKGC9_IRTL: 0x%08llx (", base_cpu, msr);
1929 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
1930 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
1931 
1932 	get_msr(base_cpu, MSR_PKGC10_IRTL, &msr);
1933 	fprintf(outf, "cpu%d: MSR_PKGC10_IRTL: 0x%08llx (", base_cpu, msr);
1934 	fprintf(outf, "%svalid, %lld ns)\n", msr & (1 << 15) ? "" : "NOT",
1935 		(msr & 0x3FF) * irtl_time_units[(msr >> 10) & 0x3]);
1936 
1937 }
1938 void free_fd_percpu(void)
1939 {
1940 	int i;
1941 
1942 	for (i = 0; i < topo.max_cpu_num + 1; ++i) {
1943 		if (fd_percpu[i] != 0)
1944 			close(fd_percpu[i]);
1945 	}
1946 
1947 	free(fd_percpu);
1948 }
1949 
1950 void free_all_buffers(void)
1951 {
1952 	CPU_FREE(cpu_present_set);
1953 	cpu_present_set = NULL;
1954 	cpu_present_setsize = 0;
1955 
1956 	CPU_FREE(cpu_affinity_set);
1957 	cpu_affinity_set = NULL;
1958 	cpu_affinity_setsize = 0;
1959 
1960 	free(thread_even);
1961 	free(core_even);
1962 	free(package_even);
1963 
1964 	thread_even = NULL;
1965 	core_even = NULL;
1966 	package_even = NULL;
1967 
1968 	free(thread_odd);
1969 	free(core_odd);
1970 	free(package_odd);
1971 
1972 	thread_odd = NULL;
1973 	core_odd = NULL;
1974 	package_odd = NULL;
1975 
1976 	free(output_buffer);
1977 	output_buffer = NULL;
1978 	outp = NULL;
1979 
1980 	free_fd_percpu();
1981 
1982 	free(irq_column_2_cpu);
1983 	free(irqs_per_cpu);
1984 }
1985 
1986 /*
1987  * Open a file, and exit on failure
1988  */
1989 FILE *fopen_or_die(const char *path, const char *mode)
1990 {
1991 	FILE *filep = fopen(path, mode);
1992 	if (!filep)
1993 		err(1, "%s: open failed", path);
1994 	return filep;
1995 }
1996 
1997 /*
1998  * Parse a file containing a single int.
1999  */
2000 int parse_int_file(const char *fmt, ...)
2001 {
2002 	va_list args;
2003 	char path[PATH_MAX];
2004 	FILE *filep;
2005 	int value;
2006 
2007 	va_start(args, fmt);
2008 	vsnprintf(path, sizeof(path), fmt, args);
2009 	va_end(args);
2010 	filep = fopen_or_die(path, "r");
2011 	if (fscanf(filep, "%d", &value) != 1)
2012 		err(1, "%s: failed to parse number from file", path);
2013 	fclose(filep);
2014 	return value;
2015 }
2016 
2017 /*
2018  * get_cpu_position_in_core(cpu)
2019  * return the position of the CPU among its HT siblings in the core
2020  * return -1 if the sibling is not in list
2021  */
2022 int get_cpu_position_in_core(int cpu)
2023 {
2024 	char path[64];
2025 	FILE *filep;
2026 	int this_cpu;
2027 	char character;
2028 	int i;
2029 
2030 	sprintf(path,
2031 		"/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list",
2032 		cpu);
2033 	filep = fopen(path, "r");
2034 	if (filep == NULL) {
2035 		perror(path);
2036 		exit(1);
2037 	}
2038 
2039 	for (i = 0; i < topo.num_threads_per_core; i++) {
2040 		fscanf(filep, "%d", &this_cpu);
2041 		if (this_cpu == cpu) {
2042 			fclose(filep);
2043 			return i;
2044 		}
2045 
2046 		/* Account for no separator after last thread*/
2047 		if (i != (topo.num_threads_per_core - 1))
2048 			fscanf(filep, "%c", &character);
2049 	}
2050 
2051 	fclose(filep);
2052 	return -1;
2053 }
2054 
2055 /*
2056  * cpu_is_first_core_in_package(cpu)
2057  * return 1 if given CPU is 1st core in package
2058  */
2059 int cpu_is_first_core_in_package(int cpu)
2060 {
2061 	return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
2062 }
2063 
2064 int get_physical_package_id(int cpu)
2065 {
2066 	return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
2067 }
2068 
2069 int get_core_id(int cpu)
2070 {
2071 	return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
2072 }
2073 
2074 int get_num_ht_siblings(int cpu)
2075 {
2076 	char path[80];
2077 	FILE *filep;
2078 	int sib1;
2079 	int matches = 0;
2080 	char character;
2081 	char str[100];
2082 	char *ch;
2083 
2084 	sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
2085 	filep = fopen_or_die(path, "r");
2086 
2087 	/*
2088 	 * file format:
2089 	 * A ',' separated or '-' separated set of numbers
2090 	 * (eg 1-2 or 1,3,4,5)
2091 	 */
2092 	fscanf(filep, "%d%c\n", &sib1, &character);
2093 	fseek(filep, 0, SEEK_SET);
2094 	fgets(str, 100, filep);
2095 	ch = strchr(str, character);
2096 	while (ch != NULL) {
2097 		matches++;
2098 		ch = strchr(ch+1, character);
2099 	}
2100 
2101 	fclose(filep);
2102 	return matches+1;
2103 }
2104 
2105 /*
2106  * run func(thread, core, package) in topology order
2107  * skip non-present cpus
2108  */
2109 
2110 int for_all_cpus_2(int (func)(struct thread_data *, struct core_data *,
2111 	struct pkg_data *, struct thread_data *, struct core_data *,
2112 	struct pkg_data *), struct thread_data *thread_base,
2113 	struct core_data *core_base, struct pkg_data *pkg_base,
2114 	struct thread_data *thread_base2, struct core_data *core_base2,
2115 	struct pkg_data *pkg_base2)
2116 {
2117 	int retval, pkg_no, core_no, thread_no;
2118 
2119 	for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
2120 		for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
2121 			for (thread_no = 0; thread_no <
2122 				topo.num_threads_per_core; ++thread_no) {
2123 				struct thread_data *t, *t2;
2124 				struct core_data *c, *c2;
2125 				struct pkg_data *p, *p2;
2126 
2127 				t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
2128 
2129 				if (cpu_is_not_present(t->cpu_id))
2130 					continue;
2131 
2132 				t2 = GET_THREAD(thread_base2, thread_no, core_no, pkg_no);
2133 
2134 				c = GET_CORE(core_base, core_no, pkg_no);
2135 				c2 = GET_CORE(core_base2, core_no, pkg_no);
2136 
2137 				p = GET_PKG(pkg_base, pkg_no);
2138 				p2 = GET_PKG(pkg_base2, pkg_no);
2139 
2140 				retval = func(t, c, p, t2, c2, p2);
2141 				if (retval)
2142 					return retval;
2143 			}
2144 		}
2145 	}
2146 	return 0;
2147 }
2148 
2149 /*
2150  * run func(cpu) on every cpu in /proc/stat
2151  * return max_cpu number
2152  */
2153 int for_all_proc_cpus(int (func)(int))
2154 {
2155 	FILE *fp;
2156 	int cpu_num;
2157 	int retval;
2158 
2159 	fp = fopen_or_die(proc_stat, "r");
2160 
2161 	retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
2162 	if (retval != 0)
2163 		err(1, "%s: failed to parse format", proc_stat);
2164 
2165 	while (1) {
2166 		retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
2167 		if (retval != 1)
2168 			break;
2169 
2170 		retval = func(cpu_num);
2171 		if (retval) {
2172 			fclose(fp);
2173 			return(retval);
2174 		}
2175 	}
2176 	fclose(fp);
2177 	return 0;
2178 }
2179 
2180 void re_initialize(void)
2181 {
2182 	free_all_buffers();
2183 	setup_all_buffers();
2184 	printf("turbostat: re-initialized with num_cpus %d\n", topo.num_cpus);
2185 }
2186 
2187 
2188 /*
2189  * count_cpus()
2190  * remember the last one seen, it will be the max
2191  */
2192 int count_cpus(int cpu)
2193 {
2194 	if (topo.max_cpu_num < cpu)
2195 		topo.max_cpu_num = cpu;
2196 
2197 	topo.num_cpus += 1;
2198 	return 0;
2199 }
2200 int mark_cpu_present(int cpu)
2201 {
2202 	CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
2203 	return 0;
2204 }
2205 
2206 /*
2207  * snapshot_proc_interrupts()
2208  *
2209  * read and record summary of /proc/interrupts
2210  *
2211  * return 1 if config change requires a restart, else return 0
2212  */
2213 int snapshot_proc_interrupts(void)
2214 {
2215 	static FILE *fp;
2216 	int column, retval;
2217 
2218 	if (fp == NULL)
2219 		fp = fopen_or_die("/proc/interrupts", "r");
2220 	else
2221 		rewind(fp);
2222 
2223 	/* read 1st line of /proc/interrupts to get cpu* name for each column */
2224 	for (column = 0; column < topo.num_cpus; ++column) {
2225 		int cpu_number;
2226 
2227 		retval = fscanf(fp, " CPU%d", &cpu_number);
2228 		if (retval != 1)
2229 			break;
2230 
2231 		if (cpu_number > topo.max_cpu_num) {
2232 			warn("/proc/interrupts: cpu%d: > %d", cpu_number, topo.max_cpu_num);
2233 			return 1;
2234 		}
2235 
2236 		irq_column_2_cpu[column] = cpu_number;
2237 		irqs_per_cpu[cpu_number] = 0;
2238 	}
2239 
2240 	/* read /proc/interrupt count lines and sum up irqs per cpu */
2241 	while (1) {
2242 		int column;
2243 		char buf[64];
2244 
2245 		retval = fscanf(fp, " %s:", buf);	/* flush irq# "N:" */
2246 		if (retval != 1)
2247 			break;
2248 
2249 		/* read the count per cpu */
2250 		for (column = 0; column < topo.num_cpus; ++column) {
2251 
2252 			int cpu_number, irq_count;
2253 
2254 			retval = fscanf(fp, " %d", &irq_count);
2255 			if (retval != 1)
2256 				break;
2257 
2258 			cpu_number = irq_column_2_cpu[column];
2259 			irqs_per_cpu[cpu_number] += irq_count;
2260 
2261 		}
2262 
2263 		while (getc(fp) != '\n')
2264 			;	/* flush interrupt description */
2265 
2266 	}
2267 	return 0;
2268 }
2269 /*
2270  * snapshot_gfx_rc6_ms()
2271  *
2272  * record snapshot of
2273  * /sys/class/drm/card0/power/rc6_residency_ms
2274  *
2275  * return 1 if config change requires a restart, else return 0
2276  */
2277 int snapshot_gfx_rc6_ms(void)
2278 {
2279 	FILE *fp;
2280 	int retval;
2281 
2282 	fp = fopen_or_die("/sys/class/drm/card0/power/rc6_residency_ms", "r");
2283 
2284 	retval = fscanf(fp, "%lld", &gfx_cur_rc6_ms);
2285 	if (retval != 1)
2286 		err(1, "GFX rc6");
2287 
2288 	fclose(fp);
2289 
2290 	return 0;
2291 }
2292 /*
2293  * snapshot_gfx_mhz()
2294  *
2295  * record snapshot of
2296  * /sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz
2297  *
2298  * return 1 if config change requires a restart, else return 0
2299  */
2300 int snapshot_gfx_mhz(void)
2301 {
2302 	static FILE *fp;
2303 	int retval;
2304 
2305 	if (fp == NULL)
2306 		fp = fopen_or_die("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", "r");
2307 	else
2308 		rewind(fp);
2309 
2310 	retval = fscanf(fp, "%d", &gfx_cur_mhz);
2311 	if (retval != 1)
2312 		err(1, "GFX MHz");
2313 
2314 	return 0;
2315 }
2316 
2317 /*
2318  * snapshot /proc and /sys files
2319  *
2320  * return 1 if configuration restart needed, else return 0
2321  */
2322 int snapshot_proc_sysfs_files(void)
2323 {
2324 	if (snapshot_proc_interrupts())
2325 		return 1;
2326 
2327 	if (DO_BIC(BIC_GFX_rc6))
2328 		snapshot_gfx_rc6_ms();
2329 
2330 	if (DO_BIC(BIC_GFXMHz))
2331 		snapshot_gfx_mhz();
2332 
2333 	return 0;
2334 }
2335 
2336 void turbostat_loop()
2337 {
2338 	int retval;
2339 	int restarted = 0;
2340 
2341 restart:
2342 	restarted++;
2343 
2344 	snapshot_proc_sysfs_files();
2345 	retval = for_all_cpus(get_counters, EVEN_COUNTERS);
2346 	if (retval < -1) {
2347 		exit(retval);
2348 	} else if (retval == -1) {
2349 		if (restarted > 1) {
2350 			exit(retval);
2351 		}
2352 		re_initialize();
2353 		goto restart;
2354 	}
2355 	restarted = 0;
2356 	gettimeofday(&tv_even, (struct timezone *)NULL);
2357 
2358 	while (1) {
2359 		if (for_all_proc_cpus(cpu_is_not_present)) {
2360 			re_initialize();
2361 			goto restart;
2362 		}
2363 		nanosleep(&interval_ts, NULL);
2364 		if (snapshot_proc_sysfs_files())
2365 			goto restart;
2366 		retval = for_all_cpus(get_counters, ODD_COUNTERS);
2367 		if (retval < -1) {
2368 			exit(retval);
2369 		} else if (retval == -1) {
2370 			re_initialize();
2371 			goto restart;
2372 		}
2373 		gettimeofday(&tv_odd, (struct timezone *)NULL);
2374 		timersub(&tv_odd, &tv_even, &tv_delta);
2375 		if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS)) {
2376 			re_initialize();
2377 			goto restart;
2378 		}
2379 		compute_average(EVEN_COUNTERS);
2380 		format_all_counters(EVEN_COUNTERS);
2381 		flush_output_stdout();
2382 		nanosleep(&interval_ts, NULL);
2383 		if (snapshot_proc_sysfs_files())
2384 			goto restart;
2385 		retval = for_all_cpus(get_counters, EVEN_COUNTERS);
2386 		if (retval < -1) {
2387 			exit(retval);
2388 		} else if (retval == -1) {
2389 			re_initialize();
2390 			goto restart;
2391 		}
2392 		gettimeofday(&tv_even, (struct timezone *)NULL);
2393 		timersub(&tv_even, &tv_odd, &tv_delta);
2394 		if (for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS)) {
2395 			re_initialize();
2396 			goto restart;
2397 		}
2398 		compute_average(ODD_COUNTERS);
2399 		format_all_counters(ODD_COUNTERS);
2400 		flush_output_stdout();
2401 	}
2402 }
2403 
2404 void check_dev_msr()
2405 {
2406 	struct stat sb;
2407 	char pathname[32];
2408 
2409 	sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
2410 	if (stat(pathname, &sb))
2411  		if (system("/sbin/modprobe msr > /dev/null 2>&1"))
2412 			err(-5, "no /dev/cpu/0/msr, Try \"# modprobe msr\" ");
2413 }
2414 
2415 void check_permissions()
2416 {
2417 	struct __user_cap_header_struct cap_header_data;
2418 	cap_user_header_t cap_header = &cap_header_data;
2419 	struct __user_cap_data_struct cap_data_data;
2420 	cap_user_data_t cap_data = &cap_data_data;
2421 	extern int capget(cap_user_header_t hdrp, cap_user_data_t datap);
2422 	int do_exit = 0;
2423 	char pathname[32];
2424 
2425 	/* check for CAP_SYS_RAWIO */
2426 	cap_header->pid = getpid();
2427 	cap_header->version = _LINUX_CAPABILITY_VERSION;
2428 	if (capget(cap_header, cap_data) < 0)
2429 		err(-6, "capget(2) failed");
2430 
2431 	if ((cap_data->effective & (1 << CAP_SYS_RAWIO)) == 0) {
2432 		do_exit++;
2433 		warnx("capget(CAP_SYS_RAWIO) failed,"
2434 			" try \"# setcap cap_sys_rawio=ep %s\"", progname);
2435 	}
2436 
2437 	/* test file permissions */
2438 	sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
2439 	if (euidaccess(pathname, R_OK)) {
2440 		do_exit++;
2441 		warn("/dev/cpu/0/msr open failed, try chown or chmod +r /dev/cpu/*/msr");
2442 	}
2443 
2444 	/* if all else fails, thell them to be root */
2445 	if (do_exit)
2446 		if (getuid() != 0)
2447 			warnx("... or simply run as root");
2448 
2449 	if (do_exit)
2450 		exit(-6);
2451 }
2452 
2453 /*
2454  * NHM adds support for additional MSRs:
2455  *
2456  * MSR_SMI_COUNT                   0x00000034
2457  *
2458  * MSR_PLATFORM_INFO               0x000000ce
2459  * MSR_PKG_CST_CONFIG_CONTROL     0x000000e2
2460  *
2461  * MSR_MISC_PWR_MGMT               0x000001aa
2462  *
2463  * MSR_PKG_C3_RESIDENCY            0x000003f8
2464  * MSR_PKG_C6_RESIDENCY            0x000003f9
2465  * MSR_CORE_C3_RESIDENCY           0x000003fc
2466  * MSR_CORE_C6_RESIDENCY           0x000003fd
2467  *
2468  * Side effect:
2469  * sets global pkg_cstate_limit to decode MSR_PKG_CST_CONFIG_CONTROL
2470  * sets has_misc_feature_control
2471  */
2472 int probe_nhm_msrs(unsigned int family, unsigned int model)
2473 {
2474 	unsigned long long msr;
2475 	unsigned int base_ratio;
2476 	int *pkg_cstate_limits;
2477 
2478 	if (!genuine_intel)
2479 		return 0;
2480 
2481 	if (family != 6)
2482 		return 0;
2483 
2484 	bclk = discover_bclk(family, model);
2485 
2486 	switch (model) {
2487 	case INTEL_FAM6_NEHALEM_EP:	/* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
2488 	case INTEL_FAM6_NEHALEM:	/* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
2489 	case 0x1F:	/* Core i7 and i5 Processor - Nehalem */
2490 	case INTEL_FAM6_WESTMERE:	/* Westmere Client - Clarkdale, Arrandale */
2491 	case INTEL_FAM6_WESTMERE_EP:	/* Westmere EP - Gulftown */
2492 	case INTEL_FAM6_NEHALEM_EX:	/* Nehalem-EX Xeon - Beckton */
2493 	case INTEL_FAM6_WESTMERE_EX:	/* Westmere-EX Xeon - Eagleton */
2494 		pkg_cstate_limits = nhm_pkg_cstate_limits;
2495 		break;
2496 	case INTEL_FAM6_SANDYBRIDGE:	/* SNB */
2497 	case INTEL_FAM6_SANDYBRIDGE_X:	/* SNB Xeon */
2498 	case INTEL_FAM6_IVYBRIDGE:	/* IVB */
2499 	case INTEL_FAM6_IVYBRIDGE_X:	/* IVB Xeon */
2500 		pkg_cstate_limits = snb_pkg_cstate_limits;
2501 		has_misc_feature_control = 1;
2502 		break;
2503 	case INTEL_FAM6_HASWELL_CORE:	/* HSW */
2504 	case INTEL_FAM6_HASWELL_X:	/* HSX */
2505 	case INTEL_FAM6_HASWELL_ULT:	/* HSW */
2506 	case INTEL_FAM6_HASWELL_GT3E:	/* HSW */
2507 	case INTEL_FAM6_BROADWELL_CORE:	/* BDW */
2508 	case INTEL_FAM6_BROADWELL_GT3E:	/* BDW */
2509 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
2510 	case INTEL_FAM6_BROADWELL_XEON_D:	/* BDX-DE */
2511 	case INTEL_FAM6_SKYLAKE_MOBILE:	/* SKL */
2512 	case INTEL_FAM6_SKYLAKE_DESKTOP:	/* SKL */
2513 	case INTEL_FAM6_KABYLAKE_MOBILE:	/* KBL */
2514 	case INTEL_FAM6_KABYLAKE_DESKTOP:	/* KBL */
2515 		pkg_cstate_limits = hsw_pkg_cstate_limits;
2516 		has_misc_feature_control = 1;
2517 		break;
2518 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
2519 		pkg_cstate_limits = skx_pkg_cstate_limits;
2520 		has_misc_feature_control = 1;
2521 		break;
2522 	case INTEL_FAM6_ATOM_SILVERMONT1:	/* BYT */
2523 		no_MSR_MISC_PWR_MGMT = 1;
2524 	case INTEL_FAM6_ATOM_SILVERMONT2:	/* AVN */
2525 		pkg_cstate_limits = slv_pkg_cstate_limits;
2526 		break;
2527 	case INTEL_FAM6_ATOM_AIRMONT:	/* AMT */
2528 		pkg_cstate_limits = amt_pkg_cstate_limits;
2529 		no_MSR_MISC_PWR_MGMT = 1;
2530 		break;
2531 	case INTEL_FAM6_XEON_PHI_KNL:	/* PHI */
2532 	case INTEL_FAM6_XEON_PHI_KNM:
2533 		pkg_cstate_limits = phi_pkg_cstate_limits;
2534 		break;
2535 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
2536 	case INTEL_FAM6_ATOM_DENVERTON:	/* DNV */
2537 		pkg_cstate_limits = bxt_pkg_cstate_limits;
2538 		break;
2539 	default:
2540 		return 0;
2541 	}
2542 	get_msr(base_cpu, MSR_PKG_CST_CONFIG_CONTROL, &msr);
2543 	pkg_cstate_limit = pkg_cstate_limits[msr & 0xF];
2544 
2545 	get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
2546 	base_ratio = (msr >> 8) & 0xFF;
2547 
2548 	base_hz = base_ratio * bclk * 1000000;
2549 	has_base_hz = 1;
2550 	return 1;
2551 }
2552 /*
2553  * SLV client has supporet for unique MSRs:
2554  *
2555  * MSR_CC6_DEMOTION_POLICY_CONFIG
2556  * MSR_MC6_DEMOTION_POLICY_CONFIG
2557  */
2558 
2559 int has_slv_msrs(unsigned int family, unsigned int model)
2560 {
2561 	if (!genuine_intel)
2562 		return 0;
2563 
2564 	switch (model) {
2565 	case INTEL_FAM6_ATOM_SILVERMONT1:
2566 	case INTEL_FAM6_ATOM_MERRIFIELD:
2567 	case INTEL_FAM6_ATOM_MOOREFIELD:
2568 		return 1;
2569 	}
2570 	return 0;
2571 }
2572 
2573 int has_nhm_turbo_ratio_limit(unsigned int family, unsigned int model)
2574 {
2575 	if (has_slv_msrs(family, model))
2576 		return 0;
2577 
2578 	switch (model) {
2579 	/* Nehalem compatible, but do not include turbo-ratio limit support */
2580 	case INTEL_FAM6_NEHALEM_EX:	/* Nehalem-EX Xeon - Beckton */
2581 	case INTEL_FAM6_WESTMERE_EX:	/* Westmere-EX Xeon - Eagleton */
2582 	case INTEL_FAM6_XEON_PHI_KNL:	/* PHI - Knights Landing (different MSR definition) */
2583 	case INTEL_FAM6_XEON_PHI_KNM:
2584 		return 0;
2585 	default:
2586 		return 1;
2587 	}
2588 }
2589 int has_atom_turbo_ratio_limit(unsigned int family, unsigned int model)
2590 {
2591 	if (has_slv_msrs(family, model))
2592 		return 1;
2593 
2594 	return 0;
2595 }
2596 int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
2597 {
2598 	if (!genuine_intel)
2599 		return 0;
2600 
2601 	if (family != 6)
2602 		return 0;
2603 
2604 	switch (model) {
2605 	case INTEL_FAM6_IVYBRIDGE_X:	/* IVB Xeon */
2606 	case INTEL_FAM6_HASWELL_X:	/* HSW Xeon */
2607 		return 1;
2608 	default:
2609 		return 0;
2610 	}
2611 }
2612 int has_hsw_turbo_ratio_limit(unsigned int family, unsigned int model)
2613 {
2614 	if (!genuine_intel)
2615 		return 0;
2616 
2617 	if (family != 6)
2618 		return 0;
2619 
2620 	switch (model) {
2621 	case INTEL_FAM6_HASWELL_X:	/* HSW Xeon */
2622 		return 1;
2623 	default:
2624 		return 0;
2625 	}
2626 }
2627 
2628 int has_knl_turbo_ratio_limit(unsigned int family, unsigned int model)
2629 {
2630 	if (!genuine_intel)
2631 		return 0;
2632 
2633 	if (family != 6)
2634 		return 0;
2635 
2636 	switch (model) {
2637 	case INTEL_FAM6_XEON_PHI_KNL:	/* Knights Landing */
2638 	case INTEL_FAM6_XEON_PHI_KNM:
2639 		return 1;
2640 	default:
2641 		return 0;
2642 	}
2643 }
2644 int has_config_tdp(unsigned int family, unsigned int model)
2645 {
2646 	if (!genuine_intel)
2647 		return 0;
2648 
2649 	if (family != 6)
2650 		return 0;
2651 
2652 	switch (model) {
2653 	case INTEL_FAM6_IVYBRIDGE:	/* IVB */
2654 	case INTEL_FAM6_HASWELL_CORE:	/* HSW */
2655 	case INTEL_FAM6_HASWELL_X:	/* HSX */
2656 	case INTEL_FAM6_HASWELL_ULT:	/* HSW */
2657 	case INTEL_FAM6_HASWELL_GT3E:	/* HSW */
2658 	case INTEL_FAM6_BROADWELL_CORE:	/* BDW */
2659 	case INTEL_FAM6_BROADWELL_GT3E:	/* BDW */
2660 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
2661 	case INTEL_FAM6_BROADWELL_XEON_D:	/* BDX-DE */
2662 	case INTEL_FAM6_SKYLAKE_MOBILE:	/* SKL */
2663 	case INTEL_FAM6_SKYLAKE_DESKTOP:	/* SKL */
2664 	case INTEL_FAM6_KABYLAKE_MOBILE:	/* KBL */
2665 	case INTEL_FAM6_KABYLAKE_DESKTOP:	/* KBL */
2666 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
2667 
2668 	case INTEL_FAM6_XEON_PHI_KNL:	/* Knights Landing */
2669 	case INTEL_FAM6_XEON_PHI_KNM:
2670 		return 1;
2671 	default:
2672 		return 0;
2673 	}
2674 }
2675 
2676 static void
2677 dump_cstate_pstate_config_info(unsigned int family, unsigned int model)
2678 {
2679 	if (!do_nhm_platform_info)
2680 		return;
2681 
2682 	dump_nhm_platform_info();
2683 
2684 	if (has_hsw_turbo_ratio_limit(family, model))
2685 		dump_hsw_turbo_ratio_limits();
2686 
2687 	if (has_ivt_turbo_ratio_limit(family, model))
2688 		dump_ivt_turbo_ratio_limits();
2689 
2690 	if (has_nhm_turbo_ratio_limit(family, model))
2691 		dump_nhm_turbo_ratio_limits();
2692 
2693 	if (has_atom_turbo_ratio_limit(family, model))
2694 		dump_atom_turbo_ratio_limits();
2695 
2696 	if (has_knl_turbo_ratio_limit(family, model))
2697 		dump_knl_turbo_ratio_limits();
2698 
2699 	if (has_config_tdp(family, model))
2700 		dump_config_tdp();
2701 
2702 	dump_nhm_cst_cfg();
2703 }
2704 
2705 
2706 /*
2707  * print_epb()
2708  * Decode the ENERGY_PERF_BIAS MSR
2709  */
2710 int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2711 {
2712 	unsigned long long msr;
2713 	char *epb_string;
2714 	int cpu;
2715 
2716 	if (!has_epb)
2717 		return 0;
2718 
2719 	cpu = t->cpu_id;
2720 
2721 	/* EPB is per-package */
2722 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2723 		return 0;
2724 
2725 	if (cpu_migrate(cpu)) {
2726 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
2727 		return -1;
2728 	}
2729 
2730 	if (get_msr(cpu, MSR_IA32_ENERGY_PERF_BIAS, &msr))
2731 		return 0;
2732 
2733 	switch (msr & 0xF) {
2734 	case ENERGY_PERF_BIAS_PERFORMANCE:
2735 		epb_string = "performance";
2736 		break;
2737 	case ENERGY_PERF_BIAS_NORMAL:
2738 		epb_string = "balanced";
2739 		break;
2740 	case ENERGY_PERF_BIAS_POWERSAVE:
2741 		epb_string = "powersave";
2742 		break;
2743 	default:
2744 		epb_string = "custom";
2745 		break;
2746 	}
2747 	fprintf(outf, "cpu%d: MSR_IA32_ENERGY_PERF_BIAS: 0x%08llx (%s)\n", cpu, msr, epb_string);
2748 
2749 	return 0;
2750 }
2751 /*
2752  * print_hwp()
2753  * Decode the MSR_HWP_CAPABILITIES
2754  */
2755 int print_hwp(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2756 {
2757 	unsigned long long msr;
2758 	int cpu;
2759 
2760 	if (!has_hwp)
2761 		return 0;
2762 
2763 	cpu = t->cpu_id;
2764 
2765 	/* MSR_HWP_CAPABILITIES is per-package */
2766 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2767 		return 0;
2768 
2769 	if (cpu_migrate(cpu)) {
2770 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
2771 		return -1;
2772 	}
2773 
2774 	if (get_msr(cpu, MSR_PM_ENABLE, &msr))
2775 		return 0;
2776 
2777 	fprintf(outf, "cpu%d: MSR_PM_ENABLE: 0x%08llx (%sHWP)\n",
2778 		cpu, msr, (msr & (1 << 0)) ? "" : "No-");
2779 
2780 	/* MSR_PM_ENABLE[1] == 1 if HWP is enabled and MSRs visible */
2781 	if ((msr & (1 << 0)) == 0)
2782 		return 0;
2783 
2784 	if (get_msr(cpu, MSR_HWP_CAPABILITIES, &msr))
2785 		return 0;
2786 
2787 	fprintf(outf, "cpu%d: MSR_HWP_CAPABILITIES: 0x%08llx "
2788 			"(high 0x%x guar 0x%x eff 0x%x low 0x%x)\n",
2789 			cpu, msr,
2790 			(unsigned int)HWP_HIGHEST_PERF(msr),
2791 			(unsigned int)HWP_GUARANTEED_PERF(msr),
2792 			(unsigned int)HWP_MOSTEFFICIENT_PERF(msr),
2793 			(unsigned int)HWP_LOWEST_PERF(msr));
2794 
2795 	if (get_msr(cpu, MSR_HWP_REQUEST, &msr))
2796 		return 0;
2797 
2798 	fprintf(outf, "cpu%d: MSR_HWP_REQUEST: 0x%08llx "
2799 			"(min 0x%x max 0x%x des 0x%x epp 0x%x window 0x%x pkg 0x%x)\n",
2800 			cpu, msr,
2801 			(unsigned int)(((msr) >> 0) & 0xff),
2802 			(unsigned int)(((msr) >> 8) & 0xff),
2803 			(unsigned int)(((msr) >> 16) & 0xff),
2804 			(unsigned int)(((msr) >> 24) & 0xff),
2805 			(unsigned int)(((msr) >> 32) & 0xff3),
2806 			(unsigned int)(((msr) >> 42) & 0x1));
2807 
2808 	if (has_hwp_pkg) {
2809 		if (get_msr(cpu, MSR_HWP_REQUEST_PKG, &msr))
2810 			return 0;
2811 
2812 		fprintf(outf, "cpu%d: MSR_HWP_REQUEST_PKG: 0x%08llx "
2813 			"(min 0x%x max 0x%x des 0x%x epp 0x%x window 0x%x)\n",
2814 			cpu, msr,
2815 			(unsigned int)(((msr) >> 0) & 0xff),
2816 			(unsigned int)(((msr) >> 8) & 0xff),
2817 			(unsigned int)(((msr) >> 16) & 0xff),
2818 			(unsigned int)(((msr) >> 24) & 0xff),
2819 			(unsigned int)(((msr) >> 32) & 0xff3));
2820 	}
2821 	if (has_hwp_notify) {
2822 		if (get_msr(cpu, MSR_HWP_INTERRUPT, &msr))
2823 			return 0;
2824 
2825 		fprintf(outf, "cpu%d: MSR_HWP_INTERRUPT: 0x%08llx "
2826 			"(%s_Guaranteed_Perf_Change, %s_Excursion_Min)\n",
2827 			cpu, msr,
2828 			((msr) & 0x1) ? "EN" : "Dis",
2829 			((msr) & 0x2) ? "EN" : "Dis");
2830 	}
2831 	if (get_msr(cpu, MSR_HWP_STATUS, &msr))
2832 		return 0;
2833 
2834 	fprintf(outf, "cpu%d: MSR_HWP_STATUS: 0x%08llx "
2835 			"(%sGuaranteed_Perf_Change, %sExcursion_Min)\n",
2836 			cpu, msr,
2837 			((msr) & 0x1) ? "" : "No-",
2838 			((msr) & 0x2) ? "" : "No-");
2839 
2840 	return 0;
2841 }
2842 
2843 /*
2844  * print_perf_limit()
2845  */
2846 int print_perf_limit(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2847 {
2848 	unsigned long long msr;
2849 	int cpu;
2850 
2851 	cpu = t->cpu_id;
2852 
2853 	/* per-package */
2854 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2855 		return 0;
2856 
2857 	if (cpu_migrate(cpu)) {
2858 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
2859 		return -1;
2860 	}
2861 
2862 	if (do_core_perf_limit_reasons) {
2863 		get_msr(cpu, MSR_CORE_PERF_LIMIT_REASONS, &msr);
2864 		fprintf(outf, "cpu%d: MSR_CORE_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
2865 		fprintf(outf, " (Active: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
2866 			(msr & 1 << 15) ? "bit15, " : "",
2867 			(msr & 1 << 14) ? "bit14, " : "",
2868 			(msr & 1 << 13) ? "Transitions, " : "",
2869 			(msr & 1 << 12) ? "MultiCoreTurbo, " : "",
2870 			(msr & 1 << 11) ? "PkgPwrL2, " : "",
2871 			(msr & 1 << 10) ? "PkgPwrL1, " : "",
2872 			(msr & 1 << 9) ? "CorePwr, " : "",
2873 			(msr & 1 << 8) ? "Amps, " : "",
2874 			(msr & 1 << 6) ? "VR-Therm, " : "",
2875 			(msr & 1 << 5) ? "Auto-HWP, " : "",
2876 			(msr & 1 << 4) ? "Graphics, " : "",
2877 			(msr & 1 << 2) ? "bit2, " : "",
2878 			(msr & 1 << 1) ? "ThermStatus, " : "",
2879 			(msr & 1 << 0) ? "PROCHOT, " : "");
2880 		fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
2881 			(msr & 1 << 31) ? "bit31, " : "",
2882 			(msr & 1 << 30) ? "bit30, " : "",
2883 			(msr & 1 << 29) ? "Transitions, " : "",
2884 			(msr & 1 << 28) ? "MultiCoreTurbo, " : "",
2885 			(msr & 1 << 27) ? "PkgPwrL2, " : "",
2886 			(msr & 1 << 26) ? "PkgPwrL1, " : "",
2887 			(msr & 1 << 25) ? "CorePwr, " : "",
2888 			(msr & 1 << 24) ? "Amps, " : "",
2889 			(msr & 1 << 22) ? "VR-Therm, " : "",
2890 			(msr & 1 << 21) ? "Auto-HWP, " : "",
2891 			(msr & 1 << 20) ? "Graphics, " : "",
2892 			(msr & 1 << 18) ? "bit18, " : "",
2893 			(msr & 1 << 17) ? "ThermStatus, " : "",
2894 			(msr & 1 << 16) ? "PROCHOT, " : "");
2895 
2896 	}
2897 	if (do_gfx_perf_limit_reasons) {
2898 		get_msr(cpu, MSR_GFX_PERF_LIMIT_REASONS, &msr);
2899 		fprintf(outf, "cpu%d: MSR_GFX_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
2900 		fprintf(outf, " (Active: %s%s%s%s%s%s%s%s)",
2901 			(msr & 1 << 0) ? "PROCHOT, " : "",
2902 			(msr & 1 << 1) ? "ThermStatus, " : "",
2903 			(msr & 1 << 4) ? "Graphics, " : "",
2904 			(msr & 1 << 6) ? "VR-Therm, " : "",
2905 			(msr & 1 << 8) ? "Amps, " : "",
2906 			(msr & 1 << 9) ? "GFXPwr, " : "",
2907 			(msr & 1 << 10) ? "PkgPwrL1, " : "",
2908 			(msr & 1 << 11) ? "PkgPwrL2, " : "");
2909 		fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s)\n",
2910 			(msr & 1 << 16) ? "PROCHOT, " : "",
2911 			(msr & 1 << 17) ? "ThermStatus, " : "",
2912 			(msr & 1 << 20) ? "Graphics, " : "",
2913 			(msr & 1 << 22) ? "VR-Therm, " : "",
2914 			(msr & 1 << 24) ? "Amps, " : "",
2915 			(msr & 1 << 25) ? "GFXPwr, " : "",
2916 			(msr & 1 << 26) ? "PkgPwrL1, " : "",
2917 			(msr & 1 << 27) ? "PkgPwrL2, " : "");
2918 	}
2919 	if (do_ring_perf_limit_reasons) {
2920 		get_msr(cpu, MSR_RING_PERF_LIMIT_REASONS, &msr);
2921 		fprintf(outf, "cpu%d: MSR_RING_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
2922 		fprintf(outf, " (Active: %s%s%s%s%s%s)",
2923 			(msr & 1 << 0) ? "PROCHOT, " : "",
2924 			(msr & 1 << 1) ? "ThermStatus, " : "",
2925 			(msr & 1 << 6) ? "VR-Therm, " : "",
2926 			(msr & 1 << 8) ? "Amps, " : "",
2927 			(msr & 1 << 10) ? "PkgPwrL1, " : "",
2928 			(msr & 1 << 11) ? "PkgPwrL2, " : "");
2929 		fprintf(outf, " (Logged: %s%s%s%s%s%s)\n",
2930 			(msr & 1 << 16) ? "PROCHOT, " : "",
2931 			(msr & 1 << 17) ? "ThermStatus, " : "",
2932 			(msr & 1 << 22) ? "VR-Therm, " : "",
2933 			(msr & 1 << 24) ? "Amps, " : "",
2934 			(msr & 1 << 26) ? "PkgPwrL1, " : "",
2935 			(msr & 1 << 27) ? "PkgPwrL2, " : "");
2936 	}
2937 	return 0;
2938 }
2939 
2940 #define	RAPL_POWER_GRANULARITY	0x7FFF	/* 15 bit power granularity */
2941 #define	RAPL_TIME_GRANULARITY	0x3F /* 6 bit time granularity */
2942 
2943 double get_tdp(unsigned int model)
2944 {
2945 	unsigned long long msr;
2946 
2947 	if (do_rapl & RAPL_PKG_POWER_INFO)
2948 		if (!get_msr(base_cpu, MSR_PKG_POWER_INFO, &msr))
2949 			return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
2950 
2951 	switch (model) {
2952 	case INTEL_FAM6_ATOM_SILVERMONT1:
2953 	case INTEL_FAM6_ATOM_SILVERMONT2:
2954 		return 30.0;
2955 	default:
2956 		return 135.0;
2957 	}
2958 }
2959 
2960 /*
2961  * rapl_dram_energy_units_probe()
2962  * Energy units are either hard-coded, or come from RAPL Energy Unit MSR.
2963  */
2964 static double
2965 rapl_dram_energy_units_probe(int  model, double rapl_energy_units)
2966 {
2967 	/* only called for genuine_intel, family 6 */
2968 
2969 	switch (model) {
2970 	case INTEL_FAM6_HASWELL_X:	/* HSX */
2971 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
2972 	case INTEL_FAM6_BROADWELL_XEON_D:	/* BDX-DE */
2973 	case INTEL_FAM6_XEON_PHI_KNL:	/* KNL */
2974 	case INTEL_FAM6_XEON_PHI_KNM:
2975 		return (rapl_dram_energy_units = 15.3 / 1000000);
2976 	default:
2977 		return (rapl_energy_units);
2978 	}
2979 }
2980 
2981 
2982 /*
2983  * rapl_probe()
2984  *
2985  * sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
2986  */
2987 void rapl_probe(unsigned int family, unsigned int model)
2988 {
2989 	unsigned long long msr;
2990 	unsigned int time_unit;
2991 	double tdp;
2992 
2993 	if (!genuine_intel)
2994 		return;
2995 
2996 	if (family != 6)
2997 		return;
2998 
2999 	switch (model) {
3000 	case INTEL_FAM6_SANDYBRIDGE:
3001 	case INTEL_FAM6_IVYBRIDGE:
3002 	case INTEL_FAM6_HASWELL_CORE:	/* HSW */
3003 	case INTEL_FAM6_HASWELL_ULT:	/* HSW */
3004 	case INTEL_FAM6_HASWELL_GT3E:	/* HSW */
3005 	case INTEL_FAM6_BROADWELL_CORE:	/* BDW */
3006 	case INTEL_FAM6_BROADWELL_GT3E:	/* BDW */
3007 		do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
3008 		if (rapl_joules) {
3009 			BIC_PRESENT(BIC_Pkg_J);
3010 			BIC_PRESENT(BIC_Cor_J);
3011 			BIC_PRESENT(BIC_GFX_J);
3012 		} else {
3013 			BIC_PRESENT(BIC_PkgWatt);
3014 			BIC_PRESENT(BIC_CorWatt);
3015 			BIC_PRESENT(BIC_GFXWatt);
3016 		}
3017 		break;
3018 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
3019 		do_rapl = RAPL_PKG | RAPL_PKG_POWER_INFO;
3020 		if (rapl_joules)
3021 			BIC_PRESENT(BIC_Pkg_J);
3022 		else
3023 			BIC_PRESENT(BIC_PkgWatt);
3024 		break;
3025 	case INTEL_FAM6_SKYLAKE_MOBILE:	/* SKL */
3026 	case INTEL_FAM6_SKYLAKE_DESKTOP:	/* SKL */
3027 	case INTEL_FAM6_KABYLAKE_MOBILE:	/* KBL */
3028 	case INTEL_FAM6_KABYLAKE_DESKTOP:	/* KBL */
3029 		do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
3030 		BIC_PRESENT(BIC_PKG__);
3031 		BIC_PRESENT(BIC_RAM__);
3032 		if (rapl_joules) {
3033 			BIC_PRESENT(BIC_Pkg_J);
3034 			BIC_PRESENT(BIC_Cor_J);
3035 			BIC_PRESENT(BIC_RAM_J);
3036 		} else {
3037 			BIC_PRESENT(BIC_PkgWatt);
3038 			BIC_PRESENT(BIC_CorWatt);
3039 			BIC_PRESENT(BIC_RAMWatt);
3040 		}
3041 		break;
3042 	case INTEL_FAM6_HASWELL_X:	/* HSX */
3043 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
3044 	case INTEL_FAM6_BROADWELL_XEON_D:	/* BDX-DE */
3045 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
3046 	case INTEL_FAM6_XEON_PHI_KNL:	/* KNL */
3047 	case INTEL_FAM6_XEON_PHI_KNM:
3048 		do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
3049 		BIC_PRESENT(BIC_PKG__);
3050 		BIC_PRESENT(BIC_RAM__);
3051 		if (rapl_joules) {
3052 			BIC_PRESENT(BIC_Pkg_J);
3053 			BIC_PRESENT(BIC_RAM_J);
3054 		} else {
3055 			BIC_PRESENT(BIC_PkgWatt);
3056 			BIC_PRESENT(BIC_RAMWatt);
3057 		}
3058 		break;
3059 	case INTEL_FAM6_SANDYBRIDGE_X:
3060 	case INTEL_FAM6_IVYBRIDGE_X:
3061 		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;
3062 		BIC_PRESENT(BIC_PKG__);
3063 		BIC_PRESENT(BIC_RAM__);
3064 		if (rapl_joules) {
3065 			BIC_PRESENT(BIC_Pkg_J);
3066 			BIC_PRESENT(BIC_Cor_J);
3067 			BIC_PRESENT(BIC_RAM_J);
3068 		} else {
3069 			BIC_PRESENT(BIC_PkgWatt);
3070 			BIC_PRESENT(BIC_CorWatt);
3071 			BIC_PRESENT(BIC_RAMWatt);
3072 		}
3073 		break;
3074 	case INTEL_FAM6_ATOM_SILVERMONT1:	/* BYT */
3075 	case INTEL_FAM6_ATOM_SILVERMONT2:	/* AVN */
3076 		do_rapl = RAPL_PKG | RAPL_CORES;
3077 		if (rapl_joules) {
3078 			BIC_PRESENT(BIC_Pkg_J);
3079 			BIC_PRESENT(BIC_Cor_J);
3080 		} else {
3081 			BIC_PRESENT(BIC_PkgWatt);
3082 			BIC_PRESENT(BIC_CorWatt);
3083 		}
3084 		break;
3085 	case INTEL_FAM6_ATOM_DENVERTON:	/* DNV */
3086 		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;
3087 		BIC_PRESENT(BIC_PKG__);
3088 		BIC_PRESENT(BIC_RAM__);
3089 		if (rapl_joules) {
3090 			BIC_PRESENT(BIC_Pkg_J);
3091 			BIC_PRESENT(BIC_Cor_J);
3092 			BIC_PRESENT(BIC_RAM_J);
3093 		} else {
3094 			BIC_PRESENT(BIC_PkgWatt);
3095 			BIC_PRESENT(BIC_CorWatt);
3096 			BIC_PRESENT(BIC_RAMWatt);
3097 		}
3098 		break;
3099 	default:
3100 		return;
3101 	}
3102 
3103 	/* units on package 0, verify later other packages match */
3104 	if (get_msr(base_cpu, MSR_RAPL_POWER_UNIT, &msr))
3105 		return;
3106 
3107 	rapl_power_units = 1.0 / (1 << (msr & 0xF));
3108 	if (model == INTEL_FAM6_ATOM_SILVERMONT1)
3109 		rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
3110 	else
3111 		rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
3112 
3113 	rapl_dram_energy_units = rapl_dram_energy_units_probe(model, rapl_energy_units);
3114 
3115 	time_unit = msr >> 16 & 0xF;
3116 	if (time_unit == 0)
3117 		time_unit = 0xA;
3118 
3119 	rapl_time_units = 1.0 / (1 << (time_unit));
3120 
3121 	tdp = get_tdp(model);
3122 
3123 	rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
3124 	if (debug)
3125 		fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
3126 
3127 	return;
3128 }
3129 
3130 void perf_limit_reasons_probe(unsigned int family, unsigned int model)
3131 {
3132 	if (!genuine_intel)
3133 		return;
3134 
3135 	if (family != 6)
3136 		return;
3137 
3138 	switch (model) {
3139 	case INTEL_FAM6_HASWELL_CORE:	/* HSW */
3140 	case INTEL_FAM6_HASWELL_ULT:	/* HSW */
3141 	case INTEL_FAM6_HASWELL_GT3E:	/* HSW */
3142 		do_gfx_perf_limit_reasons = 1;
3143 	case INTEL_FAM6_HASWELL_X:	/* HSX */
3144 		do_core_perf_limit_reasons = 1;
3145 		do_ring_perf_limit_reasons = 1;
3146 	default:
3147 		return;
3148 	}
3149 }
3150 
3151 int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3152 {
3153 	unsigned long long msr;
3154 	unsigned int dts;
3155 	int cpu;
3156 
3157 	if (!(do_dts || do_ptm))
3158 		return 0;
3159 
3160 	cpu = t->cpu_id;
3161 
3162 	/* DTS is per-core, no need to print for each thread */
3163 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
3164 		return 0;
3165 
3166 	if (cpu_migrate(cpu)) {
3167 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3168 		return -1;
3169 	}
3170 
3171 	if (do_ptm && (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
3172 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
3173 			return 0;
3174 
3175 		dts = (msr >> 16) & 0x7F;
3176 		fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n",
3177 			cpu, msr, tcc_activation_temp - dts);
3178 
3179 #ifdef	THERM_DEBUG
3180 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
3181 			return 0;
3182 
3183 		dts = (msr >> 16) & 0x7F;
3184 		dts2 = (msr >> 8) & 0x7F;
3185 		fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
3186 			cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
3187 #endif
3188 	}
3189 
3190 
3191 	if (do_dts) {
3192 		unsigned int resolution;
3193 
3194 		if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
3195 			return 0;
3196 
3197 		dts = (msr >> 16) & 0x7F;
3198 		resolution = (msr >> 27) & 0xF;
3199 		fprintf(outf, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
3200 			cpu, msr, tcc_activation_temp - dts, resolution);
3201 
3202 #ifdef THERM_DEBUG
3203 		if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
3204 			return 0;
3205 
3206 		dts = (msr >> 16) & 0x7F;
3207 		dts2 = (msr >> 8) & 0x7F;
3208 		fprintf(outf, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
3209 			cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
3210 #endif
3211 	}
3212 
3213 	return 0;
3214 }
3215 
3216 void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
3217 {
3218 	fprintf(outf, "cpu%d: %s: %sabled (%f Watts, %f sec, clamp %sabled)\n",
3219 		cpu, label,
3220 		((msr >> 15) & 1) ? "EN" : "DIS",
3221 		((msr >> 0) & 0x7FFF) * rapl_power_units,
3222 		(1.0 + (((msr >> 22) & 0x3)/4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
3223 		(((msr >> 16) & 1) ? "EN" : "DIS"));
3224 
3225 	return;
3226 }
3227 
3228 int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3229 {
3230 	unsigned long long msr;
3231 	int cpu;
3232 
3233 	if (!do_rapl)
3234 		return 0;
3235 
3236 	/* RAPL counters are per package, so print only for 1st thread/package */
3237 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3238 		return 0;
3239 
3240 	cpu = t->cpu_id;
3241 	if (cpu_migrate(cpu)) {
3242 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3243 		return -1;
3244 	}
3245 
3246 	if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
3247 		return -1;
3248 
3249 	if (debug) {
3250 		fprintf(outf, "cpu%d: MSR_RAPL_POWER_UNIT: 0x%08llx "
3251 			"(%f Watts, %f Joules, %f sec.)\n", cpu, msr,
3252 			rapl_power_units, rapl_energy_units, rapl_time_units);
3253 	}
3254 	if (do_rapl & RAPL_PKG_POWER_INFO) {
3255 
3256 		if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
3257                 	return -5;
3258 
3259 
3260 		fprintf(outf, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
3261 			cpu, msr,
3262 			((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3263 			((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3264 			((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3265 			((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
3266 
3267 	}
3268 	if (do_rapl & RAPL_PKG) {
3269 
3270 		if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
3271 			return -9;
3272 
3273 		fprintf(outf, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
3274 			cpu, msr, (msr >> 63) & 1 ? "": "UN");
3275 
3276 		print_power_limit_msr(cpu, msr, "PKG Limit #1");
3277 		fprintf(outf, "cpu%d: PKG Limit #2: %sabled (%f Watts, %f* sec, clamp %sabled)\n",
3278 			cpu,
3279 			((msr >> 47) & 1) ? "EN" : "DIS",
3280 			((msr >> 32) & 0x7FFF) * rapl_power_units,
3281 			(1.0 + (((msr >> 54) & 0x3)/4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
3282 			((msr >> 48) & 1) ? "EN" : "DIS");
3283 	}
3284 
3285 	if (do_rapl & RAPL_DRAM_POWER_INFO) {
3286 		if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
3287                 	return -6;
3288 
3289 		fprintf(outf, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
3290 			cpu, msr,
3291 			((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3292 			((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3293 			((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3294 			((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
3295 	}
3296 	if (do_rapl & RAPL_DRAM) {
3297 		if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
3298 			return -9;
3299 		fprintf(outf, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
3300 				cpu, msr, (msr >> 31) & 1 ? "": "UN");
3301 
3302 		print_power_limit_msr(cpu, msr, "DRAM Limit");
3303 	}
3304 	if (do_rapl & RAPL_CORE_POLICY) {
3305 		if (debug) {
3306 			if (get_msr(cpu, MSR_PP0_POLICY, &msr))
3307 				return -7;
3308 
3309 			fprintf(outf, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
3310 		}
3311 	}
3312 	if (do_rapl & RAPL_CORES_POWER_LIMIT) {
3313 		if (debug) {
3314 			if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
3315 				return -9;
3316 			fprintf(outf, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
3317 					cpu, msr, (msr >> 31) & 1 ? "": "UN");
3318 			print_power_limit_msr(cpu, msr, "Cores Limit");
3319 		}
3320 	}
3321 	if (do_rapl & RAPL_GFX) {
3322 		if (debug) {
3323 			if (get_msr(cpu, MSR_PP1_POLICY, &msr))
3324 				return -8;
3325 
3326 			fprintf(outf, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
3327 
3328 			if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
3329 				return -9;
3330 			fprintf(outf, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
3331 					cpu, msr, (msr >> 31) & 1 ? "": "UN");
3332 			print_power_limit_msr(cpu, msr, "GFX Limit");
3333 		}
3334 	}
3335 	return 0;
3336 }
3337 
3338 /*
3339  * SNB adds support for additional MSRs:
3340  *
3341  * MSR_PKG_C7_RESIDENCY            0x000003fa
3342  * MSR_CORE_C7_RESIDENCY           0x000003fe
3343  * MSR_PKG_C2_RESIDENCY            0x0000060d
3344  */
3345 
3346 int has_snb_msrs(unsigned int family, unsigned int model)
3347 {
3348 	if (!genuine_intel)
3349 		return 0;
3350 
3351 	switch (model) {
3352 	case INTEL_FAM6_SANDYBRIDGE:
3353 	case INTEL_FAM6_SANDYBRIDGE_X:
3354 	case INTEL_FAM6_IVYBRIDGE:	/* IVB */
3355 	case INTEL_FAM6_IVYBRIDGE_X:	/* IVB Xeon */
3356 	case INTEL_FAM6_HASWELL_CORE:	/* HSW */
3357 	case INTEL_FAM6_HASWELL_X:	/* HSW */
3358 	case INTEL_FAM6_HASWELL_ULT:	/* HSW */
3359 	case INTEL_FAM6_HASWELL_GT3E:	/* HSW */
3360 	case INTEL_FAM6_BROADWELL_CORE:	/* BDW */
3361 	case INTEL_FAM6_BROADWELL_GT3E:	/* BDW */
3362 	case INTEL_FAM6_BROADWELL_X:	/* BDX */
3363 	case INTEL_FAM6_BROADWELL_XEON_D:	/* BDX-DE */
3364 	case INTEL_FAM6_SKYLAKE_MOBILE:	/* SKL */
3365 	case INTEL_FAM6_SKYLAKE_DESKTOP:	/* SKL */
3366 	case INTEL_FAM6_KABYLAKE_MOBILE:	/* KBL */
3367 	case INTEL_FAM6_KABYLAKE_DESKTOP:	/* KBL */
3368 	case INTEL_FAM6_SKYLAKE_X:	/* SKX */
3369 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
3370 	case INTEL_FAM6_ATOM_DENVERTON:	/* DNV */
3371 		return 1;
3372 	}
3373 	return 0;
3374 }
3375 
3376 /*
3377  * HSW adds support for additional MSRs:
3378  *
3379  * MSR_PKG_C8_RESIDENCY		0x00000630
3380  * MSR_PKG_C9_RESIDENCY		0x00000631
3381  * MSR_PKG_C10_RESIDENCY	0x00000632
3382  *
3383  * MSR_PKGC8_IRTL		0x00000633
3384  * MSR_PKGC9_IRTL		0x00000634
3385  * MSR_PKGC10_IRTL		0x00000635
3386  *
3387  */
3388 int has_hsw_msrs(unsigned int family, unsigned int model)
3389 {
3390 	if (!genuine_intel)
3391 		return 0;
3392 
3393 	switch (model) {
3394 	case INTEL_FAM6_HASWELL_ULT:	/* HSW */
3395 	case INTEL_FAM6_BROADWELL_CORE:	/* BDW */
3396 	case INTEL_FAM6_SKYLAKE_MOBILE:	/* SKL */
3397 	case INTEL_FAM6_SKYLAKE_DESKTOP:	/* SKL */
3398 	case INTEL_FAM6_KABYLAKE_MOBILE:	/* KBL */
3399 	case INTEL_FAM6_KABYLAKE_DESKTOP:	/* KBL */
3400 	case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
3401 		return 1;
3402 	}
3403 	return 0;
3404 }
3405 
3406 /*
3407  * SKL adds support for additional MSRS:
3408  *
3409  * MSR_PKG_WEIGHTED_CORE_C0_RES    0x00000658
3410  * MSR_PKG_ANY_CORE_C0_RES         0x00000659
3411  * MSR_PKG_ANY_GFXE_C0_RES         0x0000065A
3412  * MSR_PKG_BOTH_CORE_GFXE_C0_RES   0x0000065B
3413  */
3414 int has_skl_msrs(unsigned int family, unsigned int model)
3415 {
3416 	if (!genuine_intel)
3417 		return 0;
3418 
3419 	switch (model) {
3420 	case INTEL_FAM6_SKYLAKE_MOBILE:	/* SKL */
3421 	case INTEL_FAM6_SKYLAKE_DESKTOP:	/* SKL */
3422 	case INTEL_FAM6_KABYLAKE_MOBILE:	/* KBL */
3423 	case INTEL_FAM6_KABYLAKE_DESKTOP:	/* KBL */
3424 		return 1;
3425 	}
3426 	return 0;
3427 }
3428 
3429 int is_slm(unsigned int family, unsigned int model)
3430 {
3431 	if (!genuine_intel)
3432 		return 0;
3433 	switch (model) {
3434 	case INTEL_FAM6_ATOM_SILVERMONT1:	/* BYT */
3435 	case INTEL_FAM6_ATOM_SILVERMONT2:	/* AVN */
3436 		return 1;
3437 	}
3438 	return 0;
3439 }
3440 
3441 int is_knl(unsigned int family, unsigned int model)
3442 {
3443 	if (!genuine_intel)
3444 		return 0;
3445 	switch (model) {
3446 	case INTEL_FAM6_XEON_PHI_KNL:	/* KNL */
3447 	case INTEL_FAM6_XEON_PHI_KNM:
3448 		return 1;
3449 	}
3450 	return 0;
3451 }
3452 
3453 unsigned int get_aperf_mperf_multiplier(unsigned int family, unsigned int model)
3454 {
3455 	if (is_knl(family, model))
3456 		return 1024;
3457 	return 1;
3458 }
3459 
3460 #define SLM_BCLK_FREQS 5
3461 double slm_freq_table[SLM_BCLK_FREQS] = { 83.3, 100.0, 133.3, 116.7, 80.0};
3462 
3463 double slm_bclk(void)
3464 {
3465 	unsigned long long msr = 3;
3466 	unsigned int i;
3467 	double freq;
3468 
3469 	if (get_msr(base_cpu, MSR_FSB_FREQ, &msr))
3470 		fprintf(outf, "SLM BCLK: unknown\n");
3471 
3472 	i = msr & 0xf;
3473 	if (i >= SLM_BCLK_FREQS) {
3474 		fprintf(outf, "SLM BCLK[%d] invalid\n", i);
3475 		i = 3;
3476 	}
3477 	freq = slm_freq_table[i];
3478 
3479 	if (debug)
3480 		fprintf(outf, "SLM BCLK: %.1f Mhz\n", freq);
3481 
3482 	return freq;
3483 }
3484 
3485 double discover_bclk(unsigned int family, unsigned int model)
3486 {
3487 	if (has_snb_msrs(family, model) || is_knl(family, model))
3488 		return 100.00;
3489 	else if (is_slm(family, model))
3490 		return slm_bclk();
3491 	else
3492 		return 133.33;
3493 }
3494 
3495 /*
3496  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
3497  * the Thermal Control Circuit (TCC) activates.
3498  * This is usually equal to tjMax.
3499  *
3500  * Older processors do not have this MSR, so there we guess,
3501  * but also allow cmdline over-ride with -T.
3502  *
3503  * Several MSR temperature values are in units of degrees-C
3504  * below this value, including the Digital Thermal Sensor (DTS),
3505  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
3506  */
3507 int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3508 {
3509 	unsigned long long msr;
3510 	unsigned int target_c_local;
3511 	int cpu;
3512 
3513 	/* tcc_activation_temp is used only for dts or ptm */
3514 	if (!(do_dts || do_ptm))
3515 		return 0;
3516 
3517 	/* this is a per-package concept */
3518 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3519 		return 0;
3520 
3521 	cpu = t->cpu_id;
3522 	if (cpu_migrate(cpu)) {
3523 		fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3524 		return -1;
3525 	}
3526 
3527 	if (tcc_activation_temp_override != 0) {
3528 		tcc_activation_temp = tcc_activation_temp_override;
3529 		fprintf(outf, "cpu%d: Using cmdline TCC Target (%d C)\n",
3530 			cpu, tcc_activation_temp);
3531 		return 0;
3532 	}
3533 
3534 	/* Temperature Target MSR is Nehalem and newer only */
3535 	if (!do_nhm_platform_info)
3536 		goto guess;
3537 
3538 	if (get_msr(base_cpu, MSR_IA32_TEMPERATURE_TARGET, &msr))
3539 		goto guess;
3540 
3541 	target_c_local = (msr >> 16) & 0xFF;
3542 
3543 	if (debug)
3544 		fprintf(outf, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n",
3545 			cpu, msr, target_c_local);
3546 
3547 	if (!target_c_local)
3548 		goto guess;
3549 
3550 	tcc_activation_temp = target_c_local;
3551 
3552 	return 0;
3553 
3554 guess:
3555 	tcc_activation_temp = TJMAX_DEFAULT;
3556 	fprintf(outf, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n",
3557 		cpu, tcc_activation_temp);
3558 
3559 	return 0;
3560 }
3561 
3562 void decode_feature_control_msr(void)
3563 {
3564 	unsigned long long msr;
3565 
3566 	if (!get_msr(base_cpu, MSR_IA32_FEATURE_CONTROL, &msr))
3567 		fprintf(outf, "cpu%d: MSR_IA32_FEATURE_CONTROL: 0x%08llx (%sLocked %s)\n",
3568 			base_cpu, msr,
3569 			msr & FEATURE_CONTROL_LOCKED ? "" : "UN-",
3570 			msr & (1 << 18) ? "SGX" : "");
3571 }
3572 
3573 void decode_misc_enable_msr(void)
3574 {
3575 	unsigned long long msr;
3576 
3577 	if (!get_msr(base_cpu, MSR_IA32_MISC_ENABLE, &msr))
3578 		fprintf(outf, "cpu%d: MSR_IA32_MISC_ENABLE: 0x%08llx (%sTCC %sEIST %sMWAIT %sPREFETCH %sTURBO)\n",
3579 			base_cpu, msr,
3580 			msr & MSR_IA32_MISC_ENABLE_TM1 ? "" : "No-",
3581 			msr & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP ? "" : "No-",
3582 			msr & MSR_IA32_MISC_ENABLE_MWAIT ? "No-" : "",
3583 			msr & MSR_IA32_MISC_ENABLE_PREFETCH_DISABLE ? "No-" : "",
3584 			msr & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ? "No-" : "");
3585 }
3586 
3587 void decode_misc_feature_control(void)
3588 {
3589 	unsigned long long msr;
3590 
3591 	if (!has_misc_feature_control)
3592 		return;
3593 
3594 	if (!get_msr(base_cpu, MSR_MISC_FEATURE_CONTROL, &msr))
3595 		fprintf(outf, "cpu%d: MSR_MISC_FEATURE_CONTROL: 0x%08llx (%sL2-Prefetch %sL2-Prefetch-pair %sL1-Prefetch %sL1-IP-Prefetch)\n",
3596 			base_cpu, msr,
3597 			msr & (0 << 0) ? "No-" : "",
3598 			msr & (1 << 0) ? "No-" : "",
3599 			msr & (2 << 0) ? "No-" : "",
3600 			msr & (3 << 0) ? "No-" : "");
3601 }
3602 /*
3603  * Decode MSR_MISC_PWR_MGMT
3604  *
3605  * Decode the bits according to the Nehalem documentation
3606  * bit[0] seems to continue to have same meaning going forward
3607  * bit[1] less so...
3608  */
3609 void decode_misc_pwr_mgmt_msr(void)
3610 {
3611 	unsigned long long msr;
3612 
3613 	if (!do_nhm_platform_info)
3614 		return;
3615 
3616 	if (no_MSR_MISC_PWR_MGMT)
3617 		return;
3618 
3619 	if (!get_msr(base_cpu, MSR_MISC_PWR_MGMT, &msr))
3620 		fprintf(outf, "cpu%d: MSR_MISC_PWR_MGMT: 0x%08llx (%sable-EIST_Coordination %sable-EPB %sable-OOB)\n",
3621 			base_cpu, msr,
3622 			msr & (1 << 0) ? "DIS" : "EN",
3623 			msr & (1 << 1) ? "EN" : "DIS",
3624 			msr & (1 << 8) ? "EN" : "DIS");
3625 }
3626 /*
3627  * Decode MSR_CC6_DEMOTION_POLICY_CONFIG, MSR_MC6_DEMOTION_POLICY_CONFIG
3628  *
3629  * This MSRs are present on Silvermont processors,
3630  * Intel Atom processor E3000 series (Baytrail), and friends.
3631  */
3632 void decode_c6_demotion_policy_msr(void)
3633 {
3634 	unsigned long long msr;
3635 
3636 	if (!get_msr(base_cpu, MSR_CC6_DEMOTION_POLICY_CONFIG, &msr))
3637 		fprintf(outf, "cpu%d: MSR_CC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-CC6-Demotion)\n",
3638 			base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
3639 
3640 	if (!get_msr(base_cpu, MSR_MC6_DEMOTION_POLICY_CONFIG, &msr))
3641 		fprintf(outf, "cpu%d: MSR_MC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-MC6-Demotion)\n",
3642 			base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
3643 }
3644 
3645 void process_cpuid()
3646 {
3647 	unsigned int eax, ebx, ecx, edx, max_level, max_extended_level;
3648 	unsigned int fms, family, model, stepping;
3649 	unsigned int has_turbo;
3650 
3651 	eax = ebx = ecx = edx = 0;
3652 
3653 	__cpuid(0, max_level, ebx, ecx, edx);
3654 
3655 	if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
3656 		genuine_intel = 1;
3657 
3658 	if (debug)
3659 		fprintf(outf, "CPUID(0): %.4s%.4s%.4s ",
3660 			(char *)&ebx, (char *)&edx, (char *)&ecx);
3661 
3662 	__cpuid(1, fms, ebx, ecx, edx);
3663 	family = (fms >> 8) & 0xf;
3664 	model = (fms >> 4) & 0xf;
3665 	stepping = fms & 0xf;
3666 	if (family == 6 || family == 0xf)
3667 		model += ((fms >> 16) & 0xf) << 4;
3668 
3669 	if (debug) {
3670 		fprintf(outf, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
3671 			max_level, family, model, stepping, family, model, stepping);
3672 		fprintf(outf, "CPUID(1): %s %s %s %s %s %s %s %s %s\n",
3673 			ecx & (1 << 0) ? "SSE3" : "-",
3674 			ecx & (1 << 3) ? "MONITOR" : "-",
3675 			ecx & (1 << 6) ? "SMX" : "-",
3676 			ecx & (1 << 7) ? "EIST" : "-",
3677 			ecx & (1 << 8) ? "TM2" : "-",
3678 			edx & (1 << 4) ? "TSC" : "-",
3679 			edx & (1 << 5) ? "MSR" : "-",
3680 			edx & (1 << 22) ? "ACPI-TM" : "-",
3681 			edx & (1 << 29) ? "TM" : "-");
3682 	}
3683 
3684 	if (!(edx & (1 << 5)))
3685 		errx(1, "CPUID: no MSR");
3686 
3687 	/*
3688 	 * check max extended function levels of CPUID.
3689 	 * This is needed to check for invariant TSC.
3690 	 * This check is valid for both Intel and AMD.
3691 	 */
3692 	ebx = ecx = edx = 0;
3693 	__cpuid(0x80000000, max_extended_level, ebx, ecx, edx);
3694 
3695 	if (max_extended_level >= 0x80000007) {
3696 
3697 		/*
3698 		 * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
3699 		 * this check is valid for both Intel and AMD
3700 		 */
3701 		__cpuid(0x80000007, eax, ebx, ecx, edx);
3702 		has_invariant_tsc = edx & (1 << 8);
3703 	}
3704 
3705 	/*
3706 	 * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
3707 	 * this check is valid for both Intel and AMD
3708 	 */
3709 
3710 	__cpuid(0x6, eax, ebx, ecx, edx);
3711 	has_aperf = ecx & (1 << 0);
3712 	if (has_aperf) {
3713 		BIC_PRESENT(BIC_Avg_MHz);
3714 		BIC_PRESENT(BIC_Busy);
3715 		BIC_PRESENT(BIC_Bzy_MHz);
3716 	}
3717 	do_dts = eax & (1 << 0);
3718 	if (do_dts)
3719 		BIC_PRESENT(BIC_CoreTmp);
3720 	has_turbo = eax & (1 << 1);
3721 	do_ptm = eax & (1 << 6);
3722 	if (do_ptm)
3723 		BIC_PRESENT(BIC_PkgTmp);
3724 	has_hwp = eax & (1 << 7);
3725 	has_hwp_notify = eax & (1 << 8);
3726 	has_hwp_activity_window = eax & (1 << 9);
3727 	has_hwp_epp = eax & (1 << 10);
3728 	has_hwp_pkg = eax & (1 << 11);
3729 	has_epb = ecx & (1 << 3);
3730 
3731 	if (debug)
3732 		fprintf(outf, "CPUID(6): %sAPERF, %sTURBO, %sDTS, %sPTM, %sHWP, "
3733 			"%sHWPnotify, %sHWPwindow, %sHWPepp, %sHWPpkg, %sEPB\n",
3734 			has_aperf ? "" : "No-",
3735 			has_turbo ? "" : "No-",
3736 			do_dts ? "" : "No-",
3737 			do_ptm ? "" : "No-",
3738 			has_hwp ? "" : "No-",
3739 			has_hwp_notify ? "" : "No-",
3740 			has_hwp_activity_window ? "" : "No-",
3741 			has_hwp_epp ? "" : "No-",
3742 			has_hwp_pkg ? "" : "No-",
3743 			has_epb ? "" : "No-");
3744 
3745 	if (debug)
3746 		decode_misc_enable_msr();
3747 
3748 
3749 	if (max_level >= 0x7 && debug) {
3750 		int has_sgx;
3751 
3752 		ecx = 0;
3753 
3754 		__cpuid_count(0x7, 0, eax, ebx, ecx, edx);
3755 
3756 		has_sgx = ebx & (1 << 2);
3757 		fprintf(outf, "CPUID(7): %sSGX\n", has_sgx ? "" : "No-");
3758 
3759 		if (has_sgx)
3760 			decode_feature_control_msr();
3761 	}
3762 
3763 	if (max_level >= 0x15) {
3764 		unsigned int eax_crystal;
3765 		unsigned int ebx_tsc;
3766 
3767 		/*
3768 		 * CPUID 15H TSC/Crystal ratio, possibly Crystal Hz
3769 		 */
3770 		eax_crystal = ebx_tsc = crystal_hz = edx = 0;
3771 		__cpuid(0x15, eax_crystal, ebx_tsc, crystal_hz, edx);
3772 
3773 		if (ebx_tsc != 0) {
3774 
3775 			if (debug && (ebx != 0))
3776 				fprintf(outf, "CPUID(0x15): eax_crystal: %d ebx_tsc: %d ecx_crystal_hz: %d\n",
3777 					eax_crystal, ebx_tsc, crystal_hz);
3778 
3779 			if (crystal_hz == 0)
3780 				switch(model) {
3781 				case INTEL_FAM6_SKYLAKE_MOBILE:	/* SKL */
3782 				case INTEL_FAM6_SKYLAKE_DESKTOP:	/* SKL */
3783 				case INTEL_FAM6_KABYLAKE_MOBILE:	/* KBL */
3784 				case INTEL_FAM6_KABYLAKE_DESKTOP:	/* KBL */
3785 					crystal_hz = 24000000;	/* 24.0 MHz */
3786 					break;
3787 				case INTEL_FAM6_SKYLAKE_X:	/* SKX */
3788 				case INTEL_FAM6_ATOM_DENVERTON:	/* DNV */
3789 					crystal_hz = 25000000;	/* 25.0 MHz */
3790 					break;
3791 				case INTEL_FAM6_ATOM_GOLDMONT:	/* BXT */
3792 					crystal_hz = 19200000;	/* 19.2 MHz */
3793 					break;
3794 				default:
3795 					crystal_hz = 0;
3796 			}
3797 
3798 			if (crystal_hz) {
3799 				tsc_hz =  (unsigned long long) crystal_hz * ebx_tsc / eax_crystal;
3800 				if (debug)
3801 					fprintf(outf, "TSC: %lld MHz (%d Hz * %d / %d / 1000000)\n",
3802 						tsc_hz / 1000000, crystal_hz, ebx_tsc,  eax_crystal);
3803 			}
3804 		}
3805 	}
3806 	if (max_level >= 0x16) {
3807 		unsigned int base_mhz, max_mhz, bus_mhz, edx;
3808 
3809 		/*
3810 		 * CPUID 16H Base MHz, Max MHz, Bus MHz
3811 		 */
3812 		base_mhz = max_mhz = bus_mhz = edx = 0;
3813 
3814 		__cpuid(0x16, base_mhz, max_mhz, bus_mhz, edx);
3815 		if (debug)
3816 			fprintf(outf, "CPUID(0x16): base_mhz: %d max_mhz: %d bus_mhz: %d\n",
3817 				base_mhz, max_mhz, bus_mhz);
3818 	}
3819 
3820 	if (has_aperf)
3821 		aperf_mperf_multiplier = get_aperf_mperf_multiplier(family, model);
3822 
3823 	BIC_PRESENT(BIC_IRQ);
3824 	BIC_PRESENT(BIC_TSC_MHz);
3825 
3826 	if (probe_nhm_msrs(family, model)) {
3827 		do_nhm_platform_info = 1;
3828 		BIC_PRESENT(BIC_CPU_c1);
3829 		BIC_PRESENT(BIC_CPU_c3);
3830 		BIC_PRESENT(BIC_CPU_c6);
3831 		BIC_PRESENT(BIC_SMI);
3832 	}
3833 	do_snb_cstates = has_snb_msrs(family, model);
3834 
3835 	if (do_snb_cstates)
3836 		BIC_PRESENT(BIC_CPU_c7);
3837 
3838 	do_irtl_snb = has_snb_msrs(family, model);
3839 	do_pc2 = do_snb_cstates && (pkg_cstate_limit >= PCL__2);
3840 	do_pc3 = (pkg_cstate_limit >= PCL__3);
3841 	do_pc6 = (pkg_cstate_limit >= PCL__6);
3842 	do_pc7 = do_snb_cstates && (pkg_cstate_limit >= PCL__7);
3843 	if (has_slv_msrs(family, model)) {
3844 		do_pc2 = do_pc3 = do_pc7 = 0;
3845 		do_pc6 = 1;
3846 		BIC_PRESENT(BIC_Mod_c6);
3847 		use_c1_residency_msr = 1;
3848 	}
3849 	do_c8_c9_c10 = has_hsw_msrs(family, model);
3850 	do_irtl_hsw = has_hsw_msrs(family, model);
3851 	do_skl_residency = has_skl_msrs(family, model);
3852 	do_slm_cstates = is_slm(family, model);
3853 	do_knl_cstates  = is_knl(family, model);
3854 
3855 	if (debug)
3856 		decode_misc_pwr_mgmt_msr();
3857 
3858 	if (debug && has_slv_msrs(family, model))
3859 		decode_c6_demotion_policy_msr();
3860 
3861 	rapl_probe(family, model);
3862 	perf_limit_reasons_probe(family, model);
3863 
3864 	if (debug)
3865 		dump_cstate_pstate_config_info(family, model);
3866 
3867 	if (has_skl_msrs(family, model))
3868 		calculate_tsc_tweak();
3869 
3870 	if (!access("/sys/class/drm/card0/power/rc6_residency_ms", R_OK))
3871 		BIC_PRESENT(BIC_GFX_rc6);
3872 
3873 	if (!access("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", R_OK))
3874 		BIC_PRESENT(BIC_GFXMHz);
3875 
3876 	if (debug)
3877 		decode_misc_feature_control();
3878 
3879 	return;
3880 }
3881 
3882 void help()
3883 {
3884 	fprintf(outf,
3885 	"Usage: turbostat [OPTIONS][(--interval seconds) | COMMAND ...]\n"
3886 	"\n"
3887 	"Turbostat forks the specified COMMAND and prints statistics\n"
3888 	"when COMMAND completes.\n"
3889 	"If no COMMAND is specified, turbostat wakes every 5-seconds\n"
3890 	"to print statistics, until interrupted.\n"
3891 	"--add		add a counter\n"
3892 	"		eg. --add msr0x10,u64,cpu,delta,MY_TSC\n"
3893 	"--debug	run in \"debug\" mode\n"
3894 	"--interval sec	Override default 5-second measurement interval\n"
3895 	"--help		print this help message\n"
3896 	"--out file	create or truncate \"file\" for all output\n"
3897 	"--version	print version information\n"
3898 	"\n"
3899 	"For more help, run \"man turbostat\"\n");
3900 }
3901 
3902 
3903 /*
3904  * in /dev/cpu/ return success for names that are numbers
3905  * ie. filter out ".", "..", "microcode".
3906  */
3907 int dir_filter(const struct dirent *dirp)
3908 {
3909 	if (isdigit(dirp->d_name[0]))
3910 		return 1;
3911 	else
3912 		return 0;
3913 }
3914 
3915 int open_dev_cpu_msr(int dummy1)
3916 {
3917 	return 0;
3918 }
3919 
3920 void topology_probe()
3921 {
3922 	int i;
3923 	int max_core_id = 0;
3924 	int max_package_id = 0;
3925 	int max_siblings = 0;
3926 	struct cpu_topology {
3927 		int core_id;
3928 		int physical_package_id;
3929 	} *cpus;
3930 
3931 	/* Initialize num_cpus, max_cpu_num */
3932 	topo.num_cpus = 0;
3933 	topo.max_cpu_num = 0;
3934 	for_all_proc_cpus(count_cpus);
3935 	if (!summary_only && topo.num_cpus > 1)
3936 		BIC_PRESENT(BIC_CPU);
3937 
3938 	if (debug > 1)
3939 		fprintf(outf, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
3940 
3941 	cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
3942 	if (cpus == NULL)
3943 		err(1, "calloc cpus");
3944 
3945 	/*
3946 	 * Allocate and initialize cpu_present_set
3947 	 */
3948 	cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
3949 	if (cpu_present_set == NULL)
3950 		err(3, "CPU_ALLOC");
3951 	cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
3952 	CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
3953 	for_all_proc_cpus(mark_cpu_present);
3954 
3955 	/*
3956 	 * Allocate and initialize cpu_affinity_set
3957 	 */
3958 	cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
3959 	if (cpu_affinity_set == NULL)
3960 		err(3, "CPU_ALLOC");
3961 	cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
3962 	CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
3963 
3964 
3965 	/*
3966 	 * For online cpus
3967 	 * find max_core_id, max_package_id
3968 	 */
3969 	for (i = 0; i <= topo.max_cpu_num; ++i) {
3970 		int siblings;
3971 
3972 		if (cpu_is_not_present(i)) {
3973 			if (debug > 1)
3974 				fprintf(outf, "cpu%d NOT PRESENT\n", i);
3975 			continue;
3976 		}
3977 		cpus[i].core_id = get_core_id(i);
3978 		if (cpus[i].core_id > max_core_id)
3979 			max_core_id = cpus[i].core_id;
3980 
3981 		cpus[i].physical_package_id = get_physical_package_id(i);
3982 		if (cpus[i].physical_package_id > max_package_id)
3983 			max_package_id = cpus[i].physical_package_id;
3984 
3985 		siblings = get_num_ht_siblings(i);
3986 		if (siblings > max_siblings)
3987 			max_siblings = siblings;
3988 		if (debug > 1)
3989 			fprintf(outf, "cpu %d pkg %d core %d\n",
3990 				i, cpus[i].physical_package_id, cpus[i].core_id);
3991 	}
3992 	topo.num_cores_per_pkg = max_core_id + 1;
3993 	if (debug > 1)
3994 		fprintf(outf, "max_core_id %d, sizing for %d cores per package\n",
3995 			max_core_id, topo.num_cores_per_pkg);
3996 	if (debug && !summary_only && topo.num_cores_per_pkg > 1)
3997 		BIC_PRESENT(BIC_Core);
3998 
3999 	topo.num_packages = max_package_id + 1;
4000 	if (debug > 1)
4001 		fprintf(outf, "max_package_id %d, sizing for %d packages\n",
4002 			max_package_id, topo.num_packages);
4003 	if (debug && !summary_only && topo.num_packages > 1)
4004 		BIC_PRESENT(BIC_Package);
4005 
4006 	topo.num_threads_per_core = max_siblings;
4007 	if (debug > 1)
4008 		fprintf(outf, "max_siblings %d\n", max_siblings);
4009 
4010 	free(cpus);
4011 }
4012 
4013 void
4014 allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
4015 {
4016 	int i;
4017 
4018 	*t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
4019 		topo.num_packages, sizeof(struct thread_data));
4020 	if (*t == NULL)
4021 		goto error;
4022 
4023 	for (i = 0; i < topo.num_threads_per_core *
4024 		topo.num_cores_per_pkg * topo.num_packages; i++)
4025 		(*t)[i].cpu_id = -1;
4026 
4027 	*c = calloc(topo.num_cores_per_pkg * topo.num_packages,
4028 		sizeof(struct core_data));
4029 	if (*c == NULL)
4030 		goto error;
4031 
4032 	for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
4033 		(*c)[i].core_id = -1;
4034 
4035 	*p = calloc(topo.num_packages, sizeof(struct pkg_data));
4036 	if (*p == NULL)
4037 		goto error;
4038 
4039 	for (i = 0; i < topo.num_packages; i++)
4040 		(*p)[i].package_id = i;
4041 
4042 	return;
4043 error:
4044 	err(1, "calloc counters");
4045 }
4046 /*
4047  * init_counter()
4048  *
4049  * set cpu_id, core_num, pkg_num
4050  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
4051  *
4052  * increment topo.num_cores when 1st core in pkg seen
4053  */
4054 void init_counter(struct thread_data *thread_base, struct core_data *core_base,
4055 	struct pkg_data *pkg_base, int thread_num, int core_num,
4056 	int pkg_num, int cpu_id)
4057 {
4058 	struct thread_data *t;
4059 	struct core_data *c;
4060 	struct pkg_data *p;
4061 
4062 	t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
4063 	c = GET_CORE(core_base, core_num, pkg_num);
4064 	p = GET_PKG(pkg_base, pkg_num);
4065 
4066 	t->cpu_id = cpu_id;
4067 	if (thread_num == 0) {
4068 		t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
4069 		if (cpu_is_first_core_in_package(cpu_id))
4070 			t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
4071 	}
4072 
4073 	c->core_id = core_num;
4074 	p->package_id = pkg_num;
4075 }
4076 
4077 
4078 int initialize_counters(int cpu_id)
4079 {
4080 	int my_thread_id, my_core_id, my_package_id;
4081 
4082 	my_package_id = get_physical_package_id(cpu_id);
4083 	my_core_id = get_core_id(cpu_id);
4084 	my_thread_id = get_cpu_position_in_core(cpu_id);
4085 	if (!my_thread_id)
4086 		topo.num_cores++;
4087 
4088 	init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
4089 	init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
4090 	return 0;
4091 }
4092 
4093 void allocate_output_buffer()
4094 {
4095 	output_buffer = calloc(1, (1 + topo.num_cpus) * 1024);
4096 	outp = output_buffer;
4097 	if (outp == NULL)
4098 		err(-1, "calloc output buffer");
4099 }
4100 void allocate_fd_percpu(void)
4101 {
4102 	fd_percpu = calloc(topo.max_cpu_num + 1, sizeof(int));
4103 	if (fd_percpu == NULL)
4104 		err(-1, "calloc fd_percpu");
4105 }
4106 void allocate_irq_buffers(void)
4107 {
4108 	irq_column_2_cpu = calloc(topo.num_cpus, sizeof(int));
4109 	if (irq_column_2_cpu == NULL)
4110 		err(-1, "calloc %d", topo.num_cpus);
4111 
4112 	irqs_per_cpu = calloc(topo.max_cpu_num + 1, sizeof(int));
4113 	if (irqs_per_cpu == NULL)
4114 		err(-1, "calloc %d", topo.max_cpu_num + 1);
4115 }
4116 void setup_all_buffers(void)
4117 {
4118 	topology_probe();
4119 	allocate_irq_buffers();
4120 	allocate_fd_percpu();
4121 	allocate_counters(&thread_even, &core_even, &package_even);
4122 	allocate_counters(&thread_odd, &core_odd, &package_odd);
4123 	allocate_output_buffer();
4124 	for_all_proc_cpus(initialize_counters);
4125 }
4126 
4127 void set_base_cpu(void)
4128 {
4129 	base_cpu = sched_getcpu();
4130 	if (base_cpu < 0)
4131 		err(-ENODEV, "No valid cpus found");
4132 
4133 	if (debug > 1)
4134 		fprintf(outf, "base_cpu = %d\n", base_cpu);
4135 }
4136 
4137 void turbostat_init()
4138 {
4139 	setup_all_buffers();
4140 	set_base_cpu();
4141 	check_dev_msr();
4142 	check_permissions();
4143 	process_cpuid();
4144 
4145 
4146 	if (debug)
4147 		for_all_cpus(print_hwp, ODD_COUNTERS);
4148 
4149 	if (debug)
4150 		for_all_cpus(print_epb, ODD_COUNTERS);
4151 
4152 	if (debug)
4153 		for_all_cpus(print_perf_limit, ODD_COUNTERS);
4154 
4155 	if (debug)
4156 		for_all_cpus(print_rapl, ODD_COUNTERS);
4157 
4158 	for_all_cpus(set_temperature_target, ODD_COUNTERS);
4159 
4160 	if (debug)
4161 		for_all_cpus(print_thermal, ODD_COUNTERS);
4162 
4163 	if (debug && do_irtl_snb)
4164 		print_irtl();
4165 }
4166 
4167 int fork_it(char **argv)
4168 {
4169 	pid_t child_pid;
4170 	int status;
4171 
4172 	status = for_all_cpus(get_counters, EVEN_COUNTERS);
4173 	if (status)
4174 		exit(status);
4175 	/* clear affinity side-effect of get_counters() */
4176 	sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
4177 	gettimeofday(&tv_even, (struct timezone *)NULL);
4178 
4179 	child_pid = fork();
4180 	if (!child_pid) {
4181 		/* child */
4182 		execvp(argv[0], argv);
4183 	} else {
4184 
4185 		/* parent */
4186 		if (child_pid == -1)
4187 			err(1, "fork");
4188 
4189 		signal(SIGINT, SIG_IGN);
4190 		signal(SIGQUIT, SIG_IGN);
4191 		if (waitpid(child_pid, &status, 0) == -1)
4192 			err(status, "waitpid");
4193 	}
4194 	/*
4195 	 * n.b. fork_it() does not check for errors from for_all_cpus()
4196 	 * because re-starting is problematic when forking
4197 	 */
4198 	for_all_cpus(get_counters, ODD_COUNTERS);
4199 	gettimeofday(&tv_odd, (struct timezone *)NULL);
4200 	timersub(&tv_odd, &tv_even, &tv_delta);
4201 	if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS))
4202 		fprintf(outf, "%s: Counter reset detected\n", progname);
4203 	else {
4204 		compute_average(EVEN_COUNTERS);
4205 		format_all_counters(EVEN_COUNTERS);
4206 	}
4207 
4208 	fprintf(outf, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
4209 
4210 	flush_output_stderr();
4211 
4212 	return status;
4213 }
4214 
4215 int get_and_dump_counters(void)
4216 {
4217 	int status;
4218 
4219 	status = for_all_cpus(get_counters, ODD_COUNTERS);
4220 	if (status)
4221 		return status;
4222 
4223 	status = for_all_cpus(dump_counters, ODD_COUNTERS);
4224 	if (status)
4225 		return status;
4226 
4227 	flush_output_stdout();
4228 
4229 	return status;
4230 }
4231 
4232 void print_version() {
4233 	fprintf(outf, "turbostat version 4.17 10 Jan 2017"
4234 		" - Len Brown <lenb@kernel.org>\n");
4235 }
4236 
4237 int add_counter(unsigned int msr_num, char *name, unsigned int width,
4238 	enum counter_scope scope, enum counter_type type,
4239 	enum counter_format format)
4240 {
4241 	struct msr_counter *msrp;
4242 
4243 	msrp = calloc(1, sizeof(struct msr_counter));
4244 	if (msrp == NULL) {
4245 		perror("calloc");
4246 		exit(1);
4247 	}
4248 
4249 	msrp->msr_num = msr_num;
4250 	strncpy(msrp->name, name, NAME_BYTES);
4251 	msrp->width = width;
4252 	msrp->type = type;
4253 	msrp->format = format;
4254 
4255 	switch (scope) {
4256 
4257 	case SCOPE_CPU:
4258 		msrp->next = sys.tp;
4259 		sys.tp = msrp;
4260 		sys.added_thread_counters++;
4261 		if (sys.added_thread_counters > MAX_ADDED_COUNTERS) {
4262 			fprintf(stderr, "exceeded max %d added thread counters\n",
4263 				MAX_ADDED_COUNTERS);
4264 			exit(-1);
4265 		}
4266 		break;
4267 
4268 	case SCOPE_CORE:
4269 		msrp->next = sys.cp;
4270 		sys.cp = msrp;
4271 		sys.added_core_counters++;
4272 		if (sys.added_core_counters > MAX_ADDED_COUNTERS) {
4273 			fprintf(stderr, "exceeded max %d added core counters\n",
4274 				MAX_ADDED_COUNTERS);
4275 			exit(-1);
4276 		}
4277 		break;
4278 
4279 	case SCOPE_PACKAGE:
4280 		msrp->next = sys.pp;
4281 		sys.pp = msrp;
4282 		sys.added_package_counters++;
4283 		if (sys.added_package_counters > MAX_ADDED_COUNTERS) {
4284 			fprintf(stderr, "exceeded max %d added package counters\n",
4285 				MAX_ADDED_COUNTERS);
4286 			exit(-1);
4287 		}
4288 		break;
4289 	}
4290 
4291 	return 0;
4292 }
4293 
4294 void parse_add_command(char *add_command)
4295 {
4296 	int msr_num = 0;
4297 	char name_buffer[NAME_BYTES];
4298 	int width = 64;
4299 	int fail = 0;
4300 	enum counter_scope scope = SCOPE_CPU;
4301 	enum counter_type type = COUNTER_CYCLES;
4302 	enum counter_format format = FORMAT_DELTA;
4303 
4304 	while (add_command) {
4305 
4306 		if (sscanf(add_command, "msr0x%x", &msr_num) == 1)
4307 			goto next;
4308 
4309 		if (sscanf(add_command, "msr%d", &msr_num) == 1)
4310 			goto next;
4311 
4312 		if (sscanf(add_command, "u%d", &width) == 1) {
4313 			if ((width == 32) || (width == 64))
4314 				goto next;
4315 			width = 64;
4316 		}
4317 		if (!strncmp(add_command, "cpu", strlen("cpu"))) {
4318 			scope = SCOPE_CPU;
4319 			goto next;
4320 		}
4321 		if (!strncmp(add_command, "core", strlen("core"))) {
4322 			scope = SCOPE_CORE;
4323 			goto next;
4324 		}
4325 		if (!strncmp(add_command, "package", strlen("package"))) {
4326 			scope = SCOPE_PACKAGE;
4327 			goto next;
4328 		}
4329 		if (!strncmp(add_command, "cycles", strlen("cycles"))) {
4330 			type = COUNTER_CYCLES;
4331 			goto next;
4332 		}
4333 		if (!strncmp(add_command, "seconds", strlen("seconds"))) {
4334 			type = COUNTER_SECONDS;
4335 			goto next;
4336 		}
4337 		if (!strncmp(add_command, "raw", strlen("raw"))) {
4338 			format = FORMAT_RAW;
4339 			goto next;
4340 		}
4341 		if (!strncmp(add_command, "delta", strlen("delta"))) {
4342 			format = FORMAT_DELTA;
4343 			goto next;
4344 		}
4345 		if (!strncmp(add_command, "percent", strlen("percent"))) {
4346 			format = FORMAT_PERCENT;
4347 			goto next;
4348 		}
4349 
4350 		if (sscanf(add_command, "%18s,%*s", name_buffer) == 1) {	/* 18 < NAME_BYTES */
4351 			char *eos;
4352 
4353 			eos = strchr(name_buffer, ',');
4354 			if (eos)
4355 				*eos = '\0';
4356 			goto next;
4357 		}
4358 
4359 next:
4360 		add_command = strchr(add_command, ',');
4361 		if (add_command)
4362 			add_command++;
4363 
4364 	}
4365 	if (msr_num == 0) {
4366 		fprintf(stderr, "--add: (msrDDD | msr0xXXX) required\n");
4367 		fail++;
4368 	}
4369 
4370 	/* generate default column header */
4371 	if (*name_buffer == '\0') {
4372 		if (format == FORMAT_RAW) {
4373 			if (width == 32)
4374 				sprintf(name_buffer, "msr%d", msr_num);
4375 			else
4376 				sprintf(name_buffer, "MSR%d", msr_num);
4377 		} else if (format == FORMAT_DELTA) {
4378 			if (width == 32)
4379 				sprintf(name_buffer, "cnt%d", msr_num);
4380 			else
4381 				sprintf(name_buffer, "CNT%d", msr_num);
4382 		} else if (format == FORMAT_PERCENT) {
4383 			if (width == 32)
4384 				sprintf(name_buffer, "msr%d%%", msr_num);
4385 			else
4386 				sprintf(name_buffer, "MSR%d%%", msr_num);
4387 		}
4388 	}
4389 
4390 	if (add_counter(msr_num, name_buffer, width, scope, type, format))
4391 		fail++;
4392 
4393 	if (fail) {
4394 		help();
4395 		exit(1);
4396 	}
4397 }
4398 /*
4399  * HIDE_LIST - hide this list of counters, show the rest [default]
4400  * SHOW_LIST - show this list of counters, hide the rest
4401  */
4402 enum show_hide_mode { SHOW_LIST, HIDE_LIST } global_show_hide_mode = HIDE_LIST;
4403 
4404 int shown;
4405 /*
4406  * parse_show_hide() - process cmdline to set default counter action
4407  */
4408 void parse_show_hide(char *optarg, enum show_hide_mode new_mode)
4409 {
4410 	/*
4411 	 * --show: show only those specified
4412 	 *  The 1st invocation will clear and replace the enabled mask
4413 	 *  subsequent invocations can add to it.
4414 	 */
4415 	if (new_mode == SHOW_LIST) {
4416 		if (shown == 0)
4417 			bic_enabled = bic_lookup(optarg);
4418 		else
4419 			bic_enabled |= bic_lookup(optarg);
4420 		shown = 1;
4421 
4422 		return;
4423 	}
4424 
4425 	/*
4426 	 * --hide: do not show those specified
4427 	 *  multiple invocations simply clear more bits in enabled mask
4428 	 */
4429 	bic_enabled &= ~bic_lookup(optarg);
4430 }
4431 
4432 void cmdline(int argc, char **argv)
4433 {
4434 	int opt;
4435 	int option_index = 0;
4436 	static struct option long_options[] = {
4437 		{"add",		required_argument,	0, 'a'},
4438 		{"Dump",	no_argument,		0, 'D'},
4439 		{"debug",	no_argument,		0, 'd'},
4440 		{"interval",	required_argument,	0, 'i'},
4441 		{"help",	no_argument,		0, 'h'},
4442 		{"hide",	required_argument,	0, 'H'},	// meh, -h taken by --help
4443 		{"Joules",	no_argument,		0, 'J'},
4444 		{"out",		required_argument,	0, 'o'},
4445 		{"Package",	no_argument,		0, 'p'},
4446 		{"processor",	no_argument,		0, 'p'},
4447 		{"show",	required_argument,	0, 's'},
4448 		{"Summary",	no_argument,		0, 'S'},
4449 		{"TCC",		required_argument,	0, 'T'},
4450 		{"version",	no_argument,		0, 'v' },
4451 		{0,		0,			0,  0 }
4452 	};
4453 
4454 	progname = argv[0];
4455 
4456 	while ((opt = getopt_long_only(argc, argv, "+C:c:Ddhi:JM:m:o:PpST:v",
4457 				long_options, &option_index)) != -1) {
4458 		switch (opt) {
4459 		case 'a':
4460 			parse_add_command(optarg);
4461 			break;
4462 		case 'D':
4463 			dump_only++;
4464 			break;
4465 		case 'd':
4466 			debug++;
4467 			break;
4468 		case 'H':
4469 			parse_show_hide(optarg, HIDE_LIST);
4470 			break;
4471 		case 'h':
4472 		default:
4473 			help();
4474 			exit(1);
4475 		case 'i':
4476 			{
4477 				double interval = strtod(optarg, NULL);
4478 
4479 				if (interval < 0.001) {
4480 					fprintf(outf, "interval %f seconds is too small\n",
4481 						interval);
4482 					exit(2);
4483 				}
4484 
4485 				interval_ts.tv_sec = interval;
4486 				interval_ts.tv_nsec = (interval - interval_ts.tv_sec) * 1000000000;
4487 			}
4488 			break;
4489 		case 'J':
4490 			rapl_joules++;
4491 			break;
4492 		case 'o':
4493 			outf = fopen_or_die(optarg, "w");
4494 			break;
4495 		case 'P':
4496 			show_pkg_only++;
4497 			break;
4498 		case 'p':
4499 			show_core_only++;
4500 			break;
4501 		case 's':
4502 			parse_show_hide(optarg, SHOW_LIST);
4503 			break;
4504 		case 'S':
4505 			summary_only++;
4506 			break;
4507 		case 'T':
4508 			tcc_activation_temp_override = atoi(optarg);
4509 			break;
4510 		case 'v':
4511 			print_version();
4512 			exit(0);
4513 			break;
4514 		}
4515 	}
4516 }
4517 
4518 int main(int argc, char **argv)
4519 {
4520 	outf = stderr;
4521 
4522 	cmdline(argc, argv);
4523 
4524 	if (debug)
4525 		print_version();
4526 
4527 	turbostat_init();
4528 
4529 	/* dump counters and exit */
4530 	if (dump_only)
4531 		return get_and_dump_counters();
4532 
4533 	/*
4534 	 * if any params left, it must be a command to fork
4535 	 */
4536 	if (argc - optind)
4537 		return fork_it(argv + optind);
4538 	else
4539 		turbostat_loop();
4540 
4541 	return 0;
4542 }
4543