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