xref: /openbmc/linux/tools/power/x86/turbostat/turbostat.c (revision e6f9bb3cc63346e457405ef30209b3d2e18c5992)
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 <stdarg.h>
25 #include <stdio.h>
26 #include <err.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <sys/stat.h>
31 #include <sys/resource.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <sys/time.h>
35 #include <stdlib.h>
36 #include <dirent.h>
37 #include <string.h>
38 #include <ctype.h>
39 #include <sched.h>
40 #include <cpuid.h>
41 
42 char *proc_stat = "/proc/stat";
43 unsigned int interval_sec = 5;	/* set with -i interval_sec */
44 unsigned int verbose;		/* set with -v */
45 unsigned int rapl_verbose;	/* set with -R */
46 unsigned int thermal_verbose;	/* set with -T */
47 unsigned int summary_only;	/* set with -s */
48 unsigned int skip_c0;
49 unsigned int skip_c1;
50 unsigned int do_nhm_cstates;
51 unsigned int do_snb_cstates;
52 unsigned int do_c8_c9_c10;
53 unsigned int do_slm_cstates;
54 unsigned int use_c1_residency_msr;
55 unsigned int has_aperf;
56 unsigned int has_epb;
57 unsigned int units = 1000000000;	/* Ghz etc */
58 unsigned int genuine_intel;
59 unsigned int has_invariant_tsc;
60 unsigned int do_nehalem_platform_info;
61 unsigned int do_nehalem_turbo_ratio_limit;
62 unsigned int do_ivt_turbo_ratio_limit;
63 unsigned int extra_msr_offset32;
64 unsigned int extra_msr_offset64;
65 unsigned int extra_delta_offset32;
66 unsigned int extra_delta_offset64;
67 int do_smi;
68 double bclk;
69 unsigned int show_pkg;
70 unsigned int show_core;
71 unsigned int show_cpu;
72 unsigned int show_pkg_only;
73 unsigned int show_core_only;
74 char *output_buffer, *outp;
75 unsigned int do_rapl;
76 unsigned int do_dts;
77 unsigned int do_ptm;
78 unsigned int tcc_activation_temp;
79 unsigned int tcc_activation_temp_override;
80 double rapl_power_units, rapl_energy_units, rapl_time_units;
81 double rapl_joule_counter_range;
82 
83 #define RAPL_PKG		(1 << 0)
84 					/* 0x610 MSR_PKG_POWER_LIMIT */
85 					/* 0x611 MSR_PKG_ENERGY_STATUS */
86 #define RAPL_PKG_PERF_STATUS	(1 << 1)
87 					/* 0x613 MSR_PKG_PERF_STATUS */
88 #define RAPL_PKG_POWER_INFO	(1 << 2)
89 					/* 0x614 MSR_PKG_POWER_INFO */
90 
91 #define RAPL_DRAM		(1 << 3)
92 					/* 0x618 MSR_DRAM_POWER_LIMIT */
93 					/* 0x619 MSR_DRAM_ENERGY_STATUS */
94 					/* 0x61c MSR_DRAM_POWER_INFO */
95 #define RAPL_DRAM_PERF_STATUS	(1 << 4)
96 					/* 0x61b MSR_DRAM_PERF_STATUS */
97 
98 #define RAPL_CORES		(1 << 5)
99 					/* 0x638 MSR_PP0_POWER_LIMIT */
100 					/* 0x639 MSR_PP0_ENERGY_STATUS */
101 #define RAPL_CORE_POLICY	(1 << 6)
102 					/* 0x63a MSR_PP0_POLICY */
103 
104 
105 #define RAPL_GFX		(1 << 7)
106 					/* 0x640 MSR_PP1_POWER_LIMIT */
107 					/* 0x641 MSR_PP1_ENERGY_STATUS */
108 					/* 0x642 MSR_PP1_POLICY */
109 #define	TJMAX_DEFAULT	100
110 
111 #define MAX(a, b) ((a) > (b) ? (a) : (b))
112 
113 int aperf_mperf_unstable;
114 int backwards_count;
115 char *progname;
116 
117 cpu_set_t *cpu_present_set, *cpu_affinity_set;
118 size_t cpu_present_setsize, cpu_affinity_setsize;
119 
120 struct thread_data {
121 	unsigned long long tsc;
122 	unsigned long long aperf;
123 	unsigned long long mperf;
124 	unsigned long long c1;
125 	unsigned long long extra_msr64;
126 	unsigned long long extra_delta64;
127 	unsigned long long extra_msr32;
128 	unsigned long long extra_delta32;
129 	unsigned int smi_count;
130 	unsigned int cpu_id;
131 	unsigned int flags;
132 #define CPU_IS_FIRST_THREAD_IN_CORE	0x2
133 #define CPU_IS_FIRST_CORE_IN_PACKAGE	0x4
134 } *thread_even, *thread_odd;
135 
136 struct core_data {
137 	unsigned long long c3;
138 	unsigned long long c6;
139 	unsigned long long c7;
140 	unsigned int core_temp_c;
141 	unsigned int core_id;
142 } *core_even, *core_odd;
143 
144 struct pkg_data {
145 	unsigned long long pc2;
146 	unsigned long long pc3;
147 	unsigned long long pc6;
148 	unsigned long long pc7;
149 	unsigned long long pc8;
150 	unsigned long long pc9;
151 	unsigned long long pc10;
152 	unsigned int package_id;
153 	unsigned int energy_pkg;	/* MSR_PKG_ENERGY_STATUS */
154 	unsigned int energy_dram;	/* MSR_DRAM_ENERGY_STATUS */
155 	unsigned int energy_cores;	/* MSR_PP0_ENERGY_STATUS */
156 	unsigned int energy_gfx;	/* MSR_PP1_ENERGY_STATUS */
157 	unsigned int rapl_pkg_perf_status;	/* MSR_PKG_PERF_STATUS */
158 	unsigned int rapl_dram_perf_status;	/* MSR_DRAM_PERF_STATUS */
159 	unsigned int pkg_temp_c;
160 
161 } *package_even, *package_odd;
162 
163 #define ODD_COUNTERS thread_odd, core_odd, package_odd
164 #define EVEN_COUNTERS thread_even, core_even, package_even
165 
166 #define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \
167 	(thread_base + (pkg_no) * topo.num_cores_per_pkg * \
168 		topo.num_threads_per_core + \
169 		(core_no) * topo.num_threads_per_core + (thread_no))
170 #define GET_CORE(core_base, core_no, pkg_no) \
171 	(core_base + (pkg_no) * topo.num_cores_per_pkg + (core_no))
172 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
173 
174 struct system_summary {
175 	struct thread_data threads;
176 	struct core_data cores;
177 	struct pkg_data packages;
178 } sum, average;
179 
180 
181 struct topo_params {
182 	int num_packages;
183 	int num_cpus;
184 	int num_cores;
185 	int max_cpu_num;
186 	int num_cores_per_pkg;
187 	int num_threads_per_core;
188 } topo;
189 
190 struct timeval tv_even, tv_odd, tv_delta;
191 
192 void setup_all_buffers(void);
193 
194 int cpu_is_not_present(int cpu)
195 {
196 	return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
197 }
198 /*
199  * run func(thread, core, package) in topology order
200  * skip non-present cpus
201  */
202 
203 int for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
204 	struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
205 {
206 	int retval, pkg_no, core_no, thread_no;
207 
208 	for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
209 		for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
210 			for (thread_no = 0; thread_no <
211 				topo.num_threads_per_core; ++thread_no) {
212 				struct thread_data *t;
213 				struct core_data *c;
214 				struct pkg_data *p;
215 
216 				t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
217 
218 				if (cpu_is_not_present(t->cpu_id))
219 					continue;
220 
221 				c = GET_CORE(core_base, core_no, pkg_no);
222 				p = GET_PKG(pkg_base, pkg_no);
223 
224 				retval = func(t, c, p);
225 				if (retval)
226 					return retval;
227 			}
228 		}
229 	}
230 	return 0;
231 }
232 
233 int cpu_migrate(int cpu)
234 {
235 	CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
236 	CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
237 	if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1)
238 		return -1;
239 	else
240 		return 0;
241 }
242 
243 int get_msr(int cpu, off_t offset, unsigned long long *msr)
244 {
245 	ssize_t retval;
246 	char pathname[32];
247 	int fd;
248 
249 	sprintf(pathname, "/dev/cpu/%d/msr", cpu);
250 	fd = open(pathname, O_RDONLY);
251 	if (fd < 0)
252 		return -1;
253 
254 	retval = pread(fd, msr, sizeof *msr, offset);
255 	close(fd);
256 
257 	if (retval != sizeof *msr) {
258 		fprintf(stderr, "%s offset 0x%llx read failed\n", pathname, (unsigned long long)offset);
259 		return -1;
260 	}
261 
262 	return 0;
263 }
264 
265 void print_header(void)
266 {
267 	if (show_pkg)
268 		outp += sprintf(outp, "pk");
269 	if (show_pkg)
270 		outp += sprintf(outp, " ");
271 	if (show_core)
272 		outp += sprintf(outp, "cor");
273 	if (show_cpu)
274 		outp += sprintf(outp, " CPU");
275 	if (show_pkg || show_core || show_cpu)
276 		outp += sprintf(outp, " ");
277 	if (do_nhm_cstates)
278 		outp += sprintf(outp, "   %%c0");
279 	if (has_aperf)
280 		outp += sprintf(outp, "  GHz");
281 	outp += sprintf(outp, "  TSC");
282 	if (do_smi)
283 		outp += sprintf(outp, " SMI");
284 	if (extra_delta_offset32)
285 		outp += sprintf(outp, "  count 0x%03X", extra_delta_offset32);
286 	if (extra_delta_offset64)
287 		outp += sprintf(outp, "  COUNT 0x%03X", extra_delta_offset64);
288 	if (extra_msr_offset32)
289 		outp += sprintf(outp, "   MSR 0x%03X", extra_msr_offset32);
290 	if (extra_msr_offset64)
291 		outp += sprintf(outp, "           MSR 0x%03X", extra_msr_offset64);
292 	if (do_nhm_cstates)
293 		outp += sprintf(outp, "    %%c1");
294 	if (do_nhm_cstates && !do_slm_cstates)
295 		outp += sprintf(outp, "    %%c3");
296 	if (do_nhm_cstates)
297 		outp += sprintf(outp, "    %%c6");
298 	if (do_snb_cstates)
299 		outp += sprintf(outp, "    %%c7");
300 
301 	if (do_dts)
302 		outp += sprintf(outp, " CTMP");
303 	if (do_ptm)
304 		outp += sprintf(outp, " PTMP");
305 
306 	if (do_snb_cstates)
307 		outp += sprintf(outp, "   %%pc2");
308 	if (do_nhm_cstates && !do_slm_cstates)
309 		outp += sprintf(outp, "   %%pc3");
310 	if (do_nhm_cstates && !do_slm_cstates)
311 		outp += sprintf(outp, "   %%pc6");
312 	if (do_snb_cstates)
313 		outp += sprintf(outp, "   %%pc7");
314 	if (do_c8_c9_c10) {
315 		outp += sprintf(outp, "   %%pc8");
316 		outp += sprintf(outp, "   %%pc9");
317 		outp += sprintf(outp, "  %%pc10");
318 	}
319 
320 	if (do_rapl & RAPL_PKG)
321 		outp += sprintf(outp, "  Pkg_W");
322 	if (do_rapl & RAPL_CORES)
323 		outp += sprintf(outp, "  Cor_W");
324 	if (do_rapl & RAPL_GFX)
325 		outp += sprintf(outp, " GFX_W");
326 	if (do_rapl & RAPL_DRAM)
327 		outp += sprintf(outp, " RAM_W");
328 	if (do_rapl & RAPL_PKG_PERF_STATUS)
329 		outp += sprintf(outp, " PKG_%%");
330 	if (do_rapl & RAPL_DRAM_PERF_STATUS)
331 		outp += sprintf(outp, " RAM_%%");
332 
333 	outp += sprintf(outp, "\n");
334 }
335 
336 int dump_counters(struct thread_data *t, struct core_data *c,
337 	struct pkg_data *p)
338 {
339 	fprintf(stderr, "t %p, c %p, p %p\n", t, c, p);
340 
341 	if (t) {
342 		fprintf(stderr, "CPU: %d flags 0x%x\n", t->cpu_id, t->flags);
343 		fprintf(stderr, "TSC: %016llX\n", t->tsc);
344 		fprintf(stderr, "aperf: %016llX\n", t->aperf);
345 		fprintf(stderr, "mperf: %016llX\n", t->mperf);
346 		fprintf(stderr, "c1: %016llX\n", t->c1);
347 		fprintf(stderr, "msr0x%x: %08llX\n",
348 			extra_delta_offset32, t->extra_delta32);
349 		fprintf(stderr, "msr0x%x: %016llX\n",
350 			extra_delta_offset64, t->extra_delta64);
351 		fprintf(stderr, "msr0x%x: %08llX\n",
352 			extra_msr_offset32, t->extra_msr32);
353 		fprintf(stderr, "msr0x%x: %016llX\n",
354 			extra_msr_offset64, t->extra_msr64);
355 		if (do_smi)
356 			fprintf(stderr, "SMI: %08X\n", t->smi_count);
357 	}
358 
359 	if (c) {
360 		fprintf(stderr, "core: %d\n", c->core_id);
361 		fprintf(stderr, "c3: %016llX\n", c->c3);
362 		fprintf(stderr, "c6: %016llX\n", c->c6);
363 		fprintf(stderr, "c7: %016llX\n", c->c7);
364 		fprintf(stderr, "DTS: %dC\n", c->core_temp_c);
365 	}
366 
367 	if (p) {
368 		fprintf(stderr, "package: %d\n", p->package_id);
369 		fprintf(stderr, "pc2: %016llX\n", p->pc2);
370 		fprintf(stderr, "pc3: %016llX\n", p->pc3);
371 		fprintf(stderr, "pc6: %016llX\n", p->pc6);
372 		fprintf(stderr, "pc7: %016llX\n", p->pc7);
373 		fprintf(stderr, "pc8: %016llX\n", p->pc8);
374 		fprintf(stderr, "pc9: %016llX\n", p->pc9);
375 		fprintf(stderr, "pc10: %016llX\n", p->pc10);
376 		fprintf(stderr, "Joules PKG: %0X\n", p->energy_pkg);
377 		fprintf(stderr, "Joules COR: %0X\n", p->energy_cores);
378 		fprintf(stderr, "Joules GFX: %0X\n", p->energy_gfx);
379 		fprintf(stderr, "Joules RAM: %0X\n", p->energy_dram);
380 		fprintf(stderr, "Throttle PKG: %0X\n", p->rapl_pkg_perf_status);
381 		fprintf(stderr, "Throttle RAM: %0X\n", p->rapl_dram_perf_status);
382 		fprintf(stderr, "PTM: %dC\n", p->pkg_temp_c);
383 	}
384 	return 0;
385 }
386 
387 /*
388  * column formatting convention & formats
389  * package: "pk" 2 columns %2d
390  * core: "cor" 3 columns %3d
391  * CPU: "CPU" 3 columns %3d
392  * Pkg_W: %6.2
393  * Cor_W: %6.2
394  * GFX_W: %5.2
395  * RAM_W: %5.2
396  * GHz: "GHz" 3 columns %3.2
397  * TSC: "TSC" 3 columns %3.2
398  * SMI: "SMI" 4 columns %4d
399  * percentage " %pc3" %6.2
400  * Perf Status percentage: %5.2
401  * "CTMP" 4 columns %4d
402  */
403 int format_counters(struct thread_data *t, struct core_data *c,
404 	struct pkg_data *p)
405 {
406 	double interval_float;
407 	char *fmt5, *fmt6;
408 
409 	 /* if showing only 1st thread in core and this isn't one, bail out */
410 	if (show_core_only && !(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
411 		return 0;
412 
413 	 /* if showing only 1st thread in pkg and this isn't one, bail out */
414 	if (show_pkg_only && !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
415 		return 0;
416 
417 	interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
418 
419 	/* topo columns, print blanks on 1st (average) line */
420 	if (t == &average.threads) {
421 		if (show_pkg)
422 			outp += sprintf(outp, "  ");
423 		if (show_pkg && show_core)
424 			outp += sprintf(outp, " ");
425 		if (show_core)
426 			outp += sprintf(outp, "   ");
427 		if (show_cpu)
428 			outp += sprintf(outp, " " "   ");
429 	} else {
430 		if (show_pkg) {
431 			if (p)
432 				outp += sprintf(outp, "%2d", p->package_id);
433 			else
434 				outp += sprintf(outp, "  ");
435 		}
436 		if (show_pkg && show_core)
437 			outp += sprintf(outp, " ");
438 		if (show_core) {
439 			if (c)
440 				outp += sprintf(outp, "%3d", c->core_id);
441 			else
442 				outp += sprintf(outp, "   ");
443 		}
444 		if (show_cpu)
445 			outp += sprintf(outp, " %3d", t->cpu_id);
446 	}
447 	/* %c0 */
448 	if (do_nhm_cstates) {
449 		if (show_pkg || show_core || show_cpu)
450 			outp += sprintf(outp, " ");
451 		if (!skip_c0)
452 			outp += sprintf(outp, "%6.2f", 100.0 * t->mperf/t->tsc);
453 		else
454 			outp += sprintf(outp, "  ****");
455 	}
456 
457 	/* GHz */
458 	if (has_aperf) {
459 		if (!aperf_mperf_unstable) {
460 			outp += sprintf(outp, " %3.2f",
461 				1.0 * t->tsc / units * t->aperf /
462 				t->mperf / interval_float);
463 		} else {
464 			if (t->aperf > t->tsc || t->mperf > t->tsc) {
465 				outp += sprintf(outp, " ***");
466 			} else {
467 				outp += sprintf(outp, "%3.1f*",
468 					1.0 * t->tsc /
469 					units * t->aperf /
470 					t->mperf / interval_float);
471 			}
472 		}
473 	}
474 
475 	/* TSC */
476 	outp += sprintf(outp, "%5.2f", 1.0 * t->tsc/units/interval_float);
477 
478 	/* SMI */
479 	if (do_smi)
480 		outp += sprintf(outp, "%4d", t->smi_count);
481 
482 	/* delta */
483 	if (extra_delta_offset32)
484 		outp += sprintf(outp, "  %11llu", t->extra_delta32);
485 
486 	/* DELTA */
487 	if (extra_delta_offset64)
488 		outp += sprintf(outp, "  %11llu", t->extra_delta64);
489 	/* msr */
490 	if (extra_msr_offset32)
491 		outp += sprintf(outp, "  0x%08llx", t->extra_msr32);
492 
493 	/* MSR */
494 	if (extra_msr_offset64)
495 		outp += sprintf(outp, "  0x%016llx", t->extra_msr64);
496 
497 	if (do_nhm_cstates) {
498 		if (!skip_c1)
499 			outp += sprintf(outp, " %6.2f", 100.0 * t->c1/t->tsc);
500 		else
501 			outp += sprintf(outp, "  ****");
502 	}
503 
504 	/* print per-core data only for 1st thread in core */
505 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
506 		goto done;
507 
508 	if (do_nhm_cstates && !do_slm_cstates)
509 		outp += sprintf(outp, " %6.2f", 100.0 * c->c3/t->tsc);
510 	if (do_nhm_cstates)
511 		outp += sprintf(outp, " %6.2f", 100.0 * c->c6/t->tsc);
512 	if (do_snb_cstates)
513 		outp += sprintf(outp, " %6.2f", 100.0 * c->c7/t->tsc);
514 
515 	if (do_dts)
516 		outp += sprintf(outp, " %4d", c->core_temp_c);
517 
518 	/* print per-package data only for 1st core in package */
519 	if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
520 		goto done;
521 
522 	if (do_ptm)
523 		outp += sprintf(outp, " %4d", p->pkg_temp_c);
524 
525 	if (do_snb_cstates)
526 		outp += sprintf(outp, " %6.2f", 100.0 * p->pc2/t->tsc);
527 	if (do_nhm_cstates && !do_slm_cstates)
528 		outp += sprintf(outp, " %6.2f", 100.0 * p->pc3/t->tsc);
529 	if (do_nhm_cstates && !do_slm_cstates)
530 		outp += sprintf(outp, " %6.2f", 100.0 * p->pc6/t->tsc);
531 	if (do_snb_cstates)
532 		outp += sprintf(outp, " %6.2f", 100.0 * p->pc7/t->tsc);
533 	if (do_c8_c9_c10) {
534 		outp += sprintf(outp, " %6.2f", 100.0 * p->pc8/t->tsc);
535 		outp += sprintf(outp, " %6.2f", 100.0 * p->pc9/t->tsc);
536 		outp += sprintf(outp, " %6.2f", 100.0 * p->pc10/t->tsc);
537 	}
538 
539 	/*
540  	 * If measurement interval exceeds minimum RAPL Joule Counter range,
541  	 * indicate that results are suspect by printing "**" in fraction place.
542  	 */
543 	if (interval_float < rapl_joule_counter_range) {
544 		fmt5 = " %5.2f";
545 		fmt6 = " %6.2f";
546 	} else {
547 		fmt5 = " %3.0f**";
548 		fmt6 = " %4.0f**";
549 	}
550 
551 	if (do_rapl & RAPL_PKG)
552 		outp += sprintf(outp, fmt6, p->energy_pkg * rapl_energy_units / interval_float);
553 	if (do_rapl & RAPL_CORES)
554 		outp += sprintf(outp, fmt6, p->energy_cores * rapl_energy_units / interval_float);
555 	if (do_rapl & RAPL_GFX)
556 		outp += sprintf(outp, fmt5, p->energy_gfx * rapl_energy_units / interval_float);
557 	if (do_rapl & RAPL_DRAM)
558 		outp += sprintf(outp, fmt5, p->energy_dram * rapl_energy_units / interval_float);
559 	if (do_rapl & RAPL_PKG_PERF_STATUS )
560 		outp += sprintf(outp, fmt5, 100.0 * p->rapl_pkg_perf_status * rapl_time_units / interval_float);
561 	if (do_rapl & RAPL_DRAM_PERF_STATUS )
562 		outp += sprintf(outp, fmt5, 100.0 * p->rapl_dram_perf_status * rapl_time_units / interval_float);
563 
564 done:
565 	outp += sprintf(outp, "\n");
566 
567 	return 0;
568 }
569 
570 void flush_stdout()
571 {
572 	fputs(output_buffer, stdout);
573 	fflush(stdout);
574 	outp = output_buffer;
575 }
576 void flush_stderr()
577 {
578 	fputs(output_buffer, stderr);
579 	outp = output_buffer;
580 }
581 void format_all_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
582 {
583 	static int printed;
584 
585 	if (!printed || !summary_only)
586 		print_header();
587 
588 	if (topo.num_cpus > 1)
589 		format_counters(&average.threads, &average.cores,
590 			&average.packages);
591 
592 	printed = 1;
593 
594 	if (summary_only)
595 		return;
596 
597 	for_all_cpus(format_counters, t, c, p);
598 }
599 
600 #define DELTA_WRAP32(new, old)			\
601 	if (new > old) {			\
602 		old = new - old;		\
603 	} else {				\
604 		old = 0x100000000 + new - old;	\
605 	}
606 
607 void
608 delta_package(struct pkg_data *new, struct pkg_data *old)
609 {
610 	old->pc2 = new->pc2 - old->pc2;
611 	old->pc3 = new->pc3 - old->pc3;
612 	old->pc6 = new->pc6 - old->pc6;
613 	old->pc7 = new->pc7 - old->pc7;
614 	old->pc8 = new->pc8 - old->pc8;
615 	old->pc9 = new->pc9 - old->pc9;
616 	old->pc10 = new->pc10 - old->pc10;
617 	old->pkg_temp_c = new->pkg_temp_c;
618 
619 	DELTA_WRAP32(new->energy_pkg, old->energy_pkg);
620 	DELTA_WRAP32(new->energy_cores, old->energy_cores);
621 	DELTA_WRAP32(new->energy_gfx, old->energy_gfx);
622 	DELTA_WRAP32(new->energy_dram, old->energy_dram);
623 	DELTA_WRAP32(new->rapl_pkg_perf_status, old->rapl_pkg_perf_status);
624 	DELTA_WRAP32(new->rapl_dram_perf_status, old->rapl_dram_perf_status);
625 }
626 
627 void
628 delta_core(struct core_data *new, struct core_data *old)
629 {
630 	old->c3 = new->c3 - old->c3;
631 	old->c6 = new->c6 - old->c6;
632 	old->c7 = new->c7 - old->c7;
633 	old->core_temp_c = new->core_temp_c;
634 }
635 
636 /*
637  * old = new - old
638  */
639 void
640 delta_thread(struct thread_data *new, struct thread_data *old,
641 	struct core_data *core_delta)
642 {
643 	old->tsc = new->tsc - old->tsc;
644 
645 	/* check for TSC < 1 Mcycles over interval */
646 	if (old->tsc < (1000 * 1000))
647 		errx(-3, "Insanely slow TSC rate, TSC stops in idle?\n"
648 		     "You can disable all c-states by booting with \"idle=poll\"\n"
649 		     "or just the deep ones with \"processor.max_cstate=1\"");
650 
651 	old->c1 = new->c1 - old->c1;
652 
653 	if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
654 		old->aperf = new->aperf - old->aperf;
655 		old->mperf = new->mperf - old->mperf;
656 	} else {
657 
658 		if (!aperf_mperf_unstable) {
659 			fprintf(stderr, "%s: APERF or MPERF went backwards *\n", progname);
660 			fprintf(stderr, "* Frequency results do not cover entire interval *\n");
661 			fprintf(stderr, "* fix this by running Linux-2.6.30 or later *\n");
662 
663 			aperf_mperf_unstable = 1;
664 		}
665 		/*
666 		 * mperf delta is likely a huge "positive" number
667 		 * can not use it for calculating c0 time
668 		 */
669 		skip_c0 = 1;
670 		skip_c1 = 1;
671 	}
672 
673 
674 	if (use_c1_residency_msr) {
675 		/*
676 		 * Some models have a dedicated C1 residency MSR,
677 		 * which should be more accurate than the derivation below.
678 		 */
679 	} else {
680 		/*
681 		 * As counter collection is not atomic,
682 		 * it is possible for mperf's non-halted cycles + idle states
683 		 * to exceed TSC's all cycles: show c1 = 0% in that case.
684 		 */
685 		if ((old->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > old->tsc)
686 			old->c1 = 0;
687 		else {
688 			/* normal case, derive c1 */
689 			old->c1 = old->tsc - old->mperf - core_delta->c3
690 				- core_delta->c6 - core_delta->c7;
691 		}
692 	}
693 
694 	if (old->mperf == 0) {
695 		if (verbose > 1) fprintf(stderr, "cpu%d MPERF 0!\n", old->cpu_id);
696 		old->mperf = 1;	/* divide by 0 protection */
697 	}
698 
699 	old->extra_delta32 = new->extra_delta32 - old->extra_delta32;
700 	old->extra_delta32 &= 0xFFFFFFFF;
701 
702 	old->extra_delta64 = new->extra_delta64 - old->extra_delta64;
703 
704 	/*
705 	 * Extra MSR is just a snapshot, simply copy latest w/o subtracting
706 	 */
707 	old->extra_msr32 = new->extra_msr32;
708 	old->extra_msr64 = new->extra_msr64;
709 
710 	if (do_smi)
711 		old->smi_count = new->smi_count - old->smi_count;
712 }
713 
714 int delta_cpu(struct thread_data *t, struct core_data *c,
715 	struct pkg_data *p, struct thread_data *t2,
716 	struct core_data *c2, struct pkg_data *p2)
717 {
718 	/* calculate core delta only for 1st thread in core */
719 	if (t->flags & CPU_IS_FIRST_THREAD_IN_CORE)
720 		delta_core(c, c2);
721 
722 	/* always calculate thread delta */
723 	delta_thread(t, t2, c2);	/* c2 is core delta */
724 
725 	/* calculate package delta only for 1st core in package */
726 	if (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)
727 		delta_package(p, p2);
728 
729 	return 0;
730 }
731 
732 void clear_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
733 {
734 	t->tsc = 0;
735 	t->aperf = 0;
736 	t->mperf = 0;
737 	t->c1 = 0;
738 
739 	t->smi_count = 0;
740 	t->extra_delta32 = 0;
741 	t->extra_delta64 = 0;
742 
743 	/* tells format_counters to dump all fields from this set */
744 	t->flags = CPU_IS_FIRST_THREAD_IN_CORE | CPU_IS_FIRST_CORE_IN_PACKAGE;
745 
746 	c->c3 = 0;
747 	c->c6 = 0;
748 	c->c7 = 0;
749 	c->core_temp_c = 0;
750 
751 	p->pc2 = 0;
752 	p->pc3 = 0;
753 	p->pc6 = 0;
754 	p->pc7 = 0;
755 	p->pc8 = 0;
756 	p->pc9 = 0;
757 	p->pc10 = 0;
758 
759 	p->energy_pkg = 0;
760 	p->energy_dram = 0;
761 	p->energy_cores = 0;
762 	p->energy_gfx = 0;
763 	p->rapl_pkg_perf_status = 0;
764 	p->rapl_dram_perf_status = 0;
765 	p->pkg_temp_c = 0;
766 }
767 int sum_counters(struct thread_data *t, struct core_data *c,
768 	struct pkg_data *p)
769 {
770 	average.threads.tsc += t->tsc;
771 	average.threads.aperf += t->aperf;
772 	average.threads.mperf += t->mperf;
773 	average.threads.c1 += t->c1;
774 
775 	average.threads.extra_delta32 += t->extra_delta32;
776 	average.threads.extra_delta64 += t->extra_delta64;
777 
778 	/* sum per-core values only for 1st thread in core */
779 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
780 		return 0;
781 
782 	average.cores.c3 += c->c3;
783 	average.cores.c6 += c->c6;
784 	average.cores.c7 += c->c7;
785 
786 	average.cores.core_temp_c = MAX(average.cores.core_temp_c, c->core_temp_c);
787 
788 	/* sum per-pkg values only for 1st core in pkg */
789 	if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
790 		return 0;
791 
792 	average.packages.pc2 += p->pc2;
793 	average.packages.pc3 += p->pc3;
794 	average.packages.pc6 += p->pc6;
795 	average.packages.pc7 += p->pc7;
796 	average.packages.pc8 += p->pc8;
797 	average.packages.pc9 += p->pc9;
798 	average.packages.pc10 += p->pc10;
799 
800 	average.packages.energy_pkg += p->energy_pkg;
801 	average.packages.energy_dram += p->energy_dram;
802 	average.packages.energy_cores += p->energy_cores;
803 	average.packages.energy_gfx += p->energy_gfx;
804 
805 	average.packages.pkg_temp_c = MAX(average.packages.pkg_temp_c, p->pkg_temp_c);
806 
807 	average.packages.rapl_pkg_perf_status += p->rapl_pkg_perf_status;
808 	average.packages.rapl_dram_perf_status += p->rapl_dram_perf_status;
809 	return 0;
810 }
811 /*
812  * sum the counters for all cpus in the system
813  * compute the weighted average
814  */
815 void compute_average(struct thread_data *t, struct core_data *c,
816 	struct pkg_data *p)
817 {
818 	clear_counters(&average.threads, &average.cores, &average.packages);
819 
820 	for_all_cpus(sum_counters, t, c, p);
821 
822 	average.threads.tsc /= topo.num_cpus;
823 	average.threads.aperf /= topo.num_cpus;
824 	average.threads.mperf /= topo.num_cpus;
825 	average.threads.c1 /= topo.num_cpus;
826 
827 	average.threads.extra_delta32 /= topo.num_cpus;
828 	average.threads.extra_delta32 &= 0xFFFFFFFF;
829 
830 	average.threads.extra_delta64 /= topo.num_cpus;
831 
832 	average.cores.c3 /= topo.num_cores;
833 	average.cores.c6 /= topo.num_cores;
834 	average.cores.c7 /= topo.num_cores;
835 
836 	average.packages.pc2 /= topo.num_packages;
837 	average.packages.pc3 /= topo.num_packages;
838 	average.packages.pc6 /= topo.num_packages;
839 	average.packages.pc7 /= topo.num_packages;
840 
841 	average.packages.pc8 /= topo.num_packages;
842 	average.packages.pc9 /= topo.num_packages;
843 	average.packages.pc10 /= topo.num_packages;
844 }
845 
846 static unsigned long long rdtsc(void)
847 {
848 	unsigned int low, high;
849 
850 	asm volatile("rdtsc" : "=a" (low), "=d" (high));
851 
852 	return low | ((unsigned long long)high) << 32;
853 }
854 
855 
856 /*
857  * get_counters(...)
858  * migrate to cpu
859  * acquire and record local counters for that cpu
860  */
861 int get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
862 {
863 	int cpu = t->cpu_id;
864 	unsigned long long msr;
865 
866 	if (cpu_migrate(cpu)) {
867 		fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
868 		return -1;
869 	}
870 
871 	t->tsc = rdtsc();	/* we are running on local CPU of interest */
872 
873 	if (has_aperf) {
874 		if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
875 			return -3;
876 		if (get_msr(cpu, MSR_IA32_MPERF, &t->mperf))
877 			return -4;
878 	}
879 
880 	if (do_smi) {
881 		if (get_msr(cpu, MSR_SMI_COUNT, &msr))
882 			return -5;
883 		t->smi_count = msr & 0xFFFFFFFF;
884 	}
885 	if (extra_delta_offset32) {
886 		if (get_msr(cpu, extra_delta_offset32, &msr))
887 			return -5;
888 		t->extra_delta32 = msr & 0xFFFFFFFF;
889 	}
890 
891 	if (extra_delta_offset64)
892 		if (get_msr(cpu, extra_delta_offset64, &t->extra_delta64))
893 			return -5;
894 
895 	if (extra_msr_offset32) {
896 		if (get_msr(cpu, extra_msr_offset32, &msr))
897 			return -5;
898 		t->extra_msr32 = msr & 0xFFFFFFFF;
899 	}
900 
901 	if (extra_msr_offset64)
902 		if (get_msr(cpu, extra_msr_offset64, &t->extra_msr64))
903 			return -5;
904 
905 	if (use_c1_residency_msr) {
906 		if (get_msr(cpu, MSR_CORE_C1_RES, &t->c1))
907 			return -6;
908 	}
909 
910 	/* collect core counters only for 1st thread in core */
911 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
912 		return 0;
913 
914 	if (do_nhm_cstates && !do_slm_cstates) {
915 		if (get_msr(cpu, MSR_CORE_C3_RESIDENCY, &c->c3))
916 			return -6;
917 	}
918 
919 	if (do_nhm_cstates) {
920 		if (get_msr(cpu, MSR_CORE_C6_RESIDENCY, &c->c6))
921 			return -7;
922 	}
923 
924 	if (do_snb_cstates)
925 		if (get_msr(cpu, MSR_CORE_C7_RESIDENCY, &c->c7))
926 			return -8;
927 
928 	if (do_dts) {
929 		if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
930 			return -9;
931 		c->core_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
932 	}
933 
934 
935 	/* collect package counters only for 1st core in package */
936 	if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
937 		return 0;
938 
939 	if (do_nhm_cstates && !do_slm_cstates) {
940 		if (get_msr(cpu, MSR_PKG_C3_RESIDENCY, &p->pc3))
941 			return -9;
942 		if (get_msr(cpu, MSR_PKG_C6_RESIDENCY, &p->pc6))
943 			return -10;
944 	}
945 	if (do_snb_cstates) {
946 		if (get_msr(cpu, MSR_PKG_C2_RESIDENCY, &p->pc2))
947 			return -11;
948 		if (get_msr(cpu, MSR_PKG_C7_RESIDENCY, &p->pc7))
949 			return -12;
950 	}
951 	if (do_c8_c9_c10) {
952 		if (get_msr(cpu, MSR_PKG_C8_RESIDENCY, &p->pc8))
953 			return -13;
954 		if (get_msr(cpu, MSR_PKG_C9_RESIDENCY, &p->pc9))
955 			return -13;
956 		if (get_msr(cpu, MSR_PKG_C10_RESIDENCY, &p->pc10))
957 			return -13;
958 	}
959 	if (do_rapl & RAPL_PKG) {
960 		if (get_msr(cpu, MSR_PKG_ENERGY_STATUS, &msr))
961 			return -13;
962 		p->energy_pkg = msr & 0xFFFFFFFF;
963 	}
964 	if (do_rapl & RAPL_CORES) {
965 		if (get_msr(cpu, MSR_PP0_ENERGY_STATUS, &msr))
966 			return -14;
967 		p->energy_cores = msr & 0xFFFFFFFF;
968 	}
969 	if (do_rapl & RAPL_DRAM) {
970 		if (get_msr(cpu, MSR_DRAM_ENERGY_STATUS, &msr))
971 			return -15;
972 		p->energy_dram = msr & 0xFFFFFFFF;
973 	}
974 	if (do_rapl & RAPL_GFX) {
975 		if (get_msr(cpu, MSR_PP1_ENERGY_STATUS, &msr))
976 			return -16;
977 		p->energy_gfx = msr & 0xFFFFFFFF;
978 	}
979 	if (do_rapl & RAPL_PKG_PERF_STATUS) {
980 		if (get_msr(cpu, MSR_PKG_PERF_STATUS, &msr))
981 			return -16;
982 		p->rapl_pkg_perf_status = msr & 0xFFFFFFFF;
983 	}
984 	if (do_rapl & RAPL_DRAM_PERF_STATUS) {
985 		if (get_msr(cpu, MSR_DRAM_PERF_STATUS, &msr))
986 			return -16;
987 		p->rapl_dram_perf_status = msr & 0xFFFFFFFF;
988 	}
989 	if (do_ptm) {
990 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
991 			return -17;
992 		p->pkg_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
993 	}
994 	return 0;
995 }
996 
997 void print_verbose_header(void)
998 {
999 	unsigned long long msr;
1000 	unsigned int ratio;
1001 
1002 	if (!do_nehalem_platform_info)
1003 		return;
1004 
1005 	get_msr(0, MSR_NHM_PLATFORM_INFO, &msr);
1006 
1007 	fprintf(stderr, "cpu0: MSR_NHM_PLATFORM_INFO: 0x%08llx\n", msr);
1008 
1009 	ratio = (msr >> 40) & 0xFF;
1010 	fprintf(stderr, "%d * %.0f = %.0f MHz max efficiency\n",
1011 		ratio, bclk, ratio * bclk);
1012 
1013 	ratio = (msr >> 8) & 0xFF;
1014 	fprintf(stderr, "%d * %.0f = %.0f MHz TSC frequency\n",
1015 		ratio, bclk, ratio * bclk);
1016 
1017 	get_msr(0, MSR_IA32_POWER_CTL, &msr);
1018 	fprintf(stderr, "cpu0: MSR_IA32_POWER_CTL: 0x%08llx (C1E auto-promotion: %sabled)\n",
1019 		msr, msr & 0x2 ? "EN" : "DIS");
1020 
1021 	if (!do_ivt_turbo_ratio_limit)
1022 		goto print_nhm_turbo_ratio_limits;
1023 
1024 	get_msr(0, MSR_IVT_TURBO_RATIO_LIMIT, &msr);
1025 
1026 	fprintf(stderr, "cpu0: MSR_IVT_TURBO_RATIO_LIMIT: 0x%08llx\n", msr);
1027 
1028 	ratio = (msr >> 56) & 0xFF;
1029 	if (ratio)
1030 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 16 active cores\n",
1031 			ratio, bclk, ratio * bclk);
1032 
1033 	ratio = (msr >> 48) & 0xFF;
1034 	if (ratio)
1035 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 15 active cores\n",
1036 			ratio, bclk, ratio * bclk);
1037 
1038 	ratio = (msr >> 40) & 0xFF;
1039 	if (ratio)
1040 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 14 active cores\n",
1041 			ratio, bclk, ratio * bclk);
1042 
1043 	ratio = (msr >> 32) & 0xFF;
1044 	if (ratio)
1045 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 13 active cores\n",
1046 			ratio, bclk, ratio * bclk);
1047 
1048 	ratio = (msr >> 24) & 0xFF;
1049 	if (ratio)
1050 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 12 active cores\n",
1051 			ratio, bclk, ratio * bclk);
1052 
1053 	ratio = (msr >> 16) & 0xFF;
1054 	if (ratio)
1055 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 11 active cores\n",
1056 			ratio, bclk, ratio * bclk);
1057 
1058 	ratio = (msr >> 8) & 0xFF;
1059 	if (ratio)
1060 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 10 active cores\n",
1061 			ratio, bclk, ratio * bclk);
1062 
1063 	ratio = (msr >> 0) & 0xFF;
1064 	if (ratio)
1065 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 9 active cores\n",
1066 			ratio, bclk, ratio * bclk);
1067 
1068 print_nhm_turbo_ratio_limits:
1069 	get_msr(0, MSR_NHM_SNB_PKG_CST_CFG_CTL, &msr);
1070 
1071 #define SNB_C1_AUTO_UNDEMOTE              (1UL << 27)
1072 #define SNB_C3_AUTO_UNDEMOTE              (1UL << 28)
1073 
1074 	fprintf(stderr, "cpu0: MSR_NHM_SNB_PKG_CST_CFG_CTL: 0x%08llx", msr);
1075 
1076 	fprintf(stderr, " (%s%s%s%s%slocked: pkg-cstate-limit=%d: ",
1077 		(msr & SNB_C3_AUTO_UNDEMOTE) ? "UNdemote-C3, " : "",
1078 		(msr & SNB_C1_AUTO_UNDEMOTE) ? "UNdemote-C1, " : "",
1079 		(msr & NHM_C3_AUTO_DEMOTE) ? "demote-C3, " : "",
1080 		(msr & NHM_C1_AUTO_DEMOTE) ? "demote-C1, " : "",
1081 		(msr & (1 << 15)) ? "" : "UN",
1082 		(unsigned int)msr & 7);
1083 
1084 
1085 	switch(msr & 0x7) {
1086 	case 0:
1087 		fprintf(stderr, do_slm_cstates ? "no pkg states" : "pc0");
1088 		break;
1089 	case 1:
1090 		fprintf(stderr, do_slm_cstates ? "no pkg states" : do_snb_cstates ? "pc2" : "pc0");
1091 		break;
1092 	case 2:
1093 		fprintf(stderr, do_slm_cstates ? "invalid" : do_snb_cstates ? "pc6-noret" : "pc3");
1094 		break;
1095 	case 3:
1096 		fprintf(stderr, do_slm_cstates ? "invalid" : "pc6");
1097 		break;
1098 	case 4:
1099 		fprintf(stderr, do_slm_cstates ? "pc4" : "pc7");
1100 		break;
1101 	case 5:
1102 		fprintf(stderr, do_slm_cstates ? "invalid" : do_snb_cstates ? "pc7s" : "invalid");
1103 		break;
1104 	case 6:
1105 		fprintf(stderr, do_slm_cstates ? "pc6" : "invalid");
1106 		break;
1107 	case 7:
1108 		fprintf(stderr, do_slm_cstates ? "pc7" : "unlimited");
1109 		break;
1110 	default:
1111 		fprintf(stderr, "invalid");
1112 	}
1113 	fprintf(stderr, ")\n");
1114 
1115 	if (!do_nehalem_turbo_ratio_limit)
1116 		return;
1117 
1118 	get_msr(0, MSR_NHM_TURBO_RATIO_LIMIT, &msr);
1119 
1120 	fprintf(stderr, "cpu0: MSR_NHM_TURBO_RATIO_LIMIT: 0x%08llx\n", msr);
1121 
1122 	ratio = (msr >> 56) & 0xFF;
1123 	if (ratio)
1124 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 8 active cores\n",
1125 			ratio, bclk, ratio * bclk);
1126 
1127 	ratio = (msr >> 48) & 0xFF;
1128 	if (ratio)
1129 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 7 active cores\n",
1130 			ratio, bclk, ratio * bclk);
1131 
1132 	ratio = (msr >> 40) & 0xFF;
1133 	if (ratio)
1134 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 6 active cores\n",
1135 			ratio, bclk, ratio * bclk);
1136 
1137 	ratio = (msr >> 32) & 0xFF;
1138 	if (ratio)
1139 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 5 active cores\n",
1140 			ratio, bclk, ratio * bclk);
1141 
1142 	ratio = (msr >> 24) & 0xFF;
1143 	if (ratio)
1144 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 4 active cores\n",
1145 			ratio, bclk, ratio * bclk);
1146 
1147 	ratio = (msr >> 16) & 0xFF;
1148 	if (ratio)
1149 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 3 active cores\n",
1150 			ratio, bclk, ratio * bclk);
1151 
1152 	ratio = (msr >> 8) & 0xFF;
1153 	if (ratio)
1154 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 2 active cores\n",
1155 			ratio, bclk, ratio * bclk);
1156 
1157 	ratio = (msr >> 0) & 0xFF;
1158 	if (ratio)
1159 		fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 1 active cores\n",
1160 			ratio, bclk, ratio * bclk);
1161 }
1162 
1163 void free_all_buffers(void)
1164 {
1165 	CPU_FREE(cpu_present_set);
1166 	cpu_present_set = NULL;
1167 	cpu_present_set = 0;
1168 
1169 	CPU_FREE(cpu_affinity_set);
1170 	cpu_affinity_set = NULL;
1171 	cpu_affinity_setsize = 0;
1172 
1173 	free(thread_even);
1174 	free(core_even);
1175 	free(package_even);
1176 
1177 	thread_even = NULL;
1178 	core_even = NULL;
1179 	package_even = NULL;
1180 
1181 	free(thread_odd);
1182 	free(core_odd);
1183 	free(package_odd);
1184 
1185 	thread_odd = NULL;
1186 	core_odd = NULL;
1187 	package_odd = NULL;
1188 
1189 	free(output_buffer);
1190 	output_buffer = NULL;
1191 	outp = NULL;
1192 }
1193 
1194 /*
1195  * Open a file, and exit on failure
1196  */
1197 FILE *fopen_or_die(const char *path, const char *mode)
1198 {
1199 	FILE *filep = fopen(path, "r");
1200 	if (!filep)
1201 		err(1, "%s: open failed", path);
1202 	return filep;
1203 }
1204 
1205 /*
1206  * Parse a file containing a single int.
1207  */
1208 int parse_int_file(const char *fmt, ...)
1209 {
1210 	va_list args;
1211 	char path[PATH_MAX];
1212 	FILE *filep;
1213 	int value;
1214 
1215 	va_start(args, fmt);
1216 	vsnprintf(path, sizeof(path), fmt, args);
1217 	va_end(args);
1218 	filep = fopen_or_die(path, "r");
1219 	if (fscanf(filep, "%d", &value) != 1)
1220 		err(1, "%s: failed to parse number from file", path);
1221 	fclose(filep);
1222 	return value;
1223 }
1224 
1225 /*
1226  * cpu_is_first_sibling_in_core(cpu)
1227  * return 1 if given CPU is 1st HT sibling in the core
1228  */
1229 int cpu_is_first_sibling_in_core(int cpu)
1230 {
1231 	return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
1232 }
1233 
1234 /*
1235  * cpu_is_first_core_in_package(cpu)
1236  * return 1 if given CPU is 1st core in package
1237  */
1238 int cpu_is_first_core_in_package(int cpu)
1239 {
1240 	return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
1241 }
1242 
1243 int get_physical_package_id(int cpu)
1244 {
1245 	return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
1246 }
1247 
1248 int get_core_id(int cpu)
1249 {
1250 	return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
1251 }
1252 
1253 int get_num_ht_siblings(int cpu)
1254 {
1255 	char path[80];
1256 	FILE *filep;
1257 	int sib1, sib2;
1258 	int matches;
1259 	char character;
1260 
1261 	sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
1262 	filep = fopen_or_die(path, "r");
1263 	/*
1264 	 * file format:
1265 	 * if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4)
1266 	 * otherwinse 1 sibling (self).
1267 	 */
1268 	matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2);
1269 
1270 	fclose(filep);
1271 
1272 	if (matches == 3)
1273 		return 2;
1274 	else
1275 		return 1;
1276 }
1277 
1278 /*
1279  * run func(thread, core, package) in topology order
1280  * skip non-present cpus
1281  */
1282 
1283 int for_all_cpus_2(int (func)(struct thread_data *, struct core_data *,
1284 	struct pkg_data *, struct thread_data *, struct core_data *,
1285 	struct pkg_data *), struct thread_data *thread_base,
1286 	struct core_data *core_base, struct pkg_data *pkg_base,
1287 	struct thread_data *thread_base2, struct core_data *core_base2,
1288 	struct pkg_data *pkg_base2)
1289 {
1290 	int retval, pkg_no, core_no, thread_no;
1291 
1292 	for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
1293 		for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
1294 			for (thread_no = 0; thread_no <
1295 				topo.num_threads_per_core; ++thread_no) {
1296 				struct thread_data *t, *t2;
1297 				struct core_data *c, *c2;
1298 				struct pkg_data *p, *p2;
1299 
1300 				t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
1301 
1302 				if (cpu_is_not_present(t->cpu_id))
1303 					continue;
1304 
1305 				t2 = GET_THREAD(thread_base2, thread_no, core_no, pkg_no);
1306 
1307 				c = GET_CORE(core_base, core_no, pkg_no);
1308 				c2 = GET_CORE(core_base2, core_no, pkg_no);
1309 
1310 				p = GET_PKG(pkg_base, pkg_no);
1311 				p2 = GET_PKG(pkg_base2, pkg_no);
1312 
1313 				retval = func(t, c, p, t2, c2, p2);
1314 				if (retval)
1315 					return retval;
1316 			}
1317 		}
1318 	}
1319 	return 0;
1320 }
1321 
1322 /*
1323  * run func(cpu) on every cpu in /proc/stat
1324  * return max_cpu number
1325  */
1326 int for_all_proc_cpus(int (func)(int))
1327 {
1328 	FILE *fp;
1329 	int cpu_num;
1330 	int retval;
1331 
1332 	fp = fopen_or_die(proc_stat, "r");
1333 
1334 	retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
1335 	if (retval != 0)
1336 		err(1, "%s: failed to parse format", proc_stat);
1337 
1338 	while (1) {
1339 		retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
1340 		if (retval != 1)
1341 			break;
1342 
1343 		retval = func(cpu_num);
1344 		if (retval) {
1345 			fclose(fp);
1346 			return(retval);
1347 		}
1348 	}
1349 	fclose(fp);
1350 	return 0;
1351 }
1352 
1353 void re_initialize(void)
1354 {
1355 	free_all_buffers();
1356 	setup_all_buffers();
1357 	printf("turbostat: re-initialized with num_cpus %d\n", topo.num_cpus);
1358 }
1359 
1360 
1361 /*
1362  * count_cpus()
1363  * remember the last one seen, it will be the max
1364  */
1365 int count_cpus(int cpu)
1366 {
1367 	if (topo.max_cpu_num < cpu)
1368 		topo.max_cpu_num = cpu;
1369 
1370 	topo.num_cpus += 1;
1371 	return 0;
1372 }
1373 int mark_cpu_present(int cpu)
1374 {
1375 	CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
1376 	return 0;
1377 }
1378 
1379 void turbostat_loop()
1380 {
1381 	int retval;
1382 	int restarted = 0;
1383 
1384 restart:
1385 	restarted++;
1386 
1387 	retval = for_all_cpus(get_counters, EVEN_COUNTERS);
1388 	if (retval < -1) {
1389 		exit(retval);
1390 	} else if (retval == -1) {
1391 		if (restarted > 1) {
1392 			exit(retval);
1393 		}
1394 		re_initialize();
1395 		goto restart;
1396 	}
1397 	restarted = 0;
1398 	gettimeofday(&tv_even, (struct timezone *)NULL);
1399 
1400 	while (1) {
1401 		if (for_all_proc_cpus(cpu_is_not_present)) {
1402 			re_initialize();
1403 			goto restart;
1404 		}
1405 		sleep(interval_sec);
1406 		retval = for_all_cpus(get_counters, ODD_COUNTERS);
1407 		if (retval < -1) {
1408 			exit(retval);
1409 		} else if (retval == -1) {
1410 			re_initialize();
1411 			goto restart;
1412 		}
1413 		gettimeofday(&tv_odd, (struct timezone *)NULL);
1414 		timersub(&tv_odd, &tv_even, &tv_delta);
1415 		for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
1416 		compute_average(EVEN_COUNTERS);
1417 		format_all_counters(EVEN_COUNTERS);
1418 		flush_stdout();
1419 		sleep(interval_sec);
1420 		retval = for_all_cpus(get_counters, EVEN_COUNTERS);
1421 		if (retval < -1) {
1422 			exit(retval);
1423 		} else if (retval == -1) {
1424 			re_initialize();
1425 			goto restart;
1426 		}
1427 		gettimeofday(&tv_even, (struct timezone *)NULL);
1428 		timersub(&tv_even, &tv_odd, &tv_delta);
1429 		for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS);
1430 		compute_average(ODD_COUNTERS);
1431 		format_all_counters(ODD_COUNTERS);
1432 		flush_stdout();
1433 	}
1434 }
1435 
1436 void check_dev_msr()
1437 {
1438 	struct stat sb;
1439 
1440 	if (stat("/dev/cpu/0/msr", &sb))
1441 		err(-5, "no /dev/cpu/0/msr\n"
1442 		    "Try \"# modprobe msr\"");
1443 }
1444 
1445 void check_super_user()
1446 {
1447 	if (getuid() != 0)
1448 		errx(-6, "must be root");
1449 }
1450 
1451 int has_nehalem_turbo_ratio_limit(unsigned int family, unsigned int model)
1452 {
1453 	if (!genuine_intel)
1454 		return 0;
1455 
1456 	if (family != 6)
1457 		return 0;
1458 
1459 	switch (model) {
1460 	case 0x1A:	/* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
1461 	case 0x1E:	/* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
1462 	case 0x1F:	/* Core i7 and i5 Processor - Nehalem */
1463 	case 0x25:	/* Westmere Client - Clarkdale, Arrandale */
1464 	case 0x2C:	/* Westmere EP - Gulftown */
1465 	case 0x2A:	/* SNB */
1466 	case 0x2D:	/* SNB Xeon */
1467 	case 0x3A:	/* IVB */
1468 	case 0x3E:	/* IVB Xeon */
1469 	case 0x3C:	/* HSW */
1470 	case 0x3F:	/* HSX */
1471 	case 0x45:	/* HSW */
1472 	case 0x46:	/* HSW */
1473 	case 0x37:	/* BYT */
1474 	case 0x4D:	/* AVN */
1475 		return 1;
1476 	case 0x2E:	/* Nehalem-EX Xeon - Beckton */
1477 	case 0x2F:	/* Westmere-EX Xeon - Eagleton */
1478 	default:
1479 		return 0;
1480 	}
1481 }
1482 int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
1483 {
1484 	if (!genuine_intel)
1485 		return 0;
1486 
1487 	if (family != 6)
1488 		return 0;
1489 
1490 	switch (model) {
1491 	case 0x3E:	/* IVB Xeon */
1492 		return 1;
1493 	default:
1494 		return 0;
1495 	}
1496 }
1497 
1498 /*
1499  * print_epb()
1500  * Decode the ENERGY_PERF_BIAS MSR
1501  */
1502 int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1503 {
1504 	unsigned long long msr;
1505 	char *epb_string;
1506 	int cpu;
1507 
1508 	if (!has_epb)
1509 		return 0;
1510 
1511 	cpu = t->cpu_id;
1512 
1513 	/* EPB is per-package */
1514 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1515 		return 0;
1516 
1517 	if (cpu_migrate(cpu)) {
1518 		fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
1519 		return -1;
1520 	}
1521 
1522 	if (get_msr(cpu, MSR_IA32_ENERGY_PERF_BIAS, &msr))
1523 		return 0;
1524 
1525 	switch (msr & 0x7) {
1526 	case ENERGY_PERF_BIAS_PERFORMANCE:
1527 		epb_string = "performance";
1528 		break;
1529 	case ENERGY_PERF_BIAS_NORMAL:
1530 		epb_string = "balanced";
1531 		break;
1532 	case ENERGY_PERF_BIAS_POWERSAVE:
1533 		epb_string = "powersave";
1534 		break;
1535 	default:
1536 		epb_string = "custom";
1537 		break;
1538 	}
1539 	fprintf(stderr, "cpu%d: MSR_IA32_ENERGY_PERF_BIAS: 0x%08llx (%s)\n", cpu, msr, epb_string);
1540 
1541 	return 0;
1542 }
1543 
1544 #define	RAPL_POWER_GRANULARITY	0x7FFF	/* 15 bit power granularity */
1545 #define	RAPL_TIME_GRANULARITY	0x3F /* 6 bit time granularity */
1546 
1547 double get_tdp(model)
1548 {
1549 	unsigned long long msr;
1550 
1551 	if (do_rapl & RAPL_PKG_POWER_INFO)
1552 		if (!get_msr(0, MSR_PKG_POWER_INFO, &msr))
1553 			return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
1554 
1555 	switch (model) {
1556 	case 0x37:
1557 	case 0x4D:
1558 		return 30.0;
1559 	default:
1560 		return 135.0;
1561 	}
1562 }
1563 
1564 
1565 /*
1566  * rapl_probe()
1567  *
1568  * sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
1569  */
1570 void rapl_probe(unsigned int family, unsigned int model)
1571 {
1572 	unsigned long long msr;
1573 	unsigned int time_unit;
1574 	double tdp;
1575 
1576 	if (!genuine_intel)
1577 		return;
1578 
1579 	if (family != 6)
1580 		return;
1581 
1582 	switch (model) {
1583 	case 0x2A:
1584 	case 0x3A:
1585 	case 0x3C:	/* HSW */
1586 	case 0x45:	/* HSW */
1587 	case 0x46:	/* HSW */
1588 		do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
1589 		break;
1590 	case 0x3F:	/* HSX */
1591 		do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
1592 		break;
1593 	case 0x2D:
1594 	case 0x3E:
1595 		do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_PKG_PERF_STATUS | RAPL_DRAM_PERF_STATUS | RAPL_PKG_POWER_INFO;
1596 		break;
1597 	case 0x37:	/* BYT */
1598 	case 0x4D:	/* AVN */
1599 		do_rapl = RAPL_PKG | RAPL_CORES ;
1600 		break;
1601 	default:
1602 		return;
1603 	}
1604 
1605 	/* units on package 0, verify later other packages match */
1606 	if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr))
1607 		return;
1608 
1609 	rapl_power_units = 1.0 / (1 << (msr & 0xF));
1610 	if (model == 0x37)
1611 		rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
1612 	else
1613 		rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
1614 
1615 	time_unit = msr >> 16 & 0xF;
1616 	if (time_unit == 0)
1617 		time_unit = 0xA;
1618 
1619 	rapl_time_units = 1.0 / (1 << (time_unit));
1620 
1621 	tdp = get_tdp(model);
1622 
1623 	rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
1624 	if (verbose)
1625 		fprintf(stderr, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
1626 
1627 	return;
1628 }
1629 
1630 int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1631 {
1632 	unsigned long long msr;
1633 	unsigned int dts;
1634 	int cpu;
1635 
1636 	if (!(do_dts || do_ptm))
1637 		return 0;
1638 
1639 	cpu = t->cpu_id;
1640 
1641 	/* DTS is per-core, no need to print for each thread */
1642 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1643 		return 0;
1644 
1645 	if (cpu_migrate(cpu)) {
1646 		fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
1647 		return -1;
1648 	}
1649 
1650 	if (do_ptm && (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
1651 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
1652 			return 0;
1653 
1654 		dts = (msr >> 16) & 0x7F;
1655 		fprintf(stderr, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n",
1656 			cpu, msr, tcc_activation_temp - dts);
1657 
1658 #ifdef	THERM_DEBUG
1659 		if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
1660 			return 0;
1661 
1662 		dts = (msr >> 16) & 0x7F;
1663 		dts2 = (msr >> 8) & 0x7F;
1664 		fprintf(stderr, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
1665 			cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
1666 #endif
1667 	}
1668 
1669 
1670 	if (do_dts) {
1671 		unsigned int resolution;
1672 
1673 		if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
1674 			return 0;
1675 
1676 		dts = (msr >> 16) & 0x7F;
1677 		resolution = (msr >> 27) & 0xF;
1678 		fprintf(stderr, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
1679 			cpu, msr, tcc_activation_temp - dts, resolution);
1680 
1681 #ifdef THERM_DEBUG
1682 		if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
1683 			return 0;
1684 
1685 		dts = (msr >> 16) & 0x7F;
1686 		dts2 = (msr >> 8) & 0x7F;
1687 		fprintf(stderr, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
1688 			cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
1689 #endif
1690 	}
1691 
1692 	return 0;
1693 }
1694 
1695 void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
1696 {
1697 	fprintf(stderr, "cpu%d: %s: %sabled (%f Watts, %f sec, clamp %sabled)\n",
1698 		cpu, label,
1699 		((msr >> 15) & 1) ? "EN" : "DIS",
1700 		((msr >> 0) & 0x7FFF) * rapl_power_units,
1701 		(1.0 + (((msr >> 22) & 0x3)/4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
1702 		(((msr >> 16) & 1) ? "EN" : "DIS"));
1703 
1704 	return;
1705 }
1706 
1707 int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1708 {
1709 	unsigned long long msr;
1710 	int cpu;
1711 
1712 	if (!do_rapl)
1713 		return 0;
1714 
1715 	/* RAPL counters are per package, so print only for 1st thread/package */
1716 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1717 		return 0;
1718 
1719 	cpu = t->cpu_id;
1720 	if (cpu_migrate(cpu)) {
1721 		fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
1722 		return -1;
1723 	}
1724 
1725 	if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
1726 		return -1;
1727 
1728 	if (verbose) {
1729 		fprintf(stderr, "cpu%d: MSR_RAPL_POWER_UNIT: 0x%08llx "
1730 			"(%f Watts, %f Joules, %f sec.)\n", cpu, msr,
1731 			rapl_power_units, rapl_energy_units, rapl_time_units);
1732 	}
1733 	if (do_rapl & RAPL_PKG_POWER_INFO) {
1734 
1735 		if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
1736                 	return -5;
1737 
1738 
1739 		fprintf(stderr, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
1740 			cpu, msr,
1741 			((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
1742 			((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
1743 			((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
1744 			((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
1745 
1746 	}
1747 	if (do_rapl & RAPL_PKG) {
1748 
1749 		if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
1750 			return -9;
1751 
1752 		fprintf(stderr, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
1753 			cpu, msr, (msr >> 63) & 1 ? "": "UN");
1754 
1755 		print_power_limit_msr(cpu, msr, "PKG Limit #1");
1756 		fprintf(stderr, "cpu%d: PKG Limit #2: %sabled (%f Watts, %f* sec, clamp %sabled)\n",
1757 			cpu,
1758 			((msr >> 47) & 1) ? "EN" : "DIS",
1759 			((msr >> 32) & 0x7FFF) * rapl_power_units,
1760 			(1.0 + (((msr >> 54) & 0x3)/4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
1761 			((msr >> 48) & 1) ? "EN" : "DIS");
1762 	}
1763 
1764 	if (do_rapl & RAPL_DRAM) {
1765 		if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
1766                 	return -6;
1767 
1768 
1769 		fprintf(stderr, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
1770 			cpu, msr,
1771 			((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
1772 			((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
1773 			((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
1774 			((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
1775 
1776 
1777 		if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
1778 			return -9;
1779 		fprintf(stderr, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
1780 				cpu, msr, (msr >> 31) & 1 ? "": "UN");
1781 
1782 		print_power_limit_msr(cpu, msr, "DRAM Limit");
1783 	}
1784 	if (do_rapl & RAPL_CORE_POLICY) {
1785 		if (verbose) {
1786 			if (get_msr(cpu, MSR_PP0_POLICY, &msr))
1787 				return -7;
1788 
1789 			fprintf(stderr, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
1790 		}
1791 	}
1792 	if (do_rapl & RAPL_CORES) {
1793 		if (verbose) {
1794 
1795 			if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
1796 				return -9;
1797 			fprintf(stderr, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
1798 					cpu, msr, (msr >> 31) & 1 ? "": "UN");
1799 			print_power_limit_msr(cpu, msr, "Cores Limit");
1800 		}
1801 	}
1802 	if (do_rapl & RAPL_GFX) {
1803 		if (verbose) {
1804 			if (get_msr(cpu, MSR_PP1_POLICY, &msr))
1805 				return -8;
1806 
1807 			fprintf(stderr, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
1808 
1809 			if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
1810 				return -9;
1811 			fprintf(stderr, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
1812 					cpu, msr, (msr >> 31) & 1 ? "": "UN");
1813 			print_power_limit_msr(cpu, msr, "GFX Limit");
1814 		}
1815 	}
1816 	return 0;
1817 }
1818 
1819 
1820 int is_snb(unsigned int family, unsigned int model)
1821 {
1822 	if (!genuine_intel)
1823 		return 0;
1824 
1825 	switch (model) {
1826 	case 0x2A:
1827 	case 0x2D:
1828 	case 0x3A:	/* IVB */
1829 	case 0x3E:	/* IVB Xeon */
1830 	case 0x3C:	/* HSW */
1831 	case 0x3F:	/* HSW */
1832 	case 0x45:	/* HSW */
1833 	case 0x46:	/* HSW */
1834 		return 1;
1835 	}
1836 	return 0;
1837 }
1838 
1839 int has_c8_c9_c10(unsigned int family, unsigned int model)
1840 {
1841 	if (!genuine_intel)
1842 		return 0;
1843 
1844 	switch (model) {
1845 	case 0x45:
1846 		return 1;
1847 	}
1848 	return 0;
1849 }
1850 
1851 
1852 int is_slm(unsigned int family, unsigned int model)
1853 {
1854 	if (!genuine_intel)
1855 		return 0;
1856 	switch (model) {
1857 	case 0x37:	/* BYT */
1858 	case 0x4D:	/* AVN */
1859 		return 1;
1860 	}
1861 	return 0;
1862 }
1863 
1864 #define SLM_BCLK_FREQS 5
1865 double slm_freq_table[SLM_BCLK_FREQS] = { 83.3, 100.0, 133.3, 116.7, 80.0};
1866 
1867 double slm_bclk(void)
1868 {
1869 	unsigned long long msr = 3;
1870 	unsigned int i;
1871 	double freq;
1872 
1873 	if (get_msr(0, MSR_FSB_FREQ, &msr))
1874 		fprintf(stderr, "SLM BCLK: unknown\n");
1875 
1876 	i = msr & 0xf;
1877 	if (i >= SLM_BCLK_FREQS) {
1878 		fprintf(stderr, "SLM BCLK[%d] invalid\n", i);
1879 		msr = 3;
1880 	}
1881 	freq = slm_freq_table[i];
1882 
1883 	fprintf(stderr, "SLM BCLK: %.1f Mhz\n", freq);
1884 
1885 	return freq;
1886 }
1887 
1888 double discover_bclk(unsigned int family, unsigned int model)
1889 {
1890 	if (is_snb(family, model))
1891 		return 100.00;
1892 	else if (is_slm(family, model))
1893 		return slm_bclk();
1894 	else
1895 		return 133.33;
1896 }
1897 
1898 /*
1899  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
1900  * the Thermal Control Circuit (TCC) activates.
1901  * This is usually equal to tjMax.
1902  *
1903  * Older processors do not have this MSR, so there we guess,
1904  * but also allow cmdline over-ride with -T.
1905  *
1906  * Several MSR temperature values are in units of degrees-C
1907  * below this value, including the Digital Thermal Sensor (DTS),
1908  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
1909  */
1910 int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
1911 {
1912 	unsigned long long msr;
1913 	unsigned int target_c_local;
1914 	int cpu;
1915 
1916 	/* tcc_activation_temp is used only for dts or ptm */
1917 	if (!(do_dts || do_ptm))
1918 		return 0;
1919 
1920 	/* this is a per-package concept */
1921 	if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1922 		return 0;
1923 
1924 	cpu = t->cpu_id;
1925 	if (cpu_migrate(cpu)) {
1926 		fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
1927 		return -1;
1928 	}
1929 
1930 	if (tcc_activation_temp_override != 0) {
1931 		tcc_activation_temp = tcc_activation_temp_override;
1932 		fprintf(stderr, "cpu%d: Using cmdline TCC Target (%d C)\n",
1933 			cpu, tcc_activation_temp);
1934 		return 0;
1935 	}
1936 
1937 	/* Temperature Target MSR is Nehalem and newer only */
1938 	if (!do_nehalem_platform_info)
1939 		goto guess;
1940 
1941 	if (get_msr(0, MSR_IA32_TEMPERATURE_TARGET, &msr))
1942 		goto guess;
1943 
1944 	target_c_local = (msr >> 16) & 0x7F;
1945 
1946 	if (verbose)
1947 		fprintf(stderr, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n",
1948 			cpu, msr, target_c_local);
1949 
1950 	if (target_c_local < 85 || target_c_local > 127)
1951 		goto guess;
1952 
1953 	tcc_activation_temp = target_c_local;
1954 
1955 	return 0;
1956 
1957 guess:
1958 	tcc_activation_temp = TJMAX_DEFAULT;
1959 	fprintf(stderr, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n",
1960 		cpu, tcc_activation_temp);
1961 
1962 	return 0;
1963 }
1964 void check_cpuid()
1965 {
1966 	unsigned int eax, ebx, ecx, edx, max_level;
1967 	unsigned int fms, family, model, stepping;
1968 
1969 	eax = ebx = ecx = edx = 0;
1970 
1971 	__get_cpuid(0, &max_level, &ebx, &ecx, &edx);
1972 
1973 	if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
1974 		genuine_intel = 1;
1975 
1976 	if (verbose)
1977 		fprintf(stderr, "CPUID(0): %.4s%.4s%.4s ",
1978 			(char *)&ebx, (char *)&edx, (char *)&ecx);
1979 
1980 	__get_cpuid(1, &fms, &ebx, &ecx, &edx);
1981 	family = (fms >> 8) & 0xf;
1982 	model = (fms >> 4) & 0xf;
1983 	stepping = fms & 0xf;
1984 	if (family == 6 || family == 0xf)
1985 		model += ((fms >> 16) & 0xf) << 4;
1986 
1987 	if (verbose)
1988 		fprintf(stderr, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
1989 			max_level, family, model, stepping, family, model, stepping);
1990 
1991 	if (!(edx & (1 << 5)))
1992 		errx(1, "CPUID: no MSR");
1993 
1994 	/*
1995 	 * check max extended function levels of CPUID.
1996 	 * This is needed to check for invariant TSC.
1997 	 * This check is valid for both Intel and AMD.
1998 	 */
1999 	ebx = ecx = edx = 0;
2000 	__get_cpuid(0x80000000, &max_level, &ebx, &ecx, &edx);
2001 
2002 	if (max_level < 0x80000007)
2003 		errx(1, "CPUID: no invariant TSC (max_level 0x%x)", max_level);
2004 
2005 	/*
2006 	 * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
2007 	 * this check is valid for both Intel and AMD
2008 	 */
2009 	__get_cpuid(0x80000007, &eax, &ebx, &ecx, &edx);
2010 	has_invariant_tsc = edx & (1 << 8);
2011 
2012 	if (!has_invariant_tsc)
2013 		errx(1, "No invariant TSC");
2014 
2015 	/*
2016 	 * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
2017 	 * this check is valid for both Intel and AMD
2018 	 */
2019 
2020 	__get_cpuid(0x6, &eax, &ebx, &ecx, &edx);
2021 	has_aperf = ecx & (1 << 0);
2022 	do_dts = eax & (1 << 0);
2023 	do_ptm = eax & (1 << 6);
2024 	has_epb = ecx & (1 << 3);
2025 
2026 	if (verbose)
2027 		fprintf(stderr, "CPUID(6): %s%s%s%s\n",
2028 			has_aperf ? "APERF" : "No APERF!",
2029 			do_dts ? ", DTS" : "",
2030 			do_ptm ? ", PTM": "",
2031 			has_epb ? ", EPB": "");
2032 
2033 	if (!has_aperf)
2034 		errx(-1, "No APERF");
2035 
2036 	do_nehalem_platform_info = genuine_intel && has_invariant_tsc;
2037 	do_nhm_cstates = genuine_intel;	/* all Intel w/ non-stop TSC have NHM counters */
2038 	do_smi = do_nhm_cstates;
2039 	do_snb_cstates = is_snb(family, model);
2040 	do_c8_c9_c10 = has_c8_c9_c10(family, model);
2041 	do_slm_cstates = is_slm(family, model);
2042 	bclk = discover_bclk(family, model);
2043 
2044 	do_nehalem_turbo_ratio_limit = has_nehalem_turbo_ratio_limit(family, model);
2045 	do_ivt_turbo_ratio_limit = has_ivt_turbo_ratio_limit(family, model);
2046 	rapl_probe(family, model);
2047 
2048 	return;
2049 }
2050 
2051 
2052 void usage()
2053 {
2054 	errx(1, "%s: [-v][-R][-T][-p|-P|-S][-c MSR# | -s]][-C MSR#][-m MSR#][-M MSR#][-i interval_sec | command ...]\n",
2055 	     progname);
2056 }
2057 
2058 
2059 /*
2060  * in /dev/cpu/ return success for names that are numbers
2061  * ie. filter out ".", "..", "microcode".
2062  */
2063 int dir_filter(const struct dirent *dirp)
2064 {
2065 	if (isdigit(dirp->d_name[0]))
2066 		return 1;
2067 	else
2068 		return 0;
2069 }
2070 
2071 int open_dev_cpu_msr(int dummy1)
2072 {
2073 	return 0;
2074 }
2075 
2076 void topology_probe()
2077 {
2078 	int i;
2079 	int max_core_id = 0;
2080 	int max_package_id = 0;
2081 	int max_siblings = 0;
2082 	struct cpu_topology {
2083 		int core_id;
2084 		int physical_package_id;
2085 	} *cpus;
2086 
2087 	/* Initialize num_cpus, max_cpu_num */
2088 	topo.num_cpus = 0;
2089 	topo.max_cpu_num = 0;
2090 	for_all_proc_cpus(count_cpus);
2091 	if (!summary_only && topo.num_cpus > 1)
2092 		show_cpu = 1;
2093 
2094 	if (verbose > 1)
2095 		fprintf(stderr, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
2096 
2097 	cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
2098 	if (cpus == NULL)
2099 		err(1, "calloc cpus");
2100 
2101 	/*
2102 	 * Allocate and initialize cpu_present_set
2103 	 */
2104 	cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
2105 	if (cpu_present_set == NULL)
2106 		err(3, "CPU_ALLOC");
2107 	cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
2108 	CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
2109 	for_all_proc_cpus(mark_cpu_present);
2110 
2111 	/*
2112 	 * Allocate and initialize cpu_affinity_set
2113 	 */
2114 	cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
2115 	if (cpu_affinity_set == NULL)
2116 		err(3, "CPU_ALLOC");
2117 	cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
2118 	CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
2119 
2120 
2121 	/*
2122 	 * For online cpus
2123 	 * find max_core_id, max_package_id
2124 	 */
2125 	for (i = 0; i <= topo.max_cpu_num; ++i) {
2126 		int siblings;
2127 
2128 		if (cpu_is_not_present(i)) {
2129 			if (verbose > 1)
2130 				fprintf(stderr, "cpu%d NOT PRESENT\n", i);
2131 			continue;
2132 		}
2133 		cpus[i].core_id = get_core_id(i);
2134 		if (cpus[i].core_id > max_core_id)
2135 			max_core_id = cpus[i].core_id;
2136 
2137 		cpus[i].physical_package_id = get_physical_package_id(i);
2138 		if (cpus[i].physical_package_id > max_package_id)
2139 			max_package_id = cpus[i].physical_package_id;
2140 
2141 		siblings = get_num_ht_siblings(i);
2142 		if (siblings > max_siblings)
2143 			max_siblings = siblings;
2144 		if (verbose > 1)
2145 			fprintf(stderr, "cpu %d pkg %d core %d\n",
2146 				i, cpus[i].physical_package_id, cpus[i].core_id);
2147 	}
2148 	topo.num_cores_per_pkg = max_core_id + 1;
2149 	if (verbose > 1)
2150 		fprintf(stderr, "max_core_id %d, sizing for %d cores per package\n",
2151 			max_core_id, topo.num_cores_per_pkg);
2152 	if (!summary_only && topo.num_cores_per_pkg > 1)
2153 		show_core = 1;
2154 
2155 	topo.num_packages = max_package_id + 1;
2156 	if (verbose > 1)
2157 		fprintf(stderr, "max_package_id %d, sizing for %d packages\n",
2158 			max_package_id, topo.num_packages);
2159 	if (!summary_only && topo.num_packages > 1)
2160 		show_pkg = 1;
2161 
2162 	topo.num_threads_per_core = max_siblings;
2163 	if (verbose > 1)
2164 		fprintf(stderr, "max_siblings %d\n", max_siblings);
2165 
2166 	free(cpus);
2167 }
2168 
2169 void
2170 allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
2171 {
2172 	int i;
2173 
2174 	*t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
2175 		topo.num_packages, sizeof(struct thread_data));
2176 	if (*t == NULL)
2177 		goto error;
2178 
2179 	for (i = 0; i < topo.num_threads_per_core *
2180 		topo.num_cores_per_pkg * topo.num_packages; i++)
2181 		(*t)[i].cpu_id = -1;
2182 
2183 	*c = calloc(topo.num_cores_per_pkg * topo.num_packages,
2184 		sizeof(struct core_data));
2185 	if (*c == NULL)
2186 		goto error;
2187 
2188 	for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
2189 		(*c)[i].core_id = -1;
2190 
2191 	*p = calloc(topo.num_packages, sizeof(struct pkg_data));
2192 	if (*p == NULL)
2193 		goto error;
2194 
2195 	for (i = 0; i < topo.num_packages; i++)
2196 		(*p)[i].package_id = i;
2197 
2198 	return;
2199 error:
2200 	err(1, "calloc counters");
2201 }
2202 /*
2203  * init_counter()
2204  *
2205  * set cpu_id, core_num, pkg_num
2206  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
2207  *
2208  * increment topo.num_cores when 1st core in pkg seen
2209  */
2210 void init_counter(struct thread_data *thread_base, struct core_data *core_base,
2211 	struct pkg_data *pkg_base, int thread_num, int core_num,
2212 	int pkg_num, int cpu_id)
2213 {
2214 	struct thread_data *t;
2215 	struct core_data *c;
2216 	struct pkg_data *p;
2217 
2218 	t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
2219 	c = GET_CORE(core_base, core_num, pkg_num);
2220 	p = GET_PKG(pkg_base, pkg_num);
2221 
2222 	t->cpu_id = cpu_id;
2223 	if (thread_num == 0) {
2224 		t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
2225 		if (cpu_is_first_core_in_package(cpu_id))
2226 			t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
2227 	}
2228 
2229 	c->core_id = core_num;
2230 	p->package_id = pkg_num;
2231 }
2232 
2233 
2234 int initialize_counters(int cpu_id)
2235 {
2236 	int my_thread_id, my_core_id, my_package_id;
2237 
2238 	my_package_id = get_physical_package_id(cpu_id);
2239 	my_core_id = get_core_id(cpu_id);
2240 
2241 	if (cpu_is_first_sibling_in_core(cpu_id)) {
2242 		my_thread_id = 0;
2243 		topo.num_cores++;
2244 	} else {
2245 		my_thread_id = 1;
2246 	}
2247 
2248 	init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
2249 	init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
2250 	return 0;
2251 }
2252 
2253 void allocate_output_buffer()
2254 {
2255 	output_buffer = calloc(1, (1 + topo.num_cpus) * 256);
2256 	outp = output_buffer;
2257 	if (outp == NULL)
2258 		err(-1, "calloc output buffer");
2259 }
2260 
2261 void setup_all_buffers(void)
2262 {
2263 	topology_probe();
2264 	allocate_counters(&thread_even, &core_even, &package_even);
2265 	allocate_counters(&thread_odd, &core_odd, &package_odd);
2266 	allocate_output_buffer();
2267 	for_all_proc_cpus(initialize_counters);
2268 }
2269 void turbostat_init()
2270 {
2271 	check_cpuid();
2272 
2273 	check_dev_msr();
2274 	check_super_user();
2275 
2276 	setup_all_buffers();
2277 
2278 	if (verbose)
2279 		print_verbose_header();
2280 
2281 	if (verbose)
2282 		for_all_cpus(print_epb, ODD_COUNTERS);
2283 
2284 	if (verbose)
2285 		for_all_cpus(print_rapl, ODD_COUNTERS);
2286 
2287 	for_all_cpus(set_temperature_target, ODD_COUNTERS);
2288 
2289 	if (verbose)
2290 		for_all_cpus(print_thermal, ODD_COUNTERS);
2291 }
2292 
2293 int fork_it(char **argv)
2294 {
2295 	pid_t child_pid;
2296 	int status;
2297 
2298 	status = for_all_cpus(get_counters, EVEN_COUNTERS);
2299 	if (status)
2300 		exit(status);
2301 	/* clear affinity side-effect of get_counters() */
2302 	sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
2303 	gettimeofday(&tv_even, (struct timezone *)NULL);
2304 
2305 	child_pid = fork();
2306 	if (!child_pid) {
2307 		/* child */
2308 		execvp(argv[0], argv);
2309 	} else {
2310 
2311 		/* parent */
2312 		if (child_pid == -1)
2313 			err(1, "fork");
2314 
2315 		signal(SIGINT, SIG_IGN);
2316 		signal(SIGQUIT, SIG_IGN);
2317 		if (waitpid(child_pid, &status, 0) == -1)
2318 			err(status, "waitpid");
2319 	}
2320 	/*
2321 	 * n.b. fork_it() does not check for errors from for_all_cpus()
2322 	 * because re-starting is problematic when forking
2323 	 */
2324 	for_all_cpus(get_counters, ODD_COUNTERS);
2325 	gettimeofday(&tv_odd, (struct timezone *)NULL);
2326 	timersub(&tv_odd, &tv_even, &tv_delta);
2327 	for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
2328 	compute_average(EVEN_COUNTERS);
2329 	format_all_counters(EVEN_COUNTERS);
2330 	flush_stderr();
2331 
2332 	fprintf(stderr, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
2333 
2334 	return status;
2335 }
2336 
2337 void cmdline(int argc, char **argv)
2338 {
2339 	int opt;
2340 
2341 	progname = argv[0];
2342 
2343 	while ((opt = getopt(argc, argv, "+pPSvi:sc:sC:m:M:RT:")) != -1) {
2344 		switch (opt) {
2345 		case 'p':
2346 			show_core_only++;
2347 			break;
2348 		case 'P':
2349 			show_pkg_only++;
2350 			break;
2351 		case 'S':
2352 			summary_only++;
2353 			break;
2354 		case 'v':
2355 			verbose++;
2356 			break;
2357 		case 'i':
2358 			interval_sec = atoi(optarg);
2359 			break;
2360 		case 'c':
2361 			sscanf(optarg, "%x", &extra_delta_offset32);
2362 			break;
2363 		case 'C':
2364 			sscanf(optarg, "%x", &extra_delta_offset64);
2365 			break;
2366 		case 'm':
2367 			sscanf(optarg, "%x", &extra_msr_offset32);
2368 			break;
2369 		case 'M':
2370 			sscanf(optarg, "%x", &extra_msr_offset64);
2371 			break;
2372 		case 'R':
2373 			rapl_verbose++;
2374 			break;
2375 		case 'T':
2376 			tcc_activation_temp_override = atoi(optarg);
2377 			break;
2378 		default:
2379 			usage();
2380 		}
2381 	}
2382 }
2383 
2384 int main(int argc, char **argv)
2385 {
2386 	cmdline(argc, argv);
2387 
2388 	if (verbose)
2389 		fprintf(stderr, "turbostat v3.6 Dec 2, 2013"
2390 			" - Len Brown <lenb@kernel.org>\n");
2391 
2392 	turbostat_init();
2393 
2394 	/*
2395 	 * if any params left, it must be a command to fork
2396 	 */
2397 	if (argc - optind)
2398 		return fork_it(argv + optind);
2399 	else
2400 		turbostat_loop();
2401 
2402 	return 0;
2403 }
2404