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