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