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