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