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