tools/power turbostat: add --enable Time_Of_Day_Seconds
[sfrench/cifs-2.6.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 void turbostat_loop()
2604 {
2605         int retval;
2606         int restarted = 0;
2607
2608 restart:
2609         restarted++;
2610
2611         snapshot_proc_sysfs_files();
2612         retval = for_all_cpus(get_counters, EVEN_COUNTERS);
2613         if (retval < -1) {
2614                 exit(retval);
2615         } else if (retval == -1) {
2616                 if (restarted > 1) {
2617                         exit(retval);
2618                 }
2619                 re_initialize();
2620                 goto restart;
2621         }
2622         restarted = 0;
2623         gettimeofday(&tv_even, (struct timezone *)NULL);
2624
2625         while (1) {
2626                 if (for_all_proc_cpus(cpu_is_not_present)) {
2627                         re_initialize();
2628                         goto restart;
2629                 }
2630                 nanosleep(&interval_ts, NULL);
2631                 if (snapshot_proc_sysfs_files())
2632                         goto restart;
2633                 retval = for_all_cpus(get_counters, ODD_COUNTERS);
2634                 if (retval < -1) {
2635                         exit(retval);
2636                 } else if (retval == -1) {
2637                         re_initialize();
2638                         goto restart;
2639                 }
2640                 gettimeofday(&tv_odd, (struct timezone *)NULL);
2641                 timersub(&tv_odd, &tv_even, &tv_delta);
2642                 if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS)) {
2643                         re_initialize();
2644                         goto restart;
2645                 }
2646                 compute_average(EVEN_COUNTERS);
2647                 format_all_counters(EVEN_COUNTERS);
2648                 flush_output_stdout();
2649                 nanosleep(&interval_ts, NULL);
2650                 if (snapshot_proc_sysfs_files())
2651                         goto restart;
2652                 retval = for_all_cpus(get_counters, EVEN_COUNTERS);
2653                 if (retval < -1) {
2654                         exit(retval);
2655                 } else if (retval == -1) {
2656                         re_initialize();
2657                         goto restart;
2658                 }
2659                 gettimeofday(&tv_even, (struct timezone *)NULL);
2660                 timersub(&tv_even, &tv_odd, &tv_delta);
2661                 if (for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS)) {
2662                         re_initialize();
2663                         goto restart;
2664                 }
2665                 compute_average(ODD_COUNTERS);
2666                 format_all_counters(ODD_COUNTERS);
2667                 flush_output_stdout();
2668         }
2669 }
2670
2671 void check_dev_msr()
2672 {
2673         struct stat sb;
2674         char pathname[32];
2675
2676         sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
2677         if (stat(pathname, &sb))
2678                 if (system("/sbin/modprobe msr > /dev/null 2>&1"))
2679                         err(-5, "no /dev/cpu/0/msr, Try \"# modprobe msr\" ");
2680 }
2681
2682 void check_permissions()
2683 {
2684         struct __user_cap_header_struct cap_header_data;
2685         cap_user_header_t cap_header = &cap_header_data;
2686         struct __user_cap_data_struct cap_data_data;
2687         cap_user_data_t cap_data = &cap_data_data;
2688         extern int capget(cap_user_header_t hdrp, cap_user_data_t datap);
2689         int do_exit = 0;
2690         char pathname[32];
2691
2692         /* check for CAP_SYS_RAWIO */
2693         cap_header->pid = getpid();
2694         cap_header->version = _LINUX_CAPABILITY_VERSION;
2695         if (capget(cap_header, cap_data) < 0)
2696                 err(-6, "capget(2) failed");
2697
2698         if ((cap_data->effective & (1 << CAP_SYS_RAWIO)) == 0) {
2699                 do_exit++;
2700                 warnx("capget(CAP_SYS_RAWIO) failed,"
2701                         " try \"# setcap cap_sys_rawio=ep %s\"", progname);
2702         }
2703
2704         /* test file permissions */
2705         sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
2706         if (euidaccess(pathname, R_OK)) {
2707                 do_exit++;
2708                 warn("/dev/cpu/0/msr open failed, try chown or chmod +r /dev/cpu/*/msr");
2709         }
2710
2711         /* if all else fails, thell them to be root */
2712         if (do_exit)
2713                 if (getuid() != 0)
2714                         warnx("... or simply run as root");
2715
2716         if (do_exit)
2717                 exit(-6);
2718 }
2719
2720 /*
2721  * NHM adds support for additional MSRs:
2722  *
2723  * MSR_SMI_COUNT                   0x00000034
2724  *
2725  * MSR_PLATFORM_INFO               0x000000ce
2726  * MSR_PKG_CST_CONFIG_CONTROL     0x000000e2
2727  *
2728  * MSR_MISC_PWR_MGMT               0x000001aa
2729  *
2730  * MSR_PKG_C3_RESIDENCY            0x000003f8
2731  * MSR_PKG_C6_RESIDENCY            0x000003f9
2732  * MSR_CORE_C3_RESIDENCY           0x000003fc
2733  * MSR_CORE_C6_RESIDENCY           0x000003fd
2734  *
2735  * Side effect:
2736  * sets global pkg_cstate_limit to decode MSR_PKG_CST_CONFIG_CONTROL
2737  * sets has_misc_feature_control
2738  */
2739 int probe_nhm_msrs(unsigned int family, unsigned int model)
2740 {
2741         unsigned long long msr;
2742         unsigned int base_ratio;
2743         int *pkg_cstate_limits;
2744
2745         if (!genuine_intel)
2746                 return 0;
2747
2748         if (family != 6)
2749                 return 0;
2750
2751         bclk = discover_bclk(family, model);
2752
2753         switch (model) {
2754         case INTEL_FAM6_NEHALEM_EP:     /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
2755         case INTEL_FAM6_NEHALEM:        /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
2756         case 0x1F:      /* Core i7 and i5 Processor - Nehalem */
2757         case INTEL_FAM6_WESTMERE:       /* Westmere Client - Clarkdale, Arrandale */
2758         case INTEL_FAM6_WESTMERE_EP:    /* Westmere EP - Gulftown */
2759         case INTEL_FAM6_NEHALEM_EX:     /* Nehalem-EX Xeon - Beckton */
2760         case INTEL_FAM6_WESTMERE_EX:    /* Westmere-EX Xeon - Eagleton */
2761                 pkg_cstate_limits = nhm_pkg_cstate_limits;
2762                 break;
2763         case INTEL_FAM6_SANDYBRIDGE:    /* SNB */
2764         case INTEL_FAM6_SANDYBRIDGE_X:  /* SNB Xeon */
2765         case INTEL_FAM6_IVYBRIDGE:      /* IVB */
2766         case INTEL_FAM6_IVYBRIDGE_X:    /* IVB Xeon */
2767                 pkg_cstate_limits = snb_pkg_cstate_limits;
2768                 has_misc_feature_control = 1;
2769                 break;
2770         case INTEL_FAM6_HASWELL_CORE:   /* HSW */
2771         case INTEL_FAM6_HASWELL_X:      /* HSX */
2772         case INTEL_FAM6_HASWELL_ULT:    /* HSW */
2773         case INTEL_FAM6_HASWELL_GT3E:   /* HSW */
2774         case INTEL_FAM6_BROADWELL_CORE: /* BDW */
2775         case INTEL_FAM6_BROADWELL_GT3E: /* BDW */
2776         case INTEL_FAM6_BROADWELL_X:    /* BDX */
2777         case INTEL_FAM6_BROADWELL_XEON_D:       /* BDX-DE */
2778         case INTEL_FAM6_SKYLAKE_MOBILE: /* SKL */
2779         case INTEL_FAM6_SKYLAKE_DESKTOP:        /* SKL */
2780         case INTEL_FAM6_KABYLAKE_MOBILE:        /* KBL */
2781         case INTEL_FAM6_KABYLAKE_DESKTOP:       /* KBL */
2782                 pkg_cstate_limits = hsw_pkg_cstate_limits;
2783                 has_misc_feature_control = 1;
2784                 break;
2785         case INTEL_FAM6_SKYLAKE_X:      /* SKX */
2786                 pkg_cstate_limits = skx_pkg_cstate_limits;
2787                 has_misc_feature_control = 1;
2788                 break;
2789         case INTEL_FAM6_ATOM_SILVERMONT1:       /* BYT */
2790                 no_MSR_MISC_PWR_MGMT = 1;
2791         case INTEL_FAM6_ATOM_SILVERMONT2:       /* AVN */
2792                 pkg_cstate_limits = slv_pkg_cstate_limits;
2793                 break;
2794         case INTEL_FAM6_ATOM_AIRMONT:   /* AMT */
2795                 pkg_cstate_limits = amt_pkg_cstate_limits;
2796                 no_MSR_MISC_PWR_MGMT = 1;
2797                 break;
2798         case INTEL_FAM6_XEON_PHI_KNL:   /* PHI */
2799         case INTEL_FAM6_XEON_PHI_KNM:
2800                 pkg_cstate_limits = phi_pkg_cstate_limits;
2801                 break;
2802         case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
2803         case INTEL_FAM6_ATOM_GEMINI_LAKE:
2804         case INTEL_FAM6_ATOM_DENVERTON: /* DNV */
2805                 pkg_cstate_limits = bxt_pkg_cstate_limits;
2806                 break;
2807         default:
2808                 return 0;
2809         }
2810         get_msr(base_cpu, MSR_PKG_CST_CONFIG_CONTROL, &msr);
2811         pkg_cstate_limit = pkg_cstate_limits[msr & 0xF];
2812
2813         get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
2814         base_ratio = (msr >> 8) & 0xFF;
2815
2816         base_hz = base_ratio * bclk * 1000000;
2817         has_base_hz = 1;
2818         return 1;
2819 }
2820 /*
2821  * SLV client has support for unique MSRs:
2822  *
2823  * MSR_CC6_DEMOTION_POLICY_CONFIG
2824  * MSR_MC6_DEMOTION_POLICY_CONFIG
2825  */
2826
2827 int has_slv_msrs(unsigned int family, unsigned int model)
2828 {
2829         if (!genuine_intel)
2830                 return 0;
2831
2832         switch (model) {
2833         case INTEL_FAM6_ATOM_SILVERMONT1:
2834         case INTEL_FAM6_ATOM_MERRIFIELD:
2835         case INTEL_FAM6_ATOM_MOOREFIELD:
2836                 return 1;
2837         }
2838         return 0;
2839 }
2840 int is_dnv(unsigned int family, unsigned int model)
2841 {
2842
2843         if (!genuine_intel)
2844                 return 0;
2845
2846         switch (model) {
2847         case INTEL_FAM6_ATOM_DENVERTON:
2848                 return 1;
2849         }
2850         return 0;
2851 }
2852 int is_bdx(unsigned int family, unsigned int model)
2853 {
2854
2855         if (!genuine_intel)
2856                 return 0;
2857
2858         switch (model) {
2859         case INTEL_FAM6_BROADWELL_X:
2860         case INTEL_FAM6_BROADWELL_XEON_D:
2861                 return 1;
2862         }
2863         return 0;
2864 }
2865 int is_skx(unsigned int family, unsigned int model)
2866 {
2867
2868         if (!genuine_intel)
2869                 return 0;
2870
2871         switch (model) {
2872         case INTEL_FAM6_SKYLAKE_X:
2873                 return 1;
2874         }
2875         return 0;
2876 }
2877
2878 int has_turbo_ratio_limit(unsigned int family, unsigned int model)
2879 {
2880         if (has_slv_msrs(family, model))
2881                 return 0;
2882
2883         switch (model) {
2884         /* Nehalem compatible, but do not include turbo-ratio limit support */
2885         case INTEL_FAM6_NEHALEM_EX:     /* Nehalem-EX Xeon - Beckton */
2886         case INTEL_FAM6_WESTMERE_EX:    /* Westmere-EX Xeon - Eagleton */
2887         case INTEL_FAM6_XEON_PHI_KNL:   /* PHI - Knights Landing (different MSR definition) */
2888         case INTEL_FAM6_XEON_PHI_KNM:
2889                 return 0;
2890         default:
2891                 return 1;
2892         }
2893 }
2894 int has_atom_turbo_ratio_limit(unsigned int family, unsigned int model)
2895 {
2896         if (has_slv_msrs(family, model))
2897                 return 1;
2898
2899         return 0;
2900 }
2901 int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
2902 {
2903         if (!genuine_intel)
2904                 return 0;
2905
2906         if (family != 6)
2907                 return 0;
2908
2909         switch (model) {
2910         case INTEL_FAM6_IVYBRIDGE_X:    /* IVB Xeon */
2911         case INTEL_FAM6_HASWELL_X:      /* HSW Xeon */
2912                 return 1;
2913         default:
2914                 return 0;
2915         }
2916 }
2917 int has_hsw_turbo_ratio_limit(unsigned int family, unsigned int model)
2918 {
2919         if (!genuine_intel)
2920                 return 0;
2921
2922         if (family != 6)
2923                 return 0;
2924
2925         switch (model) {
2926         case INTEL_FAM6_HASWELL_X:      /* HSW Xeon */
2927                 return 1;
2928         default:
2929                 return 0;
2930         }
2931 }
2932
2933 int has_knl_turbo_ratio_limit(unsigned int family, unsigned int model)
2934 {
2935         if (!genuine_intel)
2936                 return 0;
2937
2938         if (family != 6)
2939                 return 0;
2940
2941         switch (model) {
2942         case INTEL_FAM6_XEON_PHI_KNL:   /* Knights Landing */
2943         case INTEL_FAM6_XEON_PHI_KNM:
2944                 return 1;
2945         default:
2946                 return 0;
2947         }
2948 }
2949 int has_glm_turbo_ratio_limit(unsigned int family, unsigned int model)
2950 {
2951         if (!genuine_intel)
2952                 return 0;
2953
2954         if (family != 6)
2955                 return 0;
2956
2957         switch (model) {
2958         case INTEL_FAM6_ATOM_GOLDMONT:
2959         case INTEL_FAM6_SKYLAKE_X:
2960                 return 1;
2961         default:
2962                 return 0;
2963         }
2964 }
2965 int has_config_tdp(unsigned int family, unsigned int model)
2966 {
2967         if (!genuine_intel)
2968                 return 0;
2969
2970         if (family != 6)
2971                 return 0;
2972
2973         switch (model) {
2974         case INTEL_FAM6_IVYBRIDGE:      /* IVB */
2975         case INTEL_FAM6_HASWELL_CORE:   /* HSW */
2976         case INTEL_FAM6_HASWELL_X:      /* HSX */
2977         case INTEL_FAM6_HASWELL_ULT:    /* HSW */
2978         case INTEL_FAM6_HASWELL_GT3E:   /* HSW */
2979         case INTEL_FAM6_BROADWELL_CORE: /* BDW */
2980         case INTEL_FAM6_BROADWELL_GT3E: /* BDW */
2981         case INTEL_FAM6_BROADWELL_X:    /* BDX */
2982         case INTEL_FAM6_BROADWELL_XEON_D:       /* BDX-DE */
2983         case INTEL_FAM6_SKYLAKE_MOBILE: /* SKL */
2984         case INTEL_FAM6_SKYLAKE_DESKTOP:        /* SKL */
2985         case INTEL_FAM6_KABYLAKE_MOBILE:        /* KBL */
2986         case INTEL_FAM6_KABYLAKE_DESKTOP:       /* KBL */
2987         case INTEL_FAM6_SKYLAKE_X:      /* SKX */
2988
2989         case INTEL_FAM6_XEON_PHI_KNL:   /* Knights Landing */
2990         case INTEL_FAM6_XEON_PHI_KNM:
2991                 return 1;
2992         default:
2993                 return 0;
2994         }
2995 }
2996
2997 static void
2998 dump_cstate_pstate_config_info(unsigned int family, unsigned int model)
2999 {
3000         if (!do_nhm_platform_info)
3001                 return;
3002
3003         dump_nhm_platform_info();
3004
3005         if (has_hsw_turbo_ratio_limit(family, model))
3006                 dump_hsw_turbo_ratio_limits();
3007
3008         if (has_ivt_turbo_ratio_limit(family, model))
3009                 dump_ivt_turbo_ratio_limits();
3010
3011         if (has_turbo_ratio_limit(family, model))
3012                 dump_turbo_ratio_limits(family, model);
3013
3014         if (has_atom_turbo_ratio_limit(family, model))
3015                 dump_atom_turbo_ratio_limits();
3016
3017         if (has_knl_turbo_ratio_limit(family, model))
3018                 dump_knl_turbo_ratio_limits();
3019
3020         if (has_config_tdp(family, model))
3021                 dump_config_tdp();
3022
3023         dump_nhm_cst_cfg();
3024 }
3025
3026 static void
3027 dump_sysfs_cstate_config(void)
3028 {
3029         char path[64];
3030         char name_buf[16];
3031         char desc[64];
3032         FILE *input;
3033         int state;
3034         char *sp;
3035
3036         if (!DO_BIC(BIC_sysfs))
3037                 return;
3038
3039         for (state = 0; state < 10; ++state) {
3040
3041                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name",
3042                         base_cpu, state);
3043                 input = fopen(path, "r");
3044                 if (input == NULL)
3045                         continue;
3046                 fgets(name_buf, sizeof(name_buf), input);
3047
3048                  /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
3049                 sp = strchr(name_buf, '-');
3050                 if (!sp)
3051                         sp = strchrnul(name_buf, '\n');
3052                 *sp = '\0';
3053
3054                 fclose(input);
3055
3056                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/desc",
3057                         base_cpu, state);
3058                 input = fopen(path, "r");
3059                 if (input == NULL)
3060                         continue;
3061                 fgets(desc, sizeof(desc), input);
3062
3063                 fprintf(outf, "cpu%d: %s: %s", base_cpu, name_buf, desc);
3064                 fclose(input);
3065         }
3066 }
3067 static void
3068 dump_sysfs_pstate_config(void)
3069 {
3070         char path[64];
3071         char driver_buf[64];
3072         char governor_buf[64];
3073         FILE *input;
3074         int turbo;
3075
3076         sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_driver",
3077                         base_cpu);
3078         input = fopen(path, "r");
3079         if (input == NULL) {
3080                 fprintf(stderr, "NSFOD %s\n", path);
3081                 return;
3082         }
3083         fgets(driver_buf, sizeof(driver_buf), input);
3084         fclose(input);
3085
3086         sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor",
3087                         base_cpu);
3088         input = fopen(path, "r");
3089         if (input == NULL) {
3090                 fprintf(stderr, "NSFOD %s\n", path);
3091                 return;
3092         }
3093         fgets(governor_buf, sizeof(governor_buf), input);
3094         fclose(input);
3095
3096         fprintf(outf, "cpu%d: cpufreq driver: %s", base_cpu, driver_buf);
3097         fprintf(outf, "cpu%d: cpufreq governor: %s", base_cpu, governor_buf);
3098
3099         sprintf(path, "/sys/devices/system/cpu/cpufreq/boost");
3100         input = fopen(path, "r");
3101         if (input != NULL) {
3102                 fscanf(input, "%d", &turbo);
3103                 fprintf(outf, "cpufreq boost: %d\n", turbo);
3104                 fclose(input);
3105         }
3106
3107         sprintf(path, "/sys/devices/system/cpu/intel_pstate/no_turbo");
3108         input = fopen(path, "r");
3109         if (input != NULL) {
3110                 fscanf(input, "%d", &turbo);
3111                 fprintf(outf, "cpufreq intel_pstate no_turbo: %d\n", turbo);
3112                 fclose(input);
3113         }
3114 }
3115
3116
3117 /*
3118  * print_epb()
3119  * Decode the ENERGY_PERF_BIAS MSR
3120  */
3121 int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3122 {
3123         unsigned long long msr;
3124         char *epb_string;
3125         int cpu;
3126
3127         if (!has_epb)
3128                 return 0;
3129
3130         cpu = t->cpu_id;
3131
3132         /* EPB is per-package */
3133         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3134                 return 0;
3135
3136         if (cpu_migrate(cpu)) {
3137                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3138                 return -1;
3139         }
3140
3141         if (get_msr(cpu, MSR_IA32_ENERGY_PERF_BIAS, &msr))
3142                 return 0;
3143
3144         switch (msr & 0xF) {
3145         case ENERGY_PERF_BIAS_PERFORMANCE:
3146                 epb_string = "performance";
3147                 break;
3148         case ENERGY_PERF_BIAS_NORMAL:
3149                 epb_string = "balanced";
3150                 break;
3151         case ENERGY_PERF_BIAS_POWERSAVE:
3152                 epb_string = "powersave";
3153                 break;
3154         default:
3155                 epb_string = "custom";
3156                 break;
3157         }
3158         fprintf(outf, "cpu%d: MSR_IA32_ENERGY_PERF_BIAS: 0x%08llx (%s)\n", cpu, msr, epb_string);
3159
3160         return 0;
3161 }
3162 /*
3163  * print_hwp()
3164  * Decode the MSR_HWP_CAPABILITIES
3165  */
3166 int print_hwp(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3167 {
3168         unsigned long long msr;
3169         int cpu;
3170
3171         if (!has_hwp)
3172                 return 0;
3173
3174         cpu = t->cpu_id;
3175
3176         /* MSR_HWP_CAPABILITIES is per-package */
3177         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3178                 return 0;
3179
3180         if (cpu_migrate(cpu)) {
3181                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3182                 return -1;
3183         }
3184
3185         if (get_msr(cpu, MSR_PM_ENABLE, &msr))
3186                 return 0;
3187
3188         fprintf(outf, "cpu%d: MSR_PM_ENABLE: 0x%08llx (%sHWP)\n",
3189                 cpu, msr, (msr & (1 << 0)) ? "" : "No-");
3190
3191         /* MSR_PM_ENABLE[1] == 1 if HWP is enabled and MSRs visible */
3192         if ((msr & (1 << 0)) == 0)
3193                 return 0;
3194
3195         if (get_msr(cpu, MSR_HWP_CAPABILITIES, &msr))
3196                 return 0;
3197
3198         fprintf(outf, "cpu%d: MSR_HWP_CAPABILITIES: 0x%08llx "
3199                         "(high %d guar %d eff %d low %d)\n",
3200                         cpu, msr,
3201                         (unsigned int)HWP_HIGHEST_PERF(msr),
3202                         (unsigned int)HWP_GUARANTEED_PERF(msr),
3203                         (unsigned int)HWP_MOSTEFFICIENT_PERF(msr),
3204                         (unsigned int)HWP_LOWEST_PERF(msr));
3205
3206         if (get_msr(cpu, MSR_HWP_REQUEST, &msr))
3207                 return 0;
3208
3209         fprintf(outf, "cpu%d: MSR_HWP_REQUEST: 0x%08llx "
3210                         "(min %d max %d des %d epp 0x%x window 0x%x pkg 0x%x)\n",
3211                         cpu, msr,
3212                         (unsigned int)(((msr) >> 0) & 0xff),
3213                         (unsigned int)(((msr) >> 8) & 0xff),
3214                         (unsigned int)(((msr) >> 16) & 0xff),
3215                         (unsigned int)(((msr) >> 24) & 0xff),
3216                         (unsigned int)(((msr) >> 32) & 0xff3),
3217                         (unsigned int)(((msr) >> 42) & 0x1));
3218
3219         if (has_hwp_pkg) {
3220                 if (get_msr(cpu, MSR_HWP_REQUEST_PKG, &msr))
3221                         return 0;
3222
3223                 fprintf(outf, "cpu%d: MSR_HWP_REQUEST_PKG: 0x%08llx "
3224                         "(min %d max %d des %d epp 0x%x window 0x%x)\n",
3225                         cpu, msr,
3226                         (unsigned int)(((msr) >> 0) & 0xff),
3227                         (unsigned int)(((msr) >> 8) & 0xff),
3228                         (unsigned int)(((msr) >> 16) & 0xff),
3229                         (unsigned int)(((msr) >> 24) & 0xff),
3230                         (unsigned int)(((msr) >> 32) & 0xff3));
3231         }
3232         if (has_hwp_notify) {
3233                 if (get_msr(cpu, MSR_HWP_INTERRUPT, &msr))
3234                         return 0;
3235
3236                 fprintf(outf, "cpu%d: MSR_HWP_INTERRUPT: 0x%08llx "
3237                         "(%s_Guaranteed_Perf_Change, %s_Excursion_Min)\n",
3238                         cpu, msr,
3239                         ((msr) & 0x1) ? "EN" : "Dis",
3240                         ((msr) & 0x2) ? "EN" : "Dis");
3241         }
3242         if (get_msr(cpu, MSR_HWP_STATUS, &msr))
3243                 return 0;
3244
3245         fprintf(outf, "cpu%d: MSR_HWP_STATUS: 0x%08llx "
3246                         "(%sGuaranteed_Perf_Change, %sExcursion_Min)\n",
3247                         cpu, msr,
3248                         ((msr) & 0x1) ? "" : "No-",
3249                         ((msr) & 0x2) ? "" : "No-");
3250
3251         return 0;
3252 }
3253
3254 /*
3255  * print_perf_limit()
3256  */
3257 int print_perf_limit(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3258 {
3259         unsigned long long msr;
3260         int cpu;
3261
3262         cpu = t->cpu_id;
3263
3264         /* per-package */
3265         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3266                 return 0;
3267
3268         if (cpu_migrate(cpu)) {
3269                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3270                 return -1;
3271         }
3272
3273         if (do_core_perf_limit_reasons) {
3274                 get_msr(cpu, MSR_CORE_PERF_LIMIT_REASONS, &msr);
3275                 fprintf(outf, "cpu%d: MSR_CORE_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
3276                 fprintf(outf, " (Active: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
3277                         (msr & 1 << 15) ? "bit15, " : "",
3278                         (msr & 1 << 14) ? "bit14, " : "",
3279                         (msr & 1 << 13) ? "Transitions, " : "",
3280                         (msr & 1 << 12) ? "MultiCoreTurbo, " : "",
3281                         (msr & 1 << 11) ? "PkgPwrL2, " : "",
3282                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
3283                         (msr & 1 << 9) ? "CorePwr, " : "",
3284                         (msr & 1 << 8) ? "Amps, " : "",
3285                         (msr & 1 << 6) ? "VR-Therm, " : "",
3286                         (msr & 1 << 5) ? "Auto-HWP, " : "",
3287                         (msr & 1 << 4) ? "Graphics, " : "",
3288                         (msr & 1 << 2) ? "bit2, " : "",
3289                         (msr & 1 << 1) ? "ThermStatus, " : "",
3290                         (msr & 1 << 0) ? "PROCHOT, " : "");
3291                 fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
3292                         (msr & 1 << 31) ? "bit31, " : "",
3293                         (msr & 1 << 30) ? "bit30, " : "",
3294                         (msr & 1 << 29) ? "Transitions, " : "",
3295                         (msr & 1 << 28) ? "MultiCoreTurbo, " : "",
3296                         (msr & 1 << 27) ? "PkgPwrL2, " : "",
3297                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
3298                         (msr & 1 << 25) ? "CorePwr, " : "",
3299                         (msr & 1 << 24) ? "Amps, " : "",
3300                         (msr & 1 << 22) ? "VR-Therm, " : "",
3301                         (msr & 1 << 21) ? "Auto-HWP, " : "",
3302                         (msr & 1 << 20) ? "Graphics, " : "",
3303                         (msr & 1 << 18) ? "bit18, " : "",
3304                         (msr & 1 << 17) ? "ThermStatus, " : "",
3305                         (msr & 1 << 16) ? "PROCHOT, " : "");
3306
3307         }
3308         if (do_gfx_perf_limit_reasons) {
3309                 get_msr(cpu, MSR_GFX_PERF_LIMIT_REASONS, &msr);
3310                 fprintf(outf, "cpu%d: MSR_GFX_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
3311                 fprintf(outf, " (Active: %s%s%s%s%s%s%s%s)",
3312                         (msr & 1 << 0) ? "PROCHOT, " : "",
3313                         (msr & 1 << 1) ? "ThermStatus, " : "",
3314                         (msr & 1 << 4) ? "Graphics, " : "",
3315                         (msr & 1 << 6) ? "VR-Therm, " : "",
3316                         (msr & 1 << 8) ? "Amps, " : "",
3317                         (msr & 1 << 9) ? "GFXPwr, " : "",
3318                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
3319                         (msr & 1 << 11) ? "PkgPwrL2, " : "");
3320                 fprintf(outf, " (Logged: %s%s%s%s%s%s%s%s)\n",
3321                         (msr & 1 << 16) ? "PROCHOT, " : "",
3322                         (msr & 1 << 17) ? "ThermStatus, " : "",
3323                         (msr & 1 << 20) ? "Graphics, " : "",
3324                         (msr & 1 << 22) ? "VR-Therm, " : "",
3325                         (msr & 1 << 24) ? "Amps, " : "",
3326                         (msr & 1 << 25) ? "GFXPwr, " : "",
3327                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
3328                         (msr & 1 << 27) ? "PkgPwrL2, " : "");
3329         }
3330         if (do_ring_perf_limit_reasons) {
3331                 get_msr(cpu, MSR_RING_PERF_LIMIT_REASONS, &msr);
3332                 fprintf(outf, "cpu%d: MSR_RING_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
3333                 fprintf(outf, " (Active: %s%s%s%s%s%s)",
3334                         (msr & 1 << 0) ? "PROCHOT, " : "",
3335                         (msr & 1 << 1) ? "ThermStatus, " : "",
3336                         (msr & 1 << 6) ? "VR-Therm, " : "",
3337                         (msr & 1 << 8) ? "Amps, " : "",
3338                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
3339                         (msr & 1 << 11) ? "PkgPwrL2, " : "");
3340                 fprintf(outf, " (Logged: %s%s%s%s%s%s)\n",
3341                         (msr & 1 << 16) ? "PROCHOT, " : "",
3342                         (msr & 1 << 17) ? "ThermStatus, " : "",
3343                         (msr & 1 << 22) ? "VR-Therm, " : "",
3344                         (msr & 1 << 24) ? "Amps, " : "",
3345                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
3346                         (msr & 1 << 27) ? "PkgPwrL2, " : "");
3347         }
3348         return 0;
3349 }
3350
3351 #define RAPL_POWER_GRANULARITY  0x7FFF  /* 15 bit power granularity */
3352 #define RAPL_TIME_GRANULARITY   0x3F /* 6 bit time granularity */
3353
3354 double get_tdp(unsigned int model)
3355 {
3356         unsigned long long msr;
3357
3358         if (do_rapl & RAPL_PKG_POWER_INFO)
3359                 if (!get_msr(base_cpu, MSR_PKG_POWER_INFO, &msr))
3360                         return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
3361
3362         switch (model) {
3363         case INTEL_FAM6_ATOM_SILVERMONT1:
3364         case INTEL_FAM6_ATOM_SILVERMONT2:
3365                 return 30.0;
3366         default:
3367                 return 135.0;
3368         }
3369 }
3370
3371 /*
3372  * rapl_dram_energy_units_probe()
3373  * Energy units are either hard-coded, or come from RAPL Energy Unit MSR.
3374  */
3375 static double
3376 rapl_dram_energy_units_probe(int  model, double rapl_energy_units)
3377 {
3378         /* only called for genuine_intel, family 6 */
3379
3380         switch (model) {
3381         case INTEL_FAM6_HASWELL_X:      /* HSX */
3382         case INTEL_FAM6_BROADWELL_X:    /* BDX */
3383         case INTEL_FAM6_BROADWELL_XEON_D:       /* BDX-DE */
3384         case INTEL_FAM6_XEON_PHI_KNL:   /* KNL */
3385         case INTEL_FAM6_XEON_PHI_KNM:
3386                 return (rapl_dram_energy_units = 15.3 / 1000000);
3387         default:
3388                 return (rapl_energy_units);
3389         }
3390 }
3391
3392
3393 /*
3394  * rapl_probe()
3395  *
3396  * sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
3397  */
3398 void rapl_probe(unsigned int family, unsigned int model)
3399 {
3400         unsigned long long msr;
3401         unsigned int time_unit;
3402         double tdp;
3403
3404         if (!genuine_intel)
3405                 return;
3406
3407         if (family != 6)
3408                 return;
3409
3410         switch (model) {
3411         case INTEL_FAM6_SANDYBRIDGE:
3412         case INTEL_FAM6_IVYBRIDGE:
3413         case INTEL_FAM6_HASWELL_CORE:   /* HSW */
3414         case INTEL_FAM6_HASWELL_ULT:    /* HSW */
3415         case INTEL_FAM6_HASWELL_GT3E:   /* HSW */
3416         case INTEL_FAM6_BROADWELL_CORE: /* BDW */
3417         case INTEL_FAM6_BROADWELL_GT3E: /* BDW */
3418                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
3419                 if (rapl_joules) {
3420                         BIC_PRESENT(BIC_Pkg_J);
3421                         BIC_PRESENT(BIC_Cor_J);
3422                         BIC_PRESENT(BIC_GFX_J);
3423                 } else {
3424                         BIC_PRESENT(BIC_PkgWatt);
3425                         BIC_PRESENT(BIC_CorWatt);
3426                         BIC_PRESENT(BIC_GFXWatt);
3427                 }
3428                 break;
3429         case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
3430         case INTEL_FAM6_ATOM_GEMINI_LAKE:
3431                 do_rapl = RAPL_PKG | RAPL_PKG_POWER_INFO;
3432                 if (rapl_joules)
3433                         BIC_PRESENT(BIC_Pkg_J);
3434                 else
3435                         BIC_PRESENT(BIC_PkgWatt);
3436                 break;
3437         case INTEL_FAM6_SKYLAKE_MOBILE: /* SKL */
3438         case INTEL_FAM6_SKYLAKE_DESKTOP:        /* SKL */
3439         case INTEL_FAM6_KABYLAKE_MOBILE:        /* KBL */
3440         case INTEL_FAM6_KABYLAKE_DESKTOP:       /* KBL */
3441                 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;
3442                 BIC_PRESENT(BIC_PKG__);
3443                 BIC_PRESENT(BIC_RAM__);
3444                 if (rapl_joules) {
3445                         BIC_PRESENT(BIC_Pkg_J);
3446                         BIC_PRESENT(BIC_Cor_J);
3447                         BIC_PRESENT(BIC_RAM_J);
3448                         BIC_PRESENT(BIC_GFX_J);
3449                 } else {
3450                         BIC_PRESENT(BIC_PkgWatt);
3451                         BIC_PRESENT(BIC_CorWatt);
3452                         BIC_PRESENT(BIC_RAMWatt);
3453                         BIC_PRESENT(BIC_GFXWatt);
3454                 }
3455                 break;
3456         case INTEL_FAM6_HASWELL_X:      /* HSX */
3457         case INTEL_FAM6_BROADWELL_X:    /* BDX */
3458         case INTEL_FAM6_BROADWELL_XEON_D:       /* BDX-DE */
3459         case INTEL_FAM6_SKYLAKE_X:      /* SKX */
3460         case INTEL_FAM6_XEON_PHI_KNL:   /* KNL */
3461         case INTEL_FAM6_XEON_PHI_KNM:
3462                 do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
3463                 BIC_PRESENT(BIC_PKG__);
3464                 BIC_PRESENT(BIC_RAM__);
3465                 if (rapl_joules) {
3466                         BIC_PRESENT(BIC_Pkg_J);
3467                         BIC_PRESENT(BIC_RAM_J);
3468                 } else {
3469                         BIC_PRESENT(BIC_PkgWatt);
3470                         BIC_PRESENT(BIC_RAMWatt);
3471                 }
3472                 break;
3473         case INTEL_FAM6_SANDYBRIDGE_X:
3474         case INTEL_FAM6_IVYBRIDGE_X:
3475                 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;
3476                 BIC_PRESENT(BIC_PKG__);
3477                 BIC_PRESENT(BIC_RAM__);
3478                 if (rapl_joules) {
3479                         BIC_PRESENT(BIC_Pkg_J);
3480                         BIC_PRESENT(BIC_Cor_J);
3481                         BIC_PRESENT(BIC_RAM_J);
3482                 } else {
3483                         BIC_PRESENT(BIC_PkgWatt);
3484                         BIC_PRESENT(BIC_CorWatt);
3485                         BIC_PRESENT(BIC_RAMWatt);
3486                 }
3487                 break;
3488         case INTEL_FAM6_ATOM_SILVERMONT1:       /* BYT */
3489         case INTEL_FAM6_ATOM_SILVERMONT2:       /* AVN */
3490                 do_rapl = RAPL_PKG | RAPL_CORES;
3491                 if (rapl_joules) {
3492                         BIC_PRESENT(BIC_Pkg_J);
3493                         BIC_PRESENT(BIC_Cor_J);
3494                 } else {
3495                         BIC_PRESENT(BIC_PkgWatt);
3496                         BIC_PRESENT(BIC_CorWatt);
3497                 }
3498                 break;
3499         case INTEL_FAM6_ATOM_DENVERTON: /* DNV */
3500                 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;
3501                 BIC_PRESENT(BIC_PKG__);
3502                 BIC_PRESENT(BIC_RAM__);
3503                 if (rapl_joules) {
3504                         BIC_PRESENT(BIC_Pkg_J);
3505                         BIC_PRESENT(BIC_Cor_J);
3506                         BIC_PRESENT(BIC_RAM_J);
3507                 } else {
3508                         BIC_PRESENT(BIC_PkgWatt);
3509                         BIC_PRESENT(BIC_CorWatt);
3510                         BIC_PRESENT(BIC_RAMWatt);
3511                 }
3512                 break;
3513         default:
3514                 return;
3515         }
3516
3517         /* units on package 0, verify later other packages match */
3518         if (get_msr(base_cpu, MSR_RAPL_POWER_UNIT, &msr))
3519                 return;
3520
3521         rapl_power_units = 1.0 / (1 << (msr & 0xF));
3522         if (model == INTEL_FAM6_ATOM_SILVERMONT1)
3523                 rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
3524         else
3525                 rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
3526
3527         rapl_dram_energy_units = rapl_dram_energy_units_probe(model, rapl_energy_units);
3528
3529         time_unit = msr >> 16 & 0xF;
3530         if (time_unit == 0)
3531                 time_unit = 0xA;
3532
3533         rapl_time_units = 1.0 / (1 << (time_unit));
3534
3535         tdp = get_tdp(model);
3536
3537         rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
3538         if (!quiet)
3539                 fprintf(outf, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
3540
3541         return;
3542 }
3543
3544 void perf_limit_reasons_probe(unsigned int family, unsigned int model)
3545 {
3546         if (!genuine_intel)
3547                 return;
3548
3549         if (family != 6)
3550                 return;
3551
3552         switch (model) {
3553         case INTEL_FAM6_HASWELL_CORE:   /* HSW */
3554         case INTEL_FAM6_HASWELL_ULT:    /* HSW */
3555         case INTEL_FAM6_HASWELL_GT3E:   /* HSW */
3556                 do_gfx_perf_limit_reasons = 1;
3557         case INTEL_FAM6_HASWELL_X:      /* HSX */
3558                 do_core_perf_limit_reasons = 1;
3559                 do_ring_perf_limit_reasons = 1;
3560         default:
3561                 return;
3562         }
3563 }
3564
3565 int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3566 {
3567         unsigned long long msr;
3568         unsigned int dts, dts2;
3569         int cpu;
3570
3571         if (!(do_dts || do_ptm))
3572                 return 0;
3573
3574         cpu = t->cpu_id;
3575
3576         /* DTS is per-core, no need to print for each thread */
3577         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
3578                 return 0;
3579
3580         if (cpu_migrate(cpu)) {
3581                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3582                 return -1;
3583         }
3584
3585         if (do_ptm && (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
3586                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
3587                         return 0;
3588
3589                 dts = (msr >> 16) & 0x7F;
3590                 fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n",
3591                         cpu, msr, tcc_activation_temp - dts);
3592
3593                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
3594                         return 0;
3595
3596                 dts = (msr >> 16) & 0x7F;
3597                 dts2 = (msr >> 8) & 0x7F;
3598                 fprintf(outf, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
3599                         cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
3600         }
3601
3602
3603         if (do_dts && debug) {
3604                 unsigned int resolution;
3605
3606                 if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
3607                         return 0;
3608
3609                 dts = (msr >> 16) & 0x7F;
3610                 resolution = (msr >> 27) & 0xF;
3611                 fprintf(outf, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
3612                         cpu, msr, tcc_activation_temp - dts, resolution);
3613
3614                 if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
3615                         return 0;
3616
3617                 dts = (msr >> 16) & 0x7F;
3618                 dts2 = (msr >> 8) & 0x7F;
3619                 fprintf(outf, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
3620                         cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
3621         }
3622
3623         return 0;
3624 }
3625
3626 void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
3627 {
3628         fprintf(outf, "cpu%d: %s: %sabled (%f Watts, %f sec, clamp %sabled)\n",
3629                 cpu, label,
3630                 ((msr >> 15) & 1) ? "EN" : "DIS",
3631                 ((msr >> 0) & 0x7FFF) * rapl_power_units,
3632                 (1.0 + (((msr >> 22) & 0x3)/4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
3633                 (((msr >> 16) & 1) ? "EN" : "DIS"));
3634
3635         return;
3636 }
3637
3638 int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3639 {
3640         unsigned long long msr;
3641         int cpu;
3642
3643         if (!do_rapl)
3644                 return 0;
3645
3646         /* RAPL counters are per package, so print only for 1st thread/package */
3647         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3648                 return 0;
3649
3650         cpu = t->cpu_id;
3651         if (cpu_migrate(cpu)) {
3652                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3653                 return -1;
3654         }
3655
3656         if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
3657                 return -1;
3658
3659         fprintf(outf, "cpu%d: MSR_RAPL_POWER_UNIT: 0x%08llx (%f Watts, %f Joules, %f sec.)\n", cpu, msr,
3660                 rapl_power_units, rapl_energy_units, rapl_time_units);
3661
3662         if (do_rapl & RAPL_PKG_POWER_INFO) {
3663
3664                 if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
3665                         return -5;
3666
3667
3668                 fprintf(outf, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
3669                         cpu, msr,
3670                         ((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3671                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3672                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3673                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
3674
3675         }
3676         if (do_rapl & RAPL_PKG) {
3677
3678                 if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
3679                         return -9;
3680
3681                 fprintf(outf, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
3682                         cpu, msr, (msr >> 63) & 1 ? "" : "UN");
3683
3684                 print_power_limit_msr(cpu, msr, "PKG Limit #1");
3685                 fprintf(outf, "cpu%d: PKG Limit #2: %sabled (%f Watts, %f* sec, clamp %sabled)\n",
3686                         cpu,
3687                         ((msr >> 47) & 1) ? "EN" : "DIS",
3688                         ((msr >> 32) & 0x7FFF) * rapl_power_units,
3689                         (1.0 + (((msr >> 54) & 0x3)/4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
3690                         ((msr >> 48) & 1) ? "EN" : "DIS");
3691         }
3692
3693         if (do_rapl & RAPL_DRAM_POWER_INFO) {
3694                 if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
3695                         return -6;
3696
3697                 fprintf(outf, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
3698                         cpu, msr,
3699                         ((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3700                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3701                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
3702                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
3703         }
3704         if (do_rapl & RAPL_DRAM) {
3705                 if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
3706                         return -9;
3707                 fprintf(outf, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
3708                                 cpu, msr, (msr >> 31) & 1 ? "" : "UN");
3709
3710                 print_power_limit_msr(cpu, msr, "DRAM Limit");
3711         }
3712         if (do_rapl & RAPL_CORE_POLICY) {
3713                 if (get_msr(cpu, MSR_PP0_POLICY, &msr))
3714                         return -7;
3715
3716                 fprintf(outf, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
3717         }
3718         if (do_rapl & RAPL_CORES_POWER_LIMIT) {
3719                 if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
3720                         return -9;
3721                 fprintf(outf, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
3722                                 cpu, msr, (msr >> 31) & 1 ? "" : "UN");
3723                 print_power_limit_msr(cpu, msr, "Cores Limit");
3724         }
3725         if (do_rapl & RAPL_GFX) {
3726                 if (get_msr(cpu, MSR_PP1_POLICY, &msr))
3727                         return -8;
3728
3729                 fprintf(outf, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
3730
3731                 if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
3732                         return -9;
3733                 fprintf(outf, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
3734                                 cpu, msr, (msr >> 31) & 1 ? "" : "UN");
3735                 print_power_limit_msr(cpu, msr, "GFX Limit");
3736         }
3737         return 0;
3738 }
3739
3740 /*
3741  * SNB adds support for additional MSRs:
3742  *
3743  * MSR_PKG_C7_RESIDENCY            0x000003fa
3744  * MSR_CORE_C7_RESIDENCY           0x000003fe
3745  * MSR_PKG_C2_RESIDENCY            0x0000060d
3746  */
3747
3748 int has_snb_msrs(unsigned int family, unsigned int model)
3749 {
3750         if (!genuine_intel)
3751                 return 0;
3752
3753         switch (model) {
3754         case INTEL_FAM6_SANDYBRIDGE:
3755         case INTEL_FAM6_SANDYBRIDGE_X:
3756         case INTEL_FAM6_IVYBRIDGE:      /* IVB */
3757         case INTEL_FAM6_IVYBRIDGE_X:    /* IVB Xeon */
3758         case INTEL_FAM6_HASWELL_CORE:   /* HSW */
3759         case INTEL_FAM6_HASWELL_X:      /* HSW */
3760         case INTEL_FAM6_HASWELL_ULT:    /* HSW */
3761         case INTEL_FAM6_HASWELL_GT3E:   /* HSW */
3762         case INTEL_FAM6_BROADWELL_CORE: /* BDW */
3763         case INTEL_FAM6_BROADWELL_GT3E: /* BDW */
3764         case INTEL_FAM6_BROADWELL_X:    /* BDX */
3765         case INTEL_FAM6_BROADWELL_XEON_D:       /* BDX-DE */
3766         case INTEL_FAM6_SKYLAKE_MOBILE: /* SKL */
3767         case INTEL_FAM6_SKYLAKE_DESKTOP:        /* SKL */
3768         case INTEL_FAM6_KABYLAKE_MOBILE:        /* KBL */
3769         case INTEL_FAM6_KABYLAKE_DESKTOP:       /* KBL */
3770         case INTEL_FAM6_SKYLAKE_X:      /* SKX */
3771         case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
3772         case INTEL_FAM6_ATOM_GEMINI_LAKE:
3773         case INTEL_FAM6_ATOM_DENVERTON: /* DNV */
3774                 return 1;
3775         }
3776         return 0;
3777 }
3778
3779 /*
3780  * HSW adds support for additional MSRs:
3781  *
3782  * MSR_PKG_C8_RESIDENCY         0x00000630
3783  * MSR_PKG_C9_RESIDENCY         0x00000631
3784  * MSR_PKG_C10_RESIDENCY        0x00000632
3785  *
3786  * MSR_PKGC8_IRTL               0x00000633
3787  * MSR_PKGC9_IRTL               0x00000634
3788  * MSR_PKGC10_IRTL              0x00000635
3789  *
3790  */
3791 int has_hsw_msrs(unsigned int family, unsigned int model)
3792 {
3793         if (!genuine_intel)
3794                 return 0;
3795
3796         switch (model) {
3797         case INTEL_FAM6_HASWELL_ULT:    /* HSW */
3798         case INTEL_FAM6_BROADWELL_CORE: /* BDW */
3799         case INTEL_FAM6_SKYLAKE_MOBILE: /* SKL */
3800         case INTEL_FAM6_SKYLAKE_DESKTOP:        /* SKL */
3801         case INTEL_FAM6_KABYLAKE_MOBILE:        /* KBL */
3802         case INTEL_FAM6_KABYLAKE_DESKTOP:       /* KBL */
3803         case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
3804         case INTEL_FAM6_ATOM_GEMINI_LAKE:
3805                 return 1;
3806         }
3807         return 0;
3808 }
3809
3810 /*
3811  * SKL adds support for additional MSRS:
3812  *
3813  * MSR_PKG_WEIGHTED_CORE_C0_RES    0x00000658
3814  * MSR_PKG_ANY_CORE_C0_RES         0x00000659
3815  * MSR_PKG_ANY_GFXE_C0_RES         0x0000065A
3816  * MSR_PKG_BOTH_CORE_GFXE_C0_RES   0x0000065B
3817  */
3818 int has_skl_msrs(unsigned int family, unsigned int model)
3819 {
3820         if (!genuine_intel)
3821                 return 0;
3822
3823         switch (model) {
3824         case INTEL_FAM6_SKYLAKE_MOBILE: /* SKL */
3825         case INTEL_FAM6_SKYLAKE_DESKTOP:        /* SKL */
3826         case INTEL_FAM6_KABYLAKE_MOBILE:        /* KBL */
3827         case INTEL_FAM6_KABYLAKE_DESKTOP:       /* KBL */
3828                 return 1;
3829         }
3830         return 0;
3831 }
3832
3833 int is_slm(unsigned int family, unsigned int model)
3834 {
3835         if (!genuine_intel)
3836                 return 0;
3837         switch (model) {
3838         case INTEL_FAM6_ATOM_SILVERMONT1:       /* BYT */
3839         case INTEL_FAM6_ATOM_SILVERMONT2:       /* AVN */
3840                 return 1;
3841         }
3842         return 0;
3843 }
3844
3845 int is_knl(unsigned int family, unsigned int model)
3846 {
3847         if (!genuine_intel)
3848                 return 0;
3849         switch (model) {
3850         case INTEL_FAM6_XEON_PHI_KNL:   /* KNL */
3851         case INTEL_FAM6_XEON_PHI_KNM:
3852                 return 1;
3853         }
3854         return 0;
3855 }
3856
3857 unsigned int get_aperf_mperf_multiplier(unsigned int family, unsigned int model)
3858 {
3859         if (is_knl(family, model))
3860                 return 1024;
3861         return 1;
3862 }
3863
3864 #define SLM_BCLK_FREQS 5
3865 double slm_freq_table[SLM_BCLK_FREQS] = { 83.3, 100.0, 133.3, 116.7, 80.0};
3866
3867 double slm_bclk(void)
3868 {
3869         unsigned long long msr = 3;
3870         unsigned int i;
3871         double freq;
3872
3873         if (get_msr(base_cpu, MSR_FSB_FREQ, &msr))
3874                 fprintf(outf, "SLM BCLK: unknown\n");
3875
3876         i = msr & 0xf;
3877         if (i >= SLM_BCLK_FREQS) {
3878                 fprintf(outf, "SLM BCLK[%d] invalid\n", i);
3879                 i = 3;
3880         }
3881         freq = slm_freq_table[i];
3882
3883         if (!quiet)
3884                 fprintf(outf, "SLM BCLK: %.1f Mhz\n", freq);
3885
3886         return freq;
3887 }
3888
3889 double discover_bclk(unsigned int family, unsigned int model)
3890 {
3891         if (has_snb_msrs(family, model) || is_knl(family, model))
3892                 return 100.00;
3893         else if (is_slm(family, model))
3894                 return slm_bclk();
3895         else
3896                 return 133.33;
3897 }
3898
3899 /*
3900  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
3901  * the Thermal Control Circuit (TCC) activates.
3902  * This is usually equal to tjMax.
3903  *
3904  * Older processors do not have this MSR, so there we guess,
3905  * but also allow cmdline over-ride with -T.
3906  *
3907  * Several MSR temperature values are in units of degrees-C
3908  * below this value, including the Digital Thermal Sensor (DTS),
3909  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
3910  */
3911 int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
3912 {
3913         unsigned long long msr;
3914         unsigned int target_c_local;
3915         int cpu;
3916
3917         /* tcc_activation_temp is used only for dts or ptm */
3918         if (!(do_dts || do_ptm))
3919                 return 0;
3920
3921         /* this is a per-package concept */
3922         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
3923                 return 0;
3924
3925         cpu = t->cpu_id;
3926         if (cpu_migrate(cpu)) {
3927                 fprintf(outf, "Could not migrate to CPU %d\n", cpu);
3928                 return -1;
3929         }
3930
3931         if (tcc_activation_temp_override != 0) {
3932                 tcc_activation_temp = tcc_activation_temp_override;
3933                 fprintf(outf, "cpu%d: Using cmdline TCC Target (%d C)\n",
3934                         cpu, tcc_activation_temp);
3935                 return 0;
3936         }
3937
3938         /* Temperature Target MSR is Nehalem and newer only */
3939         if (!do_nhm_platform_info)
3940                 goto guess;
3941
3942         if (get_msr(base_cpu, MSR_IA32_TEMPERATURE_TARGET, &msr))
3943                 goto guess;
3944
3945         target_c_local = (msr >> 16) & 0xFF;
3946
3947         if (!quiet)
3948                 fprintf(outf, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n",
3949                         cpu, msr, target_c_local);
3950
3951         if (!target_c_local)
3952                 goto guess;
3953
3954         tcc_activation_temp = target_c_local;
3955
3956         return 0;
3957
3958 guess:
3959         tcc_activation_temp = TJMAX_DEFAULT;
3960         fprintf(outf, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n",
3961                 cpu, tcc_activation_temp);
3962
3963         return 0;
3964 }
3965
3966 void decode_feature_control_msr(void)
3967 {
3968         unsigned long long msr;
3969
3970         if (!get_msr(base_cpu, MSR_IA32_FEATURE_CONTROL, &msr))
3971                 fprintf(outf, "cpu%d: MSR_IA32_FEATURE_CONTROL: 0x%08llx (%sLocked %s)\n",
3972                         base_cpu, msr,
3973                         msr & FEATURE_CONTROL_LOCKED ? "" : "UN-",
3974                         msr & (1 << 18) ? "SGX" : "");
3975 }
3976
3977 void decode_misc_enable_msr(void)
3978 {
3979         unsigned long long msr;
3980
3981         if (!genuine_intel)
3982                 return;
3983
3984         if (!get_msr(base_cpu, MSR_IA32_MISC_ENABLE, &msr))
3985                 fprintf(outf, "cpu%d: MSR_IA32_MISC_ENABLE: 0x%08llx (%sTCC %sEIST %sMWAIT %sPREFETCH %sTURBO)\n",
3986                         base_cpu, msr,
3987                         msr & MSR_IA32_MISC_ENABLE_TM1 ? "" : "No-",
3988                         msr & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP ? "" : "No-",
3989                         msr & MSR_IA32_MISC_ENABLE_MWAIT ? "No-" : "",
3990                         msr & MSR_IA32_MISC_ENABLE_PREFETCH_DISABLE ? "No-" : "",
3991                         msr & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ? "No-" : "");
3992 }
3993
3994 void decode_misc_feature_control(void)
3995 {
3996         unsigned long long msr;
3997
3998         if (!has_misc_feature_control)
3999                 return;
4000
4001         if (!get_msr(base_cpu, MSR_MISC_FEATURE_CONTROL, &msr))
4002                 fprintf(outf, "cpu%d: MSR_MISC_FEATURE_CONTROL: 0x%08llx (%sL2-Prefetch %sL2-Prefetch-pair %sL1-Prefetch %sL1-IP-Prefetch)\n",
4003                         base_cpu, msr,
4004                         msr & (0 << 0) ? "No-" : "",
4005                         msr & (1 << 0) ? "No-" : "",
4006                         msr & (2 << 0) ? "No-" : "",
4007                         msr & (3 << 0) ? "No-" : "");
4008 }
4009 /*
4010  * Decode MSR_MISC_PWR_MGMT
4011  *
4012  * Decode the bits according to the Nehalem documentation
4013  * bit[0] seems to continue to have same meaning going forward
4014  * bit[1] less so...
4015  */
4016 void decode_misc_pwr_mgmt_msr(void)
4017 {
4018         unsigned long long msr;
4019
4020         if (!do_nhm_platform_info)
4021                 return;
4022
4023         if (no_MSR_MISC_PWR_MGMT)
4024                 return;
4025
4026         if (!get_msr(base_cpu, MSR_MISC_PWR_MGMT, &msr))
4027                 fprintf(outf, "cpu%d: MSR_MISC_PWR_MGMT: 0x%08llx (%sable-EIST_Coordination %sable-EPB %sable-OOB)\n",
4028                         base_cpu, msr,
4029                         msr & (1 << 0) ? "DIS" : "EN",
4030                         msr & (1 << 1) ? "EN" : "DIS",
4031                         msr & (1 << 8) ? "EN" : "DIS");
4032 }
4033 /*
4034  * Decode MSR_CC6_DEMOTION_POLICY_CONFIG, MSR_MC6_DEMOTION_POLICY_CONFIG
4035  *
4036  * This MSRs are present on Silvermont processors,
4037  * Intel Atom processor E3000 series (Baytrail), and friends.
4038  */
4039 void decode_c6_demotion_policy_msr(void)
4040 {
4041         unsigned long long msr;
4042
4043         if (!get_msr(base_cpu, MSR_CC6_DEMOTION_POLICY_CONFIG, &msr))
4044                 fprintf(outf, "cpu%d: MSR_CC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-CC6-Demotion)\n",
4045                         base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
4046
4047         if (!get_msr(base_cpu, MSR_MC6_DEMOTION_POLICY_CONFIG, &msr))
4048                 fprintf(outf, "cpu%d: MSR_MC6_DEMOTION_POLICY_CONFIG: 0x%08llx (%sable-MC6-Demotion)\n",
4049                         base_cpu, msr, msr & (1 << 0) ? "EN" : "DIS");
4050 }
4051
4052 void process_cpuid()
4053 {
4054         unsigned int eax, ebx, ecx, edx, max_level, max_extended_level;
4055         unsigned int fms, family, model, stepping;
4056         unsigned int has_turbo;
4057
4058         eax = ebx = ecx = edx = 0;
4059
4060         __cpuid(0, max_level, ebx, ecx, edx);
4061
4062         if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
4063                 genuine_intel = 1;
4064
4065         if (!quiet)
4066                 fprintf(outf, "CPUID(0): %.4s%.4s%.4s ",
4067                         (char *)&ebx, (char *)&edx, (char *)&ecx);
4068
4069         __cpuid(1, fms, ebx, ecx, edx);
4070         family = (fms >> 8) & 0xf;
4071         model = (fms >> 4) & 0xf;
4072         stepping = fms & 0xf;
4073         if (family == 6 || family == 0xf)
4074                 model += ((fms >> 16) & 0xf) << 4;
4075
4076         if (!quiet) {
4077                 fprintf(outf, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
4078                         max_level, family, model, stepping, family, model, stepping);
4079                 fprintf(outf, "CPUID(1): %s %s %s %s %s %s %s %s %s\n",
4080                         ecx & (1 << 0) ? "SSE3" : "-",
4081                         ecx & (1 << 3) ? "MONITOR" : "-",
4082                         ecx & (1 << 6) ? "SMX" : "-",
4083                         ecx & (1 << 7) ? "EIST" : "-",
4084                         ecx & (1 << 8) ? "TM2" : "-",
4085                         edx & (1 << 4) ? "TSC" : "-",
4086                         edx & (1 << 5) ? "MSR" : "-",
4087                         edx & (1 << 22) ? "ACPI-TM" : "-",
4088                         edx & (1 << 29) ? "TM" : "-");
4089         }
4090
4091         if (!(edx & (1 << 5)))
4092                 errx(1, "CPUID: no MSR");
4093
4094         /*
4095          * check max extended function levels of CPUID.
4096          * This is needed to check for invariant TSC.
4097          * This check is valid for both Intel and AMD.
4098          */
4099         ebx = ecx = edx = 0;
4100         __cpuid(0x80000000, max_extended_level, ebx, ecx, edx);
4101
4102         if (max_extended_level >= 0x80000007) {
4103
4104                 /*
4105                  * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
4106                  * this check is valid for both Intel and AMD
4107                  */
4108                 __cpuid(0x80000007, eax, ebx, ecx, edx);
4109                 has_invariant_tsc = edx & (1 << 8);
4110         }
4111
4112         /*
4113          * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
4114          * this check is valid for both Intel and AMD
4115          */
4116
4117         __cpuid(0x6, eax, ebx, ecx, edx);
4118         has_aperf = ecx & (1 << 0);
4119         if (has_aperf) {
4120                 BIC_PRESENT(BIC_Avg_MHz);
4121                 BIC_PRESENT(BIC_Busy);
4122                 BIC_PRESENT(BIC_Bzy_MHz);
4123         }
4124         do_dts = eax & (1 << 0);
4125         if (do_dts)
4126                 BIC_PRESENT(BIC_CoreTmp);
4127         has_turbo = eax & (1 << 1);
4128         do_ptm = eax & (1 << 6);
4129         if (do_ptm)
4130                 BIC_PRESENT(BIC_PkgTmp);
4131         has_hwp = eax & (1 << 7);
4132         has_hwp_notify = eax & (1 << 8);
4133         has_hwp_activity_window = eax & (1 << 9);
4134         has_hwp_epp = eax & (1 << 10);
4135         has_hwp_pkg = eax & (1 << 11);
4136         has_epb = ecx & (1 << 3);
4137
4138         if (!quiet)
4139                 fprintf(outf, "CPUID(6): %sAPERF, %sTURBO, %sDTS, %sPTM, %sHWP, "
4140                         "%sHWPnotify, %sHWPwindow, %sHWPepp, %sHWPpkg, %sEPB\n",
4141                         has_aperf ? "" : "No-",
4142                         has_turbo ? "" : "No-",
4143                         do_dts ? "" : "No-",
4144                         do_ptm ? "" : "No-",
4145                         has_hwp ? "" : "No-",
4146                         has_hwp_notify ? "" : "No-",
4147                         has_hwp_activity_window ? "" : "No-",
4148                         has_hwp_epp ? "" : "No-",
4149                         has_hwp_pkg ? "" : "No-",
4150                         has_epb ? "" : "No-");
4151
4152         if (!quiet)
4153                 decode_misc_enable_msr();
4154
4155
4156         if (max_level >= 0x7 && !quiet) {
4157                 int has_sgx;
4158
4159                 ecx = 0;
4160
4161                 __cpuid_count(0x7, 0, eax, ebx, ecx, edx);
4162
4163                 has_sgx = ebx & (1 << 2);
4164                 fprintf(outf, "CPUID(7): %sSGX\n", has_sgx ? "" : "No-");
4165
4166                 if (has_sgx)
4167                         decode_feature_control_msr();
4168         }
4169
4170         if (max_level >= 0x15) {
4171                 unsigned int eax_crystal;
4172                 unsigned int ebx_tsc;
4173
4174                 /*
4175                  * CPUID 15H TSC/Crystal ratio, possibly Crystal Hz
4176                  */
4177                 eax_crystal = ebx_tsc = crystal_hz = edx = 0;
4178                 __cpuid(0x15, eax_crystal, ebx_tsc, crystal_hz, edx);
4179
4180                 if (ebx_tsc != 0) {
4181
4182                         if (!quiet && (ebx != 0))
4183                                 fprintf(outf, "CPUID(0x15): eax_crystal: %d ebx_tsc: %d ecx_crystal_hz: %d\n",
4184                                         eax_crystal, ebx_tsc, crystal_hz);
4185
4186                         if (crystal_hz == 0)
4187                                 switch(model) {
4188                                 case INTEL_FAM6_SKYLAKE_MOBILE: /* SKL */
4189                                 case INTEL_FAM6_SKYLAKE_DESKTOP:        /* SKL */
4190                                 case INTEL_FAM6_KABYLAKE_MOBILE:        /* KBL */
4191                                 case INTEL_FAM6_KABYLAKE_DESKTOP:       /* KBL */
4192                                         crystal_hz = 24000000;  /* 24.0 MHz */
4193                                         break;
4194                                 case INTEL_FAM6_SKYLAKE_X:      /* SKX */
4195                                 case INTEL_FAM6_ATOM_DENVERTON: /* DNV */
4196                                         crystal_hz = 25000000;  /* 25.0 MHz */
4197                                         break;
4198                                 case INTEL_FAM6_ATOM_GOLDMONT:  /* BXT */
4199                                 case INTEL_FAM6_ATOM_GEMINI_LAKE:
4200                                         crystal_hz = 19200000;  /* 19.2 MHz */
4201                                         break;
4202                                 default:
4203                                         crystal_hz = 0;
4204                         }
4205
4206                         if (crystal_hz) {
4207                                 tsc_hz =  (unsigned long long) crystal_hz * ebx_tsc / eax_crystal;
4208                                 if (!quiet)
4209                                         fprintf(outf, "TSC: %lld MHz (%d Hz * %d / %d / 1000000)\n",
4210                                                 tsc_hz / 1000000, crystal_hz, ebx_tsc,  eax_crystal);
4211                         }
4212                 }
4213         }
4214         if (max_level >= 0x16) {
4215                 unsigned int base_mhz, max_mhz, bus_mhz, edx;
4216
4217                 /*
4218                  * CPUID 16H Base MHz, Max MHz, Bus MHz
4219                  */
4220                 base_mhz = max_mhz = bus_mhz = edx = 0;
4221
4222                 __cpuid(0x16, base_mhz, max_mhz, bus_mhz, edx);
4223                 if (!quiet)
4224                         fprintf(outf, "CPUID(0x16): base_mhz: %d max_mhz: %d bus_mhz: %d\n",
4225                                 base_mhz, max_mhz, bus_mhz);
4226         }
4227
4228         if (has_aperf)
4229                 aperf_mperf_multiplier = get_aperf_mperf_multiplier(family, model);
4230
4231         BIC_PRESENT(BIC_IRQ);
4232         BIC_PRESENT(BIC_TSC_MHz);
4233
4234         if (probe_nhm_msrs(family, model)) {
4235                 do_nhm_platform_info = 1;
4236                 BIC_PRESENT(BIC_CPU_c1);
4237                 BIC_PRESENT(BIC_CPU_c3);
4238                 BIC_PRESENT(BIC_CPU_c6);
4239                 BIC_PRESENT(BIC_SMI);
4240         }
4241         do_snb_cstates = has_snb_msrs(family, model);
4242
4243         if (do_snb_cstates)
4244                 BIC_PRESENT(BIC_CPU_c7);
4245
4246         do_irtl_snb = has_snb_msrs(family, model);
4247         if (do_snb_cstates && (pkg_cstate_limit >= PCL__2))
4248                 BIC_PRESENT(BIC_Pkgpc2);
4249         if (pkg_cstate_limit >= PCL__3)
4250                 BIC_PRESENT(BIC_Pkgpc3);
4251         if (pkg_cstate_limit >= PCL__6)
4252                 BIC_PRESENT(BIC_Pkgpc6);
4253         if (do_snb_cstates && (pkg_cstate_limit >= PCL__7))
4254                 BIC_PRESENT(BIC_Pkgpc7);
4255         if (has_slv_msrs(family, model)) {
4256                 BIC_NOT_PRESENT(BIC_Pkgpc2);
4257                 BIC_NOT_PRESENT(BIC_Pkgpc3);
4258                 BIC_PRESENT(BIC_Pkgpc6);
4259                 BIC_NOT_PRESENT(BIC_Pkgpc7);
4260                 BIC_PRESENT(BIC_Mod_c6);
4261                 use_c1_residency_msr = 1;
4262         }
4263         if (is_dnv(family, model)) {
4264                 BIC_PRESENT(BIC_CPU_c1);
4265                 BIC_NOT_PRESENT(BIC_CPU_c3);
4266                 BIC_NOT_PRESENT(BIC_Pkgpc3);
4267                 BIC_NOT_PRESENT(BIC_CPU_c7);
4268                 BIC_NOT_PRESENT(BIC_Pkgpc7);
4269                 use_c1_residency_msr = 1;
4270         }
4271         if (is_skx(family, model)) {
4272                 BIC_NOT_PRESENT(BIC_CPU_c3);
4273                 BIC_NOT_PRESENT(BIC_Pkgpc3);
4274                 BIC_NOT_PRESENT(BIC_CPU_c7);
4275                 BIC_NOT_PRESENT(BIC_Pkgpc7);
4276         }
4277         if (is_bdx(family, model)) {
4278                 BIC_NOT_PRESENT(BIC_CPU_c7);
4279                 BIC_NOT_PRESENT(BIC_Pkgpc7);
4280         }
4281         if (has_hsw_msrs(family, model)) {
4282                 BIC_PRESENT(BIC_Pkgpc8);
4283                 BIC_PRESENT(BIC_Pkgpc9);
4284                 BIC_PRESENT(BIC_Pkgpc10);
4285         }
4286         do_irtl_hsw = has_hsw_msrs(family, model);
4287         if (has_skl_msrs(family, model)) {
4288                 BIC_PRESENT(BIC_Totl_c0);
4289                 BIC_PRESENT(BIC_Any_c0);
4290                 BIC_PRESENT(BIC_GFX_c0);
4291                 BIC_PRESENT(BIC_CPUGFX);
4292         }
4293         do_slm_cstates = is_slm(family, model);
4294         do_knl_cstates  = is_knl(family, model);
4295
4296         if (!quiet)
4297                 decode_misc_pwr_mgmt_msr();
4298
4299         if (!quiet && has_slv_msrs(family, model))
4300                 decode_c6_demotion_policy_msr();
4301
4302         rapl_probe(family, model);
4303         perf_limit_reasons_probe(family, model);
4304
4305         if (!quiet)
4306                 dump_cstate_pstate_config_info(family, model);
4307
4308         if (!quiet)
4309                 dump_sysfs_cstate_config();
4310         if (!quiet)
4311                 dump_sysfs_pstate_config();
4312
4313         if (has_skl_msrs(family, model))
4314                 calculate_tsc_tweak();
4315
4316         if (!access("/sys/class/drm/card0/power/rc6_residency_ms", R_OK))
4317                 BIC_PRESENT(BIC_GFX_rc6);
4318
4319         if (!access("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", R_OK))
4320                 BIC_PRESENT(BIC_GFXMHz);
4321
4322         if (!quiet)
4323                 decode_misc_feature_control();
4324
4325         return;
4326 }
4327
4328
4329 /*
4330  * in /dev/cpu/ return success for names that are numbers
4331  * ie. filter out ".", "..", "microcode".
4332  */
4333 int dir_filter(const struct dirent *dirp)
4334 {
4335         if (isdigit(dirp->d_name[0]))
4336                 return 1;
4337         else
4338                 return 0;
4339 }
4340
4341 int open_dev_cpu_msr(int dummy1)
4342 {
4343         return 0;
4344 }
4345
4346 void topology_probe()
4347 {
4348         int i;
4349         int max_core_id = 0;
4350         int max_package_id = 0;
4351         int max_siblings = 0;
4352         struct cpu_topology {
4353                 int core_id;
4354                 int physical_package_id;
4355         } *cpus;
4356
4357         /* Initialize num_cpus, max_cpu_num */
4358         topo.num_cpus = 0;
4359         topo.max_cpu_num = 0;
4360         for_all_proc_cpus(count_cpus);
4361         if (!summary_only && topo.num_cpus > 1)
4362                 BIC_PRESENT(BIC_CPU);
4363
4364         if (debug > 1)
4365                 fprintf(outf, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
4366
4367         cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
4368         if (cpus == NULL)
4369                 err(1, "calloc cpus");
4370
4371         /*
4372          * Allocate and initialize cpu_present_set
4373          */
4374         cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
4375         if (cpu_present_set == NULL)
4376                 err(3, "CPU_ALLOC");
4377         cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
4378         CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
4379         for_all_proc_cpus(mark_cpu_present);
4380
4381         /*
4382          * Validate that all cpus in cpu_subset are also in cpu_present_set
4383          */
4384         for (i = 0; i < CPU_SUBSET_MAXCPUS; ++i) {
4385                 if (CPU_ISSET_S(i, cpu_subset_size, cpu_subset))
4386                         if (!CPU_ISSET_S(i, cpu_present_setsize, cpu_present_set))
4387                                 err(1, "cpu%d not present", i);
4388         }
4389
4390         /*
4391          * Allocate and initialize cpu_affinity_set
4392          */
4393         cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
4394         if (cpu_affinity_set == NULL)
4395                 err(3, "CPU_ALLOC");
4396         cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
4397         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
4398
4399
4400         /*
4401          * For online cpus
4402          * find max_core_id, max_package_id
4403          */
4404         for (i = 0; i <= topo.max_cpu_num; ++i) {
4405                 int siblings;
4406
4407                 if (cpu_is_not_present(i)) {
4408                         if (debug > 1)
4409                                 fprintf(outf, "cpu%d NOT PRESENT\n", i);
4410                         continue;
4411                 }
4412                 cpus[i].core_id = get_core_id(i);
4413                 if (cpus[i].core_id > max_core_id)
4414                         max_core_id = cpus[i].core_id;
4415
4416                 cpus[i].physical_package_id = get_physical_package_id(i);
4417                 if (cpus[i].physical_package_id > max_package_id)
4418                         max_package_id = cpus[i].physical_package_id;
4419
4420                 siblings = get_num_ht_siblings(i);
4421                 if (siblings > max_siblings)
4422                         max_siblings = siblings;
4423                 if (debug > 1)
4424                         fprintf(outf, "cpu %d pkg %d core %d\n",
4425                                 i, cpus[i].physical_package_id, cpus[i].core_id);
4426         }
4427         topo.num_cores_per_pkg = max_core_id + 1;
4428         if (debug > 1)
4429                 fprintf(outf, "max_core_id %d, sizing for %d cores per package\n",
4430                         max_core_id, topo.num_cores_per_pkg);
4431         if (!summary_only && topo.num_cores_per_pkg > 1)
4432                 BIC_PRESENT(BIC_Core);
4433
4434         topo.num_packages = max_package_id + 1;
4435         if (debug > 1)
4436                 fprintf(outf, "max_package_id %d, sizing for %d packages\n",
4437                         max_package_id, topo.num_packages);
4438         if (!summary_only && topo.num_packages > 1)
4439                 BIC_PRESENT(BIC_Package);
4440
4441         topo.num_threads_per_core = max_siblings;
4442         if (debug > 1)
4443                 fprintf(outf, "max_siblings %d\n", max_siblings);
4444
4445         free(cpus);
4446 }
4447
4448 void
4449 allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
4450 {
4451         int i;
4452
4453         *t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
4454                 topo.num_packages, sizeof(struct thread_data));
4455         if (*t == NULL)
4456                 goto error;
4457
4458         for (i = 0; i < topo.num_threads_per_core *
4459                 topo.num_cores_per_pkg * topo.num_packages; i++)
4460                 (*t)[i].cpu_id = -1;
4461
4462         *c = calloc(topo.num_cores_per_pkg * topo.num_packages,
4463                 sizeof(struct core_data));
4464         if (*c == NULL)
4465                 goto error;
4466
4467         for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
4468                 (*c)[i].core_id = -1;
4469
4470         *p = calloc(topo.num_packages, sizeof(struct pkg_data));
4471         if (*p == NULL)
4472                 goto error;
4473
4474         for (i = 0; i < topo.num_packages; i++)
4475                 (*p)[i].package_id = i;
4476
4477         return;
4478 error:
4479         err(1, "calloc counters");
4480 }
4481 /*
4482  * init_counter()
4483  *
4484  * set cpu_id, core_num, pkg_num
4485  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
4486  *
4487  * increment topo.num_cores when 1st core in pkg seen
4488  */
4489 void init_counter(struct thread_data *thread_base, struct core_data *core_base,
4490         struct pkg_data *pkg_base, int thread_num, int core_num,
4491         int pkg_num, int cpu_id)
4492 {
4493         struct thread_data *t;
4494         struct core_data *c;
4495         struct pkg_data *p;
4496
4497         t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
4498         c = GET_CORE(core_base, core_num, pkg_num);
4499         p = GET_PKG(pkg_base, pkg_num);
4500
4501         t->cpu_id = cpu_id;
4502         if (thread_num == 0) {
4503                 t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
4504                 if (cpu_is_first_core_in_package(cpu_id))
4505                         t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
4506         }
4507
4508         c->core_id = core_num;
4509         p->package_id = pkg_num;
4510 }
4511
4512
4513 int initialize_counters(int cpu_id)
4514 {
4515         int my_thread_id, my_core_id, my_package_id;
4516
4517         my_package_id = get_physical_package_id(cpu_id);
4518         my_core_id = get_core_id(cpu_id);
4519         my_thread_id = get_cpu_position_in_core(cpu_id);
4520         if (!my_thread_id)
4521                 topo.num_cores++;
4522
4523         init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
4524         init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
4525         return 0;
4526 }
4527
4528 void allocate_output_buffer()
4529 {
4530         output_buffer = calloc(1, (1 + topo.num_cpus) * 1024);
4531         outp = output_buffer;
4532         if (outp == NULL)
4533                 err(-1, "calloc output buffer");
4534 }
4535 void allocate_fd_percpu(void)
4536 {
4537         fd_percpu = calloc(topo.max_cpu_num + 1, sizeof(int));
4538         if (fd_percpu == NULL)
4539                 err(-1, "calloc fd_percpu");
4540 }
4541 void allocate_irq_buffers(void)
4542 {
4543         irq_column_2_cpu = calloc(topo.num_cpus, sizeof(int));
4544         if (irq_column_2_cpu == NULL)
4545                 err(-1, "calloc %d", topo.num_cpus);
4546
4547         irqs_per_cpu = calloc(topo.max_cpu_num + 1, sizeof(int));
4548         if (irqs_per_cpu == NULL)
4549                 err(-1, "calloc %d", topo.max_cpu_num + 1);
4550 }
4551 void setup_all_buffers(void)
4552 {
4553         topology_probe();
4554         allocate_irq_buffers();
4555         allocate_fd_percpu();
4556         allocate_counters(&thread_even, &core_even, &package_even);
4557         allocate_counters(&thread_odd, &core_odd, &package_odd);
4558         allocate_output_buffer();
4559         for_all_proc_cpus(initialize_counters);
4560 }
4561
4562 void set_base_cpu(void)
4563 {
4564         base_cpu = sched_getcpu();
4565         if (base_cpu < 0)
4566                 err(-ENODEV, "No valid cpus found");
4567
4568         if (debug > 1)
4569                 fprintf(outf, "base_cpu = %d\n", base_cpu);
4570 }
4571
4572 void turbostat_init()
4573 {
4574         setup_all_buffers();
4575         set_base_cpu();
4576         check_dev_msr();
4577         check_permissions();
4578         process_cpuid();
4579
4580
4581         if (!quiet)
4582                 for_all_cpus(print_hwp, ODD_COUNTERS);
4583
4584         if (!quiet)
4585                 for_all_cpus(print_epb, ODD_COUNTERS);
4586
4587         if (!quiet)
4588                 for_all_cpus(print_perf_limit, ODD_COUNTERS);
4589
4590         if (!quiet)
4591                 for_all_cpus(print_rapl, ODD_COUNTERS);
4592
4593         for_all_cpus(set_temperature_target, ODD_COUNTERS);
4594
4595         if (!quiet)
4596                 for_all_cpus(print_thermal, ODD_COUNTERS);
4597
4598         if (!quiet && do_irtl_snb)
4599                 print_irtl();
4600 }
4601
4602 int fork_it(char **argv)
4603 {
4604         pid_t child_pid;
4605         int status;
4606
4607         snapshot_proc_sysfs_files();
4608         status = for_all_cpus(get_counters, EVEN_COUNTERS);
4609         if (status)
4610                 exit(status);
4611         /* clear affinity side-effect of get_counters() */
4612         sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
4613         gettimeofday(&tv_even, (struct timezone *)NULL);
4614
4615         child_pid = fork();
4616         if (!child_pid) {
4617                 /* child */
4618                 execvp(argv[0], argv);
4619                 err(errno, "exec %s", argv[0]);
4620         } else {
4621
4622                 /* parent */
4623                 if (child_pid == -1)
4624                         err(1, "fork");
4625
4626                 signal(SIGINT, SIG_IGN);
4627                 signal(SIGQUIT, SIG_IGN);
4628                 if (waitpid(child_pid, &status, 0) == -1)
4629                         err(status, "waitpid");
4630         }
4631         /*
4632          * n.b. fork_it() does not check for errors from for_all_cpus()
4633          * because re-starting is problematic when forking
4634          */
4635         snapshot_proc_sysfs_files();
4636         for_all_cpus(get_counters, ODD_COUNTERS);
4637         gettimeofday(&tv_odd, (struct timezone *)NULL);
4638         timersub(&tv_odd, &tv_even, &tv_delta);
4639         if (for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS))
4640                 fprintf(outf, "%s: Counter reset detected\n", progname);
4641         else {
4642                 compute_average(EVEN_COUNTERS);
4643                 format_all_counters(EVEN_COUNTERS);
4644         }
4645
4646         fprintf(outf, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
4647
4648         flush_output_stderr();
4649
4650         return status;
4651 }
4652
4653 int get_and_dump_counters(void)
4654 {
4655         int status;
4656
4657         snapshot_proc_sysfs_files();
4658         status = for_all_cpus(get_counters, ODD_COUNTERS);
4659         if (status)
4660                 return status;
4661
4662         status = for_all_cpus(dump_counters, ODD_COUNTERS);
4663         if (status)
4664                 return status;
4665
4666         flush_output_stdout();
4667
4668         return status;
4669 }
4670
4671 void print_version() {
4672         fprintf(outf, "turbostat version 17.06.23"
4673                 " - Len Brown <lenb@kernel.org>\n");
4674 }
4675
4676 int add_counter(unsigned int msr_num, char *path, char *name,
4677         unsigned int width, enum counter_scope scope,
4678         enum counter_type type, enum counter_format format, int flags)
4679 {
4680         struct msr_counter *msrp;
4681
4682         msrp = calloc(1, sizeof(struct msr_counter));
4683         if (msrp == NULL) {
4684                 perror("calloc");
4685                 exit(1);
4686         }
4687
4688         msrp->msr_num = msr_num;
4689         strncpy(msrp->name, name, NAME_BYTES);
4690         if (path)
4691                 strncpy(msrp->path, path, PATH_BYTES);
4692         msrp->width = width;
4693         msrp->type = type;
4694         msrp->format = format;
4695         msrp->flags = flags;
4696
4697         switch (scope) {
4698
4699         case SCOPE_CPU:
4700                 msrp->next = sys.tp;
4701                 sys.tp = msrp;
4702                 sys.added_thread_counters++;
4703                 if (sys.added_thread_counters > MAX_ADDED_COUNTERS) {
4704                         fprintf(stderr, "exceeded max %d added thread counters\n",
4705                                 MAX_ADDED_COUNTERS);
4706                         exit(-1);
4707                 }
4708                 break;
4709
4710         case SCOPE_CORE:
4711                 msrp->next = sys.cp;
4712                 sys.cp = msrp;
4713                 sys.added_core_counters++;
4714                 if (sys.added_core_counters > MAX_ADDED_COUNTERS) {
4715                         fprintf(stderr, "exceeded max %d added core counters\n",
4716                                 MAX_ADDED_COUNTERS);
4717                         exit(-1);
4718                 }
4719                 break;
4720
4721         case SCOPE_PACKAGE:
4722                 msrp->next = sys.pp;
4723                 sys.pp = msrp;
4724                 sys.added_package_counters++;
4725                 if (sys.added_package_counters > MAX_ADDED_COUNTERS) {
4726                         fprintf(stderr, "exceeded max %d added package counters\n",
4727                                 MAX_ADDED_COUNTERS);
4728                         exit(-1);
4729                 }
4730                 break;
4731         }
4732
4733         return 0;
4734 }
4735
4736 void parse_add_command(char *add_command)
4737 {
4738         int msr_num = 0;
4739         char *path = NULL;
4740         char name_buffer[NAME_BYTES] = "";
4741         int width = 64;
4742         int fail = 0;
4743         enum counter_scope scope = SCOPE_CPU;
4744         enum counter_type type = COUNTER_CYCLES;
4745         enum counter_format format = FORMAT_DELTA;
4746
4747         while (add_command) {
4748
4749                 if (sscanf(add_command, "msr0x%x", &msr_num) == 1)
4750                         goto next;
4751
4752                 if (sscanf(add_command, "msr%d", &msr_num) == 1)
4753                         goto next;
4754
4755                 if (*add_command == '/') {
4756                         path = add_command;
4757                         goto next;
4758                 }
4759
4760                 if (sscanf(add_command, "u%d", &width) == 1) {
4761                         if ((width == 32) || (width == 64))
4762                                 goto next;
4763                         width = 64;
4764                 }
4765                 if (!strncmp(add_command, "cpu", strlen("cpu"))) {
4766                         scope = SCOPE_CPU;
4767                         goto next;
4768                 }
4769                 if (!strncmp(add_command, "core", strlen("core"))) {
4770                         scope = SCOPE_CORE;
4771                         goto next;
4772                 }
4773                 if (!strncmp(add_command, "package", strlen("package"))) {
4774                         scope = SCOPE_PACKAGE;
4775                         goto next;
4776                 }
4777                 if (!strncmp(add_command, "cycles", strlen("cycles"))) {
4778                         type = COUNTER_CYCLES;
4779                         goto next;
4780                 }
4781                 if (!strncmp(add_command, "seconds", strlen("seconds"))) {
4782                         type = COUNTER_SECONDS;
4783                         goto next;
4784                 }
4785                 if (!strncmp(add_command, "usec", strlen("usec"))) {
4786                         type = COUNTER_USEC;
4787                         goto next;
4788                 }
4789                 if (!strncmp(add_command, "raw", strlen("raw"))) {
4790                         format = FORMAT_RAW;
4791                         goto next;
4792                 }
4793                 if (!strncmp(add_command, "delta", strlen("delta"))) {
4794                         format = FORMAT_DELTA;
4795                         goto next;
4796                 }
4797                 if (!strncmp(add_command, "percent", strlen("percent"))) {
4798                         format = FORMAT_PERCENT;
4799                         goto next;
4800                 }
4801
4802                 if (sscanf(add_command, "%18s,%*s", name_buffer) == 1) {        /* 18 < NAME_BYTES */
4803                         char *eos;
4804
4805                         eos = strchr(name_buffer, ',');
4806                         if (eos)
4807                                 *eos = '\0';
4808                         goto next;
4809                 }
4810
4811 next:
4812                 add_command = strchr(add_command, ',');
4813                 if (add_command) {
4814                         *add_command = '\0';
4815                         add_command++;
4816                 }
4817
4818         }
4819         if ((msr_num == 0) && (path == NULL)) {
4820                 fprintf(stderr, "--add: (msrDDD | msr0xXXX | /path_to_counter ) required\n");
4821                 fail++;
4822         }
4823
4824         /* generate default column header */
4825         if (*name_buffer == '\0') {
4826                 if (width == 32)
4827                         sprintf(name_buffer, "M0x%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
4828                 else
4829                         sprintf(name_buffer, "M0X%x%s", msr_num, format == FORMAT_PERCENT ? "%" : "");
4830         }
4831
4832         if (add_counter(msr_num, path, name_buffer, width, scope, type, format, 0))
4833                 fail++;
4834
4835         if (fail) {
4836                 help();
4837                 exit(1);
4838         }
4839 }
4840
4841 int is_deferred_skip(char *name)
4842 {
4843         int i;
4844
4845         for (i = 0; i < deferred_skip_index; ++i)
4846                 if (!strcmp(name, deferred_skip_names[i]))
4847                         return 1;
4848         return 0;
4849 }
4850
4851 void probe_sysfs(void)
4852 {
4853         char path[64];
4854         char name_buf[16];
4855         FILE *input;
4856         int state;
4857         char *sp;
4858
4859         if (!DO_BIC(BIC_sysfs))
4860                 return;
4861
4862         for (state = 10; state > 0; --state) {
4863
4864                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name",
4865                         base_cpu, state);
4866                 input = fopen(path, "r");
4867                 if (input == NULL)
4868                         continue;
4869                 fgets(name_buf, sizeof(name_buf), input);
4870
4871                  /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
4872                 sp = strchr(name_buf, '-');
4873                 if (!sp)
4874                         sp = strchrnul(name_buf, '\n');
4875                 *sp = '%';
4876                 *(sp + 1) = '\0';
4877
4878                 fclose(input);
4879
4880                 sprintf(path, "cpuidle/state%d/time", state);
4881
4882                 if (is_deferred_skip(name_buf))
4883                         continue;
4884
4885                 add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_USEC,
4886                                 FORMAT_PERCENT, SYSFS_PERCPU);
4887         }
4888
4889         for (state = 10; state > 0; --state) {
4890
4891                 sprintf(path, "/sys/devices/system/cpu/cpu%d/cpuidle/state%d/name",
4892                         base_cpu, state);
4893                 input = fopen(path, "r");
4894                 if (input == NULL)
4895                         continue;
4896                 fgets(name_buf, sizeof(name_buf), input);
4897                  /* truncate "C1-HSW\n" to "C1", or truncate "C1\n" to "C1" */
4898                 sp = strchr(name_buf, '-');
4899                 if (!sp)
4900                         sp = strchrnul(name_buf, '\n');
4901                 *sp = '\0';
4902                 fclose(input);
4903
4904                 sprintf(path, "cpuidle/state%d/usage", state);
4905
4906                 if (is_deferred_skip(name_buf))
4907                         continue;
4908
4909                 add_counter(0, path, name_buf, 64, SCOPE_CPU, COUNTER_ITEMS,
4910                                 FORMAT_DELTA, SYSFS_PERCPU);
4911         }
4912
4913 }
4914
4915
4916 /*
4917  * parse cpuset with following syntax
4918  * 1,2,4..6,8-10 and set bits in cpu_subset
4919  */
4920 void parse_cpu_command(char *optarg)
4921 {
4922         unsigned int start, end;
4923         char *next;
4924
4925         if (!strcmp(optarg, "core")) {
4926                 if (cpu_subset)
4927                         goto error;
4928                 show_core_only++;
4929                 return;
4930         }
4931         if (!strcmp(optarg, "package")) {
4932                 if (cpu_subset)
4933                         goto error;
4934                 show_pkg_only++;
4935                 return;
4936         }
4937         if (show_core_only || show_pkg_only)
4938                 goto error;
4939
4940         cpu_subset = CPU_ALLOC(CPU_SUBSET_MAXCPUS);
4941         if (cpu_subset == NULL)
4942                 err(3, "CPU_ALLOC");
4943         cpu_subset_size = CPU_ALLOC_SIZE(CPU_SUBSET_MAXCPUS);
4944
4945         CPU_ZERO_S(cpu_subset_size, cpu_subset);
4946
4947         next = optarg;
4948
4949         while (next && *next) {
4950
4951                 if (*next == '-')       /* no negative cpu numbers */
4952                         goto error;
4953
4954                 start = strtoul(next, &next, 10);
4955
4956                 if (start >= CPU_SUBSET_MAXCPUS)
4957                         goto error;
4958                 CPU_SET_S(start, cpu_subset_size, cpu_subset);
4959
4960                 if (*next == '\0')
4961                         break;
4962
4963                 if (*next == ',') {
4964                         next += 1;
4965                         continue;
4966                 }
4967
4968                 if (*next == '-') {
4969                         next += 1;      /* start range */
4970                 } else if (*next == '.') {
4971                         next += 1;
4972                         if (*next == '.')
4973                                 next += 1;      /* start range */
4974                         else
4975                                 goto error;
4976                 }
4977
4978                 end = strtoul(next, &next, 10);
4979                 if (end <= start)
4980                         goto error;
4981
4982                 while (++start <= end) {
4983                         if (start >= CPU_SUBSET_MAXCPUS)
4984                                 goto error;
4985                         CPU_SET_S(start, cpu_subset_size, cpu_subset);
4986                 }
4987
4988                 if (*next == ',')
4989                         next += 1;
4990                 else if (*next != '\0')
4991                         goto error;
4992         }
4993
4994         return;
4995
4996 error:
4997         fprintf(stderr, "\"--cpu %s\" malformed\n", optarg);
4998         help();
4999         exit(-1);
5000 }
5001
5002
5003 void cmdline(int argc, char **argv)
5004 {
5005         int opt;
5006         int option_index = 0;
5007         static struct option long_options[] = {
5008                 {"add",         required_argument,      0, 'a'},
5009                 {"cpu",         required_argument,      0, 'c'},
5010                 {"Dump",        no_argument,            0, 'D'},
5011                 {"debug",       no_argument,            0, 'd'},        /* internal, not documented */
5012                 {"enable",      required_argument,      0, 'e'},
5013                 {"interval",    required_argument,      0, 'i'},
5014                 {"help",        no_argument,            0, 'h'},
5015                 {"hide",        required_argument,      0, 'H'},        // meh, -h taken by --help
5016                 {"Joules",      no_argument,            0, 'J'},
5017                 {"list",        no_argument,            0, 'l'},
5018                 {"out",         required_argument,      0, 'o'},
5019                 {"quiet",       no_argument,            0, 'q'},
5020                 {"show",        required_argument,      0, 's'},
5021                 {"Summary",     no_argument,            0, 'S'},
5022                 {"TCC",         required_argument,      0, 'T'},
5023                 {"version",     no_argument,            0, 'v' },
5024                 {0,             0,                      0,  0 }
5025         };
5026
5027         progname = argv[0];
5028
5029         while ((opt = getopt_long_only(argc, argv, "+C:c:Dde:hi:Jo:qST:v",
5030                                 long_options, &option_index)) != -1) {
5031                 switch (opt) {
5032                 case 'a':
5033                         parse_add_command(optarg);
5034                         break;
5035                 case 'c':
5036                         parse_cpu_command(optarg);
5037                         break;
5038                 case 'D':
5039                         dump_only++;
5040                         break;
5041                 case 'e':
5042                         /* --enable specified counter */
5043                         bic_enabled |= bic_lookup(optarg, SHOW_LIST);
5044                         break;
5045                 case 'd':
5046                         debug++;
5047                         ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
5048                         break;
5049                 case 'H':
5050                         /*
5051                          * --hide: do not show those specified
5052                          *  multiple invocations simply clear more bits in enabled mask
5053                          */
5054                         bic_enabled &= ~bic_lookup(optarg, HIDE_LIST);
5055                         break;
5056                 case 'h':
5057                 default:
5058                         help();
5059                         exit(1);
5060                 case 'i':
5061                         {
5062                                 double interval = strtod(optarg, NULL);
5063
5064                                 if (interval < 0.001) {
5065                                         fprintf(outf, "interval %f seconds is too small\n",
5066                                                 interval);
5067                                         exit(2);
5068                                 }
5069
5070                                 interval_ts.tv_sec = interval;
5071                                 interval_ts.tv_nsec = (interval - interval_ts.tv_sec) * 1000000000;
5072                         }
5073                         break;
5074                 case 'J':
5075                         rapl_joules++;
5076                         break;
5077                 case 'l':
5078                         ENABLE_BIC(BIC_DISABLED_BY_DEFAULT);
5079                         list_header_only++;
5080                         quiet++;
5081                         break;
5082                 case 'o':
5083                         outf = fopen_or_die(optarg, "w");
5084                         break;
5085                 case 'q':
5086                         quiet = 1;
5087                         break;
5088                 case 's':
5089                         /*
5090                          * --show: show only those specified
5091                          *  The 1st invocation will clear and replace the enabled mask
5092                          *  subsequent invocations can add to it.
5093                          */
5094                         if (shown == 0)
5095                                 bic_enabled = bic_lookup(optarg, SHOW_LIST);
5096                         else
5097                                 bic_enabled |= bic_lookup(optarg, SHOW_LIST);
5098                         shown = 1;
5099                         break;
5100                 case 'S':
5101                         summary_only++;
5102                         break;
5103                 case 'T':
5104                         tcc_activation_temp_override = atoi(optarg);
5105                         break;
5106                 case 'v':
5107                         print_version();
5108                         exit(0);
5109                         break;
5110                 }
5111         }
5112 }
5113
5114 int main(int argc, char **argv)
5115 {
5116         outf = stderr;
5117
5118         cmdline(argc, argv);
5119
5120         if (!quiet)
5121                 print_version();
5122
5123         probe_sysfs();
5124
5125         turbostat_init();
5126
5127         /* dump counters and exit */
5128         if (dump_only)
5129                 return get_and_dump_counters();
5130
5131         /* list header and exit */
5132         if (list_header_only) {
5133                 print_header(",");
5134                 flush_output_stdout();
5135                 return 0;
5136         }
5137
5138         /*
5139          * if any params left, it must be a command to fork
5140          */
5141         if (argc - optind)
5142                 return fork_it(argv + optind);
5143         else
5144                 turbostat_loop();
5145
5146         return 0;
5147 }