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