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