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