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