OSDN Git Service

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