python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
// SPDX-License-Identifier: GPL-2.0 #include <linux/export.h> #include <linux/types.h> #include <linux/bits.h> #include "probe.h" static umode_t not_visible(struct kobject *kobj, struct attribute *attr, int i) { return 0; } /* * Accepts msr[] array with non populated entries as long as either * msr[i].msr is 0 or msr[i].grp is NULL. Note that the default sysfs * visibility is visible when group->is_visible callback is set. */ unsigned long perf_msr_probe(struct perf_msr *msr, int cnt, bool zero, void *data) { unsigned long avail = 0; unsigned int bit; u64 val; if (cnt >= BITS_PER_LONG) return 0; for (bit = 0; bit < cnt; bit++) { if (!msr[bit].no_check) { struct attribute_group *grp = msr[bit].grp; u64 mask; /* skip entry with no group */ if (!grp) continue; grp->is_visible = not_visible; /* skip unpopulated entry */ if (!msr[bit].msr) continue; if (msr[bit].test && !msr[bit].test(bit, data)) continue; /* Virt sucks; you cannot tell if a R/O MSR is present :/ */ if (rdmsrl_safe(msr[bit].msr, &val)) continue; mask = msr[bit].mask; if (!mask) mask = ~0ULL; /* Disable zero counters if requested. */ if (!zero && !(val & mask)) continue; grp->is_visible = NULL; } avail |= BIT(bit); } return avail; } EXPORT_SYMBOL_GPL(perf_msr_probe);
linux-master
arch/x86/events/probe.c
// SPDX-License-Identifier: GPL-2.0 /* Driver for Intel Xeon Phi "Knights Corner" PMU */ #include <linux/perf_event.h> #include <linux/types.h> #include <asm/hardirq.h> #include "../perf_event.h" static const u64 knc_perfmon_event_map[] = { [PERF_COUNT_HW_CPU_CYCLES] = 0x002a, [PERF_COUNT_HW_INSTRUCTIONS] = 0x0016, [PERF_COUNT_HW_CACHE_REFERENCES] = 0x0028, [PERF_COUNT_HW_CACHE_MISSES] = 0x0029, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x0012, [PERF_COUNT_HW_BRANCH_MISSES] = 0x002b, }; static const u64 __initconst knc_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { /* On Xeon Phi event "0" is a valid DATA_READ */ /* (L1 Data Cache Reads) Instruction. */ /* We code this as ARCH_PERFMON_EVENTSEL_INT as this */ /* bit will always be set in x86_pmu_hw_config(). */ [ C(RESULT_ACCESS) ] = ARCH_PERFMON_EVENTSEL_INT, /* DATA_READ */ [ C(RESULT_MISS) ] = 0x0003, /* DATA_READ_MISS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x0001, /* DATA_WRITE */ [ C(RESULT_MISS) ] = 0x0004, /* DATA_WRITE_MISS */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0011, /* L1_DATA_PF1 */ [ C(RESULT_MISS) ] = 0x001c, /* L1_DATA_PF1_MISS */ }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x000c, /* CODE_READ */ [ C(RESULT_MISS) ] = 0x000e, /* CODE_CACHE_MISS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0x10cb, /* L2_READ_MISS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x10cc, /* L2_WRITE_HIT */ [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x10fc, /* L2_DATA_PF2 */ [ C(RESULT_MISS) ] = 0x10fe, /* L2_DATA_PF2_MISS */ }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = ARCH_PERFMON_EVENTSEL_INT, /* DATA_READ */ /* see note on L1 OP_READ */ [ C(RESULT_MISS) ] = 0x0002, /* DATA_PAGE_WALK */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x0001, /* DATA_WRITE */ [ C(RESULT_MISS) ] = 0x0002, /* DATA_PAGE_WALK */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x000c, /* CODE_READ */ [ C(RESULT_MISS) ] = 0x000d, /* CODE_PAGE_WALK */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0012, /* BRANCHES */ [ C(RESULT_MISS) ] = 0x002b, /* BRANCHES_MISPREDICTED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, }; static u64 knc_pmu_event_map(int hw_event) { return knc_perfmon_event_map[hw_event]; } static struct event_constraint knc_event_constraints[] = { INTEL_EVENT_CONSTRAINT(0xc3, 0x1), /* HWP_L2HIT */ INTEL_EVENT_CONSTRAINT(0xc4, 0x1), /* HWP_L2MISS */ INTEL_EVENT_CONSTRAINT(0xc8, 0x1), /* L2_READ_HIT_E */ INTEL_EVENT_CONSTRAINT(0xc9, 0x1), /* L2_READ_HIT_M */ INTEL_EVENT_CONSTRAINT(0xca, 0x1), /* L2_READ_HIT_S */ INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* L2_READ_MISS */ INTEL_EVENT_CONSTRAINT(0xcc, 0x1), /* L2_WRITE_HIT */ INTEL_EVENT_CONSTRAINT(0xce, 0x1), /* L2_STRONGLY_ORDERED_STREAMING_VSTORES_MISS */ INTEL_EVENT_CONSTRAINT(0xcf, 0x1), /* L2_WEAKLY_ORDERED_STREAMING_VSTORE_MISS */ INTEL_EVENT_CONSTRAINT(0xd7, 0x1), /* L2_VICTIM_REQ_WITH_DATA */ INTEL_EVENT_CONSTRAINT(0xe3, 0x1), /* SNP_HITM_BUNIT */ INTEL_EVENT_CONSTRAINT(0xe6, 0x1), /* SNP_HIT_L2 */ INTEL_EVENT_CONSTRAINT(0xe7, 0x1), /* SNP_HITM_L2 */ INTEL_EVENT_CONSTRAINT(0xf1, 0x1), /* L2_DATA_READ_MISS_CACHE_FILL */ INTEL_EVENT_CONSTRAINT(0xf2, 0x1), /* L2_DATA_WRITE_MISS_CACHE_FILL */ INTEL_EVENT_CONSTRAINT(0xf6, 0x1), /* L2_DATA_READ_MISS_MEM_FILL */ INTEL_EVENT_CONSTRAINT(0xf7, 0x1), /* L2_DATA_WRITE_MISS_MEM_FILL */ INTEL_EVENT_CONSTRAINT(0xfc, 0x1), /* L2_DATA_PF2 */ INTEL_EVENT_CONSTRAINT(0xfd, 0x1), /* L2_DATA_PF2_DROP */ INTEL_EVENT_CONSTRAINT(0xfe, 0x1), /* L2_DATA_PF2_MISS */ INTEL_EVENT_CONSTRAINT(0xff, 0x1), /* L2_DATA_HIT_INFLIGHT_PF2 */ EVENT_CONSTRAINT_END }; #define MSR_KNC_IA32_PERF_GLOBAL_STATUS 0x0000002d #define MSR_KNC_IA32_PERF_GLOBAL_OVF_CONTROL 0x0000002e #define MSR_KNC_IA32_PERF_GLOBAL_CTRL 0x0000002f #define KNC_ENABLE_COUNTER0 0x00000001 #define KNC_ENABLE_COUNTER1 0x00000002 static void knc_pmu_disable_all(void) { u64 val; rdmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val); val &= ~(KNC_ENABLE_COUNTER0|KNC_ENABLE_COUNTER1); wrmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val); } static void knc_pmu_enable_all(int added) { u64 val; rdmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val); val |= (KNC_ENABLE_COUNTER0|KNC_ENABLE_COUNTER1); wrmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val); } static inline void knc_pmu_disable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 val; val = hwc->config; val &= ~ARCH_PERFMON_EVENTSEL_ENABLE; (void)wrmsrl_safe(hwc->config_base + hwc->idx, val); } static void knc_pmu_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 val; val = hwc->config; val |= ARCH_PERFMON_EVENTSEL_ENABLE; (void)wrmsrl_safe(hwc->config_base + hwc->idx, val); } static inline u64 knc_pmu_get_status(void) { u64 status; rdmsrl(MSR_KNC_IA32_PERF_GLOBAL_STATUS, status); return status; } static inline void knc_pmu_ack_status(u64 ack) { wrmsrl(MSR_KNC_IA32_PERF_GLOBAL_OVF_CONTROL, ack); } static int knc_pmu_handle_irq(struct pt_regs *regs) { struct perf_sample_data data; struct cpu_hw_events *cpuc; int handled = 0; int bit, loops; u64 status; cpuc = this_cpu_ptr(&cpu_hw_events); knc_pmu_disable_all(); status = knc_pmu_get_status(); if (!status) { knc_pmu_enable_all(0); return handled; } loops = 0; again: knc_pmu_ack_status(status); if (++loops > 100) { WARN_ONCE(1, "perf: irq loop stuck!\n"); perf_event_print_debug(); goto done; } inc_irq_stat(apic_perf_irqs); for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) { struct perf_event *event = cpuc->events[bit]; handled++; if (!test_bit(bit, cpuc->active_mask)) continue; if (!intel_pmu_save_and_restart(event)) continue; perf_sample_data_init(&data, 0, event->hw.last_period); if (perf_event_overflow(event, &data, regs)) x86_pmu_stop(event, 0); } /* * Repeat if there is more work to be done: */ status = knc_pmu_get_status(); if (status) goto again; done: /* Only restore PMU state when it's active. See x86_pmu_disable(). */ if (cpuc->enabled) knc_pmu_enable_all(0); return handled; } PMU_FORMAT_ATTR(event, "config:0-7" ); PMU_FORMAT_ATTR(umask, "config:8-15" ); PMU_FORMAT_ATTR(edge, "config:18" ); PMU_FORMAT_ATTR(inv, "config:23" ); PMU_FORMAT_ATTR(cmask, "config:24-31" ); static struct attribute *intel_knc_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_cmask.attr, NULL, }; static const struct x86_pmu knc_pmu __initconst = { .name = "knc", .handle_irq = knc_pmu_handle_irq, .disable_all = knc_pmu_disable_all, .enable_all = knc_pmu_enable_all, .enable = knc_pmu_enable_event, .disable = knc_pmu_disable_event, .hw_config = x86_pmu_hw_config, .schedule_events = x86_schedule_events, .eventsel = MSR_KNC_EVNTSEL0, .perfctr = MSR_KNC_PERFCTR0, .event_map = knc_pmu_event_map, .max_events = ARRAY_SIZE(knc_perfmon_event_map), .apic = 1, .max_period = (1ULL << 39) - 1, .version = 0, .num_counters = 2, .cntval_bits = 40, .cntval_mask = (1ULL << 40) - 1, .get_event_constraints = x86_get_event_constraints, .event_constraints = knc_event_constraints, .format_attrs = intel_knc_formats_attr, }; __init int knc_pmu_init(void) { x86_pmu = knc_pmu; memcpy(hw_cache_event_ids, knc_hw_cache_event_ids, sizeof(hw_cache_event_ids)); return 0; }
linux-master
arch/x86/events/intel/knc.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/module.h> #include <asm/cpu_device_id.h> #include <asm/intel-family.h> #include "uncore.h" #include "uncore_discovery.h" static bool uncore_no_discover; module_param(uncore_no_discover, bool, 0); MODULE_PARM_DESC(uncore_no_discover, "Don't enable the Intel uncore PerfMon discovery mechanism " "(default: enable the discovery mechanism)."); struct intel_uncore_type *empty_uncore[] = { NULL, }; struct intel_uncore_type **uncore_msr_uncores = empty_uncore; struct intel_uncore_type **uncore_pci_uncores = empty_uncore; struct intel_uncore_type **uncore_mmio_uncores = empty_uncore; static bool pcidrv_registered; struct pci_driver *uncore_pci_driver; /* The PCI driver for the device which the uncore doesn't own. */ struct pci_driver *uncore_pci_sub_driver; /* pci bus to socket mapping */ DEFINE_RAW_SPINLOCK(pci2phy_map_lock); struct list_head pci2phy_map_head = LIST_HEAD_INIT(pci2phy_map_head); struct pci_extra_dev *uncore_extra_pci_dev; int __uncore_max_dies; /* mask of cpus that collect uncore events */ static cpumask_t uncore_cpu_mask; /* constraint for the fixed counter */ static struct event_constraint uncore_constraint_fixed = EVENT_CONSTRAINT(~0ULL, 1 << UNCORE_PMC_IDX_FIXED, ~0ULL); struct event_constraint uncore_constraint_empty = EVENT_CONSTRAINT(0, 0, 0); MODULE_LICENSE("GPL"); int uncore_pcibus_to_dieid(struct pci_bus *bus) { struct pci2phy_map *map; int die_id = -1; raw_spin_lock(&pci2phy_map_lock); list_for_each_entry(map, &pci2phy_map_head, list) { if (map->segment == pci_domain_nr(bus)) { die_id = map->pbus_to_dieid[bus->number]; break; } } raw_spin_unlock(&pci2phy_map_lock); return die_id; } int uncore_die_to_segment(int die) { struct pci_bus *bus = NULL; /* Find first pci bus which attributes to specified die. */ while ((bus = pci_find_next_bus(bus)) && (die != uncore_pcibus_to_dieid(bus))) ; return bus ? pci_domain_nr(bus) : -EINVAL; } int uncore_device_to_die(struct pci_dev *dev) { int node = pcibus_to_node(dev->bus); int cpu; for_each_cpu(cpu, cpumask_of_pcibus(dev->bus)) { struct cpuinfo_x86 *c = &cpu_data(cpu); if (c->initialized && cpu_to_node(cpu) == node) return c->logical_die_id; } return -1; } static void uncore_free_pcibus_map(void) { struct pci2phy_map *map, *tmp; list_for_each_entry_safe(map, tmp, &pci2phy_map_head, list) { list_del(&map->list); kfree(map); } } struct pci2phy_map *__find_pci2phy_map(int segment) { struct pci2phy_map *map, *alloc = NULL; int i; lockdep_assert_held(&pci2phy_map_lock); lookup: list_for_each_entry(map, &pci2phy_map_head, list) { if (map->segment == segment) goto end; } if (!alloc) { raw_spin_unlock(&pci2phy_map_lock); alloc = kmalloc(sizeof(struct pci2phy_map), GFP_KERNEL); raw_spin_lock(&pci2phy_map_lock); if (!alloc) return NULL; goto lookup; } map = alloc; alloc = NULL; map->segment = segment; for (i = 0; i < 256; i++) map->pbus_to_dieid[i] = -1; list_add_tail(&map->list, &pci2phy_map_head); end: kfree(alloc); return map; } ssize_t uncore_event_show(struct device *dev, struct device_attribute *attr, char *buf) { struct uncore_event_desc *event = container_of(attr, struct uncore_event_desc, attr); return sprintf(buf, "%s", event->config); } struct intel_uncore_box *uncore_pmu_to_box(struct intel_uncore_pmu *pmu, int cpu) { unsigned int dieid = topology_logical_die_id(cpu); /* * The unsigned check also catches the '-1' return value for non * existent mappings in the topology map. */ return dieid < uncore_max_dies() ? pmu->boxes[dieid] : NULL; } u64 uncore_msr_read_counter(struct intel_uncore_box *box, struct perf_event *event) { u64 count; rdmsrl(event->hw.event_base, count); return count; } void uncore_mmio_exit_box(struct intel_uncore_box *box) { if (box->io_addr) iounmap(box->io_addr); } u64 uncore_mmio_read_counter(struct intel_uncore_box *box, struct perf_event *event) { if (!box->io_addr) return 0; if (!uncore_mmio_is_valid_offset(box, event->hw.event_base)) return 0; return readq(box->io_addr + event->hw.event_base); } /* * generic get constraint function for shared match/mask registers. */ struct event_constraint * uncore_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct intel_uncore_extra_reg *er; struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct hw_perf_event_extra *reg2 = &event->hw.branch_reg; unsigned long flags; bool ok = false; /* * reg->alloc can be set due to existing state, so for fake box we * need to ignore this, otherwise we might fail to allocate proper * fake state for this extra reg constraint. */ if (reg1->idx == EXTRA_REG_NONE || (!uncore_box_is_fake(box) && reg1->alloc)) return NULL; er = &box->shared_regs[reg1->idx]; raw_spin_lock_irqsave(&er->lock, flags); if (!atomic_read(&er->ref) || (er->config1 == reg1->config && er->config2 == reg2->config)) { atomic_inc(&er->ref); er->config1 = reg1->config; er->config2 = reg2->config; ok = true; } raw_spin_unlock_irqrestore(&er->lock, flags); if (ok) { if (!uncore_box_is_fake(box)) reg1->alloc = 1; return NULL; } return &uncore_constraint_empty; } void uncore_put_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct intel_uncore_extra_reg *er; struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; /* * Only put constraint if extra reg was actually allocated. Also * takes care of event which do not use an extra shared reg. * * Also, if this is a fake box we shouldn't touch any event state * (reg->alloc) and we don't care about leaving inconsistent box * state either since it will be thrown out. */ if (uncore_box_is_fake(box) || !reg1->alloc) return; er = &box->shared_regs[reg1->idx]; atomic_dec(&er->ref); reg1->alloc = 0; } u64 uncore_shared_reg_config(struct intel_uncore_box *box, int idx) { struct intel_uncore_extra_reg *er; unsigned long flags; u64 config; er = &box->shared_regs[idx]; raw_spin_lock_irqsave(&er->lock, flags); config = er->config; raw_spin_unlock_irqrestore(&er->lock, flags); return config; } static void uncore_assign_hw_event(struct intel_uncore_box *box, struct perf_event *event, int idx) { struct hw_perf_event *hwc = &event->hw; hwc->idx = idx; hwc->last_tag = ++box->tags[idx]; if (uncore_pmc_fixed(hwc->idx)) { hwc->event_base = uncore_fixed_ctr(box); hwc->config_base = uncore_fixed_ctl(box); return; } hwc->config_base = uncore_event_ctl(box, hwc->idx); hwc->event_base = uncore_perf_ctr(box, hwc->idx); } void uncore_perf_event_update(struct intel_uncore_box *box, struct perf_event *event) { u64 prev_count, new_count, delta; int shift; if (uncore_pmc_freerunning(event->hw.idx)) shift = 64 - uncore_freerunning_bits(box, event); else if (uncore_pmc_fixed(event->hw.idx)) shift = 64 - uncore_fixed_ctr_bits(box); else shift = 64 - uncore_perf_ctr_bits(box); /* the hrtimer might modify the previous event value */ again: prev_count = local64_read(&event->hw.prev_count); new_count = uncore_read_counter(box, event); if (local64_xchg(&event->hw.prev_count, new_count) != prev_count) goto again; delta = (new_count << shift) - (prev_count << shift); delta >>= shift; local64_add(delta, &event->count); } /* * The overflow interrupt is unavailable for SandyBridge-EP, is broken * for SandyBridge. So we use hrtimer to periodically poll the counter * to avoid overflow. */ static enum hrtimer_restart uncore_pmu_hrtimer(struct hrtimer *hrtimer) { struct intel_uncore_box *box; struct perf_event *event; unsigned long flags; int bit; box = container_of(hrtimer, struct intel_uncore_box, hrtimer); if (!box->n_active || box->cpu != smp_processor_id()) return HRTIMER_NORESTART; /* * disable local interrupt to prevent uncore_pmu_event_start/stop * to interrupt the update process */ local_irq_save(flags); /* * handle boxes with an active event list as opposed to active * counters */ list_for_each_entry(event, &box->active_list, active_entry) { uncore_perf_event_update(box, event); } for_each_set_bit(bit, box->active_mask, UNCORE_PMC_IDX_MAX) uncore_perf_event_update(box, box->events[bit]); local_irq_restore(flags); hrtimer_forward_now(hrtimer, ns_to_ktime(box->hrtimer_duration)); return HRTIMER_RESTART; } void uncore_pmu_start_hrtimer(struct intel_uncore_box *box) { hrtimer_start(&box->hrtimer, ns_to_ktime(box->hrtimer_duration), HRTIMER_MODE_REL_PINNED); } void uncore_pmu_cancel_hrtimer(struct intel_uncore_box *box) { hrtimer_cancel(&box->hrtimer); } static void uncore_pmu_init_hrtimer(struct intel_uncore_box *box) { hrtimer_init(&box->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); box->hrtimer.function = uncore_pmu_hrtimer; } static struct intel_uncore_box *uncore_alloc_box(struct intel_uncore_type *type, int node) { int i, size, numshared = type->num_shared_regs ; struct intel_uncore_box *box; size = sizeof(*box) + numshared * sizeof(struct intel_uncore_extra_reg); box = kzalloc_node(size, GFP_KERNEL, node); if (!box) return NULL; for (i = 0; i < numshared; i++) raw_spin_lock_init(&box->shared_regs[i].lock); uncore_pmu_init_hrtimer(box); box->cpu = -1; box->dieid = -1; /* set default hrtimer timeout */ box->hrtimer_duration = UNCORE_PMU_HRTIMER_INTERVAL; INIT_LIST_HEAD(&box->active_list); return box; } /* * Using uncore_pmu_event_init pmu event_init callback * as a detection point for uncore events. */ static int uncore_pmu_event_init(struct perf_event *event); static bool is_box_event(struct intel_uncore_box *box, struct perf_event *event) { return &box->pmu->pmu == event->pmu; } static int uncore_collect_events(struct intel_uncore_box *box, struct perf_event *leader, bool dogrp) { struct perf_event *event; int n, max_count; max_count = box->pmu->type->num_counters; if (box->pmu->type->fixed_ctl) max_count++; if (box->n_events >= max_count) return -EINVAL; n = box->n_events; if (is_box_event(box, leader)) { box->event_list[n] = leader; n++; } if (!dogrp) return n; for_each_sibling_event(event, leader) { if (!is_box_event(box, event) || event->state <= PERF_EVENT_STATE_OFF) continue; if (n >= max_count) return -EINVAL; box->event_list[n] = event; n++; } return n; } static struct event_constraint * uncore_get_event_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct intel_uncore_type *type = box->pmu->type; struct event_constraint *c; if (type->ops->get_constraint) { c = type->ops->get_constraint(box, event); if (c) return c; } if (event->attr.config == UNCORE_FIXED_EVENT) return &uncore_constraint_fixed; if (type->constraints) { for_each_event_constraint(c, type->constraints) { if ((event->hw.config & c->cmask) == c->code) return c; } } return &type->unconstrainted; } static void uncore_put_event_constraint(struct intel_uncore_box *box, struct perf_event *event) { if (box->pmu->type->ops->put_constraint) box->pmu->type->ops->put_constraint(box, event); } static int uncore_assign_events(struct intel_uncore_box *box, int assign[], int n) { unsigned long used_mask[BITS_TO_LONGS(UNCORE_PMC_IDX_MAX)]; struct event_constraint *c; int i, wmin, wmax, ret = 0; struct hw_perf_event *hwc; bitmap_zero(used_mask, UNCORE_PMC_IDX_MAX); for (i = 0, wmin = UNCORE_PMC_IDX_MAX, wmax = 0; i < n; i++) { c = uncore_get_event_constraint(box, box->event_list[i]); box->event_constraint[i] = c; wmin = min(wmin, c->weight); wmax = max(wmax, c->weight); } /* fastpath, try to reuse previous register */ for (i = 0; i < n; i++) { hwc = &box->event_list[i]->hw; c = box->event_constraint[i]; /* never assigned */ if (hwc->idx == -1) break; /* constraint still honored */ if (!test_bit(hwc->idx, c->idxmsk)) break; /* not already used */ if (test_bit(hwc->idx, used_mask)) break; __set_bit(hwc->idx, used_mask); if (assign) assign[i] = hwc->idx; } /* slow path */ if (i != n) ret = perf_assign_events(box->event_constraint, n, wmin, wmax, n, assign); if (!assign || ret) { for (i = 0; i < n; i++) uncore_put_event_constraint(box, box->event_list[i]); } return ret ? -EINVAL : 0; } void uncore_pmu_event_start(struct perf_event *event, int flags) { struct intel_uncore_box *box = uncore_event_to_box(event); int idx = event->hw.idx; if (WARN_ON_ONCE(idx == -1 || idx >= UNCORE_PMC_IDX_MAX)) return; /* * Free running counter is read-only and always active. * Use the current counter value as start point. * There is no overflow interrupt for free running counter. * Use hrtimer to periodically poll the counter to avoid overflow. */ if (uncore_pmc_freerunning(event->hw.idx)) { list_add_tail(&event->active_entry, &box->active_list); local64_set(&event->hw.prev_count, uncore_read_counter(box, event)); if (box->n_active++ == 0) uncore_pmu_start_hrtimer(box); return; } if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED))) return; event->hw.state = 0; box->events[idx] = event; box->n_active++; __set_bit(idx, box->active_mask); local64_set(&event->hw.prev_count, uncore_read_counter(box, event)); uncore_enable_event(box, event); if (box->n_active == 1) uncore_pmu_start_hrtimer(box); } void uncore_pmu_event_stop(struct perf_event *event, int flags) { struct intel_uncore_box *box = uncore_event_to_box(event); struct hw_perf_event *hwc = &event->hw; /* Cannot disable free running counter which is read-only */ if (uncore_pmc_freerunning(hwc->idx)) { list_del(&event->active_entry); if (--box->n_active == 0) uncore_pmu_cancel_hrtimer(box); uncore_perf_event_update(box, event); return; } if (__test_and_clear_bit(hwc->idx, box->active_mask)) { uncore_disable_event(box, event); box->n_active--; box->events[hwc->idx] = NULL; WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED); hwc->state |= PERF_HES_STOPPED; if (box->n_active == 0) uncore_pmu_cancel_hrtimer(box); } if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) { /* * Drain the remaining delta count out of a event * that we are disabling: */ uncore_perf_event_update(box, event); hwc->state |= PERF_HES_UPTODATE; } } int uncore_pmu_event_add(struct perf_event *event, int flags) { struct intel_uncore_box *box = uncore_event_to_box(event); struct hw_perf_event *hwc = &event->hw; int assign[UNCORE_PMC_IDX_MAX]; int i, n, ret; if (!box) return -ENODEV; /* * The free funning counter is assigned in event_init(). * The free running counter event and free running counter * are 1:1 mapped. It doesn't need to be tracked in event_list. */ if (uncore_pmc_freerunning(hwc->idx)) { if (flags & PERF_EF_START) uncore_pmu_event_start(event, 0); return 0; } ret = n = uncore_collect_events(box, event, false); if (ret < 0) return ret; hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED; if (!(flags & PERF_EF_START)) hwc->state |= PERF_HES_ARCH; ret = uncore_assign_events(box, assign, n); if (ret) return ret; /* save events moving to new counters */ for (i = 0; i < box->n_events; i++) { event = box->event_list[i]; hwc = &event->hw; if (hwc->idx == assign[i] && hwc->last_tag == box->tags[assign[i]]) continue; /* * Ensure we don't accidentally enable a stopped * counter simply because we rescheduled. */ if (hwc->state & PERF_HES_STOPPED) hwc->state |= PERF_HES_ARCH; uncore_pmu_event_stop(event, PERF_EF_UPDATE); } /* reprogram moved events into new counters */ for (i = 0; i < n; i++) { event = box->event_list[i]; hwc = &event->hw; if (hwc->idx != assign[i] || hwc->last_tag != box->tags[assign[i]]) uncore_assign_hw_event(box, event, assign[i]); else if (i < box->n_events) continue; if (hwc->state & PERF_HES_ARCH) continue; uncore_pmu_event_start(event, 0); } box->n_events = n; return 0; } void uncore_pmu_event_del(struct perf_event *event, int flags) { struct intel_uncore_box *box = uncore_event_to_box(event); int i; uncore_pmu_event_stop(event, PERF_EF_UPDATE); /* * The event for free running counter is not tracked by event_list. * It doesn't need to force event->hw.idx = -1 to reassign the counter. * Because the event and the free running counter are 1:1 mapped. */ if (uncore_pmc_freerunning(event->hw.idx)) return; for (i = 0; i < box->n_events; i++) { if (event == box->event_list[i]) { uncore_put_event_constraint(box, event); for (++i; i < box->n_events; i++) box->event_list[i - 1] = box->event_list[i]; --box->n_events; break; } } event->hw.idx = -1; event->hw.last_tag = ~0ULL; } void uncore_pmu_event_read(struct perf_event *event) { struct intel_uncore_box *box = uncore_event_to_box(event); uncore_perf_event_update(box, event); } /* * validation ensures the group can be loaded onto the * PMU if it was the only group available. */ static int uncore_validate_group(struct intel_uncore_pmu *pmu, struct perf_event *event) { struct perf_event *leader = event->group_leader; struct intel_uncore_box *fake_box; int ret = -EINVAL, n; /* The free running counter is always active. */ if (uncore_pmc_freerunning(event->hw.idx)) return 0; fake_box = uncore_alloc_box(pmu->type, NUMA_NO_NODE); if (!fake_box) return -ENOMEM; fake_box->pmu = pmu; /* * the event is not yet connected with its * siblings therefore we must first collect * existing siblings, then add the new event * before we can simulate the scheduling */ n = uncore_collect_events(fake_box, leader, true); if (n < 0) goto out; fake_box->n_events = n; n = uncore_collect_events(fake_box, event, false); if (n < 0) goto out; fake_box->n_events = n; ret = uncore_assign_events(fake_box, NULL, n); out: kfree(fake_box); return ret; } static int uncore_pmu_event_init(struct perf_event *event) { struct intel_uncore_pmu *pmu; struct intel_uncore_box *box; struct hw_perf_event *hwc = &event->hw; int ret; if (event->attr.type != event->pmu->type) return -ENOENT; pmu = uncore_event_to_pmu(event); /* no device found for this pmu */ if (pmu->func_id < 0) return -ENOENT; /* Sampling not supported yet */ if (hwc->sample_period) return -EINVAL; /* * Place all uncore events for a particular physical package * onto a single cpu */ if (event->cpu < 0) return -EINVAL; box = uncore_pmu_to_box(pmu, event->cpu); if (!box || box->cpu < 0) return -EINVAL; event->cpu = box->cpu; event->pmu_private = box; event->event_caps |= PERF_EV_CAP_READ_ACTIVE_PKG; event->hw.idx = -1; event->hw.last_tag = ~0ULL; event->hw.extra_reg.idx = EXTRA_REG_NONE; event->hw.branch_reg.idx = EXTRA_REG_NONE; if (event->attr.config == UNCORE_FIXED_EVENT) { /* no fixed counter */ if (!pmu->type->fixed_ctl) return -EINVAL; /* * if there is only one fixed counter, only the first pmu * can access the fixed counter */ if (pmu->type->single_fixed && pmu->pmu_idx > 0) return -EINVAL; /* fixed counters have event field hardcoded to zero */ hwc->config = 0ULL; } else if (is_freerunning_event(event)) { hwc->config = event->attr.config; if (!check_valid_freerunning_event(box, event)) return -EINVAL; event->hw.idx = UNCORE_PMC_IDX_FREERUNNING; /* * The free running counter event and free running counter * are always 1:1 mapped. * The free running counter is always active. * Assign the free running counter here. */ event->hw.event_base = uncore_freerunning_counter(box, event); } else { hwc->config = event->attr.config & (pmu->type->event_mask | ((u64)pmu->type->event_mask_ext << 32)); if (pmu->type->ops->hw_config) { ret = pmu->type->ops->hw_config(box, event); if (ret) return ret; } } if (event->group_leader != event) ret = uncore_validate_group(pmu, event); else ret = 0; return ret; } static void uncore_pmu_enable(struct pmu *pmu) { struct intel_uncore_pmu *uncore_pmu; struct intel_uncore_box *box; uncore_pmu = container_of(pmu, struct intel_uncore_pmu, pmu); box = uncore_pmu_to_box(uncore_pmu, smp_processor_id()); if (!box) return; if (uncore_pmu->type->ops->enable_box) uncore_pmu->type->ops->enable_box(box); } static void uncore_pmu_disable(struct pmu *pmu) { struct intel_uncore_pmu *uncore_pmu; struct intel_uncore_box *box; uncore_pmu = container_of(pmu, struct intel_uncore_pmu, pmu); box = uncore_pmu_to_box(uncore_pmu, smp_processor_id()); if (!box) return; if (uncore_pmu->type->ops->disable_box) uncore_pmu->type->ops->disable_box(box); } static ssize_t uncore_get_attr_cpumask(struct device *dev, struct device_attribute *attr, char *buf) { return cpumap_print_to_pagebuf(true, buf, &uncore_cpu_mask); } static DEVICE_ATTR(cpumask, S_IRUGO, uncore_get_attr_cpumask, NULL); static struct attribute *uncore_pmu_attrs[] = { &dev_attr_cpumask.attr, NULL, }; static const struct attribute_group uncore_pmu_attr_group = { .attrs = uncore_pmu_attrs, }; static inline int uncore_get_box_id(struct intel_uncore_type *type, struct intel_uncore_pmu *pmu) { return type->box_ids ? type->box_ids[pmu->pmu_idx] : pmu->pmu_idx; } void uncore_get_alias_name(char *pmu_name, struct intel_uncore_pmu *pmu) { struct intel_uncore_type *type = pmu->type; if (type->num_boxes == 1) sprintf(pmu_name, "uncore_type_%u", type->type_id); else { sprintf(pmu_name, "uncore_type_%u_%d", type->type_id, uncore_get_box_id(type, pmu)); } } static void uncore_get_pmu_name(struct intel_uncore_pmu *pmu) { struct intel_uncore_type *type = pmu->type; /* * No uncore block name in discovery table. * Use uncore_type_&typeid_&boxid as name. */ if (!type->name) { uncore_get_alias_name(pmu->name, pmu); return; } if (type->num_boxes == 1) { if (strlen(type->name) > 0) sprintf(pmu->name, "uncore_%s", type->name); else sprintf(pmu->name, "uncore"); } else { /* * Use the box ID from the discovery table if applicable. */ sprintf(pmu->name, "uncore_%s_%d", type->name, uncore_get_box_id(type, pmu)); } } static int uncore_pmu_register(struct intel_uncore_pmu *pmu) { int ret; if (!pmu->type->pmu) { pmu->pmu = (struct pmu) { .attr_groups = pmu->type->attr_groups, .task_ctx_nr = perf_invalid_context, .pmu_enable = uncore_pmu_enable, .pmu_disable = uncore_pmu_disable, .event_init = uncore_pmu_event_init, .add = uncore_pmu_event_add, .del = uncore_pmu_event_del, .start = uncore_pmu_event_start, .stop = uncore_pmu_event_stop, .read = uncore_pmu_event_read, .module = THIS_MODULE, .capabilities = PERF_PMU_CAP_NO_EXCLUDE, .attr_update = pmu->type->attr_update, }; } else { pmu->pmu = *pmu->type->pmu; pmu->pmu.attr_groups = pmu->type->attr_groups; pmu->pmu.attr_update = pmu->type->attr_update; } uncore_get_pmu_name(pmu); ret = perf_pmu_register(&pmu->pmu, pmu->name, -1); if (!ret) pmu->registered = true; return ret; } static void uncore_pmu_unregister(struct intel_uncore_pmu *pmu) { if (!pmu->registered) return; perf_pmu_unregister(&pmu->pmu); pmu->registered = false; } static void uncore_free_boxes(struct intel_uncore_pmu *pmu) { int die; for (die = 0; die < uncore_max_dies(); die++) kfree(pmu->boxes[die]); kfree(pmu->boxes); } static void uncore_type_exit(struct intel_uncore_type *type) { struct intel_uncore_pmu *pmu = type->pmus; int i; if (type->cleanup_mapping) type->cleanup_mapping(type); if (pmu) { for (i = 0; i < type->num_boxes; i++, pmu++) { uncore_pmu_unregister(pmu); uncore_free_boxes(pmu); } kfree(type->pmus); type->pmus = NULL; } if (type->box_ids) { kfree(type->box_ids); type->box_ids = NULL; } kfree(type->events_group); type->events_group = NULL; } static void uncore_types_exit(struct intel_uncore_type **types) { for (; *types; types++) uncore_type_exit(*types); } static int __init uncore_type_init(struct intel_uncore_type *type, bool setid) { struct intel_uncore_pmu *pmus; size_t size; int i, j; pmus = kcalloc(type->num_boxes, sizeof(*pmus), GFP_KERNEL); if (!pmus) return -ENOMEM; size = uncore_max_dies() * sizeof(struct intel_uncore_box *); for (i = 0; i < type->num_boxes; i++) { pmus[i].func_id = setid ? i : -1; pmus[i].pmu_idx = i; pmus[i].type = type; pmus[i].boxes = kzalloc(size, GFP_KERNEL); if (!pmus[i].boxes) goto err; } type->pmus = pmus; type->unconstrainted = (struct event_constraint) __EVENT_CONSTRAINT(0, (1ULL << type->num_counters) - 1, 0, type->num_counters, 0, 0); if (type->event_descs) { struct { struct attribute_group group; struct attribute *attrs[]; } *attr_group; for (i = 0; type->event_descs[i].attr.attr.name; i++); attr_group = kzalloc(struct_size(attr_group, attrs, i + 1), GFP_KERNEL); if (!attr_group) goto err; attr_group->group.name = "events"; attr_group->group.attrs = attr_group->attrs; for (j = 0; j < i; j++) attr_group->attrs[j] = &type->event_descs[j].attr.attr; type->events_group = &attr_group->group; } type->pmu_group = &uncore_pmu_attr_group; if (type->set_mapping) type->set_mapping(type); return 0; err: for (i = 0; i < type->num_boxes; i++) kfree(pmus[i].boxes); kfree(pmus); return -ENOMEM; } static int __init uncore_types_init(struct intel_uncore_type **types, bool setid) { int ret; for (; *types; types++) { ret = uncore_type_init(*types, setid); if (ret) return ret; } return 0; } /* * Get the die information of a PCI device. * @pdev: The PCI device. * @die: The die id which the device maps to. */ static int uncore_pci_get_dev_die_info(struct pci_dev *pdev, int *die) { *die = uncore_pcibus_to_dieid(pdev->bus); if (*die < 0) return -EINVAL; return 0; } static struct intel_uncore_pmu * uncore_pci_find_dev_pmu_from_types(struct pci_dev *pdev) { struct intel_uncore_type **types = uncore_pci_uncores; struct intel_uncore_type *type; u64 box_ctl; int i, die; for (; *types; types++) { type = *types; for (die = 0; die < __uncore_max_dies; die++) { for (i = 0; i < type->num_boxes; i++) { if (!type->box_ctls[die]) continue; box_ctl = type->box_ctls[die] + type->pci_offsets[i]; if (pdev->devfn == UNCORE_DISCOVERY_PCI_DEVFN(box_ctl) && pdev->bus->number == UNCORE_DISCOVERY_PCI_BUS(box_ctl) && pci_domain_nr(pdev->bus) == UNCORE_DISCOVERY_PCI_DOMAIN(box_ctl)) return &type->pmus[i]; } } } return NULL; } /* * Find the PMU of a PCI device. * @pdev: The PCI device. * @ids: The ID table of the available PCI devices with a PMU. * If NULL, search the whole uncore_pci_uncores. */ static struct intel_uncore_pmu * uncore_pci_find_dev_pmu(struct pci_dev *pdev, const struct pci_device_id *ids) { struct intel_uncore_pmu *pmu = NULL; struct intel_uncore_type *type; kernel_ulong_t data; unsigned int devfn; if (!ids) return uncore_pci_find_dev_pmu_from_types(pdev); while (ids && ids->vendor) { if ((ids->vendor == pdev->vendor) && (ids->device == pdev->device)) { data = ids->driver_data; devfn = PCI_DEVFN(UNCORE_PCI_DEV_DEV(data), UNCORE_PCI_DEV_FUNC(data)); if (devfn == pdev->devfn) { type = uncore_pci_uncores[UNCORE_PCI_DEV_TYPE(data)]; pmu = &type->pmus[UNCORE_PCI_DEV_IDX(data)]; break; } } ids++; } return pmu; } /* * Register the PMU for a PCI device * @pdev: The PCI device. * @type: The corresponding PMU type of the device. * @pmu: The corresponding PMU of the device. * @die: The die id which the device maps to. */ static int uncore_pci_pmu_register(struct pci_dev *pdev, struct intel_uncore_type *type, struct intel_uncore_pmu *pmu, int die) { struct intel_uncore_box *box; int ret; if (WARN_ON_ONCE(pmu->boxes[die] != NULL)) return -EINVAL; box = uncore_alloc_box(type, NUMA_NO_NODE); if (!box) return -ENOMEM; if (pmu->func_id < 0) pmu->func_id = pdev->devfn; else WARN_ON_ONCE(pmu->func_id != pdev->devfn); atomic_inc(&box->refcnt); box->dieid = die; box->pci_dev = pdev; box->pmu = pmu; uncore_box_init(box); pmu->boxes[die] = box; if (atomic_inc_return(&pmu->activeboxes) > 1) return 0; /* First active box registers the pmu */ ret = uncore_pmu_register(pmu); if (ret) { pmu->boxes[die] = NULL; uncore_box_exit(box); kfree(box); } return ret; } /* * add a pci uncore device */ static int uncore_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) { struct intel_uncore_type *type; struct intel_uncore_pmu *pmu = NULL; int die, ret; ret = uncore_pci_get_dev_die_info(pdev, &die); if (ret) return ret; if (UNCORE_PCI_DEV_TYPE(id->driver_data) == UNCORE_EXTRA_PCI_DEV) { int idx = UNCORE_PCI_DEV_IDX(id->driver_data); uncore_extra_pci_dev[die].dev[idx] = pdev; pci_set_drvdata(pdev, NULL); return 0; } type = uncore_pci_uncores[UNCORE_PCI_DEV_TYPE(id->driver_data)]; /* * Some platforms, e.g. Knights Landing, use a common PCI device ID * for multiple instances of an uncore PMU device type. We should check * PCI slot and func to indicate the uncore box. */ if (id->driver_data & ~0xffff) { struct pci_driver *pci_drv = to_pci_driver(pdev->dev.driver); pmu = uncore_pci_find_dev_pmu(pdev, pci_drv->id_table); if (pmu == NULL) return -ENODEV; } else { /* * for performance monitoring unit with multiple boxes, * each box has a different function id. */ pmu = &type->pmus[UNCORE_PCI_DEV_IDX(id->driver_data)]; } ret = uncore_pci_pmu_register(pdev, type, pmu, die); pci_set_drvdata(pdev, pmu->boxes[die]); return ret; } /* * Unregister the PMU of a PCI device * @pmu: The corresponding PMU is unregistered. * @die: The die id which the device maps to. */ static void uncore_pci_pmu_unregister(struct intel_uncore_pmu *pmu, int die) { struct intel_uncore_box *box = pmu->boxes[die]; pmu->boxes[die] = NULL; if (atomic_dec_return(&pmu->activeboxes) == 0) uncore_pmu_unregister(pmu); uncore_box_exit(box); kfree(box); } static void uncore_pci_remove(struct pci_dev *pdev) { struct intel_uncore_box *box; struct intel_uncore_pmu *pmu; int i, die; if (uncore_pci_get_dev_die_info(pdev, &die)) return; box = pci_get_drvdata(pdev); if (!box) { for (i = 0; i < UNCORE_EXTRA_PCI_DEV_MAX; i++) { if (uncore_extra_pci_dev[die].dev[i] == pdev) { uncore_extra_pci_dev[die].dev[i] = NULL; break; } } WARN_ON_ONCE(i >= UNCORE_EXTRA_PCI_DEV_MAX); return; } pmu = box->pmu; pci_set_drvdata(pdev, NULL); uncore_pci_pmu_unregister(pmu, die); } static int uncore_bus_notify(struct notifier_block *nb, unsigned long action, void *data, const struct pci_device_id *ids) { struct device *dev = data; struct pci_dev *pdev = to_pci_dev(dev); struct intel_uncore_pmu *pmu; int die; /* Unregister the PMU when the device is going to be deleted. */ if (action != BUS_NOTIFY_DEL_DEVICE) return NOTIFY_DONE; pmu = uncore_pci_find_dev_pmu(pdev, ids); if (!pmu) return NOTIFY_DONE; if (uncore_pci_get_dev_die_info(pdev, &die)) return NOTIFY_DONE; uncore_pci_pmu_unregister(pmu, die); return NOTIFY_OK; } static int uncore_pci_sub_bus_notify(struct notifier_block *nb, unsigned long action, void *data) { return uncore_bus_notify(nb, action, data, uncore_pci_sub_driver->id_table); } static struct notifier_block uncore_pci_sub_notifier = { .notifier_call = uncore_pci_sub_bus_notify, }; static void uncore_pci_sub_driver_init(void) { const struct pci_device_id *ids = uncore_pci_sub_driver->id_table; struct intel_uncore_type *type; struct intel_uncore_pmu *pmu; struct pci_dev *pci_sub_dev; bool notify = false; unsigned int devfn; int die; while (ids && ids->vendor) { pci_sub_dev = NULL; type = uncore_pci_uncores[UNCORE_PCI_DEV_TYPE(ids->driver_data)]; /* * Search the available device, and register the * corresponding PMU. */ while ((pci_sub_dev = pci_get_device(PCI_VENDOR_ID_INTEL, ids->device, pci_sub_dev))) { devfn = PCI_DEVFN(UNCORE_PCI_DEV_DEV(ids->driver_data), UNCORE_PCI_DEV_FUNC(ids->driver_data)); if (devfn != pci_sub_dev->devfn) continue; pmu = &type->pmus[UNCORE_PCI_DEV_IDX(ids->driver_data)]; if (!pmu) continue; if (uncore_pci_get_dev_die_info(pci_sub_dev, &die)) continue; if (!uncore_pci_pmu_register(pci_sub_dev, type, pmu, die)) notify = true; } ids++; } if (notify && bus_register_notifier(&pci_bus_type, &uncore_pci_sub_notifier)) notify = false; if (!notify) uncore_pci_sub_driver = NULL; } static int uncore_pci_bus_notify(struct notifier_block *nb, unsigned long action, void *data) { return uncore_bus_notify(nb, action, data, NULL); } static struct notifier_block uncore_pci_notifier = { .notifier_call = uncore_pci_bus_notify, }; static void uncore_pci_pmus_register(void) { struct intel_uncore_type **types = uncore_pci_uncores; struct intel_uncore_type *type; struct intel_uncore_pmu *pmu; struct pci_dev *pdev; u64 box_ctl; int i, die; for (; *types; types++) { type = *types; for (die = 0; die < __uncore_max_dies; die++) { for (i = 0; i < type->num_boxes; i++) { if (!type->box_ctls[die]) continue; box_ctl = type->box_ctls[die] + type->pci_offsets[i]; pdev = pci_get_domain_bus_and_slot(UNCORE_DISCOVERY_PCI_DOMAIN(box_ctl), UNCORE_DISCOVERY_PCI_BUS(box_ctl), UNCORE_DISCOVERY_PCI_DEVFN(box_ctl)); if (!pdev) continue; pmu = &type->pmus[i]; uncore_pci_pmu_register(pdev, type, pmu, die); } } } bus_register_notifier(&pci_bus_type, &uncore_pci_notifier); } static int __init uncore_pci_init(void) { size_t size; int ret; size = uncore_max_dies() * sizeof(struct pci_extra_dev); uncore_extra_pci_dev = kzalloc(size, GFP_KERNEL); if (!uncore_extra_pci_dev) { ret = -ENOMEM; goto err; } ret = uncore_types_init(uncore_pci_uncores, false); if (ret) goto errtype; if (uncore_pci_driver) { uncore_pci_driver->probe = uncore_pci_probe; uncore_pci_driver->remove = uncore_pci_remove; ret = pci_register_driver(uncore_pci_driver); if (ret) goto errtype; } else uncore_pci_pmus_register(); if (uncore_pci_sub_driver) uncore_pci_sub_driver_init(); pcidrv_registered = true; return 0; errtype: uncore_types_exit(uncore_pci_uncores); kfree(uncore_extra_pci_dev); uncore_extra_pci_dev = NULL; uncore_free_pcibus_map(); err: uncore_pci_uncores = empty_uncore; return ret; } static void uncore_pci_exit(void) { if (pcidrv_registered) { pcidrv_registered = false; if (uncore_pci_sub_driver) bus_unregister_notifier(&pci_bus_type, &uncore_pci_sub_notifier); if (uncore_pci_driver) pci_unregister_driver(uncore_pci_driver); else bus_unregister_notifier(&pci_bus_type, &uncore_pci_notifier); uncore_types_exit(uncore_pci_uncores); kfree(uncore_extra_pci_dev); uncore_free_pcibus_map(); } } static void uncore_change_type_ctx(struct intel_uncore_type *type, int old_cpu, int new_cpu) { struct intel_uncore_pmu *pmu = type->pmus; struct intel_uncore_box *box; int i, die; die = topology_logical_die_id(old_cpu < 0 ? new_cpu : old_cpu); for (i = 0; i < type->num_boxes; i++, pmu++) { box = pmu->boxes[die]; if (!box) continue; if (old_cpu < 0) { WARN_ON_ONCE(box->cpu != -1); box->cpu = new_cpu; continue; } WARN_ON_ONCE(box->cpu != old_cpu); box->cpu = -1; if (new_cpu < 0) continue; uncore_pmu_cancel_hrtimer(box); perf_pmu_migrate_context(&pmu->pmu, old_cpu, new_cpu); box->cpu = new_cpu; } } static void uncore_change_context(struct intel_uncore_type **uncores, int old_cpu, int new_cpu) { for (; *uncores; uncores++) uncore_change_type_ctx(*uncores, old_cpu, new_cpu); } static void uncore_box_unref(struct intel_uncore_type **types, int id) { struct intel_uncore_type *type; struct intel_uncore_pmu *pmu; struct intel_uncore_box *box; int i; for (; *types; types++) { type = *types; pmu = type->pmus; for (i = 0; i < type->num_boxes; i++, pmu++) { box = pmu->boxes[id]; if (box && atomic_dec_return(&box->refcnt) == 0) uncore_box_exit(box); } } } static int uncore_event_cpu_offline(unsigned int cpu) { int die, target; /* Check if exiting cpu is used for collecting uncore events */ if (!cpumask_test_and_clear_cpu(cpu, &uncore_cpu_mask)) goto unref; /* Find a new cpu to collect uncore events */ target = cpumask_any_but(topology_die_cpumask(cpu), cpu); /* Migrate uncore events to the new target */ if (target < nr_cpu_ids) cpumask_set_cpu(target, &uncore_cpu_mask); else target = -1; uncore_change_context(uncore_msr_uncores, cpu, target); uncore_change_context(uncore_mmio_uncores, cpu, target); uncore_change_context(uncore_pci_uncores, cpu, target); unref: /* Clear the references */ die = topology_logical_die_id(cpu); uncore_box_unref(uncore_msr_uncores, die); uncore_box_unref(uncore_mmio_uncores, die); return 0; } static int allocate_boxes(struct intel_uncore_type **types, unsigned int die, unsigned int cpu) { struct intel_uncore_box *box, *tmp; struct intel_uncore_type *type; struct intel_uncore_pmu *pmu; LIST_HEAD(allocated); int i; /* Try to allocate all required boxes */ for (; *types; types++) { type = *types; pmu = type->pmus; for (i = 0; i < type->num_boxes; i++, pmu++) { if (pmu->boxes[die]) continue; box = uncore_alloc_box(type, cpu_to_node(cpu)); if (!box) goto cleanup; box->pmu = pmu; box->dieid = die; list_add(&box->active_list, &allocated); } } /* Install them in the pmus */ list_for_each_entry_safe(box, tmp, &allocated, active_list) { list_del_init(&box->active_list); box->pmu->boxes[die] = box; } return 0; cleanup: list_for_each_entry_safe(box, tmp, &allocated, active_list) { list_del_init(&box->active_list); kfree(box); } return -ENOMEM; } static int uncore_box_ref(struct intel_uncore_type **types, int id, unsigned int cpu) { struct intel_uncore_type *type; struct intel_uncore_pmu *pmu; struct intel_uncore_box *box; int i, ret; ret = allocate_boxes(types, id, cpu); if (ret) return ret; for (; *types; types++) { type = *types; pmu = type->pmus; for (i = 0; i < type->num_boxes; i++, pmu++) { box = pmu->boxes[id]; if (box && atomic_inc_return(&box->refcnt) == 1) uncore_box_init(box); } } return 0; } static int uncore_event_cpu_online(unsigned int cpu) { int die, target, msr_ret, mmio_ret; die = topology_logical_die_id(cpu); msr_ret = uncore_box_ref(uncore_msr_uncores, die, cpu); mmio_ret = uncore_box_ref(uncore_mmio_uncores, die, cpu); if (msr_ret && mmio_ret) return -ENOMEM; /* * Check if there is an online cpu in the package * which collects uncore events already. */ target = cpumask_any_and(&uncore_cpu_mask, topology_die_cpumask(cpu)); if (target < nr_cpu_ids) return 0; cpumask_set_cpu(cpu, &uncore_cpu_mask); if (!msr_ret) uncore_change_context(uncore_msr_uncores, -1, cpu); if (!mmio_ret) uncore_change_context(uncore_mmio_uncores, -1, cpu); uncore_change_context(uncore_pci_uncores, -1, cpu); return 0; } static int __init type_pmu_register(struct intel_uncore_type *type) { int i, ret; for (i = 0; i < type->num_boxes; i++) { ret = uncore_pmu_register(&type->pmus[i]); if (ret) return ret; } return 0; } static int __init uncore_msr_pmus_register(void) { struct intel_uncore_type **types = uncore_msr_uncores; int ret; for (; *types; types++) { ret = type_pmu_register(*types); if (ret) return ret; } return 0; } static int __init uncore_cpu_init(void) { int ret; ret = uncore_types_init(uncore_msr_uncores, true); if (ret) goto err; ret = uncore_msr_pmus_register(); if (ret) goto err; return 0; err: uncore_types_exit(uncore_msr_uncores); uncore_msr_uncores = empty_uncore; return ret; } static int __init uncore_mmio_init(void) { struct intel_uncore_type **types = uncore_mmio_uncores; int ret; ret = uncore_types_init(types, true); if (ret) goto err; for (; *types; types++) { ret = type_pmu_register(*types); if (ret) goto err; } return 0; err: uncore_types_exit(uncore_mmio_uncores); uncore_mmio_uncores = empty_uncore; return ret; } struct intel_uncore_init_fun { void (*cpu_init)(void); int (*pci_init)(void); void (*mmio_init)(void); /* Discovery table is required */ bool use_discovery; /* The units in the discovery table should be ignored. */ int *uncore_units_ignore; }; static const struct intel_uncore_init_fun nhm_uncore_init __initconst = { .cpu_init = nhm_uncore_cpu_init, }; static const struct intel_uncore_init_fun snb_uncore_init __initconst = { .cpu_init = snb_uncore_cpu_init, .pci_init = snb_uncore_pci_init, }; static const struct intel_uncore_init_fun ivb_uncore_init __initconst = { .cpu_init = snb_uncore_cpu_init, .pci_init = ivb_uncore_pci_init, }; static const struct intel_uncore_init_fun hsw_uncore_init __initconst = { .cpu_init = snb_uncore_cpu_init, .pci_init = hsw_uncore_pci_init, }; static const struct intel_uncore_init_fun bdw_uncore_init __initconst = { .cpu_init = snb_uncore_cpu_init, .pci_init = bdw_uncore_pci_init, }; static const struct intel_uncore_init_fun snbep_uncore_init __initconst = { .cpu_init = snbep_uncore_cpu_init, .pci_init = snbep_uncore_pci_init, }; static const struct intel_uncore_init_fun nhmex_uncore_init __initconst = { .cpu_init = nhmex_uncore_cpu_init, }; static const struct intel_uncore_init_fun ivbep_uncore_init __initconst = { .cpu_init = ivbep_uncore_cpu_init, .pci_init = ivbep_uncore_pci_init, }; static const struct intel_uncore_init_fun hswep_uncore_init __initconst = { .cpu_init = hswep_uncore_cpu_init, .pci_init = hswep_uncore_pci_init, }; static const struct intel_uncore_init_fun bdx_uncore_init __initconst = { .cpu_init = bdx_uncore_cpu_init, .pci_init = bdx_uncore_pci_init, }; static const struct intel_uncore_init_fun knl_uncore_init __initconst = { .cpu_init = knl_uncore_cpu_init, .pci_init = knl_uncore_pci_init, }; static const struct intel_uncore_init_fun skl_uncore_init __initconst = { .cpu_init = skl_uncore_cpu_init, .pci_init = skl_uncore_pci_init, }; static const struct intel_uncore_init_fun skx_uncore_init __initconst = { .cpu_init = skx_uncore_cpu_init, .pci_init = skx_uncore_pci_init, }; static const struct intel_uncore_init_fun icl_uncore_init __initconst = { .cpu_init = icl_uncore_cpu_init, .pci_init = skl_uncore_pci_init, }; static const struct intel_uncore_init_fun tgl_uncore_init __initconst = { .cpu_init = tgl_uncore_cpu_init, .mmio_init = tgl_uncore_mmio_init, }; static const struct intel_uncore_init_fun tgl_l_uncore_init __initconst = { .cpu_init = tgl_uncore_cpu_init, .mmio_init = tgl_l_uncore_mmio_init, }; static const struct intel_uncore_init_fun rkl_uncore_init __initconst = { .cpu_init = tgl_uncore_cpu_init, .pci_init = skl_uncore_pci_init, }; static const struct intel_uncore_init_fun adl_uncore_init __initconst = { .cpu_init = adl_uncore_cpu_init, .mmio_init = adl_uncore_mmio_init, }; static const struct intel_uncore_init_fun mtl_uncore_init __initconst = { .cpu_init = mtl_uncore_cpu_init, .mmio_init = adl_uncore_mmio_init, }; static const struct intel_uncore_init_fun icx_uncore_init __initconst = { .cpu_init = icx_uncore_cpu_init, .pci_init = icx_uncore_pci_init, .mmio_init = icx_uncore_mmio_init, }; static const struct intel_uncore_init_fun snr_uncore_init __initconst = { .cpu_init = snr_uncore_cpu_init, .pci_init = snr_uncore_pci_init, .mmio_init = snr_uncore_mmio_init, }; static const struct intel_uncore_init_fun spr_uncore_init __initconst = { .cpu_init = spr_uncore_cpu_init, .pci_init = spr_uncore_pci_init, .mmio_init = spr_uncore_mmio_init, .use_discovery = true, .uncore_units_ignore = spr_uncore_units_ignore, }; static const struct intel_uncore_init_fun generic_uncore_init __initconst = { .cpu_init = intel_uncore_generic_uncore_cpu_init, .pci_init = intel_uncore_generic_uncore_pci_init, .mmio_init = intel_uncore_generic_uncore_mmio_init, }; static const struct x86_cpu_id intel_uncore_match[] __initconst = { X86_MATCH_INTEL_FAM6_MODEL(NEHALEM_EP, &nhm_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(NEHALEM, &nhm_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(WESTMERE, &nhm_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(WESTMERE_EP, &nhm_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE, &snb_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE, &ivb_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(HASWELL, &hsw_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(HASWELL_L, &hsw_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(HASWELL_G, &hsw_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL, &bdw_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_G, &bdw_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE_X, &snbep_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(NEHALEM_EX, &nhmex_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(WESTMERE_EX, &nhmex_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE_X, &ivbep_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(HASWELL_X, &hswep_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_X, &bdx_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_D, &bdx_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNL, &knl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNM, &knl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE, &skl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_L, &skl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_X, &skx_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE_L, &skl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE, &skl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE_L, &skl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE, &skl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_L, &icl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_NNPI, &icl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE, &icl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_D, &icx_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_X, &icx_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(TIGERLAKE_L, &tgl_l_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(TIGERLAKE, &tgl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ROCKETLAKE, &rkl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ALDERLAKE, &adl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ALDERLAKE_L, &adl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE, &adl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE_P, &adl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE_S, &adl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(METEORLAKE, &mtl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(METEORLAKE_L, &mtl_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(SAPPHIRERAPIDS_X, &spr_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(EMERALDRAPIDS_X, &spr_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT_D, &snr_uncore_init), X86_MATCH_INTEL_FAM6_MODEL(ATOM_GRACEMONT, &adl_uncore_init), {}, }; MODULE_DEVICE_TABLE(x86cpu, intel_uncore_match); static int __init intel_uncore_init(void) { const struct x86_cpu_id *id; struct intel_uncore_init_fun *uncore_init; int pret = 0, cret = 0, mret = 0, ret; if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) return -ENODEV; __uncore_max_dies = topology_max_packages() * topology_max_die_per_package(); id = x86_match_cpu(intel_uncore_match); if (!id) { if (!uncore_no_discover && intel_uncore_has_discovery_tables(NULL)) uncore_init = (struct intel_uncore_init_fun *)&generic_uncore_init; else return -ENODEV; } else { uncore_init = (struct intel_uncore_init_fun *)id->driver_data; if (uncore_no_discover && uncore_init->use_discovery) return -ENODEV; if (uncore_init->use_discovery && !intel_uncore_has_discovery_tables(uncore_init->uncore_units_ignore)) return -ENODEV; } if (uncore_init->pci_init) { pret = uncore_init->pci_init(); if (!pret) pret = uncore_pci_init(); } if (uncore_init->cpu_init) { uncore_init->cpu_init(); cret = uncore_cpu_init(); } if (uncore_init->mmio_init) { uncore_init->mmio_init(); mret = uncore_mmio_init(); } if (cret && pret && mret) { ret = -ENODEV; goto free_discovery; } /* Install hotplug callbacks to setup the targets for each package */ ret = cpuhp_setup_state(CPUHP_AP_PERF_X86_UNCORE_ONLINE, "perf/x86/intel/uncore:online", uncore_event_cpu_online, uncore_event_cpu_offline); if (ret) goto err; return 0; err: uncore_types_exit(uncore_msr_uncores); uncore_types_exit(uncore_mmio_uncores); uncore_pci_exit(); free_discovery: intel_uncore_clear_discovery_tables(); return ret; } module_init(intel_uncore_init); static void __exit intel_uncore_exit(void) { cpuhp_remove_state(CPUHP_AP_PERF_X86_UNCORE_ONLINE); uncore_types_exit(uncore_msr_uncores); uncore_types_exit(uncore_mmio_uncores); uncore_pci_exit(); intel_uncore_clear_discovery_tables(); } module_exit(intel_uncore_exit);
linux-master
arch/x86/events/intel/uncore.c
// SPDX-License-Identifier: GPL-2.0-only /* * Intel(R) Processor Trace PMU driver for perf * Copyright (c) 2013-2014, Intel Corporation. * * Intel PT is specified in the Intel Architecture Instruction Set Extensions * Programming Reference: * http://software.intel.com/en-us/intel-isa-extensions */ #undef DEBUG #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/types.h> #include <linux/bits.h> #include <linux/limits.h> #include <linux/slab.h> #include <linux/device.h> #include <asm/perf_event.h> #include <asm/insn.h> #include <asm/io.h> #include <asm/intel_pt.h> #include <asm/intel-family.h> #include "../perf_event.h" #include "pt.h" static DEFINE_PER_CPU(struct pt, pt_ctx); static struct pt_pmu pt_pmu; /* * Capabilities of Intel PT hardware, such as number of address bits or * supported output schemes, are cached and exported to userspace as "caps" * attribute group of pt pmu device * (/sys/bus/event_source/devices/intel_pt/caps/) so that userspace can store * relevant bits together with intel_pt traces. * * These are necessary for both trace decoding (payloads_lip, contains address * width encoded in IP-related packets), and event configuration (bitmasks with * permitted values for certain bit fields). */ #define PT_CAP(_n, _l, _r, _m) \ [PT_CAP_ ## _n] = { .name = __stringify(_n), .leaf = _l, \ .reg = _r, .mask = _m } static struct pt_cap_desc { const char *name; u32 leaf; u8 reg; u32 mask; } pt_caps[] = { PT_CAP(max_subleaf, 0, CPUID_EAX, 0xffffffff), PT_CAP(cr3_filtering, 0, CPUID_EBX, BIT(0)), PT_CAP(psb_cyc, 0, CPUID_EBX, BIT(1)), PT_CAP(ip_filtering, 0, CPUID_EBX, BIT(2)), PT_CAP(mtc, 0, CPUID_EBX, BIT(3)), PT_CAP(ptwrite, 0, CPUID_EBX, BIT(4)), PT_CAP(power_event_trace, 0, CPUID_EBX, BIT(5)), PT_CAP(event_trace, 0, CPUID_EBX, BIT(7)), PT_CAP(tnt_disable, 0, CPUID_EBX, BIT(8)), PT_CAP(topa_output, 0, CPUID_ECX, BIT(0)), PT_CAP(topa_multiple_entries, 0, CPUID_ECX, BIT(1)), PT_CAP(single_range_output, 0, CPUID_ECX, BIT(2)), PT_CAP(output_subsys, 0, CPUID_ECX, BIT(3)), PT_CAP(payloads_lip, 0, CPUID_ECX, BIT(31)), PT_CAP(num_address_ranges, 1, CPUID_EAX, 0x7), PT_CAP(mtc_periods, 1, CPUID_EAX, 0xffff0000), PT_CAP(cycle_thresholds, 1, CPUID_EBX, 0xffff), PT_CAP(psb_periods, 1, CPUID_EBX, 0xffff0000), }; u32 intel_pt_validate_cap(u32 *caps, enum pt_capabilities capability) { struct pt_cap_desc *cd = &pt_caps[capability]; u32 c = caps[cd->leaf * PT_CPUID_REGS_NUM + cd->reg]; unsigned int shift = __ffs(cd->mask); return (c & cd->mask) >> shift; } EXPORT_SYMBOL_GPL(intel_pt_validate_cap); u32 intel_pt_validate_hw_cap(enum pt_capabilities cap) { return intel_pt_validate_cap(pt_pmu.caps, cap); } EXPORT_SYMBOL_GPL(intel_pt_validate_hw_cap); static ssize_t pt_cap_show(struct device *cdev, struct device_attribute *attr, char *buf) { struct dev_ext_attribute *ea = container_of(attr, struct dev_ext_attribute, attr); enum pt_capabilities cap = (long)ea->var; return snprintf(buf, PAGE_SIZE, "%x\n", intel_pt_validate_hw_cap(cap)); } static struct attribute_group pt_cap_group __ro_after_init = { .name = "caps", }; PMU_FORMAT_ATTR(pt, "config:0" ); PMU_FORMAT_ATTR(cyc, "config:1" ); PMU_FORMAT_ATTR(pwr_evt, "config:4" ); PMU_FORMAT_ATTR(fup_on_ptw, "config:5" ); PMU_FORMAT_ATTR(mtc, "config:9" ); PMU_FORMAT_ATTR(tsc, "config:10" ); PMU_FORMAT_ATTR(noretcomp, "config:11" ); PMU_FORMAT_ATTR(ptw, "config:12" ); PMU_FORMAT_ATTR(branch, "config:13" ); PMU_FORMAT_ATTR(event, "config:31" ); PMU_FORMAT_ATTR(notnt, "config:55" ); PMU_FORMAT_ATTR(mtc_period, "config:14-17" ); PMU_FORMAT_ATTR(cyc_thresh, "config:19-22" ); PMU_FORMAT_ATTR(psb_period, "config:24-27" ); static struct attribute *pt_formats_attr[] = { &format_attr_pt.attr, &format_attr_cyc.attr, &format_attr_pwr_evt.attr, &format_attr_event.attr, &format_attr_notnt.attr, &format_attr_fup_on_ptw.attr, &format_attr_mtc.attr, &format_attr_tsc.attr, &format_attr_noretcomp.attr, &format_attr_ptw.attr, &format_attr_branch.attr, &format_attr_mtc_period.attr, &format_attr_cyc_thresh.attr, &format_attr_psb_period.attr, NULL, }; static struct attribute_group pt_format_group = { .name = "format", .attrs = pt_formats_attr, }; static ssize_t pt_timing_attr_show(struct device *dev, struct device_attribute *attr, char *page) { struct perf_pmu_events_attr *pmu_attr = container_of(attr, struct perf_pmu_events_attr, attr); switch (pmu_attr->id) { case 0: return sprintf(page, "%lu\n", pt_pmu.max_nonturbo_ratio); case 1: return sprintf(page, "%u:%u\n", pt_pmu.tsc_art_num, pt_pmu.tsc_art_den); default: break; } return -EINVAL; } PMU_EVENT_ATTR(max_nonturbo_ratio, timing_attr_max_nonturbo_ratio, 0, pt_timing_attr_show); PMU_EVENT_ATTR(tsc_art_ratio, timing_attr_tsc_art_ratio, 1, pt_timing_attr_show); static struct attribute *pt_timing_attr[] = { &timing_attr_max_nonturbo_ratio.attr.attr, &timing_attr_tsc_art_ratio.attr.attr, NULL, }; static struct attribute_group pt_timing_group = { .attrs = pt_timing_attr, }; static const struct attribute_group *pt_attr_groups[] = { &pt_cap_group, &pt_format_group, &pt_timing_group, NULL, }; static int __init pt_pmu_hw_init(void) { struct dev_ext_attribute *de_attrs; struct attribute **attrs; size_t size; u64 reg; int ret; long i; rdmsrl(MSR_PLATFORM_INFO, reg); pt_pmu.max_nonturbo_ratio = (reg & 0xff00) >> 8; /* * if available, read in TSC to core crystal clock ratio, * otherwise, zero for numerator stands for "not enumerated" * as per SDM */ if (boot_cpu_data.cpuid_level >= CPUID_TSC_LEAF) { u32 eax, ebx, ecx, edx; cpuid(CPUID_TSC_LEAF, &eax, &ebx, &ecx, &edx); pt_pmu.tsc_art_num = ebx; pt_pmu.tsc_art_den = eax; } /* model-specific quirks */ switch (boot_cpu_data.x86_model) { case INTEL_FAM6_BROADWELL: case INTEL_FAM6_BROADWELL_D: case INTEL_FAM6_BROADWELL_G: case INTEL_FAM6_BROADWELL_X: /* not setting BRANCH_EN will #GP, erratum BDM106 */ pt_pmu.branch_en_always_on = true; break; default: break; } if (boot_cpu_has(X86_FEATURE_VMX)) { /* * Intel SDM, 36.5 "Tracing post-VMXON" says that * "IA32_VMX_MISC[bit 14]" being 1 means PT can trace * post-VMXON. */ rdmsrl(MSR_IA32_VMX_MISC, reg); if (reg & BIT(14)) pt_pmu.vmx = true; } for (i = 0; i < PT_CPUID_LEAVES; i++) { cpuid_count(20, i, &pt_pmu.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM], &pt_pmu.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM], &pt_pmu.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM], &pt_pmu.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM]); } ret = -ENOMEM; size = sizeof(struct attribute *) * (ARRAY_SIZE(pt_caps)+1); attrs = kzalloc(size, GFP_KERNEL); if (!attrs) goto fail; size = sizeof(struct dev_ext_attribute) * (ARRAY_SIZE(pt_caps)+1); de_attrs = kzalloc(size, GFP_KERNEL); if (!de_attrs) goto fail; for (i = 0; i < ARRAY_SIZE(pt_caps); i++) { struct dev_ext_attribute *de_attr = de_attrs + i; de_attr->attr.attr.name = pt_caps[i].name; sysfs_attr_init(&de_attr->attr.attr); de_attr->attr.attr.mode = S_IRUGO; de_attr->attr.show = pt_cap_show; de_attr->var = (void *)i; attrs[i] = &de_attr->attr.attr; } pt_cap_group.attrs = attrs; return 0; fail: kfree(attrs); return ret; } #define RTIT_CTL_CYC_PSB (RTIT_CTL_CYCLEACC | \ RTIT_CTL_CYC_THRESH | \ RTIT_CTL_PSB_FREQ) #define RTIT_CTL_MTC (RTIT_CTL_MTC_EN | \ RTIT_CTL_MTC_RANGE) #define RTIT_CTL_PTW (RTIT_CTL_PTW_EN | \ RTIT_CTL_FUP_ON_PTW) /* * Bit 0 (TraceEn) in the attr.config is meaningless as the * corresponding bit in the RTIT_CTL can only be controlled * by the driver; therefore, repurpose it to mean: pass * through the bit that was previously assumed to be always * on for PT, thereby allowing the user to *not* set it if * they so wish. See also pt_event_valid() and pt_config(). */ #define RTIT_CTL_PASSTHROUGH RTIT_CTL_TRACEEN #define PT_CONFIG_MASK (RTIT_CTL_TRACEEN | \ RTIT_CTL_TSC_EN | \ RTIT_CTL_DISRETC | \ RTIT_CTL_BRANCH_EN | \ RTIT_CTL_CYC_PSB | \ RTIT_CTL_MTC | \ RTIT_CTL_PWR_EVT_EN | \ RTIT_CTL_EVENT_EN | \ RTIT_CTL_NOTNT | \ RTIT_CTL_FUP_ON_PTW | \ RTIT_CTL_PTW_EN) static bool pt_event_valid(struct perf_event *event) { u64 config = event->attr.config; u64 allowed, requested; if ((config & PT_CONFIG_MASK) != config) return false; if (config & RTIT_CTL_CYC_PSB) { if (!intel_pt_validate_hw_cap(PT_CAP_psb_cyc)) return false; allowed = intel_pt_validate_hw_cap(PT_CAP_psb_periods); requested = (config & RTIT_CTL_PSB_FREQ) >> RTIT_CTL_PSB_FREQ_OFFSET; if (requested && (!(allowed & BIT(requested)))) return false; allowed = intel_pt_validate_hw_cap(PT_CAP_cycle_thresholds); requested = (config & RTIT_CTL_CYC_THRESH) >> RTIT_CTL_CYC_THRESH_OFFSET; if (requested && (!(allowed & BIT(requested)))) return false; } if (config & RTIT_CTL_MTC) { /* * In the unlikely case that CPUID lists valid mtc periods, * but not the mtc capability, drop out here. * * Spec says that setting mtc period bits while mtc bit in * CPUID is 0 will #GP, so better safe than sorry. */ if (!intel_pt_validate_hw_cap(PT_CAP_mtc)) return false; allowed = intel_pt_validate_hw_cap(PT_CAP_mtc_periods); if (!allowed) return false; requested = (config & RTIT_CTL_MTC_RANGE) >> RTIT_CTL_MTC_RANGE_OFFSET; if (!(allowed & BIT(requested))) return false; } if (config & RTIT_CTL_PWR_EVT_EN && !intel_pt_validate_hw_cap(PT_CAP_power_event_trace)) return false; if (config & RTIT_CTL_EVENT_EN && !intel_pt_validate_hw_cap(PT_CAP_event_trace)) return false; if (config & RTIT_CTL_NOTNT && !intel_pt_validate_hw_cap(PT_CAP_tnt_disable)) return false; if (config & RTIT_CTL_PTW) { if (!intel_pt_validate_hw_cap(PT_CAP_ptwrite)) return false; /* FUPonPTW without PTW doesn't make sense */ if ((config & RTIT_CTL_FUP_ON_PTW) && !(config & RTIT_CTL_PTW_EN)) return false; } /* * Setting bit 0 (TraceEn in RTIT_CTL MSR) in the attr.config * clears the assumption that BranchEn must always be enabled, * as was the case with the first implementation of PT. * If this bit is not set, the legacy behavior is preserved * for compatibility with the older userspace. * * Re-using bit 0 for this purpose is fine because it is never * directly set by the user; previous attempts at setting it in * the attr.config resulted in -EINVAL. */ if (config & RTIT_CTL_PASSTHROUGH) { /* * Disallow not setting BRANCH_EN where BRANCH_EN is * always required. */ if (pt_pmu.branch_en_always_on && !(config & RTIT_CTL_BRANCH_EN)) return false; } else { /* * Disallow BRANCH_EN without the PASSTHROUGH. */ if (config & RTIT_CTL_BRANCH_EN) return false; } return true; } /* * PT configuration helpers * These all are cpu affine and operate on a local PT */ static void pt_config_start(struct perf_event *event) { struct pt *pt = this_cpu_ptr(&pt_ctx); u64 ctl = event->hw.config; ctl |= RTIT_CTL_TRACEEN; if (READ_ONCE(pt->vmx_on)) perf_aux_output_flag(&pt->handle, PERF_AUX_FLAG_PARTIAL); else wrmsrl(MSR_IA32_RTIT_CTL, ctl); WRITE_ONCE(event->hw.config, ctl); } /* Address ranges and their corresponding msr configuration registers */ static const struct pt_address_range { unsigned long msr_a; unsigned long msr_b; unsigned int reg_off; } pt_address_ranges[] = { { .msr_a = MSR_IA32_RTIT_ADDR0_A, .msr_b = MSR_IA32_RTIT_ADDR0_B, .reg_off = RTIT_CTL_ADDR0_OFFSET, }, { .msr_a = MSR_IA32_RTIT_ADDR1_A, .msr_b = MSR_IA32_RTIT_ADDR1_B, .reg_off = RTIT_CTL_ADDR1_OFFSET, }, { .msr_a = MSR_IA32_RTIT_ADDR2_A, .msr_b = MSR_IA32_RTIT_ADDR2_B, .reg_off = RTIT_CTL_ADDR2_OFFSET, }, { .msr_a = MSR_IA32_RTIT_ADDR3_A, .msr_b = MSR_IA32_RTIT_ADDR3_B, .reg_off = RTIT_CTL_ADDR3_OFFSET, } }; static u64 pt_config_filters(struct perf_event *event) { struct pt_filters *filters = event->hw.addr_filters; struct pt *pt = this_cpu_ptr(&pt_ctx); unsigned int range = 0; u64 rtit_ctl = 0; if (!filters) return 0; perf_event_addr_filters_sync(event); for (range = 0; range < filters->nr_filters; range++) { struct pt_filter *filter = &filters->filter[range]; /* * Note, if the range has zero start/end addresses due * to its dynamic object not being loaded yet, we just * go ahead and program zeroed range, which will simply * produce no data. Note^2: if executable code at 0x0 * is a concern, we can set up an "invalid" configuration * such as msr_b < msr_a. */ /* avoid redundant msr writes */ if (pt->filters.filter[range].msr_a != filter->msr_a) { wrmsrl(pt_address_ranges[range].msr_a, filter->msr_a); pt->filters.filter[range].msr_a = filter->msr_a; } if (pt->filters.filter[range].msr_b != filter->msr_b) { wrmsrl(pt_address_ranges[range].msr_b, filter->msr_b); pt->filters.filter[range].msr_b = filter->msr_b; } rtit_ctl |= (u64)filter->config << pt_address_ranges[range].reg_off; } return rtit_ctl; } static void pt_config(struct perf_event *event) { struct pt *pt = this_cpu_ptr(&pt_ctx); struct pt_buffer *buf = perf_get_aux(&pt->handle); u64 reg; /* First round: clear STATUS, in particular the PSB byte counter. */ if (!event->hw.config) { perf_event_itrace_started(event); wrmsrl(MSR_IA32_RTIT_STATUS, 0); } reg = pt_config_filters(event); reg |= RTIT_CTL_TRACEEN; if (!buf->single) reg |= RTIT_CTL_TOPA; /* * Previously, we had BRANCH_EN on by default, but now that PT has * grown features outside of branch tracing, it is useful to allow * the user to disable it. Setting bit 0 in the event's attr.config * allows BRANCH_EN to pass through instead of being always on. See * also the comment in pt_event_valid(). */ if (event->attr.config & BIT(0)) { reg |= event->attr.config & RTIT_CTL_BRANCH_EN; } else { reg |= RTIT_CTL_BRANCH_EN; } if (!event->attr.exclude_kernel) reg |= RTIT_CTL_OS; if (!event->attr.exclude_user) reg |= RTIT_CTL_USR; reg |= (event->attr.config & PT_CONFIG_MASK); event->hw.config = reg; pt_config_start(event); } static void pt_config_stop(struct perf_event *event) { struct pt *pt = this_cpu_ptr(&pt_ctx); u64 ctl = READ_ONCE(event->hw.config); /* may be already stopped by a PMI */ if (!(ctl & RTIT_CTL_TRACEEN)) return; ctl &= ~RTIT_CTL_TRACEEN; if (!READ_ONCE(pt->vmx_on)) wrmsrl(MSR_IA32_RTIT_CTL, ctl); WRITE_ONCE(event->hw.config, ctl); /* * A wrmsr that disables trace generation serializes other PT * registers and causes all data packets to be written to memory, * but a fence is required for the data to become globally visible. * * The below WMB, separating data store and aux_head store matches * the consumer's RMB that separates aux_head load and data load. */ wmb(); } /** * struct topa - ToPA metadata * @list: linkage to struct pt_buffer's list of tables * @offset: offset of the first entry in this table in the buffer * @size: total size of all entries in this table * @last: index of the last initialized entry in this table * @z_count: how many times the first entry repeats */ struct topa { struct list_head list; u64 offset; size_t size; int last; unsigned int z_count; }; /* * Keep ToPA table-related metadata on the same page as the actual table, * taking up a few words from the top */ #define TENTS_PER_PAGE \ ((PAGE_SIZE - sizeof(struct topa)) / sizeof(struct topa_entry)) /** * struct topa_page - page-sized ToPA table with metadata at the top * @table: actual ToPA table entries, as understood by PT hardware * @topa: metadata */ struct topa_page { struct topa_entry table[TENTS_PER_PAGE]; struct topa topa; }; static inline struct topa_page *topa_to_page(struct topa *topa) { return container_of(topa, struct topa_page, topa); } static inline struct topa_page *topa_entry_to_page(struct topa_entry *te) { return (struct topa_page *)((unsigned long)te & PAGE_MASK); } static inline phys_addr_t topa_pfn(struct topa *topa) { return PFN_DOWN(virt_to_phys(topa_to_page(topa))); } /* make -1 stand for the last table entry */ #define TOPA_ENTRY(t, i) \ ((i) == -1 \ ? &topa_to_page(t)->table[(t)->last] \ : &topa_to_page(t)->table[(i)]) #define TOPA_ENTRY_SIZE(t, i) (sizes(TOPA_ENTRY((t), (i))->size)) #define TOPA_ENTRY_PAGES(t, i) (1 << TOPA_ENTRY((t), (i))->size) static void pt_config_buffer(struct pt_buffer *buf) { struct pt *pt = this_cpu_ptr(&pt_ctx); u64 reg, mask; void *base; if (buf->single) { base = buf->data_pages[0]; mask = (buf->nr_pages * PAGE_SIZE - 1) >> 7; } else { base = topa_to_page(buf->cur)->table; mask = (u64)buf->cur_idx; } reg = virt_to_phys(base); if (pt->output_base != reg) { pt->output_base = reg; wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, reg); } reg = 0x7f | (mask << 7) | ((u64)buf->output_off << 32); if (pt->output_mask != reg) { pt->output_mask = reg; wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, reg); } } /** * topa_alloc() - allocate page-sized ToPA table * @cpu: CPU on which to allocate. * @gfp: Allocation flags. * * Return: On success, return the pointer to ToPA table page. */ static struct topa *topa_alloc(int cpu, gfp_t gfp) { int node = cpu_to_node(cpu); struct topa_page *tp; struct page *p; p = alloc_pages_node(node, gfp | __GFP_ZERO, 0); if (!p) return NULL; tp = page_address(p); tp->topa.last = 0; /* * In case of singe-entry ToPA, always put the self-referencing END * link as the 2nd entry in the table */ if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) { TOPA_ENTRY(&tp->topa, 1)->base = page_to_phys(p) >> TOPA_SHIFT; TOPA_ENTRY(&tp->topa, 1)->end = 1; } return &tp->topa; } /** * topa_free() - free a page-sized ToPA table * @topa: Table to deallocate. */ static void topa_free(struct topa *topa) { free_page((unsigned long)topa); } /** * topa_insert_table() - insert a ToPA table into a buffer * @buf: PT buffer that's being extended. * @topa: New topa table to be inserted. * * If it's the first table in this buffer, set up buffer's pointers * accordingly; otherwise, add a END=1 link entry to @topa to the current * "last" table and adjust the last table pointer to @topa. */ static void topa_insert_table(struct pt_buffer *buf, struct topa *topa) { struct topa *last = buf->last; list_add_tail(&topa->list, &buf->tables); if (!buf->first) { buf->first = buf->last = buf->cur = topa; return; } topa->offset = last->offset + last->size; buf->last = topa; if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) return; BUG_ON(last->last != TENTS_PER_PAGE - 1); TOPA_ENTRY(last, -1)->base = topa_pfn(topa); TOPA_ENTRY(last, -1)->end = 1; } /** * topa_table_full() - check if a ToPA table is filled up * @topa: ToPA table. */ static bool topa_table_full(struct topa *topa) { /* single-entry ToPA is a special case */ if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) return !!topa->last; return topa->last == TENTS_PER_PAGE - 1; } /** * topa_insert_pages() - create a list of ToPA tables * @buf: PT buffer being initialized. * @gfp: Allocation flags. * * This initializes a list of ToPA tables with entries from * the data_pages provided by rb_alloc_aux(). * * Return: 0 on success or error code. */ static int topa_insert_pages(struct pt_buffer *buf, int cpu, gfp_t gfp) { struct topa *topa = buf->last; int order = 0; struct page *p; p = virt_to_page(buf->data_pages[buf->nr_pages]); if (PagePrivate(p)) order = page_private(p); if (topa_table_full(topa)) { topa = topa_alloc(cpu, gfp); if (!topa) return -ENOMEM; topa_insert_table(buf, topa); } if (topa->z_count == topa->last - 1) { if (order == TOPA_ENTRY(topa, topa->last - 1)->size) topa->z_count++; } TOPA_ENTRY(topa, -1)->base = page_to_phys(p) >> TOPA_SHIFT; TOPA_ENTRY(topa, -1)->size = order; if (!buf->snapshot && !intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) { TOPA_ENTRY(topa, -1)->intr = 1; TOPA_ENTRY(topa, -1)->stop = 1; } topa->last++; topa->size += sizes(order); buf->nr_pages += 1ul << order; return 0; } /** * pt_topa_dump() - print ToPA tables and their entries * @buf: PT buffer. */ static void pt_topa_dump(struct pt_buffer *buf) { struct topa *topa; list_for_each_entry(topa, &buf->tables, list) { struct topa_page *tp = topa_to_page(topa); int i; pr_debug("# table @%p, off %llx size %zx\n", tp->table, topa->offset, topa->size); for (i = 0; i < TENTS_PER_PAGE; i++) { pr_debug("# entry @%p (%lx sz %u %c%c%c) raw=%16llx\n", &tp->table[i], (unsigned long)tp->table[i].base << TOPA_SHIFT, sizes(tp->table[i].size), tp->table[i].end ? 'E' : ' ', tp->table[i].intr ? 'I' : ' ', tp->table[i].stop ? 'S' : ' ', *(u64 *)&tp->table[i]); if ((intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) && tp->table[i].stop) || tp->table[i].end) break; if (!i && topa->z_count) i += topa->z_count; } } } /** * pt_buffer_advance() - advance to the next output region * @buf: PT buffer. * * Advance the current pointers in the buffer to the next ToPA entry. */ static void pt_buffer_advance(struct pt_buffer *buf) { buf->output_off = 0; buf->cur_idx++; if (buf->cur_idx == buf->cur->last) { if (buf->cur == buf->last) buf->cur = buf->first; else buf->cur = list_entry(buf->cur->list.next, struct topa, list); buf->cur_idx = 0; } } /** * pt_update_head() - calculate current offsets and sizes * @pt: Per-cpu pt context. * * Update buffer's current write pointer position and data size. */ static void pt_update_head(struct pt *pt) { struct pt_buffer *buf = perf_get_aux(&pt->handle); u64 topa_idx, base, old; if (buf->single) { local_set(&buf->data_size, buf->output_off); return; } /* offset of the first region in this table from the beginning of buf */ base = buf->cur->offset + buf->output_off; /* offset of the current output region within this table */ for (topa_idx = 0; topa_idx < buf->cur_idx; topa_idx++) base += TOPA_ENTRY_SIZE(buf->cur, topa_idx); if (buf->snapshot) { local_set(&buf->data_size, base); } else { old = (local64_xchg(&buf->head, base) & ((buf->nr_pages << PAGE_SHIFT) - 1)); if (base < old) base += buf->nr_pages << PAGE_SHIFT; local_add(base - old, &buf->data_size); } } /** * pt_buffer_region() - obtain current output region's address * @buf: PT buffer. */ static void *pt_buffer_region(struct pt_buffer *buf) { return phys_to_virt(TOPA_ENTRY(buf->cur, buf->cur_idx)->base << TOPA_SHIFT); } /** * pt_buffer_region_size() - obtain current output region's size * @buf: PT buffer. */ static size_t pt_buffer_region_size(struct pt_buffer *buf) { return TOPA_ENTRY_SIZE(buf->cur, buf->cur_idx); } /** * pt_handle_status() - take care of possible status conditions * @pt: Per-cpu pt context. */ static void pt_handle_status(struct pt *pt) { struct pt_buffer *buf = perf_get_aux(&pt->handle); int advance = 0; u64 status; rdmsrl(MSR_IA32_RTIT_STATUS, status); if (status & RTIT_STATUS_ERROR) { pr_err_ratelimited("ToPA ERROR encountered, trying to recover\n"); pt_topa_dump(buf); status &= ~RTIT_STATUS_ERROR; } if (status & RTIT_STATUS_STOPPED) { status &= ~RTIT_STATUS_STOPPED; /* * On systems that only do single-entry ToPA, hitting STOP * means we are already losing data; need to let the decoder * know. */ if (!buf->single && (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) || buf->output_off == pt_buffer_region_size(buf))) { perf_aux_output_flag(&pt->handle, PERF_AUX_FLAG_TRUNCATED); advance++; } } /* * Also on single-entry ToPA implementations, interrupt will come * before the output reaches its output region's boundary. */ if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) && !buf->snapshot && pt_buffer_region_size(buf) - buf->output_off <= TOPA_PMI_MARGIN) { void *head = pt_buffer_region(buf); /* everything within this margin needs to be zeroed out */ memset(head + buf->output_off, 0, pt_buffer_region_size(buf) - buf->output_off); advance++; } if (advance) pt_buffer_advance(buf); wrmsrl(MSR_IA32_RTIT_STATUS, status); } /** * pt_read_offset() - translate registers into buffer pointers * @buf: PT buffer. * * Set buffer's output pointers from MSR values. */ static void pt_read_offset(struct pt_buffer *buf) { struct pt *pt = this_cpu_ptr(&pt_ctx); struct topa_page *tp; if (!buf->single) { rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, pt->output_base); tp = phys_to_virt(pt->output_base); buf->cur = &tp->topa; } rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, pt->output_mask); /* offset within current output region */ buf->output_off = pt->output_mask >> 32; /* index of current output region within this table */ if (!buf->single) buf->cur_idx = (pt->output_mask & 0xffffff80) >> 7; } static struct topa_entry * pt_topa_entry_for_page(struct pt_buffer *buf, unsigned int pg) { struct topa_page *tp; struct topa *topa; unsigned int idx, cur_pg = 0, z_pg = 0, start_idx = 0; /* * Indicates a bug in the caller. */ if (WARN_ON_ONCE(pg >= buf->nr_pages)) return NULL; /* * First, find the ToPA table where @pg fits. With high * order allocations, there shouldn't be many of these. */ list_for_each_entry(topa, &buf->tables, list) { if (topa->offset + topa->size > pg << PAGE_SHIFT) goto found; } /* * Hitting this means we have a problem in the ToPA * allocation code. */ WARN_ON_ONCE(1); return NULL; found: /* * Indicates a problem in the ToPA allocation code. */ if (WARN_ON_ONCE(topa->last == -1)) return NULL; tp = topa_to_page(topa); cur_pg = PFN_DOWN(topa->offset); if (topa->z_count) { z_pg = TOPA_ENTRY_PAGES(topa, 0) * (topa->z_count + 1); start_idx = topa->z_count + 1; } /* * Multiple entries at the beginning of the table have the same size, * ideally all of them; if @pg falls there, the search is done. */ if (pg >= cur_pg && pg < cur_pg + z_pg) { idx = (pg - cur_pg) / TOPA_ENTRY_PAGES(topa, 0); return &tp->table[idx]; } /* * Otherwise, slow path: iterate through the remaining entries. */ for (idx = start_idx, cur_pg += z_pg; idx < topa->last; idx++) { if (cur_pg + TOPA_ENTRY_PAGES(topa, idx) > pg) return &tp->table[idx]; cur_pg += TOPA_ENTRY_PAGES(topa, idx); } /* * Means we couldn't find a ToPA entry in the table that does match. */ WARN_ON_ONCE(1); return NULL; } static struct topa_entry * pt_topa_prev_entry(struct pt_buffer *buf, struct topa_entry *te) { unsigned long table = (unsigned long)te & ~(PAGE_SIZE - 1); struct topa_page *tp; struct topa *topa; tp = (struct topa_page *)table; if (tp->table != te) return --te; topa = &tp->topa; if (topa == buf->first) topa = buf->last; else topa = list_prev_entry(topa, list); tp = topa_to_page(topa); return &tp->table[topa->last - 1]; } /** * pt_buffer_reset_markers() - place interrupt and stop bits in the buffer * @buf: PT buffer. * @handle: Current output handle. * * Place INT and STOP marks to prevent overwriting old data that the consumer * hasn't yet collected and waking up the consumer after a certain fraction of * the buffer has filled up. Only needed and sensible for non-snapshot counters. * * This obviously relies on buf::head to figure out buffer markers, so it has * to be called after pt_buffer_reset_offsets() and before the hardware tracing * is enabled. */ static int pt_buffer_reset_markers(struct pt_buffer *buf, struct perf_output_handle *handle) { unsigned long head = local64_read(&buf->head); unsigned long idx, npages, wakeup; if (buf->single) return 0; /* can't stop in the middle of an output region */ if (buf->output_off + handle->size + 1 < pt_buffer_region_size(buf)) { perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED); return -EINVAL; } /* single entry ToPA is handled by marking all regions STOP=1 INT=1 */ if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) return 0; /* clear STOP and INT from current entry */ if (buf->stop_te) { buf->stop_te->stop = 0; buf->stop_te->intr = 0; } if (buf->intr_te) buf->intr_te->intr = 0; /* how many pages till the STOP marker */ npages = handle->size >> PAGE_SHIFT; /* if it's on a page boundary, fill up one more page */ if (!offset_in_page(head + handle->size + 1)) npages++; idx = (head >> PAGE_SHIFT) + npages; idx &= buf->nr_pages - 1; if (idx != buf->stop_pos) { buf->stop_pos = idx; buf->stop_te = pt_topa_entry_for_page(buf, idx); buf->stop_te = pt_topa_prev_entry(buf, buf->stop_te); } wakeup = handle->wakeup >> PAGE_SHIFT; /* in the worst case, wake up the consumer one page before hard stop */ idx = (head >> PAGE_SHIFT) + npages - 1; if (idx > wakeup) idx = wakeup; idx &= buf->nr_pages - 1; if (idx != buf->intr_pos) { buf->intr_pos = idx; buf->intr_te = pt_topa_entry_for_page(buf, idx); buf->intr_te = pt_topa_prev_entry(buf, buf->intr_te); } buf->stop_te->stop = 1; buf->stop_te->intr = 1; buf->intr_te->intr = 1; return 0; } /** * pt_buffer_reset_offsets() - adjust buffer's write pointers from aux_head * @buf: PT buffer. * @head: Write pointer (aux_head) from AUX buffer. * * Find the ToPA table and entry corresponding to given @head and set buffer's * "current" pointers accordingly. This is done after we have obtained the * current aux_head position from a successful call to perf_aux_output_begin() * to make sure the hardware is writing to the right place. * * This function modifies buf::{cur,cur_idx,output_off} that will be programmed * into PT msrs when the tracing is enabled and buf::head and buf::data_size, * which are used to determine INT and STOP markers' locations by a subsequent * call to pt_buffer_reset_markers(). */ static void pt_buffer_reset_offsets(struct pt_buffer *buf, unsigned long head) { struct topa_page *cur_tp; struct topa_entry *te; int pg; if (buf->snapshot) head &= (buf->nr_pages << PAGE_SHIFT) - 1; if (!buf->single) { pg = (head >> PAGE_SHIFT) & (buf->nr_pages - 1); te = pt_topa_entry_for_page(buf, pg); cur_tp = topa_entry_to_page(te); buf->cur = &cur_tp->topa; buf->cur_idx = te - TOPA_ENTRY(buf->cur, 0); buf->output_off = head & (pt_buffer_region_size(buf) - 1); } else { buf->output_off = head; } local64_set(&buf->head, head); local_set(&buf->data_size, 0); } /** * pt_buffer_fini_topa() - deallocate ToPA structure of a buffer * @buf: PT buffer. */ static void pt_buffer_fini_topa(struct pt_buffer *buf) { struct topa *topa, *iter; if (buf->single) return; list_for_each_entry_safe(topa, iter, &buf->tables, list) { /* * right now, this is in free_aux() path only, so * no need to unlink this table from the list */ topa_free(topa); } } /** * pt_buffer_init_topa() - initialize ToPA table for pt buffer * @buf: PT buffer. * @size: Total size of all regions within this ToPA. * @gfp: Allocation flags. */ static int pt_buffer_init_topa(struct pt_buffer *buf, int cpu, unsigned long nr_pages, gfp_t gfp) { struct topa *topa; int err; topa = topa_alloc(cpu, gfp); if (!topa) return -ENOMEM; topa_insert_table(buf, topa); while (buf->nr_pages < nr_pages) { err = topa_insert_pages(buf, cpu, gfp); if (err) { pt_buffer_fini_topa(buf); return -ENOMEM; } } /* link last table to the first one, unless we're double buffering */ if (intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) { TOPA_ENTRY(buf->last, -1)->base = topa_pfn(buf->first); TOPA_ENTRY(buf->last, -1)->end = 1; } pt_topa_dump(buf); return 0; } static int pt_buffer_try_single(struct pt_buffer *buf, int nr_pages) { struct page *p = virt_to_page(buf->data_pages[0]); int ret = -ENOTSUPP, order = 0; /* * We can use single range output mode * + in snapshot mode, where we don't need interrupts; * + if the hardware supports it; * + if the entire buffer is one contiguous allocation. */ if (!buf->snapshot) goto out; if (!intel_pt_validate_hw_cap(PT_CAP_single_range_output)) goto out; if (PagePrivate(p)) order = page_private(p); if (1 << order != nr_pages) goto out; /* * Some processors cannot always support single range for more than * 4KB - refer errata TGL052, ADL037 and RPL017. Future processors might * also be affected, so for now rather than trying to keep track of * which ones, just disable it for all. */ if (nr_pages > 1) goto out; buf->single = true; buf->nr_pages = nr_pages; ret = 0; out: return ret; } /** * pt_buffer_setup_aux() - set up topa tables for a PT buffer * @cpu: Cpu on which to allocate, -1 means current. * @pages: Array of pointers to buffer pages passed from perf core. * @nr_pages: Number of pages in the buffer. * @snapshot: If this is a snapshot/overwrite counter. * * This is a pmu::setup_aux callback that sets up ToPA tables and all the * bookkeeping for an AUX buffer. * * Return: Our private PT buffer structure. */ static void * pt_buffer_setup_aux(struct perf_event *event, void **pages, int nr_pages, bool snapshot) { struct pt_buffer *buf; int node, ret, cpu = event->cpu; if (!nr_pages) return NULL; /* * Only support AUX sampling in snapshot mode, where we don't * generate NMIs. */ if (event->attr.aux_sample_size && !snapshot) return NULL; if (cpu == -1) cpu = raw_smp_processor_id(); node = cpu_to_node(cpu); buf = kzalloc_node(sizeof(struct pt_buffer), GFP_KERNEL, node); if (!buf) return NULL; buf->snapshot = snapshot; buf->data_pages = pages; buf->stop_pos = -1; buf->intr_pos = -1; INIT_LIST_HEAD(&buf->tables); ret = pt_buffer_try_single(buf, nr_pages); if (!ret) return buf; ret = pt_buffer_init_topa(buf, cpu, nr_pages, GFP_KERNEL); if (ret) { kfree(buf); return NULL; } return buf; } /** * pt_buffer_free_aux() - perf AUX deallocation path callback * @data: PT buffer. */ static void pt_buffer_free_aux(void *data) { struct pt_buffer *buf = data; pt_buffer_fini_topa(buf); kfree(buf); } static int pt_addr_filters_init(struct perf_event *event) { struct pt_filters *filters; int node = event->cpu == -1 ? -1 : cpu_to_node(event->cpu); if (!intel_pt_validate_hw_cap(PT_CAP_num_address_ranges)) return 0; filters = kzalloc_node(sizeof(struct pt_filters), GFP_KERNEL, node); if (!filters) return -ENOMEM; if (event->parent) memcpy(filters, event->parent->hw.addr_filters, sizeof(*filters)); event->hw.addr_filters = filters; return 0; } static void pt_addr_filters_fini(struct perf_event *event) { kfree(event->hw.addr_filters); event->hw.addr_filters = NULL; } #ifdef CONFIG_X86_64 /* Clamp to a canonical address greater-than-or-equal-to the address given */ static u64 clamp_to_ge_canonical_addr(u64 vaddr, u8 vaddr_bits) { return __is_canonical_address(vaddr, vaddr_bits) ? vaddr : -BIT_ULL(vaddr_bits - 1); } /* Clamp to a canonical address less-than-or-equal-to the address given */ static u64 clamp_to_le_canonical_addr(u64 vaddr, u8 vaddr_bits) { return __is_canonical_address(vaddr, vaddr_bits) ? vaddr : BIT_ULL(vaddr_bits - 1) - 1; } #else #define clamp_to_ge_canonical_addr(x, y) (x) #define clamp_to_le_canonical_addr(x, y) (x) #endif static int pt_event_addr_filters_validate(struct list_head *filters) { struct perf_addr_filter *filter; int range = 0; list_for_each_entry(filter, filters, entry) { /* * PT doesn't support single address triggers and * 'start' filters. */ if (!filter->size || filter->action == PERF_ADDR_FILTER_ACTION_START) return -EOPNOTSUPP; if (++range > intel_pt_validate_hw_cap(PT_CAP_num_address_ranges)) return -EOPNOTSUPP; } return 0; } static void pt_event_addr_filters_sync(struct perf_event *event) { struct perf_addr_filters_head *head = perf_event_addr_filters(event); unsigned long msr_a, msr_b; struct perf_addr_filter_range *fr = event->addr_filter_ranges; struct pt_filters *filters = event->hw.addr_filters; struct perf_addr_filter *filter; int range = 0; if (!filters) return; list_for_each_entry(filter, &head->list, entry) { if (filter->path.dentry && !fr[range].start) { msr_a = msr_b = 0; } else { unsigned long n = fr[range].size - 1; unsigned long a = fr[range].start; unsigned long b; if (a > ULONG_MAX - n) b = ULONG_MAX; else b = a + n; /* * Apply the offset. 64-bit addresses written to the * MSRs must be canonical, but the range can encompass * non-canonical addresses. Since software cannot * execute at non-canonical addresses, adjusting to * canonical addresses does not affect the result of the * address filter. */ msr_a = clamp_to_ge_canonical_addr(a, boot_cpu_data.x86_virt_bits); msr_b = clamp_to_le_canonical_addr(b, boot_cpu_data.x86_virt_bits); if (msr_b < msr_a) msr_a = msr_b = 0; } filters->filter[range].msr_a = msr_a; filters->filter[range].msr_b = msr_b; if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER) filters->filter[range].config = 1; else filters->filter[range].config = 2; range++; } filters->nr_filters = range; } /** * intel_pt_interrupt() - PT PMI handler */ void intel_pt_interrupt(void) { struct pt *pt = this_cpu_ptr(&pt_ctx); struct pt_buffer *buf; struct perf_event *event = pt->handle.event; /* * There may be a dangling PT bit in the interrupt status register * after PT has been disabled by pt_event_stop(). Make sure we don't * do anything (particularly, re-enable) for this event here. */ if (!READ_ONCE(pt->handle_nmi)) return; if (!event) return; pt_config_stop(event); buf = perf_get_aux(&pt->handle); if (!buf) return; pt_read_offset(buf); pt_handle_status(pt); pt_update_head(pt); perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0)); if (!event->hw.state) { int ret; buf = perf_aux_output_begin(&pt->handle, event); if (!buf) { event->hw.state = PERF_HES_STOPPED; return; } pt_buffer_reset_offsets(buf, pt->handle.head); /* snapshot counters don't use PMI, so it's safe */ ret = pt_buffer_reset_markers(buf, &pt->handle); if (ret) { perf_aux_output_end(&pt->handle, 0); return; } pt_config_buffer(buf); pt_config_start(event); } } void intel_pt_handle_vmx(int on) { struct pt *pt = this_cpu_ptr(&pt_ctx); struct perf_event *event; unsigned long flags; /* PT plays nice with VMX, do nothing */ if (pt_pmu.vmx) return; /* * VMXON will clear RTIT_CTL.TraceEn; we need to make * sure to not try to set it while VMX is on. Disable * interrupts to avoid racing with pmu callbacks; * concurrent PMI should be handled fine. */ local_irq_save(flags); WRITE_ONCE(pt->vmx_on, on); /* * If an AUX transaction is in progress, it will contain * gap(s), so flag it PARTIAL to inform the user. */ event = pt->handle.event; if (event) perf_aux_output_flag(&pt->handle, PERF_AUX_FLAG_PARTIAL); /* Turn PTs back on */ if (!on && event) wrmsrl(MSR_IA32_RTIT_CTL, event->hw.config); local_irq_restore(flags); } EXPORT_SYMBOL_GPL(intel_pt_handle_vmx); /* * PMU callbacks */ static void pt_event_start(struct perf_event *event, int mode) { struct hw_perf_event *hwc = &event->hw; struct pt *pt = this_cpu_ptr(&pt_ctx); struct pt_buffer *buf; buf = perf_aux_output_begin(&pt->handle, event); if (!buf) goto fail_stop; pt_buffer_reset_offsets(buf, pt->handle.head); if (!buf->snapshot) { if (pt_buffer_reset_markers(buf, &pt->handle)) goto fail_end_stop; } WRITE_ONCE(pt->handle_nmi, 1); hwc->state = 0; pt_config_buffer(buf); pt_config(event); return; fail_end_stop: perf_aux_output_end(&pt->handle, 0); fail_stop: hwc->state = PERF_HES_STOPPED; } static void pt_event_stop(struct perf_event *event, int mode) { struct pt *pt = this_cpu_ptr(&pt_ctx); /* * Protect against the PMI racing with disabling wrmsr, * see comment in intel_pt_interrupt(). */ WRITE_ONCE(pt->handle_nmi, 0); pt_config_stop(event); if (event->hw.state == PERF_HES_STOPPED) return; event->hw.state = PERF_HES_STOPPED; if (mode & PERF_EF_UPDATE) { struct pt_buffer *buf = perf_get_aux(&pt->handle); if (!buf) return; if (WARN_ON_ONCE(pt->handle.event != event)) return; pt_read_offset(buf); pt_handle_status(pt); pt_update_head(pt); if (buf->snapshot) pt->handle.head = local_xchg(&buf->data_size, buf->nr_pages << PAGE_SHIFT); perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0)); } } static long pt_event_snapshot_aux(struct perf_event *event, struct perf_output_handle *handle, unsigned long size) { struct pt *pt = this_cpu_ptr(&pt_ctx); struct pt_buffer *buf = perf_get_aux(&pt->handle); unsigned long from = 0, to; long ret; if (WARN_ON_ONCE(!buf)) return 0; /* * Sampling is only allowed on snapshot events; * see pt_buffer_setup_aux(). */ if (WARN_ON_ONCE(!buf->snapshot)) return 0; /* * Here, handle_nmi tells us if the tracing is on */ if (READ_ONCE(pt->handle_nmi)) pt_config_stop(event); pt_read_offset(buf); pt_update_head(pt); to = local_read(&buf->data_size); if (to < size) from = buf->nr_pages << PAGE_SHIFT; from += to - size; ret = perf_output_copy_aux(&pt->handle, handle, from, to); /* * If the tracing was on when we turned up, restart it. * Compiler barrier not needed as we couldn't have been * preempted by anything that touches pt->handle_nmi. */ if (pt->handle_nmi) pt_config_start(event); return ret; } static void pt_event_del(struct perf_event *event, int mode) { pt_event_stop(event, PERF_EF_UPDATE); } static int pt_event_add(struct perf_event *event, int mode) { struct pt *pt = this_cpu_ptr(&pt_ctx); struct hw_perf_event *hwc = &event->hw; int ret = -EBUSY; if (pt->handle.event) goto fail; if (mode & PERF_EF_START) { pt_event_start(event, 0); ret = -EINVAL; if (hwc->state == PERF_HES_STOPPED) goto fail; } else { hwc->state = PERF_HES_STOPPED; } ret = 0; fail: return ret; } static void pt_event_read(struct perf_event *event) { } static void pt_event_destroy(struct perf_event *event) { pt_addr_filters_fini(event); x86_del_exclusive(x86_lbr_exclusive_pt); } static int pt_event_init(struct perf_event *event) { if (event->attr.type != pt_pmu.pmu.type) return -ENOENT; if (!pt_event_valid(event)) return -EINVAL; if (x86_add_exclusive(x86_lbr_exclusive_pt)) return -EBUSY; if (pt_addr_filters_init(event)) { x86_del_exclusive(x86_lbr_exclusive_pt); return -ENOMEM; } event->destroy = pt_event_destroy; return 0; } void cpu_emergency_stop_pt(void) { struct pt *pt = this_cpu_ptr(&pt_ctx); if (pt->handle.event) pt_event_stop(pt->handle.event, PERF_EF_UPDATE); } int is_intel_pt_event(struct perf_event *event) { return event->pmu == &pt_pmu.pmu; } static __init int pt_init(void) { int ret, cpu, prior_warn = 0; BUILD_BUG_ON(sizeof(struct topa) > PAGE_SIZE); if (!boot_cpu_has(X86_FEATURE_INTEL_PT)) return -ENODEV; cpus_read_lock(); for_each_online_cpu(cpu) { u64 ctl; ret = rdmsrl_safe_on_cpu(cpu, MSR_IA32_RTIT_CTL, &ctl); if (!ret && (ctl & RTIT_CTL_TRACEEN)) prior_warn++; } cpus_read_unlock(); if (prior_warn) { x86_add_exclusive(x86_lbr_exclusive_pt); pr_warn("PT is enabled at boot time, doing nothing\n"); return -EBUSY; } ret = pt_pmu_hw_init(); if (ret) return ret; if (!intel_pt_validate_hw_cap(PT_CAP_topa_output)) { pr_warn("ToPA output is not supported on this CPU\n"); return -ENODEV; } if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) pt_pmu.pmu.capabilities = PERF_PMU_CAP_AUX_NO_SG; pt_pmu.pmu.capabilities |= PERF_PMU_CAP_EXCLUSIVE | PERF_PMU_CAP_ITRACE; pt_pmu.pmu.attr_groups = pt_attr_groups; pt_pmu.pmu.task_ctx_nr = perf_sw_context; pt_pmu.pmu.event_init = pt_event_init; pt_pmu.pmu.add = pt_event_add; pt_pmu.pmu.del = pt_event_del; pt_pmu.pmu.start = pt_event_start; pt_pmu.pmu.stop = pt_event_stop; pt_pmu.pmu.snapshot_aux = pt_event_snapshot_aux; pt_pmu.pmu.read = pt_event_read; pt_pmu.pmu.setup_aux = pt_buffer_setup_aux; pt_pmu.pmu.free_aux = pt_buffer_free_aux; pt_pmu.pmu.addr_filters_sync = pt_event_addr_filters_sync; pt_pmu.pmu.addr_filters_validate = pt_event_addr_filters_validate; pt_pmu.pmu.nr_addr_filters = intel_pt_validate_hw_cap(PT_CAP_num_address_ranges); ret = perf_pmu_register(&pt_pmu.pmu, "intel_pt", -1); return ret; } arch_initcall(pt_init);
linux-master
arch/x86/events/intel/pt.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/perf_event.h> #include <linux/types.h> #include "../perf_event.h" /* * Not sure about some of these */ static const u64 p6_perfmon_event_map[] = { [PERF_COUNT_HW_CPU_CYCLES] = 0x0079, /* CPU_CLK_UNHALTED */ [PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0, /* INST_RETIRED */ [PERF_COUNT_HW_CACHE_REFERENCES] = 0x0f2e, /* L2_RQSTS:M:E:S:I */ [PERF_COUNT_HW_CACHE_MISSES] = 0x012e, /* L2_RQSTS:I */ [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c4, /* BR_INST_RETIRED */ [PERF_COUNT_HW_BRANCH_MISSES] = 0x00c5, /* BR_MISS_PRED_RETIRED */ [PERF_COUNT_HW_BUS_CYCLES] = 0x0062, /* BUS_DRDY_CLOCKS */ [PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = 0x00a2, /* RESOURCE_STALLS */ }; static const u64 __initconst p6_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0043, /* DATA_MEM_REFS */ [ C(RESULT_MISS) ] = 0x0045, /* DCU_LINES_IN */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0x0f29, /* L2_LD:M:E:S:I */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0080, /* IFU_IFETCH */ [ C(RESULT_MISS) ] = 0x0f28, /* L2_IFETCH:M:E:S:I */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0x0025, /* L2_M_LINES_INM */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0043, /* DATA_MEM_REFS */ [ C(RESULT_MISS) ] = 0, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0080, /* IFU_IFETCH */ [ C(RESULT_MISS) ] = 0x0085, /* ITLB_MISS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED */ [ C(RESULT_MISS) ] = 0x00c5, /* BR_MISS_PRED_RETIRED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, }; static u64 p6_pmu_event_map(int hw_event) { return p6_perfmon_event_map[hw_event]; } /* * Event setting that is specified not to count anything. * We use this to effectively disable a counter. * * L2_RQSTS with 0 MESI unit mask. */ #define P6_NOP_EVENT 0x0000002EULL static struct event_constraint p6_event_constraints[] = { INTEL_EVENT_CONSTRAINT(0xc1, 0x1), /* FLOPS */ INTEL_EVENT_CONSTRAINT(0x10, 0x1), /* FP_COMP_OPS_EXE */ INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */ INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */ INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */ INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */ EVENT_CONSTRAINT_END }; static void p6_pmu_disable_all(void) { u64 val; /* p6 only has one enable register */ rdmsrl(MSR_P6_EVNTSEL0, val); val &= ~ARCH_PERFMON_EVENTSEL_ENABLE; wrmsrl(MSR_P6_EVNTSEL0, val); } static void p6_pmu_enable_all(int added) { unsigned long val; /* p6 only has one enable register */ rdmsrl(MSR_P6_EVNTSEL0, val); val |= ARCH_PERFMON_EVENTSEL_ENABLE; wrmsrl(MSR_P6_EVNTSEL0, val); } static inline void p6_pmu_disable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 val = P6_NOP_EVENT; (void)wrmsrl_safe(hwc->config_base, val); } static void p6_pmu_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 val; val = hwc->config; /* * p6 only has a global event enable, set on PerfEvtSel0 * We "disable" events by programming P6_NOP_EVENT * and we rely on p6_pmu_enable_all() being called * to actually enable the events. */ (void)wrmsrl_safe(hwc->config_base, val); } PMU_FORMAT_ATTR(event, "config:0-7" ); PMU_FORMAT_ATTR(umask, "config:8-15" ); PMU_FORMAT_ATTR(edge, "config:18" ); PMU_FORMAT_ATTR(pc, "config:19" ); PMU_FORMAT_ATTR(inv, "config:23" ); PMU_FORMAT_ATTR(cmask, "config:24-31" ); static struct attribute *intel_p6_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_pc.attr, &format_attr_inv.attr, &format_attr_cmask.attr, NULL, }; static __initconst const struct x86_pmu p6_pmu = { .name = "p6", .handle_irq = x86_pmu_handle_irq, .disable_all = p6_pmu_disable_all, .enable_all = p6_pmu_enable_all, .enable = p6_pmu_enable_event, .disable = p6_pmu_disable_event, .hw_config = x86_pmu_hw_config, .schedule_events = x86_schedule_events, .eventsel = MSR_P6_EVNTSEL0, .perfctr = MSR_P6_PERFCTR0, .event_map = p6_pmu_event_map, .max_events = ARRAY_SIZE(p6_perfmon_event_map), .apic = 1, .max_period = (1ULL << 31) - 1, .version = 0, .num_counters = 2, /* * Events have 40 bits implemented. However they are designed such * that bits [32-39] are sign extensions of bit 31. As such the * effective width of a event for P6-like PMU is 32 bits only. * * See IA-32 Intel Architecture Software developer manual Vol 3B */ .cntval_bits = 32, .cntval_mask = (1ULL << 32) - 1, .get_event_constraints = x86_get_event_constraints, .event_constraints = p6_event_constraints, .format_attrs = intel_p6_formats_attr, .events_sysfs_show = intel_event_sysfs_show, }; static __init void p6_pmu_rdpmc_quirk(void) { if (boot_cpu_data.x86_stepping < 9) { /* * PPro erratum 26; fixed in stepping 9 and above. */ pr_warn("Userspace RDPMC support disabled due to a CPU erratum\n"); x86_pmu.attr_rdpmc_broken = 1; x86_pmu.attr_rdpmc = 0; } } __init int p6_pmu_init(void) { x86_pmu = p6_pmu; switch (boot_cpu_data.x86_model) { case 1: /* Pentium Pro */ x86_add_quirk(p6_pmu_rdpmc_quirk); break; case 3: /* Pentium II - Klamath */ case 5: /* Pentium II - Deschutes */ case 6: /* Pentium II - Mendocino */ break; case 7: /* Pentium III - Katmai */ case 8: /* Pentium III - Coppermine */ case 10: /* Pentium III Xeon */ case 11: /* Pentium III - Tualatin */ break; case 9: /* Pentium M - Banias */ case 13: /* Pentium M - Dothan */ break; default: pr_cont("unsupported p6 CPU model %d ", boot_cpu_data.x86_model); return -ENODEV; } memcpy(hw_cache_event_ids, p6_hw_cache_event_ids, sizeof(hw_cache_event_ids)); return 0; }
linux-master
arch/x86/events/intel/p6.c
/* SPDX-License-Identifier: GPL-2.0-only */ /* * Support Intel uncore PerfMon discovery mechanism. * Copyright(c) 2021 Intel Corporation. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include "uncore.h" #include "uncore_discovery.h" static struct rb_root discovery_tables = RB_ROOT; static int num_discovered_types[UNCORE_ACCESS_MAX]; static bool has_generic_discovery_table(void) { struct pci_dev *dev; int dvsec; dev = pci_get_device(PCI_VENDOR_ID_INTEL, UNCORE_DISCOVERY_TABLE_DEVICE, NULL); if (!dev) return false; /* A discovery table device has the unique capability ID. */ dvsec = pci_find_next_ext_capability(dev, 0, UNCORE_EXT_CAP_ID_DISCOVERY); pci_dev_put(dev); if (dvsec) return true; return false; } static int logical_die_id; static int get_device_die_id(struct pci_dev *dev) { int node = pcibus_to_node(dev->bus); /* * If the NUMA info is not available, assume that the logical die id is * continuous in the order in which the discovery table devices are * detected. */ if (node < 0) return logical_die_id++; return uncore_device_to_die(dev); } #define __node_2_type(cur) \ rb_entry((cur), struct intel_uncore_discovery_type, node) static inline int __type_cmp(const void *key, const struct rb_node *b) { struct intel_uncore_discovery_type *type_b = __node_2_type(b); const u16 *type_id = key; if (type_b->type > *type_id) return -1; else if (type_b->type < *type_id) return 1; return 0; } static inline struct intel_uncore_discovery_type * search_uncore_discovery_type(u16 type_id) { struct rb_node *node = rb_find(&type_id, &discovery_tables, __type_cmp); return (node) ? __node_2_type(node) : NULL; } static inline bool __type_less(struct rb_node *a, const struct rb_node *b) { return (__node_2_type(a)->type < __node_2_type(b)->type); } static struct intel_uncore_discovery_type * add_uncore_discovery_type(struct uncore_unit_discovery *unit) { struct intel_uncore_discovery_type *type; if (unit->access_type >= UNCORE_ACCESS_MAX) { pr_warn("Unsupported access type %d\n", unit->access_type); return NULL; } type = kzalloc(sizeof(struct intel_uncore_discovery_type), GFP_KERNEL); if (!type) return NULL; type->box_ctrl_die = kcalloc(__uncore_max_dies, sizeof(u64), GFP_KERNEL); if (!type->box_ctrl_die) goto free_type; type->access_type = unit->access_type; num_discovered_types[type->access_type]++; type->type = unit->box_type; rb_add(&type->node, &discovery_tables, __type_less); return type; free_type: kfree(type); return NULL; } static struct intel_uncore_discovery_type * get_uncore_discovery_type(struct uncore_unit_discovery *unit) { struct intel_uncore_discovery_type *type; type = search_uncore_discovery_type(unit->box_type); if (type) return type; return add_uncore_discovery_type(unit); } static void uncore_insert_box_info(struct uncore_unit_discovery *unit, int die, bool parsed) { struct intel_uncore_discovery_type *type; unsigned int *box_offset, *ids; int i; if (!unit->ctl || !unit->ctl_offset || !unit->ctr_offset) { pr_info("Invalid address is detected for uncore type %d box %d, " "Disable the uncore unit.\n", unit->box_type, unit->box_id); return; } if (parsed) { type = search_uncore_discovery_type(unit->box_type); if (!type) { pr_info("A spurious uncore type %d is detected, " "Disable the uncore type.\n", unit->box_type); return; } /* Store the first box of each die */ if (!type->box_ctrl_die[die]) type->box_ctrl_die[die] = unit->ctl; return; } type = get_uncore_discovery_type(unit); if (!type) return; box_offset = kcalloc(type->num_boxes + 1, sizeof(unsigned int), GFP_KERNEL); if (!box_offset) return; ids = kcalloc(type->num_boxes + 1, sizeof(unsigned int), GFP_KERNEL); if (!ids) goto free_box_offset; /* Store generic information for the first box */ if (!type->num_boxes) { type->box_ctrl = unit->ctl; type->box_ctrl_die[die] = unit->ctl; type->num_counters = unit->num_regs; type->counter_width = unit->bit_width; type->ctl_offset = unit->ctl_offset; type->ctr_offset = unit->ctr_offset; *ids = unit->box_id; goto end; } for (i = 0; i < type->num_boxes; i++) { ids[i] = type->ids[i]; box_offset[i] = type->box_offset[i]; if (unit->box_id == ids[i]) { pr_info("Duplicate uncore type %d box ID %d is detected, " "Drop the duplicate uncore unit.\n", unit->box_type, unit->box_id); goto free_ids; } } ids[i] = unit->box_id; box_offset[i] = unit->ctl - type->box_ctrl; kfree(type->ids); kfree(type->box_offset); end: type->ids = ids; type->box_offset = box_offset; type->num_boxes++; return; free_ids: kfree(ids); free_box_offset: kfree(box_offset); } static bool uncore_ignore_unit(struct uncore_unit_discovery *unit, int *ignore) { int i; if (!ignore) return false; for (i = 0; ignore[i] != UNCORE_IGNORE_END ; i++) { if (unit->box_type == ignore[i]) return true; } return false; } static int parse_discovery_table(struct pci_dev *dev, int die, u32 bar_offset, bool *parsed, int *ignore) { struct uncore_global_discovery global; struct uncore_unit_discovery unit; void __iomem *io_addr; resource_size_t addr; unsigned long size; u32 val; int i; pci_read_config_dword(dev, bar_offset, &val); if (val & ~PCI_BASE_ADDRESS_MEM_MASK & ~PCI_BASE_ADDRESS_MEM_TYPE_64) return -EINVAL; addr = (resource_size_t)(val & PCI_BASE_ADDRESS_MEM_MASK); #ifdef CONFIG_PHYS_ADDR_T_64BIT if ((val & PCI_BASE_ADDRESS_MEM_TYPE_MASK) == PCI_BASE_ADDRESS_MEM_TYPE_64) { u32 val2; pci_read_config_dword(dev, bar_offset + 4, &val2); addr |= ((resource_size_t)val2) << 32; } #endif size = UNCORE_DISCOVERY_GLOBAL_MAP_SIZE; io_addr = ioremap(addr, size); if (!io_addr) return -ENOMEM; /* Read Global Discovery State */ memcpy_fromio(&global, io_addr, sizeof(struct uncore_global_discovery)); if (uncore_discovery_invalid_unit(global)) { pr_info("Invalid Global Discovery State: 0x%llx 0x%llx 0x%llx\n", global.table1, global.ctl, global.table3); iounmap(io_addr); return -EINVAL; } iounmap(io_addr); size = (1 + global.max_units) * global.stride * 8; io_addr = ioremap(addr, size); if (!io_addr) return -ENOMEM; /* Parsing Unit Discovery State */ for (i = 0; i < global.max_units; i++) { memcpy_fromio(&unit, io_addr + (i + 1) * (global.stride * 8), sizeof(struct uncore_unit_discovery)); if (uncore_discovery_invalid_unit(unit)) continue; if (unit.access_type >= UNCORE_ACCESS_MAX) continue; if (uncore_ignore_unit(&unit, ignore)) continue; uncore_insert_box_info(&unit, die, *parsed); } *parsed = true; iounmap(io_addr); return 0; } bool intel_uncore_has_discovery_tables(int *ignore) { u32 device, val, entry_id, bar_offset; int die, dvsec = 0, ret = true; struct pci_dev *dev = NULL; bool parsed = false; if (has_generic_discovery_table()) device = UNCORE_DISCOVERY_TABLE_DEVICE; else device = PCI_ANY_ID; /* * Start a new search and iterates through the list of * the discovery table devices. */ while ((dev = pci_get_device(PCI_VENDOR_ID_INTEL, device, dev)) != NULL) { while ((dvsec = pci_find_next_ext_capability(dev, dvsec, UNCORE_EXT_CAP_ID_DISCOVERY))) { pci_read_config_dword(dev, dvsec + UNCORE_DISCOVERY_DVSEC_OFFSET, &val); entry_id = val & UNCORE_DISCOVERY_DVSEC_ID_MASK; if (entry_id != UNCORE_DISCOVERY_DVSEC_ID_PMON) continue; pci_read_config_dword(dev, dvsec + UNCORE_DISCOVERY_DVSEC2_OFFSET, &val); if (val & ~UNCORE_DISCOVERY_DVSEC2_BIR_MASK) { ret = false; goto err; } bar_offset = UNCORE_DISCOVERY_BIR_BASE + (val & UNCORE_DISCOVERY_DVSEC2_BIR_MASK) * UNCORE_DISCOVERY_BIR_STEP; die = get_device_die_id(dev); if (die < 0) continue; parse_discovery_table(dev, die, bar_offset, &parsed, ignore); } } /* None of the discovery tables are available */ if (!parsed) ret = false; err: pci_dev_put(dev); return ret; } void intel_uncore_clear_discovery_tables(void) { struct intel_uncore_discovery_type *type, *next; rbtree_postorder_for_each_entry_safe(type, next, &discovery_tables, node) { kfree(type->box_ctrl_die); kfree(type); } } DEFINE_UNCORE_FORMAT_ATTR(event, event, "config:0-7"); DEFINE_UNCORE_FORMAT_ATTR(umask, umask, "config:8-15"); DEFINE_UNCORE_FORMAT_ATTR(edge, edge, "config:18"); DEFINE_UNCORE_FORMAT_ATTR(inv, inv, "config:23"); DEFINE_UNCORE_FORMAT_ATTR(thresh, thresh, "config:24-31"); static struct attribute *generic_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh.attr, NULL, }; static const struct attribute_group generic_uncore_format_group = { .name = "format", .attrs = generic_uncore_formats_attr, }; void intel_generic_uncore_msr_init_box(struct intel_uncore_box *box) { wrmsrl(uncore_msr_box_ctl(box), GENERIC_PMON_BOX_CTL_INT); } void intel_generic_uncore_msr_disable_box(struct intel_uncore_box *box) { wrmsrl(uncore_msr_box_ctl(box), GENERIC_PMON_BOX_CTL_FRZ); } void intel_generic_uncore_msr_enable_box(struct intel_uncore_box *box) { wrmsrl(uncore_msr_box_ctl(box), 0); } static void intel_generic_uncore_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; wrmsrl(hwc->config_base, hwc->config); } static void intel_generic_uncore_msr_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; wrmsrl(hwc->config_base, 0); } static struct intel_uncore_ops generic_uncore_msr_ops = { .init_box = intel_generic_uncore_msr_init_box, .disable_box = intel_generic_uncore_msr_disable_box, .enable_box = intel_generic_uncore_msr_enable_box, .disable_event = intel_generic_uncore_msr_disable_event, .enable_event = intel_generic_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, }; void intel_generic_uncore_pci_init_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); __set_bit(UNCORE_BOX_FLAG_CTL_OFFS8, &box->flags); pci_write_config_dword(pdev, box_ctl, GENERIC_PMON_BOX_CTL_INT); } void intel_generic_uncore_pci_disable_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); pci_write_config_dword(pdev, box_ctl, GENERIC_PMON_BOX_CTL_FRZ); } void intel_generic_uncore_pci_enable_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); pci_write_config_dword(pdev, box_ctl, 0); } static void intel_generic_uncore_pci_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, hwc->config_base, hwc->config); } void intel_generic_uncore_pci_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, hwc->config_base, 0); } u64 intel_generic_uncore_pci_read_counter(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; u64 count = 0; pci_read_config_dword(pdev, hwc->event_base, (u32 *)&count); pci_read_config_dword(pdev, hwc->event_base + 4, (u32 *)&count + 1); return count; } static struct intel_uncore_ops generic_uncore_pci_ops = { .init_box = intel_generic_uncore_pci_init_box, .disable_box = intel_generic_uncore_pci_disable_box, .enable_box = intel_generic_uncore_pci_enable_box, .disable_event = intel_generic_uncore_pci_disable_event, .enable_event = intel_generic_uncore_pci_enable_event, .read_counter = intel_generic_uncore_pci_read_counter, }; #define UNCORE_GENERIC_MMIO_SIZE 0x4000 static u64 generic_uncore_mmio_box_ctl(struct intel_uncore_box *box) { struct intel_uncore_type *type = box->pmu->type; if (!type->box_ctls || !type->box_ctls[box->dieid] || !type->mmio_offsets) return 0; return type->box_ctls[box->dieid] + type->mmio_offsets[box->pmu->pmu_idx]; } void intel_generic_uncore_mmio_init_box(struct intel_uncore_box *box) { u64 box_ctl = generic_uncore_mmio_box_ctl(box); struct intel_uncore_type *type = box->pmu->type; resource_size_t addr; if (!box_ctl) { pr_warn("Uncore type %d box %d: Invalid box control address.\n", type->type_id, type->box_ids[box->pmu->pmu_idx]); return; } addr = box_ctl; box->io_addr = ioremap(addr, UNCORE_GENERIC_MMIO_SIZE); if (!box->io_addr) { pr_warn("Uncore type %d box %d: ioremap error for 0x%llx.\n", type->type_id, type->box_ids[box->pmu->pmu_idx], (unsigned long long)addr); return; } writel(GENERIC_PMON_BOX_CTL_INT, box->io_addr); } void intel_generic_uncore_mmio_disable_box(struct intel_uncore_box *box) { if (!box->io_addr) return; writel(GENERIC_PMON_BOX_CTL_FRZ, box->io_addr); } void intel_generic_uncore_mmio_enable_box(struct intel_uncore_box *box) { if (!box->io_addr) return; writel(0, box->io_addr); } void intel_generic_uncore_mmio_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (!box->io_addr) return; writel(hwc->config, box->io_addr + hwc->config_base); } void intel_generic_uncore_mmio_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (!box->io_addr) return; writel(0, box->io_addr + hwc->config_base); } static struct intel_uncore_ops generic_uncore_mmio_ops = { .init_box = intel_generic_uncore_mmio_init_box, .exit_box = uncore_mmio_exit_box, .disable_box = intel_generic_uncore_mmio_disable_box, .enable_box = intel_generic_uncore_mmio_enable_box, .disable_event = intel_generic_uncore_mmio_disable_event, .enable_event = intel_generic_uncore_mmio_enable_event, .read_counter = uncore_mmio_read_counter, }; static bool uncore_update_uncore_type(enum uncore_access_type type_id, struct intel_uncore_type *uncore, struct intel_uncore_discovery_type *type) { uncore->type_id = type->type; uncore->num_boxes = type->num_boxes; uncore->num_counters = type->num_counters; uncore->perf_ctr_bits = type->counter_width; uncore->box_ids = type->ids; switch (type_id) { case UNCORE_ACCESS_MSR: uncore->ops = &generic_uncore_msr_ops; uncore->perf_ctr = (unsigned int)type->box_ctrl + type->ctr_offset; uncore->event_ctl = (unsigned int)type->box_ctrl + type->ctl_offset; uncore->box_ctl = (unsigned int)type->box_ctrl; uncore->msr_offsets = type->box_offset; break; case UNCORE_ACCESS_PCI: uncore->ops = &generic_uncore_pci_ops; uncore->perf_ctr = (unsigned int)UNCORE_DISCOVERY_PCI_BOX_CTRL(type->box_ctrl) + type->ctr_offset; uncore->event_ctl = (unsigned int)UNCORE_DISCOVERY_PCI_BOX_CTRL(type->box_ctrl) + type->ctl_offset; uncore->box_ctl = (unsigned int)UNCORE_DISCOVERY_PCI_BOX_CTRL(type->box_ctrl); uncore->box_ctls = type->box_ctrl_die; uncore->pci_offsets = type->box_offset; break; case UNCORE_ACCESS_MMIO: uncore->ops = &generic_uncore_mmio_ops; uncore->perf_ctr = (unsigned int)type->ctr_offset; uncore->event_ctl = (unsigned int)type->ctl_offset; uncore->box_ctl = (unsigned int)type->box_ctrl; uncore->box_ctls = type->box_ctrl_die; uncore->mmio_offsets = type->box_offset; uncore->mmio_map_size = UNCORE_GENERIC_MMIO_SIZE; break; default: return false; } return true; } struct intel_uncore_type ** intel_uncore_generic_init_uncores(enum uncore_access_type type_id, int num_extra) { struct intel_uncore_discovery_type *type; struct intel_uncore_type **uncores; struct intel_uncore_type *uncore; struct rb_node *node; int i = 0; uncores = kcalloc(num_discovered_types[type_id] + num_extra + 1, sizeof(struct intel_uncore_type *), GFP_KERNEL); if (!uncores) return empty_uncore; for (node = rb_first(&discovery_tables); node; node = rb_next(node)) { type = rb_entry(node, struct intel_uncore_discovery_type, node); if (type->access_type != type_id) continue; uncore = kzalloc(sizeof(struct intel_uncore_type), GFP_KERNEL); if (!uncore) break; uncore->event_mask = GENERIC_PMON_RAW_EVENT_MASK; uncore->format_group = &generic_uncore_format_group; if (!uncore_update_uncore_type(type_id, uncore, type)) { kfree(uncore); continue; } uncores[i++] = uncore; } return uncores; } void intel_uncore_generic_uncore_cpu_init(void) { uncore_msr_uncores = intel_uncore_generic_init_uncores(UNCORE_ACCESS_MSR, 0); } int intel_uncore_generic_uncore_pci_init(void) { uncore_pci_uncores = intel_uncore_generic_init_uncores(UNCORE_ACCESS_PCI, 0); return 0; } void intel_uncore_generic_uncore_mmio_init(void) { uncore_mmio_uncores = intel_uncore_generic_init_uncores(UNCORE_ACCESS_MMIO, 0); }
linux-master
arch/x86/events/intel/uncore_discovery.c
// SPDX-License-Identifier: GPL-2.0-only /* * Per core/cpu state * * Used to coordinate shared registers between HT threads or * among events on a single PMU. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/stddef.h> #include <linux/types.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/export.h> #include <linux/nmi.h> #include <linux/kvm_host.h> #include <asm/cpufeature.h> #include <asm/hardirq.h> #include <asm/intel-family.h> #include <asm/intel_pt.h> #include <asm/apic.h> #include <asm/cpu_device_id.h> #include "../perf_event.h" /* * Intel PerfMon, used on Core and later. */ static u64 intel_perfmon_event_map[PERF_COUNT_HW_MAX] __read_mostly = { [PERF_COUNT_HW_CPU_CYCLES] = 0x003c, [PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0, [PERF_COUNT_HW_CACHE_REFERENCES] = 0x4f2e, [PERF_COUNT_HW_CACHE_MISSES] = 0x412e, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c4, [PERF_COUNT_HW_BRANCH_MISSES] = 0x00c5, [PERF_COUNT_HW_BUS_CYCLES] = 0x013c, [PERF_COUNT_HW_REF_CPU_CYCLES] = 0x0300, /* pseudo-encoding */ }; static struct event_constraint intel_core_event_constraints[] __read_mostly = { INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */ INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */ INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */ INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */ INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */ INTEL_EVENT_CONSTRAINT(0xc1, 0x1), /* FP_COMP_INSTR_RET */ EVENT_CONSTRAINT_END }; static struct event_constraint intel_core2_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_EVENT_CONSTRAINT(0x10, 0x1), /* FP_COMP_OPS_EXE */ INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */ INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */ INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */ INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */ INTEL_EVENT_CONSTRAINT(0x18, 0x1), /* IDLE_DURING_DIV */ INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */ INTEL_EVENT_CONSTRAINT(0xa1, 0x1), /* RS_UOPS_DISPATCH_CYCLES */ INTEL_EVENT_CONSTRAINT(0xc9, 0x1), /* ITLB_MISS_RETIRED (T30-9) */ INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED */ EVENT_CONSTRAINT_END }; static struct event_constraint intel_nehalem_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_EVENT_CONSTRAINT(0x40, 0x3), /* L1D_CACHE_LD */ INTEL_EVENT_CONSTRAINT(0x41, 0x3), /* L1D_CACHE_ST */ INTEL_EVENT_CONSTRAINT(0x42, 0x3), /* L1D_CACHE_LOCK */ INTEL_EVENT_CONSTRAINT(0x43, 0x3), /* L1D_ALL_REF */ INTEL_EVENT_CONSTRAINT(0x48, 0x3), /* L1D_PEND_MISS */ INTEL_EVENT_CONSTRAINT(0x4e, 0x3), /* L1D_PREFETCH */ INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */ INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */ EVENT_CONSTRAINT_END }; static struct extra_reg intel_nehalem_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x100b), EVENT_EXTRA_END }; static struct event_constraint intel_westmere_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */ INTEL_EVENT_CONSTRAINT(0x60, 0x1), /* OFFCORE_REQUESTS_OUTSTANDING */ INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */ INTEL_EVENT_CONSTRAINT(0xb3, 0x1), /* SNOOPQ_REQUEST_OUTSTANDING */ EVENT_CONSTRAINT_END }; static struct event_constraint intel_snb_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_NO_DISPATCH */ INTEL_UEVENT_CONSTRAINT(0x05a3, 0xf), /* CYCLE_ACTIVITY.STALLS_L2_PENDING */ INTEL_UEVENT_CONSTRAINT(0x02a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */ INTEL_UEVENT_CONSTRAINT(0x06a3, 0x4), /* CYCLE_ACTIVITY.STALLS_L1D_PENDING */ INTEL_EVENT_CONSTRAINT(0x48, 0x4), /* L1D_PEND_MISS.PENDING */ INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */ INTEL_EVENT_CONSTRAINT(0xcd, 0x8), /* MEM_TRANS_RETIRED.LOAD_LATENCY */ INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_NO_DISPATCH */ INTEL_UEVENT_CONSTRAINT(0x02a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */ /* * When HT is off these events can only run on the bottom 4 counters * When HT is on, they are impacted by the HT bug and require EXCL access */ INTEL_EXCLEVT_CONSTRAINT(0xd0, 0xf), /* MEM_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd3, 0xf), /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */ EVENT_CONSTRAINT_END }; static struct event_constraint intel_ivb_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_UEVENT_CONSTRAINT(0x0148, 0x4), /* L1D_PEND_MISS.PENDING */ INTEL_UEVENT_CONSTRAINT(0x0279, 0xf), /* IDQ.EMPTY */ INTEL_UEVENT_CONSTRAINT(0x019c, 0xf), /* IDQ_UOPS_NOT_DELIVERED.CORE */ INTEL_UEVENT_CONSTRAINT(0x02a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_LDM_PENDING */ INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_NO_EXECUTE */ INTEL_UEVENT_CONSTRAINT(0x05a3, 0xf), /* CYCLE_ACTIVITY.STALLS_L2_PENDING */ INTEL_UEVENT_CONSTRAINT(0x06a3, 0xf), /* CYCLE_ACTIVITY.STALLS_LDM_PENDING */ INTEL_UEVENT_CONSTRAINT(0x08a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */ INTEL_UEVENT_CONSTRAINT(0x0ca3, 0x4), /* CYCLE_ACTIVITY.STALLS_L1D_PENDING */ INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */ /* * When HT is off these events can only run on the bottom 4 counters * When HT is on, they are impacted by the HT bug and require EXCL access */ INTEL_EXCLEVT_CONSTRAINT(0xd0, 0xf), /* MEM_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd3, 0xf), /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */ EVENT_CONSTRAINT_END }; static struct extra_reg intel_westmere_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0), INTEL_UEVENT_EXTRA_REG(0x01bb, MSR_OFFCORE_RSP_1, 0xffff, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x100b), EVENT_EXTRA_END }; static struct event_constraint intel_v1_event_constraints[] __read_mostly = { EVENT_CONSTRAINT_END }; static struct event_constraint intel_gen_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ EVENT_CONSTRAINT_END }; static struct event_constraint intel_v5_gen_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ FIXED_EVENT_CONSTRAINT(0x0400, 3), /* SLOTS */ FIXED_EVENT_CONSTRAINT(0x0500, 4), FIXED_EVENT_CONSTRAINT(0x0600, 5), FIXED_EVENT_CONSTRAINT(0x0700, 6), FIXED_EVENT_CONSTRAINT(0x0800, 7), FIXED_EVENT_CONSTRAINT(0x0900, 8), FIXED_EVENT_CONSTRAINT(0x0a00, 9), FIXED_EVENT_CONSTRAINT(0x0b00, 10), FIXED_EVENT_CONSTRAINT(0x0c00, 11), FIXED_EVENT_CONSTRAINT(0x0d00, 12), FIXED_EVENT_CONSTRAINT(0x0e00, 13), FIXED_EVENT_CONSTRAINT(0x0f00, 14), FIXED_EVENT_CONSTRAINT(0x1000, 15), EVENT_CONSTRAINT_END }; static struct event_constraint intel_slm_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* pseudo CPU_CLK_UNHALTED.REF */ EVENT_CONSTRAINT_END }; static struct event_constraint intel_skl_event_constraints[] = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_UEVENT_CONSTRAINT(0x1c0, 0x2), /* INST_RETIRED.PREC_DIST */ /* * when HT is off, these can only run on the bottom 4 counters */ INTEL_EVENT_CONSTRAINT(0xd0, 0xf), /* MEM_INST_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_L3_HIT_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xcd, 0xf), /* MEM_TRANS_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xc6, 0xf), /* FRONTEND_RETIRED.* */ EVENT_CONSTRAINT_END }; static struct extra_reg intel_knl_extra_regs[] __read_mostly = { INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x799ffbb6e7ull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x02b7, MSR_OFFCORE_RSP_1, 0x399ffbffe7ull, RSP_1), EVENT_EXTRA_END }; static struct extra_reg intel_snb_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x3f807f8fffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x01bb, MSR_OFFCORE_RSP_1, 0x3f807f8fffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x01cd), EVENT_EXTRA_END }; static struct extra_reg intel_snbep_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x3fffff8fffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x01bb, MSR_OFFCORE_RSP_1, 0x3fffff8fffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x01cd), EVENT_EXTRA_END }; static struct extra_reg intel_skl_extra_regs[] __read_mostly = { INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x3fffff8fffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x01bb, MSR_OFFCORE_RSP_1, 0x3fffff8fffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x01cd), /* * Note the low 8 bits eventsel code is not a continuous field, containing * some #GPing bits. These are masked out. */ INTEL_UEVENT_EXTRA_REG(0x01c6, MSR_PEBS_FRONTEND, 0x7fff17, FE), EVENT_EXTRA_END }; static struct event_constraint intel_icl_event_constraints[] = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x01c0, 0), /* old INST_RETIRED.PREC_DIST */ FIXED_EVENT_CONSTRAINT(0x0100, 0), /* INST_RETIRED.PREC_DIST */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ FIXED_EVENT_CONSTRAINT(0x0400, 3), /* SLOTS */ METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_RETIRING, 0), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_BAD_SPEC, 1), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_FE_BOUND, 2), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_BE_BOUND, 3), INTEL_EVENT_CONSTRAINT_RANGE(0x03, 0x0a, 0xf), INTEL_EVENT_CONSTRAINT_RANGE(0x1f, 0x28, 0xf), INTEL_EVENT_CONSTRAINT(0x32, 0xf), /* SW_PREFETCH_ACCESS.* */ INTEL_EVENT_CONSTRAINT_RANGE(0x48, 0x56, 0xf), INTEL_EVENT_CONSTRAINT_RANGE(0x60, 0x8b, 0xf), INTEL_UEVENT_CONSTRAINT(0x04a3, 0xff), /* CYCLE_ACTIVITY.STALLS_TOTAL */ INTEL_UEVENT_CONSTRAINT(0x10a3, 0xff), /* CYCLE_ACTIVITY.CYCLES_MEM_ANY */ INTEL_UEVENT_CONSTRAINT(0x14a3, 0xff), /* CYCLE_ACTIVITY.STALLS_MEM_ANY */ INTEL_EVENT_CONSTRAINT(0xa3, 0xf), /* CYCLE_ACTIVITY.* */ INTEL_EVENT_CONSTRAINT_RANGE(0xa8, 0xb0, 0xf), INTEL_EVENT_CONSTRAINT_RANGE(0xb7, 0xbd, 0xf), INTEL_EVENT_CONSTRAINT_RANGE(0xd0, 0xe6, 0xf), INTEL_EVENT_CONSTRAINT(0xef, 0xf), INTEL_EVENT_CONSTRAINT_RANGE(0xf0, 0xf4, 0xf), EVENT_CONSTRAINT_END }; static struct extra_reg intel_icl_extra_regs[] __read_mostly = { INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x3fffffbfffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x01bb, MSR_OFFCORE_RSP_1, 0x3fffffbfffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x01cd), INTEL_UEVENT_EXTRA_REG(0x01c6, MSR_PEBS_FRONTEND, 0x7fff17, FE), EVENT_EXTRA_END }; static struct extra_reg intel_spr_extra_regs[] __read_mostly = { INTEL_UEVENT_EXTRA_REG(0x012a, MSR_OFFCORE_RSP_0, 0x3fffffffffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x012b, MSR_OFFCORE_RSP_1, 0x3fffffffffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x01cd), INTEL_UEVENT_EXTRA_REG(0x01c6, MSR_PEBS_FRONTEND, 0x7fff1f, FE), INTEL_UEVENT_EXTRA_REG(0x40ad, MSR_PEBS_FRONTEND, 0x7, FE), INTEL_UEVENT_EXTRA_REG(0x04c2, MSR_PEBS_FRONTEND, 0x8, FE), EVENT_EXTRA_END }; static struct event_constraint intel_spr_event_constraints[] = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x0100, 0), /* INST_RETIRED.PREC_DIST */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ FIXED_EVENT_CONSTRAINT(0x0400, 3), /* SLOTS */ METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_RETIRING, 0), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_BAD_SPEC, 1), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_FE_BOUND, 2), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_BE_BOUND, 3), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_HEAVY_OPS, 4), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_BR_MISPREDICT, 5), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_FETCH_LAT, 6), METRIC_EVENT_CONSTRAINT(INTEL_TD_METRIC_MEM_BOUND, 7), INTEL_EVENT_CONSTRAINT(0x2e, 0xff), INTEL_EVENT_CONSTRAINT(0x3c, 0xff), /* * Generally event codes < 0x90 are restricted to counters 0-3. * The 0x2E and 0x3C are exception, which has no restriction. */ INTEL_EVENT_CONSTRAINT_RANGE(0x01, 0x8f, 0xf), INTEL_UEVENT_CONSTRAINT(0x01a3, 0xf), INTEL_UEVENT_CONSTRAINT(0x02a3, 0xf), INTEL_UEVENT_CONSTRAINT(0x08a3, 0xf), INTEL_UEVENT_CONSTRAINT(0x04a4, 0x1), INTEL_UEVENT_CONSTRAINT(0x08a4, 0x1), INTEL_UEVENT_CONSTRAINT(0x02cd, 0x1), INTEL_EVENT_CONSTRAINT(0xce, 0x1), INTEL_EVENT_CONSTRAINT_RANGE(0xd0, 0xdf, 0xf), /* * Generally event codes >= 0x90 are likely to have no restrictions. * The exception are defined as above. */ INTEL_EVENT_CONSTRAINT_RANGE(0x90, 0xfe, 0xff), EVENT_CONSTRAINT_END }; static struct extra_reg intel_gnr_extra_regs[] __read_mostly = { INTEL_UEVENT_EXTRA_REG(0x012a, MSR_OFFCORE_RSP_0, 0x3fffffffffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x012b, MSR_OFFCORE_RSP_1, 0x3fffffffffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x01cd), INTEL_UEVENT_EXTRA_REG(0x02c6, MSR_PEBS_FRONTEND, 0x9, FE), INTEL_UEVENT_EXTRA_REG(0x03c6, MSR_PEBS_FRONTEND, 0x7fff1f, FE), INTEL_UEVENT_EXTRA_REG(0x40ad, MSR_PEBS_FRONTEND, 0x7, FE), INTEL_UEVENT_EXTRA_REG(0x04c2, MSR_PEBS_FRONTEND, 0x8, FE), EVENT_EXTRA_END }; EVENT_ATTR_STR(mem-loads, mem_ld_nhm, "event=0x0b,umask=0x10,ldlat=3"); EVENT_ATTR_STR(mem-loads, mem_ld_snb, "event=0xcd,umask=0x1,ldlat=3"); EVENT_ATTR_STR(mem-stores, mem_st_snb, "event=0xcd,umask=0x2"); static struct attribute *nhm_mem_events_attrs[] = { EVENT_PTR(mem_ld_nhm), NULL, }; /* * topdown events for Intel Core CPUs. * * The events are all in slots, which is a free slot in a 4 wide * pipeline. Some events are already reported in slots, for cycle * events we multiply by the pipeline width (4). * * With Hyper Threading on, topdown metrics are either summed or averaged * between the threads of a core: (count_t0 + count_t1). * * For the average case the metric is always scaled to pipeline width, * so we use factor 2 ((count_t0 + count_t1) / 2 * 4) */ EVENT_ATTR_STR_HT(topdown-total-slots, td_total_slots, "event=0x3c,umask=0x0", /* cpu_clk_unhalted.thread */ "event=0x3c,umask=0x0,any=1"); /* cpu_clk_unhalted.thread_any */ EVENT_ATTR_STR_HT(topdown-total-slots.scale, td_total_slots_scale, "4", "2"); EVENT_ATTR_STR(topdown-slots-issued, td_slots_issued, "event=0xe,umask=0x1"); /* uops_issued.any */ EVENT_ATTR_STR(topdown-slots-retired, td_slots_retired, "event=0xc2,umask=0x2"); /* uops_retired.retire_slots */ EVENT_ATTR_STR(topdown-fetch-bubbles, td_fetch_bubbles, "event=0x9c,umask=0x1"); /* idq_uops_not_delivered_core */ EVENT_ATTR_STR_HT(topdown-recovery-bubbles, td_recovery_bubbles, "event=0xd,umask=0x3,cmask=1", /* int_misc.recovery_cycles */ "event=0xd,umask=0x3,cmask=1,any=1"); /* int_misc.recovery_cycles_any */ EVENT_ATTR_STR_HT(topdown-recovery-bubbles.scale, td_recovery_bubbles_scale, "4", "2"); EVENT_ATTR_STR(slots, slots, "event=0x00,umask=0x4"); EVENT_ATTR_STR(topdown-retiring, td_retiring, "event=0x00,umask=0x80"); EVENT_ATTR_STR(topdown-bad-spec, td_bad_spec, "event=0x00,umask=0x81"); EVENT_ATTR_STR(topdown-fe-bound, td_fe_bound, "event=0x00,umask=0x82"); EVENT_ATTR_STR(topdown-be-bound, td_be_bound, "event=0x00,umask=0x83"); EVENT_ATTR_STR(topdown-heavy-ops, td_heavy_ops, "event=0x00,umask=0x84"); EVENT_ATTR_STR(topdown-br-mispredict, td_br_mispredict, "event=0x00,umask=0x85"); EVENT_ATTR_STR(topdown-fetch-lat, td_fetch_lat, "event=0x00,umask=0x86"); EVENT_ATTR_STR(topdown-mem-bound, td_mem_bound, "event=0x00,umask=0x87"); static struct attribute *snb_events_attrs[] = { EVENT_PTR(td_slots_issued), EVENT_PTR(td_slots_retired), EVENT_PTR(td_fetch_bubbles), EVENT_PTR(td_total_slots), EVENT_PTR(td_total_slots_scale), EVENT_PTR(td_recovery_bubbles), EVENT_PTR(td_recovery_bubbles_scale), NULL, }; static struct attribute *snb_mem_events_attrs[] = { EVENT_PTR(mem_ld_snb), EVENT_PTR(mem_st_snb), NULL, }; static struct event_constraint intel_hsw_event_constraints[] = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_UEVENT_CONSTRAINT(0x148, 0x4), /* L1D_PEND_MISS.PENDING */ INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */ INTEL_EVENT_CONSTRAINT(0xcd, 0x8), /* MEM_TRANS_RETIRED.LOAD_LATENCY */ /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */ INTEL_UEVENT_CONSTRAINT(0x08a3, 0x4), /* CYCLE_ACTIVITY.STALLS_L1D_PENDING */ INTEL_UEVENT_CONSTRAINT(0x0ca3, 0x4), /* CYCLE_ACTIVITY.CYCLES_NO_EXECUTE */ INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* * When HT is off these events can only run on the bottom 4 counters * When HT is on, they are impacted by the HT bug and require EXCL access */ INTEL_EXCLEVT_CONSTRAINT(0xd0, 0xf), /* MEM_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd3, 0xf), /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */ EVENT_CONSTRAINT_END }; static struct event_constraint intel_bdw_event_constraints[] = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */ FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */ FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */ INTEL_UEVENT_CONSTRAINT(0x148, 0x4), /* L1D_PEND_MISS.PENDING */ INTEL_UBIT_EVENT_CONSTRAINT(0x8a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_MISS */ /* * when HT is off, these can only run on the bottom 4 counters */ INTEL_EVENT_CONSTRAINT(0xd0, 0xf), /* MEM_INST_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_L3_HIT_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xcd, 0xf), /* MEM_TRANS_RETIRED.* */ EVENT_CONSTRAINT_END }; static u64 intel_pmu_event_map(int hw_event) { return intel_perfmon_event_map[hw_event]; } static __initconst const u64 spr_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x81d0, [ C(RESULT_MISS) ] = 0xe124, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x82d0, }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_MISS) ] = 0xe424, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x12a, [ C(RESULT_MISS) ] = 0x12a, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x12a, [ C(RESULT_MISS) ] = 0x12a, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x81d0, [ C(RESULT_MISS) ] = 0xe12, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x82d0, [ C(RESULT_MISS) ] = 0xe13, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = 0xe11, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x4c4, [ C(RESULT_MISS) ] = 0x4c5, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x12a, [ C(RESULT_MISS) ] = 0x12a, }, }, }; static __initconst const u64 spr_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x10001, [ C(RESULT_MISS) ] = 0x3fbfc00001, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x3f3ffc0002, [ C(RESULT_MISS) ] = 0x3f3fc00002, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x10c000001, [ C(RESULT_MISS) ] = 0x3fb3000001, }, }, }; /* * Notes on the events: * - data reads do not include code reads (comparable to earlier tables) * - data counts include speculative execution (except L1 write, dtlb, bpu) * - remote node access includes remote memory, remote cache, remote mmio. * - prefetches are not included in the counts. * - icache miss does not include decoded icache */ #define SKL_DEMAND_DATA_RD BIT_ULL(0) #define SKL_DEMAND_RFO BIT_ULL(1) #define SKL_ANY_RESPONSE BIT_ULL(16) #define SKL_SUPPLIER_NONE BIT_ULL(17) #define SKL_L3_MISS_LOCAL_DRAM BIT_ULL(26) #define SKL_L3_MISS_REMOTE_HOP0_DRAM BIT_ULL(27) #define SKL_L3_MISS_REMOTE_HOP1_DRAM BIT_ULL(28) #define SKL_L3_MISS_REMOTE_HOP2P_DRAM BIT_ULL(29) #define SKL_L3_MISS (SKL_L3_MISS_LOCAL_DRAM| \ SKL_L3_MISS_REMOTE_HOP0_DRAM| \ SKL_L3_MISS_REMOTE_HOP1_DRAM| \ SKL_L3_MISS_REMOTE_HOP2P_DRAM) #define SKL_SPL_HIT BIT_ULL(30) #define SKL_SNOOP_NONE BIT_ULL(31) #define SKL_SNOOP_NOT_NEEDED BIT_ULL(32) #define SKL_SNOOP_MISS BIT_ULL(33) #define SKL_SNOOP_HIT_NO_FWD BIT_ULL(34) #define SKL_SNOOP_HIT_WITH_FWD BIT_ULL(35) #define SKL_SNOOP_HITM BIT_ULL(36) #define SKL_SNOOP_NON_DRAM BIT_ULL(37) #define SKL_ANY_SNOOP (SKL_SPL_HIT|SKL_SNOOP_NONE| \ SKL_SNOOP_NOT_NEEDED|SKL_SNOOP_MISS| \ SKL_SNOOP_HIT_NO_FWD|SKL_SNOOP_HIT_WITH_FWD| \ SKL_SNOOP_HITM|SKL_SNOOP_NON_DRAM) #define SKL_DEMAND_READ SKL_DEMAND_DATA_RD #define SKL_SNOOP_DRAM (SKL_SNOOP_NONE| \ SKL_SNOOP_NOT_NEEDED|SKL_SNOOP_MISS| \ SKL_SNOOP_HIT_NO_FWD|SKL_SNOOP_HIT_WITH_FWD| \ SKL_SNOOP_HITM|SKL_SPL_HIT) #define SKL_DEMAND_WRITE SKL_DEMAND_RFO #define SKL_LLC_ACCESS SKL_ANY_RESPONSE #define SKL_L3_MISS_REMOTE (SKL_L3_MISS_REMOTE_HOP0_DRAM| \ SKL_L3_MISS_REMOTE_HOP1_DRAM| \ SKL_L3_MISS_REMOTE_HOP2P_DRAM) static __initconst const u64 skl_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_INST_RETIRED.ALL_LOADS */ [ C(RESULT_MISS) ] = 0x151, /* L1D.REPLACEMENT */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_INST_RETIRED.ALL_STORES */ [ C(RESULT_MISS) ] = 0x0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x283, /* ICACHE_64B.MISS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_INST_RETIRED.ALL_LOADS */ [ C(RESULT_MISS) ] = 0xe08, /* DTLB_LOAD_MISSES.WALK_COMPLETED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_INST_RETIRED.ALL_STORES */ [ C(RESULT_MISS) ] = 0xe49, /* DTLB_STORE_MISSES.WALK_COMPLETED */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x2085, /* ITLB_MISSES.STLB_HIT */ [ C(RESULT_MISS) ] = 0xe85, /* ITLB_MISSES.WALK_COMPLETED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0xc4, /* BR_INST_RETIRED.ALL_BRANCHES */ [ C(RESULT_MISS) ] = 0xc5, /* BR_MISP_RETIRED.ALL_BRANCHES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, }; static __initconst const u64 skl_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = SKL_DEMAND_READ| SKL_LLC_ACCESS|SKL_ANY_SNOOP, [ C(RESULT_MISS) ] = SKL_DEMAND_READ| SKL_L3_MISS|SKL_ANY_SNOOP| SKL_SUPPLIER_NONE, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = SKL_DEMAND_WRITE| SKL_LLC_ACCESS|SKL_ANY_SNOOP, [ C(RESULT_MISS) ] = SKL_DEMAND_WRITE| SKL_L3_MISS|SKL_ANY_SNOOP| SKL_SUPPLIER_NONE, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = SKL_DEMAND_READ| SKL_L3_MISS_LOCAL_DRAM|SKL_SNOOP_DRAM, [ C(RESULT_MISS) ] = SKL_DEMAND_READ| SKL_L3_MISS_REMOTE|SKL_SNOOP_DRAM, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = SKL_DEMAND_WRITE| SKL_L3_MISS_LOCAL_DRAM|SKL_SNOOP_DRAM, [ C(RESULT_MISS) ] = SKL_DEMAND_WRITE| SKL_L3_MISS_REMOTE|SKL_SNOOP_DRAM, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, }; #define SNB_DMND_DATA_RD (1ULL << 0) #define SNB_DMND_RFO (1ULL << 1) #define SNB_DMND_IFETCH (1ULL << 2) #define SNB_DMND_WB (1ULL << 3) #define SNB_PF_DATA_RD (1ULL << 4) #define SNB_PF_RFO (1ULL << 5) #define SNB_PF_IFETCH (1ULL << 6) #define SNB_LLC_DATA_RD (1ULL << 7) #define SNB_LLC_RFO (1ULL << 8) #define SNB_LLC_IFETCH (1ULL << 9) #define SNB_BUS_LOCKS (1ULL << 10) #define SNB_STRM_ST (1ULL << 11) #define SNB_OTHER (1ULL << 15) #define SNB_RESP_ANY (1ULL << 16) #define SNB_NO_SUPP (1ULL << 17) #define SNB_LLC_HITM (1ULL << 18) #define SNB_LLC_HITE (1ULL << 19) #define SNB_LLC_HITS (1ULL << 20) #define SNB_LLC_HITF (1ULL << 21) #define SNB_LOCAL (1ULL << 22) #define SNB_REMOTE (0xffULL << 23) #define SNB_SNP_NONE (1ULL << 31) #define SNB_SNP_NOT_NEEDED (1ULL << 32) #define SNB_SNP_MISS (1ULL << 33) #define SNB_NO_FWD (1ULL << 34) #define SNB_SNP_FWD (1ULL << 35) #define SNB_HITM (1ULL << 36) #define SNB_NON_DRAM (1ULL << 37) #define SNB_DMND_READ (SNB_DMND_DATA_RD|SNB_LLC_DATA_RD) #define SNB_DMND_WRITE (SNB_DMND_RFO|SNB_LLC_RFO) #define SNB_DMND_PREFETCH (SNB_PF_DATA_RD|SNB_PF_RFO) #define SNB_SNP_ANY (SNB_SNP_NONE|SNB_SNP_NOT_NEEDED| \ SNB_SNP_MISS|SNB_NO_FWD|SNB_SNP_FWD| \ SNB_HITM) #define SNB_DRAM_ANY (SNB_LOCAL|SNB_REMOTE|SNB_SNP_ANY) #define SNB_DRAM_REMOTE (SNB_REMOTE|SNB_SNP_ANY) #define SNB_L3_ACCESS SNB_RESP_ANY #define SNB_L3_MISS (SNB_DRAM_ANY|SNB_NON_DRAM) static __initconst const u64 snb_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = SNB_DMND_READ|SNB_L3_ACCESS, [ C(RESULT_MISS) ] = SNB_DMND_READ|SNB_L3_MISS, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = SNB_DMND_WRITE|SNB_L3_ACCESS, [ C(RESULT_MISS) ] = SNB_DMND_WRITE|SNB_L3_MISS, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = SNB_DMND_PREFETCH|SNB_L3_ACCESS, [ C(RESULT_MISS) ] = SNB_DMND_PREFETCH|SNB_L3_MISS, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = SNB_DMND_READ|SNB_DRAM_ANY, [ C(RESULT_MISS) ] = SNB_DMND_READ|SNB_DRAM_REMOTE, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = SNB_DMND_WRITE|SNB_DRAM_ANY, [ C(RESULT_MISS) ] = SNB_DMND_WRITE|SNB_DRAM_REMOTE, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = SNB_DMND_PREFETCH|SNB_DRAM_ANY, [ C(RESULT_MISS) ] = SNB_DMND_PREFETCH|SNB_DRAM_REMOTE, }, }, }; static __initconst const u64 snb_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0xf1d0, /* MEM_UOP_RETIRED.LOADS */ [ C(RESULT_MISS) ] = 0x0151, /* L1D.REPLACEMENT */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0xf2d0, /* MEM_UOP_RETIRED.STORES */ [ C(RESULT_MISS) ] = 0x0851, /* L1D.ALL_M_REPLACEMENT */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x024e, /* HW_PRE_REQ.DL1_MISS */ }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0280, /* ICACHE.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { /* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_WRITE) ] = { /* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_PREFETCH) ] = { /* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_UOP_RETIRED.ALL_LOADS */ [ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.CAUSES_A_WALK */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_UOP_RETIRED.ALL_STORES */ [ C(RESULT_MISS) ] = 0x0149, /* DTLB_STORE_MISSES.MISS_CAUSES_A_WALK */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x1085, /* ITLB_MISSES.STLB_HIT */ [ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.CAUSES_A_WALK */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */ [ C(RESULT_MISS) ] = 0x00c5, /* BR_MISP_RETIRED.ALL_BRANCHES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, }, }; /* * Notes on the events: * - data reads do not include code reads (comparable to earlier tables) * - data counts include speculative execution (except L1 write, dtlb, bpu) * - remote node access includes remote memory, remote cache, remote mmio. * - prefetches are not included in the counts because they are not * reliably counted. */ #define HSW_DEMAND_DATA_RD BIT_ULL(0) #define HSW_DEMAND_RFO BIT_ULL(1) #define HSW_ANY_RESPONSE BIT_ULL(16) #define HSW_SUPPLIER_NONE BIT_ULL(17) #define HSW_L3_MISS_LOCAL_DRAM BIT_ULL(22) #define HSW_L3_MISS_REMOTE_HOP0 BIT_ULL(27) #define HSW_L3_MISS_REMOTE_HOP1 BIT_ULL(28) #define HSW_L3_MISS_REMOTE_HOP2P BIT_ULL(29) #define HSW_L3_MISS (HSW_L3_MISS_LOCAL_DRAM| \ HSW_L3_MISS_REMOTE_HOP0|HSW_L3_MISS_REMOTE_HOP1| \ HSW_L3_MISS_REMOTE_HOP2P) #define HSW_SNOOP_NONE BIT_ULL(31) #define HSW_SNOOP_NOT_NEEDED BIT_ULL(32) #define HSW_SNOOP_MISS BIT_ULL(33) #define HSW_SNOOP_HIT_NO_FWD BIT_ULL(34) #define HSW_SNOOP_HIT_WITH_FWD BIT_ULL(35) #define HSW_SNOOP_HITM BIT_ULL(36) #define HSW_SNOOP_NON_DRAM BIT_ULL(37) #define HSW_ANY_SNOOP (HSW_SNOOP_NONE| \ HSW_SNOOP_NOT_NEEDED|HSW_SNOOP_MISS| \ HSW_SNOOP_HIT_NO_FWD|HSW_SNOOP_HIT_WITH_FWD| \ HSW_SNOOP_HITM|HSW_SNOOP_NON_DRAM) #define HSW_SNOOP_DRAM (HSW_ANY_SNOOP & ~HSW_SNOOP_NON_DRAM) #define HSW_DEMAND_READ HSW_DEMAND_DATA_RD #define HSW_DEMAND_WRITE HSW_DEMAND_RFO #define HSW_L3_MISS_REMOTE (HSW_L3_MISS_REMOTE_HOP0|\ HSW_L3_MISS_REMOTE_HOP1|HSW_L3_MISS_REMOTE_HOP2P) #define HSW_LLC_ACCESS HSW_ANY_RESPONSE #define BDW_L3_MISS_LOCAL BIT(26) #define BDW_L3_MISS (BDW_L3_MISS_LOCAL| \ HSW_L3_MISS_REMOTE_HOP0|HSW_L3_MISS_REMOTE_HOP1| \ HSW_L3_MISS_REMOTE_HOP2P) static __initconst const u64 hsw_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_UOPS_RETIRED.ALL_LOADS */ [ C(RESULT_MISS) ] = 0x151, /* L1D.REPLACEMENT */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_UOPS_RETIRED.ALL_STORES */ [ C(RESULT_MISS) ] = 0x0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x280, /* ICACHE.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_UOPS_RETIRED.ALL_LOADS */ [ C(RESULT_MISS) ] = 0x108, /* DTLB_LOAD_MISSES.MISS_CAUSES_A_WALK */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_UOPS_RETIRED.ALL_STORES */ [ C(RESULT_MISS) ] = 0x149, /* DTLB_STORE_MISSES.MISS_CAUSES_A_WALK */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x6085, /* ITLB_MISSES.STLB_HIT */ [ C(RESULT_MISS) ] = 0x185, /* ITLB_MISSES.MISS_CAUSES_A_WALK */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0xc4, /* BR_INST_RETIRED.ALL_BRANCHES */ [ C(RESULT_MISS) ] = 0xc5, /* BR_MISP_RETIRED.ALL_BRANCHES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x1b7, /* OFFCORE_RESPONSE */ [ C(RESULT_MISS) ] = 0x1b7, /* OFFCORE_RESPONSE */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, }; static __initconst const u64 hsw_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = HSW_DEMAND_READ| HSW_LLC_ACCESS, [ C(RESULT_MISS) ] = HSW_DEMAND_READ| HSW_L3_MISS|HSW_ANY_SNOOP, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = HSW_DEMAND_WRITE| HSW_LLC_ACCESS, [ C(RESULT_MISS) ] = HSW_DEMAND_WRITE| HSW_L3_MISS|HSW_ANY_SNOOP, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = HSW_DEMAND_READ| HSW_L3_MISS_LOCAL_DRAM| HSW_SNOOP_DRAM, [ C(RESULT_MISS) ] = HSW_DEMAND_READ| HSW_L3_MISS_REMOTE| HSW_SNOOP_DRAM, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = HSW_DEMAND_WRITE| HSW_L3_MISS_LOCAL_DRAM| HSW_SNOOP_DRAM, [ C(RESULT_MISS) ] = HSW_DEMAND_WRITE| HSW_L3_MISS_REMOTE| HSW_SNOOP_DRAM, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, }; static __initconst const u64 westmere_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */ [ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */ [ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */ [ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */ }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */ [ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { /* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, /* * Use RFO, not WRITEBACK, because a write miss would typically occur * on RFO. */ [ C(OP_WRITE) ] = { /* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_PREFETCH) ] = { /* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */ [ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */ [ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */ [ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.ANY */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */ [ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, }, }; /* * Nehalem/Westmere MSR_OFFCORE_RESPONSE bits; * See IA32 SDM Vol 3B 30.6.1.3 */ #define NHM_DMND_DATA_RD (1 << 0) #define NHM_DMND_RFO (1 << 1) #define NHM_DMND_IFETCH (1 << 2) #define NHM_DMND_WB (1 << 3) #define NHM_PF_DATA_RD (1 << 4) #define NHM_PF_DATA_RFO (1 << 5) #define NHM_PF_IFETCH (1 << 6) #define NHM_OFFCORE_OTHER (1 << 7) #define NHM_UNCORE_HIT (1 << 8) #define NHM_OTHER_CORE_HIT_SNP (1 << 9) #define NHM_OTHER_CORE_HITM (1 << 10) /* reserved */ #define NHM_REMOTE_CACHE_FWD (1 << 12) #define NHM_REMOTE_DRAM (1 << 13) #define NHM_LOCAL_DRAM (1 << 14) #define NHM_NON_DRAM (1 << 15) #define NHM_LOCAL (NHM_LOCAL_DRAM|NHM_REMOTE_CACHE_FWD) #define NHM_REMOTE (NHM_REMOTE_DRAM) #define NHM_DMND_READ (NHM_DMND_DATA_RD) #define NHM_DMND_WRITE (NHM_DMND_RFO|NHM_DMND_WB) #define NHM_DMND_PREFETCH (NHM_PF_DATA_RD|NHM_PF_DATA_RFO) #define NHM_L3_HIT (NHM_UNCORE_HIT|NHM_OTHER_CORE_HIT_SNP|NHM_OTHER_CORE_HITM) #define NHM_L3_MISS (NHM_NON_DRAM|NHM_LOCAL_DRAM|NHM_REMOTE_DRAM|NHM_REMOTE_CACHE_FWD) #define NHM_L3_ACCESS (NHM_L3_HIT|NHM_L3_MISS) static __initconst const u64 nehalem_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_L3_ACCESS, [ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_L3_MISS, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_L3_ACCESS, [ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_L3_MISS, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_L3_ACCESS, [ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_L3_MISS, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_LOCAL|NHM_REMOTE, [ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_REMOTE, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_LOCAL|NHM_REMOTE, [ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_REMOTE, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_LOCAL|NHM_REMOTE, [ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_REMOTE, }, }, }; static __initconst const u64 nehalem_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */ [ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */ [ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */ [ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */ }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */ [ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { /* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, /* * Use RFO, not WRITEBACK, because a write miss would typically occur * on RFO. */ [ C(OP_WRITE) ] = { /* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_PREFETCH) ] = { /* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */ [ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */ [ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0x0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */ [ C(RESULT_MISS) ] = 0x20c8, /* ITLB_MISS_RETIRED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */ [ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0x01b7, }, }, }; static __initconst const u64 core2_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI */ [ C(RESULT_MISS) ] = 0x0140, /* L1D_CACHE_LD.I_STATE */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI */ [ C(RESULT_MISS) ] = 0x0141, /* L1D_CACHE_ST.I_STATE */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x104e, /* L1D_PREFETCH.REQUESTS */ [ C(RESULT_MISS) ] = 0, }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0080, /* L1I.READS */ [ C(RESULT_MISS) ] = 0x0081, /* L1I.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */ [ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */ [ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */ [ C(RESULT_MISS) ] = 0x0208, /* DTLB_MISSES.MISS_LD */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */ [ C(RESULT_MISS) ] = 0x0808, /* DTLB_MISSES.MISS_ST */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */ [ C(RESULT_MISS) ] = 0x1282, /* ITLBMISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */ [ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, }; static __initconst const u64 atom_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE.LD */ [ C(RESULT_MISS) ] = 0, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE.ST */ [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = 0, }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */ [ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */ [ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */ [ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE_LD.MESI (alias) */ [ C(RESULT_MISS) ] = 0x0508, /* DTLB_MISSES.MISS_LD */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE_ST.MESI (alias) */ [ C(RESULT_MISS) ] = 0x0608, /* DTLB_MISSES.MISS_ST */ }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */ [ C(RESULT_MISS) ] = 0x0282, /* ITLB.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */ [ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, }; EVENT_ATTR_STR(topdown-total-slots, td_total_slots_slm, "event=0x3c"); EVENT_ATTR_STR(topdown-total-slots.scale, td_total_slots_scale_slm, "2"); /* no_alloc_cycles.not_delivered */ EVENT_ATTR_STR(topdown-fetch-bubbles, td_fetch_bubbles_slm, "event=0xca,umask=0x50"); EVENT_ATTR_STR(topdown-fetch-bubbles.scale, td_fetch_bubbles_scale_slm, "2"); /* uops_retired.all */ EVENT_ATTR_STR(topdown-slots-issued, td_slots_issued_slm, "event=0xc2,umask=0x10"); /* uops_retired.all */ EVENT_ATTR_STR(topdown-slots-retired, td_slots_retired_slm, "event=0xc2,umask=0x10"); static struct attribute *slm_events_attrs[] = { EVENT_PTR(td_total_slots_slm), EVENT_PTR(td_total_slots_scale_slm), EVENT_PTR(td_fetch_bubbles_slm), EVENT_PTR(td_fetch_bubbles_scale_slm), EVENT_PTR(td_slots_issued_slm), EVENT_PTR(td_slots_retired_slm), NULL }; static struct extra_reg intel_slm_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x768005ffffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x02b7, MSR_OFFCORE_RSP_1, 0x368005ffffull, RSP_1), EVENT_EXTRA_END }; #define SLM_DMND_READ SNB_DMND_DATA_RD #define SLM_DMND_WRITE SNB_DMND_RFO #define SLM_DMND_PREFETCH (SNB_PF_DATA_RD|SNB_PF_RFO) #define SLM_SNP_ANY (SNB_SNP_NONE|SNB_SNP_MISS|SNB_NO_FWD|SNB_HITM) #define SLM_LLC_ACCESS SNB_RESP_ANY #define SLM_LLC_MISS (SLM_SNP_ANY|SNB_NON_DRAM) static __initconst const u64 slm_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = SLM_DMND_READ|SLM_LLC_ACCESS, [ C(RESULT_MISS) ] = 0, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = SLM_DMND_WRITE|SLM_LLC_ACCESS, [ C(RESULT_MISS) ] = SLM_DMND_WRITE|SLM_LLC_MISS, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = SLM_DMND_PREFETCH|SLM_LLC_ACCESS, [ C(RESULT_MISS) ] = SLM_DMND_PREFETCH|SLM_LLC_MISS, }, }, }; static __initconst const u64 slm_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0x0104, /* LD_DCU_MISS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0380, /* ICACHE.ACCESSES */ [ C(RESULT_MISS) ] = 0x0280, /* ICACGE.MISSES */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { /* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, [ C(RESULT_MISS) ] = 0, }, [ C(OP_WRITE) ] = { /* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, [ C(OP_PREFETCH) ] = { /* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */ [ C(RESULT_ACCESS) ] = 0x01b7, /* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */ [ C(RESULT_MISS) ] = 0x01b7, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0x0804, /* LD_DTLB_MISS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */ [ C(RESULT_MISS) ] = 0x40205, /* PAGE_WALKS.I_SIDE_WALKS */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */ [ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, }; EVENT_ATTR_STR(topdown-total-slots, td_total_slots_glm, "event=0x3c"); EVENT_ATTR_STR(topdown-total-slots.scale, td_total_slots_scale_glm, "3"); /* UOPS_NOT_DELIVERED.ANY */ EVENT_ATTR_STR(topdown-fetch-bubbles, td_fetch_bubbles_glm, "event=0x9c"); /* ISSUE_SLOTS_NOT_CONSUMED.RECOVERY */ EVENT_ATTR_STR(topdown-recovery-bubbles, td_recovery_bubbles_glm, "event=0xca,umask=0x02"); /* UOPS_RETIRED.ANY */ EVENT_ATTR_STR(topdown-slots-retired, td_slots_retired_glm, "event=0xc2"); /* UOPS_ISSUED.ANY */ EVENT_ATTR_STR(topdown-slots-issued, td_slots_issued_glm, "event=0x0e"); static struct attribute *glm_events_attrs[] = { EVENT_PTR(td_total_slots_glm), EVENT_PTR(td_total_slots_scale_glm), EVENT_PTR(td_fetch_bubbles_glm), EVENT_PTR(td_recovery_bubbles_glm), EVENT_PTR(td_slots_issued_glm), EVENT_PTR(td_slots_retired_glm), NULL }; static struct extra_reg intel_glm_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x760005ffbfull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x02b7, MSR_OFFCORE_RSP_1, 0x360005ffbfull, RSP_1), EVENT_EXTRA_END }; #define GLM_DEMAND_DATA_RD BIT_ULL(0) #define GLM_DEMAND_RFO BIT_ULL(1) #define GLM_ANY_RESPONSE BIT_ULL(16) #define GLM_SNP_NONE_OR_MISS BIT_ULL(33) #define GLM_DEMAND_READ GLM_DEMAND_DATA_RD #define GLM_DEMAND_WRITE GLM_DEMAND_RFO #define GLM_DEMAND_PREFETCH (SNB_PF_DATA_RD|SNB_PF_RFO) #define GLM_LLC_ACCESS GLM_ANY_RESPONSE #define GLM_SNP_ANY (GLM_SNP_NONE_OR_MISS|SNB_NO_FWD|SNB_HITM) #define GLM_LLC_MISS (GLM_SNP_ANY|SNB_NON_DRAM) static __initconst const u64 glm_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x81d0, /* MEM_UOPS_RETIRED.ALL_LOADS */ [C(RESULT_MISS)] = 0x0, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x82d0, /* MEM_UOPS_RETIRED.ALL_STORES */ [C(RESULT_MISS)] = 0x0, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0380, /* ICACHE.ACCESSES */ [C(RESULT_MISS)] = 0x0280, /* ICACHE.MISSES */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x1b7, /* OFFCORE_RESPONSE */ [C(RESULT_MISS)] = 0x1b7, /* OFFCORE_RESPONSE */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x1b7, /* OFFCORE_RESPONSE */ [C(RESULT_MISS)] = 0x1b7, /* OFFCORE_RESPONSE */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x1b7, /* OFFCORE_RESPONSE */ [C(RESULT_MISS)] = 0x1b7, /* OFFCORE_RESPONSE */ }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x81d0, /* MEM_UOPS_RETIRED.ALL_LOADS */ [C(RESULT_MISS)] = 0x0, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x82d0, /* MEM_UOPS_RETIRED.ALL_STORES */ [C(RESULT_MISS)] = 0x0, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x00c0, /* INST_RETIRED.ANY_P */ [C(RESULT_MISS)] = 0x0481, /* ITLB.MISS */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */ [C(RESULT_MISS)] = 0x00c5, /* BR_MISP_RETIRED.ALL_BRANCHES */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, }; static __initconst const u64 glm_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = GLM_DEMAND_READ| GLM_LLC_ACCESS, [C(RESULT_MISS)] = GLM_DEMAND_READ| GLM_LLC_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = GLM_DEMAND_WRITE| GLM_LLC_ACCESS, [C(RESULT_MISS)] = GLM_DEMAND_WRITE| GLM_LLC_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = GLM_DEMAND_PREFETCH| GLM_LLC_ACCESS, [C(RESULT_MISS)] = GLM_DEMAND_PREFETCH| GLM_LLC_MISS, }, }, }; static __initconst const u64 glp_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x81d0, /* MEM_UOPS_RETIRED.ALL_LOADS */ [C(RESULT_MISS)] = 0x0, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x82d0, /* MEM_UOPS_RETIRED.ALL_STORES */ [C(RESULT_MISS)] = 0x0, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0380, /* ICACHE.ACCESSES */ [C(RESULT_MISS)] = 0x0280, /* ICACHE.MISSES */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x1b7, /* OFFCORE_RESPONSE */ [C(RESULT_MISS)] = 0x1b7, /* OFFCORE_RESPONSE */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x1b7, /* OFFCORE_RESPONSE */ [C(RESULT_MISS)] = 0x1b7, /* OFFCORE_RESPONSE */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x81d0, /* MEM_UOPS_RETIRED.ALL_LOADS */ [C(RESULT_MISS)] = 0xe08, /* DTLB_LOAD_MISSES.WALK_COMPLETED */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x82d0, /* MEM_UOPS_RETIRED.ALL_STORES */ [C(RESULT_MISS)] = 0xe49, /* DTLB_STORE_MISSES.WALK_COMPLETED */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x00c0, /* INST_RETIRED.ANY_P */ [C(RESULT_MISS)] = 0x0481, /* ITLB.MISS */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */ [C(RESULT_MISS)] = 0x00c5, /* BR_MISP_RETIRED.ALL_BRANCHES */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, }; static __initconst const u64 glp_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = GLM_DEMAND_READ| GLM_LLC_ACCESS, [C(RESULT_MISS)] = GLM_DEMAND_READ| GLM_LLC_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = GLM_DEMAND_WRITE| GLM_LLC_ACCESS, [C(RESULT_MISS)] = GLM_DEMAND_WRITE| GLM_LLC_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, }; #define TNT_LOCAL_DRAM BIT_ULL(26) #define TNT_DEMAND_READ GLM_DEMAND_DATA_RD #define TNT_DEMAND_WRITE GLM_DEMAND_RFO #define TNT_LLC_ACCESS GLM_ANY_RESPONSE #define TNT_SNP_ANY (SNB_SNP_NOT_NEEDED|SNB_SNP_MISS| \ SNB_NO_FWD|SNB_SNP_FWD|SNB_HITM) #define TNT_LLC_MISS (TNT_SNP_ANY|SNB_NON_DRAM|TNT_LOCAL_DRAM) static __initconst const u64 tnt_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TNT_DEMAND_READ| TNT_LLC_ACCESS, [C(RESULT_MISS)] = TNT_DEMAND_READ| TNT_LLC_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TNT_DEMAND_WRITE| TNT_LLC_ACCESS, [C(RESULT_MISS)] = TNT_DEMAND_WRITE| TNT_LLC_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, }; EVENT_ATTR_STR(topdown-fe-bound, td_fe_bound_tnt, "event=0x71,umask=0x0"); EVENT_ATTR_STR(topdown-retiring, td_retiring_tnt, "event=0xc2,umask=0x0"); EVENT_ATTR_STR(topdown-bad-spec, td_bad_spec_tnt, "event=0x73,umask=0x6"); EVENT_ATTR_STR(topdown-be-bound, td_be_bound_tnt, "event=0x74,umask=0x0"); static struct attribute *tnt_events_attrs[] = { EVENT_PTR(td_fe_bound_tnt), EVENT_PTR(td_retiring_tnt), EVENT_PTR(td_bad_spec_tnt), EVENT_PTR(td_be_bound_tnt), NULL, }; static struct extra_reg intel_tnt_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x800ff0ffffff9fffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x02b7, MSR_OFFCORE_RSP_1, 0xff0ffffff9fffull, RSP_1), EVENT_EXTRA_END }; EVENT_ATTR_STR(mem-loads, mem_ld_grt, "event=0xd0,umask=0x5,ldlat=3"); EVENT_ATTR_STR(mem-stores, mem_st_grt, "event=0xd0,umask=0x6"); static struct attribute *grt_mem_attrs[] = { EVENT_PTR(mem_ld_grt), EVENT_PTR(mem_st_grt), NULL }; static struct extra_reg intel_grt_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x3fffffffffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x02b7, MSR_OFFCORE_RSP_1, 0x3fffffffffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x5d0), EVENT_EXTRA_END }; EVENT_ATTR_STR(topdown-retiring, td_retiring_cmt, "event=0x72,umask=0x0"); EVENT_ATTR_STR(topdown-bad-spec, td_bad_spec_cmt, "event=0x73,umask=0x0"); static struct attribute *cmt_events_attrs[] = { EVENT_PTR(td_fe_bound_tnt), EVENT_PTR(td_retiring_cmt), EVENT_PTR(td_bad_spec_cmt), EVENT_PTR(td_be_bound_tnt), NULL }; static struct extra_reg intel_cmt_extra_regs[] __read_mostly = { /* must define OFFCORE_RSP_X first, see intel_fixup_er() */ INTEL_UEVENT_EXTRA_REG(0x01b7, MSR_OFFCORE_RSP_0, 0x800ff3ffffffffffull, RSP_0), INTEL_UEVENT_EXTRA_REG(0x02b7, MSR_OFFCORE_RSP_1, 0xff3ffffffffffull, RSP_1), INTEL_UEVENT_PEBS_LDLAT_EXTRA_REG(0x5d0), INTEL_UEVENT_EXTRA_REG(0x0127, MSR_SNOOP_RSP_0, 0xffffffffffffffffull, SNOOP_0), INTEL_UEVENT_EXTRA_REG(0x0227, MSR_SNOOP_RSP_1, 0xffffffffffffffffull, SNOOP_1), EVENT_EXTRA_END }; #define KNL_OT_L2_HITE BIT_ULL(19) /* Other Tile L2 Hit */ #define KNL_OT_L2_HITF BIT_ULL(20) /* Other Tile L2 Hit */ #define KNL_MCDRAM_LOCAL BIT_ULL(21) #define KNL_MCDRAM_FAR BIT_ULL(22) #define KNL_DDR_LOCAL BIT_ULL(23) #define KNL_DDR_FAR BIT_ULL(24) #define KNL_DRAM_ANY (KNL_MCDRAM_LOCAL | KNL_MCDRAM_FAR | \ KNL_DDR_LOCAL | KNL_DDR_FAR) #define KNL_L2_READ SLM_DMND_READ #define KNL_L2_WRITE SLM_DMND_WRITE #define KNL_L2_PREFETCH SLM_DMND_PREFETCH #define KNL_L2_ACCESS SLM_LLC_ACCESS #define KNL_L2_MISS (KNL_OT_L2_HITE | KNL_OT_L2_HITF | \ KNL_DRAM_ANY | SNB_SNP_ANY | \ SNB_NON_DRAM) static __initconst const u64 knl_hw_cache_extra_regs [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = KNL_L2_READ | KNL_L2_ACCESS, [C(RESULT_MISS)] = 0, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = KNL_L2_WRITE | KNL_L2_ACCESS, [C(RESULT_MISS)] = KNL_L2_WRITE | KNL_L2_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = KNL_L2_PREFETCH | KNL_L2_ACCESS, [C(RESULT_MISS)] = KNL_L2_PREFETCH | KNL_L2_MISS, }, }, }; /* * Used from PMIs where the LBRs are already disabled. * * This function could be called consecutively. It is required to remain in * disabled state if called consecutively. * * During consecutive calls, the same disable value will be written to related * registers, so the PMU state remains unchanged. * * intel_bts events don't coexist with intel PMU's BTS events because of * x86_add_exclusive(x86_lbr_exclusive_lbr); there's no need to keep them * disabled around intel PMU's event batching etc, only inside the PMI handler. * * Avoid PEBS_ENABLE MSR access in PMIs. * The GLOBAL_CTRL has been disabled. All the counters do not count anymore. * It doesn't matter if the PEBS is enabled or not. * Usually, the PEBS status are not changed in PMIs. It's unnecessary to * access PEBS_ENABLE MSR in disable_all()/enable_all(). * However, there are some cases which may change PEBS status, e.g. PMI * throttle. The PEBS_ENABLE should be updated where the status changes. */ static __always_inline void __intel_pmu_disable_all(bool bts) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0); if (bts && test_bit(INTEL_PMC_IDX_FIXED_BTS, cpuc->active_mask)) intel_pmu_disable_bts(); } static __always_inline void intel_pmu_disable_all(void) { __intel_pmu_disable_all(true); intel_pmu_pebs_disable_all(); intel_pmu_lbr_disable_all(); } static void __intel_pmu_enable_all(int added, bool pmi) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); u64 intel_ctrl = hybrid(cpuc->pmu, intel_ctrl); intel_pmu_lbr_enable_all(pmi); if (cpuc->fixed_ctrl_val != cpuc->active_fixed_ctrl_val) { wrmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, cpuc->fixed_ctrl_val); cpuc->active_fixed_ctrl_val = cpuc->fixed_ctrl_val; } wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, intel_ctrl & ~cpuc->intel_ctrl_guest_mask); if (test_bit(INTEL_PMC_IDX_FIXED_BTS, cpuc->active_mask)) { struct perf_event *event = cpuc->events[INTEL_PMC_IDX_FIXED_BTS]; if (WARN_ON_ONCE(!event)) return; intel_pmu_enable_bts(event->hw.config); } } static void intel_pmu_enable_all(int added) { intel_pmu_pebs_enable_all(); __intel_pmu_enable_all(added, false); } static noinline int __intel_pmu_snapshot_branch_stack(struct perf_branch_entry *entries, unsigned int cnt, unsigned long flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); intel_pmu_lbr_read(); cnt = min_t(unsigned int, cnt, x86_pmu.lbr_nr); memcpy(entries, cpuc->lbr_entries, sizeof(struct perf_branch_entry) * cnt); intel_pmu_enable_all(0); local_irq_restore(flags); return cnt; } static int intel_pmu_snapshot_branch_stack(struct perf_branch_entry *entries, unsigned int cnt) { unsigned long flags; /* must not have branches... */ local_irq_save(flags); __intel_pmu_disable_all(false); /* we don't care about BTS */ __intel_pmu_lbr_disable(); /* ... until here */ return __intel_pmu_snapshot_branch_stack(entries, cnt, flags); } static int intel_pmu_snapshot_arch_branch_stack(struct perf_branch_entry *entries, unsigned int cnt) { unsigned long flags; /* must not have branches... */ local_irq_save(flags); __intel_pmu_disable_all(false); /* we don't care about BTS */ __intel_pmu_arch_lbr_disable(); /* ... until here */ return __intel_pmu_snapshot_branch_stack(entries, cnt, flags); } /* * Workaround for: * Intel Errata AAK100 (model 26) * Intel Errata AAP53 (model 30) * Intel Errata BD53 (model 44) * * The official story: * These chips need to be 'reset' when adding counters by programming the * magic three (non-counting) events 0x4300B5, 0x4300D2, and 0x4300B1 either * in sequence on the same PMC or on different PMCs. * * In practice it appears some of these events do in fact count, and * we need to program all 4 events. */ static void intel_pmu_nhm_workaround(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); static const unsigned long nhm_magic[4] = { 0x4300B5, 0x4300D2, 0x4300B1, 0x4300B1 }; struct perf_event *event; int i; /* * The Errata requires below steps: * 1) Clear MSR_IA32_PEBS_ENABLE and MSR_CORE_PERF_GLOBAL_CTRL; * 2) Configure 4 PERFEVTSELx with the magic events and clear * the corresponding PMCx; * 3) set bit0~bit3 of MSR_CORE_PERF_GLOBAL_CTRL; * 4) Clear MSR_CORE_PERF_GLOBAL_CTRL; * 5) Clear 4 pairs of ERFEVTSELx and PMCx; */ /* * The real steps we choose are a little different from above. * A) To reduce MSR operations, we don't run step 1) as they * are already cleared before this function is called; * B) Call x86_perf_event_update to save PMCx before configuring * PERFEVTSELx with magic number; * C) With step 5), we do clear only when the PERFEVTSELx is * not used currently. * D) Call x86_perf_event_set_period to restore PMCx; */ /* We always operate 4 pairs of PERF Counters */ for (i = 0; i < 4; i++) { event = cpuc->events[i]; if (event) static_call(x86_pmu_update)(event); } for (i = 0; i < 4; i++) { wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, nhm_magic[i]); wrmsrl(MSR_ARCH_PERFMON_PERFCTR0 + i, 0x0); } wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0xf); wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0x0); for (i = 0; i < 4; i++) { event = cpuc->events[i]; if (event) { static_call(x86_pmu_set_period)(event); __x86_pmu_enable_event(&event->hw, ARCH_PERFMON_EVENTSEL_ENABLE); } else wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, 0x0); } } static void intel_pmu_nhm_enable_all(int added) { if (added) intel_pmu_nhm_workaround(); intel_pmu_enable_all(added); } static void intel_set_tfa(struct cpu_hw_events *cpuc, bool on) { u64 val = on ? MSR_TFA_RTM_FORCE_ABORT : 0; if (cpuc->tfa_shadow != val) { cpuc->tfa_shadow = val; wrmsrl(MSR_TSX_FORCE_ABORT, val); } } static void intel_tfa_commit_scheduling(struct cpu_hw_events *cpuc, int idx, int cntr) { /* * We're going to use PMC3, make sure TFA is set before we touch it. */ if (cntr == 3) intel_set_tfa(cpuc, true); } static void intel_tfa_pmu_enable_all(int added) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* * If we find PMC3 is no longer used when we enable the PMU, we can * clear TFA. */ if (!test_bit(3, cpuc->active_mask)) intel_set_tfa(cpuc, false); intel_pmu_enable_all(added); } static inline u64 intel_pmu_get_status(void) { u64 status; rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status); return status; } static inline void intel_pmu_ack_status(u64 ack) { wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack); } static inline bool event_is_checkpointed(struct perf_event *event) { return unlikely(event->hw.config & HSW_IN_TX_CHECKPOINTED) != 0; } static inline void intel_set_masks(struct perf_event *event, int idx) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (event->attr.exclude_host) __set_bit(idx, (unsigned long *)&cpuc->intel_ctrl_guest_mask); if (event->attr.exclude_guest) __set_bit(idx, (unsigned long *)&cpuc->intel_ctrl_host_mask); if (event_is_checkpointed(event)) __set_bit(idx, (unsigned long *)&cpuc->intel_cp_status); } static inline void intel_clear_masks(struct perf_event *event, int idx) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); __clear_bit(idx, (unsigned long *)&cpuc->intel_ctrl_guest_mask); __clear_bit(idx, (unsigned long *)&cpuc->intel_ctrl_host_mask); __clear_bit(idx, (unsigned long *)&cpuc->intel_cp_status); } static void intel_pmu_disable_fixed(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; int idx = hwc->idx; u64 mask; if (is_topdown_idx(idx)) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* * When there are other active TopDown events, * don't disable the fixed counter 3. */ if (*(u64 *)cpuc->active_mask & INTEL_PMC_OTHER_TOPDOWN_BITS(idx)) return; idx = INTEL_PMC_IDX_FIXED_SLOTS; } intel_clear_masks(event, idx); mask = intel_fixed_bits_by_idx(idx - INTEL_PMC_IDX_FIXED, INTEL_FIXED_BITS_MASK); cpuc->fixed_ctrl_val &= ~mask; } static void intel_pmu_disable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int idx = hwc->idx; switch (idx) { case 0 ... INTEL_PMC_IDX_FIXED - 1: intel_clear_masks(event, idx); x86_pmu_disable_event(event); break; case INTEL_PMC_IDX_FIXED ... INTEL_PMC_IDX_FIXED_BTS - 1: case INTEL_PMC_IDX_METRIC_BASE ... INTEL_PMC_IDX_METRIC_END: intel_pmu_disable_fixed(event); break; case INTEL_PMC_IDX_FIXED_BTS: intel_pmu_disable_bts(); intel_pmu_drain_bts_buffer(); return; case INTEL_PMC_IDX_FIXED_VLBR: intel_clear_masks(event, idx); break; default: intel_clear_masks(event, idx); pr_warn("Failed to disable the event with invalid index %d\n", idx); return; } /* * Needs to be called after x86_pmu_disable_event, * so we don't trigger the event without PEBS bit set. */ if (unlikely(event->attr.precise_ip)) intel_pmu_pebs_disable(event); } static void intel_pmu_assign_event(struct perf_event *event, int idx) { if (is_pebs_pt(event)) perf_report_aux_output_id(event, idx); } static void intel_pmu_del_event(struct perf_event *event) { if (needs_branch_stack(event)) intel_pmu_lbr_del(event); if (event->attr.precise_ip) intel_pmu_pebs_del(event); } static int icl_set_topdown_event_period(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; s64 left = local64_read(&hwc->period_left); /* * The values in PERF_METRICS MSR are derived from fixed counter 3. * Software should start both registers, PERF_METRICS and fixed * counter 3, from zero. * Clear PERF_METRICS and Fixed counter 3 in initialization. * After that, both MSRs will be cleared for each read. * Don't need to clear them again. */ if (left == x86_pmu.max_period) { wrmsrl(MSR_CORE_PERF_FIXED_CTR3, 0); wrmsrl(MSR_PERF_METRICS, 0); hwc->saved_slots = 0; hwc->saved_metric = 0; } if ((hwc->saved_slots) && is_slots_event(event)) { wrmsrl(MSR_CORE_PERF_FIXED_CTR3, hwc->saved_slots); wrmsrl(MSR_PERF_METRICS, hwc->saved_metric); } perf_event_update_userpage(event); return 0; } static int adl_set_topdown_event_period(struct perf_event *event) { struct x86_hybrid_pmu *pmu = hybrid_pmu(event->pmu); if (pmu->cpu_type != hybrid_big) return 0; return icl_set_topdown_event_period(event); } DEFINE_STATIC_CALL(intel_pmu_set_topdown_event_period, x86_perf_event_set_period); static inline u64 icl_get_metrics_event_value(u64 metric, u64 slots, int idx) { u32 val; /* * The metric is reported as an 8bit integer fraction * summing up to 0xff. * slots-in-metric = (Metric / 0xff) * slots */ val = (metric >> ((idx - INTEL_PMC_IDX_METRIC_BASE) * 8)) & 0xff; return mul_u64_u32_div(slots, val, 0xff); } static u64 icl_get_topdown_value(struct perf_event *event, u64 slots, u64 metrics) { int idx = event->hw.idx; u64 delta; if (is_metric_idx(idx)) delta = icl_get_metrics_event_value(metrics, slots, idx); else delta = slots; return delta; } static void __icl_update_topdown_event(struct perf_event *event, u64 slots, u64 metrics, u64 last_slots, u64 last_metrics) { u64 delta, last = 0; delta = icl_get_topdown_value(event, slots, metrics); if (last_slots) last = icl_get_topdown_value(event, last_slots, last_metrics); /* * The 8bit integer fraction of metric may be not accurate, * especially when the changes is very small. * For example, if only a few bad_spec happens, the fraction * may be reduced from 1 to 0. If so, the bad_spec event value * will be 0 which is definitely less than the last value. * Avoid update event->count for this case. */ if (delta > last) { delta -= last; local64_add(delta, &event->count); } } static void update_saved_topdown_regs(struct perf_event *event, u64 slots, u64 metrics, int metric_end) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_event *other; int idx; event->hw.saved_slots = slots; event->hw.saved_metric = metrics; for_each_set_bit(idx, cpuc->active_mask, metric_end + 1) { if (!is_topdown_idx(idx)) continue; other = cpuc->events[idx]; other->hw.saved_slots = slots; other->hw.saved_metric = metrics; } } /* * Update all active Topdown events. * * The PERF_METRICS and Fixed counter 3 are read separately. The values may be * modify by a NMI. PMU has to be disabled before calling this function. */ static u64 intel_update_topdown_event(struct perf_event *event, int metric_end) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_event *other; u64 slots, metrics; bool reset = true; int idx; /* read Fixed counter 3 */ rdpmcl((3 | INTEL_PMC_FIXED_RDPMC_BASE), slots); if (!slots) return 0; /* read PERF_METRICS */ rdpmcl(INTEL_PMC_FIXED_RDPMC_METRICS, metrics); for_each_set_bit(idx, cpuc->active_mask, metric_end + 1) { if (!is_topdown_idx(idx)) continue; other = cpuc->events[idx]; __icl_update_topdown_event(other, slots, metrics, event ? event->hw.saved_slots : 0, event ? event->hw.saved_metric : 0); } /* * Check and update this event, which may have been cleared * in active_mask e.g. x86_pmu_stop() */ if (event && !test_bit(event->hw.idx, cpuc->active_mask)) { __icl_update_topdown_event(event, slots, metrics, event->hw.saved_slots, event->hw.saved_metric); /* * In x86_pmu_stop(), the event is cleared in active_mask first, * then drain the delta, which indicates context switch for * counting. * Save metric and slots for context switch. * Don't need to reset the PERF_METRICS and Fixed counter 3. * Because the values will be restored in next schedule in. */ update_saved_topdown_regs(event, slots, metrics, metric_end); reset = false; } if (reset) { /* The fixed counter 3 has to be written before the PERF_METRICS. */ wrmsrl(MSR_CORE_PERF_FIXED_CTR3, 0); wrmsrl(MSR_PERF_METRICS, 0); if (event) update_saved_topdown_regs(event, 0, 0, metric_end); } return slots; } static u64 icl_update_topdown_event(struct perf_event *event) { return intel_update_topdown_event(event, INTEL_PMC_IDX_METRIC_BASE + x86_pmu.num_topdown_events - 1); } static u64 adl_update_topdown_event(struct perf_event *event) { struct x86_hybrid_pmu *pmu = hybrid_pmu(event->pmu); if (pmu->cpu_type != hybrid_big) return 0; return icl_update_topdown_event(event); } DEFINE_STATIC_CALL(intel_pmu_update_topdown_event, x86_perf_event_update); static void intel_pmu_read_topdown_event(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* Only need to call update_topdown_event() once for group read. */ if ((cpuc->txn_flags & PERF_PMU_TXN_READ) && !is_slots_event(event)) return; perf_pmu_disable(event->pmu); static_call(intel_pmu_update_topdown_event)(event); perf_pmu_enable(event->pmu); } static void intel_pmu_read_event(struct perf_event *event) { if (event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD) intel_pmu_auto_reload_read(event); else if (is_topdown_count(event)) intel_pmu_read_topdown_event(event); else x86_perf_event_update(event); } static void intel_pmu_enable_fixed(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; u64 mask, bits = 0; int idx = hwc->idx; if (is_topdown_idx(idx)) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* * When there are other active TopDown events, * don't enable the fixed counter 3 again. */ if (*(u64 *)cpuc->active_mask & INTEL_PMC_OTHER_TOPDOWN_BITS(idx)) return; idx = INTEL_PMC_IDX_FIXED_SLOTS; } intel_set_masks(event, idx); /* * Enable IRQ generation (0x8), if not PEBS, * and enable ring-3 counting (0x2) and ring-0 counting (0x1) * if requested: */ if (!event->attr.precise_ip) bits |= INTEL_FIXED_0_ENABLE_PMI; if (hwc->config & ARCH_PERFMON_EVENTSEL_USR) bits |= INTEL_FIXED_0_USER; if (hwc->config & ARCH_PERFMON_EVENTSEL_OS) bits |= INTEL_FIXED_0_KERNEL; /* * ANY bit is supported in v3 and up */ if (x86_pmu.version > 2 && hwc->config & ARCH_PERFMON_EVENTSEL_ANY) bits |= INTEL_FIXED_0_ANYTHREAD; idx -= INTEL_PMC_IDX_FIXED; bits = intel_fixed_bits_by_idx(idx, bits); mask = intel_fixed_bits_by_idx(idx, INTEL_FIXED_BITS_MASK); if (x86_pmu.intel_cap.pebs_baseline && event->attr.precise_ip) { bits |= intel_fixed_bits_by_idx(idx, ICL_FIXED_0_ADAPTIVE); mask |= intel_fixed_bits_by_idx(idx, ICL_FIXED_0_ADAPTIVE); } cpuc->fixed_ctrl_val &= ~mask; cpuc->fixed_ctrl_val |= bits; } static void intel_pmu_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int idx = hwc->idx; if (unlikely(event->attr.precise_ip)) intel_pmu_pebs_enable(event); switch (idx) { case 0 ... INTEL_PMC_IDX_FIXED - 1: intel_set_masks(event, idx); __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE); break; case INTEL_PMC_IDX_FIXED ... INTEL_PMC_IDX_FIXED_BTS - 1: case INTEL_PMC_IDX_METRIC_BASE ... INTEL_PMC_IDX_METRIC_END: intel_pmu_enable_fixed(event); break; case INTEL_PMC_IDX_FIXED_BTS: if (!__this_cpu_read(cpu_hw_events.enabled)) return; intel_pmu_enable_bts(hwc->config); break; case INTEL_PMC_IDX_FIXED_VLBR: intel_set_masks(event, idx); break; default: pr_warn("Failed to enable the event with invalid index %d\n", idx); } } static void intel_pmu_add_event(struct perf_event *event) { if (event->attr.precise_ip) intel_pmu_pebs_add(event); if (needs_branch_stack(event)) intel_pmu_lbr_add(event); } /* * Save and restart an expired event. Called by NMI contexts, * so it has to be careful about preempting normal event ops: */ int intel_pmu_save_and_restart(struct perf_event *event) { static_call(x86_pmu_update)(event); /* * For a checkpointed counter always reset back to 0. This * avoids a situation where the counter overflows, aborts the * transaction and is then set back to shortly before the * overflow, and overflows and aborts again. */ if (unlikely(event_is_checkpointed(event))) { /* No race with NMIs because the counter should not be armed */ wrmsrl(event->hw.event_base, 0); local64_set(&event->hw.prev_count, 0); } return static_call(x86_pmu_set_period)(event); } static int intel_pmu_set_period(struct perf_event *event) { if (unlikely(is_topdown_count(event))) return static_call(intel_pmu_set_topdown_event_period)(event); return x86_perf_event_set_period(event); } static u64 intel_pmu_update(struct perf_event *event) { if (unlikely(is_topdown_count(event))) return static_call(intel_pmu_update_topdown_event)(event); return x86_perf_event_update(event); } static void intel_pmu_reset(void) { struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds); struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int num_counters_fixed = hybrid(cpuc->pmu, num_counters_fixed); int num_counters = hybrid(cpuc->pmu, num_counters); unsigned long flags; int idx; if (!num_counters) return; local_irq_save(flags); pr_info("clearing PMU state on CPU#%d\n", smp_processor_id()); for (idx = 0; idx < num_counters; idx++) { wrmsrl_safe(x86_pmu_config_addr(idx), 0ull); wrmsrl_safe(x86_pmu_event_addr(idx), 0ull); } for (idx = 0; idx < num_counters_fixed; idx++) { if (fixed_counter_disabled(idx, cpuc->pmu)) continue; wrmsrl_safe(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, 0ull); } if (ds) ds->bts_index = ds->bts_buffer_base; /* Ack all overflows and disable fixed counters */ if (x86_pmu.version >= 2) { intel_pmu_ack_status(intel_pmu_get_status()); wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0); } /* Reset LBRs and LBR freezing */ if (x86_pmu.lbr_nr) { update_debugctlmsr(get_debugctlmsr() & ~(DEBUGCTLMSR_FREEZE_LBRS_ON_PMI|DEBUGCTLMSR_LBR)); } local_irq_restore(flags); } /* * We may be running with guest PEBS events created by KVM, and the * PEBS records are logged into the guest's DS and invisible to host. * * In the case of guest PEBS overflow, we only trigger a fake event * to emulate the PEBS overflow PMI for guest PEBS counters in KVM. * The guest will then vm-entry and check the guest DS area to read * the guest PEBS records. * * The contents and other behavior of the guest event do not matter. */ static void x86_pmu_handle_guest_pebs(struct pt_regs *regs, struct perf_sample_data *data) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); u64 guest_pebs_idxs = cpuc->pebs_enabled & ~cpuc->intel_ctrl_host_mask; struct perf_event *event = NULL; int bit; if (!unlikely(perf_guest_state())) return; if (!x86_pmu.pebs_ept || !x86_pmu.pebs_active || !guest_pebs_idxs) return; for_each_set_bit(bit, (unsigned long *)&guest_pebs_idxs, INTEL_PMC_IDX_FIXED + x86_pmu.num_counters_fixed) { event = cpuc->events[bit]; if (!event->attr.precise_ip) continue; perf_sample_data_init(data, 0, event->hw.last_period); if (perf_event_overflow(event, data, regs)) x86_pmu_stop(event, 0); /* Inject one fake event is enough. */ break; } } static int handle_pmi_common(struct pt_regs *regs, u64 status) { struct perf_sample_data data; struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int bit; int handled = 0; u64 intel_ctrl = hybrid(cpuc->pmu, intel_ctrl); inc_irq_stat(apic_perf_irqs); /* * Ignore a range of extra bits in status that do not indicate * overflow by themselves. */ status &= ~(GLOBAL_STATUS_COND_CHG | GLOBAL_STATUS_ASIF | GLOBAL_STATUS_LBRS_FROZEN); if (!status) return 0; /* * In case multiple PEBS events are sampled at the same time, * it is possible to have GLOBAL_STATUS bit 62 set indicating * PEBS buffer overflow and also seeing at most 3 PEBS counters * having their bits set in the status register. This is a sign * that there was at least one PEBS record pending at the time * of the PMU interrupt. PEBS counters must only be processed * via the drain_pebs() calls and not via the regular sample * processing loop coming after that the function, otherwise * phony regular samples may be generated in the sampling buffer * not marked with the EXACT tag. Another possibility is to have * one PEBS event and at least one non-PEBS event which overflows * while PEBS has armed. In this case, bit 62 of GLOBAL_STATUS will * not be set, yet the overflow status bit for the PEBS counter will * be on Skylake. * * To avoid this problem, we systematically ignore the PEBS-enabled * counters from the GLOBAL_STATUS mask and we always process PEBS * events via drain_pebs(). */ status &= ~(cpuc->pebs_enabled & x86_pmu.pebs_capable); /* * PEBS overflow sets bit 62 in the global status register */ if (__test_and_clear_bit(GLOBAL_STATUS_BUFFER_OVF_BIT, (unsigned long *)&status)) { u64 pebs_enabled = cpuc->pebs_enabled; handled++; x86_pmu_handle_guest_pebs(regs, &data); x86_pmu.drain_pebs(regs, &data); status &= intel_ctrl | GLOBAL_STATUS_TRACE_TOPAPMI; /* * PMI throttle may be triggered, which stops the PEBS event. * Although cpuc->pebs_enabled is updated accordingly, the * MSR_IA32_PEBS_ENABLE is not updated. Because the * cpuc->enabled has been forced to 0 in PMI. * Update the MSR if pebs_enabled is changed. */ if (pebs_enabled != cpuc->pebs_enabled) wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled); } /* * Intel PT */ if (__test_and_clear_bit(GLOBAL_STATUS_TRACE_TOPAPMI_BIT, (unsigned long *)&status)) { handled++; if (!perf_guest_handle_intel_pt_intr()) intel_pt_interrupt(); } /* * Intel Perf metrics */ if (__test_and_clear_bit(GLOBAL_STATUS_PERF_METRICS_OVF_BIT, (unsigned long *)&status)) { handled++; static_call(intel_pmu_update_topdown_event)(NULL); } /* * Checkpointed counters can lead to 'spurious' PMIs because the * rollback caused by the PMI will have cleared the overflow status * bit. Therefore always force probe these counters. */ status |= cpuc->intel_cp_status; for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) { struct perf_event *event = cpuc->events[bit]; handled++; if (!test_bit(bit, cpuc->active_mask)) continue; if (!intel_pmu_save_and_restart(event)) continue; perf_sample_data_init(&data, 0, event->hw.last_period); if (has_branch_stack(event)) perf_sample_save_brstack(&data, event, &cpuc->lbr_stack); if (perf_event_overflow(event, &data, regs)) x86_pmu_stop(event, 0); } return handled; } /* * This handler is triggered by the local APIC, so the APIC IRQ handling * rules apply: */ static int intel_pmu_handle_irq(struct pt_regs *regs) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); bool late_ack = hybrid_bit(cpuc->pmu, late_ack); bool mid_ack = hybrid_bit(cpuc->pmu, mid_ack); int loops; u64 status; int handled; int pmu_enabled; /* * Save the PMU state. * It needs to be restored when leaving the handler. */ pmu_enabled = cpuc->enabled; /* * In general, the early ACK is only applied for old platforms. * For the big core starts from Haswell, the late ACK should be * applied. * For the small core after Tremont, we have to do the ACK right * before re-enabling counters, which is in the middle of the * NMI handler. */ if (!late_ack && !mid_ack) apic_write(APIC_LVTPC, APIC_DM_NMI); intel_bts_disable_local(); cpuc->enabled = 0; __intel_pmu_disable_all(true); handled = intel_pmu_drain_bts_buffer(); handled += intel_bts_interrupt(); status = intel_pmu_get_status(); if (!status) goto done; loops = 0; again: intel_pmu_lbr_read(); intel_pmu_ack_status(status); if (++loops > 100) { static bool warned; if (!warned) { WARN(1, "perfevents: irq loop stuck!\n"); perf_event_print_debug(); warned = true; } intel_pmu_reset(); goto done; } handled += handle_pmi_common(regs, status); /* * Repeat if there is more work to be done: */ status = intel_pmu_get_status(); if (status) goto again; done: if (mid_ack) apic_write(APIC_LVTPC, APIC_DM_NMI); /* Only restore PMU state when it's active. See x86_pmu_disable(). */ cpuc->enabled = pmu_enabled; if (pmu_enabled) __intel_pmu_enable_all(0, true); intel_bts_enable_local(); /* * Only unmask the NMI after the overflow counters * have been reset. This avoids spurious NMIs on * Haswell CPUs. */ if (late_ack) apic_write(APIC_LVTPC, APIC_DM_NMI); return handled; } static struct event_constraint * intel_bts_constraints(struct perf_event *event) { if (unlikely(intel_pmu_has_bts(event))) return &bts_constraint; return NULL; } /* * Note: matches a fake event, like Fixed2. */ static struct event_constraint * intel_vlbr_constraints(struct perf_event *event) { struct event_constraint *c = &vlbr_constraint; if (unlikely(constraint_match(c, event->hw.config))) { event->hw.flags |= c->flags; return c; } return NULL; } static int intel_alt_er(struct cpu_hw_events *cpuc, int idx, u64 config) { struct extra_reg *extra_regs = hybrid(cpuc->pmu, extra_regs); int alt_idx = idx; if (!(x86_pmu.flags & PMU_FL_HAS_RSP_1)) return idx; if (idx == EXTRA_REG_RSP_0) alt_idx = EXTRA_REG_RSP_1; if (idx == EXTRA_REG_RSP_1) alt_idx = EXTRA_REG_RSP_0; if (config & ~extra_regs[alt_idx].valid_mask) return idx; return alt_idx; } static void intel_fixup_er(struct perf_event *event, int idx) { struct extra_reg *extra_regs = hybrid(event->pmu, extra_regs); event->hw.extra_reg.idx = idx; if (idx == EXTRA_REG_RSP_0) { event->hw.config &= ~INTEL_ARCH_EVENT_MASK; event->hw.config |= extra_regs[EXTRA_REG_RSP_0].event; event->hw.extra_reg.reg = MSR_OFFCORE_RSP_0; } else if (idx == EXTRA_REG_RSP_1) { event->hw.config &= ~INTEL_ARCH_EVENT_MASK; event->hw.config |= extra_regs[EXTRA_REG_RSP_1].event; event->hw.extra_reg.reg = MSR_OFFCORE_RSP_1; } } /* * manage allocation of shared extra msr for certain events * * sharing can be: * per-cpu: to be shared between the various events on a single PMU * per-core: per-cpu + shared by HT threads */ static struct event_constraint * __intel_shared_reg_get_constraints(struct cpu_hw_events *cpuc, struct perf_event *event, struct hw_perf_event_extra *reg) { struct event_constraint *c = &emptyconstraint; struct er_account *era; unsigned long flags; int idx = reg->idx; /* * reg->alloc can be set due to existing state, so for fake cpuc we * need to ignore this, otherwise we might fail to allocate proper fake * state for this extra reg constraint. Also see the comment below. */ if (reg->alloc && !cpuc->is_fake) return NULL; /* call x86_get_event_constraint() */ again: era = &cpuc->shared_regs->regs[idx]; /* * we use spin_lock_irqsave() to avoid lockdep issues when * passing a fake cpuc */ raw_spin_lock_irqsave(&era->lock, flags); if (!atomic_read(&era->ref) || era->config == reg->config) { /* * If its a fake cpuc -- as per validate_{group,event}() we * shouldn't touch event state and we can avoid doing so * since both will only call get_event_constraints() once * on each event, this avoids the need for reg->alloc. * * Not doing the ER fixup will only result in era->reg being * wrong, but since we won't actually try and program hardware * this isn't a problem either. */ if (!cpuc->is_fake) { if (idx != reg->idx) intel_fixup_er(event, idx); /* * x86_schedule_events() can call get_event_constraints() * multiple times on events in the case of incremental * scheduling(). reg->alloc ensures we only do the ER * allocation once. */ reg->alloc = 1; } /* lock in msr value */ era->config = reg->config; era->reg = reg->reg; /* one more user */ atomic_inc(&era->ref); /* * need to call x86_get_event_constraint() * to check if associated event has constraints */ c = NULL; } else { idx = intel_alt_er(cpuc, idx, reg->config); if (idx != reg->idx) { raw_spin_unlock_irqrestore(&era->lock, flags); goto again; } } raw_spin_unlock_irqrestore(&era->lock, flags); return c; } static void __intel_shared_reg_put_constraints(struct cpu_hw_events *cpuc, struct hw_perf_event_extra *reg) { struct er_account *era; /* * Only put constraint if extra reg was actually allocated. Also takes * care of event which do not use an extra shared reg. * * Also, if this is a fake cpuc we shouldn't touch any event state * (reg->alloc) and we don't care about leaving inconsistent cpuc state * either since it'll be thrown out. */ if (!reg->alloc || cpuc->is_fake) return; era = &cpuc->shared_regs->regs[reg->idx]; /* one fewer user */ atomic_dec(&era->ref); /* allocate again next time */ reg->alloc = 0; } static struct event_constraint * intel_shared_regs_constraints(struct cpu_hw_events *cpuc, struct perf_event *event) { struct event_constraint *c = NULL, *d; struct hw_perf_event_extra *xreg, *breg; xreg = &event->hw.extra_reg; if (xreg->idx != EXTRA_REG_NONE) { c = __intel_shared_reg_get_constraints(cpuc, event, xreg); if (c == &emptyconstraint) return c; } breg = &event->hw.branch_reg; if (breg->idx != EXTRA_REG_NONE) { d = __intel_shared_reg_get_constraints(cpuc, event, breg); if (d == &emptyconstraint) { __intel_shared_reg_put_constraints(cpuc, xreg); c = d; } } return c; } struct event_constraint * x86_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *event_constraints = hybrid(cpuc->pmu, event_constraints); struct event_constraint *c; if (event_constraints) { for_each_event_constraint(c, event_constraints) { if (constraint_match(c, event->hw.config)) { event->hw.flags |= c->flags; return c; } } } return &hybrid_var(cpuc->pmu, unconstrained); } static struct event_constraint * __intel_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; c = intel_vlbr_constraints(event); if (c) return c; c = intel_bts_constraints(event); if (c) return c; c = intel_shared_regs_constraints(cpuc, event); if (c) return c; c = intel_pebs_constraints(event); if (c) return c; return x86_get_event_constraints(cpuc, idx, event); } static void intel_start_scheduling(struct cpu_hw_events *cpuc) { struct intel_excl_cntrs *excl_cntrs = cpuc->excl_cntrs; struct intel_excl_states *xl; int tid = cpuc->excl_thread_id; /* * nothing needed if in group validation mode */ if (cpuc->is_fake || !is_ht_workaround_enabled()) return; /* * no exclusion needed */ if (WARN_ON_ONCE(!excl_cntrs)) return; xl = &excl_cntrs->states[tid]; xl->sched_started = true; /* * lock shared state until we are done scheduling * in stop_event_scheduling() * makes scheduling appear as a transaction */ raw_spin_lock(&excl_cntrs->lock); } static void intel_commit_scheduling(struct cpu_hw_events *cpuc, int idx, int cntr) { struct intel_excl_cntrs *excl_cntrs = cpuc->excl_cntrs; struct event_constraint *c = cpuc->event_constraint[idx]; struct intel_excl_states *xl; int tid = cpuc->excl_thread_id; if (cpuc->is_fake || !is_ht_workaround_enabled()) return; if (WARN_ON_ONCE(!excl_cntrs)) return; if (!(c->flags & PERF_X86_EVENT_DYNAMIC)) return; xl = &excl_cntrs->states[tid]; lockdep_assert_held(&excl_cntrs->lock); if (c->flags & PERF_X86_EVENT_EXCL) xl->state[cntr] = INTEL_EXCL_EXCLUSIVE; else xl->state[cntr] = INTEL_EXCL_SHARED; } static void intel_stop_scheduling(struct cpu_hw_events *cpuc) { struct intel_excl_cntrs *excl_cntrs = cpuc->excl_cntrs; struct intel_excl_states *xl; int tid = cpuc->excl_thread_id; /* * nothing needed if in group validation mode */ if (cpuc->is_fake || !is_ht_workaround_enabled()) return; /* * no exclusion needed */ if (WARN_ON_ONCE(!excl_cntrs)) return; xl = &excl_cntrs->states[tid]; xl->sched_started = false; /* * release shared state lock (acquired in intel_start_scheduling()) */ raw_spin_unlock(&excl_cntrs->lock); } static struct event_constraint * dyn_constraint(struct cpu_hw_events *cpuc, struct event_constraint *c, int idx) { WARN_ON_ONCE(!cpuc->constraint_list); if (!(c->flags & PERF_X86_EVENT_DYNAMIC)) { struct event_constraint *cx; /* * grab pre-allocated constraint entry */ cx = &cpuc->constraint_list[idx]; /* * initialize dynamic constraint * with static constraint */ *cx = *c; /* * mark constraint as dynamic */ cx->flags |= PERF_X86_EVENT_DYNAMIC; c = cx; } return c; } static struct event_constraint * intel_get_excl_constraints(struct cpu_hw_events *cpuc, struct perf_event *event, int idx, struct event_constraint *c) { struct intel_excl_cntrs *excl_cntrs = cpuc->excl_cntrs; struct intel_excl_states *xlo; int tid = cpuc->excl_thread_id; int is_excl, i, w; /* * validating a group does not require * enforcing cross-thread exclusion */ if (cpuc->is_fake || !is_ht_workaround_enabled()) return c; /* * no exclusion needed */ if (WARN_ON_ONCE(!excl_cntrs)) return c; /* * because we modify the constraint, we need * to make a copy. Static constraints come * from static const tables. * * only needed when constraint has not yet * been cloned (marked dynamic) */ c = dyn_constraint(cpuc, c, idx); /* * From here on, the constraint is dynamic. * Either it was just allocated above, or it * was allocated during a earlier invocation * of this function */ /* * state of sibling HT */ xlo = &excl_cntrs->states[tid ^ 1]; /* * event requires exclusive counter access * across HT threads */ is_excl = c->flags & PERF_X86_EVENT_EXCL; if (is_excl && !(event->hw.flags & PERF_X86_EVENT_EXCL_ACCT)) { event->hw.flags |= PERF_X86_EVENT_EXCL_ACCT; if (!cpuc->n_excl++) WRITE_ONCE(excl_cntrs->has_exclusive[tid], 1); } /* * Modify static constraint with current dynamic * state of thread * * EXCLUSIVE: sibling counter measuring exclusive event * SHARED : sibling counter measuring non-exclusive event * UNUSED : sibling counter unused */ w = c->weight; for_each_set_bit(i, c->idxmsk, X86_PMC_IDX_MAX) { /* * exclusive event in sibling counter * our corresponding counter cannot be used * regardless of our event */ if (xlo->state[i] == INTEL_EXCL_EXCLUSIVE) { __clear_bit(i, c->idxmsk); w--; continue; } /* * if measuring an exclusive event, sibling * measuring non-exclusive, then counter cannot * be used */ if (is_excl && xlo->state[i] == INTEL_EXCL_SHARED) { __clear_bit(i, c->idxmsk); w--; continue; } } /* * if we return an empty mask, then switch * back to static empty constraint to avoid * the cost of freeing later on */ if (!w) c = &emptyconstraint; c->weight = w; return c; } static struct event_constraint * intel_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c1, *c2; c1 = cpuc->event_constraint[idx]; /* * first time only * - static constraint: no change across incremental scheduling calls * - dynamic constraint: handled by intel_get_excl_constraints() */ c2 = __intel_get_event_constraints(cpuc, idx, event); if (c1) { WARN_ON_ONCE(!(c1->flags & PERF_X86_EVENT_DYNAMIC)); bitmap_copy(c1->idxmsk, c2->idxmsk, X86_PMC_IDX_MAX); c1->weight = c2->weight; c2 = c1; } if (cpuc->excl_cntrs) return intel_get_excl_constraints(cpuc, event, idx, c2); return c2; } static void intel_put_excl_constraints(struct cpu_hw_events *cpuc, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct intel_excl_cntrs *excl_cntrs = cpuc->excl_cntrs; int tid = cpuc->excl_thread_id; struct intel_excl_states *xl; /* * nothing needed if in group validation mode */ if (cpuc->is_fake) return; if (WARN_ON_ONCE(!excl_cntrs)) return; if (hwc->flags & PERF_X86_EVENT_EXCL_ACCT) { hwc->flags &= ~PERF_X86_EVENT_EXCL_ACCT; if (!--cpuc->n_excl) WRITE_ONCE(excl_cntrs->has_exclusive[tid], 0); } /* * If event was actually assigned, then mark the counter state as * unused now. */ if (hwc->idx >= 0) { xl = &excl_cntrs->states[tid]; /* * put_constraint may be called from x86_schedule_events() * which already has the lock held so here make locking * conditional. */ if (!xl->sched_started) raw_spin_lock(&excl_cntrs->lock); xl->state[hwc->idx] = INTEL_EXCL_UNUSED; if (!xl->sched_started) raw_spin_unlock(&excl_cntrs->lock); } } static void intel_put_shared_regs_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event) { struct hw_perf_event_extra *reg; reg = &event->hw.extra_reg; if (reg->idx != EXTRA_REG_NONE) __intel_shared_reg_put_constraints(cpuc, reg); reg = &event->hw.branch_reg; if (reg->idx != EXTRA_REG_NONE) __intel_shared_reg_put_constraints(cpuc, reg); } static void intel_put_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event) { intel_put_shared_regs_event_constraints(cpuc, event); /* * is PMU has exclusive counter restrictions, then * all events are subject to and must call the * put_excl_constraints() routine */ if (cpuc->excl_cntrs) intel_put_excl_constraints(cpuc, event); } static void intel_pebs_aliases_core2(struct perf_event *event) { if ((event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) { /* * Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P * (0x003c) so that we can use it with PEBS. * * The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't * PEBS capable. However we can use INST_RETIRED.ANY_P * (0x00c0), which is a PEBS capable event, to get the same * count. * * INST_RETIRED.ANY_P counts the number of cycles that retires * CNTMASK instructions. By setting CNTMASK to a value (16) * larger than the maximum number of instructions that can be * retired per cycle (4) and then inverting the condition, we * count all cycles that retire 16 or less instructions, which * is every cycle. * * Thereby we gain a PEBS capable cycle counter. */ u64 alt_config = X86_CONFIG(.event=0xc0, .inv=1, .cmask=16); alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK); event->hw.config = alt_config; } } static void intel_pebs_aliases_snb(struct perf_event *event) { if ((event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) { /* * Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P * (0x003c) so that we can use it with PEBS. * * The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't * PEBS capable. However we can use UOPS_RETIRED.ALL * (0x01c2), which is a PEBS capable event, to get the same * count. * * UOPS_RETIRED.ALL counts the number of cycles that retires * CNTMASK micro-ops. By setting CNTMASK to a value (16) * larger than the maximum number of micro-ops that can be * retired per cycle (4) and then inverting the condition, we * count all cycles that retire 16 or less micro-ops, which * is every cycle. * * Thereby we gain a PEBS capable cycle counter. */ u64 alt_config = X86_CONFIG(.event=0xc2, .umask=0x01, .inv=1, .cmask=16); alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK); event->hw.config = alt_config; } } static void intel_pebs_aliases_precdist(struct perf_event *event) { if ((event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) { /* * Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P * (0x003c) so that we can use it with PEBS. * * The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't * PEBS capable. However we can use INST_RETIRED.PREC_DIST * (0x01c0), which is a PEBS capable event, to get the same * count. * * The PREC_DIST event has special support to minimize sample * shadowing effects. One drawback is that it can be * only programmed on counter 1, but that seems like an * acceptable trade off. */ u64 alt_config = X86_CONFIG(.event=0xc0, .umask=0x01, .inv=1, .cmask=16); alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK); event->hw.config = alt_config; } } static void intel_pebs_aliases_ivb(struct perf_event *event) { if (event->attr.precise_ip < 3) return intel_pebs_aliases_snb(event); return intel_pebs_aliases_precdist(event); } static void intel_pebs_aliases_skl(struct perf_event *event) { if (event->attr.precise_ip < 3) return intel_pebs_aliases_core2(event); return intel_pebs_aliases_precdist(event); } static unsigned long intel_pmu_large_pebs_flags(struct perf_event *event) { unsigned long flags = x86_pmu.large_pebs_flags; if (event->attr.use_clockid) flags &= ~PERF_SAMPLE_TIME; if (!event->attr.exclude_kernel) flags &= ~PERF_SAMPLE_REGS_USER; if (event->attr.sample_regs_user & ~PEBS_GP_REGS) flags &= ~(PERF_SAMPLE_REGS_USER | PERF_SAMPLE_REGS_INTR); return flags; } static int intel_pmu_bts_config(struct perf_event *event) { struct perf_event_attr *attr = &event->attr; if (unlikely(intel_pmu_has_bts(event))) { /* BTS is not supported by this architecture. */ if (!x86_pmu.bts_active) return -EOPNOTSUPP; /* BTS is currently only allowed for user-mode. */ if (!attr->exclude_kernel) return -EOPNOTSUPP; /* BTS is not allowed for precise events. */ if (attr->precise_ip) return -EOPNOTSUPP; /* disallow bts if conflicting events are present */ if (x86_add_exclusive(x86_lbr_exclusive_lbr)) return -EBUSY; event->destroy = hw_perf_lbr_event_destroy; } return 0; } static int core_pmu_hw_config(struct perf_event *event) { int ret = x86_pmu_hw_config(event); if (ret) return ret; return intel_pmu_bts_config(event); } #define INTEL_TD_METRIC_AVAILABLE_MAX (INTEL_TD_METRIC_RETIRING + \ ((x86_pmu.num_topdown_events - 1) << 8)) static bool is_available_metric_event(struct perf_event *event) { return is_metric_event(event) && event->attr.config <= INTEL_TD_METRIC_AVAILABLE_MAX; } static inline bool is_mem_loads_event(struct perf_event *event) { return (event->attr.config & INTEL_ARCH_EVENT_MASK) == X86_CONFIG(.event=0xcd, .umask=0x01); } static inline bool is_mem_loads_aux_event(struct perf_event *event) { return (event->attr.config & INTEL_ARCH_EVENT_MASK) == X86_CONFIG(.event=0x03, .umask=0x82); } static inline bool require_mem_loads_aux_event(struct perf_event *event) { if (!(x86_pmu.flags & PMU_FL_MEM_LOADS_AUX)) return false; if (is_hybrid()) return hybrid_pmu(event->pmu)->cpu_type == hybrid_big; return true; } static inline bool intel_pmu_has_cap(struct perf_event *event, int idx) { union perf_capabilities *intel_cap = &hybrid(event->pmu, intel_cap); return test_bit(idx, (unsigned long *)&intel_cap->capabilities); } static int intel_pmu_hw_config(struct perf_event *event) { int ret = x86_pmu_hw_config(event); if (ret) return ret; ret = intel_pmu_bts_config(event); if (ret) return ret; if (event->attr.precise_ip) { if ((event->attr.config & INTEL_ARCH_EVENT_MASK) == INTEL_FIXED_VLBR_EVENT) return -EINVAL; if (!(event->attr.freq || (event->attr.wakeup_events && !event->attr.watermark))) { event->hw.flags |= PERF_X86_EVENT_AUTO_RELOAD; if (!(event->attr.sample_type & ~intel_pmu_large_pebs_flags(event))) { event->hw.flags |= PERF_X86_EVENT_LARGE_PEBS; event->attach_state |= PERF_ATTACH_SCHED_CB; } } if (x86_pmu.pebs_aliases) x86_pmu.pebs_aliases(event); } if (needs_branch_stack(event)) { ret = intel_pmu_setup_lbr_filter(event); if (ret) return ret; event->attach_state |= PERF_ATTACH_SCHED_CB; /* * BTS is set up earlier in this path, so don't account twice */ if (!unlikely(intel_pmu_has_bts(event))) { /* disallow lbr if conflicting events are present */ if (x86_add_exclusive(x86_lbr_exclusive_lbr)) return -EBUSY; event->destroy = hw_perf_lbr_event_destroy; } } if (event->attr.aux_output) { if (!event->attr.precise_ip) return -EINVAL; event->hw.flags |= PERF_X86_EVENT_PEBS_VIA_PT; } if ((event->attr.type == PERF_TYPE_HARDWARE) || (event->attr.type == PERF_TYPE_HW_CACHE)) return 0; /* * Config Topdown slots and metric events * * The slots event on Fixed Counter 3 can support sampling, * which will be handled normally in x86_perf_event_update(). * * Metric events don't support sampling and require being paired * with a slots event as group leader. When the slots event * is used in a metrics group, it too cannot support sampling. */ if (intel_pmu_has_cap(event, PERF_CAP_METRICS_IDX) && is_topdown_event(event)) { if (event->attr.config1 || event->attr.config2) return -EINVAL; /* * The TopDown metrics events and slots event don't * support any filters. */ if (event->attr.config & X86_ALL_EVENT_FLAGS) return -EINVAL; if (is_available_metric_event(event)) { struct perf_event *leader = event->group_leader; /* The metric events don't support sampling. */ if (is_sampling_event(event)) return -EINVAL; /* The metric events require a slots group leader. */ if (!is_slots_event(leader)) return -EINVAL; /* * The leader/SLOTS must not be a sampling event for * metric use; hardware requires it starts at 0 when used * in conjunction with MSR_PERF_METRICS. */ if (is_sampling_event(leader)) return -EINVAL; event->event_caps |= PERF_EV_CAP_SIBLING; /* * Only once we have a METRICs sibling do we * need TopDown magic. */ leader->hw.flags |= PERF_X86_EVENT_TOPDOWN; event->hw.flags |= PERF_X86_EVENT_TOPDOWN; } } /* * The load latency event X86_CONFIG(.event=0xcd, .umask=0x01) on SPR * doesn't function quite right. As a work-around it needs to always be * co-scheduled with a auxiliary event X86_CONFIG(.event=0x03, .umask=0x82). * The actual count of this second event is irrelevant it just needs * to be active to make the first event function correctly. * * In a group, the auxiliary event must be in front of the load latency * event. The rule is to simplify the implementation of the check. * That's because perf cannot have a complete group at the moment. */ if (require_mem_loads_aux_event(event) && (event->attr.sample_type & PERF_SAMPLE_DATA_SRC) && is_mem_loads_event(event)) { struct perf_event *leader = event->group_leader; struct perf_event *sibling = NULL; /* * When this memload event is also the first event (no group * exists yet), then there is no aux event before it. */ if (leader == event) return -ENODATA; if (!is_mem_loads_aux_event(leader)) { for_each_sibling_event(sibling, leader) { if (is_mem_loads_aux_event(sibling)) break; } if (list_entry_is_head(sibling, &leader->sibling_list, sibling_list)) return -ENODATA; } } if (!(event->attr.config & ARCH_PERFMON_EVENTSEL_ANY)) return 0; if (x86_pmu.version < 3) return -EINVAL; ret = perf_allow_cpu(&event->attr); if (ret) return ret; event->hw.config |= ARCH_PERFMON_EVENTSEL_ANY; return 0; } /* * Currently, the only caller of this function is the atomic_switch_perf_msrs(). * The host perf conext helps to prepare the values of the real hardware for * a set of msrs that need to be switched atomically in a vmx transaction. * * For example, the pseudocode needed to add a new msr should look like: * * arr[(*nr)++] = (struct perf_guest_switch_msr){ * .msr = the hardware msr address, * .host = the value the hardware has when it doesn't run a guest, * .guest = the value the hardware has when it runs a guest, * }; * * These values have nothing to do with the emulated values the guest sees * when it uses {RD,WR}MSR, which should be handled by the KVM context, * specifically in the intel_pmu_{get,set}_msr(). */ static struct perf_guest_switch_msr *intel_guest_get_msrs(int *nr, void *data) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs; struct kvm_pmu *kvm_pmu = (struct kvm_pmu *)data; u64 intel_ctrl = hybrid(cpuc->pmu, intel_ctrl); u64 pebs_mask = cpuc->pebs_enabled & x86_pmu.pebs_capable; int global_ctrl, pebs_enable; *nr = 0; global_ctrl = (*nr)++; arr[global_ctrl] = (struct perf_guest_switch_msr){ .msr = MSR_CORE_PERF_GLOBAL_CTRL, .host = intel_ctrl & ~cpuc->intel_ctrl_guest_mask, .guest = intel_ctrl & (~cpuc->intel_ctrl_host_mask | ~pebs_mask), }; if (!x86_pmu.pebs) return arr; /* * If PMU counter has PEBS enabled it is not enough to * disable counter on a guest entry since PEBS memory * write can overshoot guest entry and corrupt guest * memory. Disabling PEBS solves the problem. * * Don't do this if the CPU already enforces it. */ if (x86_pmu.pebs_no_isolation) { arr[(*nr)++] = (struct perf_guest_switch_msr){ .msr = MSR_IA32_PEBS_ENABLE, .host = cpuc->pebs_enabled, .guest = 0, }; return arr; } if (!kvm_pmu || !x86_pmu.pebs_ept) return arr; arr[(*nr)++] = (struct perf_guest_switch_msr){ .msr = MSR_IA32_DS_AREA, .host = (unsigned long)cpuc->ds, .guest = kvm_pmu->ds_area, }; if (x86_pmu.intel_cap.pebs_baseline) { arr[(*nr)++] = (struct perf_guest_switch_msr){ .msr = MSR_PEBS_DATA_CFG, .host = cpuc->active_pebs_data_cfg, .guest = kvm_pmu->pebs_data_cfg, }; } pebs_enable = (*nr)++; arr[pebs_enable] = (struct perf_guest_switch_msr){ .msr = MSR_IA32_PEBS_ENABLE, .host = cpuc->pebs_enabled & ~cpuc->intel_ctrl_guest_mask, .guest = pebs_mask & ~cpuc->intel_ctrl_host_mask, }; if (arr[pebs_enable].host) { /* Disable guest PEBS if host PEBS is enabled. */ arr[pebs_enable].guest = 0; } else { /* Disable guest PEBS thoroughly for cross-mapped PEBS counters. */ arr[pebs_enable].guest &= ~kvm_pmu->host_cross_mapped_mask; arr[global_ctrl].guest &= ~kvm_pmu->host_cross_mapped_mask; /* Set hw GLOBAL_CTRL bits for PEBS counter when it runs for guest */ arr[global_ctrl].guest |= arr[pebs_enable].guest; } return arr; } static struct perf_guest_switch_msr *core_guest_get_msrs(int *nr, void *data) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs; int idx; for (idx = 0; idx < x86_pmu.num_counters; idx++) { struct perf_event *event = cpuc->events[idx]; arr[idx].msr = x86_pmu_config_addr(idx); arr[idx].host = arr[idx].guest = 0; if (!test_bit(idx, cpuc->active_mask)) continue; arr[idx].host = arr[idx].guest = event->hw.config | ARCH_PERFMON_EVENTSEL_ENABLE; if (event->attr.exclude_host) arr[idx].host &= ~ARCH_PERFMON_EVENTSEL_ENABLE; else if (event->attr.exclude_guest) arr[idx].guest &= ~ARCH_PERFMON_EVENTSEL_ENABLE; } *nr = x86_pmu.num_counters; return arr; } static void core_pmu_enable_event(struct perf_event *event) { if (!event->attr.exclude_host) x86_pmu_enable_event(event); } static void core_pmu_enable_all(int added) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int idx; for (idx = 0; idx < x86_pmu.num_counters; idx++) { struct hw_perf_event *hwc = &cpuc->events[idx]->hw; if (!test_bit(idx, cpuc->active_mask) || cpuc->events[idx]->attr.exclude_host) continue; __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE); } } static int hsw_hw_config(struct perf_event *event) { int ret = intel_pmu_hw_config(event); if (ret) return ret; if (!boot_cpu_has(X86_FEATURE_RTM) && !boot_cpu_has(X86_FEATURE_HLE)) return 0; event->hw.config |= event->attr.config & (HSW_IN_TX|HSW_IN_TX_CHECKPOINTED); /* * IN_TX/IN_TX-CP filters are not supported by the Haswell PMU with * PEBS or in ANY thread mode. Since the results are non-sensical forbid * this combination. */ if ((event->hw.config & (HSW_IN_TX|HSW_IN_TX_CHECKPOINTED)) && ((event->hw.config & ARCH_PERFMON_EVENTSEL_ANY) || event->attr.precise_ip > 0)) return -EOPNOTSUPP; if (event_is_checkpointed(event)) { /* * Sampling of checkpointed events can cause situations where * the CPU constantly aborts because of a overflow, which is * then checkpointed back and ignored. Forbid checkpointing * for sampling. * * But still allow a long sampling period, so that perf stat * from KVM works. */ if (event->attr.sample_period > 0 && event->attr.sample_period < 0x7fffffff) return -EOPNOTSUPP; } return 0; } static struct event_constraint counter0_constraint = INTEL_ALL_EVENT_CONSTRAINT(0, 0x1); static struct event_constraint counter1_constraint = INTEL_ALL_EVENT_CONSTRAINT(0, 0x2); static struct event_constraint counter0_1_constraint = INTEL_ALL_EVENT_CONSTRAINT(0, 0x3); static struct event_constraint counter2_constraint = EVENT_CONSTRAINT(0, 0x4, 0); static struct event_constraint fixed0_constraint = FIXED_EVENT_CONSTRAINT(0x00c0, 0); static struct event_constraint fixed0_counter0_constraint = INTEL_ALL_EVENT_CONSTRAINT(0, 0x100000001ULL); static struct event_constraint fixed0_counter0_1_constraint = INTEL_ALL_EVENT_CONSTRAINT(0, 0x100000003ULL); static struct event_constraint counters_1_7_constraint = INTEL_ALL_EVENT_CONSTRAINT(0, 0xfeULL); static struct event_constraint * hsw_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; c = intel_get_event_constraints(cpuc, idx, event); /* Handle special quirk on in_tx_checkpointed only in counter 2 */ if (event->hw.config & HSW_IN_TX_CHECKPOINTED) { if (c->idxmsk64 & (1U << 2)) return &counter2_constraint; return &emptyconstraint; } return c; } static struct event_constraint * icl_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { /* * Fixed counter 0 has less skid. * Force instruction:ppp in Fixed counter 0 */ if ((event->attr.precise_ip == 3) && constraint_match(&fixed0_constraint, event->hw.config)) return &fixed0_constraint; return hsw_get_event_constraints(cpuc, idx, event); } static struct event_constraint * spr_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; c = icl_get_event_constraints(cpuc, idx, event); /* * The :ppp indicates the Precise Distribution (PDist) facility, which * is only supported on the GP counter 0. If a :ppp event which is not * available on the GP counter 0, error out. * Exception: Instruction PDIR is only available on the fixed counter 0. */ if ((event->attr.precise_ip == 3) && !constraint_match(&fixed0_constraint, event->hw.config)) { if (c->idxmsk64 & BIT_ULL(0)) return &counter0_constraint; return &emptyconstraint; } return c; } static struct event_constraint * glp_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; /* :ppp means to do reduced skid PEBS which is PMC0 only. */ if (event->attr.precise_ip == 3) return &counter0_constraint; c = intel_get_event_constraints(cpuc, idx, event); return c; } static struct event_constraint * tnt_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; c = intel_get_event_constraints(cpuc, idx, event); /* * :ppp means to do reduced skid PEBS, * which is available on PMC0 and fixed counter 0. */ if (event->attr.precise_ip == 3) { /* Force instruction:ppp on PMC0 and Fixed counter 0 */ if (constraint_match(&fixed0_constraint, event->hw.config)) return &fixed0_counter0_constraint; return &counter0_constraint; } return c; } static bool allow_tsx_force_abort = true; static struct event_constraint * tfa_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c = hsw_get_event_constraints(cpuc, idx, event); /* * Without TFA we must not use PMC3. */ if (!allow_tsx_force_abort && test_bit(3, c->idxmsk)) { c = dyn_constraint(cpuc, c, idx); c->idxmsk64 &= ~(1ULL << 3); c->weight--; } return c; } static struct event_constraint * adl_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct x86_hybrid_pmu *pmu = hybrid_pmu(event->pmu); if (pmu->cpu_type == hybrid_big) return spr_get_event_constraints(cpuc, idx, event); else if (pmu->cpu_type == hybrid_small) return tnt_get_event_constraints(cpuc, idx, event); WARN_ON(1); return &emptyconstraint; } static struct event_constraint * cmt_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; c = intel_get_event_constraints(cpuc, idx, event); /* * The :ppp indicates the Precise Distribution (PDist) facility, which * is only supported on the GP counter 0 & 1 and Fixed counter 0. * If a :ppp event which is not available on the above eligible counters, * error out. */ if (event->attr.precise_ip == 3) { /* Force instruction:ppp on PMC0, 1 and Fixed counter 0 */ if (constraint_match(&fixed0_constraint, event->hw.config)) return &fixed0_counter0_1_constraint; switch (c->idxmsk64 & 0x3ull) { case 0x1: return &counter0_constraint; case 0x2: return &counter1_constraint; case 0x3: return &counter0_1_constraint; } return &emptyconstraint; } return c; } static struct event_constraint * rwc_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; c = spr_get_event_constraints(cpuc, idx, event); /* The Retire Latency is not supported by the fixed counter 0. */ if (event->attr.precise_ip && (event->attr.sample_type & PERF_SAMPLE_WEIGHT_TYPE) && constraint_match(&fixed0_constraint, event->hw.config)) { /* * The Instruction PDIR is only available * on the fixed counter 0. Error out for this case. */ if (event->attr.precise_ip == 3) return &emptyconstraint; return &counters_1_7_constraint; } return c; } static struct event_constraint * mtl_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct x86_hybrid_pmu *pmu = hybrid_pmu(event->pmu); if (pmu->cpu_type == hybrid_big) return rwc_get_event_constraints(cpuc, idx, event); if (pmu->cpu_type == hybrid_small) return cmt_get_event_constraints(cpuc, idx, event); WARN_ON(1); return &emptyconstraint; } static int adl_hw_config(struct perf_event *event) { struct x86_hybrid_pmu *pmu = hybrid_pmu(event->pmu); if (pmu->cpu_type == hybrid_big) return hsw_hw_config(event); else if (pmu->cpu_type == hybrid_small) return intel_pmu_hw_config(event); WARN_ON(1); return -EOPNOTSUPP; } static u8 adl_get_hybrid_cpu_type(void) { return hybrid_big; } /* * Broadwell: * * The INST_RETIRED.ALL period always needs to have lowest 6 bits cleared * (BDM55) and it must not use a period smaller than 100 (BDM11). We combine * the two to enforce a minimum period of 128 (the smallest value that has bits * 0-5 cleared and >= 100). * * Because of how the code in x86_perf_event_set_period() works, the truncation * of the lower 6 bits is 'harmless' as we'll occasionally add a longer period * to make up for the 'lost' events due to carrying the 'error' in period_left. * * Therefore the effective (average) period matches the requested period, * despite coarser hardware granularity. */ static void bdw_limit_period(struct perf_event *event, s64 *left) { if ((event->hw.config & INTEL_ARCH_EVENT_MASK) == X86_CONFIG(.event=0xc0, .umask=0x01)) { if (*left < 128) *left = 128; *left &= ~0x3fULL; } } static void nhm_limit_period(struct perf_event *event, s64 *left) { *left = max(*left, 32LL); } static void spr_limit_period(struct perf_event *event, s64 *left) { if (event->attr.precise_ip == 3) *left = max(*left, 128LL); } PMU_FORMAT_ATTR(event, "config:0-7" ); PMU_FORMAT_ATTR(umask, "config:8-15" ); PMU_FORMAT_ATTR(edge, "config:18" ); PMU_FORMAT_ATTR(pc, "config:19" ); PMU_FORMAT_ATTR(any, "config:21" ); /* v3 + */ PMU_FORMAT_ATTR(inv, "config:23" ); PMU_FORMAT_ATTR(cmask, "config:24-31" ); PMU_FORMAT_ATTR(in_tx, "config:32"); PMU_FORMAT_ATTR(in_tx_cp, "config:33"); static struct attribute *intel_arch_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_pc.attr, &format_attr_inv.attr, &format_attr_cmask.attr, NULL, }; ssize_t intel_event_sysfs_show(char *page, u64 config) { u64 event = (config & ARCH_PERFMON_EVENTSEL_EVENT); return x86_event_sysfs_show(page, config, event); } static struct intel_shared_regs *allocate_shared_regs(int cpu) { struct intel_shared_regs *regs; int i; regs = kzalloc_node(sizeof(struct intel_shared_regs), GFP_KERNEL, cpu_to_node(cpu)); if (regs) { /* * initialize the locks to keep lockdep happy */ for (i = 0; i < EXTRA_REG_MAX; i++) raw_spin_lock_init(&regs->regs[i].lock); regs->core_id = -1; } return regs; } static struct intel_excl_cntrs *allocate_excl_cntrs(int cpu) { struct intel_excl_cntrs *c; c = kzalloc_node(sizeof(struct intel_excl_cntrs), GFP_KERNEL, cpu_to_node(cpu)); if (c) { raw_spin_lock_init(&c->lock); c->core_id = -1; } return c; } int intel_cpuc_prepare(struct cpu_hw_events *cpuc, int cpu) { cpuc->pebs_record_size = x86_pmu.pebs_record_size; if (is_hybrid() || x86_pmu.extra_regs || x86_pmu.lbr_sel_map) { cpuc->shared_regs = allocate_shared_regs(cpu); if (!cpuc->shared_regs) goto err; } if (x86_pmu.flags & (PMU_FL_EXCL_CNTRS | PMU_FL_TFA)) { size_t sz = X86_PMC_IDX_MAX * sizeof(struct event_constraint); cpuc->constraint_list = kzalloc_node(sz, GFP_KERNEL, cpu_to_node(cpu)); if (!cpuc->constraint_list) goto err_shared_regs; } if (x86_pmu.flags & PMU_FL_EXCL_CNTRS) { cpuc->excl_cntrs = allocate_excl_cntrs(cpu); if (!cpuc->excl_cntrs) goto err_constraint_list; cpuc->excl_thread_id = 0; } return 0; err_constraint_list: kfree(cpuc->constraint_list); cpuc->constraint_list = NULL; err_shared_regs: kfree(cpuc->shared_regs); cpuc->shared_regs = NULL; err: return -ENOMEM; } static int intel_pmu_cpu_prepare(int cpu) { return intel_cpuc_prepare(&per_cpu(cpu_hw_events, cpu), cpu); } static void flip_smm_bit(void *data) { unsigned long set = *(unsigned long *)data; if (set > 0) { msr_set_bit(MSR_IA32_DEBUGCTLMSR, DEBUGCTLMSR_FREEZE_IN_SMM_BIT); } else { msr_clear_bit(MSR_IA32_DEBUGCTLMSR, DEBUGCTLMSR_FREEZE_IN_SMM_BIT); } } static void intel_pmu_check_num_counters(int *num_counters, int *num_counters_fixed, u64 *intel_ctrl, u64 fixed_mask); static void update_pmu_cap(struct x86_hybrid_pmu *pmu) { unsigned int sub_bitmaps = cpuid_eax(ARCH_PERFMON_EXT_LEAF); unsigned int eax, ebx, ecx, edx; if (sub_bitmaps & ARCH_PERFMON_NUM_COUNTER_LEAF_BIT) { cpuid_count(ARCH_PERFMON_EXT_LEAF, ARCH_PERFMON_NUM_COUNTER_LEAF, &eax, &ebx, &ecx, &edx); pmu->num_counters = fls(eax); pmu->num_counters_fixed = fls(ebx); intel_pmu_check_num_counters(&pmu->num_counters, &pmu->num_counters_fixed, &pmu->intel_ctrl, ebx); } } static bool init_hybrid_pmu(int cpu) { struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu); u8 cpu_type = get_this_hybrid_cpu_type(); struct x86_hybrid_pmu *pmu = NULL; int i; if (!cpu_type && x86_pmu.get_hybrid_cpu_type) cpu_type = x86_pmu.get_hybrid_cpu_type(); for (i = 0; i < x86_pmu.num_hybrid_pmus; i++) { if (x86_pmu.hybrid_pmu[i].cpu_type == cpu_type) { pmu = &x86_pmu.hybrid_pmu[i]; break; } } if (WARN_ON_ONCE(!pmu || (pmu->pmu.type == -1))) { cpuc->pmu = NULL; return false; } /* Only check and dump the PMU information for the first CPU */ if (!cpumask_empty(&pmu->supported_cpus)) goto end; if (this_cpu_has(X86_FEATURE_ARCH_PERFMON_EXT)) update_pmu_cap(pmu); if (!check_hw_exists(&pmu->pmu, pmu->num_counters, pmu->num_counters_fixed)) return false; pr_info("%s PMU driver: ", pmu->name); if (pmu->intel_cap.pebs_output_pt_available) pr_cont("PEBS-via-PT "); pr_cont("\n"); x86_pmu_show_pmu_cap(pmu->num_counters, pmu->num_counters_fixed, pmu->intel_ctrl); end: cpumask_set_cpu(cpu, &pmu->supported_cpus); cpuc->pmu = &pmu->pmu; return true; } static void intel_pmu_cpu_starting(int cpu) { struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu); int core_id = topology_core_id(cpu); int i; if (is_hybrid() && !init_hybrid_pmu(cpu)) return; init_debug_store_on_cpu(cpu); /* * Deal with CPUs that don't clear their LBRs on power-up. */ intel_pmu_lbr_reset(); cpuc->lbr_sel = NULL; if (x86_pmu.flags & PMU_FL_TFA) { WARN_ON_ONCE(cpuc->tfa_shadow); cpuc->tfa_shadow = ~0ULL; intel_set_tfa(cpuc, false); } if (x86_pmu.version > 1) flip_smm_bit(&x86_pmu.attr_freeze_on_smi); /* * Disable perf metrics if any added CPU doesn't support it. * * Turn off the check for a hybrid architecture, because the * architecture MSR, MSR_IA32_PERF_CAPABILITIES, only indicate * the architecture features. The perf metrics is a model-specific * feature for now. The corresponding bit should always be 0 on * a hybrid platform, e.g., Alder Lake. */ if (!is_hybrid() && x86_pmu.intel_cap.perf_metrics) { union perf_capabilities perf_cap; rdmsrl(MSR_IA32_PERF_CAPABILITIES, perf_cap.capabilities); if (!perf_cap.perf_metrics) { x86_pmu.intel_cap.perf_metrics = 0; x86_pmu.intel_ctrl &= ~(1ULL << GLOBAL_CTRL_EN_PERF_METRICS); } } if (!cpuc->shared_regs) return; if (!(x86_pmu.flags & PMU_FL_NO_HT_SHARING)) { for_each_cpu(i, topology_sibling_cpumask(cpu)) { struct intel_shared_regs *pc; pc = per_cpu(cpu_hw_events, i).shared_regs; if (pc && pc->core_id == core_id) { cpuc->kfree_on_online[0] = cpuc->shared_regs; cpuc->shared_regs = pc; break; } } cpuc->shared_regs->core_id = core_id; cpuc->shared_regs->refcnt++; } if (x86_pmu.lbr_sel_map) cpuc->lbr_sel = &cpuc->shared_regs->regs[EXTRA_REG_LBR]; if (x86_pmu.flags & PMU_FL_EXCL_CNTRS) { for_each_cpu(i, topology_sibling_cpumask(cpu)) { struct cpu_hw_events *sibling; struct intel_excl_cntrs *c; sibling = &per_cpu(cpu_hw_events, i); c = sibling->excl_cntrs; if (c && c->core_id == core_id) { cpuc->kfree_on_online[1] = cpuc->excl_cntrs; cpuc->excl_cntrs = c; if (!sibling->excl_thread_id) cpuc->excl_thread_id = 1; break; } } cpuc->excl_cntrs->core_id = core_id; cpuc->excl_cntrs->refcnt++; } } static void free_excl_cntrs(struct cpu_hw_events *cpuc) { struct intel_excl_cntrs *c; c = cpuc->excl_cntrs; if (c) { if (c->core_id == -1 || --c->refcnt == 0) kfree(c); cpuc->excl_cntrs = NULL; } kfree(cpuc->constraint_list); cpuc->constraint_list = NULL; } static void intel_pmu_cpu_dying(int cpu) { fini_debug_store_on_cpu(cpu); } void intel_cpuc_finish(struct cpu_hw_events *cpuc) { struct intel_shared_regs *pc; pc = cpuc->shared_regs; if (pc) { if (pc->core_id == -1 || --pc->refcnt == 0) kfree(pc); cpuc->shared_regs = NULL; } free_excl_cntrs(cpuc); } static void intel_pmu_cpu_dead(int cpu) { struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu); intel_cpuc_finish(cpuc); if (is_hybrid() && cpuc->pmu) cpumask_clear_cpu(cpu, &hybrid_pmu(cpuc->pmu)->supported_cpus); } static void intel_pmu_sched_task(struct perf_event_pmu_context *pmu_ctx, bool sched_in) { intel_pmu_pebs_sched_task(pmu_ctx, sched_in); intel_pmu_lbr_sched_task(pmu_ctx, sched_in); } static void intel_pmu_swap_task_ctx(struct perf_event_pmu_context *prev_epc, struct perf_event_pmu_context *next_epc) { intel_pmu_lbr_swap_task_ctx(prev_epc, next_epc); } static int intel_pmu_check_period(struct perf_event *event, u64 value) { return intel_pmu_has_bts_period(event, value) ? -EINVAL : 0; } static void intel_aux_output_init(void) { /* Refer also intel_pmu_aux_output_match() */ if (x86_pmu.intel_cap.pebs_output_pt_available) x86_pmu.assign = intel_pmu_assign_event; } static int intel_pmu_aux_output_match(struct perf_event *event) { /* intel_pmu_assign_event() is needed, refer intel_aux_output_init() */ if (!x86_pmu.intel_cap.pebs_output_pt_available) return 0; return is_intel_pt_event(event); } static void intel_pmu_filter(struct pmu *pmu, int cpu, bool *ret) { struct x86_hybrid_pmu *hpmu = hybrid_pmu(pmu); *ret = !cpumask_test_cpu(cpu, &hpmu->supported_cpus); } PMU_FORMAT_ATTR(offcore_rsp, "config1:0-63"); PMU_FORMAT_ATTR(ldlat, "config1:0-15"); PMU_FORMAT_ATTR(frontend, "config1:0-23"); PMU_FORMAT_ATTR(snoop_rsp, "config1:0-63"); static struct attribute *intel_arch3_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_pc.attr, &format_attr_any.attr, &format_attr_inv.attr, &format_attr_cmask.attr, NULL, }; static struct attribute *hsw_format_attr[] = { &format_attr_in_tx.attr, &format_attr_in_tx_cp.attr, &format_attr_offcore_rsp.attr, &format_attr_ldlat.attr, NULL }; static struct attribute *nhm_format_attr[] = { &format_attr_offcore_rsp.attr, &format_attr_ldlat.attr, NULL }; static struct attribute *slm_format_attr[] = { &format_attr_offcore_rsp.attr, NULL }; static struct attribute *cmt_format_attr[] = { &format_attr_offcore_rsp.attr, &format_attr_ldlat.attr, &format_attr_snoop_rsp.attr, NULL }; static struct attribute *skl_format_attr[] = { &format_attr_frontend.attr, NULL, }; static __initconst const struct x86_pmu core_pmu = { .name = "core", .handle_irq = x86_pmu_handle_irq, .disable_all = x86_pmu_disable_all, .enable_all = core_pmu_enable_all, .enable = core_pmu_enable_event, .disable = x86_pmu_disable_event, .hw_config = core_pmu_hw_config, .schedule_events = x86_schedule_events, .eventsel = MSR_ARCH_PERFMON_EVENTSEL0, .perfctr = MSR_ARCH_PERFMON_PERFCTR0, .event_map = intel_pmu_event_map, .max_events = ARRAY_SIZE(intel_perfmon_event_map), .apic = 1, .large_pebs_flags = LARGE_PEBS_FLAGS, /* * Intel PMCs cannot be accessed sanely above 32-bit width, * so we install an artificial 1<<31 period regardless of * the generic event period: */ .max_period = (1ULL<<31) - 1, .get_event_constraints = intel_get_event_constraints, .put_event_constraints = intel_put_event_constraints, .event_constraints = intel_core_event_constraints, .guest_get_msrs = core_guest_get_msrs, .format_attrs = intel_arch_formats_attr, .events_sysfs_show = intel_event_sysfs_show, /* * Virtual (or funny metal) CPU can define x86_pmu.extra_regs * together with PMU version 1 and thus be using core_pmu with * shared_regs. We need following callbacks here to allocate * it properly. */ .cpu_prepare = intel_pmu_cpu_prepare, .cpu_starting = intel_pmu_cpu_starting, .cpu_dying = intel_pmu_cpu_dying, .cpu_dead = intel_pmu_cpu_dead, .check_period = intel_pmu_check_period, .lbr_reset = intel_pmu_lbr_reset_64, .lbr_read = intel_pmu_lbr_read_64, .lbr_save = intel_pmu_lbr_save, .lbr_restore = intel_pmu_lbr_restore, }; static __initconst const struct x86_pmu intel_pmu = { .name = "Intel", .handle_irq = intel_pmu_handle_irq, .disable_all = intel_pmu_disable_all, .enable_all = intel_pmu_enable_all, .enable = intel_pmu_enable_event, .disable = intel_pmu_disable_event, .add = intel_pmu_add_event, .del = intel_pmu_del_event, .read = intel_pmu_read_event, .set_period = intel_pmu_set_period, .update = intel_pmu_update, .hw_config = intel_pmu_hw_config, .schedule_events = x86_schedule_events, .eventsel = MSR_ARCH_PERFMON_EVENTSEL0, .perfctr = MSR_ARCH_PERFMON_PERFCTR0, .event_map = intel_pmu_event_map, .max_events = ARRAY_SIZE(intel_perfmon_event_map), .apic = 1, .large_pebs_flags = LARGE_PEBS_FLAGS, /* * Intel PMCs cannot be accessed sanely above 32 bit width, * so we install an artificial 1<<31 period regardless of * the generic event period: */ .max_period = (1ULL << 31) - 1, .get_event_constraints = intel_get_event_constraints, .put_event_constraints = intel_put_event_constraints, .pebs_aliases = intel_pebs_aliases_core2, .format_attrs = intel_arch3_formats_attr, .events_sysfs_show = intel_event_sysfs_show, .cpu_prepare = intel_pmu_cpu_prepare, .cpu_starting = intel_pmu_cpu_starting, .cpu_dying = intel_pmu_cpu_dying, .cpu_dead = intel_pmu_cpu_dead, .guest_get_msrs = intel_guest_get_msrs, .sched_task = intel_pmu_sched_task, .swap_task_ctx = intel_pmu_swap_task_ctx, .check_period = intel_pmu_check_period, .aux_output_match = intel_pmu_aux_output_match, .lbr_reset = intel_pmu_lbr_reset_64, .lbr_read = intel_pmu_lbr_read_64, .lbr_save = intel_pmu_lbr_save, .lbr_restore = intel_pmu_lbr_restore, /* * SMM has access to all 4 rings and while traditionally SMM code only * ran in CPL0, 2021-era firmware is starting to make use of CPL3 in SMM. * * Since the EVENTSEL.{USR,OS} CPL filtering makes no distinction * between SMM or not, this results in what should be pure userspace * counters including SMM data. * * This is a clear privilege issue, therefore globally disable * counting SMM by default. */ .attr_freeze_on_smi = 1, }; static __init void intel_clovertown_quirk(void) { /* * PEBS is unreliable due to: * * AJ67 - PEBS may experience CPL leaks * AJ68 - PEBS PMI may be delayed by one event * AJ69 - GLOBAL_STATUS[62] will only be set when DEBUGCTL[12] * AJ106 - FREEZE_LBRS_ON_PMI doesn't work in combination with PEBS * * AJ67 could be worked around by restricting the OS/USR flags. * AJ69 could be worked around by setting PMU_FREEZE_ON_PMI. * * AJ106 could possibly be worked around by not allowing LBR * usage from PEBS, including the fixup. * AJ68 could possibly be worked around by always programming * a pebs_event_reset[0] value and coping with the lost events. * * But taken together it might just make sense to not enable PEBS on * these chips. */ pr_warn("PEBS disabled due to CPU errata\n"); x86_pmu.pebs = 0; x86_pmu.pebs_constraints = NULL; } static const struct x86_cpu_desc isolation_ucodes[] = { INTEL_CPU_DESC(INTEL_FAM6_HASWELL, 3, 0x0000001f), INTEL_CPU_DESC(INTEL_FAM6_HASWELL_L, 1, 0x0000001e), INTEL_CPU_DESC(INTEL_FAM6_HASWELL_G, 1, 0x00000015), INTEL_CPU_DESC(INTEL_FAM6_HASWELL_X, 2, 0x00000037), INTEL_CPU_DESC(INTEL_FAM6_HASWELL_X, 4, 0x0000000a), INTEL_CPU_DESC(INTEL_FAM6_BROADWELL, 4, 0x00000023), INTEL_CPU_DESC(INTEL_FAM6_BROADWELL_G, 1, 0x00000014), INTEL_CPU_DESC(INTEL_FAM6_BROADWELL_D, 2, 0x00000010), INTEL_CPU_DESC(INTEL_FAM6_BROADWELL_D, 3, 0x07000009), INTEL_CPU_DESC(INTEL_FAM6_BROADWELL_D, 4, 0x0f000009), INTEL_CPU_DESC(INTEL_FAM6_BROADWELL_D, 5, 0x0e000002), INTEL_CPU_DESC(INTEL_FAM6_BROADWELL_X, 1, 0x0b000014), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE_X, 3, 0x00000021), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE_X, 4, 0x00000000), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE_X, 5, 0x00000000), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE_X, 6, 0x00000000), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE_X, 7, 0x00000000), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE_X, 11, 0x00000000), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE_L, 3, 0x0000007c), INTEL_CPU_DESC(INTEL_FAM6_SKYLAKE, 3, 0x0000007c), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE, 9, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE_L, 9, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE_L, 10, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE_L, 11, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE_L, 12, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE, 10, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE, 11, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE, 12, 0x0000004e), INTEL_CPU_DESC(INTEL_FAM6_KABYLAKE, 13, 0x0000004e), {} }; static void intel_check_pebs_isolation(void) { x86_pmu.pebs_no_isolation = !x86_cpu_has_min_microcode_rev(isolation_ucodes); } static __init void intel_pebs_isolation_quirk(void) { WARN_ON_ONCE(x86_pmu.check_microcode); x86_pmu.check_microcode = intel_check_pebs_isolation; intel_check_pebs_isolation(); } static const struct x86_cpu_desc pebs_ucodes[] = { INTEL_CPU_DESC(INTEL_FAM6_SANDYBRIDGE, 7, 0x00000028), INTEL_CPU_DESC(INTEL_FAM6_SANDYBRIDGE_X, 6, 0x00000618), INTEL_CPU_DESC(INTEL_FAM6_SANDYBRIDGE_X, 7, 0x0000070c), {} }; static bool intel_snb_pebs_broken(void) { return !x86_cpu_has_min_microcode_rev(pebs_ucodes); } static void intel_snb_check_microcode(void) { if (intel_snb_pebs_broken() == x86_pmu.pebs_broken) return; /* * Serialized by the microcode lock.. */ if (x86_pmu.pebs_broken) { pr_info("PEBS enabled due to microcode update\n"); x86_pmu.pebs_broken = 0; } else { pr_info("PEBS disabled due to CPU errata, please upgrade microcode\n"); x86_pmu.pebs_broken = 1; } } static bool is_lbr_from(unsigned long msr) { unsigned long lbr_from_nr = x86_pmu.lbr_from + x86_pmu.lbr_nr; return x86_pmu.lbr_from <= msr && msr < lbr_from_nr; } /* * Under certain circumstances, access certain MSR may cause #GP. * The function tests if the input MSR can be safely accessed. */ static bool check_msr(unsigned long msr, u64 mask) { u64 val_old, val_new, val_tmp; /* * Disable the check for real HW, so we don't * mess with potentially enabled registers: */ if (!boot_cpu_has(X86_FEATURE_HYPERVISOR)) return true; /* * Read the current value, change it and read it back to see if it * matches, this is needed to detect certain hardware emulators * (qemu/kvm) that don't trap on the MSR access and always return 0s. */ if (rdmsrl_safe(msr, &val_old)) return false; /* * Only change the bits which can be updated by wrmsrl. */ val_tmp = val_old ^ mask; if (is_lbr_from(msr)) val_tmp = lbr_from_signext_quirk_wr(val_tmp); if (wrmsrl_safe(msr, val_tmp) || rdmsrl_safe(msr, &val_new)) return false; /* * Quirk only affects validation in wrmsr(), so wrmsrl()'s value * should equal rdmsrl()'s even with the quirk. */ if (val_new != val_tmp) return false; if (is_lbr_from(msr)) val_old = lbr_from_signext_quirk_wr(val_old); /* Here it's sure that the MSR can be safely accessed. * Restore the old value and return. */ wrmsrl(msr, val_old); return true; } static __init void intel_sandybridge_quirk(void) { x86_pmu.check_microcode = intel_snb_check_microcode; cpus_read_lock(); intel_snb_check_microcode(); cpus_read_unlock(); } static const struct { int id; char *name; } intel_arch_events_map[] __initconst = { { PERF_COUNT_HW_CPU_CYCLES, "cpu cycles" }, { PERF_COUNT_HW_INSTRUCTIONS, "instructions" }, { PERF_COUNT_HW_BUS_CYCLES, "bus cycles" }, { PERF_COUNT_HW_CACHE_REFERENCES, "cache references" }, { PERF_COUNT_HW_CACHE_MISSES, "cache misses" }, { PERF_COUNT_HW_BRANCH_INSTRUCTIONS, "branch instructions" }, { PERF_COUNT_HW_BRANCH_MISSES, "branch misses" }, }; static __init void intel_arch_events_quirk(void) { int bit; /* disable event that reported as not present by cpuid */ for_each_set_bit(bit, x86_pmu.events_mask, ARRAY_SIZE(intel_arch_events_map)) { intel_perfmon_event_map[intel_arch_events_map[bit].id] = 0; pr_warn("CPUID marked event: \'%s\' unavailable\n", intel_arch_events_map[bit].name); } } static __init void intel_nehalem_quirk(void) { union cpuid10_ebx ebx; ebx.full = x86_pmu.events_maskl; if (ebx.split.no_branch_misses_retired) { /* * Erratum AAJ80 detected, we work it around by using * the BR_MISP_EXEC.ANY event. This will over-count * branch-misses, but it's still much better than the * architectural event which is often completely bogus: */ intel_perfmon_event_map[PERF_COUNT_HW_BRANCH_MISSES] = 0x7f89; ebx.split.no_branch_misses_retired = 0; x86_pmu.events_maskl = ebx.full; pr_info("CPU erratum AAJ80 worked around\n"); } } /* * enable software workaround for errata: * SNB: BJ122 * IVB: BV98 * HSW: HSD29 * * Only needed when HT is enabled. However detecting * if HT is enabled is difficult (model specific). So instead, * we enable the workaround in the early boot, and verify if * it is needed in a later initcall phase once we have valid * topology information to check if HT is actually enabled */ static __init void intel_ht_bug(void) { x86_pmu.flags |= PMU_FL_EXCL_CNTRS | PMU_FL_EXCL_ENABLED; x86_pmu.start_scheduling = intel_start_scheduling; x86_pmu.commit_scheduling = intel_commit_scheduling; x86_pmu.stop_scheduling = intel_stop_scheduling; } EVENT_ATTR_STR(mem-loads, mem_ld_hsw, "event=0xcd,umask=0x1,ldlat=3"); EVENT_ATTR_STR(mem-stores, mem_st_hsw, "event=0xd0,umask=0x82") /* Haswell special events */ EVENT_ATTR_STR(tx-start, tx_start, "event=0xc9,umask=0x1"); EVENT_ATTR_STR(tx-commit, tx_commit, "event=0xc9,umask=0x2"); EVENT_ATTR_STR(tx-abort, tx_abort, "event=0xc9,umask=0x4"); EVENT_ATTR_STR(tx-capacity, tx_capacity, "event=0x54,umask=0x2"); EVENT_ATTR_STR(tx-conflict, tx_conflict, "event=0x54,umask=0x1"); EVENT_ATTR_STR(el-start, el_start, "event=0xc8,umask=0x1"); EVENT_ATTR_STR(el-commit, el_commit, "event=0xc8,umask=0x2"); EVENT_ATTR_STR(el-abort, el_abort, "event=0xc8,umask=0x4"); EVENT_ATTR_STR(el-capacity, el_capacity, "event=0x54,umask=0x2"); EVENT_ATTR_STR(el-conflict, el_conflict, "event=0x54,umask=0x1"); EVENT_ATTR_STR(cycles-t, cycles_t, "event=0x3c,in_tx=1"); EVENT_ATTR_STR(cycles-ct, cycles_ct, "event=0x3c,in_tx=1,in_tx_cp=1"); static struct attribute *hsw_events_attrs[] = { EVENT_PTR(td_slots_issued), EVENT_PTR(td_slots_retired), EVENT_PTR(td_fetch_bubbles), EVENT_PTR(td_total_slots), EVENT_PTR(td_total_slots_scale), EVENT_PTR(td_recovery_bubbles), EVENT_PTR(td_recovery_bubbles_scale), NULL }; static struct attribute *hsw_mem_events_attrs[] = { EVENT_PTR(mem_ld_hsw), EVENT_PTR(mem_st_hsw), NULL, }; static struct attribute *hsw_tsx_events_attrs[] = { EVENT_PTR(tx_start), EVENT_PTR(tx_commit), EVENT_PTR(tx_abort), EVENT_PTR(tx_capacity), EVENT_PTR(tx_conflict), EVENT_PTR(el_start), EVENT_PTR(el_commit), EVENT_PTR(el_abort), EVENT_PTR(el_capacity), EVENT_PTR(el_conflict), EVENT_PTR(cycles_t), EVENT_PTR(cycles_ct), NULL }; EVENT_ATTR_STR(tx-capacity-read, tx_capacity_read, "event=0x54,umask=0x80"); EVENT_ATTR_STR(tx-capacity-write, tx_capacity_write, "event=0x54,umask=0x2"); EVENT_ATTR_STR(el-capacity-read, el_capacity_read, "event=0x54,umask=0x80"); EVENT_ATTR_STR(el-capacity-write, el_capacity_write, "event=0x54,umask=0x2"); static struct attribute *icl_events_attrs[] = { EVENT_PTR(mem_ld_hsw), EVENT_PTR(mem_st_hsw), NULL, }; static struct attribute *icl_td_events_attrs[] = { EVENT_PTR(slots), EVENT_PTR(td_retiring), EVENT_PTR(td_bad_spec), EVENT_PTR(td_fe_bound), EVENT_PTR(td_be_bound), NULL, }; static struct attribute *icl_tsx_events_attrs[] = { EVENT_PTR(tx_start), EVENT_PTR(tx_abort), EVENT_PTR(tx_commit), EVENT_PTR(tx_capacity_read), EVENT_PTR(tx_capacity_write), EVENT_PTR(tx_conflict), EVENT_PTR(el_start), EVENT_PTR(el_abort), EVENT_PTR(el_commit), EVENT_PTR(el_capacity_read), EVENT_PTR(el_capacity_write), EVENT_PTR(el_conflict), EVENT_PTR(cycles_t), EVENT_PTR(cycles_ct), NULL, }; EVENT_ATTR_STR(mem-stores, mem_st_spr, "event=0xcd,umask=0x2"); EVENT_ATTR_STR(mem-loads-aux, mem_ld_aux, "event=0x03,umask=0x82"); static struct attribute *spr_events_attrs[] = { EVENT_PTR(mem_ld_hsw), EVENT_PTR(mem_st_spr), EVENT_PTR(mem_ld_aux), NULL, }; static struct attribute *spr_td_events_attrs[] = { EVENT_PTR(slots), EVENT_PTR(td_retiring), EVENT_PTR(td_bad_spec), EVENT_PTR(td_fe_bound), EVENT_PTR(td_be_bound), EVENT_PTR(td_heavy_ops), EVENT_PTR(td_br_mispredict), EVENT_PTR(td_fetch_lat), EVENT_PTR(td_mem_bound), NULL, }; static struct attribute *spr_tsx_events_attrs[] = { EVENT_PTR(tx_start), EVENT_PTR(tx_abort), EVENT_PTR(tx_commit), EVENT_PTR(tx_capacity_read), EVENT_PTR(tx_capacity_write), EVENT_PTR(tx_conflict), EVENT_PTR(cycles_t), EVENT_PTR(cycles_ct), NULL, }; static ssize_t freeze_on_smi_show(struct device *cdev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%lu\n", x86_pmu.attr_freeze_on_smi); } static DEFINE_MUTEX(freeze_on_smi_mutex); static ssize_t freeze_on_smi_store(struct device *cdev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long val; ssize_t ret; ret = kstrtoul(buf, 0, &val); if (ret) return ret; if (val > 1) return -EINVAL; mutex_lock(&freeze_on_smi_mutex); if (x86_pmu.attr_freeze_on_smi == val) goto done; x86_pmu.attr_freeze_on_smi = val; cpus_read_lock(); on_each_cpu(flip_smm_bit, &val, 1); cpus_read_unlock(); done: mutex_unlock(&freeze_on_smi_mutex); return count; } static void update_tfa_sched(void *ignored) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* * check if PMC3 is used * and if so force schedule out for all event types all contexts */ if (test_bit(3, cpuc->active_mask)) perf_pmu_resched(x86_get_pmu(smp_processor_id())); } static ssize_t show_sysctl_tfa(struct device *cdev, struct device_attribute *attr, char *buf) { return snprintf(buf, 40, "%d\n", allow_tsx_force_abort); } static ssize_t set_sysctl_tfa(struct device *cdev, struct device_attribute *attr, const char *buf, size_t count) { bool val; ssize_t ret; ret = kstrtobool(buf, &val); if (ret) return ret; /* no change */ if (val == allow_tsx_force_abort) return count; allow_tsx_force_abort = val; cpus_read_lock(); on_each_cpu(update_tfa_sched, NULL, 1); cpus_read_unlock(); return count; } static DEVICE_ATTR_RW(freeze_on_smi); static ssize_t branches_show(struct device *cdev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", x86_pmu.lbr_nr); } static DEVICE_ATTR_RO(branches); static struct attribute *lbr_attrs[] = { &dev_attr_branches.attr, NULL }; static char pmu_name_str[30]; static ssize_t pmu_name_show(struct device *cdev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%s\n", pmu_name_str); } static DEVICE_ATTR_RO(pmu_name); static struct attribute *intel_pmu_caps_attrs[] = { &dev_attr_pmu_name.attr, NULL }; static DEVICE_ATTR(allow_tsx_force_abort, 0644, show_sysctl_tfa, set_sysctl_tfa); static struct attribute *intel_pmu_attrs[] = { &dev_attr_freeze_on_smi.attr, &dev_attr_allow_tsx_force_abort.attr, NULL, }; static umode_t tsx_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return boot_cpu_has(X86_FEATURE_RTM) ? attr->mode : 0; } static umode_t pebs_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return x86_pmu.pebs ? attr->mode : 0; } static umode_t mem_is_visible(struct kobject *kobj, struct attribute *attr, int i) { if (attr == &event_attr_mem_ld_aux.attr.attr) return x86_pmu.flags & PMU_FL_MEM_LOADS_AUX ? attr->mode : 0; return pebs_is_visible(kobj, attr, i); } static umode_t lbr_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return x86_pmu.lbr_nr ? attr->mode : 0; } static umode_t exra_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return x86_pmu.version >= 2 ? attr->mode : 0; } static umode_t default_is_visible(struct kobject *kobj, struct attribute *attr, int i) { if (attr == &dev_attr_allow_tsx_force_abort.attr) return x86_pmu.flags & PMU_FL_TFA ? attr->mode : 0; return attr->mode; } static struct attribute_group group_events_td = { .name = "events", }; static struct attribute_group group_events_mem = { .name = "events", .is_visible = mem_is_visible, }; static struct attribute_group group_events_tsx = { .name = "events", .is_visible = tsx_is_visible, }; static struct attribute_group group_caps_gen = { .name = "caps", .attrs = intel_pmu_caps_attrs, }; static struct attribute_group group_caps_lbr = { .name = "caps", .attrs = lbr_attrs, .is_visible = lbr_is_visible, }; static struct attribute_group group_format_extra = { .name = "format", .is_visible = exra_is_visible, }; static struct attribute_group group_format_extra_skl = { .name = "format", .is_visible = exra_is_visible, }; static struct attribute_group group_default = { .attrs = intel_pmu_attrs, .is_visible = default_is_visible, }; static const struct attribute_group *attr_update[] = { &group_events_td, &group_events_mem, &group_events_tsx, &group_caps_gen, &group_caps_lbr, &group_format_extra, &group_format_extra_skl, &group_default, NULL, }; EVENT_ATTR_STR_HYBRID(slots, slots_adl, "event=0x00,umask=0x4", hybrid_big); EVENT_ATTR_STR_HYBRID(topdown-retiring, td_retiring_adl, "event=0xc2,umask=0x0;event=0x00,umask=0x80", hybrid_big_small); EVENT_ATTR_STR_HYBRID(topdown-bad-spec, td_bad_spec_adl, "event=0x73,umask=0x0;event=0x00,umask=0x81", hybrid_big_small); EVENT_ATTR_STR_HYBRID(topdown-fe-bound, td_fe_bound_adl, "event=0x71,umask=0x0;event=0x00,umask=0x82", hybrid_big_small); EVENT_ATTR_STR_HYBRID(topdown-be-bound, td_be_bound_adl, "event=0x74,umask=0x0;event=0x00,umask=0x83", hybrid_big_small); EVENT_ATTR_STR_HYBRID(topdown-heavy-ops, td_heavy_ops_adl, "event=0x00,umask=0x84", hybrid_big); EVENT_ATTR_STR_HYBRID(topdown-br-mispredict, td_br_mis_adl, "event=0x00,umask=0x85", hybrid_big); EVENT_ATTR_STR_HYBRID(topdown-fetch-lat, td_fetch_lat_adl, "event=0x00,umask=0x86", hybrid_big); EVENT_ATTR_STR_HYBRID(topdown-mem-bound, td_mem_bound_adl, "event=0x00,umask=0x87", hybrid_big); static struct attribute *adl_hybrid_events_attrs[] = { EVENT_PTR(slots_adl), EVENT_PTR(td_retiring_adl), EVENT_PTR(td_bad_spec_adl), EVENT_PTR(td_fe_bound_adl), EVENT_PTR(td_be_bound_adl), EVENT_PTR(td_heavy_ops_adl), EVENT_PTR(td_br_mis_adl), EVENT_PTR(td_fetch_lat_adl), EVENT_PTR(td_mem_bound_adl), NULL, }; /* Must be in IDX order */ EVENT_ATTR_STR_HYBRID(mem-loads, mem_ld_adl, "event=0xd0,umask=0x5,ldlat=3;event=0xcd,umask=0x1,ldlat=3", hybrid_big_small); EVENT_ATTR_STR_HYBRID(mem-stores, mem_st_adl, "event=0xd0,umask=0x6;event=0xcd,umask=0x2", hybrid_big_small); EVENT_ATTR_STR_HYBRID(mem-loads-aux, mem_ld_aux_adl, "event=0x03,umask=0x82", hybrid_big); static struct attribute *adl_hybrid_mem_attrs[] = { EVENT_PTR(mem_ld_adl), EVENT_PTR(mem_st_adl), EVENT_PTR(mem_ld_aux_adl), NULL, }; static struct attribute *mtl_hybrid_mem_attrs[] = { EVENT_PTR(mem_ld_adl), EVENT_PTR(mem_st_adl), NULL }; EVENT_ATTR_STR_HYBRID(tx-start, tx_start_adl, "event=0xc9,umask=0x1", hybrid_big); EVENT_ATTR_STR_HYBRID(tx-commit, tx_commit_adl, "event=0xc9,umask=0x2", hybrid_big); EVENT_ATTR_STR_HYBRID(tx-abort, tx_abort_adl, "event=0xc9,umask=0x4", hybrid_big); EVENT_ATTR_STR_HYBRID(tx-conflict, tx_conflict_adl, "event=0x54,umask=0x1", hybrid_big); EVENT_ATTR_STR_HYBRID(cycles-t, cycles_t_adl, "event=0x3c,in_tx=1", hybrid_big); EVENT_ATTR_STR_HYBRID(cycles-ct, cycles_ct_adl, "event=0x3c,in_tx=1,in_tx_cp=1", hybrid_big); EVENT_ATTR_STR_HYBRID(tx-capacity-read, tx_capacity_read_adl, "event=0x54,umask=0x80", hybrid_big); EVENT_ATTR_STR_HYBRID(tx-capacity-write, tx_capacity_write_adl, "event=0x54,umask=0x2", hybrid_big); static struct attribute *adl_hybrid_tsx_attrs[] = { EVENT_PTR(tx_start_adl), EVENT_PTR(tx_abort_adl), EVENT_PTR(tx_commit_adl), EVENT_PTR(tx_capacity_read_adl), EVENT_PTR(tx_capacity_write_adl), EVENT_PTR(tx_conflict_adl), EVENT_PTR(cycles_t_adl), EVENT_PTR(cycles_ct_adl), NULL, }; FORMAT_ATTR_HYBRID(in_tx, hybrid_big); FORMAT_ATTR_HYBRID(in_tx_cp, hybrid_big); FORMAT_ATTR_HYBRID(offcore_rsp, hybrid_big_small); FORMAT_ATTR_HYBRID(ldlat, hybrid_big_small); FORMAT_ATTR_HYBRID(frontend, hybrid_big); #define ADL_HYBRID_RTM_FORMAT_ATTR \ FORMAT_HYBRID_PTR(in_tx), \ FORMAT_HYBRID_PTR(in_tx_cp) #define ADL_HYBRID_FORMAT_ATTR \ FORMAT_HYBRID_PTR(offcore_rsp), \ FORMAT_HYBRID_PTR(ldlat), \ FORMAT_HYBRID_PTR(frontend) static struct attribute *adl_hybrid_extra_attr_rtm[] = { ADL_HYBRID_RTM_FORMAT_ATTR, ADL_HYBRID_FORMAT_ATTR, NULL }; static struct attribute *adl_hybrid_extra_attr[] = { ADL_HYBRID_FORMAT_ATTR, NULL }; FORMAT_ATTR_HYBRID(snoop_rsp, hybrid_small); static struct attribute *mtl_hybrid_extra_attr_rtm[] = { ADL_HYBRID_RTM_FORMAT_ATTR, ADL_HYBRID_FORMAT_ATTR, FORMAT_HYBRID_PTR(snoop_rsp), NULL }; static struct attribute *mtl_hybrid_extra_attr[] = { ADL_HYBRID_FORMAT_ATTR, FORMAT_HYBRID_PTR(snoop_rsp), NULL }; static bool is_attr_for_this_pmu(struct kobject *kobj, struct attribute *attr) { struct device *dev = kobj_to_dev(kobj); struct x86_hybrid_pmu *pmu = container_of(dev_get_drvdata(dev), struct x86_hybrid_pmu, pmu); struct perf_pmu_events_hybrid_attr *pmu_attr = container_of(attr, struct perf_pmu_events_hybrid_attr, attr.attr); return pmu->cpu_type & pmu_attr->pmu_type; } static umode_t hybrid_events_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return is_attr_for_this_pmu(kobj, attr) ? attr->mode : 0; } static inline int hybrid_find_supported_cpu(struct x86_hybrid_pmu *pmu) { int cpu = cpumask_first(&pmu->supported_cpus); return (cpu >= nr_cpu_ids) ? -1 : cpu; } static umode_t hybrid_tsx_is_visible(struct kobject *kobj, struct attribute *attr, int i) { struct device *dev = kobj_to_dev(kobj); struct x86_hybrid_pmu *pmu = container_of(dev_get_drvdata(dev), struct x86_hybrid_pmu, pmu); int cpu = hybrid_find_supported_cpu(pmu); return (cpu >= 0) && is_attr_for_this_pmu(kobj, attr) && cpu_has(&cpu_data(cpu), X86_FEATURE_RTM) ? attr->mode : 0; } static umode_t hybrid_format_is_visible(struct kobject *kobj, struct attribute *attr, int i) { struct device *dev = kobj_to_dev(kobj); struct x86_hybrid_pmu *pmu = container_of(dev_get_drvdata(dev), struct x86_hybrid_pmu, pmu); struct perf_pmu_format_hybrid_attr *pmu_attr = container_of(attr, struct perf_pmu_format_hybrid_attr, attr.attr); int cpu = hybrid_find_supported_cpu(pmu); return (cpu >= 0) && (pmu->cpu_type & pmu_attr->pmu_type) ? attr->mode : 0; } static struct attribute_group hybrid_group_events_td = { .name = "events", .is_visible = hybrid_events_is_visible, }; static struct attribute_group hybrid_group_events_mem = { .name = "events", .is_visible = hybrid_events_is_visible, }; static struct attribute_group hybrid_group_events_tsx = { .name = "events", .is_visible = hybrid_tsx_is_visible, }; static struct attribute_group hybrid_group_format_extra = { .name = "format", .is_visible = hybrid_format_is_visible, }; static ssize_t intel_hybrid_get_attr_cpus(struct device *dev, struct device_attribute *attr, char *buf) { struct x86_hybrid_pmu *pmu = container_of(dev_get_drvdata(dev), struct x86_hybrid_pmu, pmu); return cpumap_print_to_pagebuf(true, buf, &pmu->supported_cpus); } static DEVICE_ATTR(cpus, S_IRUGO, intel_hybrid_get_attr_cpus, NULL); static struct attribute *intel_hybrid_cpus_attrs[] = { &dev_attr_cpus.attr, NULL, }; static struct attribute_group hybrid_group_cpus = { .attrs = intel_hybrid_cpus_attrs, }; static const struct attribute_group *hybrid_attr_update[] = { &hybrid_group_events_td, &hybrid_group_events_mem, &hybrid_group_events_tsx, &group_caps_gen, &group_caps_lbr, &hybrid_group_format_extra, &group_default, &hybrid_group_cpus, NULL, }; static struct attribute *empty_attrs; static void intel_pmu_check_num_counters(int *num_counters, int *num_counters_fixed, u64 *intel_ctrl, u64 fixed_mask) { if (*num_counters > INTEL_PMC_MAX_GENERIC) { WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!", *num_counters, INTEL_PMC_MAX_GENERIC); *num_counters = INTEL_PMC_MAX_GENERIC; } *intel_ctrl = (1ULL << *num_counters) - 1; if (*num_counters_fixed > INTEL_PMC_MAX_FIXED) { WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!", *num_counters_fixed, INTEL_PMC_MAX_FIXED); *num_counters_fixed = INTEL_PMC_MAX_FIXED; } *intel_ctrl |= fixed_mask << INTEL_PMC_IDX_FIXED; } static void intel_pmu_check_event_constraints(struct event_constraint *event_constraints, int num_counters, int num_counters_fixed, u64 intel_ctrl) { struct event_constraint *c; if (!event_constraints) return; /* * event on fixed counter2 (REF_CYCLES) only works on this * counter, so do not extend mask to generic counters */ for_each_event_constraint(c, event_constraints) { /* * Don't extend the topdown slots and metrics * events to the generic counters. */ if (c->idxmsk64 & INTEL_PMC_MSK_TOPDOWN) { /* * Disable topdown slots and metrics events, * if slots event is not in CPUID. */ if (!(INTEL_PMC_MSK_FIXED_SLOTS & intel_ctrl)) c->idxmsk64 = 0; c->weight = hweight64(c->idxmsk64); continue; } if (c->cmask == FIXED_EVENT_FLAGS) { /* Disabled fixed counters which are not in CPUID */ c->idxmsk64 &= intel_ctrl; /* * Don't extend the pseudo-encoding to the * generic counters */ if (!use_fixed_pseudo_encoding(c->code)) c->idxmsk64 |= (1ULL << num_counters) - 1; } c->idxmsk64 &= ~(~0ULL << (INTEL_PMC_IDX_FIXED + num_counters_fixed)); c->weight = hweight64(c->idxmsk64); } } static void intel_pmu_check_extra_regs(struct extra_reg *extra_regs) { struct extra_reg *er; /* * Access extra MSR may cause #GP under certain circumstances. * E.g. KVM doesn't support offcore event * Check all extra_regs here. */ if (!extra_regs) return; for (er = extra_regs; er->msr; er++) { er->extra_msr_access = check_msr(er->msr, 0x11UL); /* Disable LBR select mapping */ if ((er->idx == EXTRA_REG_LBR) && !er->extra_msr_access) x86_pmu.lbr_sel_map = NULL; } } static void intel_pmu_check_hybrid_pmus(u64 fixed_mask) { struct x86_hybrid_pmu *pmu; int i; for (i = 0; i < x86_pmu.num_hybrid_pmus; i++) { pmu = &x86_pmu.hybrid_pmu[i]; intel_pmu_check_num_counters(&pmu->num_counters, &pmu->num_counters_fixed, &pmu->intel_ctrl, fixed_mask); if (pmu->intel_cap.perf_metrics) { pmu->intel_ctrl |= 1ULL << GLOBAL_CTRL_EN_PERF_METRICS; pmu->intel_ctrl |= INTEL_PMC_MSK_FIXED_SLOTS; } if (pmu->intel_cap.pebs_output_pt_available) pmu->pmu.capabilities |= PERF_PMU_CAP_AUX_OUTPUT; intel_pmu_check_event_constraints(pmu->event_constraints, pmu->num_counters, pmu->num_counters_fixed, pmu->intel_ctrl); intel_pmu_check_extra_regs(pmu->extra_regs); } } static __always_inline bool is_mtl(u8 x86_model) { return (x86_model == INTEL_FAM6_METEORLAKE) || (x86_model == INTEL_FAM6_METEORLAKE_L); } __init int intel_pmu_init(void) { struct attribute **extra_skl_attr = &empty_attrs; struct attribute **extra_attr = &empty_attrs; struct attribute **td_attr = &empty_attrs; struct attribute **mem_attr = &empty_attrs; struct attribute **tsx_attr = &empty_attrs; union cpuid10_edx edx; union cpuid10_eax eax; union cpuid10_ebx ebx; unsigned int fixed_mask; bool pmem = false; int version, i; char *name; struct x86_hybrid_pmu *pmu; if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON)) { switch (boot_cpu_data.x86) { case 0x6: return p6_pmu_init(); case 0xb: return knc_pmu_init(); case 0xf: return p4_pmu_init(); } return -ENODEV; } /* * Check whether the Architectural PerfMon supports * Branch Misses Retired hw_event or not. */ cpuid(10, &eax.full, &ebx.full, &fixed_mask, &edx.full); if (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT) return -ENODEV; version = eax.split.version_id; if (version < 2) x86_pmu = core_pmu; else x86_pmu = intel_pmu; x86_pmu.version = version; x86_pmu.num_counters = eax.split.num_counters; x86_pmu.cntval_bits = eax.split.bit_width; x86_pmu.cntval_mask = (1ULL << eax.split.bit_width) - 1; x86_pmu.events_maskl = ebx.full; x86_pmu.events_mask_len = eax.split.mask_length; x86_pmu.max_pebs_events = min_t(unsigned, MAX_PEBS_EVENTS, x86_pmu.num_counters); x86_pmu.pebs_capable = PEBS_COUNTER_MASK; /* * Quirk: v2 perfmon does not report fixed-purpose events, so * assume at least 3 events, when not running in a hypervisor: */ if (version > 1 && version < 5) { int assume = 3 * !boot_cpu_has(X86_FEATURE_HYPERVISOR); x86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, assume); fixed_mask = (1L << x86_pmu.num_counters_fixed) - 1; } else if (version >= 5) x86_pmu.num_counters_fixed = fls(fixed_mask); if (boot_cpu_has(X86_FEATURE_PDCM)) { u64 capabilities; rdmsrl(MSR_IA32_PERF_CAPABILITIES, capabilities); x86_pmu.intel_cap.capabilities = capabilities; } if (x86_pmu.intel_cap.lbr_format == LBR_FORMAT_32) { x86_pmu.lbr_reset = intel_pmu_lbr_reset_32; x86_pmu.lbr_read = intel_pmu_lbr_read_32; } if (boot_cpu_has(X86_FEATURE_ARCH_LBR)) intel_pmu_arch_lbr_init(); intel_ds_init(); x86_add_quirk(intel_arch_events_quirk); /* Install first, so it runs last */ if (version >= 5) { x86_pmu.intel_cap.anythread_deprecated = edx.split.anythread_deprecated; if (x86_pmu.intel_cap.anythread_deprecated) pr_cont(" AnyThread deprecated, "); } /* * Install the hw-cache-events table: */ switch (boot_cpu_data.x86_model) { case INTEL_FAM6_CORE_YONAH: pr_cont("Core events, "); name = "core"; break; case INTEL_FAM6_CORE2_MEROM: x86_add_quirk(intel_clovertown_quirk); fallthrough; case INTEL_FAM6_CORE2_MEROM_L: case INTEL_FAM6_CORE2_PENRYN: case INTEL_FAM6_CORE2_DUNNINGTON: memcpy(hw_cache_event_ids, core2_hw_cache_event_ids, sizeof(hw_cache_event_ids)); intel_pmu_lbr_init_core(); x86_pmu.event_constraints = intel_core2_event_constraints; x86_pmu.pebs_constraints = intel_core2_pebs_event_constraints; pr_cont("Core2 events, "); name = "core2"; break; case INTEL_FAM6_NEHALEM: case INTEL_FAM6_NEHALEM_EP: case INTEL_FAM6_NEHALEM_EX: memcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_nhm(); x86_pmu.event_constraints = intel_nehalem_event_constraints; x86_pmu.pebs_constraints = intel_nehalem_pebs_event_constraints; x86_pmu.enable_all = intel_pmu_nhm_enable_all; x86_pmu.extra_regs = intel_nehalem_extra_regs; x86_pmu.limit_period = nhm_limit_period; mem_attr = nhm_mem_events_attrs; /* UOPS_ISSUED.STALLED_CYCLES */ intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1); /* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */ intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1); intel_pmu_pebs_data_source_nhm(); x86_add_quirk(intel_nehalem_quirk); x86_pmu.pebs_no_tlb = 1; extra_attr = nhm_format_attr; pr_cont("Nehalem events, "); name = "nehalem"; break; case INTEL_FAM6_ATOM_BONNELL: case INTEL_FAM6_ATOM_BONNELL_MID: case INTEL_FAM6_ATOM_SALTWELL: case INTEL_FAM6_ATOM_SALTWELL_MID: case INTEL_FAM6_ATOM_SALTWELL_TABLET: memcpy(hw_cache_event_ids, atom_hw_cache_event_ids, sizeof(hw_cache_event_ids)); intel_pmu_lbr_init_atom(); x86_pmu.event_constraints = intel_gen_event_constraints; x86_pmu.pebs_constraints = intel_atom_pebs_event_constraints; x86_pmu.pebs_aliases = intel_pebs_aliases_core2; pr_cont("Atom events, "); name = "bonnell"; break; case INTEL_FAM6_ATOM_SILVERMONT: case INTEL_FAM6_ATOM_SILVERMONT_D: case INTEL_FAM6_ATOM_SILVERMONT_MID: case INTEL_FAM6_ATOM_AIRMONT: case INTEL_FAM6_ATOM_AIRMONT_MID: memcpy(hw_cache_event_ids, slm_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, slm_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_slm(); x86_pmu.event_constraints = intel_slm_event_constraints; x86_pmu.pebs_constraints = intel_slm_pebs_event_constraints; x86_pmu.extra_regs = intel_slm_extra_regs; x86_pmu.flags |= PMU_FL_HAS_RSP_1; td_attr = slm_events_attrs; extra_attr = slm_format_attr; pr_cont("Silvermont events, "); name = "silvermont"; break; case INTEL_FAM6_ATOM_GOLDMONT: case INTEL_FAM6_ATOM_GOLDMONT_D: memcpy(hw_cache_event_ids, glm_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, glm_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_skl(); x86_pmu.event_constraints = intel_slm_event_constraints; x86_pmu.pebs_constraints = intel_glm_pebs_event_constraints; x86_pmu.extra_regs = intel_glm_extra_regs; /* * It's recommended to use CPU_CLK_UNHALTED.CORE_P + NPEBS * for precise cycles. * :pp is identical to :ppp */ x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.lbr_pt_coexist = true; x86_pmu.flags |= PMU_FL_HAS_RSP_1; td_attr = glm_events_attrs; extra_attr = slm_format_attr; pr_cont("Goldmont events, "); name = "goldmont"; break; case INTEL_FAM6_ATOM_GOLDMONT_PLUS: memcpy(hw_cache_event_ids, glp_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, glp_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_skl(); x86_pmu.event_constraints = intel_slm_event_constraints; x86_pmu.extra_regs = intel_glm_extra_regs; /* * It's recommended to use CPU_CLK_UNHALTED.CORE_P + NPEBS * for precise cycles. */ x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.lbr_pt_coexist = true; x86_pmu.pebs_capable = ~0ULL; x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_PEBS_ALL; x86_pmu.get_event_constraints = glp_get_event_constraints; td_attr = glm_events_attrs; /* Goldmont Plus has 4-wide pipeline */ event_attr_td_total_slots_scale_glm.event_str = "4"; extra_attr = slm_format_attr; pr_cont("Goldmont plus events, "); name = "goldmont_plus"; break; case INTEL_FAM6_ATOM_TREMONT_D: case INTEL_FAM6_ATOM_TREMONT: case INTEL_FAM6_ATOM_TREMONT_L: x86_pmu.late_ack = true; memcpy(hw_cache_event_ids, glp_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, tnt_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); hw_cache_event_ids[C(ITLB)][C(OP_READ)][C(RESULT_ACCESS)] = -1; intel_pmu_lbr_init_skl(); x86_pmu.event_constraints = intel_slm_event_constraints; x86_pmu.extra_regs = intel_tnt_extra_regs; /* * It's recommended to use CPU_CLK_UNHALTED.CORE_P + NPEBS * for precise cycles. */ x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.lbr_pt_coexist = true; x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.get_event_constraints = tnt_get_event_constraints; td_attr = tnt_events_attrs; extra_attr = slm_format_attr; pr_cont("Tremont events, "); name = "Tremont"; break; case INTEL_FAM6_ATOM_GRACEMONT: x86_pmu.mid_ack = true; memcpy(hw_cache_event_ids, glp_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, tnt_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); hw_cache_event_ids[C(ITLB)][C(OP_READ)][C(RESULT_ACCESS)] = -1; x86_pmu.event_constraints = intel_slm_event_constraints; x86_pmu.pebs_constraints = intel_grt_pebs_event_constraints; x86_pmu.extra_regs = intel_grt_extra_regs; x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.pebs_block = true; x86_pmu.lbr_pt_coexist = true; x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_INSTR_LATENCY; intel_pmu_pebs_data_source_grt(); x86_pmu.pebs_latency_data = adl_latency_data_small; x86_pmu.get_event_constraints = tnt_get_event_constraints; x86_pmu.limit_period = spr_limit_period; td_attr = tnt_events_attrs; mem_attr = grt_mem_attrs; extra_attr = nhm_format_attr; pr_cont("Gracemont events, "); name = "gracemont"; break; case INTEL_FAM6_ATOM_CRESTMONT: case INTEL_FAM6_ATOM_CRESTMONT_X: x86_pmu.mid_ack = true; memcpy(hw_cache_event_ids, glp_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, tnt_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); hw_cache_event_ids[C(ITLB)][C(OP_READ)][C(RESULT_ACCESS)] = -1; x86_pmu.event_constraints = intel_slm_event_constraints; x86_pmu.pebs_constraints = intel_grt_pebs_event_constraints; x86_pmu.extra_regs = intel_cmt_extra_regs; x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.lbr_pt_coexist = true; x86_pmu.pebs_block = true; x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_INSTR_LATENCY; intel_pmu_pebs_data_source_cmt(); x86_pmu.pebs_latency_data = mtl_latency_data_small; x86_pmu.get_event_constraints = cmt_get_event_constraints; x86_pmu.limit_period = spr_limit_period; td_attr = cmt_events_attrs; mem_attr = grt_mem_attrs; extra_attr = cmt_format_attr; pr_cont("Crestmont events, "); name = "crestmont"; break; case INTEL_FAM6_WESTMERE: case INTEL_FAM6_WESTMERE_EP: case INTEL_FAM6_WESTMERE_EX: memcpy(hw_cache_event_ids, westmere_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_nhm(); x86_pmu.event_constraints = intel_westmere_event_constraints; x86_pmu.enable_all = intel_pmu_nhm_enable_all; x86_pmu.pebs_constraints = intel_westmere_pebs_event_constraints; x86_pmu.extra_regs = intel_westmere_extra_regs; x86_pmu.flags |= PMU_FL_HAS_RSP_1; mem_attr = nhm_mem_events_attrs; /* UOPS_ISSUED.STALLED_CYCLES */ intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1); /* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */ intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1); intel_pmu_pebs_data_source_nhm(); extra_attr = nhm_format_attr; pr_cont("Westmere events, "); name = "westmere"; break; case INTEL_FAM6_SANDYBRIDGE: case INTEL_FAM6_SANDYBRIDGE_X: x86_add_quirk(intel_sandybridge_quirk); x86_add_quirk(intel_ht_bug); memcpy(hw_cache_event_ids, snb_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_snb(); x86_pmu.event_constraints = intel_snb_event_constraints; x86_pmu.pebs_constraints = intel_snb_pebs_event_constraints; x86_pmu.pebs_aliases = intel_pebs_aliases_snb; if (boot_cpu_data.x86_model == INTEL_FAM6_SANDYBRIDGE_X) x86_pmu.extra_regs = intel_snbep_extra_regs; else x86_pmu.extra_regs = intel_snb_extra_regs; /* all extra regs are per-cpu when HT is on */ x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; td_attr = snb_events_attrs; mem_attr = snb_mem_events_attrs; /* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */ intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1); /* UOPS_DISPATCHED.THREAD,c=1,i=1 to count stall cycles*/ intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = X86_CONFIG(.event=0xb1, .umask=0x01, .inv=1, .cmask=1); extra_attr = nhm_format_attr; pr_cont("SandyBridge events, "); name = "sandybridge"; break; case INTEL_FAM6_IVYBRIDGE: case INTEL_FAM6_IVYBRIDGE_X: x86_add_quirk(intel_ht_bug); memcpy(hw_cache_event_ids, snb_hw_cache_event_ids, sizeof(hw_cache_event_ids)); /* dTLB-load-misses on IVB is different than SNB */ hw_cache_event_ids[C(DTLB)][C(OP_READ)][C(RESULT_MISS)] = 0x8108; /* DTLB_LOAD_MISSES.DEMAND_LD_MISS_CAUSES_A_WALK */ memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_snb(); x86_pmu.event_constraints = intel_ivb_event_constraints; x86_pmu.pebs_constraints = intel_ivb_pebs_event_constraints; x86_pmu.pebs_aliases = intel_pebs_aliases_ivb; x86_pmu.pebs_prec_dist = true; if (boot_cpu_data.x86_model == INTEL_FAM6_IVYBRIDGE_X) x86_pmu.extra_regs = intel_snbep_extra_regs; else x86_pmu.extra_regs = intel_snb_extra_regs; /* all extra regs are per-cpu when HT is on */ x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; td_attr = snb_events_attrs; mem_attr = snb_mem_events_attrs; /* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */ intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1); extra_attr = nhm_format_attr; pr_cont("IvyBridge events, "); name = "ivybridge"; break; case INTEL_FAM6_HASWELL: case INTEL_FAM6_HASWELL_X: case INTEL_FAM6_HASWELL_L: case INTEL_FAM6_HASWELL_G: x86_add_quirk(intel_ht_bug); x86_add_quirk(intel_pebs_isolation_quirk); x86_pmu.late_ack = true; memcpy(hw_cache_event_ids, hsw_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, hsw_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_hsw(); x86_pmu.event_constraints = intel_hsw_event_constraints; x86_pmu.pebs_constraints = intel_hsw_pebs_event_constraints; x86_pmu.extra_regs = intel_snbep_extra_regs; x86_pmu.pebs_aliases = intel_pebs_aliases_ivb; x86_pmu.pebs_prec_dist = true; /* all extra regs are per-cpu when HT is on */ x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; x86_pmu.hw_config = hsw_hw_config; x86_pmu.get_event_constraints = hsw_get_event_constraints; x86_pmu.lbr_double_abort = true; extra_attr = boot_cpu_has(X86_FEATURE_RTM) ? hsw_format_attr : nhm_format_attr; td_attr = hsw_events_attrs; mem_attr = hsw_mem_events_attrs; tsx_attr = hsw_tsx_events_attrs; pr_cont("Haswell events, "); name = "haswell"; break; case INTEL_FAM6_BROADWELL: case INTEL_FAM6_BROADWELL_D: case INTEL_FAM6_BROADWELL_G: case INTEL_FAM6_BROADWELL_X: x86_add_quirk(intel_pebs_isolation_quirk); x86_pmu.late_ack = true; memcpy(hw_cache_event_ids, hsw_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, hsw_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); /* L3_MISS_LOCAL_DRAM is BIT(26) in Broadwell */ hw_cache_extra_regs[C(LL)][C(OP_READ)][C(RESULT_MISS)] = HSW_DEMAND_READ | BDW_L3_MISS|HSW_SNOOP_DRAM; hw_cache_extra_regs[C(LL)][C(OP_WRITE)][C(RESULT_MISS)] = HSW_DEMAND_WRITE|BDW_L3_MISS| HSW_SNOOP_DRAM; hw_cache_extra_regs[C(NODE)][C(OP_READ)][C(RESULT_ACCESS)] = HSW_DEMAND_READ| BDW_L3_MISS_LOCAL|HSW_SNOOP_DRAM; hw_cache_extra_regs[C(NODE)][C(OP_WRITE)][C(RESULT_ACCESS)] = HSW_DEMAND_WRITE| BDW_L3_MISS_LOCAL|HSW_SNOOP_DRAM; intel_pmu_lbr_init_hsw(); x86_pmu.event_constraints = intel_bdw_event_constraints; x86_pmu.pebs_constraints = intel_bdw_pebs_event_constraints; x86_pmu.extra_regs = intel_snbep_extra_regs; x86_pmu.pebs_aliases = intel_pebs_aliases_ivb; x86_pmu.pebs_prec_dist = true; /* all extra regs are per-cpu when HT is on */ x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; x86_pmu.hw_config = hsw_hw_config; x86_pmu.get_event_constraints = hsw_get_event_constraints; x86_pmu.limit_period = bdw_limit_period; extra_attr = boot_cpu_has(X86_FEATURE_RTM) ? hsw_format_attr : nhm_format_attr; td_attr = hsw_events_attrs; mem_attr = hsw_mem_events_attrs; tsx_attr = hsw_tsx_events_attrs; pr_cont("Broadwell events, "); name = "broadwell"; break; case INTEL_FAM6_XEON_PHI_KNL: case INTEL_FAM6_XEON_PHI_KNM: memcpy(hw_cache_event_ids, slm_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, knl_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_knl(); x86_pmu.event_constraints = intel_slm_event_constraints; x86_pmu.pebs_constraints = intel_slm_pebs_event_constraints; x86_pmu.extra_regs = intel_knl_extra_regs; /* all extra regs are per-cpu when HT is on */ x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; extra_attr = slm_format_attr; pr_cont("Knights Landing/Mill events, "); name = "knights-landing"; break; case INTEL_FAM6_SKYLAKE_X: pmem = true; fallthrough; case INTEL_FAM6_SKYLAKE_L: case INTEL_FAM6_SKYLAKE: case INTEL_FAM6_KABYLAKE_L: case INTEL_FAM6_KABYLAKE: case INTEL_FAM6_COMETLAKE_L: case INTEL_FAM6_COMETLAKE: x86_add_quirk(intel_pebs_isolation_quirk); x86_pmu.late_ack = true; memcpy(hw_cache_event_ids, skl_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, skl_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); intel_pmu_lbr_init_skl(); /* INT_MISC.RECOVERY_CYCLES has umask 1 in Skylake */ event_attr_td_recovery_bubbles.event_str_noht = "event=0xd,umask=0x1,cmask=1"; event_attr_td_recovery_bubbles.event_str_ht = "event=0xd,umask=0x1,cmask=1,any=1"; x86_pmu.event_constraints = intel_skl_event_constraints; x86_pmu.pebs_constraints = intel_skl_pebs_event_constraints; x86_pmu.extra_regs = intel_skl_extra_regs; x86_pmu.pebs_aliases = intel_pebs_aliases_skl; x86_pmu.pebs_prec_dist = true; /* all extra regs are per-cpu when HT is on */ x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; x86_pmu.hw_config = hsw_hw_config; x86_pmu.get_event_constraints = hsw_get_event_constraints; extra_attr = boot_cpu_has(X86_FEATURE_RTM) ? hsw_format_attr : nhm_format_attr; extra_skl_attr = skl_format_attr; td_attr = hsw_events_attrs; mem_attr = hsw_mem_events_attrs; tsx_attr = hsw_tsx_events_attrs; intel_pmu_pebs_data_source_skl(pmem); /* * Processors with CPUID.RTM_ALWAYS_ABORT have TSX deprecated by default. * TSX force abort hooks are not required on these systems. Only deploy * workaround when microcode has not enabled X86_FEATURE_RTM_ALWAYS_ABORT. */ if (boot_cpu_has(X86_FEATURE_TSX_FORCE_ABORT) && !boot_cpu_has(X86_FEATURE_RTM_ALWAYS_ABORT)) { x86_pmu.flags |= PMU_FL_TFA; x86_pmu.get_event_constraints = tfa_get_event_constraints; x86_pmu.enable_all = intel_tfa_pmu_enable_all; x86_pmu.commit_scheduling = intel_tfa_commit_scheduling; } pr_cont("Skylake events, "); name = "skylake"; break; case INTEL_FAM6_ICELAKE_X: case INTEL_FAM6_ICELAKE_D: x86_pmu.pebs_ept = 1; pmem = true; fallthrough; case INTEL_FAM6_ICELAKE_L: case INTEL_FAM6_ICELAKE: case INTEL_FAM6_TIGERLAKE_L: case INTEL_FAM6_TIGERLAKE: case INTEL_FAM6_ROCKETLAKE: x86_pmu.late_ack = true; memcpy(hw_cache_event_ids, skl_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, skl_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); hw_cache_event_ids[C(ITLB)][C(OP_READ)][C(RESULT_ACCESS)] = -1; intel_pmu_lbr_init_skl(); x86_pmu.event_constraints = intel_icl_event_constraints; x86_pmu.pebs_constraints = intel_icl_pebs_event_constraints; x86_pmu.extra_regs = intel_icl_extra_regs; x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; x86_pmu.hw_config = hsw_hw_config; x86_pmu.get_event_constraints = icl_get_event_constraints; extra_attr = boot_cpu_has(X86_FEATURE_RTM) ? hsw_format_attr : nhm_format_attr; extra_skl_attr = skl_format_attr; mem_attr = icl_events_attrs; td_attr = icl_td_events_attrs; tsx_attr = icl_tsx_events_attrs; x86_pmu.rtm_abort_event = X86_CONFIG(.event=0xc9, .umask=0x04); x86_pmu.lbr_pt_coexist = true; intel_pmu_pebs_data_source_skl(pmem); x86_pmu.num_topdown_events = 4; static_call_update(intel_pmu_update_topdown_event, &icl_update_topdown_event); static_call_update(intel_pmu_set_topdown_event_period, &icl_set_topdown_event_period); pr_cont("Icelake events, "); name = "icelake"; break; case INTEL_FAM6_SAPPHIRERAPIDS_X: case INTEL_FAM6_EMERALDRAPIDS_X: x86_pmu.flags |= PMU_FL_MEM_LOADS_AUX; x86_pmu.extra_regs = intel_spr_extra_regs; fallthrough; case INTEL_FAM6_GRANITERAPIDS_X: case INTEL_FAM6_GRANITERAPIDS_D: pmem = true; x86_pmu.late_ack = true; memcpy(hw_cache_event_ids, spr_hw_cache_event_ids, sizeof(hw_cache_event_ids)); memcpy(hw_cache_extra_regs, spr_hw_cache_extra_regs, sizeof(hw_cache_extra_regs)); x86_pmu.event_constraints = intel_spr_event_constraints; x86_pmu.pebs_constraints = intel_spr_pebs_event_constraints; if (!x86_pmu.extra_regs) x86_pmu.extra_regs = intel_gnr_extra_regs; x86_pmu.limit_period = spr_limit_period; x86_pmu.pebs_ept = 1; x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.pebs_block = true; x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; x86_pmu.flags |= PMU_FL_INSTR_LATENCY; x86_pmu.hw_config = hsw_hw_config; x86_pmu.get_event_constraints = spr_get_event_constraints; extra_attr = boot_cpu_has(X86_FEATURE_RTM) ? hsw_format_attr : nhm_format_attr; extra_skl_attr = skl_format_attr; mem_attr = spr_events_attrs; td_attr = spr_td_events_attrs; tsx_attr = spr_tsx_events_attrs; x86_pmu.rtm_abort_event = X86_CONFIG(.event=0xc9, .umask=0x04); x86_pmu.lbr_pt_coexist = true; intel_pmu_pebs_data_source_skl(pmem); x86_pmu.num_topdown_events = 8; static_call_update(intel_pmu_update_topdown_event, &icl_update_topdown_event); static_call_update(intel_pmu_set_topdown_event_period, &icl_set_topdown_event_period); pr_cont("Sapphire Rapids events, "); name = "sapphire_rapids"; break; case INTEL_FAM6_ALDERLAKE: case INTEL_FAM6_ALDERLAKE_L: case INTEL_FAM6_RAPTORLAKE: case INTEL_FAM6_RAPTORLAKE_P: case INTEL_FAM6_RAPTORLAKE_S: case INTEL_FAM6_METEORLAKE: case INTEL_FAM6_METEORLAKE_L: /* * Alder Lake has 2 types of CPU, core and atom. * * Initialize the common PerfMon capabilities here. */ x86_pmu.hybrid_pmu = kcalloc(X86_HYBRID_NUM_PMUS, sizeof(struct x86_hybrid_pmu), GFP_KERNEL); if (!x86_pmu.hybrid_pmu) return -ENOMEM; static_branch_enable(&perf_is_hybrid); x86_pmu.num_hybrid_pmus = X86_HYBRID_NUM_PMUS; x86_pmu.pebs_aliases = NULL; x86_pmu.pebs_prec_dist = true; x86_pmu.pebs_block = true; x86_pmu.flags |= PMU_FL_HAS_RSP_1; x86_pmu.flags |= PMU_FL_NO_HT_SHARING; x86_pmu.flags |= PMU_FL_INSTR_LATENCY; x86_pmu.lbr_pt_coexist = true; x86_pmu.pebs_latency_data = adl_latency_data_small; x86_pmu.num_topdown_events = 8; static_call_update(intel_pmu_update_topdown_event, &adl_update_topdown_event); static_call_update(intel_pmu_set_topdown_event_period, &adl_set_topdown_event_period); x86_pmu.filter = intel_pmu_filter; x86_pmu.get_event_constraints = adl_get_event_constraints; x86_pmu.hw_config = adl_hw_config; x86_pmu.limit_period = spr_limit_period; x86_pmu.get_hybrid_cpu_type = adl_get_hybrid_cpu_type; /* * The rtm_abort_event is used to check whether to enable GPRs * for the RTM abort event. Atom doesn't have the RTM abort * event. There is no harmful to set it in the common * x86_pmu.rtm_abort_event. */ x86_pmu.rtm_abort_event = X86_CONFIG(.event=0xc9, .umask=0x04); td_attr = adl_hybrid_events_attrs; mem_attr = adl_hybrid_mem_attrs; tsx_attr = adl_hybrid_tsx_attrs; extra_attr = boot_cpu_has(X86_FEATURE_RTM) ? adl_hybrid_extra_attr_rtm : adl_hybrid_extra_attr; /* Initialize big core specific PerfMon capabilities.*/ pmu = &x86_pmu.hybrid_pmu[X86_HYBRID_PMU_CORE_IDX]; pmu->name = "cpu_core"; pmu->cpu_type = hybrid_big; pmu->late_ack = true; if (cpu_feature_enabled(X86_FEATURE_HYBRID_CPU)) { pmu->num_counters = x86_pmu.num_counters + 2; pmu->num_counters_fixed = x86_pmu.num_counters_fixed + 1; } else { pmu->num_counters = x86_pmu.num_counters; pmu->num_counters_fixed = x86_pmu.num_counters_fixed; } /* * Quirk: For some Alder Lake machine, when all E-cores are disabled in * a BIOS, the leaf 0xA will enumerate all counters of P-cores. However, * the X86_FEATURE_HYBRID_CPU is still set. The above codes will * mistakenly add extra counters for P-cores. Correct the number of * counters here. */ if ((pmu->num_counters > 8) || (pmu->num_counters_fixed > 4)) { pmu->num_counters = x86_pmu.num_counters; pmu->num_counters_fixed = x86_pmu.num_counters_fixed; } pmu->max_pebs_events = min_t(unsigned, MAX_PEBS_EVENTS, pmu->num_counters); pmu->unconstrained = (struct event_constraint) __EVENT_CONSTRAINT(0, (1ULL << pmu->num_counters) - 1, 0, pmu->num_counters, 0, 0); pmu->intel_cap.capabilities = x86_pmu.intel_cap.capabilities; pmu->intel_cap.perf_metrics = 1; pmu->intel_cap.pebs_output_pt_available = 0; memcpy(pmu->hw_cache_event_ids, spr_hw_cache_event_ids, sizeof(pmu->hw_cache_event_ids)); memcpy(pmu->hw_cache_extra_regs, spr_hw_cache_extra_regs, sizeof(pmu->hw_cache_extra_regs)); pmu->event_constraints = intel_spr_event_constraints; pmu->pebs_constraints = intel_spr_pebs_event_constraints; pmu->extra_regs = intel_spr_extra_regs; /* Initialize Atom core specific PerfMon capabilities.*/ pmu = &x86_pmu.hybrid_pmu[X86_HYBRID_PMU_ATOM_IDX]; pmu->name = "cpu_atom"; pmu->cpu_type = hybrid_small; pmu->mid_ack = true; pmu->num_counters = x86_pmu.num_counters; pmu->num_counters_fixed = x86_pmu.num_counters_fixed; pmu->max_pebs_events = x86_pmu.max_pebs_events; pmu->unconstrained = (struct event_constraint) __EVENT_CONSTRAINT(0, (1ULL << pmu->num_counters) - 1, 0, pmu->num_counters, 0, 0); pmu->intel_cap.capabilities = x86_pmu.intel_cap.capabilities; pmu->intel_cap.perf_metrics = 0; pmu->intel_cap.pebs_output_pt_available = 1; memcpy(pmu->hw_cache_event_ids, glp_hw_cache_event_ids, sizeof(pmu->hw_cache_event_ids)); memcpy(pmu->hw_cache_extra_regs, tnt_hw_cache_extra_regs, sizeof(pmu->hw_cache_extra_regs)); pmu->hw_cache_event_ids[C(ITLB)][C(OP_READ)][C(RESULT_ACCESS)] = -1; pmu->event_constraints = intel_slm_event_constraints; pmu->pebs_constraints = intel_grt_pebs_event_constraints; pmu->extra_regs = intel_grt_extra_regs; if (is_mtl(boot_cpu_data.x86_model)) { x86_pmu.hybrid_pmu[X86_HYBRID_PMU_CORE_IDX].extra_regs = intel_gnr_extra_regs; x86_pmu.pebs_latency_data = mtl_latency_data_small; extra_attr = boot_cpu_has(X86_FEATURE_RTM) ? mtl_hybrid_extra_attr_rtm : mtl_hybrid_extra_attr; mem_attr = mtl_hybrid_mem_attrs; intel_pmu_pebs_data_source_mtl(); x86_pmu.get_event_constraints = mtl_get_event_constraints; pmu->extra_regs = intel_cmt_extra_regs; pr_cont("Meteorlake Hybrid events, "); name = "meteorlake_hybrid"; } else { x86_pmu.flags |= PMU_FL_MEM_LOADS_AUX; intel_pmu_pebs_data_source_adl(); pr_cont("Alderlake Hybrid events, "); name = "alderlake_hybrid"; } break; default: switch (x86_pmu.version) { case 1: x86_pmu.event_constraints = intel_v1_event_constraints; pr_cont("generic architected perfmon v1, "); name = "generic_arch_v1"; break; case 2: case 3: case 4: /* * default constraints for v2 and up */ x86_pmu.event_constraints = intel_gen_event_constraints; pr_cont("generic architected perfmon, "); name = "generic_arch_v2+"; break; default: /* * The default constraints for v5 and up can support up to * 16 fixed counters. For the fixed counters 4 and later, * the pseudo-encoding is applied. * The constraints may be cut according to the CPUID enumeration * by inserting the EVENT_CONSTRAINT_END. */ if (x86_pmu.num_counters_fixed > INTEL_PMC_MAX_FIXED) x86_pmu.num_counters_fixed = INTEL_PMC_MAX_FIXED; intel_v5_gen_event_constraints[x86_pmu.num_counters_fixed].weight = -1; x86_pmu.event_constraints = intel_v5_gen_event_constraints; pr_cont("generic architected perfmon, "); name = "generic_arch_v5+"; break; } } snprintf(pmu_name_str, sizeof(pmu_name_str), "%s", name); if (!is_hybrid()) { group_events_td.attrs = td_attr; group_events_mem.attrs = mem_attr; group_events_tsx.attrs = tsx_attr; group_format_extra.attrs = extra_attr; group_format_extra_skl.attrs = extra_skl_attr; x86_pmu.attr_update = attr_update; } else { hybrid_group_events_td.attrs = td_attr; hybrid_group_events_mem.attrs = mem_attr; hybrid_group_events_tsx.attrs = tsx_attr; hybrid_group_format_extra.attrs = extra_attr; x86_pmu.attr_update = hybrid_attr_update; } intel_pmu_check_num_counters(&x86_pmu.num_counters, &x86_pmu.num_counters_fixed, &x86_pmu.intel_ctrl, (u64)fixed_mask); /* AnyThread may be deprecated on arch perfmon v5 or later */ if (x86_pmu.intel_cap.anythread_deprecated) x86_pmu.format_attrs = intel_arch_formats_attr; intel_pmu_check_event_constraints(x86_pmu.event_constraints, x86_pmu.num_counters, x86_pmu.num_counters_fixed, x86_pmu.intel_ctrl); /* * Access LBR MSR may cause #GP under certain circumstances. * Check all LBR MSR here. * Disable LBR access if any LBR MSRs can not be accessed. */ if (x86_pmu.lbr_tos && !check_msr(x86_pmu.lbr_tos, 0x3UL)) x86_pmu.lbr_nr = 0; for (i = 0; i < x86_pmu.lbr_nr; i++) { if (!(check_msr(x86_pmu.lbr_from + i, 0xffffUL) && check_msr(x86_pmu.lbr_to + i, 0xffffUL))) x86_pmu.lbr_nr = 0; } if (x86_pmu.lbr_nr) { intel_pmu_lbr_init(); pr_cont("%d-deep LBR, ", x86_pmu.lbr_nr); /* only support branch_stack snapshot for perfmon >= v2 */ if (x86_pmu.disable_all == intel_pmu_disable_all) { if (boot_cpu_has(X86_FEATURE_ARCH_LBR)) { static_call_update(perf_snapshot_branch_stack, intel_pmu_snapshot_arch_branch_stack); } else { static_call_update(perf_snapshot_branch_stack, intel_pmu_snapshot_branch_stack); } } } intel_pmu_check_extra_regs(x86_pmu.extra_regs); /* Support full width counters using alternative MSR range */ if (x86_pmu.intel_cap.full_width_write) { x86_pmu.max_period = x86_pmu.cntval_mask >> 1; x86_pmu.perfctr = MSR_IA32_PMC0; pr_cont("full-width counters, "); } if (!is_hybrid() && x86_pmu.intel_cap.perf_metrics) x86_pmu.intel_ctrl |= 1ULL << GLOBAL_CTRL_EN_PERF_METRICS; if (is_hybrid()) intel_pmu_check_hybrid_pmus((u64)fixed_mask); if (x86_pmu.intel_cap.pebs_timing_info) x86_pmu.flags |= PMU_FL_RETIRE_LATENCY; intel_aux_output_init(); return 0; } /* * HT bug: phase 2 init * Called once we have valid topology information to check * whether or not HT is enabled * If HT is off, then we disable the workaround */ static __init int fixup_ht_bug(void) { int c; /* * problem not present on this CPU model, nothing to do */ if (!(x86_pmu.flags & PMU_FL_EXCL_ENABLED)) return 0; if (topology_max_smt_threads() > 1) { pr_info("PMU erratum BJ122, BV98, HSD29 worked around, HT is on\n"); return 0; } cpus_read_lock(); hardlockup_detector_perf_stop(); x86_pmu.flags &= ~(PMU_FL_EXCL_CNTRS | PMU_FL_EXCL_ENABLED); x86_pmu.start_scheduling = NULL; x86_pmu.commit_scheduling = NULL; x86_pmu.stop_scheduling = NULL; hardlockup_detector_perf_restart(); for_each_online_cpu(c) free_excl_cntrs(&per_cpu(cpu_hw_events, c)); cpus_read_unlock(); pr_info("PMU erratum BJ122, BV98, HSD29 workaround disabled, HT off\n"); return 0; } subsys_initcall(fixup_ht_bug)
linux-master
arch/x86/events/intel/core.c
/* * Support cstate residency counters * * Copyright (C) 2015, Intel Corp. * Author: Kan Liang ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * */ /* * This file export cstate related free running (read-only) counters * for perf. These counters may be use simultaneously by other tools, * such as turbostat. However, it still make sense to implement them * in perf. Because we can conveniently collect them together with * other events, and allow to use them from tools without special MSR * access code. * * The events only support system-wide mode counting. There is no * sampling support because it is not supported by the hardware. * * According to counters' scope and category, two PMUs are registered * with the perf_event core subsystem. * - 'cstate_core': The counter is available for each physical core. * The counters include CORE_C*_RESIDENCY. * - 'cstate_pkg': The counter is available for each physical package. * The counters include PKG_C*_RESIDENCY. * * All of these counters are specified in the Intel® 64 and IA-32 * Architectures Software Developer.s Manual Vol3b. * * Model specific counters: * MSR_CORE_C1_RES: CORE C1 Residency Counter * perf code: 0x00 * Available model: SLM,AMT,GLM,CNL,ICX,TNT,ADL,RPL * MTL * Scope: Core (each processor core has a MSR) * MSR_CORE_C3_RESIDENCY: CORE C3 Residency Counter * perf code: 0x01 * Available model: NHM,WSM,SNB,IVB,HSW,BDW,SKL,GLM, * CNL,KBL,CML,TNT * Scope: Core * MSR_CORE_C6_RESIDENCY: CORE C6 Residency Counter * perf code: 0x02 * Available model: SLM,AMT,NHM,WSM,SNB,IVB,HSW,BDW, * SKL,KNL,GLM,CNL,KBL,CML,ICL,ICX, * TGL,TNT,RKL,ADL,RPL,SPR,MTL * Scope: Core * MSR_CORE_C7_RESIDENCY: CORE C7 Residency Counter * perf code: 0x03 * Available model: SNB,IVB,HSW,BDW,SKL,CNL,KBL,CML, * ICL,TGL,RKL,ADL,RPL,MTL * Scope: Core * MSR_PKG_C2_RESIDENCY: Package C2 Residency Counter. * perf code: 0x00 * Available model: SNB,IVB,HSW,BDW,SKL,KNL,GLM,CNL, * KBL,CML,ICL,ICX,TGL,TNT,RKL,ADL, * RPL,SPR,MTL * Scope: Package (physical package) * MSR_PKG_C3_RESIDENCY: Package C3 Residency Counter. * perf code: 0x01 * Available model: NHM,WSM,SNB,IVB,HSW,BDW,SKL,KNL, * GLM,CNL,KBL,CML,ICL,TGL,TNT,RKL, * ADL,RPL,MTL * Scope: Package (physical package) * MSR_PKG_C6_RESIDENCY: Package C6 Residency Counter. * perf code: 0x02 * Available model: SLM,AMT,NHM,WSM,SNB,IVB,HSW,BDW, * SKL,KNL,GLM,CNL,KBL,CML,ICL,ICX, * TGL,TNT,RKL,ADL,RPL,SPR,MTL * Scope: Package (physical package) * MSR_PKG_C7_RESIDENCY: Package C7 Residency Counter. * perf code: 0x03 * Available model: NHM,WSM,SNB,IVB,HSW,BDW,SKL,CNL, * KBL,CML,ICL,TGL,RKL,ADL,RPL,MTL * Scope: Package (physical package) * MSR_PKG_C8_RESIDENCY: Package C8 Residency Counter. * perf code: 0x04 * Available model: HSW ULT,KBL,CNL,CML,ICL,TGL,RKL, * ADL,RPL,MTL * Scope: Package (physical package) * MSR_PKG_C9_RESIDENCY: Package C9 Residency Counter. * perf code: 0x05 * Available model: HSW ULT,KBL,CNL,CML,ICL,TGL,RKL, * ADL,RPL,MTL * Scope: Package (physical package) * MSR_PKG_C10_RESIDENCY: Package C10 Residency Counter. * perf code: 0x06 * Available model: HSW ULT,KBL,GLM,CNL,CML,ICL,TGL, * TNT,RKL,ADL,RPL,MTL * Scope: Package (physical package) * */ #include <linux/module.h> #include <linux/slab.h> #include <linux/perf_event.h> #include <linux/nospec.h> #include <asm/cpu_device_id.h> #include <asm/intel-family.h> #include "../perf_event.h" #include "../probe.h" MODULE_LICENSE("GPL"); #define DEFINE_CSTATE_FORMAT_ATTR(_var, _name, _format) \ static ssize_t __cstate_##_var##_show(struct device *dev, \ struct device_attribute *attr, \ char *page) \ { \ BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE); \ return sprintf(page, _format "\n"); \ } \ static struct device_attribute format_attr_##_var = \ __ATTR(_name, 0444, __cstate_##_var##_show, NULL) static ssize_t cstate_get_attr_cpumask(struct device *dev, struct device_attribute *attr, char *buf); /* Model -> events mapping */ struct cstate_model { unsigned long core_events; unsigned long pkg_events; unsigned long quirks; }; /* Quirk flags */ #define SLM_PKG_C6_USE_C7_MSR (1UL << 0) #define KNL_CORE_C6_MSR (1UL << 1) struct perf_cstate_msr { u64 msr; struct perf_pmu_events_attr *attr; }; /* cstate_core PMU */ static struct pmu cstate_core_pmu; static bool has_cstate_core; enum perf_cstate_core_events { PERF_CSTATE_CORE_C1_RES = 0, PERF_CSTATE_CORE_C3_RES, PERF_CSTATE_CORE_C6_RES, PERF_CSTATE_CORE_C7_RES, PERF_CSTATE_CORE_EVENT_MAX, }; PMU_EVENT_ATTR_STRING(c1-residency, attr_cstate_core_c1, "event=0x00"); PMU_EVENT_ATTR_STRING(c3-residency, attr_cstate_core_c3, "event=0x01"); PMU_EVENT_ATTR_STRING(c6-residency, attr_cstate_core_c6, "event=0x02"); PMU_EVENT_ATTR_STRING(c7-residency, attr_cstate_core_c7, "event=0x03"); static unsigned long core_msr_mask; PMU_EVENT_GROUP(events, cstate_core_c1); PMU_EVENT_GROUP(events, cstate_core_c3); PMU_EVENT_GROUP(events, cstate_core_c6); PMU_EVENT_GROUP(events, cstate_core_c7); static bool test_msr(int idx, void *data) { return test_bit(idx, (unsigned long *) data); } static struct perf_msr core_msr[] = { [PERF_CSTATE_CORE_C1_RES] = { MSR_CORE_C1_RES, &group_cstate_core_c1, test_msr }, [PERF_CSTATE_CORE_C3_RES] = { MSR_CORE_C3_RESIDENCY, &group_cstate_core_c3, test_msr }, [PERF_CSTATE_CORE_C6_RES] = { MSR_CORE_C6_RESIDENCY, &group_cstate_core_c6, test_msr }, [PERF_CSTATE_CORE_C7_RES] = { MSR_CORE_C7_RESIDENCY, &group_cstate_core_c7, test_msr }, }; static struct attribute *attrs_empty[] = { NULL, }; /* * There are no default events, but we need to create * "events" group (with empty attrs) before updating * it with detected events. */ static struct attribute_group core_events_attr_group = { .name = "events", .attrs = attrs_empty, }; DEFINE_CSTATE_FORMAT_ATTR(core_event, event, "config:0-63"); static struct attribute *core_format_attrs[] = { &format_attr_core_event.attr, NULL, }; static struct attribute_group core_format_attr_group = { .name = "format", .attrs = core_format_attrs, }; static cpumask_t cstate_core_cpu_mask; static DEVICE_ATTR(cpumask, S_IRUGO, cstate_get_attr_cpumask, NULL); static struct attribute *cstate_cpumask_attrs[] = { &dev_attr_cpumask.attr, NULL, }; static struct attribute_group cpumask_attr_group = { .attrs = cstate_cpumask_attrs, }; static const struct attribute_group *core_attr_groups[] = { &core_events_attr_group, &core_format_attr_group, &cpumask_attr_group, NULL, }; /* cstate_pkg PMU */ static struct pmu cstate_pkg_pmu; static bool has_cstate_pkg; enum perf_cstate_pkg_events { PERF_CSTATE_PKG_C2_RES = 0, PERF_CSTATE_PKG_C3_RES, PERF_CSTATE_PKG_C6_RES, PERF_CSTATE_PKG_C7_RES, PERF_CSTATE_PKG_C8_RES, PERF_CSTATE_PKG_C9_RES, PERF_CSTATE_PKG_C10_RES, PERF_CSTATE_PKG_EVENT_MAX, }; PMU_EVENT_ATTR_STRING(c2-residency, attr_cstate_pkg_c2, "event=0x00"); PMU_EVENT_ATTR_STRING(c3-residency, attr_cstate_pkg_c3, "event=0x01"); PMU_EVENT_ATTR_STRING(c6-residency, attr_cstate_pkg_c6, "event=0x02"); PMU_EVENT_ATTR_STRING(c7-residency, attr_cstate_pkg_c7, "event=0x03"); PMU_EVENT_ATTR_STRING(c8-residency, attr_cstate_pkg_c8, "event=0x04"); PMU_EVENT_ATTR_STRING(c9-residency, attr_cstate_pkg_c9, "event=0x05"); PMU_EVENT_ATTR_STRING(c10-residency, attr_cstate_pkg_c10, "event=0x06"); static unsigned long pkg_msr_mask; PMU_EVENT_GROUP(events, cstate_pkg_c2); PMU_EVENT_GROUP(events, cstate_pkg_c3); PMU_EVENT_GROUP(events, cstate_pkg_c6); PMU_EVENT_GROUP(events, cstate_pkg_c7); PMU_EVENT_GROUP(events, cstate_pkg_c8); PMU_EVENT_GROUP(events, cstate_pkg_c9); PMU_EVENT_GROUP(events, cstate_pkg_c10); static struct perf_msr pkg_msr[] = { [PERF_CSTATE_PKG_C2_RES] = { MSR_PKG_C2_RESIDENCY, &group_cstate_pkg_c2, test_msr }, [PERF_CSTATE_PKG_C3_RES] = { MSR_PKG_C3_RESIDENCY, &group_cstate_pkg_c3, test_msr }, [PERF_CSTATE_PKG_C6_RES] = { MSR_PKG_C6_RESIDENCY, &group_cstate_pkg_c6, test_msr }, [PERF_CSTATE_PKG_C7_RES] = { MSR_PKG_C7_RESIDENCY, &group_cstate_pkg_c7, test_msr }, [PERF_CSTATE_PKG_C8_RES] = { MSR_PKG_C8_RESIDENCY, &group_cstate_pkg_c8, test_msr }, [PERF_CSTATE_PKG_C9_RES] = { MSR_PKG_C9_RESIDENCY, &group_cstate_pkg_c9, test_msr }, [PERF_CSTATE_PKG_C10_RES] = { MSR_PKG_C10_RESIDENCY, &group_cstate_pkg_c10, test_msr }, }; static struct attribute_group pkg_events_attr_group = { .name = "events", .attrs = attrs_empty, }; DEFINE_CSTATE_FORMAT_ATTR(pkg_event, event, "config:0-63"); static struct attribute *pkg_format_attrs[] = { &format_attr_pkg_event.attr, NULL, }; static struct attribute_group pkg_format_attr_group = { .name = "format", .attrs = pkg_format_attrs, }; static cpumask_t cstate_pkg_cpu_mask; static const struct attribute_group *pkg_attr_groups[] = { &pkg_events_attr_group, &pkg_format_attr_group, &cpumask_attr_group, NULL, }; static ssize_t cstate_get_attr_cpumask(struct device *dev, struct device_attribute *attr, char *buf) { struct pmu *pmu = dev_get_drvdata(dev); if (pmu == &cstate_core_pmu) return cpumap_print_to_pagebuf(true, buf, &cstate_core_cpu_mask); else if (pmu == &cstate_pkg_pmu) return cpumap_print_to_pagebuf(true, buf, &cstate_pkg_cpu_mask); else return 0; } static int cstate_pmu_event_init(struct perf_event *event) { u64 cfg = event->attr.config; int cpu; if (event->attr.type != event->pmu->type) return -ENOENT; /* unsupported modes and filters */ if (event->attr.sample_period) /* no sampling */ return -EINVAL; if (event->cpu < 0) return -EINVAL; if (event->pmu == &cstate_core_pmu) { if (cfg >= PERF_CSTATE_CORE_EVENT_MAX) return -EINVAL; cfg = array_index_nospec((unsigned long)cfg, PERF_CSTATE_CORE_EVENT_MAX); if (!(core_msr_mask & (1 << cfg))) return -EINVAL; event->hw.event_base = core_msr[cfg].msr; cpu = cpumask_any_and(&cstate_core_cpu_mask, topology_sibling_cpumask(event->cpu)); } else if (event->pmu == &cstate_pkg_pmu) { if (cfg >= PERF_CSTATE_PKG_EVENT_MAX) return -EINVAL; cfg = array_index_nospec((unsigned long)cfg, PERF_CSTATE_PKG_EVENT_MAX); if (!(pkg_msr_mask & (1 << cfg))) return -EINVAL; event->hw.event_base = pkg_msr[cfg].msr; cpu = cpumask_any_and(&cstate_pkg_cpu_mask, topology_die_cpumask(event->cpu)); } else { return -ENOENT; } if (cpu >= nr_cpu_ids) return -ENODEV; event->cpu = cpu; event->hw.config = cfg; event->hw.idx = -1; return 0; } static inline u64 cstate_pmu_read_counter(struct perf_event *event) { u64 val; rdmsrl(event->hw.event_base, val); return val; } static void cstate_pmu_event_update(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 prev_raw_count, new_raw_count; prev_raw_count = local64_read(&hwc->prev_count); do { new_raw_count = cstate_pmu_read_counter(event); } while (!local64_try_cmpxchg(&hwc->prev_count, &prev_raw_count, new_raw_count)); local64_add(new_raw_count - prev_raw_count, &event->count); } static void cstate_pmu_event_start(struct perf_event *event, int mode) { local64_set(&event->hw.prev_count, cstate_pmu_read_counter(event)); } static void cstate_pmu_event_stop(struct perf_event *event, int mode) { cstate_pmu_event_update(event); } static void cstate_pmu_event_del(struct perf_event *event, int mode) { cstate_pmu_event_stop(event, PERF_EF_UPDATE); } static int cstate_pmu_event_add(struct perf_event *event, int mode) { if (mode & PERF_EF_START) cstate_pmu_event_start(event, mode); return 0; } /* * Check if exiting cpu is the designated reader. If so migrate the * events when there is a valid target available */ static int cstate_cpu_exit(unsigned int cpu) { unsigned int target; if (has_cstate_core && cpumask_test_and_clear_cpu(cpu, &cstate_core_cpu_mask)) { target = cpumask_any_but(topology_sibling_cpumask(cpu), cpu); /* Migrate events if there is a valid target */ if (target < nr_cpu_ids) { cpumask_set_cpu(target, &cstate_core_cpu_mask); perf_pmu_migrate_context(&cstate_core_pmu, cpu, target); } } if (has_cstate_pkg && cpumask_test_and_clear_cpu(cpu, &cstate_pkg_cpu_mask)) { target = cpumask_any_but(topology_die_cpumask(cpu), cpu); /* Migrate events if there is a valid target */ if (target < nr_cpu_ids) { cpumask_set_cpu(target, &cstate_pkg_cpu_mask); perf_pmu_migrate_context(&cstate_pkg_pmu, cpu, target); } } return 0; } static int cstate_cpu_init(unsigned int cpu) { unsigned int target; /* * If this is the first online thread of that core, set it in * the core cpu mask as the designated reader. */ target = cpumask_any_and(&cstate_core_cpu_mask, topology_sibling_cpumask(cpu)); if (has_cstate_core && target >= nr_cpu_ids) cpumask_set_cpu(cpu, &cstate_core_cpu_mask); /* * If this is the first online thread of that package, set it * in the package cpu mask as the designated reader. */ target = cpumask_any_and(&cstate_pkg_cpu_mask, topology_die_cpumask(cpu)); if (has_cstate_pkg && target >= nr_cpu_ids) cpumask_set_cpu(cpu, &cstate_pkg_cpu_mask); return 0; } static const struct attribute_group *core_attr_update[] = { &group_cstate_core_c1, &group_cstate_core_c3, &group_cstate_core_c6, &group_cstate_core_c7, NULL, }; static const struct attribute_group *pkg_attr_update[] = { &group_cstate_pkg_c2, &group_cstate_pkg_c3, &group_cstate_pkg_c6, &group_cstate_pkg_c7, &group_cstate_pkg_c8, &group_cstate_pkg_c9, &group_cstate_pkg_c10, NULL, }; static struct pmu cstate_core_pmu = { .attr_groups = core_attr_groups, .attr_update = core_attr_update, .name = "cstate_core", .task_ctx_nr = perf_invalid_context, .event_init = cstate_pmu_event_init, .add = cstate_pmu_event_add, .del = cstate_pmu_event_del, .start = cstate_pmu_event_start, .stop = cstate_pmu_event_stop, .read = cstate_pmu_event_update, .capabilities = PERF_PMU_CAP_NO_INTERRUPT | PERF_PMU_CAP_NO_EXCLUDE, .module = THIS_MODULE, }; static struct pmu cstate_pkg_pmu = { .attr_groups = pkg_attr_groups, .attr_update = pkg_attr_update, .name = "cstate_pkg", .task_ctx_nr = perf_invalid_context, .event_init = cstate_pmu_event_init, .add = cstate_pmu_event_add, .del = cstate_pmu_event_del, .start = cstate_pmu_event_start, .stop = cstate_pmu_event_stop, .read = cstate_pmu_event_update, .capabilities = PERF_PMU_CAP_NO_INTERRUPT | PERF_PMU_CAP_NO_EXCLUDE, .module = THIS_MODULE, }; static const struct cstate_model nhm_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C3_RES) | BIT(PERF_CSTATE_CORE_C6_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES) | BIT(PERF_CSTATE_PKG_C7_RES), }; static const struct cstate_model snb_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C3_RES) | BIT(PERF_CSTATE_CORE_C6_RES) | BIT(PERF_CSTATE_CORE_C7_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES) | BIT(PERF_CSTATE_PKG_C7_RES), }; static const struct cstate_model hswult_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C3_RES) | BIT(PERF_CSTATE_CORE_C6_RES) | BIT(PERF_CSTATE_CORE_C7_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES) | BIT(PERF_CSTATE_PKG_C7_RES) | BIT(PERF_CSTATE_PKG_C8_RES) | BIT(PERF_CSTATE_PKG_C9_RES) | BIT(PERF_CSTATE_PKG_C10_RES), }; static const struct cstate_model cnl_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C1_RES) | BIT(PERF_CSTATE_CORE_C3_RES) | BIT(PERF_CSTATE_CORE_C6_RES) | BIT(PERF_CSTATE_CORE_C7_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES) | BIT(PERF_CSTATE_PKG_C7_RES) | BIT(PERF_CSTATE_PKG_C8_RES) | BIT(PERF_CSTATE_PKG_C9_RES) | BIT(PERF_CSTATE_PKG_C10_RES), }; static const struct cstate_model icl_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C6_RES) | BIT(PERF_CSTATE_CORE_C7_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES) | BIT(PERF_CSTATE_PKG_C7_RES) | BIT(PERF_CSTATE_PKG_C8_RES) | BIT(PERF_CSTATE_PKG_C9_RES) | BIT(PERF_CSTATE_PKG_C10_RES), }; static const struct cstate_model icx_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C1_RES) | BIT(PERF_CSTATE_CORE_C6_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C6_RES), }; static const struct cstate_model adl_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C1_RES) | BIT(PERF_CSTATE_CORE_C6_RES) | BIT(PERF_CSTATE_CORE_C7_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES) | BIT(PERF_CSTATE_PKG_C7_RES) | BIT(PERF_CSTATE_PKG_C8_RES) | BIT(PERF_CSTATE_PKG_C9_RES) | BIT(PERF_CSTATE_PKG_C10_RES), }; static const struct cstate_model slm_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C1_RES) | BIT(PERF_CSTATE_CORE_C6_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C6_RES), .quirks = SLM_PKG_C6_USE_C7_MSR, }; static const struct cstate_model knl_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C6_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES), .quirks = KNL_CORE_C6_MSR, }; static const struct cstate_model glm_cstates __initconst = { .core_events = BIT(PERF_CSTATE_CORE_C1_RES) | BIT(PERF_CSTATE_CORE_C3_RES) | BIT(PERF_CSTATE_CORE_C6_RES), .pkg_events = BIT(PERF_CSTATE_PKG_C2_RES) | BIT(PERF_CSTATE_PKG_C3_RES) | BIT(PERF_CSTATE_PKG_C6_RES) | BIT(PERF_CSTATE_PKG_C10_RES), }; static const struct x86_cpu_id intel_cstates_match[] __initconst = { X86_MATCH_INTEL_FAM6_MODEL(NEHALEM, &nhm_cstates), X86_MATCH_INTEL_FAM6_MODEL(NEHALEM_EP, &nhm_cstates), X86_MATCH_INTEL_FAM6_MODEL(NEHALEM_EX, &nhm_cstates), X86_MATCH_INTEL_FAM6_MODEL(WESTMERE, &nhm_cstates), X86_MATCH_INTEL_FAM6_MODEL(WESTMERE_EP, &nhm_cstates), X86_MATCH_INTEL_FAM6_MODEL(WESTMERE_EX, &nhm_cstates), X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE_X, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE_X, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(HASWELL, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(HASWELL_X, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(HASWELL_G, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(HASWELL_L, &hswult_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_SILVERMONT, &slm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_SILVERMONT_D, &slm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_AIRMONT, &slm_cstates), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_D, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_G, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_X, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_L, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_X, &snb_cstates), X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE_L, &hswult_cstates), X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE, &hswult_cstates), X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE_L, &hswult_cstates), X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE, &hswult_cstates), X86_MATCH_INTEL_FAM6_MODEL(CANNONLAKE_L, &cnl_cstates), X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNL, &knl_cstates), X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNM, &knl_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT, &glm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_D, &glm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_PLUS, &glm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT_D, &glm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT, &glm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT_L, &glm_cstates), X86_MATCH_INTEL_FAM6_MODEL(ATOM_GRACEMONT, &adl_cstates), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_L, &icl_cstates), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE, &icl_cstates), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_X, &icx_cstates), X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_D, &icx_cstates), X86_MATCH_INTEL_FAM6_MODEL(SAPPHIRERAPIDS_X, &icx_cstates), X86_MATCH_INTEL_FAM6_MODEL(EMERALDRAPIDS_X, &icx_cstates), X86_MATCH_INTEL_FAM6_MODEL(GRANITERAPIDS_X, &icx_cstates), X86_MATCH_INTEL_FAM6_MODEL(GRANITERAPIDS_D, &icx_cstates), X86_MATCH_INTEL_FAM6_MODEL(TIGERLAKE_L, &icl_cstates), X86_MATCH_INTEL_FAM6_MODEL(TIGERLAKE, &icl_cstates), X86_MATCH_INTEL_FAM6_MODEL(ROCKETLAKE, &icl_cstates), X86_MATCH_INTEL_FAM6_MODEL(ALDERLAKE, &adl_cstates), X86_MATCH_INTEL_FAM6_MODEL(ALDERLAKE_L, &adl_cstates), X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE, &adl_cstates), X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE_P, &adl_cstates), X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE_S, &adl_cstates), X86_MATCH_INTEL_FAM6_MODEL(METEORLAKE, &adl_cstates), X86_MATCH_INTEL_FAM6_MODEL(METEORLAKE_L, &adl_cstates), { }, }; MODULE_DEVICE_TABLE(x86cpu, intel_cstates_match); static int __init cstate_probe(const struct cstate_model *cm) { /* SLM has different MSR for PKG C6 */ if (cm->quirks & SLM_PKG_C6_USE_C7_MSR) pkg_msr[PERF_CSTATE_PKG_C6_RES].msr = MSR_PKG_C7_RESIDENCY; /* KNL has different MSR for CORE C6 */ if (cm->quirks & KNL_CORE_C6_MSR) pkg_msr[PERF_CSTATE_CORE_C6_RES].msr = MSR_KNL_CORE_C6_RESIDENCY; core_msr_mask = perf_msr_probe(core_msr, PERF_CSTATE_CORE_EVENT_MAX, true, (void *) &cm->core_events); pkg_msr_mask = perf_msr_probe(pkg_msr, PERF_CSTATE_PKG_EVENT_MAX, true, (void *) &cm->pkg_events); has_cstate_core = !!core_msr_mask; has_cstate_pkg = !!pkg_msr_mask; return (has_cstate_core || has_cstate_pkg) ? 0 : -ENODEV; } static inline void cstate_cleanup(void) { cpuhp_remove_state_nocalls(CPUHP_AP_PERF_X86_CSTATE_ONLINE); cpuhp_remove_state_nocalls(CPUHP_AP_PERF_X86_CSTATE_STARTING); if (has_cstate_core) perf_pmu_unregister(&cstate_core_pmu); if (has_cstate_pkg) perf_pmu_unregister(&cstate_pkg_pmu); } static int __init cstate_init(void) { int err; cpuhp_setup_state(CPUHP_AP_PERF_X86_CSTATE_STARTING, "perf/x86/cstate:starting", cstate_cpu_init, NULL); cpuhp_setup_state(CPUHP_AP_PERF_X86_CSTATE_ONLINE, "perf/x86/cstate:online", NULL, cstate_cpu_exit); if (has_cstate_core) { err = perf_pmu_register(&cstate_core_pmu, cstate_core_pmu.name, -1); if (err) { has_cstate_core = false; pr_info("Failed to register cstate core pmu\n"); cstate_cleanup(); return err; } } if (has_cstate_pkg) { if (topology_max_die_per_package() > 1) { err = perf_pmu_register(&cstate_pkg_pmu, "cstate_die", -1); } else { err = perf_pmu_register(&cstate_pkg_pmu, cstate_pkg_pmu.name, -1); } if (err) { has_cstate_pkg = false; pr_info("Failed to register cstate pkg pmu\n"); cstate_cleanup(); return err; } } return 0; } static int __init cstate_pmu_init(void) { const struct x86_cpu_id *id; int err; if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) return -ENODEV; id = x86_match_cpu(intel_cstates_match); if (!id) return -ENODEV; err = cstate_probe((const struct cstate_model *) id->driver_data); if (err) return err; return cstate_init(); } module_init(cstate_pmu_init); static void __exit cstate_pmu_exit(void) { cstate_cleanup(); } module_exit(cstate_pmu_exit);
linux-master
arch/x86/events/intel/cstate.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/bitops.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/sched/clock.h> #include <asm/cpu_entry_area.h> #include <asm/perf_event.h> #include <asm/tlbflush.h> #include <asm/insn.h> #include <asm/io.h> #include <asm/timer.h> #include "../perf_event.h" /* Waste a full page so it can be mapped into the cpu_entry_area */ DEFINE_PER_CPU_PAGE_ALIGNED(struct debug_store, cpu_debug_store); /* The size of a BTS record in bytes: */ #define BTS_RECORD_SIZE 24 #define PEBS_FIXUP_SIZE PAGE_SIZE /* * pebs_record_32 for p4 and core not supported struct pebs_record_32 { u32 flags, ip; u32 ax, bc, cx, dx; u32 si, di, bp, sp; }; */ union intel_x86_pebs_dse { u64 val; struct { unsigned int ld_dse:4; unsigned int ld_stlb_miss:1; unsigned int ld_locked:1; unsigned int ld_data_blk:1; unsigned int ld_addr_blk:1; unsigned int ld_reserved:24; }; struct { unsigned int st_l1d_hit:1; unsigned int st_reserved1:3; unsigned int st_stlb_miss:1; unsigned int st_locked:1; unsigned int st_reserved2:26; }; struct { unsigned int st_lat_dse:4; unsigned int st_lat_stlb_miss:1; unsigned int st_lat_locked:1; unsigned int ld_reserved3:26; }; struct { unsigned int mtl_dse:5; unsigned int mtl_locked:1; unsigned int mtl_stlb_miss:1; unsigned int mtl_fwd_blk:1; unsigned int ld_reserved4:24; }; }; /* * Map PEBS Load Latency Data Source encodings to generic * memory data source information */ #define P(a, b) PERF_MEM_S(a, b) #define OP_LH (P(OP, LOAD) | P(LVL, HIT)) #define LEVEL(x) P(LVLNUM, x) #define REM P(REMOTE, REMOTE) #define SNOOP_NONE_MISS (P(SNOOP, NONE) | P(SNOOP, MISS)) /* Version for Sandy Bridge and later */ static u64 pebs_data_source[] = { P(OP, LOAD) | P(LVL, MISS) | LEVEL(L3) | P(SNOOP, NA),/* 0x00:ukn L3 */ OP_LH | P(LVL, L1) | LEVEL(L1) | P(SNOOP, NONE), /* 0x01: L1 local */ OP_LH | P(LVL, LFB) | LEVEL(LFB) | P(SNOOP, NONE), /* 0x02: LFB hit */ OP_LH | P(LVL, L2) | LEVEL(L2) | P(SNOOP, NONE), /* 0x03: L2 hit */ OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, NONE), /* 0x04: L3 hit */ OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, MISS), /* 0x05: L3 hit, snoop miss */ OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HIT), /* 0x06: L3 hit, snoop hit */ OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HITM), /* 0x07: L3 hit, snoop hitm */ OP_LH | P(LVL, REM_CCE1) | REM | LEVEL(L3) | P(SNOOP, HIT), /* 0x08: L3 miss snoop hit */ OP_LH | P(LVL, REM_CCE1) | REM | LEVEL(L3) | P(SNOOP, HITM), /* 0x09: L3 miss snoop hitm*/ OP_LH | P(LVL, LOC_RAM) | LEVEL(RAM) | P(SNOOP, HIT), /* 0x0a: L3 miss, shared */ OP_LH | P(LVL, REM_RAM1) | REM | LEVEL(L3) | P(SNOOP, HIT), /* 0x0b: L3 miss, shared */ OP_LH | P(LVL, LOC_RAM) | LEVEL(RAM) | SNOOP_NONE_MISS, /* 0x0c: L3 miss, excl */ OP_LH | P(LVL, REM_RAM1) | LEVEL(RAM) | REM | SNOOP_NONE_MISS, /* 0x0d: L3 miss, excl */ OP_LH | P(LVL, IO) | LEVEL(NA) | P(SNOOP, NONE), /* 0x0e: I/O */ OP_LH | P(LVL, UNC) | LEVEL(NA) | P(SNOOP, NONE), /* 0x0f: uncached */ }; /* Patch up minor differences in the bits */ void __init intel_pmu_pebs_data_source_nhm(void) { pebs_data_source[0x05] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HIT); pebs_data_source[0x06] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HITM); pebs_data_source[0x07] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HITM); } static void __init __intel_pmu_pebs_data_source_skl(bool pmem, u64 *data_source) { u64 pmem_or_l4 = pmem ? LEVEL(PMEM) : LEVEL(L4); data_source[0x08] = OP_LH | pmem_or_l4 | P(SNOOP, HIT); data_source[0x09] = OP_LH | pmem_or_l4 | REM | P(SNOOP, HIT); data_source[0x0b] = OP_LH | LEVEL(RAM) | REM | P(SNOOP, NONE); data_source[0x0c] = OP_LH | LEVEL(ANY_CACHE) | REM | P(SNOOPX, FWD); data_source[0x0d] = OP_LH | LEVEL(ANY_CACHE) | REM | P(SNOOP, HITM); } void __init intel_pmu_pebs_data_source_skl(bool pmem) { __intel_pmu_pebs_data_source_skl(pmem, pebs_data_source); } static void __init __intel_pmu_pebs_data_source_grt(u64 *data_source) { data_source[0x05] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HIT); data_source[0x06] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HITM); data_source[0x08] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOPX, FWD); } void __init intel_pmu_pebs_data_source_grt(void) { __intel_pmu_pebs_data_source_grt(pebs_data_source); } void __init intel_pmu_pebs_data_source_adl(void) { u64 *data_source; data_source = x86_pmu.hybrid_pmu[X86_HYBRID_PMU_CORE_IDX].pebs_data_source; memcpy(data_source, pebs_data_source, sizeof(pebs_data_source)); __intel_pmu_pebs_data_source_skl(false, data_source); data_source = x86_pmu.hybrid_pmu[X86_HYBRID_PMU_ATOM_IDX].pebs_data_source; memcpy(data_source, pebs_data_source, sizeof(pebs_data_source)); __intel_pmu_pebs_data_source_grt(data_source); } static void __init __intel_pmu_pebs_data_source_cmt(u64 *data_source) { data_source[0x07] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOPX, FWD); data_source[0x08] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HITM); data_source[0x0a] = OP_LH | P(LVL, LOC_RAM) | LEVEL(RAM) | P(SNOOP, NONE); data_source[0x0b] = OP_LH | LEVEL(RAM) | REM | P(SNOOP, NONE); data_source[0x0c] = OP_LH | LEVEL(RAM) | REM | P(SNOOPX, FWD); data_source[0x0d] = OP_LH | LEVEL(RAM) | REM | P(SNOOP, HITM); } void __init intel_pmu_pebs_data_source_mtl(void) { u64 *data_source; data_source = x86_pmu.hybrid_pmu[X86_HYBRID_PMU_CORE_IDX].pebs_data_source; memcpy(data_source, pebs_data_source, sizeof(pebs_data_source)); __intel_pmu_pebs_data_source_skl(false, data_source); data_source = x86_pmu.hybrid_pmu[X86_HYBRID_PMU_ATOM_IDX].pebs_data_source; memcpy(data_source, pebs_data_source, sizeof(pebs_data_source)); __intel_pmu_pebs_data_source_cmt(data_source); } void __init intel_pmu_pebs_data_source_cmt(void) { __intel_pmu_pebs_data_source_cmt(pebs_data_source); } static u64 precise_store_data(u64 status) { union intel_x86_pebs_dse dse; u64 val = P(OP, STORE) | P(SNOOP, NA) | P(LVL, L1) | P(TLB, L2); dse.val = status; /* * bit 4: TLB access * 1 = stored missed 2nd level TLB * * so it either hit the walker or the OS * otherwise hit 2nd level TLB */ if (dse.st_stlb_miss) val |= P(TLB, MISS); else val |= P(TLB, HIT); /* * bit 0: hit L1 data cache * if not set, then all we know is that * it missed L1D */ if (dse.st_l1d_hit) val |= P(LVL, HIT); else val |= P(LVL, MISS); /* * bit 5: Locked prefix */ if (dse.st_locked) val |= P(LOCK, LOCKED); return val; } static u64 precise_datala_hsw(struct perf_event *event, u64 status) { union perf_mem_data_src dse; dse.val = PERF_MEM_NA; if (event->hw.flags & PERF_X86_EVENT_PEBS_ST_HSW) dse.mem_op = PERF_MEM_OP_STORE; else if (event->hw.flags & PERF_X86_EVENT_PEBS_LD_HSW) dse.mem_op = PERF_MEM_OP_LOAD; /* * L1 info only valid for following events: * * MEM_UOPS_RETIRED.STLB_MISS_STORES * MEM_UOPS_RETIRED.LOCK_STORES * MEM_UOPS_RETIRED.SPLIT_STORES * MEM_UOPS_RETIRED.ALL_STORES */ if (event->hw.flags & PERF_X86_EVENT_PEBS_ST_HSW) { if (status & 1) dse.mem_lvl = PERF_MEM_LVL_L1 | PERF_MEM_LVL_HIT; else dse.mem_lvl = PERF_MEM_LVL_L1 | PERF_MEM_LVL_MISS; } return dse.val; } static inline void pebs_set_tlb_lock(u64 *val, bool tlb, bool lock) { /* * TLB access * 0 = did not miss 2nd level TLB * 1 = missed 2nd level TLB */ if (tlb) *val |= P(TLB, MISS) | P(TLB, L2); else *val |= P(TLB, HIT) | P(TLB, L1) | P(TLB, L2); /* locked prefix */ if (lock) *val |= P(LOCK, LOCKED); } /* Retrieve the latency data for e-core of ADL */ static u64 __adl_latency_data_small(struct perf_event *event, u64 status, u8 dse, bool tlb, bool lock, bool blk) { u64 val; WARN_ON_ONCE(hybrid_pmu(event->pmu)->cpu_type == hybrid_big); dse &= PERF_PEBS_DATA_SOURCE_MASK; val = hybrid_var(event->pmu, pebs_data_source)[dse]; pebs_set_tlb_lock(&val, tlb, lock); if (blk) val |= P(BLK, DATA); else val |= P(BLK, NA); return val; } u64 adl_latency_data_small(struct perf_event *event, u64 status) { union intel_x86_pebs_dse dse; dse.val = status; return __adl_latency_data_small(event, status, dse.ld_dse, dse.ld_locked, dse.ld_stlb_miss, dse.ld_data_blk); } /* Retrieve the latency data for e-core of MTL */ u64 mtl_latency_data_small(struct perf_event *event, u64 status) { union intel_x86_pebs_dse dse; dse.val = status; return __adl_latency_data_small(event, status, dse.mtl_dse, dse.mtl_stlb_miss, dse.mtl_locked, dse.mtl_fwd_blk); } static u64 load_latency_data(struct perf_event *event, u64 status) { union intel_x86_pebs_dse dse; u64 val; dse.val = status; /* * use the mapping table for bit 0-3 */ val = hybrid_var(event->pmu, pebs_data_source)[dse.ld_dse]; /* * Nehalem models do not support TLB, Lock infos */ if (x86_pmu.pebs_no_tlb) { val |= P(TLB, NA) | P(LOCK, NA); return val; } pebs_set_tlb_lock(&val, dse.ld_stlb_miss, dse.ld_locked); /* * Ice Lake and earlier models do not support block infos. */ if (!x86_pmu.pebs_block) { val |= P(BLK, NA); return val; } /* * bit 6: load was blocked since its data could not be forwarded * from a preceding store */ if (dse.ld_data_blk) val |= P(BLK, DATA); /* * bit 7: load was blocked due to potential address conflict with * a preceding store */ if (dse.ld_addr_blk) val |= P(BLK, ADDR); if (!dse.ld_data_blk && !dse.ld_addr_blk) val |= P(BLK, NA); return val; } static u64 store_latency_data(struct perf_event *event, u64 status) { union intel_x86_pebs_dse dse; union perf_mem_data_src src; u64 val; dse.val = status; /* * use the mapping table for bit 0-3 */ val = hybrid_var(event->pmu, pebs_data_source)[dse.st_lat_dse]; pebs_set_tlb_lock(&val, dse.st_lat_stlb_miss, dse.st_lat_locked); val |= P(BLK, NA); /* * the pebs_data_source table is only for loads * so override the mem_op to say STORE instead */ src.val = val; src.mem_op = P(OP,STORE); return src.val; } struct pebs_record_core { u64 flags, ip; u64 ax, bx, cx, dx; u64 si, di, bp, sp; u64 r8, r9, r10, r11; u64 r12, r13, r14, r15; }; struct pebs_record_nhm { u64 flags, ip; u64 ax, bx, cx, dx; u64 si, di, bp, sp; u64 r8, r9, r10, r11; u64 r12, r13, r14, r15; u64 status, dla, dse, lat; }; /* * Same as pebs_record_nhm, with two additional fields. */ struct pebs_record_hsw { u64 flags, ip; u64 ax, bx, cx, dx; u64 si, di, bp, sp; u64 r8, r9, r10, r11; u64 r12, r13, r14, r15; u64 status, dla, dse, lat; u64 real_ip, tsx_tuning; }; union hsw_tsx_tuning { struct { u32 cycles_last_block : 32, hle_abort : 1, rtm_abort : 1, instruction_abort : 1, non_instruction_abort : 1, retry : 1, data_conflict : 1, capacity_writes : 1, capacity_reads : 1; }; u64 value; }; #define PEBS_HSW_TSX_FLAGS 0xff00000000ULL /* Same as HSW, plus TSC */ struct pebs_record_skl { u64 flags, ip; u64 ax, bx, cx, dx; u64 si, di, bp, sp; u64 r8, r9, r10, r11; u64 r12, r13, r14, r15; u64 status, dla, dse, lat; u64 real_ip, tsx_tuning; u64 tsc; }; void init_debug_store_on_cpu(int cpu) { struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds; if (!ds) return; wrmsr_on_cpu(cpu, MSR_IA32_DS_AREA, (u32)((u64)(unsigned long)ds), (u32)((u64)(unsigned long)ds >> 32)); } void fini_debug_store_on_cpu(int cpu) { if (!per_cpu(cpu_hw_events, cpu).ds) return; wrmsr_on_cpu(cpu, MSR_IA32_DS_AREA, 0, 0); } static DEFINE_PER_CPU(void *, insn_buffer); static void ds_update_cea(void *cea, void *addr, size_t size, pgprot_t prot) { unsigned long start = (unsigned long)cea; phys_addr_t pa; size_t msz = 0; pa = virt_to_phys(addr); preempt_disable(); for (; msz < size; msz += PAGE_SIZE, pa += PAGE_SIZE, cea += PAGE_SIZE) cea_set_pte(cea, pa, prot); /* * This is a cross-CPU update of the cpu_entry_area, we must shoot down * all TLB entries for it. */ flush_tlb_kernel_range(start, start + size); preempt_enable(); } static void ds_clear_cea(void *cea, size_t size) { unsigned long start = (unsigned long)cea; size_t msz = 0; preempt_disable(); for (; msz < size; msz += PAGE_SIZE, cea += PAGE_SIZE) cea_set_pte(cea, 0, PAGE_NONE); flush_tlb_kernel_range(start, start + size); preempt_enable(); } static void *dsalloc_pages(size_t size, gfp_t flags, int cpu) { unsigned int order = get_order(size); int node = cpu_to_node(cpu); struct page *page; page = __alloc_pages_node(node, flags | __GFP_ZERO, order); return page ? page_address(page) : NULL; } static void dsfree_pages(const void *buffer, size_t size) { if (buffer) free_pages((unsigned long)buffer, get_order(size)); } static int alloc_pebs_buffer(int cpu) { struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu); struct debug_store *ds = hwev->ds; size_t bsiz = x86_pmu.pebs_buffer_size; int max, node = cpu_to_node(cpu); void *buffer, *insn_buff, *cea; if (!x86_pmu.pebs) return 0; buffer = dsalloc_pages(bsiz, GFP_KERNEL, cpu); if (unlikely(!buffer)) return -ENOMEM; /* * HSW+ already provides us the eventing ip; no need to allocate this * buffer then. */ if (x86_pmu.intel_cap.pebs_format < 2) { insn_buff = kzalloc_node(PEBS_FIXUP_SIZE, GFP_KERNEL, node); if (!insn_buff) { dsfree_pages(buffer, bsiz); return -ENOMEM; } per_cpu(insn_buffer, cpu) = insn_buff; } hwev->ds_pebs_vaddr = buffer; /* Update the cpu entry area mapping */ cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.pebs_buffer; ds->pebs_buffer_base = (unsigned long) cea; ds_update_cea(cea, buffer, bsiz, PAGE_KERNEL); ds->pebs_index = ds->pebs_buffer_base; max = x86_pmu.pebs_record_size * (bsiz / x86_pmu.pebs_record_size); ds->pebs_absolute_maximum = ds->pebs_buffer_base + max; return 0; } static void release_pebs_buffer(int cpu) { struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu); void *cea; if (!x86_pmu.pebs) return; kfree(per_cpu(insn_buffer, cpu)); per_cpu(insn_buffer, cpu) = NULL; /* Clear the fixmap */ cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.pebs_buffer; ds_clear_cea(cea, x86_pmu.pebs_buffer_size); dsfree_pages(hwev->ds_pebs_vaddr, x86_pmu.pebs_buffer_size); hwev->ds_pebs_vaddr = NULL; } static int alloc_bts_buffer(int cpu) { struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu); struct debug_store *ds = hwev->ds; void *buffer, *cea; int max; if (!x86_pmu.bts) return 0; buffer = dsalloc_pages(BTS_BUFFER_SIZE, GFP_KERNEL | __GFP_NOWARN, cpu); if (unlikely(!buffer)) { WARN_ONCE(1, "%s: BTS buffer allocation failure\n", __func__); return -ENOMEM; } hwev->ds_bts_vaddr = buffer; /* Update the fixmap */ cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.bts_buffer; ds->bts_buffer_base = (unsigned long) cea; ds_update_cea(cea, buffer, BTS_BUFFER_SIZE, PAGE_KERNEL); ds->bts_index = ds->bts_buffer_base; max = BTS_BUFFER_SIZE / BTS_RECORD_SIZE; ds->bts_absolute_maximum = ds->bts_buffer_base + max * BTS_RECORD_SIZE; ds->bts_interrupt_threshold = ds->bts_absolute_maximum - (max / 16) * BTS_RECORD_SIZE; return 0; } static void release_bts_buffer(int cpu) { struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu); void *cea; if (!x86_pmu.bts) return; /* Clear the fixmap */ cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.bts_buffer; ds_clear_cea(cea, BTS_BUFFER_SIZE); dsfree_pages(hwev->ds_bts_vaddr, BTS_BUFFER_SIZE); hwev->ds_bts_vaddr = NULL; } static int alloc_ds_buffer(int cpu) { struct debug_store *ds = &get_cpu_entry_area(cpu)->cpu_debug_store; memset(ds, 0, sizeof(*ds)); per_cpu(cpu_hw_events, cpu).ds = ds; return 0; } static void release_ds_buffer(int cpu) { per_cpu(cpu_hw_events, cpu).ds = NULL; } void release_ds_buffers(void) { int cpu; if (!x86_pmu.bts && !x86_pmu.pebs) return; for_each_possible_cpu(cpu) release_ds_buffer(cpu); for_each_possible_cpu(cpu) { /* * Again, ignore errors from offline CPUs, they will no longer * observe cpu_hw_events.ds and not program the DS_AREA when * they come up. */ fini_debug_store_on_cpu(cpu); } for_each_possible_cpu(cpu) { release_pebs_buffer(cpu); release_bts_buffer(cpu); } } void reserve_ds_buffers(void) { int bts_err = 0, pebs_err = 0; int cpu; x86_pmu.bts_active = 0; x86_pmu.pebs_active = 0; if (!x86_pmu.bts && !x86_pmu.pebs) return; if (!x86_pmu.bts) bts_err = 1; if (!x86_pmu.pebs) pebs_err = 1; for_each_possible_cpu(cpu) { if (alloc_ds_buffer(cpu)) { bts_err = 1; pebs_err = 1; } if (!bts_err && alloc_bts_buffer(cpu)) bts_err = 1; if (!pebs_err && alloc_pebs_buffer(cpu)) pebs_err = 1; if (bts_err && pebs_err) break; } if (bts_err) { for_each_possible_cpu(cpu) release_bts_buffer(cpu); } if (pebs_err) { for_each_possible_cpu(cpu) release_pebs_buffer(cpu); } if (bts_err && pebs_err) { for_each_possible_cpu(cpu) release_ds_buffer(cpu); } else { if (x86_pmu.bts && !bts_err) x86_pmu.bts_active = 1; if (x86_pmu.pebs && !pebs_err) x86_pmu.pebs_active = 1; for_each_possible_cpu(cpu) { /* * Ignores wrmsr_on_cpu() errors for offline CPUs they * will get this call through intel_pmu_cpu_starting(). */ init_debug_store_on_cpu(cpu); } } } /* * BTS */ struct event_constraint bts_constraint = EVENT_CONSTRAINT(0, 1ULL << INTEL_PMC_IDX_FIXED_BTS, 0); void intel_pmu_enable_bts(u64 config) { unsigned long debugctlmsr; debugctlmsr = get_debugctlmsr(); debugctlmsr |= DEBUGCTLMSR_TR; debugctlmsr |= DEBUGCTLMSR_BTS; if (config & ARCH_PERFMON_EVENTSEL_INT) debugctlmsr |= DEBUGCTLMSR_BTINT; if (!(config & ARCH_PERFMON_EVENTSEL_OS)) debugctlmsr |= DEBUGCTLMSR_BTS_OFF_OS; if (!(config & ARCH_PERFMON_EVENTSEL_USR)) debugctlmsr |= DEBUGCTLMSR_BTS_OFF_USR; update_debugctlmsr(debugctlmsr); } void intel_pmu_disable_bts(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); unsigned long debugctlmsr; if (!cpuc->ds) return; debugctlmsr = get_debugctlmsr(); debugctlmsr &= ~(DEBUGCTLMSR_TR | DEBUGCTLMSR_BTS | DEBUGCTLMSR_BTINT | DEBUGCTLMSR_BTS_OFF_OS | DEBUGCTLMSR_BTS_OFF_USR); update_debugctlmsr(debugctlmsr); } int intel_pmu_drain_bts_buffer(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct debug_store *ds = cpuc->ds; struct bts_record { u64 from; u64 to; u64 flags; }; struct perf_event *event = cpuc->events[INTEL_PMC_IDX_FIXED_BTS]; struct bts_record *at, *base, *top; struct perf_output_handle handle; struct perf_event_header header; struct perf_sample_data data; unsigned long skip = 0; struct pt_regs regs; if (!event) return 0; if (!x86_pmu.bts_active) return 0; base = (struct bts_record *)(unsigned long)ds->bts_buffer_base; top = (struct bts_record *)(unsigned long)ds->bts_index; if (top <= base) return 0; memset(&regs, 0, sizeof(regs)); ds->bts_index = ds->bts_buffer_base; perf_sample_data_init(&data, 0, event->hw.last_period); /* * BTS leaks kernel addresses in branches across the cpl boundary, * such as traps or system calls, so unless the user is asking for * kernel tracing (and right now it's not possible), we'd need to * filter them out. But first we need to count how many of those we * have in the current batch. This is an extra O(n) pass, however, * it's much faster than the other one especially considering that * n <= 2560 (BTS_BUFFER_SIZE / BTS_RECORD_SIZE * 15/16; see the * alloc_bts_buffer()). */ for (at = base; at < top; at++) { /* * Note that right now *this* BTS code only works if * attr::exclude_kernel is set, but let's keep this extra * check here in case that changes. */ if (event->attr.exclude_kernel && (kernel_ip(at->from) || kernel_ip(at->to))) skip++; } /* * Prepare a generic sample, i.e. fill in the invariant fields. * We will overwrite the from and to address before we output * the sample. */ rcu_read_lock(); perf_prepare_sample(&data, event, &regs); perf_prepare_header(&header, &data, event, &regs); if (perf_output_begin(&handle, &data, event, header.size * (top - base - skip))) goto unlock; for (at = base; at < top; at++) { /* Filter out any records that contain kernel addresses. */ if (event->attr.exclude_kernel && (kernel_ip(at->from) || kernel_ip(at->to))) continue; data.ip = at->from; data.addr = at->to; perf_output_sample(&handle, &header, &data, event); } perf_output_end(&handle); /* There's new data available. */ event->hw.interrupts++; event->pending_kill = POLL_IN; unlock: rcu_read_unlock(); return 1; } static inline void intel_pmu_drain_pebs_buffer(void) { struct perf_sample_data data; x86_pmu.drain_pebs(NULL, &data); } /* * PEBS */ struct event_constraint intel_core2_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c0, 0x1), /* INST_RETIRED.ANY */ INTEL_FLAGS_UEVENT_CONSTRAINT(0xfec1, 0x1), /* X87_OPS_RETIRED.ANY */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c5, 0x1), /* BR_INST_RETIRED.MISPRED */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x1fc7, 0x1), /* SIMD_INST_RETURED.ANY */ INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED.* */ /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x01), EVENT_CONSTRAINT_END }; struct event_constraint intel_atom_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c0, 0x1), /* INST_RETIRED.ANY */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c5, 0x1), /* MISPREDICTED_BRANCH_RETIRED */ INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED.* */ /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x01), /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0x1), EVENT_CONSTRAINT_END }; struct event_constraint intel_slm_pebs_event_constraints[] = { /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x1), /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0x1), EVENT_CONSTRAINT_END }; struct event_constraint intel_glm_pebs_event_constraints[] = { /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0x1), EVENT_CONSTRAINT_END }; struct event_constraint intel_grt_pebs_event_constraints[] = { /* Allow all events as PEBS with no flags */ INTEL_HYBRID_LAT_CONSTRAINT(0x5d0, 0x3), INTEL_HYBRID_LAT_CONSTRAINT(0x6d0, 0xf), EVENT_CONSTRAINT_END }; struct event_constraint intel_nehalem_pebs_event_constraints[] = { INTEL_PLD_CONSTRAINT(0x100b, 0xf), /* MEM_INST_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0x0f, 0xf), /* MEM_UNCORE_RETIRED.* */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x010c, 0xf), /* MEM_STORE_RETIRED.DTLB_MISS */ INTEL_FLAGS_EVENT_CONSTRAINT(0xc0, 0xf), /* INST_RETIRED.ANY */ INTEL_EVENT_CONSTRAINT(0xc2, 0xf), /* UOPS_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0xc4, 0xf), /* BR_INST_RETIRED.* */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x02c5, 0xf), /* BR_MISP_RETIRED.NEAR_CALL */ INTEL_FLAGS_EVENT_CONSTRAINT(0xc7, 0xf), /* SSEX_UOPS_RETIRED.* */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x20c8, 0xf), /* ITLB_MISS_RETIRED */ INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0xf), /* MEM_LOAD_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0xf7, 0xf), /* FP_ASSIST.* */ /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x0f), EVENT_CONSTRAINT_END }; struct event_constraint intel_westmere_pebs_event_constraints[] = { INTEL_PLD_CONSTRAINT(0x100b, 0xf), /* MEM_INST_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0x0f, 0xf), /* MEM_UNCORE_RETIRED.* */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x010c, 0xf), /* MEM_STORE_RETIRED.DTLB_MISS */ INTEL_FLAGS_EVENT_CONSTRAINT(0xc0, 0xf), /* INSTR_RETIRED.* */ INTEL_EVENT_CONSTRAINT(0xc2, 0xf), /* UOPS_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0xc4, 0xf), /* BR_INST_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0xc5, 0xf), /* BR_MISP_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0xc7, 0xf), /* SSEX_UOPS_RETIRED.* */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x20c8, 0xf), /* ITLB_MISS_RETIRED */ INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0xf), /* MEM_LOAD_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0xf7, 0xf), /* FP_ASSIST.* */ /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x0f), EVENT_CONSTRAINT_END }; struct event_constraint intel_snb_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */ INTEL_PLD_CONSTRAINT(0x01cd, 0x8), /* MEM_TRANS_RETIRED.LAT_ABOVE_THR */ INTEL_PST_CONSTRAINT(0x02cd, 0x8), /* MEM_TRANS_RETIRED.PRECISE_STORES */ /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf), INTEL_EXCLEVT_CONSTRAINT(0xd0, 0xf), /* MEM_UOP_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd3, 0xf), /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */ /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0xf), EVENT_CONSTRAINT_END }; struct event_constraint intel_ivb_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */ INTEL_PLD_CONSTRAINT(0x01cd, 0x8), /* MEM_TRANS_RETIRED.LAT_ABOVE_THR */ INTEL_PST_CONSTRAINT(0x02cd, 0x8), /* MEM_TRANS_RETIRED.PRECISE_STORES */ /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf), /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2), INTEL_EXCLEVT_CONSTRAINT(0xd0, 0xf), /* MEM_UOP_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */ INTEL_EXCLEVT_CONSTRAINT(0xd3, 0xf), /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */ /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0xf), EVENT_CONSTRAINT_END }; struct event_constraint intel_hsw_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */ INTEL_PLD_CONSTRAINT(0x01cd, 0xf), /* MEM_TRANS_RETIRED.* */ /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf), /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2), INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_NA(0x01c2, 0xf), /* UOPS_RETIRED.ALL */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x11d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x21d0, 0xf), /* MEM_UOPS_RETIRED.LOCK_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x41d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x81d0, 0xf), /* MEM_UOPS_RETIRED.ALL_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XST(0x12d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XST(0x42d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XST(0x82d0, 0xf), /* MEM_UOPS_RETIRED.ALL_STORES */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_XLD(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_XLD(0xd2, 0xf), /* MEM_LOAD_UOPS_L3_HIT_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_XLD(0xd3, 0xf), /* MEM_LOAD_UOPS_L3_MISS_RETIRED.* */ /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0xf), EVENT_CONSTRAINT_END }; struct event_constraint intel_bdw_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */ INTEL_PLD_CONSTRAINT(0x01cd, 0xf), /* MEM_TRANS_RETIRED.* */ /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf), /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2), INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_NA(0x01c2, 0xf), /* UOPS_RETIRED.ALL */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x11d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x21d0, 0xf), /* MEM_UOPS_RETIRED.LOCK_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x41d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x81d0, 0xf), /* MEM_UOPS_RETIRED.ALL_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x12d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x42d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x82d0, 0xf), /* MEM_UOPS_RETIRED.ALL_STORES */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd2, 0xf), /* MEM_LOAD_UOPS_L3_HIT_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd3, 0xf), /* MEM_LOAD_UOPS_L3_MISS_RETIRED.* */ /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0xf), EVENT_CONSTRAINT_END }; struct event_constraint intel_skl_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x1c0, 0x2), /* INST_RETIRED.PREC_DIST */ /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2), /* INST_RETIRED.TOTAL_CYCLES_PS (inv=1, cmask=16) (cycles:p). */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x0f), INTEL_PLD_CONSTRAINT(0x1cd, 0xf), /* MEM_TRANS_RETIRED.* */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x11d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x12d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x21d0, 0xf), /* MEM_INST_RETIRED.LOCK_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x22d0, 0xf), /* MEM_INST_RETIRED.LOCK_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x41d0, 0xf), /* MEM_INST_RETIRED.SPLIT_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x42d0, 0xf), /* MEM_INST_RETIRED.SPLIT_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x81d0, 0xf), /* MEM_INST_RETIRED.ALL_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x82d0, 0xf), /* MEM_INST_RETIRED.ALL_STORES */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd1, 0xf), /* MEM_LOAD_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd2, 0xf), /* MEM_LOAD_L3_HIT_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd3, 0xf), /* MEM_LOAD_L3_MISS_RETIRED.* */ /* Allow all events as PEBS with no flags */ INTEL_ALL_EVENT_CONSTRAINT(0, 0xf), EVENT_CONSTRAINT_END }; struct event_constraint intel_icl_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x100000000ULL), /* old INST_RETIRED.PREC_DIST */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x0100, 0x100000000ULL), /* INST_RETIRED.PREC_DIST */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x0400, 0x800000000ULL), /* SLOTS */ INTEL_PLD_CONSTRAINT(0x1cd, 0xff), /* MEM_TRANS_RETIRED.LOAD_LATENCY */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x11d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x12d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x21d0, 0xf), /* MEM_INST_RETIRED.LOCK_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x41d0, 0xf), /* MEM_INST_RETIRED.SPLIT_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x42d0, 0xf), /* MEM_INST_RETIRED.SPLIT_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x81d0, 0xf), /* MEM_INST_RETIRED.ALL_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x82d0, 0xf), /* MEM_INST_RETIRED.ALL_STORES */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD_RANGE(0xd1, 0xd4, 0xf), /* MEM_LOAD_*_RETIRED.* */ INTEL_FLAGS_EVENT_CONSTRAINT(0xd0, 0xf), /* MEM_INST_RETIRED.* */ /* * Everything else is handled by PMU_FL_PEBS_ALL, because we * need the full constraints from the main table. */ EVENT_CONSTRAINT_END }; struct event_constraint intel_spr_pebs_event_constraints[] = { INTEL_FLAGS_UEVENT_CONSTRAINT(0x100, 0x100000000ULL), /* INST_RETIRED.PREC_DIST */ INTEL_FLAGS_UEVENT_CONSTRAINT(0x0400, 0x800000000ULL), INTEL_FLAGS_EVENT_CONSTRAINT(0xc0, 0xfe), INTEL_PLD_CONSTRAINT(0x1cd, 0xfe), INTEL_PSD_CONSTRAINT(0x2cd, 0x1), INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x11d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x12d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x21d0, 0xf), /* MEM_INST_RETIRED.LOCK_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x41d0, 0xf), /* MEM_INST_RETIRED.SPLIT_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x42d0, 0xf), /* MEM_INST_RETIRED.SPLIT_STORES */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x81d0, 0xf), /* MEM_INST_RETIRED.ALL_LOADS */ INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x82d0, 0xf), /* MEM_INST_RETIRED.ALL_STORES */ INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD_RANGE(0xd1, 0xd4, 0xf), INTEL_FLAGS_EVENT_CONSTRAINT(0xd0, 0xf), /* * Everything else is handled by PMU_FL_PEBS_ALL, because we * need the full constraints from the main table. */ EVENT_CONSTRAINT_END }; struct event_constraint *intel_pebs_constraints(struct perf_event *event) { struct event_constraint *pebs_constraints = hybrid(event->pmu, pebs_constraints); struct event_constraint *c; if (!event->attr.precise_ip) return NULL; if (pebs_constraints) { for_each_event_constraint(c, pebs_constraints) { if (constraint_match(c, event->hw.config)) { event->hw.flags |= c->flags; return c; } } } /* * Extended PEBS support * Makes the PEBS code search the normal constraints. */ if (x86_pmu.flags & PMU_FL_PEBS_ALL) return NULL; return &emptyconstraint; } /* * We need the sched_task callback even for per-cpu events when we use * the large interrupt threshold, such that we can provide PID and TID * to PEBS samples. */ static inline bool pebs_needs_sched_cb(struct cpu_hw_events *cpuc) { if (cpuc->n_pebs == cpuc->n_pebs_via_pt) return false; return cpuc->n_pebs && (cpuc->n_pebs == cpuc->n_large_pebs); } void intel_pmu_pebs_sched_task(struct perf_event_pmu_context *pmu_ctx, bool sched_in) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (!sched_in && pebs_needs_sched_cb(cpuc)) intel_pmu_drain_pebs_buffer(); } static inline void pebs_update_threshold(struct cpu_hw_events *cpuc) { struct debug_store *ds = cpuc->ds; int max_pebs_events = hybrid(cpuc->pmu, max_pebs_events); int num_counters_fixed = hybrid(cpuc->pmu, num_counters_fixed); u64 threshold; int reserved; if (cpuc->n_pebs_via_pt) return; if (x86_pmu.flags & PMU_FL_PEBS_ALL) reserved = max_pebs_events + num_counters_fixed; else reserved = max_pebs_events; if (cpuc->n_pebs == cpuc->n_large_pebs) { threshold = ds->pebs_absolute_maximum - reserved * cpuc->pebs_record_size; } else { threshold = ds->pebs_buffer_base + cpuc->pebs_record_size; } ds->pebs_interrupt_threshold = threshold; } static void adaptive_pebs_record_size_update(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); u64 pebs_data_cfg = cpuc->pebs_data_cfg; int sz = sizeof(struct pebs_basic); if (pebs_data_cfg & PEBS_DATACFG_MEMINFO) sz += sizeof(struct pebs_meminfo); if (pebs_data_cfg & PEBS_DATACFG_GP) sz += sizeof(struct pebs_gprs); if (pebs_data_cfg & PEBS_DATACFG_XMMS) sz += sizeof(struct pebs_xmm); if (pebs_data_cfg & PEBS_DATACFG_LBRS) sz += x86_pmu.lbr_nr * sizeof(struct lbr_entry); cpuc->pebs_record_size = sz; } #define PERF_PEBS_MEMINFO_TYPE (PERF_SAMPLE_ADDR | PERF_SAMPLE_DATA_SRC | \ PERF_SAMPLE_PHYS_ADDR | \ PERF_SAMPLE_WEIGHT_TYPE | \ PERF_SAMPLE_TRANSACTION | \ PERF_SAMPLE_DATA_PAGE_SIZE) static u64 pebs_update_adaptive_cfg(struct perf_event *event) { struct perf_event_attr *attr = &event->attr; u64 sample_type = attr->sample_type; u64 pebs_data_cfg = 0; bool gprs, tsx_weight; if (!(sample_type & ~(PERF_SAMPLE_IP|PERF_SAMPLE_TIME)) && attr->precise_ip > 1) return pebs_data_cfg; if (sample_type & PERF_PEBS_MEMINFO_TYPE) pebs_data_cfg |= PEBS_DATACFG_MEMINFO; /* * We need GPRs when: * + user requested them * + precise_ip < 2 for the non event IP * + For RTM TSX weight we need GPRs for the abort code. */ gprs = (sample_type & PERF_SAMPLE_REGS_INTR) && (attr->sample_regs_intr & PEBS_GP_REGS); tsx_weight = (sample_type & PERF_SAMPLE_WEIGHT_TYPE) && ((attr->config & INTEL_ARCH_EVENT_MASK) == x86_pmu.rtm_abort_event); if (gprs || (attr->precise_ip < 2) || tsx_weight) pebs_data_cfg |= PEBS_DATACFG_GP; if ((sample_type & PERF_SAMPLE_REGS_INTR) && (attr->sample_regs_intr & PERF_REG_EXTENDED_MASK)) pebs_data_cfg |= PEBS_DATACFG_XMMS; if (sample_type & PERF_SAMPLE_BRANCH_STACK) { /* * For now always log all LBRs. Could configure this * later. */ pebs_data_cfg |= PEBS_DATACFG_LBRS | ((x86_pmu.lbr_nr-1) << PEBS_DATACFG_LBR_SHIFT); } return pebs_data_cfg; } static void pebs_update_state(bool needed_cb, struct cpu_hw_events *cpuc, struct perf_event *event, bool add) { struct pmu *pmu = event->pmu; /* * Make sure we get updated with the first PEBS * event. It will trigger also during removal, but * that does not hurt: */ if (cpuc->n_pebs == 1) cpuc->pebs_data_cfg = PEBS_UPDATE_DS_SW; if (needed_cb != pebs_needs_sched_cb(cpuc)) { if (!needed_cb) perf_sched_cb_inc(pmu); else perf_sched_cb_dec(pmu); cpuc->pebs_data_cfg |= PEBS_UPDATE_DS_SW; } /* * The PEBS record doesn't shrink on pmu::del(). Doing so would require * iterating all remaining PEBS events to reconstruct the config. */ if (x86_pmu.intel_cap.pebs_baseline && add) { u64 pebs_data_cfg; pebs_data_cfg = pebs_update_adaptive_cfg(event); /* * Be sure to update the thresholds when we change the record. */ if (pebs_data_cfg & ~cpuc->pebs_data_cfg) cpuc->pebs_data_cfg |= pebs_data_cfg | PEBS_UPDATE_DS_SW; } } void intel_pmu_pebs_add(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; bool needed_cb = pebs_needs_sched_cb(cpuc); cpuc->n_pebs++; if (hwc->flags & PERF_X86_EVENT_LARGE_PEBS) cpuc->n_large_pebs++; if (hwc->flags & PERF_X86_EVENT_PEBS_VIA_PT) cpuc->n_pebs_via_pt++; pebs_update_state(needed_cb, cpuc, event, true); } static void intel_pmu_pebs_via_pt_disable(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (!is_pebs_pt(event)) return; if (!(cpuc->pebs_enabled & ~PEBS_VIA_PT_MASK)) cpuc->pebs_enabled &= ~PEBS_VIA_PT_MASK; } static void intel_pmu_pebs_via_pt_enable(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; struct debug_store *ds = cpuc->ds; u64 value = ds->pebs_event_reset[hwc->idx]; u32 base = MSR_RELOAD_PMC0; unsigned int idx = hwc->idx; if (!is_pebs_pt(event)) return; if (!(event->hw.flags & PERF_X86_EVENT_LARGE_PEBS)) cpuc->pebs_enabled |= PEBS_PMI_AFTER_EACH_RECORD; cpuc->pebs_enabled |= PEBS_OUTPUT_PT; if (hwc->idx >= INTEL_PMC_IDX_FIXED) { base = MSR_RELOAD_FIXED_CTR0; idx = hwc->idx - INTEL_PMC_IDX_FIXED; if (x86_pmu.intel_cap.pebs_format < 5) value = ds->pebs_event_reset[MAX_PEBS_EVENTS_FMT4 + idx]; else value = ds->pebs_event_reset[MAX_PEBS_EVENTS + idx]; } wrmsrl(base + idx, value); } static inline void intel_pmu_drain_large_pebs(struct cpu_hw_events *cpuc) { if (cpuc->n_pebs == cpuc->n_large_pebs && cpuc->n_pebs != cpuc->n_pebs_via_pt) intel_pmu_drain_pebs_buffer(); } void intel_pmu_pebs_enable(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); u64 pebs_data_cfg = cpuc->pebs_data_cfg & ~PEBS_UPDATE_DS_SW; struct hw_perf_event *hwc = &event->hw; struct debug_store *ds = cpuc->ds; unsigned int idx = hwc->idx; hwc->config &= ~ARCH_PERFMON_EVENTSEL_INT; cpuc->pebs_enabled |= 1ULL << hwc->idx; if ((event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT) && (x86_pmu.version < 5)) cpuc->pebs_enabled |= 1ULL << (hwc->idx + 32); else if (event->hw.flags & PERF_X86_EVENT_PEBS_ST) cpuc->pebs_enabled |= 1ULL << 63; if (x86_pmu.intel_cap.pebs_baseline) { hwc->config |= ICL_EVENTSEL_ADAPTIVE; if (pebs_data_cfg != cpuc->active_pebs_data_cfg) { /* * drain_pebs() assumes uniform record size; * hence we need to drain when changing said * size. */ intel_pmu_drain_large_pebs(cpuc); adaptive_pebs_record_size_update(); wrmsrl(MSR_PEBS_DATA_CFG, pebs_data_cfg); cpuc->active_pebs_data_cfg = pebs_data_cfg; } } if (cpuc->pebs_data_cfg & PEBS_UPDATE_DS_SW) { cpuc->pebs_data_cfg = pebs_data_cfg; pebs_update_threshold(cpuc); } if (idx >= INTEL_PMC_IDX_FIXED) { if (x86_pmu.intel_cap.pebs_format < 5) idx = MAX_PEBS_EVENTS_FMT4 + (idx - INTEL_PMC_IDX_FIXED); else idx = MAX_PEBS_EVENTS + (idx - INTEL_PMC_IDX_FIXED); } /* * Use auto-reload if possible to save a MSR write in the PMI. * This must be done in pmu::start(), because PERF_EVENT_IOC_PERIOD. */ if (hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) { ds->pebs_event_reset[idx] = (u64)(-hwc->sample_period) & x86_pmu.cntval_mask; } else { ds->pebs_event_reset[idx] = 0; } intel_pmu_pebs_via_pt_enable(event); } void intel_pmu_pebs_del(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; bool needed_cb = pebs_needs_sched_cb(cpuc); cpuc->n_pebs--; if (hwc->flags & PERF_X86_EVENT_LARGE_PEBS) cpuc->n_large_pebs--; if (hwc->flags & PERF_X86_EVENT_PEBS_VIA_PT) cpuc->n_pebs_via_pt--; pebs_update_state(needed_cb, cpuc, event, false); } void intel_pmu_pebs_disable(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; intel_pmu_drain_large_pebs(cpuc); cpuc->pebs_enabled &= ~(1ULL << hwc->idx); if ((event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT) && (x86_pmu.version < 5)) cpuc->pebs_enabled &= ~(1ULL << (hwc->idx + 32)); else if (event->hw.flags & PERF_X86_EVENT_PEBS_ST) cpuc->pebs_enabled &= ~(1ULL << 63); intel_pmu_pebs_via_pt_disable(event); if (cpuc->enabled) wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled); hwc->config |= ARCH_PERFMON_EVENTSEL_INT; } void intel_pmu_pebs_enable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (cpuc->pebs_enabled) wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled); } void intel_pmu_pebs_disable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (cpuc->pebs_enabled) __intel_pmu_pebs_disable_all(); } static int intel_pmu_pebs_fixup_ip(struct pt_regs *regs) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); unsigned long from = cpuc->lbr_entries[0].from; unsigned long old_to, to = cpuc->lbr_entries[0].to; unsigned long ip = regs->ip; int is_64bit = 0; void *kaddr; int size; /* * We don't need to fixup if the PEBS assist is fault like */ if (!x86_pmu.intel_cap.pebs_trap) return 1; /* * No LBR entry, no basic block, no rewinding */ if (!cpuc->lbr_stack.nr || !from || !to) return 0; /* * Basic blocks should never cross user/kernel boundaries */ if (kernel_ip(ip) != kernel_ip(to)) return 0; /* * unsigned math, either ip is before the start (impossible) or * the basic block is larger than 1 page (sanity) */ if ((ip - to) > PEBS_FIXUP_SIZE) return 0; /* * We sampled a branch insn, rewind using the LBR stack */ if (ip == to) { set_linear_ip(regs, from); return 1; } size = ip - to; if (!kernel_ip(ip)) { int bytes; u8 *buf = this_cpu_read(insn_buffer); /* 'size' must fit our buffer, see above */ bytes = copy_from_user_nmi(buf, (void __user *)to, size); if (bytes != 0) return 0; kaddr = buf; } else { kaddr = (void *)to; } do { struct insn insn; old_to = to; #ifdef CONFIG_X86_64 is_64bit = kernel_ip(to) || any_64bit_mode(regs); #endif insn_init(&insn, kaddr, size, is_64bit); /* * Make sure there was not a problem decoding the instruction. * This is doubly important because we have an infinite loop if * insn.length=0. */ if (insn_get_length(&insn)) break; to += insn.length; kaddr += insn.length; size -= insn.length; } while (to < ip); if (to == ip) { set_linear_ip(regs, old_to); return 1; } /* * Even though we decoded the basic block, the instruction stream * never matched the given IP, either the TO or the IP got corrupted. */ return 0; } static inline u64 intel_get_tsx_weight(u64 tsx_tuning) { if (tsx_tuning) { union hsw_tsx_tuning tsx = { .value = tsx_tuning }; return tsx.cycles_last_block; } return 0; } static inline u64 intel_get_tsx_transaction(u64 tsx_tuning, u64 ax) { u64 txn = (tsx_tuning & PEBS_HSW_TSX_FLAGS) >> 32; /* For RTM XABORTs also log the abort code from AX */ if ((txn & PERF_TXN_TRANSACTION) && (ax & 1)) txn |= ((ax >> 24) & 0xff) << PERF_TXN_ABORT_SHIFT; return txn; } static inline u64 get_pebs_status(void *n) { if (x86_pmu.intel_cap.pebs_format < 4) return ((struct pebs_record_nhm *)n)->status; return ((struct pebs_basic *)n)->applicable_counters; } #define PERF_X86_EVENT_PEBS_HSW_PREC \ (PERF_X86_EVENT_PEBS_ST_HSW | \ PERF_X86_EVENT_PEBS_LD_HSW | \ PERF_X86_EVENT_PEBS_NA_HSW) static u64 get_data_src(struct perf_event *event, u64 aux) { u64 val = PERF_MEM_NA; int fl = event->hw.flags; bool fst = fl & (PERF_X86_EVENT_PEBS_ST | PERF_X86_EVENT_PEBS_HSW_PREC); if (fl & PERF_X86_EVENT_PEBS_LDLAT) val = load_latency_data(event, aux); else if (fl & PERF_X86_EVENT_PEBS_STLAT) val = store_latency_data(event, aux); else if (fl & PERF_X86_EVENT_PEBS_LAT_HYBRID) val = x86_pmu.pebs_latency_data(event, aux); else if (fst && (fl & PERF_X86_EVENT_PEBS_HSW_PREC)) val = precise_datala_hsw(event, aux); else if (fst) val = precise_store_data(aux); return val; } static void setup_pebs_time(struct perf_event *event, struct perf_sample_data *data, u64 tsc) { /* Converting to a user-defined clock is not supported yet. */ if (event->attr.use_clockid != 0) return; /* * Doesn't support the conversion when the TSC is unstable. * The TSC unstable case is a corner case and very unlikely to * happen. If it happens, the TSC in a PEBS record will be * dropped and fall back to perf_event_clock(). */ if (!using_native_sched_clock() || !sched_clock_stable()) return; data->time = native_sched_clock_from_tsc(tsc) + __sched_clock_offset; data->sample_flags |= PERF_SAMPLE_TIME; } #define PERF_SAMPLE_ADDR_TYPE (PERF_SAMPLE_ADDR | \ PERF_SAMPLE_PHYS_ADDR | \ PERF_SAMPLE_DATA_PAGE_SIZE) static void setup_pebs_fixed_sample_data(struct perf_event *event, struct pt_regs *iregs, void *__pebs, struct perf_sample_data *data, struct pt_regs *regs) { /* * We cast to the biggest pebs_record but are careful not to * unconditionally access the 'extra' entries. */ struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct pebs_record_skl *pebs = __pebs; u64 sample_type; int fll; if (pebs == NULL) return; sample_type = event->attr.sample_type; fll = event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT; perf_sample_data_init(data, 0, event->hw.last_period); data->period = event->hw.last_period; /* * Use latency for weight (only avail with PEBS-LL) */ if (fll && (sample_type & PERF_SAMPLE_WEIGHT_TYPE)) { data->weight.full = pebs->lat; data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; } /* * data.data_src encodes the data source */ if (sample_type & PERF_SAMPLE_DATA_SRC) { data->data_src.val = get_data_src(event, pebs->dse); data->sample_flags |= PERF_SAMPLE_DATA_SRC; } /* * We must however always use iregs for the unwinder to stay sane; the * record BP,SP,IP can point into thin air when the record is from a * previous PMI context or an (I)RET happened between the record and * PMI. */ if (sample_type & PERF_SAMPLE_CALLCHAIN) perf_sample_save_callchain(data, event, iregs); /* * We use the interrupt regs as a base because the PEBS record does not * contain a full regs set, specifically it seems to lack segment * descriptors, which get used by things like user_mode(). * * In the simple case fix up only the IP for PERF_SAMPLE_IP. */ *regs = *iregs; /* * Initialize regs_>flags from PEBS, * Clear exact bit (which uses x86 EFLAGS Reserved bit 3), * i.e., do not rely on it being zero: */ regs->flags = pebs->flags & ~PERF_EFLAGS_EXACT; if (sample_type & PERF_SAMPLE_REGS_INTR) { regs->ax = pebs->ax; regs->bx = pebs->bx; regs->cx = pebs->cx; regs->dx = pebs->dx; regs->si = pebs->si; regs->di = pebs->di; regs->bp = pebs->bp; regs->sp = pebs->sp; #ifndef CONFIG_X86_32 regs->r8 = pebs->r8; regs->r9 = pebs->r9; regs->r10 = pebs->r10; regs->r11 = pebs->r11; regs->r12 = pebs->r12; regs->r13 = pebs->r13; regs->r14 = pebs->r14; regs->r15 = pebs->r15; #endif } if (event->attr.precise_ip > 1) { /* * Haswell and later processors have an 'eventing IP' * (real IP) which fixes the off-by-1 skid in hardware. * Use it when precise_ip >= 2 : */ if (x86_pmu.intel_cap.pebs_format >= 2) { set_linear_ip(regs, pebs->real_ip); regs->flags |= PERF_EFLAGS_EXACT; } else { /* Otherwise, use PEBS off-by-1 IP: */ set_linear_ip(regs, pebs->ip); /* * With precise_ip >= 2, try to fix up the off-by-1 IP * using the LBR. If successful, the fixup function * corrects regs->ip and calls set_linear_ip() on regs: */ if (intel_pmu_pebs_fixup_ip(regs)) regs->flags |= PERF_EFLAGS_EXACT; } } else { /* * When precise_ip == 1, return the PEBS off-by-1 IP, * no fixup attempted: */ set_linear_ip(regs, pebs->ip); } if ((sample_type & PERF_SAMPLE_ADDR_TYPE) && x86_pmu.intel_cap.pebs_format >= 1) { data->addr = pebs->dla; data->sample_flags |= PERF_SAMPLE_ADDR; } if (x86_pmu.intel_cap.pebs_format >= 2) { /* Only set the TSX weight when no memory weight. */ if ((sample_type & PERF_SAMPLE_WEIGHT_TYPE) && !fll) { data->weight.full = intel_get_tsx_weight(pebs->tsx_tuning); data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; } if (sample_type & PERF_SAMPLE_TRANSACTION) { data->txn = intel_get_tsx_transaction(pebs->tsx_tuning, pebs->ax); data->sample_flags |= PERF_SAMPLE_TRANSACTION; } } /* * v3 supplies an accurate time stamp, so we use that * for the time stamp. * * We can only do this for the default trace clock. */ if (x86_pmu.intel_cap.pebs_format >= 3) setup_pebs_time(event, data, pebs->tsc); if (has_branch_stack(event)) perf_sample_save_brstack(data, event, &cpuc->lbr_stack); } static void adaptive_pebs_save_regs(struct pt_regs *regs, struct pebs_gprs *gprs) { regs->ax = gprs->ax; regs->bx = gprs->bx; regs->cx = gprs->cx; regs->dx = gprs->dx; regs->si = gprs->si; regs->di = gprs->di; regs->bp = gprs->bp; regs->sp = gprs->sp; #ifndef CONFIG_X86_32 regs->r8 = gprs->r8; regs->r9 = gprs->r9; regs->r10 = gprs->r10; regs->r11 = gprs->r11; regs->r12 = gprs->r12; regs->r13 = gprs->r13; regs->r14 = gprs->r14; regs->r15 = gprs->r15; #endif } #define PEBS_LATENCY_MASK 0xffff #define PEBS_CACHE_LATENCY_OFFSET 32 #define PEBS_RETIRE_LATENCY_OFFSET 32 /* * With adaptive PEBS the layout depends on what fields are configured. */ static void setup_pebs_adaptive_sample_data(struct perf_event *event, struct pt_regs *iregs, void *__pebs, struct perf_sample_data *data, struct pt_regs *regs) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct pebs_basic *basic = __pebs; void *next_record = basic + 1; u64 sample_type; u64 format_size; struct pebs_meminfo *meminfo = NULL; struct pebs_gprs *gprs = NULL; struct x86_perf_regs *perf_regs; if (basic == NULL) return; perf_regs = container_of(regs, struct x86_perf_regs, regs); perf_regs->xmm_regs = NULL; sample_type = event->attr.sample_type; format_size = basic->format_size; perf_sample_data_init(data, 0, event->hw.last_period); data->period = event->hw.last_period; setup_pebs_time(event, data, basic->tsc); /* * We must however always use iregs for the unwinder to stay sane; the * record BP,SP,IP can point into thin air when the record is from a * previous PMI context or an (I)RET happened between the record and * PMI. */ if (sample_type & PERF_SAMPLE_CALLCHAIN) perf_sample_save_callchain(data, event, iregs); *regs = *iregs; /* The ip in basic is EventingIP */ set_linear_ip(regs, basic->ip); regs->flags = PERF_EFLAGS_EXACT; if ((sample_type & PERF_SAMPLE_WEIGHT_STRUCT) && (x86_pmu.flags & PMU_FL_RETIRE_LATENCY)) data->weight.var3_w = format_size >> PEBS_RETIRE_LATENCY_OFFSET & PEBS_LATENCY_MASK; /* * The record for MEMINFO is in front of GP * But PERF_SAMPLE_TRANSACTION needs gprs->ax. * Save the pointer here but process later. */ if (format_size & PEBS_DATACFG_MEMINFO) { meminfo = next_record; next_record = meminfo + 1; } if (format_size & PEBS_DATACFG_GP) { gprs = next_record; next_record = gprs + 1; if (event->attr.precise_ip < 2) { set_linear_ip(regs, gprs->ip); regs->flags &= ~PERF_EFLAGS_EXACT; } if (sample_type & PERF_SAMPLE_REGS_INTR) adaptive_pebs_save_regs(regs, gprs); } if (format_size & PEBS_DATACFG_MEMINFO) { if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) { u64 weight = meminfo->latency; if (x86_pmu.flags & PMU_FL_INSTR_LATENCY) { data->weight.var2_w = weight & PEBS_LATENCY_MASK; weight >>= PEBS_CACHE_LATENCY_OFFSET; } /* * Although meminfo::latency is defined as a u64, * only the lower 32 bits include the valid data * in practice on Ice Lake and earlier platforms. */ if (sample_type & PERF_SAMPLE_WEIGHT) { data->weight.full = weight ?: intel_get_tsx_weight(meminfo->tsx_tuning); } else { data->weight.var1_dw = (u32)(weight & PEBS_LATENCY_MASK) ?: intel_get_tsx_weight(meminfo->tsx_tuning); } data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; } if (sample_type & PERF_SAMPLE_DATA_SRC) { data->data_src.val = get_data_src(event, meminfo->aux); data->sample_flags |= PERF_SAMPLE_DATA_SRC; } if (sample_type & PERF_SAMPLE_ADDR_TYPE) { data->addr = meminfo->address; data->sample_flags |= PERF_SAMPLE_ADDR; } if (sample_type & PERF_SAMPLE_TRANSACTION) { data->txn = intel_get_tsx_transaction(meminfo->tsx_tuning, gprs ? gprs->ax : 0); data->sample_flags |= PERF_SAMPLE_TRANSACTION; } } if (format_size & PEBS_DATACFG_XMMS) { struct pebs_xmm *xmm = next_record; next_record = xmm + 1; perf_regs->xmm_regs = xmm->xmm; } if (format_size & PEBS_DATACFG_LBRS) { struct lbr_entry *lbr = next_record; int num_lbr = ((format_size >> PEBS_DATACFG_LBR_SHIFT) & 0xff) + 1; next_record = next_record + num_lbr * sizeof(struct lbr_entry); if (has_branch_stack(event)) { intel_pmu_store_pebs_lbrs(lbr); perf_sample_save_brstack(data, event, &cpuc->lbr_stack); } } WARN_ONCE(next_record != __pebs + (format_size >> 48), "PEBS record size %llu, expected %llu, config %llx\n", format_size >> 48, (u64)(next_record - __pebs), basic->format_size); } static inline void * get_next_pebs_record_by_bit(void *base, void *top, int bit) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); void *at; u64 pebs_status; /* * fmt0 does not have a status bitfield (does not use * perf_record_nhm format) */ if (x86_pmu.intel_cap.pebs_format < 1) return base; if (base == NULL) return NULL; for (at = base; at < top; at += cpuc->pebs_record_size) { unsigned long status = get_pebs_status(at); if (test_bit(bit, (unsigned long *)&status)) { /* PEBS v3 has accurate status bits */ if (x86_pmu.intel_cap.pebs_format >= 3) return at; if (status == (1 << bit)) return at; /* clear non-PEBS bit and re-check */ pebs_status = status & cpuc->pebs_enabled; pebs_status &= PEBS_COUNTER_MASK; if (pebs_status == (1 << bit)) return at; } } return NULL; } void intel_pmu_auto_reload_read(struct perf_event *event) { WARN_ON(!(event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD)); perf_pmu_disable(event->pmu); intel_pmu_drain_pebs_buffer(); perf_pmu_enable(event->pmu); } /* * Special variant of intel_pmu_save_and_restart() for auto-reload. */ static int intel_pmu_save_and_restart_reload(struct perf_event *event, int count) { struct hw_perf_event *hwc = &event->hw; int shift = 64 - x86_pmu.cntval_bits; u64 period = hwc->sample_period; u64 prev_raw_count, new_raw_count; s64 new, old; WARN_ON(!period); /* * drain_pebs() only happens when the PMU is disabled. */ WARN_ON(this_cpu_read(cpu_hw_events.enabled)); prev_raw_count = local64_read(&hwc->prev_count); rdpmcl(hwc->event_base_rdpmc, new_raw_count); local64_set(&hwc->prev_count, new_raw_count); /* * Since the counter increments a negative counter value and * overflows on the sign switch, giving the interval: * * [-period, 0] * * the difference between two consecutive reads is: * * A) value2 - value1; * when no overflows have happened in between, * * B) (0 - value1) + (value2 - (-period)); * when one overflow happened in between, * * C) (0 - value1) + (n - 1) * (period) + (value2 - (-period)); * when @n overflows happened in between. * * Here A) is the obvious difference, B) is the extension to the * discrete interval, where the first term is to the top of the * interval and the second term is from the bottom of the next * interval and C) the extension to multiple intervals, where the * middle term is the whole intervals covered. * * An equivalent of C, by reduction, is: * * value2 - value1 + n * period */ new = ((s64)(new_raw_count << shift) >> shift); old = ((s64)(prev_raw_count << shift) >> shift); local64_add(new - old + count * period, &event->count); local64_set(&hwc->period_left, -new); perf_event_update_userpage(event); return 0; } static __always_inline void __intel_pmu_pebs_event(struct perf_event *event, struct pt_regs *iregs, struct perf_sample_data *data, void *base, void *top, int bit, int count, void (*setup_sample)(struct perf_event *, struct pt_regs *, void *, struct perf_sample_data *, struct pt_regs *)) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; struct x86_perf_regs perf_regs; struct pt_regs *regs = &perf_regs.regs; void *at = get_next_pebs_record_by_bit(base, top, bit); static struct pt_regs dummy_iregs; if (hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) { /* * Now, auto-reload is only enabled in fixed period mode. * The reload value is always hwc->sample_period. * May need to change it, if auto-reload is enabled in * freq mode later. */ intel_pmu_save_and_restart_reload(event, count); } else if (!intel_pmu_save_and_restart(event)) return; if (!iregs) iregs = &dummy_iregs; while (count > 1) { setup_sample(event, iregs, at, data, regs); perf_event_output(event, data, regs); at += cpuc->pebs_record_size; at = get_next_pebs_record_by_bit(at, top, bit); count--; } setup_sample(event, iregs, at, data, regs); if (iregs == &dummy_iregs) { /* * The PEBS records may be drained in the non-overflow context, * e.g., large PEBS + context switch. Perf should treat the * last record the same as other PEBS records, and doesn't * invoke the generic overflow handler. */ perf_event_output(event, data, regs); } else { /* * All but the last records are processed. * The last one is left to be able to call the overflow handler. */ if (perf_event_overflow(event, data, regs)) x86_pmu_stop(event, 0); } } static void intel_pmu_drain_pebs_core(struct pt_regs *iregs, struct perf_sample_data *data) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct debug_store *ds = cpuc->ds; struct perf_event *event = cpuc->events[0]; /* PMC0 only */ struct pebs_record_core *at, *top; int n; if (!x86_pmu.pebs_active) return; at = (struct pebs_record_core *)(unsigned long)ds->pebs_buffer_base; top = (struct pebs_record_core *)(unsigned long)ds->pebs_index; /* * Whatever else happens, drain the thing */ ds->pebs_index = ds->pebs_buffer_base; if (!test_bit(0, cpuc->active_mask)) return; WARN_ON_ONCE(!event); if (!event->attr.precise_ip) return; n = top - at; if (n <= 0) { if (event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD) intel_pmu_save_and_restart_reload(event, 0); return; } __intel_pmu_pebs_event(event, iregs, data, at, top, 0, n, setup_pebs_fixed_sample_data); } static void intel_pmu_pebs_event_update_no_drain(struct cpu_hw_events *cpuc, int size) { struct perf_event *event; int bit; /* * The drain_pebs() could be called twice in a short period * for auto-reload event in pmu::read(). There are no * overflows have happened in between. * It needs to call intel_pmu_save_and_restart_reload() to * update the event->count for this case. */ for_each_set_bit(bit, (unsigned long *)&cpuc->pebs_enabled, size) { event = cpuc->events[bit]; if (event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD) intel_pmu_save_and_restart_reload(event, 0); } } static void intel_pmu_drain_pebs_nhm(struct pt_regs *iregs, struct perf_sample_data *data) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct debug_store *ds = cpuc->ds; struct perf_event *event; void *base, *at, *top; short counts[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {}; short error[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {}; int bit, i, size; u64 mask; if (!x86_pmu.pebs_active) return; base = (struct pebs_record_nhm *)(unsigned long)ds->pebs_buffer_base; top = (struct pebs_record_nhm *)(unsigned long)ds->pebs_index; ds->pebs_index = ds->pebs_buffer_base; mask = (1ULL << x86_pmu.max_pebs_events) - 1; size = x86_pmu.max_pebs_events; if (x86_pmu.flags & PMU_FL_PEBS_ALL) { mask |= ((1ULL << x86_pmu.num_counters_fixed) - 1) << INTEL_PMC_IDX_FIXED; size = INTEL_PMC_IDX_FIXED + x86_pmu.num_counters_fixed; } if (unlikely(base >= top)) { intel_pmu_pebs_event_update_no_drain(cpuc, size); return; } for (at = base; at < top; at += x86_pmu.pebs_record_size) { struct pebs_record_nhm *p = at; u64 pebs_status; pebs_status = p->status & cpuc->pebs_enabled; pebs_status &= mask; /* PEBS v3 has more accurate status bits */ if (x86_pmu.intel_cap.pebs_format >= 3) { for_each_set_bit(bit, (unsigned long *)&pebs_status, size) counts[bit]++; continue; } /* * On some CPUs the PEBS status can be zero when PEBS is * racing with clearing of GLOBAL_STATUS. * * Normally we would drop that record, but in the * case when there is only a single active PEBS event * we can assume it's for that event. */ if (!pebs_status && cpuc->pebs_enabled && !(cpuc->pebs_enabled & (cpuc->pebs_enabled-1))) pebs_status = p->status = cpuc->pebs_enabled; bit = find_first_bit((unsigned long *)&pebs_status, x86_pmu.max_pebs_events); if (bit >= x86_pmu.max_pebs_events) continue; /* * The PEBS hardware does not deal well with the situation * when events happen near to each other and multiple bits * are set. But it should happen rarely. * * If these events include one PEBS and multiple non-PEBS * events, it doesn't impact PEBS record. The record will * be handled normally. (slow path) * * If these events include two or more PEBS events, the * records for the events can be collapsed into a single * one, and it's not possible to reconstruct all events * that caused the PEBS record. It's called collision. * If collision happened, the record will be dropped. */ if (pebs_status != (1ULL << bit)) { for_each_set_bit(i, (unsigned long *)&pebs_status, size) error[i]++; continue; } counts[bit]++; } for_each_set_bit(bit, (unsigned long *)&mask, size) { if ((counts[bit] == 0) && (error[bit] == 0)) continue; event = cpuc->events[bit]; if (WARN_ON_ONCE(!event)) continue; if (WARN_ON_ONCE(!event->attr.precise_ip)) continue; /* log dropped samples number */ if (error[bit]) { perf_log_lost_samples(event, error[bit]); if (iregs && perf_event_account_interrupt(event)) x86_pmu_stop(event, 0); } if (counts[bit]) { __intel_pmu_pebs_event(event, iregs, data, base, top, bit, counts[bit], setup_pebs_fixed_sample_data); } } } static void intel_pmu_drain_pebs_icl(struct pt_regs *iregs, struct perf_sample_data *data) { short counts[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {}; struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int max_pebs_events = hybrid(cpuc->pmu, max_pebs_events); int num_counters_fixed = hybrid(cpuc->pmu, num_counters_fixed); struct debug_store *ds = cpuc->ds; struct perf_event *event; void *base, *at, *top; int bit, size; u64 mask; if (!x86_pmu.pebs_active) return; base = (struct pebs_basic *)(unsigned long)ds->pebs_buffer_base; top = (struct pebs_basic *)(unsigned long)ds->pebs_index; ds->pebs_index = ds->pebs_buffer_base; mask = ((1ULL << max_pebs_events) - 1) | (((1ULL << num_counters_fixed) - 1) << INTEL_PMC_IDX_FIXED); size = INTEL_PMC_IDX_FIXED + num_counters_fixed; if (unlikely(base >= top)) { intel_pmu_pebs_event_update_no_drain(cpuc, size); return; } for (at = base; at < top; at += cpuc->pebs_record_size) { u64 pebs_status; pebs_status = get_pebs_status(at) & cpuc->pebs_enabled; pebs_status &= mask; for_each_set_bit(bit, (unsigned long *)&pebs_status, size) counts[bit]++; } for_each_set_bit(bit, (unsigned long *)&mask, size) { if (counts[bit] == 0) continue; event = cpuc->events[bit]; if (WARN_ON_ONCE(!event)) continue; if (WARN_ON_ONCE(!event->attr.precise_ip)) continue; __intel_pmu_pebs_event(event, iregs, data, base, top, bit, counts[bit], setup_pebs_adaptive_sample_data); } } /* * BTS, PEBS probe and setup */ void __init intel_ds_init(void) { /* * No support for 32bit formats */ if (!boot_cpu_has(X86_FEATURE_DTES64)) return; x86_pmu.bts = boot_cpu_has(X86_FEATURE_BTS); x86_pmu.pebs = boot_cpu_has(X86_FEATURE_PEBS); x86_pmu.pebs_buffer_size = PEBS_BUFFER_SIZE; if (x86_pmu.version <= 4) x86_pmu.pebs_no_isolation = 1; if (x86_pmu.pebs) { char pebs_type = x86_pmu.intel_cap.pebs_trap ? '+' : '-'; char *pebs_qual = ""; int format = x86_pmu.intel_cap.pebs_format; if (format < 4) x86_pmu.intel_cap.pebs_baseline = 0; switch (format) { case 0: pr_cont("PEBS fmt0%c, ", pebs_type); x86_pmu.pebs_record_size = sizeof(struct pebs_record_core); /* * Using >PAGE_SIZE buffers makes the WRMSR to * PERF_GLOBAL_CTRL in intel_pmu_enable_all() * mysteriously hang on Core2. * * As a workaround, we don't do this. */ x86_pmu.pebs_buffer_size = PAGE_SIZE; x86_pmu.drain_pebs = intel_pmu_drain_pebs_core; break; case 1: pr_cont("PEBS fmt1%c, ", pebs_type); x86_pmu.pebs_record_size = sizeof(struct pebs_record_nhm); x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm; break; case 2: pr_cont("PEBS fmt2%c, ", pebs_type); x86_pmu.pebs_record_size = sizeof(struct pebs_record_hsw); x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm; break; case 3: pr_cont("PEBS fmt3%c, ", pebs_type); x86_pmu.pebs_record_size = sizeof(struct pebs_record_skl); x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm; x86_pmu.large_pebs_flags |= PERF_SAMPLE_TIME; break; case 5: x86_pmu.pebs_ept = 1; fallthrough; case 4: x86_pmu.drain_pebs = intel_pmu_drain_pebs_icl; x86_pmu.pebs_record_size = sizeof(struct pebs_basic); if (x86_pmu.intel_cap.pebs_baseline) { x86_pmu.large_pebs_flags |= PERF_SAMPLE_BRANCH_STACK | PERF_SAMPLE_TIME; x86_pmu.flags |= PMU_FL_PEBS_ALL; x86_pmu.pebs_capable = ~0ULL; pebs_qual = "-baseline"; x86_get_pmu(smp_processor_id())->capabilities |= PERF_PMU_CAP_EXTENDED_REGS; } else { /* Only basic record supported */ x86_pmu.large_pebs_flags &= ~(PERF_SAMPLE_ADDR | PERF_SAMPLE_TIME | PERF_SAMPLE_DATA_SRC | PERF_SAMPLE_TRANSACTION | PERF_SAMPLE_REGS_USER | PERF_SAMPLE_REGS_INTR); } pr_cont("PEBS fmt4%c%s, ", pebs_type, pebs_qual); if (!is_hybrid() && x86_pmu.intel_cap.pebs_output_pt_available) { pr_cont("PEBS-via-PT, "); x86_get_pmu(smp_processor_id())->capabilities |= PERF_PMU_CAP_AUX_OUTPUT; } break; default: pr_cont("no PEBS fmt%d%c, ", format, pebs_type); x86_pmu.pebs = 0; } } } void perf_restore_debug_store(void) { struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds); if (!x86_pmu.bts && !x86_pmu.pebs) return; wrmsrl(MSR_IA32_DS_AREA, (unsigned long)ds); }
linux-master
arch/x86/events/intel/ds.c
// SPDX-License-Identifier: GPL-2.0-only /* * BTS PMU driver for perf * Copyright (c) 2013-2014, Intel Corporation. */ #undef DEBUG #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/bitops.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/debugfs.h> #include <linux/device.h> #include <linux/coredump.h> #include <linux/sizes.h> #include <asm/perf_event.h> #include "../perf_event.h" struct bts_ctx { struct perf_output_handle handle; struct debug_store ds_back; int state; }; /* BTS context states: */ enum { /* no ongoing AUX transactions */ BTS_STATE_STOPPED = 0, /* AUX transaction is on, BTS tracing is disabled */ BTS_STATE_INACTIVE, /* AUX transaction is on, BTS tracing is running */ BTS_STATE_ACTIVE, }; static DEFINE_PER_CPU(struct bts_ctx, bts_ctx); #define BTS_RECORD_SIZE 24 #define BTS_SAFETY_MARGIN 4080 struct bts_phys { struct page *page; unsigned long size; unsigned long offset; unsigned long displacement; }; struct bts_buffer { size_t real_size; /* multiple of BTS_RECORD_SIZE */ unsigned int nr_pages; unsigned int nr_bufs; unsigned int cur_buf; bool snapshot; local_t data_size; local_t head; unsigned long end; void **data_pages; struct bts_phys buf[]; }; static struct pmu bts_pmu; static int buf_nr_pages(struct page *page) { if (!PagePrivate(page)) return 1; return 1 << page_private(page); } static size_t buf_size(struct page *page) { return buf_nr_pages(page) * PAGE_SIZE; } static void * bts_buffer_setup_aux(struct perf_event *event, void **pages, int nr_pages, bool overwrite) { struct bts_buffer *buf; struct page *page; int cpu = event->cpu; int node = (cpu == -1) ? cpu : cpu_to_node(cpu); unsigned long offset; size_t size = nr_pages << PAGE_SHIFT; int pg, nbuf, pad; /* count all the high order buffers */ for (pg = 0, nbuf = 0; pg < nr_pages;) { page = virt_to_page(pages[pg]); pg += buf_nr_pages(page); nbuf++; } /* * to avoid interrupts in overwrite mode, only allow one physical */ if (overwrite && nbuf > 1) return NULL; buf = kzalloc_node(offsetof(struct bts_buffer, buf[nbuf]), GFP_KERNEL, node); if (!buf) return NULL; buf->nr_pages = nr_pages; buf->nr_bufs = nbuf; buf->snapshot = overwrite; buf->data_pages = pages; buf->real_size = size - size % BTS_RECORD_SIZE; for (pg = 0, nbuf = 0, offset = 0, pad = 0; nbuf < buf->nr_bufs; nbuf++) { unsigned int __nr_pages; page = virt_to_page(pages[pg]); __nr_pages = buf_nr_pages(page); buf->buf[nbuf].page = page; buf->buf[nbuf].offset = offset; buf->buf[nbuf].displacement = (pad ? BTS_RECORD_SIZE - pad : 0); buf->buf[nbuf].size = buf_size(page) - buf->buf[nbuf].displacement; pad = buf->buf[nbuf].size % BTS_RECORD_SIZE; buf->buf[nbuf].size -= pad; pg += __nr_pages; offset += __nr_pages << PAGE_SHIFT; } return buf; } static void bts_buffer_free_aux(void *data) { kfree(data); } static unsigned long bts_buffer_offset(struct bts_buffer *buf, unsigned int idx) { return buf->buf[idx].offset + buf->buf[idx].displacement; } static void bts_config_buffer(struct bts_buffer *buf) { int cpu = raw_smp_processor_id(); struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds; struct bts_phys *phys = &buf->buf[buf->cur_buf]; unsigned long index, thresh = 0, end = phys->size; struct page *page = phys->page; index = local_read(&buf->head); if (!buf->snapshot) { if (buf->end < phys->offset + buf_size(page)) end = buf->end - phys->offset - phys->displacement; index -= phys->offset + phys->displacement; if (end - index > BTS_SAFETY_MARGIN) thresh = end - BTS_SAFETY_MARGIN; else if (end - index > BTS_RECORD_SIZE) thresh = end - BTS_RECORD_SIZE; else thresh = end; } ds->bts_buffer_base = (u64)(long)page_address(page) + phys->displacement; ds->bts_index = ds->bts_buffer_base + index; ds->bts_absolute_maximum = ds->bts_buffer_base + end; ds->bts_interrupt_threshold = !buf->snapshot ? ds->bts_buffer_base + thresh : ds->bts_absolute_maximum + BTS_RECORD_SIZE; } static void bts_buffer_pad_out(struct bts_phys *phys, unsigned long head) { unsigned long index = head - phys->offset; memset(page_address(phys->page) + index, 0, phys->size - index); } static void bts_update(struct bts_ctx *bts) { int cpu = raw_smp_processor_id(); struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds; struct bts_buffer *buf = perf_get_aux(&bts->handle); unsigned long index = ds->bts_index - ds->bts_buffer_base, old, head; if (!buf) return; head = index + bts_buffer_offset(buf, buf->cur_buf); old = local_xchg(&buf->head, head); if (!buf->snapshot) { if (old == head) return; if (ds->bts_index >= ds->bts_absolute_maximum) perf_aux_output_flag(&bts->handle, PERF_AUX_FLAG_TRUNCATED); /* * old and head are always in the same physical buffer, so we * can subtract them to get the data size. */ local_add(head - old, &buf->data_size); } else { local_set(&buf->data_size, head); } /* * Since BTS is coherent, just add compiler barrier to ensure * BTS updating is ordered against bts::handle::event. */ barrier(); } static int bts_buffer_reset(struct bts_buffer *buf, struct perf_output_handle *handle); /* * Ordering PMU callbacks wrt themselves and the PMI is done by means * of bts::state, which: * - is set when bts::handle::event is valid, that is, between * perf_aux_output_begin() and perf_aux_output_end(); * - is zero otherwise; * - is ordered against bts::handle::event with a compiler barrier. */ static void __bts_event_start(struct perf_event *event) { struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); struct bts_buffer *buf = perf_get_aux(&bts->handle); u64 config = 0; if (!buf->snapshot) config |= ARCH_PERFMON_EVENTSEL_INT; if (!event->attr.exclude_kernel) config |= ARCH_PERFMON_EVENTSEL_OS; if (!event->attr.exclude_user) config |= ARCH_PERFMON_EVENTSEL_USR; bts_config_buffer(buf); /* * local barrier to make sure that ds configuration made it * before we enable BTS and bts::state goes ACTIVE */ wmb(); /* INACTIVE/STOPPED -> ACTIVE */ WRITE_ONCE(bts->state, BTS_STATE_ACTIVE); intel_pmu_enable_bts(config); } static void bts_event_start(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); struct bts_buffer *buf; buf = perf_aux_output_begin(&bts->handle, event); if (!buf) goto fail_stop; if (bts_buffer_reset(buf, &bts->handle)) goto fail_end_stop; bts->ds_back.bts_buffer_base = cpuc->ds->bts_buffer_base; bts->ds_back.bts_absolute_maximum = cpuc->ds->bts_absolute_maximum; bts->ds_back.bts_interrupt_threshold = cpuc->ds->bts_interrupt_threshold; perf_event_itrace_started(event); event->hw.state = 0; __bts_event_start(event); return; fail_end_stop: perf_aux_output_end(&bts->handle, 0); fail_stop: event->hw.state = PERF_HES_STOPPED; } static void __bts_event_stop(struct perf_event *event, int state) { struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); /* ACTIVE -> INACTIVE(PMI)/STOPPED(->stop()) */ WRITE_ONCE(bts->state, state); /* * No extra synchronization is mandated by the documentation to have * BTS data stores globally visible. */ intel_pmu_disable_bts(); } static void bts_event_stop(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); struct bts_buffer *buf = NULL; int state = READ_ONCE(bts->state); if (state == BTS_STATE_ACTIVE) __bts_event_stop(event, BTS_STATE_STOPPED); if (state != BTS_STATE_STOPPED) buf = perf_get_aux(&bts->handle); event->hw.state |= PERF_HES_STOPPED; if (flags & PERF_EF_UPDATE) { bts_update(bts); if (buf) { if (buf->snapshot) bts->handle.head = local_xchg(&buf->data_size, buf->nr_pages << PAGE_SHIFT); perf_aux_output_end(&bts->handle, local_xchg(&buf->data_size, 0)); } cpuc->ds->bts_index = bts->ds_back.bts_buffer_base; cpuc->ds->bts_buffer_base = bts->ds_back.bts_buffer_base; cpuc->ds->bts_absolute_maximum = bts->ds_back.bts_absolute_maximum; cpuc->ds->bts_interrupt_threshold = bts->ds_back.bts_interrupt_threshold; } } void intel_bts_enable_local(void) { struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); int state = READ_ONCE(bts->state); /* * Here we transition from INACTIVE to ACTIVE; * if we instead are STOPPED from the interrupt handler, * stay that way. Can't be ACTIVE here though. */ if (WARN_ON_ONCE(state == BTS_STATE_ACTIVE)) return; if (state == BTS_STATE_STOPPED) return; if (bts->handle.event) __bts_event_start(bts->handle.event); } void intel_bts_disable_local(void) { struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); /* * Here we transition from ACTIVE to INACTIVE; * do nothing for STOPPED or INACTIVE. */ if (READ_ONCE(bts->state) != BTS_STATE_ACTIVE) return; if (bts->handle.event) __bts_event_stop(bts->handle.event, BTS_STATE_INACTIVE); } static int bts_buffer_reset(struct bts_buffer *buf, struct perf_output_handle *handle) { unsigned long head, space, next_space, pad, gap, skip, wakeup; unsigned int next_buf; struct bts_phys *phys, *next_phys; int ret; if (buf->snapshot) return 0; head = handle->head & ((buf->nr_pages << PAGE_SHIFT) - 1); phys = &buf->buf[buf->cur_buf]; space = phys->offset + phys->displacement + phys->size - head; pad = space; if (space > handle->size) { space = handle->size; space -= space % BTS_RECORD_SIZE; } if (space <= BTS_SAFETY_MARGIN) { /* See if next phys buffer has more space */ next_buf = buf->cur_buf + 1; if (next_buf >= buf->nr_bufs) next_buf = 0; next_phys = &buf->buf[next_buf]; gap = buf_size(phys->page) - phys->displacement - phys->size + next_phys->displacement; skip = pad + gap; if (handle->size >= skip) { next_space = next_phys->size; if (next_space + skip > handle->size) { next_space = handle->size - skip; next_space -= next_space % BTS_RECORD_SIZE; } if (next_space > space || !space) { if (pad) bts_buffer_pad_out(phys, head); ret = perf_aux_output_skip(handle, skip); if (ret) return ret; /* Advance to next phys buffer */ phys = next_phys; space = next_space; head = phys->offset + phys->displacement; /* * After this, cur_buf and head won't match ds * anymore, so we must not be racing with * bts_update(). */ buf->cur_buf = next_buf; local_set(&buf->head, head); } } } /* Don't go far beyond wakeup watermark */ wakeup = BTS_SAFETY_MARGIN + BTS_RECORD_SIZE + handle->wakeup - handle->head; if (space > wakeup) { space = wakeup; space -= space % BTS_RECORD_SIZE; } buf->end = head + space; /* * If we have no space, the lost notification would have been sent when * we hit absolute_maximum - see bts_update() */ if (!space) return -ENOSPC; return 0; } int intel_bts_interrupt(void) { struct debug_store *ds = this_cpu_ptr(&cpu_hw_events)->ds; struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); struct perf_event *event = bts->handle.event; struct bts_buffer *buf; s64 old_head; int err = -ENOSPC, handled = 0; /* * The only surefire way of knowing if this NMI is ours is by checking * the write ptr against the PMI threshold. */ if (ds && (ds->bts_index >= ds->bts_interrupt_threshold)) handled = 1; /* * this is wrapped in intel_bts_enable_local/intel_bts_disable_local, * so we can only be INACTIVE or STOPPED */ if (READ_ONCE(bts->state) == BTS_STATE_STOPPED) return handled; buf = perf_get_aux(&bts->handle); if (!buf) return handled; /* * Skip snapshot counters: they don't use the interrupt, but * there's no other way of telling, because the pointer will * keep moving */ if (buf->snapshot) return 0; old_head = local_read(&buf->head); bts_update(bts); /* no new data */ if (old_head == local_read(&buf->head)) return handled; perf_aux_output_end(&bts->handle, local_xchg(&buf->data_size, 0)); buf = perf_aux_output_begin(&bts->handle, event); if (buf) err = bts_buffer_reset(buf, &bts->handle); if (err) { WRITE_ONCE(bts->state, BTS_STATE_STOPPED); if (buf) { /* * BTS_STATE_STOPPED should be visible before * cleared handle::event */ barrier(); perf_aux_output_end(&bts->handle, 0); } } return 1; } static void bts_event_del(struct perf_event *event, int mode) { bts_event_stop(event, PERF_EF_UPDATE); } static int bts_event_add(struct perf_event *event, int mode) { struct bts_ctx *bts = this_cpu_ptr(&bts_ctx); struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; event->hw.state = PERF_HES_STOPPED; if (test_bit(INTEL_PMC_IDX_FIXED_BTS, cpuc->active_mask)) return -EBUSY; if (bts->handle.event) return -EBUSY; if (mode & PERF_EF_START) { bts_event_start(event, 0); if (hwc->state & PERF_HES_STOPPED) return -EINVAL; } return 0; } static void bts_event_destroy(struct perf_event *event) { x86_release_hardware(); x86_del_exclusive(x86_lbr_exclusive_bts); } static int bts_event_init(struct perf_event *event) { int ret; if (event->attr.type != bts_pmu.type) return -ENOENT; /* * BTS leaks kernel addresses even when CPL0 tracing is * disabled, so disallow intel_bts driver for unprivileged * users on paranoid systems since it provides trace data * to the user in a zero-copy fashion. * * Note that the default paranoia setting permits unprivileged * users to profile the kernel. */ if (event->attr.exclude_kernel) { ret = perf_allow_kernel(&event->attr); if (ret) return ret; } if (x86_add_exclusive(x86_lbr_exclusive_bts)) return -EBUSY; ret = x86_reserve_hardware(); if (ret) { x86_del_exclusive(x86_lbr_exclusive_bts); return ret; } event->destroy = bts_event_destroy; return 0; } static void bts_event_read(struct perf_event *event) { } static __init int bts_init(void) { if (!boot_cpu_has(X86_FEATURE_DTES64) || !x86_pmu.bts) return -ENODEV; if (boot_cpu_has(X86_FEATURE_PTI)) { /* * BTS hardware writes through a virtual memory map we must * either use the kernel physical map, or the user mapping of * the AUX buffer. * * However, since this driver supports per-CPU and per-task inherit * we cannot use the user mapping since it will not be available * if we're not running the owning process. * * With PTI we can't use the kernel map either, because its not * there when we run userspace. * * For now, disable this driver when using PTI. */ return -ENODEV; } bts_pmu.capabilities = PERF_PMU_CAP_AUX_NO_SG | PERF_PMU_CAP_ITRACE | PERF_PMU_CAP_EXCLUSIVE; bts_pmu.task_ctx_nr = perf_sw_context; bts_pmu.event_init = bts_event_init; bts_pmu.add = bts_event_add; bts_pmu.del = bts_event_del; bts_pmu.start = bts_event_start; bts_pmu.stop = bts_event_stop; bts_pmu.read = bts_event_read; bts_pmu.setup_aux = bts_buffer_setup_aux; bts_pmu.free_aux = bts_buffer_free_aux; return perf_pmu_register(&bts_pmu, "intel_bts", -1); } arch_initcall(bts_init);
linux-master
arch/x86/events/intel/bts.c
// SPDX-License-Identifier: GPL-2.0 /* SandyBridge-EP/IvyTown uncore support */ #include "uncore.h" #include "uncore_discovery.h" /* SNB-EP pci bus to socket mapping */ #define SNBEP_CPUNODEID 0x40 #define SNBEP_GIDNIDMAP 0x54 /* SNB-EP Box level control */ #define SNBEP_PMON_BOX_CTL_RST_CTRL (1 << 0) #define SNBEP_PMON_BOX_CTL_RST_CTRS (1 << 1) #define SNBEP_PMON_BOX_CTL_FRZ (1 << 8) #define SNBEP_PMON_BOX_CTL_FRZ_EN (1 << 16) #define SNBEP_PMON_BOX_CTL_INT (SNBEP_PMON_BOX_CTL_RST_CTRL | \ SNBEP_PMON_BOX_CTL_RST_CTRS | \ SNBEP_PMON_BOX_CTL_FRZ_EN) /* SNB-EP event control */ #define SNBEP_PMON_CTL_EV_SEL_MASK 0x000000ff #define SNBEP_PMON_CTL_UMASK_MASK 0x0000ff00 #define SNBEP_PMON_CTL_RST (1 << 17) #define SNBEP_PMON_CTL_EDGE_DET (1 << 18) #define SNBEP_PMON_CTL_EV_SEL_EXT (1 << 21) #define SNBEP_PMON_CTL_EN (1 << 22) #define SNBEP_PMON_CTL_INVERT (1 << 23) #define SNBEP_PMON_CTL_TRESH_MASK 0xff000000 #define SNBEP_PMON_RAW_EVENT_MASK (SNBEP_PMON_CTL_EV_SEL_MASK | \ SNBEP_PMON_CTL_UMASK_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_PMON_CTL_INVERT | \ SNBEP_PMON_CTL_TRESH_MASK) /* SNB-EP Ubox event control */ #define SNBEP_U_MSR_PMON_CTL_TRESH_MASK 0x1f000000 #define SNBEP_U_MSR_PMON_RAW_EVENT_MASK \ (SNBEP_PMON_CTL_EV_SEL_MASK | \ SNBEP_PMON_CTL_UMASK_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_PMON_CTL_INVERT | \ SNBEP_U_MSR_PMON_CTL_TRESH_MASK) #define SNBEP_CBO_PMON_CTL_TID_EN (1 << 19) #define SNBEP_CBO_MSR_PMON_RAW_EVENT_MASK (SNBEP_PMON_RAW_EVENT_MASK | \ SNBEP_CBO_PMON_CTL_TID_EN) /* SNB-EP PCU event control */ #define SNBEP_PCU_MSR_PMON_CTL_OCC_SEL_MASK 0x0000c000 #define SNBEP_PCU_MSR_PMON_CTL_TRESH_MASK 0x1f000000 #define SNBEP_PCU_MSR_PMON_CTL_OCC_INVERT (1 << 30) #define SNBEP_PCU_MSR_PMON_CTL_OCC_EDGE_DET (1 << 31) #define SNBEP_PCU_MSR_PMON_RAW_EVENT_MASK \ (SNBEP_PMON_CTL_EV_SEL_MASK | \ SNBEP_PCU_MSR_PMON_CTL_OCC_SEL_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_PMON_CTL_INVERT | \ SNBEP_PCU_MSR_PMON_CTL_TRESH_MASK | \ SNBEP_PCU_MSR_PMON_CTL_OCC_INVERT | \ SNBEP_PCU_MSR_PMON_CTL_OCC_EDGE_DET) #define SNBEP_QPI_PCI_PMON_RAW_EVENT_MASK \ (SNBEP_PMON_RAW_EVENT_MASK | \ SNBEP_PMON_CTL_EV_SEL_EXT) /* SNB-EP pci control register */ #define SNBEP_PCI_PMON_BOX_CTL 0xf4 #define SNBEP_PCI_PMON_CTL0 0xd8 /* SNB-EP pci counter register */ #define SNBEP_PCI_PMON_CTR0 0xa0 /* SNB-EP home agent register */ #define SNBEP_HA_PCI_PMON_BOX_ADDRMATCH0 0x40 #define SNBEP_HA_PCI_PMON_BOX_ADDRMATCH1 0x44 #define SNBEP_HA_PCI_PMON_BOX_OPCODEMATCH 0x48 /* SNB-EP memory controller register */ #define SNBEP_MC_CHy_PCI_PMON_FIXED_CTL 0xf0 #define SNBEP_MC_CHy_PCI_PMON_FIXED_CTR 0xd0 /* SNB-EP QPI register */ #define SNBEP_Q_Py_PCI_PMON_PKT_MATCH0 0x228 #define SNBEP_Q_Py_PCI_PMON_PKT_MATCH1 0x22c #define SNBEP_Q_Py_PCI_PMON_PKT_MASK0 0x238 #define SNBEP_Q_Py_PCI_PMON_PKT_MASK1 0x23c /* SNB-EP Ubox register */ #define SNBEP_U_MSR_PMON_CTR0 0xc16 #define SNBEP_U_MSR_PMON_CTL0 0xc10 #define SNBEP_U_MSR_PMON_UCLK_FIXED_CTL 0xc08 #define SNBEP_U_MSR_PMON_UCLK_FIXED_CTR 0xc09 /* SNB-EP Cbo register */ #define SNBEP_C0_MSR_PMON_CTR0 0xd16 #define SNBEP_C0_MSR_PMON_CTL0 0xd10 #define SNBEP_C0_MSR_PMON_BOX_CTL 0xd04 #define SNBEP_C0_MSR_PMON_BOX_FILTER 0xd14 #define SNBEP_CBO_MSR_OFFSET 0x20 #define SNBEP_CB0_MSR_PMON_BOX_FILTER_TID 0x1f #define SNBEP_CB0_MSR_PMON_BOX_FILTER_NID 0x3fc00 #define SNBEP_CB0_MSR_PMON_BOX_FILTER_STATE 0x7c0000 #define SNBEP_CB0_MSR_PMON_BOX_FILTER_OPC 0xff800000 #define SNBEP_CBO_EVENT_EXTRA_REG(e, m, i) { \ .event = (e), \ .msr = SNBEP_C0_MSR_PMON_BOX_FILTER, \ .config_mask = (m), \ .idx = (i) \ } /* SNB-EP PCU register */ #define SNBEP_PCU_MSR_PMON_CTR0 0xc36 #define SNBEP_PCU_MSR_PMON_CTL0 0xc30 #define SNBEP_PCU_MSR_PMON_BOX_CTL 0xc24 #define SNBEP_PCU_MSR_PMON_BOX_FILTER 0xc34 #define SNBEP_PCU_MSR_PMON_BOX_FILTER_MASK 0xffffffff #define SNBEP_PCU_MSR_CORE_C3_CTR 0x3fc #define SNBEP_PCU_MSR_CORE_C6_CTR 0x3fd /* IVBEP event control */ #define IVBEP_PMON_BOX_CTL_INT (SNBEP_PMON_BOX_CTL_RST_CTRL | \ SNBEP_PMON_BOX_CTL_RST_CTRS) #define IVBEP_PMON_RAW_EVENT_MASK (SNBEP_PMON_CTL_EV_SEL_MASK | \ SNBEP_PMON_CTL_UMASK_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_PMON_CTL_TRESH_MASK) /* IVBEP Ubox */ #define IVBEP_U_MSR_PMON_GLOBAL_CTL 0xc00 #define IVBEP_U_PMON_GLOBAL_FRZ_ALL (1 << 31) #define IVBEP_U_PMON_GLOBAL_UNFRZ_ALL (1 << 29) #define IVBEP_U_MSR_PMON_RAW_EVENT_MASK \ (SNBEP_PMON_CTL_EV_SEL_MASK | \ SNBEP_PMON_CTL_UMASK_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_U_MSR_PMON_CTL_TRESH_MASK) /* IVBEP Cbo */ #define IVBEP_CBO_MSR_PMON_RAW_EVENT_MASK (IVBEP_PMON_RAW_EVENT_MASK | \ SNBEP_CBO_PMON_CTL_TID_EN) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_TID (0x1fULL << 0) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_LINK (0xfULL << 5) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_STATE (0x3fULL << 17) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_NID (0xffffULL << 32) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_OPC (0x1ffULL << 52) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_C6 (0x1ULL << 61) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_NC (0x1ULL << 62) #define IVBEP_CB0_MSR_PMON_BOX_FILTER_ISOC (0x1ULL << 63) /* IVBEP home agent */ #define IVBEP_HA_PCI_PMON_CTL_Q_OCC_RST (1 << 16) #define IVBEP_HA_PCI_PMON_RAW_EVENT_MASK \ (IVBEP_PMON_RAW_EVENT_MASK | \ IVBEP_HA_PCI_PMON_CTL_Q_OCC_RST) /* IVBEP PCU */ #define IVBEP_PCU_MSR_PMON_RAW_EVENT_MASK \ (SNBEP_PMON_CTL_EV_SEL_MASK | \ SNBEP_PCU_MSR_PMON_CTL_OCC_SEL_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_PCU_MSR_PMON_CTL_TRESH_MASK | \ SNBEP_PCU_MSR_PMON_CTL_OCC_INVERT | \ SNBEP_PCU_MSR_PMON_CTL_OCC_EDGE_DET) /* IVBEP QPI */ #define IVBEP_QPI_PCI_PMON_RAW_EVENT_MASK \ (IVBEP_PMON_RAW_EVENT_MASK | \ SNBEP_PMON_CTL_EV_SEL_EXT) #define __BITS_VALUE(x, i, n) ((typeof(x))(((x) >> ((i) * (n))) & \ ((1ULL << (n)) - 1))) /* Haswell-EP Ubox */ #define HSWEP_U_MSR_PMON_CTR0 0x709 #define HSWEP_U_MSR_PMON_CTL0 0x705 #define HSWEP_U_MSR_PMON_FILTER 0x707 #define HSWEP_U_MSR_PMON_UCLK_FIXED_CTL 0x703 #define HSWEP_U_MSR_PMON_UCLK_FIXED_CTR 0x704 #define HSWEP_U_MSR_PMON_BOX_FILTER_TID (0x1 << 0) #define HSWEP_U_MSR_PMON_BOX_FILTER_CID (0x1fULL << 1) #define HSWEP_U_MSR_PMON_BOX_FILTER_MASK \ (HSWEP_U_MSR_PMON_BOX_FILTER_TID | \ HSWEP_U_MSR_PMON_BOX_FILTER_CID) /* Haswell-EP CBo */ #define HSWEP_C0_MSR_PMON_CTR0 0xe08 #define HSWEP_C0_MSR_PMON_CTL0 0xe01 #define HSWEP_C0_MSR_PMON_BOX_CTL 0xe00 #define HSWEP_C0_MSR_PMON_BOX_FILTER0 0xe05 #define HSWEP_CBO_MSR_OFFSET 0x10 #define HSWEP_CB0_MSR_PMON_BOX_FILTER_TID (0x3fULL << 0) #define HSWEP_CB0_MSR_PMON_BOX_FILTER_LINK (0xfULL << 6) #define HSWEP_CB0_MSR_PMON_BOX_FILTER_STATE (0x7fULL << 17) #define HSWEP_CB0_MSR_PMON_BOX_FILTER_NID (0xffffULL << 32) #define HSWEP_CB0_MSR_PMON_BOX_FILTER_OPC (0x1ffULL << 52) #define HSWEP_CB0_MSR_PMON_BOX_FILTER_C6 (0x1ULL << 61) #define HSWEP_CB0_MSR_PMON_BOX_FILTER_NC (0x1ULL << 62) #define HSWEP_CB0_MSR_PMON_BOX_FILTER_ISOC (0x1ULL << 63) /* Haswell-EP Sbox */ #define HSWEP_S0_MSR_PMON_CTR0 0x726 #define HSWEP_S0_MSR_PMON_CTL0 0x721 #define HSWEP_S0_MSR_PMON_BOX_CTL 0x720 #define HSWEP_SBOX_MSR_OFFSET 0xa #define HSWEP_S_MSR_PMON_RAW_EVENT_MASK (SNBEP_PMON_RAW_EVENT_MASK | \ SNBEP_CBO_PMON_CTL_TID_EN) /* Haswell-EP PCU */ #define HSWEP_PCU_MSR_PMON_CTR0 0x717 #define HSWEP_PCU_MSR_PMON_CTL0 0x711 #define HSWEP_PCU_MSR_PMON_BOX_CTL 0x710 #define HSWEP_PCU_MSR_PMON_BOX_FILTER 0x715 /* KNL Ubox */ #define KNL_U_MSR_PMON_RAW_EVENT_MASK \ (SNBEP_U_MSR_PMON_RAW_EVENT_MASK | \ SNBEP_CBO_PMON_CTL_TID_EN) /* KNL CHA */ #define KNL_CHA_MSR_OFFSET 0xc #define KNL_CHA_MSR_PMON_CTL_QOR (1 << 16) #define KNL_CHA_MSR_PMON_RAW_EVENT_MASK \ (SNBEP_CBO_MSR_PMON_RAW_EVENT_MASK | \ KNL_CHA_MSR_PMON_CTL_QOR) #define KNL_CHA_MSR_PMON_BOX_FILTER_TID 0x1ff #define KNL_CHA_MSR_PMON_BOX_FILTER_STATE (7 << 18) #define KNL_CHA_MSR_PMON_BOX_FILTER_OP (0xfffffe2aULL << 32) #define KNL_CHA_MSR_PMON_BOX_FILTER_REMOTE_NODE (0x1ULL << 32) #define KNL_CHA_MSR_PMON_BOX_FILTER_LOCAL_NODE (0x1ULL << 33) #define KNL_CHA_MSR_PMON_BOX_FILTER_NNC (0x1ULL << 37) /* KNL EDC/MC UCLK */ #define KNL_UCLK_MSR_PMON_CTR0_LOW 0x400 #define KNL_UCLK_MSR_PMON_CTL0 0x420 #define KNL_UCLK_MSR_PMON_BOX_CTL 0x430 #define KNL_UCLK_MSR_PMON_UCLK_FIXED_LOW 0x44c #define KNL_UCLK_MSR_PMON_UCLK_FIXED_CTL 0x454 #define KNL_PMON_FIXED_CTL_EN 0x1 /* KNL EDC */ #define KNL_EDC0_ECLK_MSR_PMON_CTR0_LOW 0xa00 #define KNL_EDC0_ECLK_MSR_PMON_CTL0 0xa20 #define KNL_EDC0_ECLK_MSR_PMON_BOX_CTL 0xa30 #define KNL_EDC0_ECLK_MSR_PMON_ECLK_FIXED_LOW 0xa3c #define KNL_EDC0_ECLK_MSR_PMON_ECLK_FIXED_CTL 0xa44 /* KNL MC */ #define KNL_MC0_CH0_MSR_PMON_CTR0_LOW 0xb00 #define KNL_MC0_CH0_MSR_PMON_CTL0 0xb20 #define KNL_MC0_CH0_MSR_PMON_BOX_CTL 0xb30 #define KNL_MC0_CH0_MSR_PMON_FIXED_LOW 0xb3c #define KNL_MC0_CH0_MSR_PMON_FIXED_CTL 0xb44 /* KNL IRP */ #define KNL_IRP_PCI_PMON_BOX_CTL 0xf0 #define KNL_IRP_PCI_PMON_RAW_EVENT_MASK (SNBEP_PMON_RAW_EVENT_MASK | \ KNL_CHA_MSR_PMON_CTL_QOR) /* KNL PCU */ #define KNL_PCU_PMON_CTL_EV_SEL_MASK 0x0000007f #define KNL_PCU_PMON_CTL_USE_OCC_CTR (1 << 7) #define KNL_PCU_MSR_PMON_CTL_TRESH_MASK 0x3f000000 #define KNL_PCU_MSR_PMON_RAW_EVENT_MASK \ (KNL_PCU_PMON_CTL_EV_SEL_MASK | \ KNL_PCU_PMON_CTL_USE_OCC_CTR | \ SNBEP_PCU_MSR_PMON_CTL_OCC_SEL_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_CBO_PMON_CTL_TID_EN | \ SNBEP_PMON_CTL_INVERT | \ KNL_PCU_MSR_PMON_CTL_TRESH_MASK | \ SNBEP_PCU_MSR_PMON_CTL_OCC_INVERT | \ SNBEP_PCU_MSR_PMON_CTL_OCC_EDGE_DET) /* SKX pci bus to socket mapping */ #define SKX_CPUNODEID 0xc0 #define SKX_GIDNIDMAP 0xd4 /* * The CPU_BUS_NUMBER MSR returns the values of the respective CPUBUSNO CSR * that BIOS programmed. MSR has package scope. * | Bit | Default | Description * | [63] | 00h | VALID - When set, indicates the CPU bus * numbers have been initialized. (RO) * |[62:48]| --- | Reserved * |[47:40]| 00h | BUS_NUM_5 - Return the bus number BIOS assigned * CPUBUSNO(5). (RO) * |[39:32]| 00h | BUS_NUM_4 - Return the bus number BIOS assigned * CPUBUSNO(4). (RO) * |[31:24]| 00h | BUS_NUM_3 - Return the bus number BIOS assigned * CPUBUSNO(3). (RO) * |[23:16]| 00h | BUS_NUM_2 - Return the bus number BIOS assigned * CPUBUSNO(2). (RO) * |[15:8] | 00h | BUS_NUM_1 - Return the bus number BIOS assigned * CPUBUSNO(1). (RO) * | [7:0] | 00h | BUS_NUM_0 - Return the bus number BIOS assigned * CPUBUSNO(0). (RO) */ #define SKX_MSR_CPU_BUS_NUMBER 0x300 #define SKX_MSR_CPU_BUS_VALID_BIT (1ULL << 63) #define BUS_NUM_STRIDE 8 /* SKX CHA */ #define SKX_CHA_MSR_PMON_BOX_FILTER_TID (0x1ffULL << 0) #define SKX_CHA_MSR_PMON_BOX_FILTER_LINK (0xfULL << 9) #define SKX_CHA_MSR_PMON_BOX_FILTER_STATE (0x3ffULL << 17) #define SKX_CHA_MSR_PMON_BOX_FILTER_REM (0x1ULL << 32) #define SKX_CHA_MSR_PMON_BOX_FILTER_LOC (0x1ULL << 33) #define SKX_CHA_MSR_PMON_BOX_FILTER_ALL_OPC (0x1ULL << 35) #define SKX_CHA_MSR_PMON_BOX_FILTER_NM (0x1ULL << 36) #define SKX_CHA_MSR_PMON_BOX_FILTER_NOT_NM (0x1ULL << 37) #define SKX_CHA_MSR_PMON_BOX_FILTER_OPC0 (0x3ffULL << 41) #define SKX_CHA_MSR_PMON_BOX_FILTER_OPC1 (0x3ffULL << 51) #define SKX_CHA_MSR_PMON_BOX_FILTER_C6 (0x1ULL << 61) #define SKX_CHA_MSR_PMON_BOX_FILTER_NC (0x1ULL << 62) #define SKX_CHA_MSR_PMON_BOX_FILTER_ISOC (0x1ULL << 63) /* SKX IIO */ #define SKX_IIO0_MSR_PMON_CTL0 0xa48 #define SKX_IIO0_MSR_PMON_CTR0 0xa41 #define SKX_IIO0_MSR_PMON_BOX_CTL 0xa40 #define SKX_IIO_MSR_OFFSET 0x20 #define SKX_PMON_CTL_TRESH_MASK (0xff << 24) #define SKX_PMON_CTL_TRESH_MASK_EXT (0xf) #define SKX_PMON_CTL_CH_MASK (0xff << 4) #define SKX_PMON_CTL_FC_MASK (0x7 << 12) #define SKX_IIO_PMON_RAW_EVENT_MASK (SNBEP_PMON_CTL_EV_SEL_MASK | \ SNBEP_PMON_CTL_UMASK_MASK | \ SNBEP_PMON_CTL_EDGE_DET | \ SNBEP_PMON_CTL_INVERT | \ SKX_PMON_CTL_TRESH_MASK) #define SKX_IIO_PMON_RAW_EVENT_MASK_EXT (SKX_PMON_CTL_TRESH_MASK_EXT | \ SKX_PMON_CTL_CH_MASK | \ SKX_PMON_CTL_FC_MASK) /* SKX IRP */ #define SKX_IRP0_MSR_PMON_CTL0 0xa5b #define SKX_IRP0_MSR_PMON_CTR0 0xa59 #define SKX_IRP0_MSR_PMON_BOX_CTL 0xa58 #define SKX_IRP_MSR_OFFSET 0x20 /* SKX UPI */ #define SKX_UPI_PCI_PMON_CTL0 0x350 #define SKX_UPI_PCI_PMON_CTR0 0x318 #define SKX_UPI_PCI_PMON_BOX_CTL 0x378 #define SKX_UPI_CTL_UMASK_EXT 0xffefff /* SKX M2M */ #define SKX_M2M_PCI_PMON_CTL0 0x228 #define SKX_M2M_PCI_PMON_CTR0 0x200 #define SKX_M2M_PCI_PMON_BOX_CTL 0x258 /* Memory Map registers device ID */ #define SNR_ICX_MESH2IIO_MMAP_DID 0x9a2 #define SNR_ICX_SAD_CONTROL_CFG 0x3f4 /* Getting I/O stack id in SAD_COTROL_CFG notation */ #define SAD_CONTROL_STACK_ID(data) (((data) >> 4) & 0x7) /* SNR Ubox */ #define SNR_U_MSR_PMON_CTR0 0x1f98 #define SNR_U_MSR_PMON_CTL0 0x1f91 #define SNR_U_MSR_PMON_UCLK_FIXED_CTL 0x1f93 #define SNR_U_MSR_PMON_UCLK_FIXED_CTR 0x1f94 /* SNR CHA */ #define SNR_CHA_RAW_EVENT_MASK_EXT 0x3ffffff #define SNR_CHA_MSR_PMON_CTL0 0x1c01 #define SNR_CHA_MSR_PMON_CTR0 0x1c08 #define SNR_CHA_MSR_PMON_BOX_CTL 0x1c00 #define SNR_C0_MSR_PMON_BOX_FILTER0 0x1c05 /* SNR IIO */ #define SNR_IIO_MSR_PMON_CTL0 0x1e08 #define SNR_IIO_MSR_PMON_CTR0 0x1e01 #define SNR_IIO_MSR_PMON_BOX_CTL 0x1e00 #define SNR_IIO_MSR_OFFSET 0x10 #define SNR_IIO_PMON_RAW_EVENT_MASK_EXT 0x7ffff /* SNR IRP */ #define SNR_IRP0_MSR_PMON_CTL0 0x1ea8 #define SNR_IRP0_MSR_PMON_CTR0 0x1ea1 #define SNR_IRP0_MSR_PMON_BOX_CTL 0x1ea0 #define SNR_IRP_MSR_OFFSET 0x10 /* SNR M2PCIE */ #define SNR_M2PCIE_MSR_PMON_CTL0 0x1e58 #define SNR_M2PCIE_MSR_PMON_CTR0 0x1e51 #define SNR_M2PCIE_MSR_PMON_BOX_CTL 0x1e50 #define SNR_M2PCIE_MSR_OFFSET 0x10 /* SNR PCU */ #define SNR_PCU_MSR_PMON_CTL0 0x1ef1 #define SNR_PCU_MSR_PMON_CTR0 0x1ef8 #define SNR_PCU_MSR_PMON_BOX_CTL 0x1ef0 #define SNR_PCU_MSR_PMON_BOX_FILTER 0x1efc /* SNR M2M */ #define SNR_M2M_PCI_PMON_CTL0 0x468 #define SNR_M2M_PCI_PMON_CTR0 0x440 #define SNR_M2M_PCI_PMON_BOX_CTL 0x438 #define SNR_M2M_PCI_PMON_UMASK_EXT 0xff /* SNR PCIE3 */ #define SNR_PCIE3_PCI_PMON_CTL0 0x508 #define SNR_PCIE3_PCI_PMON_CTR0 0x4e8 #define SNR_PCIE3_PCI_PMON_BOX_CTL 0x4e0 /* SNR IMC */ #define SNR_IMC_MMIO_PMON_FIXED_CTL 0x54 #define SNR_IMC_MMIO_PMON_FIXED_CTR 0x38 #define SNR_IMC_MMIO_PMON_CTL0 0x40 #define SNR_IMC_MMIO_PMON_CTR0 0x8 #define SNR_IMC_MMIO_PMON_BOX_CTL 0x22800 #define SNR_IMC_MMIO_OFFSET 0x4000 #define SNR_IMC_MMIO_SIZE 0x4000 #define SNR_IMC_MMIO_BASE_OFFSET 0xd0 #define SNR_IMC_MMIO_BASE_MASK 0x1FFFFFFF #define SNR_IMC_MMIO_MEM0_OFFSET 0xd8 #define SNR_IMC_MMIO_MEM0_MASK 0x7FF /* ICX CHA */ #define ICX_C34_MSR_PMON_CTR0 0xb68 #define ICX_C34_MSR_PMON_CTL0 0xb61 #define ICX_C34_MSR_PMON_BOX_CTL 0xb60 #define ICX_C34_MSR_PMON_BOX_FILTER0 0xb65 /* ICX IIO */ #define ICX_IIO_MSR_PMON_CTL0 0xa58 #define ICX_IIO_MSR_PMON_CTR0 0xa51 #define ICX_IIO_MSR_PMON_BOX_CTL 0xa50 /* ICX IRP */ #define ICX_IRP0_MSR_PMON_CTL0 0xa4d #define ICX_IRP0_MSR_PMON_CTR0 0xa4b #define ICX_IRP0_MSR_PMON_BOX_CTL 0xa4a /* ICX M2PCIE */ #define ICX_M2PCIE_MSR_PMON_CTL0 0xa46 #define ICX_M2PCIE_MSR_PMON_CTR0 0xa41 #define ICX_M2PCIE_MSR_PMON_BOX_CTL 0xa40 /* ICX UPI */ #define ICX_UPI_PCI_PMON_CTL0 0x350 #define ICX_UPI_PCI_PMON_CTR0 0x320 #define ICX_UPI_PCI_PMON_BOX_CTL 0x318 #define ICX_UPI_CTL_UMASK_EXT 0xffffff #define ICX_UBOX_DID 0x3450 /* ICX M3UPI*/ #define ICX_M3UPI_PCI_PMON_CTL0 0xd8 #define ICX_M3UPI_PCI_PMON_CTR0 0xa8 #define ICX_M3UPI_PCI_PMON_BOX_CTL 0xa0 /* ICX IMC */ #define ICX_NUMBER_IMC_CHN 3 #define ICX_IMC_MEM_STRIDE 0x4 /* SPR */ #define SPR_RAW_EVENT_MASK_EXT 0xffffff #define SPR_UBOX_DID 0x3250 /* SPR CHA */ #define SPR_CHA_PMON_CTL_TID_EN (1 << 16) #define SPR_CHA_PMON_EVENT_MASK (SNBEP_PMON_RAW_EVENT_MASK | \ SPR_CHA_PMON_CTL_TID_EN) #define SPR_CHA_PMON_BOX_FILTER_TID 0x3ff #define SPR_C0_MSR_PMON_BOX_FILTER0 0x200e DEFINE_UNCORE_FORMAT_ATTR(event, event, "config:0-7"); DEFINE_UNCORE_FORMAT_ATTR(event2, event, "config:0-6"); DEFINE_UNCORE_FORMAT_ATTR(event_ext, event, "config:0-7,21"); DEFINE_UNCORE_FORMAT_ATTR(use_occ_ctr, use_occ_ctr, "config:7"); DEFINE_UNCORE_FORMAT_ATTR(umask, umask, "config:8-15"); DEFINE_UNCORE_FORMAT_ATTR(umask_ext, umask, "config:8-15,32-43,45-55"); DEFINE_UNCORE_FORMAT_ATTR(umask_ext2, umask, "config:8-15,32-57"); DEFINE_UNCORE_FORMAT_ATTR(umask_ext3, umask, "config:8-15,32-39"); DEFINE_UNCORE_FORMAT_ATTR(umask_ext4, umask, "config:8-15,32-55"); DEFINE_UNCORE_FORMAT_ATTR(qor, qor, "config:16"); DEFINE_UNCORE_FORMAT_ATTR(edge, edge, "config:18"); DEFINE_UNCORE_FORMAT_ATTR(tid_en, tid_en, "config:19"); DEFINE_UNCORE_FORMAT_ATTR(tid_en2, tid_en, "config:16"); DEFINE_UNCORE_FORMAT_ATTR(inv, inv, "config:23"); DEFINE_UNCORE_FORMAT_ATTR(thresh9, thresh, "config:24-35"); DEFINE_UNCORE_FORMAT_ATTR(thresh8, thresh, "config:24-31"); DEFINE_UNCORE_FORMAT_ATTR(thresh6, thresh, "config:24-29"); DEFINE_UNCORE_FORMAT_ATTR(thresh5, thresh, "config:24-28"); DEFINE_UNCORE_FORMAT_ATTR(occ_sel, occ_sel, "config:14-15"); DEFINE_UNCORE_FORMAT_ATTR(occ_invert, occ_invert, "config:30"); DEFINE_UNCORE_FORMAT_ATTR(occ_edge, occ_edge, "config:14-51"); DEFINE_UNCORE_FORMAT_ATTR(occ_edge_det, occ_edge_det, "config:31"); DEFINE_UNCORE_FORMAT_ATTR(ch_mask, ch_mask, "config:36-43"); DEFINE_UNCORE_FORMAT_ATTR(ch_mask2, ch_mask, "config:36-47"); DEFINE_UNCORE_FORMAT_ATTR(fc_mask, fc_mask, "config:44-46"); DEFINE_UNCORE_FORMAT_ATTR(fc_mask2, fc_mask, "config:48-50"); DEFINE_UNCORE_FORMAT_ATTR(filter_tid, filter_tid, "config1:0-4"); DEFINE_UNCORE_FORMAT_ATTR(filter_tid2, filter_tid, "config1:0"); DEFINE_UNCORE_FORMAT_ATTR(filter_tid3, filter_tid, "config1:0-5"); DEFINE_UNCORE_FORMAT_ATTR(filter_tid4, filter_tid, "config1:0-8"); DEFINE_UNCORE_FORMAT_ATTR(filter_tid5, filter_tid, "config1:0-9"); DEFINE_UNCORE_FORMAT_ATTR(filter_cid, filter_cid, "config1:5"); DEFINE_UNCORE_FORMAT_ATTR(filter_link, filter_link, "config1:5-8"); DEFINE_UNCORE_FORMAT_ATTR(filter_link2, filter_link, "config1:6-8"); DEFINE_UNCORE_FORMAT_ATTR(filter_link3, filter_link, "config1:12"); DEFINE_UNCORE_FORMAT_ATTR(filter_nid, filter_nid, "config1:10-17"); DEFINE_UNCORE_FORMAT_ATTR(filter_nid2, filter_nid, "config1:32-47"); DEFINE_UNCORE_FORMAT_ATTR(filter_state, filter_state, "config1:18-22"); DEFINE_UNCORE_FORMAT_ATTR(filter_state2, filter_state, "config1:17-22"); DEFINE_UNCORE_FORMAT_ATTR(filter_state3, filter_state, "config1:17-23"); DEFINE_UNCORE_FORMAT_ATTR(filter_state4, filter_state, "config1:18-20"); DEFINE_UNCORE_FORMAT_ATTR(filter_state5, filter_state, "config1:17-26"); DEFINE_UNCORE_FORMAT_ATTR(filter_rem, filter_rem, "config1:32"); DEFINE_UNCORE_FORMAT_ATTR(filter_loc, filter_loc, "config1:33"); DEFINE_UNCORE_FORMAT_ATTR(filter_nm, filter_nm, "config1:36"); DEFINE_UNCORE_FORMAT_ATTR(filter_not_nm, filter_not_nm, "config1:37"); DEFINE_UNCORE_FORMAT_ATTR(filter_local, filter_local, "config1:33"); DEFINE_UNCORE_FORMAT_ATTR(filter_all_op, filter_all_op, "config1:35"); DEFINE_UNCORE_FORMAT_ATTR(filter_nnm, filter_nnm, "config1:37"); DEFINE_UNCORE_FORMAT_ATTR(filter_opc, filter_opc, "config1:23-31"); DEFINE_UNCORE_FORMAT_ATTR(filter_opc2, filter_opc, "config1:52-60"); DEFINE_UNCORE_FORMAT_ATTR(filter_opc3, filter_opc, "config1:41-60"); DEFINE_UNCORE_FORMAT_ATTR(filter_opc_0, filter_opc0, "config1:41-50"); DEFINE_UNCORE_FORMAT_ATTR(filter_opc_1, filter_opc1, "config1:51-60"); DEFINE_UNCORE_FORMAT_ATTR(filter_nc, filter_nc, "config1:62"); DEFINE_UNCORE_FORMAT_ATTR(filter_c6, filter_c6, "config1:61"); DEFINE_UNCORE_FORMAT_ATTR(filter_isoc, filter_isoc, "config1:63"); DEFINE_UNCORE_FORMAT_ATTR(filter_band0, filter_band0, "config1:0-7"); DEFINE_UNCORE_FORMAT_ATTR(filter_band1, filter_band1, "config1:8-15"); DEFINE_UNCORE_FORMAT_ATTR(filter_band2, filter_band2, "config1:16-23"); DEFINE_UNCORE_FORMAT_ATTR(filter_band3, filter_band3, "config1:24-31"); DEFINE_UNCORE_FORMAT_ATTR(match_rds, match_rds, "config1:48-51"); DEFINE_UNCORE_FORMAT_ATTR(match_rnid30, match_rnid30, "config1:32-35"); DEFINE_UNCORE_FORMAT_ATTR(match_rnid4, match_rnid4, "config1:31"); DEFINE_UNCORE_FORMAT_ATTR(match_dnid, match_dnid, "config1:13-17"); DEFINE_UNCORE_FORMAT_ATTR(match_mc, match_mc, "config1:9-12"); DEFINE_UNCORE_FORMAT_ATTR(match_opc, match_opc, "config1:5-8"); DEFINE_UNCORE_FORMAT_ATTR(match_vnw, match_vnw, "config1:3-4"); DEFINE_UNCORE_FORMAT_ATTR(match0, match0, "config1:0-31"); DEFINE_UNCORE_FORMAT_ATTR(match1, match1, "config1:32-63"); DEFINE_UNCORE_FORMAT_ATTR(mask_rds, mask_rds, "config2:48-51"); DEFINE_UNCORE_FORMAT_ATTR(mask_rnid30, mask_rnid30, "config2:32-35"); DEFINE_UNCORE_FORMAT_ATTR(mask_rnid4, mask_rnid4, "config2:31"); DEFINE_UNCORE_FORMAT_ATTR(mask_dnid, mask_dnid, "config2:13-17"); DEFINE_UNCORE_FORMAT_ATTR(mask_mc, mask_mc, "config2:9-12"); DEFINE_UNCORE_FORMAT_ATTR(mask_opc, mask_opc, "config2:5-8"); DEFINE_UNCORE_FORMAT_ATTR(mask_vnw, mask_vnw, "config2:3-4"); DEFINE_UNCORE_FORMAT_ATTR(mask0, mask0, "config2:0-31"); DEFINE_UNCORE_FORMAT_ATTR(mask1, mask1, "config2:32-63"); static void snbep_uncore_pci_disable_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); u32 config = 0; if (!pci_read_config_dword(pdev, box_ctl, &config)) { config |= SNBEP_PMON_BOX_CTL_FRZ; pci_write_config_dword(pdev, box_ctl, config); } } static void snbep_uncore_pci_enable_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); u32 config = 0; if (!pci_read_config_dword(pdev, box_ctl, &config)) { config &= ~SNBEP_PMON_BOX_CTL_FRZ; pci_write_config_dword(pdev, box_ctl, config); } } static void snbep_uncore_pci_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static void snbep_uncore_pci_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, hwc->config_base, hwc->config); } static u64 snbep_uncore_pci_read_counter(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; u64 count = 0; pci_read_config_dword(pdev, hwc->event_base, (u32 *)&count); pci_read_config_dword(pdev, hwc->event_base + 4, (u32 *)&count + 1); return count; } static void snbep_uncore_pci_init_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); pci_write_config_dword(pdev, box_ctl, SNBEP_PMON_BOX_CTL_INT); } static void snbep_uncore_msr_disable_box(struct intel_uncore_box *box) { u64 config; unsigned msr; msr = uncore_msr_box_ctl(box); if (msr) { rdmsrl(msr, config); config |= SNBEP_PMON_BOX_CTL_FRZ; wrmsrl(msr, config); } } static void snbep_uncore_msr_enable_box(struct intel_uncore_box *box) { u64 config; unsigned msr; msr = uncore_msr_box_ctl(box); if (msr) { rdmsrl(msr, config); config &= ~SNBEP_PMON_BOX_CTL_FRZ; wrmsrl(msr, config); } } static void snbep_uncore_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; if (reg1->idx != EXTRA_REG_NONE) wrmsrl(reg1->reg, uncore_shared_reg_config(box, 0)); wrmsrl(hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static void snbep_uncore_msr_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; wrmsrl(hwc->config_base, hwc->config); } static void snbep_uncore_msr_init_box(struct intel_uncore_box *box) { unsigned msr = uncore_msr_box_ctl(box); if (msr) wrmsrl(msr, SNBEP_PMON_BOX_CTL_INT); } static struct attribute *snbep_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static struct attribute *snbep_uncore_ubox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh5.attr, NULL, }; static struct attribute *snbep_uncore_cbox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_filter_tid.attr, &format_attr_filter_nid.attr, &format_attr_filter_state.attr, &format_attr_filter_opc.attr, NULL, }; static struct attribute *snbep_uncore_pcu_formats_attr[] = { &format_attr_event.attr, &format_attr_occ_sel.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh5.attr, &format_attr_occ_invert.attr, &format_attr_occ_edge.attr, &format_attr_filter_band0.attr, &format_attr_filter_band1.attr, &format_attr_filter_band2.attr, &format_attr_filter_band3.attr, NULL, }; static struct attribute *snbep_uncore_qpi_formats_attr[] = { &format_attr_event_ext.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_match_rds.attr, &format_attr_match_rnid30.attr, &format_attr_match_rnid4.attr, &format_attr_match_dnid.attr, &format_attr_match_mc.attr, &format_attr_match_opc.attr, &format_attr_match_vnw.attr, &format_attr_match0.attr, &format_attr_match1.attr, &format_attr_mask_rds.attr, &format_attr_mask_rnid30.attr, &format_attr_mask_rnid4.attr, &format_attr_mask_dnid.attr, &format_attr_mask_mc.attr, &format_attr_mask_opc.attr, &format_attr_mask_vnw.attr, &format_attr_mask0.attr, &format_attr_mask1.attr, NULL, }; static struct uncore_event_desc snbep_uncore_imc_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0xff,umask=0x00"), INTEL_UNCORE_EVENT_DESC(cas_count_read, "event=0x04,umask=0x03"), INTEL_UNCORE_EVENT_DESC(cas_count_read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(cas_count_write, "event=0x04,umask=0x0c"), INTEL_UNCORE_EVENT_DESC(cas_count_write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_write.unit, "MiB"), { /* end: all zeroes */ }, }; static struct uncore_event_desc snbep_uncore_qpi_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0x14"), INTEL_UNCORE_EVENT_DESC(txl_flits_active, "event=0x00,umask=0x06"), INTEL_UNCORE_EVENT_DESC(drs_data, "event=0x102,umask=0x08"), INTEL_UNCORE_EVENT_DESC(ncb_data, "event=0x103,umask=0x04"), { /* end: all zeroes */ }, }; static const struct attribute_group snbep_uncore_format_group = { .name = "format", .attrs = snbep_uncore_formats_attr, }; static const struct attribute_group snbep_uncore_ubox_format_group = { .name = "format", .attrs = snbep_uncore_ubox_formats_attr, }; static const struct attribute_group snbep_uncore_cbox_format_group = { .name = "format", .attrs = snbep_uncore_cbox_formats_attr, }; static const struct attribute_group snbep_uncore_pcu_format_group = { .name = "format", .attrs = snbep_uncore_pcu_formats_attr, }; static const struct attribute_group snbep_uncore_qpi_format_group = { .name = "format", .attrs = snbep_uncore_qpi_formats_attr, }; #define __SNBEP_UNCORE_MSR_OPS_COMMON_INIT() \ .disable_box = snbep_uncore_msr_disable_box, \ .enable_box = snbep_uncore_msr_enable_box, \ .disable_event = snbep_uncore_msr_disable_event, \ .enable_event = snbep_uncore_msr_enable_event, \ .read_counter = uncore_msr_read_counter #define SNBEP_UNCORE_MSR_OPS_COMMON_INIT() \ __SNBEP_UNCORE_MSR_OPS_COMMON_INIT(), \ .init_box = snbep_uncore_msr_init_box \ static struct intel_uncore_ops snbep_uncore_msr_ops = { SNBEP_UNCORE_MSR_OPS_COMMON_INIT(), }; #define SNBEP_UNCORE_PCI_OPS_COMMON_INIT() \ .init_box = snbep_uncore_pci_init_box, \ .disable_box = snbep_uncore_pci_disable_box, \ .enable_box = snbep_uncore_pci_enable_box, \ .disable_event = snbep_uncore_pci_disable_event, \ .read_counter = snbep_uncore_pci_read_counter static struct intel_uncore_ops snbep_uncore_pci_ops = { SNBEP_UNCORE_PCI_OPS_COMMON_INIT(), .enable_event = snbep_uncore_pci_enable_event, \ }; static struct event_constraint snbep_uncore_cbox_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x01, 0x1), UNCORE_EVENT_CONSTRAINT(0x02, 0x3), UNCORE_EVENT_CONSTRAINT(0x04, 0x3), UNCORE_EVENT_CONSTRAINT(0x05, 0x3), UNCORE_EVENT_CONSTRAINT(0x07, 0x3), UNCORE_EVENT_CONSTRAINT(0x09, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x1), UNCORE_EVENT_CONSTRAINT(0x12, 0x3), UNCORE_EVENT_CONSTRAINT(0x13, 0x3), UNCORE_EVENT_CONSTRAINT(0x1b, 0xc), UNCORE_EVENT_CONSTRAINT(0x1c, 0xc), UNCORE_EVENT_CONSTRAINT(0x1d, 0xc), UNCORE_EVENT_CONSTRAINT(0x1e, 0xc), UNCORE_EVENT_CONSTRAINT(0x1f, 0xe), UNCORE_EVENT_CONSTRAINT(0x21, 0x3), UNCORE_EVENT_CONSTRAINT(0x23, 0x3), UNCORE_EVENT_CONSTRAINT(0x31, 0x3), UNCORE_EVENT_CONSTRAINT(0x32, 0x3), UNCORE_EVENT_CONSTRAINT(0x33, 0x3), UNCORE_EVENT_CONSTRAINT(0x34, 0x3), UNCORE_EVENT_CONSTRAINT(0x35, 0x3), UNCORE_EVENT_CONSTRAINT(0x36, 0x1), UNCORE_EVENT_CONSTRAINT(0x37, 0x3), UNCORE_EVENT_CONSTRAINT(0x38, 0x3), UNCORE_EVENT_CONSTRAINT(0x39, 0x3), UNCORE_EVENT_CONSTRAINT(0x3b, 0x1), EVENT_CONSTRAINT_END }; static struct event_constraint snbep_uncore_r2pcie_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x10, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x3), UNCORE_EVENT_CONSTRAINT(0x12, 0x1), UNCORE_EVENT_CONSTRAINT(0x23, 0x3), UNCORE_EVENT_CONSTRAINT(0x24, 0x3), UNCORE_EVENT_CONSTRAINT(0x25, 0x3), UNCORE_EVENT_CONSTRAINT(0x26, 0x3), UNCORE_EVENT_CONSTRAINT(0x32, 0x3), UNCORE_EVENT_CONSTRAINT(0x33, 0x3), UNCORE_EVENT_CONSTRAINT(0x34, 0x3), EVENT_CONSTRAINT_END }; static struct event_constraint snbep_uncore_r3qpi_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x10, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x3), UNCORE_EVENT_CONSTRAINT(0x12, 0x3), UNCORE_EVENT_CONSTRAINT(0x13, 0x1), UNCORE_EVENT_CONSTRAINT(0x20, 0x3), UNCORE_EVENT_CONSTRAINT(0x21, 0x3), UNCORE_EVENT_CONSTRAINT(0x22, 0x3), UNCORE_EVENT_CONSTRAINT(0x23, 0x3), UNCORE_EVENT_CONSTRAINT(0x24, 0x3), UNCORE_EVENT_CONSTRAINT(0x25, 0x3), UNCORE_EVENT_CONSTRAINT(0x26, 0x3), UNCORE_EVENT_CONSTRAINT(0x28, 0x3), UNCORE_EVENT_CONSTRAINT(0x29, 0x3), UNCORE_EVENT_CONSTRAINT(0x2a, 0x3), UNCORE_EVENT_CONSTRAINT(0x2b, 0x3), UNCORE_EVENT_CONSTRAINT(0x2c, 0x3), UNCORE_EVENT_CONSTRAINT(0x2d, 0x3), UNCORE_EVENT_CONSTRAINT(0x2e, 0x3), UNCORE_EVENT_CONSTRAINT(0x2f, 0x3), UNCORE_EVENT_CONSTRAINT(0x30, 0x3), UNCORE_EVENT_CONSTRAINT(0x31, 0x3), UNCORE_EVENT_CONSTRAINT(0x32, 0x3), UNCORE_EVENT_CONSTRAINT(0x33, 0x3), UNCORE_EVENT_CONSTRAINT(0x34, 0x3), UNCORE_EVENT_CONSTRAINT(0x36, 0x3), UNCORE_EVENT_CONSTRAINT(0x37, 0x3), UNCORE_EVENT_CONSTRAINT(0x38, 0x3), UNCORE_EVENT_CONSTRAINT(0x39, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type snbep_uncore_ubox = { .name = "ubox", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 44, .fixed_ctr_bits = 48, .perf_ctr = SNBEP_U_MSR_PMON_CTR0, .event_ctl = SNBEP_U_MSR_PMON_CTL0, .event_mask = SNBEP_U_MSR_PMON_RAW_EVENT_MASK, .fixed_ctr = SNBEP_U_MSR_PMON_UCLK_FIXED_CTR, .fixed_ctl = SNBEP_U_MSR_PMON_UCLK_FIXED_CTL, .ops = &snbep_uncore_msr_ops, .format_group = &snbep_uncore_ubox_format_group, }; static struct extra_reg snbep_uncore_cbox_extra_regs[] = { SNBEP_CBO_EVENT_EXTRA_REG(SNBEP_CBO_PMON_CTL_TID_EN, SNBEP_CBO_PMON_CTL_TID_EN, 0x1), SNBEP_CBO_EVENT_EXTRA_REG(0x0334, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4334, 0xffff, 0x6), SNBEP_CBO_EVENT_EXTRA_REG(0x0534, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4534, 0xffff, 0x6), SNBEP_CBO_EVENT_EXTRA_REG(0x0934, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4934, 0xffff, 0x6), SNBEP_CBO_EVENT_EXTRA_REG(0x4134, 0xffff, 0x6), SNBEP_CBO_EVENT_EXTRA_REG(0x0135, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x0335, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4135, 0xffff, 0xa), SNBEP_CBO_EVENT_EXTRA_REG(0x4335, 0xffff, 0xa), SNBEP_CBO_EVENT_EXTRA_REG(0x4435, 0xffff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x4835, 0xffff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x4a35, 0xffff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x5035, 0xffff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x0136, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x0336, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4136, 0xffff, 0xa), SNBEP_CBO_EVENT_EXTRA_REG(0x4336, 0xffff, 0xa), SNBEP_CBO_EVENT_EXTRA_REG(0x4436, 0xffff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x4836, 0xffff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x4a36, 0xffff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x4037, 0x40ff, 0x2), EVENT_EXTRA_END }; static void snbep_cbox_put_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct intel_uncore_extra_reg *er = &box->shared_regs[0]; int i; if (uncore_box_is_fake(box)) return; for (i = 0; i < 5; i++) { if (reg1->alloc & (0x1 << i)) atomic_sub(1 << (i * 6), &er->ref); } reg1->alloc = 0; } static struct event_constraint * __snbep_cbox_get_constraint(struct intel_uncore_box *box, struct perf_event *event, u64 (*cbox_filter_mask)(int fields)) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct intel_uncore_extra_reg *er = &box->shared_regs[0]; int i, alloc = 0; unsigned long flags; u64 mask; if (reg1->idx == EXTRA_REG_NONE) return NULL; raw_spin_lock_irqsave(&er->lock, flags); for (i = 0; i < 5; i++) { if (!(reg1->idx & (0x1 << i))) continue; if (!uncore_box_is_fake(box) && (reg1->alloc & (0x1 << i))) continue; mask = cbox_filter_mask(0x1 << i); if (!__BITS_VALUE(atomic_read(&er->ref), i, 6) || !((reg1->config ^ er->config) & mask)) { atomic_add(1 << (i * 6), &er->ref); er->config &= ~mask; er->config |= reg1->config & mask; alloc |= (0x1 << i); } else { break; } } raw_spin_unlock_irqrestore(&er->lock, flags); if (i < 5) goto fail; if (!uncore_box_is_fake(box)) reg1->alloc |= alloc; return NULL; fail: for (; i >= 0; i--) { if (alloc & (0x1 << i)) atomic_sub(1 << (i * 6), &er->ref); } return &uncore_constraint_empty; } static u64 snbep_cbox_filter_mask(int fields) { u64 mask = 0; if (fields & 0x1) mask |= SNBEP_CB0_MSR_PMON_BOX_FILTER_TID; if (fields & 0x2) mask |= SNBEP_CB0_MSR_PMON_BOX_FILTER_NID; if (fields & 0x4) mask |= SNBEP_CB0_MSR_PMON_BOX_FILTER_STATE; if (fields & 0x8) mask |= SNBEP_CB0_MSR_PMON_BOX_FILTER_OPC; return mask; } static struct event_constraint * snbep_cbox_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { return __snbep_cbox_get_constraint(box, event, snbep_cbox_filter_mask); } static int snbep_cbox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct extra_reg *er; int idx = 0; for (er = snbep_uncore_cbox_extra_regs; er->msr; er++) { if (er->event != (event->hw.config & er->config_mask)) continue; idx |= er->idx; } if (idx) { reg1->reg = SNBEP_C0_MSR_PMON_BOX_FILTER + SNBEP_CBO_MSR_OFFSET * box->pmu->pmu_idx; reg1->config = event->attr.config1 & snbep_cbox_filter_mask(idx); reg1->idx = idx; } return 0; } static struct intel_uncore_ops snbep_uncore_cbox_ops = { SNBEP_UNCORE_MSR_OPS_COMMON_INIT(), .hw_config = snbep_cbox_hw_config, .get_constraint = snbep_cbox_get_constraint, .put_constraint = snbep_cbox_put_constraint, }; static struct intel_uncore_type snbep_uncore_cbox = { .name = "cbox", .num_counters = 4, .num_boxes = 8, .perf_ctr_bits = 44, .event_ctl = SNBEP_C0_MSR_PMON_CTL0, .perf_ctr = SNBEP_C0_MSR_PMON_CTR0, .event_mask = SNBEP_CBO_MSR_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_C0_MSR_PMON_BOX_CTL, .msr_offset = SNBEP_CBO_MSR_OFFSET, .num_shared_regs = 1, .constraints = snbep_uncore_cbox_constraints, .ops = &snbep_uncore_cbox_ops, .format_group = &snbep_uncore_cbox_format_group, }; static u64 snbep_pcu_alter_er(struct perf_event *event, int new_idx, bool modify) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; u64 config = reg1->config; if (new_idx > reg1->idx) config <<= 8 * (new_idx - reg1->idx); else config >>= 8 * (reg1->idx - new_idx); if (modify) { hwc->config += new_idx - reg1->idx; reg1->config = config; reg1->idx = new_idx; } return config; } static struct event_constraint * snbep_pcu_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct intel_uncore_extra_reg *er = &box->shared_regs[0]; unsigned long flags; int idx = reg1->idx; u64 mask, config1 = reg1->config; bool ok = false; if (reg1->idx == EXTRA_REG_NONE || (!uncore_box_is_fake(box) && reg1->alloc)) return NULL; again: mask = 0xffULL << (idx * 8); raw_spin_lock_irqsave(&er->lock, flags); if (!__BITS_VALUE(atomic_read(&er->ref), idx, 8) || !((config1 ^ er->config) & mask)) { atomic_add(1 << (idx * 8), &er->ref); er->config &= ~mask; er->config |= config1 & mask; ok = true; } raw_spin_unlock_irqrestore(&er->lock, flags); if (!ok) { idx = (idx + 1) % 4; if (idx != reg1->idx) { config1 = snbep_pcu_alter_er(event, idx, false); goto again; } return &uncore_constraint_empty; } if (!uncore_box_is_fake(box)) { if (idx != reg1->idx) snbep_pcu_alter_er(event, idx, true); reg1->alloc = 1; } return NULL; } static void snbep_pcu_put_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct intel_uncore_extra_reg *er = &box->shared_regs[0]; if (uncore_box_is_fake(box) || !reg1->alloc) return; atomic_sub(1 << (reg1->idx * 8), &er->ref); reg1->alloc = 0; } static int snbep_pcu_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; int ev_sel = hwc->config & SNBEP_PMON_CTL_EV_SEL_MASK; if (ev_sel >= 0xb && ev_sel <= 0xe) { reg1->reg = SNBEP_PCU_MSR_PMON_BOX_FILTER; reg1->idx = ev_sel - 0xb; reg1->config = event->attr.config1 & (0xff << (reg1->idx * 8)); } return 0; } static struct intel_uncore_ops snbep_uncore_pcu_ops = { SNBEP_UNCORE_MSR_OPS_COMMON_INIT(), .hw_config = snbep_pcu_hw_config, .get_constraint = snbep_pcu_get_constraint, .put_constraint = snbep_pcu_put_constraint, }; static struct intel_uncore_type snbep_uncore_pcu = { .name = "pcu", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = SNBEP_PCU_MSR_PMON_CTR0, .event_ctl = SNBEP_PCU_MSR_PMON_CTL0, .event_mask = SNBEP_PCU_MSR_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCU_MSR_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &snbep_uncore_pcu_ops, .format_group = &snbep_uncore_pcu_format_group, }; static struct intel_uncore_type *snbep_msr_uncores[] = { &snbep_uncore_ubox, &snbep_uncore_cbox, &snbep_uncore_pcu, NULL, }; void snbep_uncore_cpu_init(void) { if (snbep_uncore_cbox.num_boxes > boot_cpu_data.x86_max_cores) snbep_uncore_cbox.num_boxes = boot_cpu_data.x86_max_cores; uncore_msr_uncores = snbep_msr_uncores; } enum { SNBEP_PCI_QPI_PORT0_FILTER, SNBEP_PCI_QPI_PORT1_FILTER, BDX_PCI_QPI_PORT2_FILTER, }; static int snbep_qpi_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; if ((hwc->config & SNBEP_PMON_CTL_EV_SEL_MASK) == 0x38) { reg1->idx = 0; reg1->reg = SNBEP_Q_Py_PCI_PMON_PKT_MATCH0; reg1->config = event->attr.config1; reg2->reg = SNBEP_Q_Py_PCI_PMON_PKT_MASK0; reg2->config = event->attr.config2; } return 0; } static void snbep_qpi_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; if (reg1->idx != EXTRA_REG_NONE) { int idx = box->pmu->pmu_idx + SNBEP_PCI_QPI_PORT0_FILTER; int die = box->dieid; struct pci_dev *filter_pdev = uncore_extra_pci_dev[die].dev[idx]; if (filter_pdev) { pci_write_config_dword(filter_pdev, reg1->reg, (u32)reg1->config); pci_write_config_dword(filter_pdev, reg1->reg + 4, (u32)(reg1->config >> 32)); pci_write_config_dword(filter_pdev, reg2->reg, (u32)reg2->config); pci_write_config_dword(filter_pdev, reg2->reg + 4, (u32)(reg2->config >> 32)); } } pci_write_config_dword(pdev, hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static struct intel_uncore_ops snbep_uncore_qpi_ops = { SNBEP_UNCORE_PCI_OPS_COMMON_INIT(), .enable_event = snbep_qpi_enable_event, .hw_config = snbep_qpi_hw_config, .get_constraint = uncore_get_constraint, .put_constraint = uncore_put_constraint, }; #define SNBEP_UNCORE_PCI_COMMON_INIT() \ .perf_ctr = SNBEP_PCI_PMON_CTR0, \ .event_ctl = SNBEP_PCI_PMON_CTL0, \ .event_mask = SNBEP_PMON_RAW_EVENT_MASK, \ .box_ctl = SNBEP_PCI_PMON_BOX_CTL, \ .ops = &snbep_uncore_pci_ops, \ .format_group = &snbep_uncore_format_group static struct intel_uncore_type snbep_uncore_ha = { .name = "ha", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct intel_uncore_type snbep_uncore_imc = { .name = "imc", .num_counters = 4, .num_boxes = 4, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .fixed_ctr = SNBEP_MC_CHy_PCI_PMON_FIXED_CTR, .fixed_ctl = SNBEP_MC_CHy_PCI_PMON_FIXED_CTL, .event_descs = snbep_uncore_imc_events, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct intel_uncore_type snbep_uncore_qpi = { .name = "qpi", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = SNBEP_QPI_PCI_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &snbep_uncore_qpi_ops, .event_descs = snbep_uncore_qpi_events, .format_group = &snbep_uncore_qpi_format_group, }; static struct intel_uncore_type snbep_uncore_r2pcie = { .name = "r2pcie", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 44, .constraints = snbep_uncore_r2pcie_constraints, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct intel_uncore_type snbep_uncore_r3qpi = { .name = "r3qpi", .num_counters = 3, .num_boxes = 2, .perf_ctr_bits = 44, .constraints = snbep_uncore_r3qpi_constraints, SNBEP_UNCORE_PCI_COMMON_INIT(), }; enum { SNBEP_PCI_UNCORE_HA, SNBEP_PCI_UNCORE_IMC, SNBEP_PCI_UNCORE_QPI, SNBEP_PCI_UNCORE_R2PCIE, SNBEP_PCI_UNCORE_R3QPI, }; static struct intel_uncore_type *snbep_pci_uncores[] = { [SNBEP_PCI_UNCORE_HA] = &snbep_uncore_ha, [SNBEP_PCI_UNCORE_IMC] = &snbep_uncore_imc, [SNBEP_PCI_UNCORE_QPI] = &snbep_uncore_qpi, [SNBEP_PCI_UNCORE_R2PCIE] = &snbep_uncore_r2pcie, [SNBEP_PCI_UNCORE_R3QPI] = &snbep_uncore_r3qpi, NULL, }; static const struct pci_device_id snbep_uncore_pci_ids[] = { { /* Home Agent */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_HA), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_HA, 0), }, { /* MC Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_IMC0), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_IMC, 0), }, { /* MC Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_IMC1), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_IMC, 1), }, { /* MC Channel 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_IMC2), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_IMC, 2), }, { /* MC Channel 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_IMC3), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_IMC, 3), }, { /* QPI Port 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_QPI0), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_QPI, 0), }, { /* QPI Port 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_QPI1), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_QPI, 1), }, { /* R2PCIe */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_R2PCIE), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_R2PCIE, 0), }, { /* R3QPI Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_R3QPI0), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_R3QPI, 0), }, { /* R3QPI Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_UNC_R3QPI1), .driver_data = UNCORE_PCI_DEV_DATA(SNBEP_PCI_UNCORE_R3QPI, 1), }, { /* QPI Port 0 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3c86), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT0_FILTER), }, { /* QPI Port 0 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3c96), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT1_FILTER), }, { /* end: all zeroes */ } }; static struct pci_driver snbep_uncore_pci_driver = { .name = "snbep_uncore", .id_table = snbep_uncore_pci_ids, }; #define NODE_ID_MASK 0x7 /* Each three bits from 0 to 23 of GIDNIDMAP register correspond Node ID. */ #define GIDNIDMAP(config, id) (((config) >> (3 * (id))) & 0x7) static int upi_nodeid_groupid(struct pci_dev *ubox_dev, int nodeid_loc, int idmap_loc, int *nodeid, int *groupid) { int ret; /* get the Node ID of the local register */ ret = pci_read_config_dword(ubox_dev, nodeid_loc, nodeid); if (ret) goto err; *nodeid = *nodeid & NODE_ID_MASK; /* get the Node ID mapping */ ret = pci_read_config_dword(ubox_dev, idmap_loc, groupid); if (ret) goto err; err: return ret; } /* * build pci bus to socket mapping */ static int snbep_pci2phy_map_init(int devid, int nodeid_loc, int idmap_loc, bool reverse) { struct pci_dev *ubox_dev = NULL; int i, bus, nodeid, segment, die_id; struct pci2phy_map *map; int err = 0; u32 config = 0; while (1) { /* find the UBOX device */ ubox_dev = pci_get_device(PCI_VENDOR_ID_INTEL, devid, ubox_dev); if (!ubox_dev) break; bus = ubox_dev->bus->number; /* * The nodeid and idmap registers only contain enough * information to handle 8 nodes. On systems with more * than 8 nodes, we need to rely on NUMA information, * filled in from BIOS supplied information, to determine * the topology. */ if (nr_node_ids <= 8) { err = upi_nodeid_groupid(ubox_dev, nodeid_loc, idmap_loc, &nodeid, &config); if (err) break; segment = pci_domain_nr(ubox_dev->bus); raw_spin_lock(&pci2phy_map_lock); map = __find_pci2phy_map(segment); if (!map) { raw_spin_unlock(&pci2phy_map_lock); err = -ENOMEM; break; } /* * every three bits in the Node ID mapping register maps * to a particular node. */ for (i = 0; i < 8; i++) { if (nodeid == GIDNIDMAP(config, i)) { if (topology_max_die_per_package() > 1) die_id = i; else die_id = topology_phys_to_logical_pkg(i); if (die_id < 0) die_id = -ENODEV; map->pbus_to_dieid[bus] = die_id; break; } } raw_spin_unlock(&pci2phy_map_lock); } else { segment = pci_domain_nr(ubox_dev->bus); raw_spin_lock(&pci2phy_map_lock); map = __find_pci2phy_map(segment); if (!map) { raw_spin_unlock(&pci2phy_map_lock); err = -ENOMEM; break; } map->pbus_to_dieid[bus] = die_id = uncore_device_to_die(ubox_dev); raw_spin_unlock(&pci2phy_map_lock); if (WARN_ON_ONCE(die_id == -1)) { err = -EINVAL; break; } } } if (!err) { /* * For PCI bus with no UBOX device, find the next bus * that has UBOX device and use its mapping. */ raw_spin_lock(&pci2phy_map_lock); list_for_each_entry(map, &pci2phy_map_head, list) { i = -1; if (reverse) { for (bus = 255; bus >= 0; bus--) { if (map->pbus_to_dieid[bus] != -1) i = map->pbus_to_dieid[bus]; else map->pbus_to_dieid[bus] = i; } } else { for (bus = 0; bus <= 255; bus++) { if (map->pbus_to_dieid[bus] != -1) i = map->pbus_to_dieid[bus]; else map->pbus_to_dieid[bus] = i; } } } raw_spin_unlock(&pci2phy_map_lock); } pci_dev_put(ubox_dev); return pcibios_err_to_errno(err); } int snbep_uncore_pci_init(void) { int ret = snbep_pci2phy_map_init(0x3ce0, SNBEP_CPUNODEID, SNBEP_GIDNIDMAP, true); if (ret) return ret; uncore_pci_uncores = snbep_pci_uncores; uncore_pci_driver = &snbep_uncore_pci_driver; return 0; } /* end of Sandy Bridge-EP uncore support */ /* IvyTown uncore support */ static void ivbep_uncore_msr_init_box(struct intel_uncore_box *box) { unsigned msr = uncore_msr_box_ctl(box); if (msr) wrmsrl(msr, IVBEP_PMON_BOX_CTL_INT); } static void ivbep_uncore_pci_init_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; pci_write_config_dword(pdev, SNBEP_PCI_PMON_BOX_CTL, IVBEP_PMON_BOX_CTL_INT); } #define IVBEP_UNCORE_MSR_OPS_COMMON_INIT() \ .init_box = ivbep_uncore_msr_init_box, \ .disable_box = snbep_uncore_msr_disable_box, \ .enable_box = snbep_uncore_msr_enable_box, \ .disable_event = snbep_uncore_msr_disable_event, \ .enable_event = snbep_uncore_msr_enable_event, \ .read_counter = uncore_msr_read_counter static struct intel_uncore_ops ivbep_uncore_msr_ops = { IVBEP_UNCORE_MSR_OPS_COMMON_INIT(), }; static struct intel_uncore_ops ivbep_uncore_pci_ops = { .init_box = ivbep_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = snbep_uncore_pci_disable_event, .enable_event = snbep_uncore_pci_enable_event, .read_counter = snbep_uncore_pci_read_counter, }; #define IVBEP_UNCORE_PCI_COMMON_INIT() \ .perf_ctr = SNBEP_PCI_PMON_CTR0, \ .event_ctl = SNBEP_PCI_PMON_CTL0, \ .event_mask = IVBEP_PMON_RAW_EVENT_MASK, \ .box_ctl = SNBEP_PCI_PMON_BOX_CTL, \ .ops = &ivbep_uncore_pci_ops, \ .format_group = &ivbep_uncore_format_group static struct attribute *ivbep_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static struct attribute *ivbep_uncore_ubox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh5.attr, NULL, }; static struct attribute *ivbep_uncore_cbox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_thresh8.attr, &format_attr_filter_tid.attr, &format_attr_filter_link.attr, &format_attr_filter_state2.attr, &format_attr_filter_nid2.attr, &format_attr_filter_opc2.attr, &format_attr_filter_nc.attr, &format_attr_filter_c6.attr, &format_attr_filter_isoc.attr, NULL, }; static struct attribute *ivbep_uncore_pcu_formats_attr[] = { &format_attr_event.attr, &format_attr_occ_sel.attr, &format_attr_edge.attr, &format_attr_thresh5.attr, &format_attr_occ_invert.attr, &format_attr_occ_edge.attr, &format_attr_filter_band0.attr, &format_attr_filter_band1.attr, &format_attr_filter_band2.attr, &format_attr_filter_band3.attr, NULL, }; static struct attribute *ivbep_uncore_qpi_formats_attr[] = { &format_attr_event_ext.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_thresh8.attr, &format_attr_match_rds.attr, &format_attr_match_rnid30.attr, &format_attr_match_rnid4.attr, &format_attr_match_dnid.attr, &format_attr_match_mc.attr, &format_attr_match_opc.attr, &format_attr_match_vnw.attr, &format_attr_match0.attr, &format_attr_match1.attr, &format_attr_mask_rds.attr, &format_attr_mask_rnid30.attr, &format_attr_mask_rnid4.attr, &format_attr_mask_dnid.attr, &format_attr_mask_mc.attr, &format_attr_mask_opc.attr, &format_attr_mask_vnw.attr, &format_attr_mask0.attr, &format_attr_mask1.attr, NULL, }; static const struct attribute_group ivbep_uncore_format_group = { .name = "format", .attrs = ivbep_uncore_formats_attr, }; static const struct attribute_group ivbep_uncore_ubox_format_group = { .name = "format", .attrs = ivbep_uncore_ubox_formats_attr, }; static const struct attribute_group ivbep_uncore_cbox_format_group = { .name = "format", .attrs = ivbep_uncore_cbox_formats_attr, }; static const struct attribute_group ivbep_uncore_pcu_format_group = { .name = "format", .attrs = ivbep_uncore_pcu_formats_attr, }; static const struct attribute_group ivbep_uncore_qpi_format_group = { .name = "format", .attrs = ivbep_uncore_qpi_formats_attr, }; static struct intel_uncore_type ivbep_uncore_ubox = { .name = "ubox", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 44, .fixed_ctr_bits = 48, .perf_ctr = SNBEP_U_MSR_PMON_CTR0, .event_ctl = SNBEP_U_MSR_PMON_CTL0, .event_mask = IVBEP_U_MSR_PMON_RAW_EVENT_MASK, .fixed_ctr = SNBEP_U_MSR_PMON_UCLK_FIXED_CTR, .fixed_ctl = SNBEP_U_MSR_PMON_UCLK_FIXED_CTL, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_ubox_format_group, }; static struct extra_reg ivbep_uncore_cbox_extra_regs[] = { SNBEP_CBO_EVENT_EXTRA_REG(SNBEP_CBO_PMON_CTL_TID_EN, SNBEP_CBO_PMON_CTL_TID_EN, 0x1), SNBEP_CBO_EVENT_EXTRA_REG(0x1031, 0x10ff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x1134, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4134, 0xffff, 0xc), SNBEP_CBO_EVENT_EXTRA_REG(0x5134, 0xffff, 0xc), SNBEP_CBO_EVENT_EXTRA_REG(0x0334, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4334, 0xffff, 0xc), SNBEP_CBO_EVENT_EXTRA_REG(0x0534, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4534, 0xffff, 0xc), SNBEP_CBO_EVENT_EXTRA_REG(0x0934, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4934, 0xffff, 0xc), SNBEP_CBO_EVENT_EXTRA_REG(0x0135, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x0335, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x2135, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x2335, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x4135, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4335, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4435, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4835, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4a35, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x5035, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x8135, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x8335, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x0136, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x0336, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x2136, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x2336, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x4136, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4336, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4436, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4836, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4a36, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x5036, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x8136, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x8336, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x4037, 0x40ff, 0x8), EVENT_EXTRA_END }; static u64 ivbep_cbox_filter_mask(int fields) { u64 mask = 0; if (fields & 0x1) mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_TID; if (fields & 0x2) mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_LINK; if (fields & 0x4) mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_STATE; if (fields & 0x8) mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_NID; if (fields & 0x10) { mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_OPC; mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_NC; mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_C6; mask |= IVBEP_CB0_MSR_PMON_BOX_FILTER_ISOC; } return mask; } static struct event_constraint * ivbep_cbox_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { return __snbep_cbox_get_constraint(box, event, ivbep_cbox_filter_mask); } static int ivbep_cbox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct extra_reg *er; int idx = 0; for (er = ivbep_uncore_cbox_extra_regs; er->msr; er++) { if (er->event != (event->hw.config & er->config_mask)) continue; idx |= er->idx; } if (idx) { reg1->reg = SNBEP_C0_MSR_PMON_BOX_FILTER + SNBEP_CBO_MSR_OFFSET * box->pmu->pmu_idx; reg1->config = event->attr.config1 & ivbep_cbox_filter_mask(idx); reg1->idx = idx; } return 0; } static void ivbep_cbox_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; if (reg1->idx != EXTRA_REG_NONE) { u64 filter = uncore_shared_reg_config(box, 0); wrmsrl(reg1->reg, filter & 0xffffffff); wrmsrl(reg1->reg + 6, filter >> 32); } wrmsrl(hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static struct intel_uncore_ops ivbep_uncore_cbox_ops = { .init_box = ivbep_uncore_msr_init_box, .disable_box = snbep_uncore_msr_disable_box, .enable_box = snbep_uncore_msr_enable_box, .disable_event = snbep_uncore_msr_disable_event, .enable_event = ivbep_cbox_enable_event, .read_counter = uncore_msr_read_counter, .hw_config = ivbep_cbox_hw_config, .get_constraint = ivbep_cbox_get_constraint, .put_constraint = snbep_cbox_put_constraint, }; static struct intel_uncore_type ivbep_uncore_cbox = { .name = "cbox", .num_counters = 4, .num_boxes = 15, .perf_ctr_bits = 44, .event_ctl = SNBEP_C0_MSR_PMON_CTL0, .perf_ctr = SNBEP_C0_MSR_PMON_CTR0, .event_mask = IVBEP_CBO_MSR_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_C0_MSR_PMON_BOX_CTL, .msr_offset = SNBEP_CBO_MSR_OFFSET, .num_shared_regs = 1, .constraints = snbep_uncore_cbox_constraints, .ops = &ivbep_uncore_cbox_ops, .format_group = &ivbep_uncore_cbox_format_group, }; static struct intel_uncore_ops ivbep_uncore_pcu_ops = { IVBEP_UNCORE_MSR_OPS_COMMON_INIT(), .hw_config = snbep_pcu_hw_config, .get_constraint = snbep_pcu_get_constraint, .put_constraint = snbep_pcu_put_constraint, }; static struct intel_uncore_type ivbep_uncore_pcu = { .name = "pcu", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = SNBEP_PCU_MSR_PMON_CTR0, .event_ctl = SNBEP_PCU_MSR_PMON_CTL0, .event_mask = IVBEP_PCU_MSR_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCU_MSR_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &ivbep_uncore_pcu_ops, .format_group = &ivbep_uncore_pcu_format_group, }; static struct intel_uncore_type *ivbep_msr_uncores[] = { &ivbep_uncore_ubox, &ivbep_uncore_cbox, &ivbep_uncore_pcu, NULL, }; void ivbep_uncore_cpu_init(void) { if (ivbep_uncore_cbox.num_boxes > boot_cpu_data.x86_max_cores) ivbep_uncore_cbox.num_boxes = boot_cpu_data.x86_max_cores; uncore_msr_uncores = ivbep_msr_uncores; } static struct intel_uncore_type ivbep_uncore_ha = { .name = "ha", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, IVBEP_UNCORE_PCI_COMMON_INIT(), }; static struct intel_uncore_type ivbep_uncore_imc = { .name = "imc", .num_counters = 4, .num_boxes = 8, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .fixed_ctr = SNBEP_MC_CHy_PCI_PMON_FIXED_CTR, .fixed_ctl = SNBEP_MC_CHy_PCI_PMON_FIXED_CTL, .event_descs = snbep_uncore_imc_events, IVBEP_UNCORE_PCI_COMMON_INIT(), }; /* registers in IRP boxes are not properly aligned */ static unsigned ivbep_uncore_irp_ctls[] = {0xd8, 0xdc, 0xe0, 0xe4}; static unsigned ivbep_uncore_irp_ctrs[] = {0xa0, 0xb0, 0xb8, 0xc0}; static void ivbep_uncore_irp_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, ivbep_uncore_irp_ctls[hwc->idx], hwc->config | SNBEP_PMON_CTL_EN); } static void ivbep_uncore_irp_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, ivbep_uncore_irp_ctls[hwc->idx], hwc->config); } static u64 ivbep_uncore_irp_read_counter(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; u64 count = 0; pci_read_config_dword(pdev, ivbep_uncore_irp_ctrs[hwc->idx], (u32 *)&count); pci_read_config_dword(pdev, ivbep_uncore_irp_ctrs[hwc->idx] + 4, (u32 *)&count + 1); return count; } static struct intel_uncore_ops ivbep_uncore_irp_ops = { .init_box = ivbep_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = ivbep_uncore_irp_disable_event, .enable_event = ivbep_uncore_irp_enable_event, .read_counter = ivbep_uncore_irp_read_counter, }; static struct intel_uncore_type ivbep_uncore_irp = { .name = "irp", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .event_mask = IVBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .ops = &ivbep_uncore_irp_ops, .format_group = &ivbep_uncore_format_group, }; static struct intel_uncore_ops ivbep_uncore_qpi_ops = { .init_box = ivbep_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = snbep_uncore_pci_disable_event, .enable_event = snbep_qpi_enable_event, .read_counter = snbep_uncore_pci_read_counter, .hw_config = snbep_qpi_hw_config, .get_constraint = uncore_get_constraint, .put_constraint = uncore_put_constraint, }; static struct intel_uncore_type ivbep_uncore_qpi = { .name = "qpi", .num_counters = 4, .num_boxes = 3, .perf_ctr_bits = 48, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = IVBEP_QPI_PCI_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &ivbep_uncore_qpi_ops, .format_group = &ivbep_uncore_qpi_format_group, }; static struct intel_uncore_type ivbep_uncore_r2pcie = { .name = "r2pcie", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 44, .constraints = snbep_uncore_r2pcie_constraints, IVBEP_UNCORE_PCI_COMMON_INIT(), }; static struct intel_uncore_type ivbep_uncore_r3qpi = { .name = "r3qpi", .num_counters = 3, .num_boxes = 2, .perf_ctr_bits = 44, .constraints = snbep_uncore_r3qpi_constraints, IVBEP_UNCORE_PCI_COMMON_INIT(), }; enum { IVBEP_PCI_UNCORE_HA, IVBEP_PCI_UNCORE_IMC, IVBEP_PCI_UNCORE_IRP, IVBEP_PCI_UNCORE_QPI, IVBEP_PCI_UNCORE_R2PCIE, IVBEP_PCI_UNCORE_R3QPI, }; static struct intel_uncore_type *ivbep_pci_uncores[] = { [IVBEP_PCI_UNCORE_HA] = &ivbep_uncore_ha, [IVBEP_PCI_UNCORE_IMC] = &ivbep_uncore_imc, [IVBEP_PCI_UNCORE_IRP] = &ivbep_uncore_irp, [IVBEP_PCI_UNCORE_QPI] = &ivbep_uncore_qpi, [IVBEP_PCI_UNCORE_R2PCIE] = &ivbep_uncore_r2pcie, [IVBEP_PCI_UNCORE_R3QPI] = &ivbep_uncore_r3qpi, NULL, }; static const struct pci_device_id ivbep_uncore_pci_ids[] = { { /* Home Agent 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe30), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_HA, 0), }, { /* Home Agent 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe38), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_HA, 1), }, { /* MC0 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xeb4), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 0), }, { /* MC0 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xeb5), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 1), }, { /* MC0 Channel 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xeb0), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 2), }, { /* MC0 Channel 4 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xeb1), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 3), }, { /* MC1 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xef4), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 4), }, { /* MC1 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xef5), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 5), }, { /* MC1 Channel 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xef0), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 6), }, { /* MC1 Channel 4 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xef1), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IMC, 7), }, { /* IRP */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe39), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_IRP, 0), }, { /* QPI0 Port 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe32), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_QPI, 0), }, { /* QPI0 Port 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe33), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_QPI, 1), }, { /* QPI1 Port 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe3a), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_QPI, 2), }, { /* R2PCIe */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe34), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_R2PCIE, 0), }, { /* R3QPI0 Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe36), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_R3QPI, 0), }, { /* R3QPI0 Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe37), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_R3QPI, 1), }, { /* R3QPI1 Link 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe3e), .driver_data = UNCORE_PCI_DEV_DATA(IVBEP_PCI_UNCORE_R3QPI, 2), }, { /* QPI Port 0 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe86), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT0_FILTER), }, { /* QPI Port 0 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0xe96), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT1_FILTER), }, { /* end: all zeroes */ } }; static struct pci_driver ivbep_uncore_pci_driver = { .name = "ivbep_uncore", .id_table = ivbep_uncore_pci_ids, }; int ivbep_uncore_pci_init(void) { int ret = snbep_pci2phy_map_init(0x0e1e, SNBEP_CPUNODEID, SNBEP_GIDNIDMAP, true); if (ret) return ret; uncore_pci_uncores = ivbep_pci_uncores; uncore_pci_driver = &ivbep_uncore_pci_driver; return 0; } /* end of IvyTown uncore support */ /* KNL uncore support */ static struct attribute *knl_uncore_ubox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_inv.attr, &format_attr_thresh5.attr, NULL, }; static const struct attribute_group knl_uncore_ubox_format_group = { .name = "format", .attrs = knl_uncore_ubox_formats_attr, }; static struct intel_uncore_type knl_uncore_ubox = { .name = "ubox", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = HSWEP_U_MSR_PMON_CTR0, .event_ctl = HSWEP_U_MSR_PMON_CTL0, .event_mask = KNL_U_MSR_PMON_RAW_EVENT_MASK, .fixed_ctr = HSWEP_U_MSR_PMON_UCLK_FIXED_CTR, .fixed_ctl = HSWEP_U_MSR_PMON_UCLK_FIXED_CTL, .ops = &snbep_uncore_msr_ops, .format_group = &knl_uncore_ubox_format_group, }; static struct attribute *knl_uncore_cha_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_qor.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_filter_tid4.attr, &format_attr_filter_link3.attr, &format_attr_filter_state4.attr, &format_attr_filter_local.attr, &format_attr_filter_all_op.attr, &format_attr_filter_nnm.attr, &format_attr_filter_opc3.attr, &format_attr_filter_nc.attr, &format_attr_filter_isoc.attr, NULL, }; static const struct attribute_group knl_uncore_cha_format_group = { .name = "format", .attrs = knl_uncore_cha_formats_attr, }; static struct event_constraint knl_uncore_cha_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x11, 0x1), UNCORE_EVENT_CONSTRAINT(0x1f, 0x1), UNCORE_EVENT_CONSTRAINT(0x36, 0x1), EVENT_CONSTRAINT_END }; static struct extra_reg knl_uncore_cha_extra_regs[] = { SNBEP_CBO_EVENT_EXTRA_REG(SNBEP_CBO_PMON_CTL_TID_EN, SNBEP_CBO_PMON_CTL_TID_EN, 0x1), SNBEP_CBO_EVENT_EXTRA_REG(0x3d, 0xff, 0x2), SNBEP_CBO_EVENT_EXTRA_REG(0x35, 0xff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x36, 0xff, 0x4), EVENT_EXTRA_END }; static u64 knl_cha_filter_mask(int fields) { u64 mask = 0; if (fields & 0x1) mask |= KNL_CHA_MSR_PMON_BOX_FILTER_TID; if (fields & 0x2) mask |= KNL_CHA_MSR_PMON_BOX_FILTER_STATE; if (fields & 0x4) mask |= KNL_CHA_MSR_PMON_BOX_FILTER_OP; return mask; } static struct event_constraint * knl_cha_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { return __snbep_cbox_get_constraint(box, event, knl_cha_filter_mask); } static int knl_cha_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct extra_reg *er; int idx = 0; for (er = knl_uncore_cha_extra_regs; er->msr; er++) { if (er->event != (event->hw.config & er->config_mask)) continue; idx |= er->idx; } if (idx) { reg1->reg = HSWEP_C0_MSR_PMON_BOX_FILTER0 + KNL_CHA_MSR_OFFSET * box->pmu->pmu_idx; reg1->config = event->attr.config1 & knl_cha_filter_mask(idx); reg1->config |= KNL_CHA_MSR_PMON_BOX_FILTER_REMOTE_NODE; reg1->config |= KNL_CHA_MSR_PMON_BOX_FILTER_LOCAL_NODE; reg1->config |= KNL_CHA_MSR_PMON_BOX_FILTER_NNC; reg1->idx = idx; } return 0; } static void hswep_cbox_enable_event(struct intel_uncore_box *box, struct perf_event *event); static struct intel_uncore_ops knl_uncore_cha_ops = { .init_box = snbep_uncore_msr_init_box, .disable_box = snbep_uncore_msr_disable_box, .enable_box = snbep_uncore_msr_enable_box, .disable_event = snbep_uncore_msr_disable_event, .enable_event = hswep_cbox_enable_event, .read_counter = uncore_msr_read_counter, .hw_config = knl_cha_hw_config, .get_constraint = knl_cha_get_constraint, .put_constraint = snbep_cbox_put_constraint, }; static struct intel_uncore_type knl_uncore_cha = { .name = "cha", .num_counters = 4, .num_boxes = 38, .perf_ctr_bits = 48, .event_ctl = HSWEP_C0_MSR_PMON_CTL0, .perf_ctr = HSWEP_C0_MSR_PMON_CTR0, .event_mask = KNL_CHA_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_C0_MSR_PMON_BOX_CTL, .msr_offset = KNL_CHA_MSR_OFFSET, .num_shared_regs = 1, .constraints = knl_uncore_cha_constraints, .ops = &knl_uncore_cha_ops, .format_group = &knl_uncore_cha_format_group, }; static struct attribute *knl_uncore_pcu_formats_attr[] = { &format_attr_event2.attr, &format_attr_use_occ_ctr.attr, &format_attr_occ_sel.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_inv.attr, &format_attr_thresh6.attr, &format_attr_occ_invert.attr, &format_attr_occ_edge_det.attr, NULL, }; static const struct attribute_group knl_uncore_pcu_format_group = { .name = "format", .attrs = knl_uncore_pcu_formats_attr, }; static struct intel_uncore_type knl_uncore_pcu = { .name = "pcu", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = HSWEP_PCU_MSR_PMON_CTR0, .event_ctl = HSWEP_PCU_MSR_PMON_CTL0, .event_mask = KNL_PCU_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_PCU_MSR_PMON_BOX_CTL, .ops = &snbep_uncore_msr_ops, .format_group = &knl_uncore_pcu_format_group, }; static struct intel_uncore_type *knl_msr_uncores[] = { &knl_uncore_ubox, &knl_uncore_cha, &knl_uncore_pcu, NULL, }; void knl_uncore_cpu_init(void) { uncore_msr_uncores = knl_msr_uncores; } static void knl_uncore_imc_enable_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); pci_write_config_dword(pdev, box_ctl, 0); } static void knl_uncore_imc_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; if ((event->attr.config & SNBEP_PMON_CTL_EV_SEL_MASK) == UNCORE_FIXED_EVENT) pci_write_config_dword(pdev, hwc->config_base, hwc->config | KNL_PMON_FIXED_CTL_EN); else pci_write_config_dword(pdev, hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static struct intel_uncore_ops knl_uncore_imc_ops = { .init_box = snbep_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = knl_uncore_imc_enable_box, .read_counter = snbep_uncore_pci_read_counter, .enable_event = knl_uncore_imc_enable_event, .disable_event = snbep_uncore_pci_disable_event, }; static struct intel_uncore_type knl_uncore_imc_uclk = { .name = "imc_uclk", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = KNL_UCLK_MSR_PMON_CTR0_LOW, .event_ctl = KNL_UCLK_MSR_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .fixed_ctr = KNL_UCLK_MSR_PMON_UCLK_FIXED_LOW, .fixed_ctl = KNL_UCLK_MSR_PMON_UCLK_FIXED_CTL, .box_ctl = KNL_UCLK_MSR_PMON_BOX_CTL, .ops = &knl_uncore_imc_ops, .format_group = &snbep_uncore_format_group, }; static struct intel_uncore_type knl_uncore_imc_dclk = { .name = "imc", .num_counters = 4, .num_boxes = 6, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = KNL_MC0_CH0_MSR_PMON_CTR0_LOW, .event_ctl = KNL_MC0_CH0_MSR_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .fixed_ctr = KNL_MC0_CH0_MSR_PMON_FIXED_LOW, .fixed_ctl = KNL_MC0_CH0_MSR_PMON_FIXED_CTL, .box_ctl = KNL_MC0_CH0_MSR_PMON_BOX_CTL, .ops = &knl_uncore_imc_ops, .format_group = &snbep_uncore_format_group, }; static struct intel_uncore_type knl_uncore_edc_uclk = { .name = "edc_uclk", .num_counters = 4, .num_boxes = 8, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = KNL_UCLK_MSR_PMON_CTR0_LOW, .event_ctl = KNL_UCLK_MSR_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .fixed_ctr = KNL_UCLK_MSR_PMON_UCLK_FIXED_LOW, .fixed_ctl = KNL_UCLK_MSR_PMON_UCLK_FIXED_CTL, .box_ctl = KNL_UCLK_MSR_PMON_BOX_CTL, .ops = &knl_uncore_imc_ops, .format_group = &snbep_uncore_format_group, }; static struct intel_uncore_type knl_uncore_edc_eclk = { .name = "edc_eclk", .num_counters = 4, .num_boxes = 8, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = KNL_EDC0_ECLK_MSR_PMON_CTR0_LOW, .event_ctl = KNL_EDC0_ECLK_MSR_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .fixed_ctr = KNL_EDC0_ECLK_MSR_PMON_ECLK_FIXED_LOW, .fixed_ctl = KNL_EDC0_ECLK_MSR_PMON_ECLK_FIXED_CTL, .box_ctl = KNL_EDC0_ECLK_MSR_PMON_BOX_CTL, .ops = &knl_uncore_imc_ops, .format_group = &snbep_uncore_format_group, }; static struct event_constraint knl_uncore_m2pcie_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x23, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type knl_uncore_m2pcie = { .name = "m2pcie", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .constraints = knl_uncore_m2pcie_constraints, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct attribute *knl_uncore_irp_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_qor.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group knl_uncore_irp_format_group = { .name = "format", .attrs = knl_uncore_irp_formats_attr, }; static struct intel_uncore_type knl_uncore_irp = { .name = "irp", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = KNL_IRP_PCI_PMON_RAW_EVENT_MASK, .box_ctl = KNL_IRP_PCI_PMON_BOX_CTL, .ops = &snbep_uncore_pci_ops, .format_group = &knl_uncore_irp_format_group, }; enum { KNL_PCI_UNCORE_MC_UCLK, KNL_PCI_UNCORE_MC_DCLK, KNL_PCI_UNCORE_EDC_UCLK, KNL_PCI_UNCORE_EDC_ECLK, KNL_PCI_UNCORE_M2PCIE, KNL_PCI_UNCORE_IRP, }; static struct intel_uncore_type *knl_pci_uncores[] = { [KNL_PCI_UNCORE_MC_UCLK] = &knl_uncore_imc_uclk, [KNL_PCI_UNCORE_MC_DCLK] = &knl_uncore_imc_dclk, [KNL_PCI_UNCORE_EDC_UCLK] = &knl_uncore_edc_uclk, [KNL_PCI_UNCORE_EDC_ECLK] = &knl_uncore_edc_eclk, [KNL_PCI_UNCORE_M2PCIE] = &knl_uncore_m2pcie, [KNL_PCI_UNCORE_IRP] = &knl_uncore_irp, NULL, }; /* * KNL uses a common PCI device ID for multiple instances of an Uncore PMU * device type. prior to KNL, each instance of a PMU device type had a unique * device ID. * * PCI Device ID Uncore PMU Devices * ---------------------------------- * 0x7841 MC0 UClk, MC1 UClk * 0x7843 MC0 DClk CH 0, MC0 DClk CH 1, MC0 DClk CH 2, * MC1 DClk CH 0, MC1 DClk CH 1, MC1 DClk CH 2 * 0x7833 EDC0 UClk, EDC1 UClk, EDC2 UClk, EDC3 UClk, * EDC4 UClk, EDC5 UClk, EDC6 UClk, EDC7 UClk * 0x7835 EDC0 EClk, EDC1 EClk, EDC2 EClk, EDC3 EClk, * EDC4 EClk, EDC5 EClk, EDC6 EClk, EDC7 EClk * 0x7817 M2PCIe * 0x7814 IRP */ static const struct pci_device_id knl_uncore_pci_ids[] = { { /* MC0 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7841), .driver_data = UNCORE_PCI_DEV_FULL_DATA(10, 0, KNL_PCI_UNCORE_MC_UCLK, 0), }, { /* MC1 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7841), .driver_data = UNCORE_PCI_DEV_FULL_DATA(11, 0, KNL_PCI_UNCORE_MC_UCLK, 1), }, { /* MC0 DClk CH 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7843), .driver_data = UNCORE_PCI_DEV_FULL_DATA(8, 2, KNL_PCI_UNCORE_MC_DCLK, 0), }, { /* MC0 DClk CH 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7843), .driver_data = UNCORE_PCI_DEV_FULL_DATA(8, 3, KNL_PCI_UNCORE_MC_DCLK, 1), }, { /* MC0 DClk CH 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7843), .driver_data = UNCORE_PCI_DEV_FULL_DATA(8, 4, KNL_PCI_UNCORE_MC_DCLK, 2), }, { /* MC1 DClk CH 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7843), .driver_data = UNCORE_PCI_DEV_FULL_DATA(9, 2, KNL_PCI_UNCORE_MC_DCLK, 3), }, { /* MC1 DClk CH 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7843), .driver_data = UNCORE_PCI_DEV_FULL_DATA(9, 3, KNL_PCI_UNCORE_MC_DCLK, 4), }, { /* MC1 DClk CH 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7843), .driver_data = UNCORE_PCI_DEV_FULL_DATA(9, 4, KNL_PCI_UNCORE_MC_DCLK, 5), }, { /* EDC0 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(15, 0, KNL_PCI_UNCORE_EDC_UCLK, 0), }, { /* EDC1 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(16, 0, KNL_PCI_UNCORE_EDC_UCLK, 1), }, { /* EDC2 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(17, 0, KNL_PCI_UNCORE_EDC_UCLK, 2), }, { /* EDC3 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(18, 0, KNL_PCI_UNCORE_EDC_UCLK, 3), }, { /* EDC4 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(19, 0, KNL_PCI_UNCORE_EDC_UCLK, 4), }, { /* EDC5 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(20, 0, KNL_PCI_UNCORE_EDC_UCLK, 5), }, { /* EDC6 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(21, 0, KNL_PCI_UNCORE_EDC_UCLK, 6), }, { /* EDC7 UClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7833), .driver_data = UNCORE_PCI_DEV_FULL_DATA(22, 0, KNL_PCI_UNCORE_EDC_UCLK, 7), }, { /* EDC0 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(24, 2, KNL_PCI_UNCORE_EDC_ECLK, 0), }, { /* EDC1 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(25, 2, KNL_PCI_UNCORE_EDC_ECLK, 1), }, { /* EDC2 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(26, 2, KNL_PCI_UNCORE_EDC_ECLK, 2), }, { /* EDC3 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(27, 2, KNL_PCI_UNCORE_EDC_ECLK, 3), }, { /* EDC4 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(28, 2, KNL_PCI_UNCORE_EDC_ECLK, 4), }, { /* EDC5 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(29, 2, KNL_PCI_UNCORE_EDC_ECLK, 5), }, { /* EDC6 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(30, 2, KNL_PCI_UNCORE_EDC_ECLK, 6), }, { /* EDC7 EClk */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7835), .driver_data = UNCORE_PCI_DEV_FULL_DATA(31, 2, KNL_PCI_UNCORE_EDC_ECLK, 7), }, { /* M2PCIe */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7817), .driver_data = UNCORE_PCI_DEV_DATA(KNL_PCI_UNCORE_M2PCIE, 0), }, { /* IRP */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x7814), .driver_data = UNCORE_PCI_DEV_DATA(KNL_PCI_UNCORE_IRP, 0), }, { /* end: all zeroes */ } }; static struct pci_driver knl_uncore_pci_driver = { .name = "knl_uncore", .id_table = knl_uncore_pci_ids, }; int knl_uncore_pci_init(void) { int ret; /* All KNL PCI based PMON units are on the same PCI bus except IRP */ ret = snb_pci2phy_map_init(0x7814); /* IRP */ if (ret) return ret; ret = snb_pci2phy_map_init(0x7817); /* M2PCIe */ if (ret) return ret; uncore_pci_uncores = knl_pci_uncores; uncore_pci_driver = &knl_uncore_pci_driver; return 0; } /* end of KNL uncore support */ /* Haswell-EP uncore support */ static struct attribute *hswep_uncore_ubox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh5.attr, &format_attr_filter_tid2.attr, &format_attr_filter_cid.attr, NULL, }; static const struct attribute_group hswep_uncore_ubox_format_group = { .name = "format", .attrs = hswep_uncore_ubox_formats_attr, }; static int hswep_ubox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; reg1->reg = HSWEP_U_MSR_PMON_FILTER; reg1->config = event->attr.config1 & HSWEP_U_MSR_PMON_BOX_FILTER_MASK; reg1->idx = 0; return 0; } static struct intel_uncore_ops hswep_uncore_ubox_ops = { SNBEP_UNCORE_MSR_OPS_COMMON_INIT(), .hw_config = hswep_ubox_hw_config, .get_constraint = uncore_get_constraint, .put_constraint = uncore_put_constraint, }; static struct intel_uncore_type hswep_uncore_ubox = { .name = "ubox", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 44, .fixed_ctr_bits = 48, .perf_ctr = HSWEP_U_MSR_PMON_CTR0, .event_ctl = HSWEP_U_MSR_PMON_CTL0, .event_mask = SNBEP_U_MSR_PMON_RAW_EVENT_MASK, .fixed_ctr = HSWEP_U_MSR_PMON_UCLK_FIXED_CTR, .fixed_ctl = HSWEP_U_MSR_PMON_UCLK_FIXED_CTL, .num_shared_regs = 1, .ops = &hswep_uncore_ubox_ops, .format_group = &hswep_uncore_ubox_format_group, }; static struct attribute *hswep_uncore_cbox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_thresh8.attr, &format_attr_filter_tid3.attr, &format_attr_filter_link2.attr, &format_attr_filter_state3.attr, &format_attr_filter_nid2.attr, &format_attr_filter_opc2.attr, &format_attr_filter_nc.attr, &format_attr_filter_c6.attr, &format_attr_filter_isoc.attr, NULL, }; static const struct attribute_group hswep_uncore_cbox_format_group = { .name = "format", .attrs = hswep_uncore_cbox_formats_attr, }; static struct event_constraint hswep_uncore_cbox_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x01, 0x1), UNCORE_EVENT_CONSTRAINT(0x09, 0x1), UNCORE_EVENT_CONSTRAINT(0x11, 0x1), UNCORE_EVENT_CONSTRAINT(0x36, 0x1), UNCORE_EVENT_CONSTRAINT(0x38, 0x3), UNCORE_EVENT_CONSTRAINT(0x3b, 0x1), UNCORE_EVENT_CONSTRAINT(0x3e, 0x1), EVENT_CONSTRAINT_END }; static struct extra_reg hswep_uncore_cbox_extra_regs[] = { SNBEP_CBO_EVENT_EXTRA_REG(SNBEP_CBO_PMON_CTL_TID_EN, SNBEP_CBO_PMON_CTL_TID_EN, 0x1), SNBEP_CBO_EVENT_EXTRA_REG(0x0334, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x0534, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x0934, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x1134, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x2134, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4134, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x4037, 0x40ff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4028, 0x40ff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4032, 0x40ff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4029, 0x40ff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4033, 0x40ff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x402A, 0x40ff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x0135, 0xffff, 0x12), SNBEP_CBO_EVENT_EXTRA_REG(0x0335, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x4135, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4435, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4835, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x5035, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4335, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4a35, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x2335, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x8335, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x2135, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x8135, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x0136, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x0336, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x4136, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4436, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4836, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x4336, 0xffff, 0x18), SNBEP_CBO_EVENT_EXTRA_REG(0x4a36, 0xffff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x2336, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x8336, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x2136, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x8136, 0xffff, 0x10), SNBEP_CBO_EVENT_EXTRA_REG(0x5036, 0xffff, 0x8), EVENT_EXTRA_END }; static u64 hswep_cbox_filter_mask(int fields) { u64 mask = 0; if (fields & 0x1) mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_TID; if (fields & 0x2) mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_LINK; if (fields & 0x4) mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_STATE; if (fields & 0x8) mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_NID; if (fields & 0x10) { mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_OPC; mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_NC; mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_C6; mask |= HSWEP_CB0_MSR_PMON_BOX_FILTER_ISOC; } return mask; } static struct event_constraint * hswep_cbox_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { return __snbep_cbox_get_constraint(box, event, hswep_cbox_filter_mask); } static int hswep_cbox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct extra_reg *er; int idx = 0; for (er = hswep_uncore_cbox_extra_regs; er->msr; er++) { if (er->event != (event->hw.config & er->config_mask)) continue; idx |= er->idx; } if (idx) { reg1->reg = HSWEP_C0_MSR_PMON_BOX_FILTER0 + HSWEP_CBO_MSR_OFFSET * box->pmu->pmu_idx; reg1->config = event->attr.config1 & hswep_cbox_filter_mask(idx); reg1->idx = idx; } return 0; } static void hswep_cbox_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; if (reg1->idx != EXTRA_REG_NONE) { u64 filter = uncore_shared_reg_config(box, 0); wrmsrl(reg1->reg, filter & 0xffffffff); wrmsrl(reg1->reg + 1, filter >> 32); } wrmsrl(hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static struct intel_uncore_ops hswep_uncore_cbox_ops = { .init_box = snbep_uncore_msr_init_box, .disable_box = snbep_uncore_msr_disable_box, .enable_box = snbep_uncore_msr_enable_box, .disable_event = snbep_uncore_msr_disable_event, .enable_event = hswep_cbox_enable_event, .read_counter = uncore_msr_read_counter, .hw_config = hswep_cbox_hw_config, .get_constraint = hswep_cbox_get_constraint, .put_constraint = snbep_cbox_put_constraint, }; static struct intel_uncore_type hswep_uncore_cbox = { .name = "cbox", .num_counters = 4, .num_boxes = 18, .perf_ctr_bits = 48, .event_ctl = HSWEP_C0_MSR_PMON_CTL0, .perf_ctr = HSWEP_C0_MSR_PMON_CTR0, .event_mask = SNBEP_CBO_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_C0_MSR_PMON_BOX_CTL, .msr_offset = HSWEP_CBO_MSR_OFFSET, .num_shared_regs = 1, .constraints = hswep_uncore_cbox_constraints, .ops = &hswep_uncore_cbox_ops, .format_group = &hswep_uncore_cbox_format_group, }; /* * Write SBOX Initialization register bit by bit to avoid spurious #GPs */ static void hswep_uncore_sbox_msr_init_box(struct intel_uncore_box *box) { unsigned msr = uncore_msr_box_ctl(box); if (msr) { u64 init = SNBEP_PMON_BOX_CTL_INT; u64 flags = 0; int i; for_each_set_bit(i, (unsigned long *)&init, 64) { flags |= (1ULL << i); wrmsrl(msr, flags); } } } static struct intel_uncore_ops hswep_uncore_sbox_msr_ops = { __SNBEP_UNCORE_MSR_OPS_COMMON_INIT(), .init_box = hswep_uncore_sbox_msr_init_box }; static struct attribute *hswep_uncore_sbox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group hswep_uncore_sbox_format_group = { .name = "format", .attrs = hswep_uncore_sbox_formats_attr, }; static struct intel_uncore_type hswep_uncore_sbox = { .name = "sbox", .num_counters = 4, .num_boxes = 4, .perf_ctr_bits = 44, .event_ctl = HSWEP_S0_MSR_PMON_CTL0, .perf_ctr = HSWEP_S0_MSR_PMON_CTR0, .event_mask = HSWEP_S_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_S0_MSR_PMON_BOX_CTL, .msr_offset = HSWEP_SBOX_MSR_OFFSET, .ops = &hswep_uncore_sbox_msr_ops, .format_group = &hswep_uncore_sbox_format_group, }; static int hswep_pcu_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; int ev_sel = hwc->config & SNBEP_PMON_CTL_EV_SEL_MASK; if (ev_sel >= 0xb && ev_sel <= 0xe) { reg1->reg = HSWEP_PCU_MSR_PMON_BOX_FILTER; reg1->idx = ev_sel - 0xb; reg1->config = event->attr.config1 & (0xff << reg1->idx); } return 0; } static struct intel_uncore_ops hswep_uncore_pcu_ops = { SNBEP_UNCORE_MSR_OPS_COMMON_INIT(), .hw_config = hswep_pcu_hw_config, .get_constraint = snbep_pcu_get_constraint, .put_constraint = snbep_pcu_put_constraint, }; static struct intel_uncore_type hswep_uncore_pcu = { .name = "pcu", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = HSWEP_PCU_MSR_PMON_CTR0, .event_ctl = HSWEP_PCU_MSR_PMON_CTL0, .event_mask = SNBEP_PCU_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_PCU_MSR_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &hswep_uncore_pcu_ops, .format_group = &snbep_uncore_pcu_format_group, }; static struct intel_uncore_type *hswep_msr_uncores[] = { &hswep_uncore_ubox, &hswep_uncore_cbox, &hswep_uncore_sbox, &hswep_uncore_pcu, NULL, }; #define HSWEP_PCU_DID 0x2fc0 #define HSWEP_PCU_CAPID4_OFFET 0x94 #define hswep_get_chop(_cap) (((_cap) >> 6) & 0x3) static bool hswep_has_limit_sbox(unsigned int device) { struct pci_dev *dev = pci_get_device(PCI_VENDOR_ID_INTEL, device, NULL); u32 capid4; if (!dev) return false; pci_read_config_dword(dev, HSWEP_PCU_CAPID4_OFFET, &capid4); pci_dev_put(dev); if (!hswep_get_chop(capid4)) return true; return false; } void hswep_uncore_cpu_init(void) { if (hswep_uncore_cbox.num_boxes > boot_cpu_data.x86_max_cores) hswep_uncore_cbox.num_boxes = boot_cpu_data.x86_max_cores; /* Detect 6-8 core systems with only two SBOXes */ if (hswep_has_limit_sbox(HSWEP_PCU_DID)) hswep_uncore_sbox.num_boxes = 2; uncore_msr_uncores = hswep_msr_uncores; } static struct intel_uncore_type hswep_uncore_ha = { .name = "ha", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct uncore_event_desc hswep_uncore_imc_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0x00,umask=0x00"), INTEL_UNCORE_EVENT_DESC(cas_count_read, "event=0x04,umask=0x03"), INTEL_UNCORE_EVENT_DESC(cas_count_read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(cas_count_write, "event=0x04,umask=0x0c"), INTEL_UNCORE_EVENT_DESC(cas_count_write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_write.unit, "MiB"), { /* end: all zeroes */ }, }; static struct intel_uncore_type hswep_uncore_imc = { .name = "imc", .num_counters = 4, .num_boxes = 8, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .fixed_ctr = SNBEP_MC_CHy_PCI_PMON_FIXED_CTR, .fixed_ctl = SNBEP_MC_CHy_PCI_PMON_FIXED_CTL, .event_descs = hswep_uncore_imc_events, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static unsigned hswep_uncore_irp_ctrs[] = {0xa0, 0xa8, 0xb0, 0xb8}; static u64 hswep_uncore_irp_read_counter(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; u64 count = 0; pci_read_config_dword(pdev, hswep_uncore_irp_ctrs[hwc->idx], (u32 *)&count); pci_read_config_dword(pdev, hswep_uncore_irp_ctrs[hwc->idx] + 4, (u32 *)&count + 1); return count; } static struct intel_uncore_ops hswep_uncore_irp_ops = { .init_box = snbep_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = ivbep_uncore_irp_disable_event, .enable_event = ivbep_uncore_irp_enable_event, .read_counter = hswep_uncore_irp_read_counter, }; static struct intel_uncore_type hswep_uncore_irp = { .name = "irp", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .ops = &hswep_uncore_irp_ops, .format_group = &snbep_uncore_format_group, }; static struct intel_uncore_type hswep_uncore_qpi = { .name = "qpi", .num_counters = 4, .num_boxes = 3, .perf_ctr_bits = 48, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = SNBEP_QPI_PCI_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &snbep_uncore_qpi_ops, .format_group = &snbep_uncore_qpi_format_group, }; static struct event_constraint hswep_uncore_r2pcie_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x10, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x3), UNCORE_EVENT_CONSTRAINT(0x13, 0x1), UNCORE_EVENT_CONSTRAINT(0x23, 0x1), UNCORE_EVENT_CONSTRAINT(0x24, 0x1), UNCORE_EVENT_CONSTRAINT(0x25, 0x1), UNCORE_EVENT_CONSTRAINT(0x26, 0x3), UNCORE_EVENT_CONSTRAINT(0x27, 0x1), UNCORE_EVENT_CONSTRAINT(0x28, 0x3), UNCORE_EVENT_CONSTRAINT(0x29, 0x3), UNCORE_EVENT_CONSTRAINT(0x2a, 0x1), UNCORE_EVENT_CONSTRAINT(0x2b, 0x3), UNCORE_EVENT_CONSTRAINT(0x2c, 0x3), UNCORE_EVENT_CONSTRAINT(0x2d, 0x3), UNCORE_EVENT_CONSTRAINT(0x32, 0x3), UNCORE_EVENT_CONSTRAINT(0x33, 0x3), UNCORE_EVENT_CONSTRAINT(0x34, 0x3), UNCORE_EVENT_CONSTRAINT(0x35, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type hswep_uncore_r2pcie = { .name = "r2pcie", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .constraints = hswep_uncore_r2pcie_constraints, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct event_constraint hswep_uncore_r3qpi_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x01, 0x3), UNCORE_EVENT_CONSTRAINT(0x07, 0x7), UNCORE_EVENT_CONSTRAINT(0x08, 0x7), UNCORE_EVENT_CONSTRAINT(0x09, 0x7), UNCORE_EVENT_CONSTRAINT(0x0a, 0x7), UNCORE_EVENT_CONSTRAINT(0x0e, 0x7), UNCORE_EVENT_CONSTRAINT(0x10, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x3), UNCORE_EVENT_CONSTRAINT(0x12, 0x3), UNCORE_EVENT_CONSTRAINT(0x13, 0x1), UNCORE_EVENT_CONSTRAINT(0x14, 0x3), UNCORE_EVENT_CONSTRAINT(0x15, 0x3), UNCORE_EVENT_CONSTRAINT(0x1f, 0x3), UNCORE_EVENT_CONSTRAINT(0x20, 0x3), UNCORE_EVENT_CONSTRAINT(0x21, 0x3), UNCORE_EVENT_CONSTRAINT(0x22, 0x3), UNCORE_EVENT_CONSTRAINT(0x23, 0x3), UNCORE_EVENT_CONSTRAINT(0x25, 0x3), UNCORE_EVENT_CONSTRAINT(0x26, 0x3), UNCORE_EVENT_CONSTRAINT(0x28, 0x3), UNCORE_EVENT_CONSTRAINT(0x29, 0x3), UNCORE_EVENT_CONSTRAINT(0x2c, 0x3), UNCORE_EVENT_CONSTRAINT(0x2d, 0x3), UNCORE_EVENT_CONSTRAINT(0x2e, 0x3), UNCORE_EVENT_CONSTRAINT(0x2f, 0x3), UNCORE_EVENT_CONSTRAINT(0x31, 0x3), UNCORE_EVENT_CONSTRAINT(0x32, 0x3), UNCORE_EVENT_CONSTRAINT(0x33, 0x3), UNCORE_EVENT_CONSTRAINT(0x34, 0x3), UNCORE_EVENT_CONSTRAINT(0x36, 0x3), UNCORE_EVENT_CONSTRAINT(0x37, 0x3), UNCORE_EVENT_CONSTRAINT(0x38, 0x3), UNCORE_EVENT_CONSTRAINT(0x39, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type hswep_uncore_r3qpi = { .name = "r3qpi", .num_counters = 3, .num_boxes = 3, .perf_ctr_bits = 44, .constraints = hswep_uncore_r3qpi_constraints, SNBEP_UNCORE_PCI_COMMON_INIT(), }; enum { HSWEP_PCI_UNCORE_HA, HSWEP_PCI_UNCORE_IMC, HSWEP_PCI_UNCORE_IRP, HSWEP_PCI_UNCORE_QPI, HSWEP_PCI_UNCORE_R2PCIE, HSWEP_PCI_UNCORE_R3QPI, }; static struct intel_uncore_type *hswep_pci_uncores[] = { [HSWEP_PCI_UNCORE_HA] = &hswep_uncore_ha, [HSWEP_PCI_UNCORE_IMC] = &hswep_uncore_imc, [HSWEP_PCI_UNCORE_IRP] = &hswep_uncore_irp, [HSWEP_PCI_UNCORE_QPI] = &hswep_uncore_qpi, [HSWEP_PCI_UNCORE_R2PCIE] = &hswep_uncore_r2pcie, [HSWEP_PCI_UNCORE_R3QPI] = &hswep_uncore_r3qpi, NULL, }; static const struct pci_device_id hswep_uncore_pci_ids[] = { { /* Home Agent 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f30), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_HA, 0), }, { /* Home Agent 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f38), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_HA, 1), }, { /* MC0 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fb0), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 0), }, { /* MC0 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fb1), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 1), }, { /* MC0 Channel 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fb4), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 2), }, { /* MC0 Channel 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fb5), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 3), }, { /* MC1 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fd0), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 4), }, { /* MC1 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fd1), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 5), }, { /* MC1 Channel 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fd4), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 6), }, { /* MC1 Channel 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2fd5), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IMC, 7), }, { /* IRP */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f39), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_IRP, 0), }, { /* QPI0 Port 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f32), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_QPI, 0), }, { /* QPI0 Port 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f33), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_QPI, 1), }, { /* QPI1 Port 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f3a), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_QPI, 2), }, { /* R2PCIe */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f34), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_R2PCIE, 0), }, { /* R3QPI0 Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f36), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_R3QPI, 0), }, { /* R3QPI0 Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f37), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_R3QPI, 1), }, { /* R3QPI1 Link 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f3e), .driver_data = UNCORE_PCI_DEV_DATA(HSWEP_PCI_UNCORE_R3QPI, 2), }, { /* QPI Port 0 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f86), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT0_FILTER), }, { /* QPI Port 1 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2f96), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT1_FILTER), }, { /* end: all zeroes */ } }; static struct pci_driver hswep_uncore_pci_driver = { .name = "hswep_uncore", .id_table = hswep_uncore_pci_ids, }; int hswep_uncore_pci_init(void) { int ret = snbep_pci2phy_map_init(0x2f1e, SNBEP_CPUNODEID, SNBEP_GIDNIDMAP, true); if (ret) return ret; uncore_pci_uncores = hswep_pci_uncores; uncore_pci_driver = &hswep_uncore_pci_driver; return 0; } /* end of Haswell-EP uncore support */ /* BDX uncore support */ static struct intel_uncore_type bdx_uncore_ubox = { .name = "ubox", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = HSWEP_U_MSR_PMON_CTR0, .event_ctl = HSWEP_U_MSR_PMON_CTL0, .event_mask = SNBEP_U_MSR_PMON_RAW_EVENT_MASK, .fixed_ctr = HSWEP_U_MSR_PMON_UCLK_FIXED_CTR, .fixed_ctl = HSWEP_U_MSR_PMON_UCLK_FIXED_CTL, .num_shared_regs = 1, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_ubox_format_group, }; static struct event_constraint bdx_uncore_cbox_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x09, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x1), UNCORE_EVENT_CONSTRAINT(0x36, 0x1), UNCORE_EVENT_CONSTRAINT(0x3e, 0x1), EVENT_CONSTRAINT_END }; static struct intel_uncore_type bdx_uncore_cbox = { .name = "cbox", .num_counters = 4, .num_boxes = 24, .perf_ctr_bits = 48, .event_ctl = HSWEP_C0_MSR_PMON_CTL0, .perf_ctr = HSWEP_C0_MSR_PMON_CTR0, .event_mask = SNBEP_CBO_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_C0_MSR_PMON_BOX_CTL, .msr_offset = HSWEP_CBO_MSR_OFFSET, .num_shared_regs = 1, .constraints = bdx_uncore_cbox_constraints, .ops = &hswep_uncore_cbox_ops, .format_group = &hswep_uncore_cbox_format_group, }; static struct intel_uncore_type bdx_uncore_sbox = { .name = "sbox", .num_counters = 4, .num_boxes = 4, .perf_ctr_bits = 48, .event_ctl = HSWEP_S0_MSR_PMON_CTL0, .perf_ctr = HSWEP_S0_MSR_PMON_CTR0, .event_mask = HSWEP_S_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_S0_MSR_PMON_BOX_CTL, .msr_offset = HSWEP_SBOX_MSR_OFFSET, .ops = &hswep_uncore_sbox_msr_ops, .format_group = &hswep_uncore_sbox_format_group, }; #define BDX_MSR_UNCORE_SBOX 3 static struct intel_uncore_type *bdx_msr_uncores[] = { &bdx_uncore_ubox, &bdx_uncore_cbox, &hswep_uncore_pcu, &bdx_uncore_sbox, NULL, }; /* Bit 7 'Use Occupancy' is not available for counter 0 on BDX */ static struct event_constraint bdx_uncore_pcu_constraints[] = { EVENT_CONSTRAINT(0x80, 0xe, 0x80), EVENT_CONSTRAINT_END }; #define BDX_PCU_DID 0x6fc0 void bdx_uncore_cpu_init(void) { if (bdx_uncore_cbox.num_boxes > boot_cpu_data.x86_max_cores) bdx_uncore_cbox.num_boxes = boot_cpu_data.x86_max_cores; uncore_msr_uncores = bdx_msr_uncores; /* Detect systems with no SBOXes */ if ((boot_cpu_data.x86_model == 86) || hswep_has_limit_sbox(BDX_PCU_DID)) uncore_msr_uncores[BDX_MSR_UNCORE_SBOX] = NULL; hswep_uncore_pcu.constraints = bdx_uncore_pcu_constraints; } static struct intel_uncore_type bdx_uncore_ha = { .name = "ha", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct intel_uncore_type bdx_uncore_imc = { .name = "imc", .num_counters = 4, .num_boxes = 8, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .fixed_ctr = SNBEP_MC_CHy_PCI_PMON_FIXED_CTR, .fixed_ctl = SNBEP_MC_CHy_PCI_PMON_FIXED_CTL, .event_descs = hswep_uncore_imc_events, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct intel_uncore_type bdx_uncore_irp = { .name = "irp", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .ops = &hswep_uncore_irp_ops, .format_group = &snbep_uncore_format_group, }; static struct intel_uncore_type bdx_uncore_qpi = { .name = "qpi", .num_counters = 4, .num_boxes = 3, .perf_ctr_bits = 48, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = SNBEP_QPI_PCI_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &snbep_uncore_qpi_ops, .format_group = &snbep_uncore_qpi_format_group, }; static struct event_constraint bdx_uncore_r2pcie_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x10, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x3), UNCORE_EVENT_CONSTRAINT(0x13, 0x1), UNCORE_EVENT_CONSTRAINT(0x23, 0x1), UNCORE_EVENT_CONSTRAINT(0x25, 0x1), UNCORE_EVENT_CONSTRAINT(0x26, 0x3), UNCORE_EVENT_CONSTRAINT(0x28, 0x3), UNCORE_EVENT_CONSTRAINT(0x2c, 0x3), UNCORE_EVENT_CONSTRAINT(0x2d, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type bdx_uncore_r2pcie = { .name = "r2pcie", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .constraints = bdx_uncore_r2pcie_constraints, SNBEP_UNCORE_PCI_COMMON_INIT(), }; static struct event_constraint bdx_uncore_r3qpi_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x01, 0x7), UNCORE_EVENT_CONSTRAINT(0x07, 0x7), UNCORE_EVENT_CONSTRAINT(0x08, 0x7), UNCORE_EVENT_CONSTRAINT(0x09, 0x7), UNCORE_EVENT_CONSTRAINT(0x0a, 0x7), UNCORE_EVENT_CONSTRAINT(0x0e, 0x7), UNCORE_EVENT_CONSTRAINT(0x10, 0x3), UNCORE_EVENT_CONSTRAINT(0x11, 0x3), UNCORE_EVENT_CONSTRAINT(0x13, 0x1), UNCORE_EVENT_CONSTRAINT(0x14, 0x3), UNCORE_EVENT_CONSTRAINT(0x15, 0x3), UNCORE_EVENT_CONSTRAINT(0x1f, 0x3), UNCORE_EVENT_CONSTRAINT(0x20, 0x3), UNCORE_EVENT_CONSTRAINT(0x21, 0x3), UNCORE_EVENT_CONSTRAINT(0x22, 0x3), UNCORE_EVENT_CONSTRAINT(0x23, 0x3), UNCORE_EVENT_CONSTRAINT(0x25, 0x3), UNCORE_EVENT_CONSTRAINT(0x26, 0x3), UNCORE_EVENT_CONSTRAINT(0x28, 0x3), UNCORE_EVENT_CONSTRAINT(0x29, 0x3), UNCORE_EVENT_CONSTRAINT(0x2c, 0x3), UNCORE_EVENT_CONSTRAINT(0x2d, 0x3), UNCORE_EVENT_CONSTRAINT(0x2e, 0x3), UNCORE_EVENT_CONSTRAINT(0x2f, 0x3), UNCORE_EVENT_CONSTRAINT(0x33, 0x3), UNCORE_EVENT_CONSTRAINT(0x34, 0x3), UNCORE_EVENT_CONSTRAINT(0x36, 0x3), UNCORE_EVENT_CONSTRAINT(0x37, 0x3), UNCORE_EVENT_CONSTRAINT(0x38, 0x3), UNCORE_EVENT_CONSTRAINT(0x39, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type bdx_uncore_r3qpi = { .name = "r3qpi", .num_counters = 3, .num_boxes = 3, .perf_ctr_bits = 48, .constraints = bdx_uncore_r3qpi_constraints, SNBEP_UNCORE_PCI_COMMON_INIT(), }; enum { BDX_PCI_UNCORE_HA, BDX_PCI_UNCORE_IMC, BDX_PCI_UNCORE_IRP, BDX_PCI_UNCORE_QPI, BDX_PCI_UNCORE_R2PCIE, BDX_PCI_UNCORE_R3QPI, }; static struct intel_uncore_type *bdx_pci_uncores[] = { [BDX_PCI_UNCORE_HA] = &bdx_uncore_ha, [BDX_PCI_UNCORE_IMC] = &bdx_uncore_imc, [BDX_PCI_UNCORE_IRP] = &bdx_uncore_irp, [BDX_PCI_UNCORE_QPI] = &bdx_uncore_qpi, [BDX_PCI_UNCORE_R2PCIE] = &bdx_uncore_r2pcie, [BDX_PCI_UNCORE_R3QPI] = &bdx_uncore_r3qpi, NULL, }; static const struct pci_device_id bdx_uncore_pci_ids[] = { { /* Home Agent 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f30), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_HA, 0), }, { /* Home Agent 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f38), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_HA, 1), }, { /* MC0 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fb0), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 0), }, { /* MC0 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fb1), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 1), }, { /* MC0 Channel 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fb4), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 2), }, { /* MC0 Channel 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fb5), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 3), }, { /* MC1 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fd0), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 4), }, { /* MC1 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fd1), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 5), }, { /* MC1 Channel 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fd4), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 6), }, { /* MC1 Channel 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6fd5), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IMC, 7), }, { /* IRP */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f39), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_IRP, 0), }, { /* QPI0 Port 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f32), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_QPI, 0), }, { /* QPI0 Port 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f33), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_QPI, 1), }, { /* QPI1 Port 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f3a), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_QPI, 2), }, { /* R2PCIe */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f34), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_R2PCIE, 0), }, { /* R3QPI0 Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f36), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_R3QPI, 0), }, { /* R3QPI0 Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f37), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_R3QPI, 1), }, { /* R3QPI1 Link 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f3e), .driver_data = UNCORE_PCI_DEV_DATA(BDX_PCI_UNCORE_R3QPI, 2), }, { /* QPI Port 0 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f86), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT0_FILTER), }, { /* QPI Port 1 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f96), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, SNBEP_PCI_QPI_PORT1_FILTER), }, { /* QPI Port 2 filter */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x6f46), .driver_data = UNCORE_PCI_DEV_DATA(UNCORE_EXTRA_PCI_DEV, BDX_PCI_QPI_PORT2_FILTER), }, { /* end: all zeroes */ } }; static struct pci_driver bdx_uncore_pci_driver = { .name = "bdx_uncore", .id_table = bdx_uncore_pci_ids, }; int bdx_uncore_pci_init(void) { int ret = snbep_pci2phy_map_init(0x6f1e, SNBEP_CPUNODEID, SNBEP_GIDNIDMAP, true); if (ret) return ret; uncore_pci_uncores = bdx_pci_uncores; uncore_pci_driver = &bdx_uncore_pci_driver; return 0; } /* end of BDX uncore support */ /* SKX uncore support */ static struct intel_uncore_type skx_uncore_ubox = { .name = "ubox", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = HSWEP_U_MSR_PMON_CTR0, .event_ctl = HSWEP_U_MSR_PMON_CTL0, .event_mask = SNBEP_U_MSR_PMON_RAW_EVENT_MASK, .fixed_ctr = HSWEP_U_MSR_PMON_UCLK_FIXED_CTR, .fixed_ctl = HSWEP_U_MSR_PMON_UCLK_FIXED_CTL, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_ubox_format_group, }; static struct attribute *skx_uncore_cha_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_filter_tid4.attr, &format_attr_filter_state5.attr, &format_attr_filter_rem.attr, &format_attr_filter_loc.attr, &format_attr_filter_nm.attr, &format_attr_filter_all_op.attr, &format_attr_filter_not_nm.attr, &format_attr_filter_opc_0.attr, &format_attr_filter_opc_1.attr, &format_attr_filter_nc.attr, &format_attr_filter_isoc.attr, NULL, }; static const struct attribute_group skx_uncore_chabox_format_group = { .name = "format", .attrs = skx_uncore_cha_formats_attr, }; static struct event_constraint skx_uncore_chabox_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x11, 0x1), UNCORE_EVENT_CONSTRAINT(0x36, 0x1), EVENT_CONSTRAINT_END }; static struct extra_reg skx_uncore_cha_extra_regs[] = { SNBEP_CBO_EVENT_EXTRA_REG(0x0334, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x0534, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x0934, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x1134, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x3134, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x9134, 0xffff, 0x4), SNBEP_CBO_EVENT_EXTRA_REG(0x35, 0xff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x36, 0xff, 0x8), SNBEP_CBO_EVENT_EXTRA_REG(0x38, 0xff, 0x3), EVENT_EXTRA_END }; static u64 skx_cha_filter_mask(int fields) { u64 mask = 0; if (fields & 0x1) mask |= SKX_CHA_MSR_PMON_BOX_FILTER_TID; if (fields & 0x2) mask |= SKX_CHA_MSR_PMON_BOX_FILTER_LINK; if (fields & 0x4) mask |= SKX_CHA_MSR_PMON_BOX_FILTER_STATE; if (fields & 0x8) { mask |= SKX_CHA_MSR_PMON_BOX_FILTER_REM; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_LOC; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_ALL_OPC; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_NM; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_NOT_NM; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_OPC0; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_OPC1; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_NC; mask |= SKX_CHA_MSR_PMON_BOX_FILTER_ISOC; } return mask; } static struct event_constraint * skx_cha_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { return __snbep_cbox_get_constraint(box, event, skx_cha_filter_mask); } static int skx_cha_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct extra_reg *er; int idx = 0; /* Any of the CHA events may be filtered by Thread/Core-ID.*/ if (event->hw.config & SNBEP_CBO_PMON_CTL_TID_EN) idx = SKX_CHA_MSR_PMON_BOX_FILTER_TID; for (er = skx_uncore_cha_extra_regs; er->msr; er++) { if (er->event != (event->hw.config & er->config_mask)) continue; idx |= er->idx; } if (idx) { reg1->reg = HSWEP_C0_MSR_PMON_BOX_FILTER0 + HSWEP_CBO_MSR_OFFSET * box->pmu->pmu_idx; reg1->config = event->attr.config1 & skx_cha_filter_mask(idx); reg1->idx = idx; } return 0; } static struct intel_uncore_ops skx_uncore_chabox_ops = { /* There is no frz_en for chabox ctl */ .init_box = ivbep_uncore_msr_init_box, .disable_box = snbep_uncore_msr_disable_box, .enable_box = snbep_uncore_msr_enable_box, .disable_event = snbep_uncore_msr_disable_event, .enable_event = hswep_cbox_enable_event, .read_counter = uncore_msr_read_counter, .hw_config = skx_cha_hw_config, .get_constraint = skx_cha_get_constraint, .put_constraint = snbep_cbox_put_constraint, }; static struct intel_uncore_type skx_uncore_chabox = { .name = "cha", .num_counters = 4, .perf_ctr_bits = 48, .event_ctl = HSWEP_C0_MSR_PMON_CTL0, .perf_ctr = HSWEP_C0_MSR_PMON_CTR0, .event_mask = HSWEP_S_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_C0_MSR_PMON_BOX_CTL, .msr_offset = HSWEP_CBO_MSR_OFFSET, .num_shared_regs = 1, .constraints = skx_uncore_chabox_constraints, .ops = &skx_uncore_chabox_ops, .format_group = &skx_uncore_chabox_format_group, }; static struct attribute *skx_uncore_iio_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh9.attr, &format_attr_ch_mask.attr, &format_attr_fc_mask.attr, NULL, }; static const struct attribute_group skx_uncore_iio_format_group = { .name = "format", .attrs = skx_uncore_iio_formats_attr, }; static struct event_constraint skx_uncore_iio_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x83, 0x3), UNCORE_EVENT_CONSTRAINT(0x88, 0xc), UNCORE_EVENT_CONSTRAINT(0x95, 0xc), UNCORE_EVENT_CONSTRAINT(0xc0, 0xc), UNCORE_EVENT_CONSTRAINT(0xc5, 0xc), UNCORE_EVENT_CONSTRAINT(0xd4, 0xc), UNCORE_EVENT_CONSTRAINT(0xd5, 0xc), EVENT_CONSTRAINT_END }; static void skx_iio_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; wrmsrl(hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static struct intel_uncore_ops skx_uncore_iio_ops = { .init_box = ivbep_uncore_msr_init_box, .disable_box = snbep_uncore_msr_disable_box, .enable_box = snbep_uncore_msr_enable_box, .disable_event = snbep_uncore_msr_disable_event, .enable_event = skx_iio_enable_event, .read_counter = uncore_msr_read_counter, }; static struct intel_uncore_topology *pmu_topology(struct intel_uncore_pmu *pmu, int die) { int idx; for (idx = 0; idx < pmu->type->num_boxes; idx++) { if (pmu->type->topology[die][idx].pmu_idx == pmu->pmu_idx) return &pmu->type->topology[die][idx]; } return NULL; } static umode_t pmu_iio_mapping_visible(struct kobject *kobj, struct attribute *attr, int die, int zero_bus_pmu) { struct intel_uncore_pmu *pmu = dev_to_uncore_pmu(kobj_to_dev(kobj)); struct intel_uncore_topology *pmut = pmu_topology(pmu, die); return (pmut && !pmut->iio->pci_bus_no && pmu->pmu_idx != zero_bus_pmu) ? 0 : attr->mode; } static umode_t skx_iio_mapping_visible(struct kobject *kobj, struct attribute *attr, int die) { /* Root bus 0x00 is valid only for pmu_idx = 0. */ return pmu_iio_mapping_visible(kobj, attr, die, 0); } static ssize_t skx_iio_mapping_show(struct device *dev, struct device_attribute *attr, char *buf) { struct intel_uncore_pmu *pmu = dev_to_uncore_pmu(dev); struct dev_ext_attribute *ea = to_dev_ext_attribute(attr); long die = (long)ea->var; struct intel_uncore_topology *pmut = pmu_topology(pmu, die); return sprintf(buf, "%04x:%02x\n", pmut ? pmut->iio->segment : 0, pmut ? pmut->iio->pci_bus_no : 0); } static int skx_msr_cpu_bus_read(int cpu, u64 *topology) { u64 msr_value; if (rdmsrl_on_cpu(cpu, SKX_MSR_CPU_BUS_NUMBER, &msr_value) || !(msr_value & SKX_MSR_CPU_BUS_VALID_BIT)) return -ENXIO; *topology = msr_value; return 0; } static int die_to_cpu(int die) { int res = 0, cpu, current_die; /* * Using cpus_read_lock() to ensure cpu is not going down between * looking at cpu_online_mask. */ cpus_read_lock(); for_each_online_cpu(cpu) { current_die = topology_logical_die_id(cpu); if (current_die == die) { res = cpu; break; } } cpus_read_unlock(); return res; } enum { IIO_TOPOLOGY_TYPE, UPI_TOPOLOGY_TYPE, TOPOLOGY_MAX }; static const size_t topology_size[TOPOLOGY_MAX] = { sizeof(*((struct intel_uncore_topology *)NULL)->iio), sizeof(*((struct intel_uncore_topology *)NULL)->upi) }; static int pmu_alloc_topology(struct intel_uncore_type *type, int topology_type) { int die, idx; struct intel_uncore_topology **topology; if (!type->num_boxes) return -EPERM; topology = kcalloc(uncore_max_dies(), sizeof(*topology), GFP_KERNEL); if (!topology) goto err; for (die = 0; die < uncore_max_dies(); die++) { topology[die] = kcalloc(type->num_boxes, sizeof(**topology), GFP_KERNEL); if (!topology[die]) goto clear; for (idx = 0; idx < type->num_boxes; idx++) { topology[die][idx].untyped = kcalloc(type->num_boxes, topology_size[topology_type], GFP_KERNEL); if (!topology[die][idx].untyped) goto clear; } } type->topology = topology; return 0; clear: for (; die >= 0; die--) { for (idx = 0; idx < type->num_boxes; idx++) kfree(topology[die][idx].untyped); kfree(topology[die]); } kfree(topology); err: return -ENOMEM; } static void pmu_free_topology(struct intel_uncore_type *type) { int die, idx; if (type->topology) { for (die = 0; die < uncore_max_dies(); die++) { for (idx = 0; idx < type->num_boxes; idx++) kfree(type->topology[die][idx].untyped); kfree(type->topology[die]); } kfree(type->topology); type->topology = NULL; } } static int skx_pmu_get_topology(struct intel_uncore_type *type, int (*topology_cb)(struct intel_uncore_type*, int, int, u64)) { int die, ret = -EPERM; u64 cpu_bus_msr; for (die = 0; die < uncore_max_dies(); die++) { ret = skx_msr_cpu_bus_read(die_to_cpu(die), &cpu_bus_msr); if (ret) break; ret = uncore_die_to_segment(die); if (ret < 0) break; ret = topology_cb(type, ret, die, cpu_bus_msr); if (ret) break; } return ret; } static int skx_iio_topology_cb(struct intel_uncore_type *type, int segment, int die, u64 cpu_bus_msr) { int idx; struct intel_uncore_topology *t; for (idx = 0; idx < type->num_boxes; idx++) { t = &type->topology[die][idx]; t->pmu_idx = idx; t->iio->segment = segment; t->iio->pci_bus_no = (cpu_bus_msr >> (idx * BUS_NUM_STRIDE)) & 0xff; } return 0; } static int skx_iio_get_topology(struct intel_uncore_type *type) { return skx_pmu_get_topology(type, skx_iio_topology_cb); } static struct attribute_group skx_iio_mapping_group = { .is_visible = skx_iio_mapping_visible, }; static const struct attribute_group *skx_iio_attr_update[] = { &skx_iio_mapping_group, NULL, }; static void pmu_clear_mapping_attr(const struct attribute_group **groups, struct attribute_group *ag) { int i; for (i = 0; groups[i]; i++) { if (groups[i] == ag) { for (i++; groups[i]; i++) groups[i - 1] = groups[i]; groups[i - 1] = NULL; break; } } } static void pmu_set_mapping(struct intel_uncore_type *type, struct attribute_group *ag, ssize_t (*show)(struct device*, struct device_attribute*, char*), int topology_type) { char buf[64]; int ret; long die = -1; struct attribute **attrs = NULL; struct dev_ext_attribute *eas = NULL; ret = pmu_alloc_topology(type, topology_type); if (ret < 0) goto clear_attr_update; ret = type->get_topology(type); if (ret < 0) goto clear_topology; /* One more for NULL. */ attrs = kcalloc((uncore_max_dies() + 1), sizeof(*attrs), GFP_KERNEL); if (!attrs) goto clear_topology; eas = kcalloc(uncore_max_dies(), sizeof(*eas), GFP_KERNEL); if (!eas) goto clear_attrs; for (die = 0; die < uncore_max_dies(); die++) { snprintf(buf, sizeof(buf), "die%ld", die); sysfs_attr_init(&eas[die].attr.attr); eas[die].attr.attr.name = kstrdup(buf, GFP_KERNEL); if (!eas[die].attr.attr.name) goto err; eas[die].attr.attr.mode = 0444; eas[die].attr.show = show; eas[die].attr.store = NULL; eas[die].var = (void *)die; attrs[die] = &eas[die].attr.attr; } ag->attrs = attrs; return; err: for (; die >= 0; die--) kfree(eas[die].attr.attr.name); kfree(eas); clear_attrs: kfree(attrs); clear_topology: pmu_free_topology(type); clear_attr_update: pmu_clear_mapping_attr(type->attr_update, ag); } static void pmu_cleanup_mapping(struct intel_uncore_type *type, struct attribute_group *ag) { struct attribute **attr = ag->attrs; if (!attr) return; for (; *attr; attr++) kfree((*attr)->name); kfree(attr_to_ext_attr(*ag->attrs)); kfree(ag->attrs); ag->attrs = NULL; pmu_free_topology(type); } static void pmu_iio_set_mapping(struct intel_uncore_type *type, struct attribute_group *ag) { pmu_set_mapping(type, ag, skx_iio_mapping_show, IIO_TOPOLOGY_TYPE); } static void skx_iio_set_mapping(struct intel_uncore_type *type) { pmu_iio_set_mapping(type, &skx_iio_mapping_group); } static void skx_iio_cleanup_mapping(struct intel_uncore_type *type) { pmu_cleanup_mapping(type, &skx_iio_mapping_group); } static struct intel_uncore_type skx_uncore_iio = { .name = "iio", .num_counters = 4, .num_boxes = 6, .perf_ctr_bits = 48, .event_ctl = SKX_IIO0_MSR_PMON_CTL0, .perf_ctr = SKX_IIO0_MSR_PMON_CTR0, .event_mask = SKX_IIO_PMON_RAW_EVENT_MASK, .event_mask_ext = SKX_IIO_PMON_RAW_EVENT_MASK_EXT, .box_ctl = SKX_IIO0_MSR_PMON_BOX_CTL, .msr_offset = SKX_IIO_MSR_OFFSET, .constraints = skx_uncore_iio_constraints, .ops = &skx_uncore_iio_ops, .format_group = &skx_uncore_iio_format_group, .attr_update = skx_iio_attr_update, .get_topology = skx_iio_get_topology, .set_mapping = skx_iio_set_mapping, .cleanup_mapping = skx_iio_cleanup_mapping, }; enum perf_uncore_iio_freerunning_type_id { SKX_IIO_MSR_IOCLK = 0, SKX_IIO_MSR_BW = 1, SKX_IIO_MSR_UTIL = 2, SKX_IIO_FREERUNNING_TYPE_MAX, }; static struct freerunning_counters skx_iio_freerunning[] = { [SKX_IIO_MSR_IOCLK] = { 0xa45, 0x1, 0x20, 1, 36 }, [SKX_IIO_MSR_BW] = { 0xb00, 0x1, 0x10, 8, 36 }, [SKX_IIO_MSR_UTIL] = { 0xb08, 0x1, 0x10, 8, 36 }, }; static struct uncore_event_desc skx_uncore_iio_freerunning_events[] = { /* Free-Running IO CLOCKS Counter */ INTEL_UNCORE_EVENT_DESC(ioclk, "event=0xff,umask=0x10"), /* Free-Running IIO BANDWIDTH Counters */ INTEL_UNCORE_EVENT_DESC(bw_in_port0, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port1, "event=0xff,umask=0x21"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port2, "event=0xff,umask=0x22"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port3, "event=0xff,umask=0x23"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port0, "event=0xff,umask=0x24"), INTEL_UNCORE_EVENT_DESC(bw_out_port0.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port0.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port1, "event=0xff,umask=0x25"), INTEL_UNCORE_EVENT_DESC(bw_out_port1.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port1.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port2, "event=0xff,umask=0x26"), INTEL_UNCORE_EVENT_DESC(bw_out_port2.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port2.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port3, "event=0xff,umask=0x27"), INTEL_UNCORE_EVENT_DESC(bw_out_port3.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port3.unit, "MiB"), /* Free-running IIO UTILIZATION Counters */ INTEL_UNCORE_EVENT_DESC(util_in_port0, "event=0xff,umask=0x30"), INTEL_UNCORE_EVENT_DESC(util_out_port0, "event=0xff,umask=0x31"), INTEL_UNCORE_EVENT_DESC(util_in_port1, "event=0xff,umask=0x32"), INTEL_UNCORE_EVENT_DESC(util_out_port1, "event=0xff,umask=0x33"), INTEL_UNCORE_EVENT_DESC(util_in_port2, "event=0xff,umask=0x34"), INTEL_UNCORE_EVENT_DESC(util_out_port2, "event=0xff,umask=0x35"), INTEL_UNCORE_EVENT_DESC(util_in_port3, "event=0xff,umask=0x36"), INTEL_UNCORE_EVENT_DESC(util_out_port3, "event=0xff,umask=0x37"), { /* end: all zeroes */ }, }; static struct intel_uncore_ops skx_uncore_iio_freerunning_ops = { .read_counter = uncore_msr_read_counter, .hw_config = uncore_freerunning_hw_config, }; static struct attribute *skx_uncore_iio_freerunning_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, NULL, }; static const struct attribute_group skx_uncore_iio_freerunning_format_group = { .name = "format", .attrs = skx_uncore_iio_freerunning_formats_attr, }; static struct intel_uncore_type skx_uncore_iio_free_running = { .name = "iio_free_running", .num_counters = 17, .num_boxes = 6, .num_freerunning_types = SKX_IIO_FREERUNNING_TYPE_MAX, .freerunning = skx_iio_freerunning, .ops = &skx_uncore_iio_freerunning_ops, .event_descs = skx_uncore_iio_freerunning_events, .format_group = &skx_uncore_iio_freerunning_format_group, }; static struct attribute *skx_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group skx_uncore_format_group = { .name = "format", .attrs = skx_uncore_formats_attr, }; static struct intel_uncore_type skx_uncore_irp = { .name = "irp", .num_counters = 2, .num_boxes = 6, .perf_ctr_bits = 48, .event_ctl = SKX_IRP0_MSR_PMON_CTL0, .perf_ctr = SKX_IRP0_MSR_PMON_CTR0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SKX_IRP0_MSR_PMON_BOX_CTL, .msr_offset = SKX_IRP_MSR_OFFSET, .ops = &skx_uncore_iio_ops, .format_group = &skx_uncore_format_group, }; static struct attribute *skx_uncore_pcu_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_occ_invert.attr, &format_attr_occ_edge_det.attr, &format_attr_filter_band0.attr, &format_attr_filter_band1.attr, &format_attr_filter_band2.attr, &format_attr_filter_band3.attr, NULL, }; static struct attribute_group skx_uncore_pcu_format_group = { .name = "format", .attrs = skx_uncore_pcu_formats_attr, }; static struct intel_uncore_ops skx_uncore_pcu_ops = { IVBEP_UNCORE_MSR_OPS_COMMON_INIT(), .hw_config = hswep_pcu_hw_config, .get_constraint = snbep_pcu_get_constraint, .put_constraint = snbep_pcu_put_constraint, }; static struct intel_uncore_type skx_uncore_pcu = { .name = "pcu", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = HSWEP_PCU_MSR_PMON_CTR0, .event_ctl = HSWEP_PCU_MSR_PMON_CTL0, .event_mask = SNBEP_PCU_MSR_PMON_RAW_EVENT_MASK, .box_ctl = HSWEP_PCU_MSR_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &skx_uncore_pcu_ops, .format_group = &skx_uncore_pcu_format_group, }; static struct intel_uncore_type *skx_msr_uncores[] = { &skx_uncore_ubox, &skx_uncore_chabox, &skx_uncore_iio, &skx_uncore_iio_free_running, &skx_uncore_irp, &skx_uncore_pcu, NULL, }; /* * To determine the number of CHAs, it should read bits 27:0 in the CAPID6 * register which located at Device 30, Function 3, Offset 0x9C. PCI ID 0x2083. */ #define SKX_CAPID6 0x9c #define SKX_CHA_BIT_MASK GENMASK(27, 0) static int skx_count_chabox(void) { struct pci_dev *dev = NULL; u32 val = 0; dev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x2083, dev); if (!dev) goto out; pci_read_config_dword(dev, SKX_CAPID6, &val); val &= SKX_CHA_BIT_MASK; out: pci_dev_put(dev); return hweight32(val); } void skx_uncore_cpu_init(void) { skx_uncore_chabox.num_boxes = skx_count_chabox(); uncore_msr_uncores = skx_msr_uncores; } static struct intel_uncore_type skx_uncore_imc = { .name = "imc", .num_counters = 4, .num_boxes = 6, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .fixed_ctr = SNBEP_MC_CHy_PCI_PMON_FIXED_CTR, .fixed_ctl = SNBEP_MC_CHy_PCI_PMON_FIXED_CTL, .event_descs = hswep_uncore_imc_events, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .ops = &ivbep_uncore_pci_ops, .format_group = &skx_uncore_format_group, }; static struct attribute *skx_upi_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask_ext.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group skx_upi_uncore_format_group = { .name = "format", .attrs = skx_upi_uncore_formats_attr, }; static void skx_upi_uncore_pci_init_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; __set_bit(UNCORE_BOX_FLAG_CTL_OFFS8, &box->flags); pci_write_config_dword(pdev, SKX_UPI_PCI_PMON_BOX_CTL, IVBEP_PMON_BOX_CTL_INT); } static struct intel_uncore_ops skx_upi_uncore_pci_ops = { .init_box = skx_upi_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = snbep_uncore_pci_disable_event, .enable_event = snbep_uncore_pci_enable_event, .read_counter = snbep_uncore_pci_read_counter, }; static umode_t skx_upi_mapping_visible(struct kobject *kobj, struct attribute *attr, int die) { struct intel_uncore_pmu *pmu = dev_to_uncore_pmu(kobj_to_dev(kobj)); return pmu->type->topology[die][pmu->pmu_idx].upi->enabled ? attr->mode : 0; } static ssize_t skx_upi_mapping_show(struct device *dev, struct device_attribute *attr, char *buf) { struct intel_uncore_pmu *pmu = dev_to_uncore_pmu(dev); struct dev_ext_attribute *ea = to_dev_ext_attribute(attr); long die = (long)ea->var; struct uncore_upi_topology *upi = pmu->type->topology[die][pmu->pmu_idx].upi; return sysfs_emit(buf, "upi_%d,die_%d\n", upi->pmu_idx_to, upi->die_to); } #define SKX_UPI_REG_DID 0x2058 #define SKX_UPI_REGS_ADDR_DEVICE_LINK0 0x0e #define SKX_UPI_REGS_ADDR_FUNCTION 0x00 /* * UPI Link Parameter 0 * | Bit | Default | Description * | 19:16 | 0h | base_nodeid - The NodeID of the sending socket. * | 12:8 | 00h | sending_port - The processor die port number of the sending port. */ #define SKX_KTILP0_OFFSET 0x94 /* * UPI Pcode Status. This register is used by PCode to store the link training status. * | Bit | Default | Description * | 4 | 0h | ll_status_valid — Bit indicates the valid training status * logged from PCode to the BIOS. */ #define SKX_KTIPCSTS_OFFSET 0x120 static int upi_fill_topology(struct pci_dev *dev, struct intel_uncore_topology *tp, int pmu_idx) { int ret; u32 upi_conf; struct uncore_upi_topology *upi = tp->upi; tp->pmu_idx = pmu_idx; ret = pci_read_config_dword(dev, SKX_KTIPCSTS_OFFSET, &upi_conf); if (ret) { ret = pcibios_err_to_errno(ret); goto err; } upi->enabled = (upi_conf >> 4) & 1; if (upi->enabled) { ret = pci_read_config_dword(dev, SKX_KTILP0_OFFSET, &upi_conf); if (ret) { ret = pcibios_err_to_errno(ret); goto err; } upi->die_to = (upi_conf >> 16) & 0xf; upi->pmu_idx_to = (upi_conf >> 8) & 0x1f; } err: return ret; } static int skx_upi_topology_cb(struct intel_uncore_type *type, int segment, int die, u64 cpu_bus_msr) { int idx, ret; struct intel_uncore_topology *upi; unsigned int devfn; struct pci_dev *dev = NULL; u8 bus = cpu_bus_msr >> (3 * BUS_NUM_STRIDE); for (idx = 0; idx < type->num_boxes; idx++) { upi = &type->topology[die][idx]; devfn = PCI_DEVFN(SKX_UPI_REGS_ADDR_DEVICE_LINK0 + idx, SKX_UPI_REGS_ADDR_FUNCTION); dev = pci_get_domain_bus_and_slot(segment, bus, devfn); if (dev) { ret = upi_fill_topology(dev, upi, idx); if (ret) break; } } pci_dev_put(dev); return ret; } static int skx_upi_get_topology(struct intel_uncore_type *type) { /* CPX case is not supported */ if (boot_cpu_data.x86_stepping == 11) return -EPERM; return skx_pmu_get_topology(type, skx_upi_topology_cb); } static struct attribute_group skx_upi_mapping_group = { .is_visible = skx_upi_mapping_visible, }; static const struct attribute_group *skx_upi_attr_update[] = { &skx_upi_mapping_group, NULL }; static void pmu_upi_set_mapping(struct intel_uncore_type *type, struct attribute_group *ag) { pmu_set_mapping(type, ag, skx_upi_mapping_show, UPI_TOPOLOGY_TYPE); } static void skx_upi_set_mapping(struct intel_uncore_type *type) { pmu_upi_set_mapping(type, &skx_upi_mapping_group); } static void skx_upi_cleanup_mapping(struct intel_uncore_type *type) { pmu_cleanup_mapping(type, &skx_upi_mapping_group); } static struct intel_uncore_type skx_uncore_upi = { .name = "upi", .num_counters = 4, .num_boxes = 3, .perf_ctr_bits = 48, .perf_ctr = SKX_UPI_PCI_PMON_CTR0, .event_ctl = SKX_UPI_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = SKX_UPI_CTL_UMASK_EXT, .box_ctl = SKX_UPI_PCI_PMON_BOX_CTL, .ops = &skx_upi_uncore_pci_ops, .format_group = &skx_upi_uncore_format_group, .attr_update = skx_upi_attr_update, .get_topology = skx_upi_get_topology, .set_mapping = skx_upi_set_mapping, .cleanup_mapping = skx_upi_cleanup_mapping, }; static void skx_m2m_uncore_pci_init_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; __set_bit(UNCORE_BOX_FLAG_CTL_OFFS8, &box->flags); pci_write_config_dword(pdev, SKX_M2M_PCI_PMON_BOX_CTL, IVBEP_PMON_BOX_CTL_INT); } static struct intel_uncore_ops skx_m2m_uncore_pci_ops = { .init_box = skx_m2m_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = snbep_uncore_pci_disable_event, .enable_event = snbep_uncore_pci_enable_event, .read_counter = snbep_uncore_pci_read_counter, }; static struct intel_uncore_type skx_uncore_m2m = { .name = "m2m", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, .perf_ctr = SKX_M2M_PCI_PMON_CTR0, .event_ctl = SKX_M2M_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SKX_M2M_PCI_PMON_BOX_CTL, .ops = &skx_m2m_uncore_pci_ops, .format_group = &skx_uncore_format_group, }; static struct event_constraint skx_uncore_m2pcie_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x23, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type skx_uncore_m2pcie = { .name = "m2pcie", .num_counters = 4, .num_boxes = 4, .perf_ctr_bits = 48, .constraints = skx_uncore_m2pcie_constraints, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .ops = &ivbep_uncore_pci_ops, .format_group = &skx_uncore_format_group, }; static struct event_constraint skx_uncore_m3upi_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x1d, 0x1), UNCORE_EVENT_CONSTRAINT(0x1e, 0x1), UNCORE_EVENT_CONSTRAINT(0x40, 0x7), UNCORE_EVENT_CONSTRAINT(0x4e, 0x7), UNCORE_EVENT_CONSTRAINT(0x4f, 0x7), UNCORE_EVENT_CONSTRAINT(0x50, 0x7), UNCORE_EVENT_CONSTRAINT(0x51, 0x7), UNCORE_EVENT_CONSTRAINT(0x52, 0x7), EVENT_CONSTRAINT_END }; static struct intel_uncore_type skx_uncore_m3upi = { .name = "m3upi", .num_counters = 3, .num_boxes = 3, .perf_ctr_bits = 48, .constraints = skx_uncore_m3upi_constraints, .perf_ctr = SNBEP_PCI_PMON_CTR0, .event_ctl = SNBEP_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNBEP_PCI_PMON_BOX_CTL, .ops = &ivbep_uncore_pci_ops, .format_group = &skx_uncore_format_group, }; enum { SKX_PCI_UNCORE_IMC, SKX_PCI_UNCORE_M2M, SKX_PCI_UNCORE_UPI, SKX_PCI_UNCORE_M2PCIE, SKX_PCI_UNCORE_M3UPI, }; static struct intel_uncore_type *skx_pci_uncores[] = { [SKX_PCI_UNCORE_IMC] = &skx_uncore_imc, [SKX_PCI_UNCORE_M2M] = &skx_uncore_m2m, [SKX_PCI_UNCORE_UPI] = &skx_uncore_upi, [SKX_PCI_UNCORE_M2PCIE] = &skx_uncore_m2pcie, [SKX_PCI_UNCORE_M3UPI] = &skx_uncore_m3upi, NULL, }; static const struct pci_device_id skx_uncore_pci_ids[] = { { /* MC0 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2042), .driver_data = UNCORE_PCI_DEV_FULL_DATA(10, 2, SKX_PCI_UNCORE_IMC, 0), }, { /* MC0 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2046), .driver_data = UNCORE_PCI_DEV_FULL_DATA(10, 6, SKX_PCI_UNCORE_IMC, 1), }, { /* MC0 Channel 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x204a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(11, 2, SKX_PCI_UNCORE_IMC, 2), }, { /* MC1 Channel 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2042), .driver_data = UNCORE_PCI_DEV_FULL_DATA(12, 2, SKX_PCI_UNCORE_IMC, 3), }, { /* MC1 Channel 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2046), .driver_data = UNCORE_PCI_DEV_FULL_DATA(12, 6, SKX_PCI_UNCORE_IMC, 4), }, { /* MC1 Channel 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x204a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(13, 2, SKX_PCI_UNCORE_IMC, 5), }, { /* M2M0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2066), .driver_data = UNCORE_PCI_DEV_FULL_DATA(8, 0, SKX_PCI_UNCORE_M2M, 0), }, { /* M2M1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2066), .driver_data = UNCORE_PCI_DEV_FULL_DATA(9, 0, SKX_PCI_UNCORE_M2M, 1), }, { /* UPI0 Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2058), .driver_data = UNCORE_PCI_DEV_FULL_DATA(14, 0, SKX_PCI_UNCORE_UPI, 0), }, { /* UPI0 Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2058), .driver_data = UNCORE_PCI_DEV_FULL_DATA(15, 0, SKX_PCI_UNCORE_UPI, 1), }, { /* UPI1 Link 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2058), .driver_data = UNCORE_PCI_DEV_FULL_DATA(16, 0, SKX_PCI_UNCORE_UPI, 2), }, { /* M2PCIe 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2088), .driver_data = UNCORE_PCI_DEV_FULL_DATA(21, 1, SKX_PCI_UNCORE_M2PCIE, 0), }, { /* M2PCIe 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2088), .driver_data = UNCORE_PCI_DEV_FULL_DATA(22, 1, SKX_PCI_UNCORE_M2PCIE, 1), }, { /* M2PCIe 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2088), .driver_data = UNCORE_PCI_DEV_FULL_DATA(23, 1, SKX_PCI_UNCORE_M2PCIE, 2), }, { /* M2PCIe 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2088), .driver_data = UNCORE_PCI_DEV_FULL_DATA(21, 5, SKX_PCI_UNCORE_M2PCIE, 3), }, { /* M3UPI0 Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x204D), .driver_data = UNCORE_PCI_DEV_FULL_DATA(18, 1, SKX_PCI_UNCORE_M3UPI, 0), }, { /* M3UPI0 Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x204E), .driver_data = UNCORE_PCI_DEV_FULL_DATA(18, 2, SKX_PCI_UNCORE_M3UPI, 1), }, { /* M3UPI1 Link 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x204D), .driver_data = UNCORE_PCI_DEV_FULL_DATA(18, 5, SKX_PCI_UNCORE_M3UPI, 2), }, { /* end: all zeroes */ } }; static struct pci_driver skx_uncore_pci_driver = { .name = "skx_uncore", .id_table = skx_uncore_pci_ids, }; int skx_uncore_pci_init(void) { /* need to double check pci address */ int ret = snbep_pci2phy_map_init(0x2014, SKX_CPUNODEID, SKX_GIDNIDMAP, false); if (ret) return ret; uncore_pci_uncores = skx_pci_uncores; uncore_pci_driver = &skx_uncore_pci_driver; return 0; } /* end of SKX uncore support */ /* SNR uncore support */ static struct intel_uncore_type snr_uncore_ubox = { .name = "ubox", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .perf_ctr = SNR_U_MSR_PMON_CTR0, .event_ctl = SNR_U_MSR_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .fixed_ctr = SNR_U_MSR_PMON_UCLK_FIXED_CTR, .fixed_ctl = SNR_U_MSR_PMON_UCLK_FIXED_CTL, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_format_group, }; static struct attribute *snr_uncore_cha_formats_attr[] = { &format_attr_event.attr, &format_attr_umask_ext2.attr, &format_attr_edge.attr, &format_attr_tid_en.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_filter_tid5.attr, NULL, }; static const struct attribute_group snr_uncore_chabox_format_group = { .name = "format", .attrs = snr_uncore_cha_formats_attr, }; static int snr_cha_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; reg1->reg = SNR_C0_MSR_PMON_BOX_FILTER0 + box->pmu->type->msr_offset * box->pmu->pmu_idx; reg1->config = event->attr.config1 & SKX_CHA_MSR_PMON_BOX_FILTER_TID; reg1->idx = 0; return 0; } static void snr_cha_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; if (reg1->idx != EXTRA_REG_NONE) wrmsrl(reg1->reg, reg1->config); wrmsrl(hwc->config_base, hwc->config | SNBEP_PMON_CTL_EN); } static struct intel_uncore_ops snr_uncore_chabox_ops = { .init_box = ivbep_uncore_msr_init_box, .disable_box = snbep_uncore_msr_disable_box, .enable_box = snbep_uncore_msr_enable_box, .disable_event = snbep_uncore_msr_disable_event, .enable_event = snr_cha_enable_event, .read_counter = uncore_msr_read_counter, .hw_config = snr_cha_hw_config, }; static struct intel_uncore_type snr_uncore_chabox = { .name = "cha", .num_counters = 4, .num_boxes = 6, .perf_ctr_bits = 48, .event_ctl = SNR_CHA_MSR_PMON_CTL0, .perf_ctr = SNR_CHA_MSR_PMON_CTR0, .box_ctl = SNR_CHA_MSR_PMON_BOX_CTL, .msr_offset = HSWEP_CBO_MSR_OFFSET, .event_mask = HSWEP_S_MSR_PMON_RAW_EVENT_MASK, .event_mask_ext = SNR_CHA_RAW_EVENT_MASK_EXT, .ops = &snr_uncore_chabox_ops, .format_group = &snr_uncore_chabox_format_group, }; static struct attribute *snr_uncore_iio_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh9.attr, &format_attr_ch_mask2.attr, &format_attr_fc_mask2.attr, NULL, }; static const struct attribute_group snr_uncore_iio_format_group = { .name = "format", .attrs = snr_uncore_iio_formats_attr, }; static umode_t snr_iio_mapping_visible(struct kobject *kobj, struct attribute *attr, int die) { /* Root bus 0x00 is valid only for pmu_idx = 1. */ return pmu_iio_mapping_visible(kobj, attr, die, 1); } static struct attribute_group snr_iio_mapping_group = { .is_visible = snr_iio_mapping_visible, }; static const struct attribute_group *snr_iio_attr_update[] = { &snr_iio_mapping_group, NULL, }; static int sad_cfg_iio_topology(struct intel_uncore_type *type, u8 *sad_pmon_mapping) { u32 sad_cfg; int die, stack_id, ret = -EPERM; struct pci_dev *dev = NULL; while ((dev = pci_get_device(PCI_VENDOR_ID_INTEL, SNR_ICX_MESH2IIO_MMAP_DID, dev))) { ret = pci_read_config_dword(dev, SNR_ICX_SAD_CONTROL_CFG, &sad_cfg); if (ret) { ret = pcibios_err_to_errno(ret); break; } die = uncore_pcibus_to_dieid(dev->bus); stack_id = SAD_CONTROL_STACK_ID(sad_cfg); if (die < 0 || stack_id >= type->num_boxes) { ret = -EPERM; break; } /* Convert stack id from SAD_CONTROL to PMON notation. */ stack_id = sad_pmon_mapping[stack_id]; type->topology[die][stack_id].iio->segment = pci_domain_nr(dev->bus); type->topology[die][stack_id].pmu_idx = stack_id; type->topology[die][stack_id].iio->pci_bus_no = dev->bus->number; } pci_dev_put(dev); return ret; } /* * SNR has a static mapping of stack IDs from SAD_CONTROL_CFG notation to PMON */ enum { SNR_QAT_PMON_ID, SNR_CBDMA_DMI_PMON_ID, SNR_NIS_PMON_ID, SNR_DLB_PMON_ID, SNR_PCIE_GEN3_PMON_ID }; static u8 snr_sad_pmon_mapping[] = { SNR_CBDMA_DMI_PMON_ID, SNR_PCIE_GEN3_PMON_ID, SNR_DLB_PMON_ID, SNR_NIS_PMON_ID, SNR_QAT_PMON_ID }; static int snr_iio_get_topology(struct intel_uncore_type *type) { return sad_cfg_iio_topology(type, snr_sad_pmon_mapping); } static void snr_iio_set_mapping(struct intel_uncore_type *type) { pmu_iio_set_mapping(type, &snr_iio_mapping_group); } static void snr_iio_cleanup_mapping(struct intel_uncore_type *type) { pmu_cleanup_mapping(type, &snr_iio_mapping_group); } static struct event_constraint snr_uncore_iio_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x83, 0x3), UNCORE_EVENT_CONSTRAINT(0xc0, 0xc), UNCORE_EVENT_CONSTRAINT(0xd5, 0xc), EVENT_CONSTRAINT_END }; static struct intel_uncore_type snr_uncore_iio = { .name = "iio", .num_counters = 4, .num_boxes = 5, .perf_ctr_bits = 48, .event_ctl = SNR_IIO_MSR_PMON_CTL0, .perf_ctr = SNR_IIO_MSR_PMON_CTR0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = SNR_IIO_PMON_RAW_EVENT_MASK_EXT, .box_ctl = SNR_IIO_MSR_PMON_BOX_CTL, .msr_offset = SNR_IIO_MSR_OFFSET, .constraints = snr_uncore_iio_constraints, .ops = &ivbep_uncore_msr_ops, .format_group = &snr_uncore_iio_format_group, .attr_update = snr_iio_attr_update, .get_topology = snr_iio_get_topology, .set_mapping = snr_iio_set_mapping, .cleanup_mapping = snr_iio_cleanup_mapping, }; static struct intel_uncore_type snr_uncore_irp = { .name = "irp", .num_counters = 2, .num_boxes = 5, .perf_ctr_bits = 48, .event_ctl = SNR_IRP0_MSR_PMON_CTL0, .perf_ctr = SNR_IRP0_MSR_PMON_CTR0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNR_IRP0_MSR_PMON_BOX_CTL, .msr_offset = SNR_IRP_MSR_OFFSET, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_format_group, }; static struct intel_uncore_type snr_uncore_m2pcie = { .name = "m2pcie", .num_counters = 4, .num_boxes = 5, .perf_ctr_bits = 48, .event_ctl = SNR_M2PCIE_MSR_PMON_CTL0, .perf_ctr = SNR_M2PCIE_MSR_PMON_CTR0, .box_ctl = SNR_M2PCIE_MSR_PMON_BOX_CTL, .msr_offset = SNR_M2PCIE_MSR_OFFSET, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_format_group, }; static int snr_pcu_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; int ev_sel = hwc->config & SNBEP_PMON_CTL_EV_SEL_MASK; if (ev_sel >= 0xb && ev_sel <= 0xe) { reg1->reg = SNR_PCU_MSR_PMON_BOX_FILTER; reg1->idx = ev_sel - 0xb; reg1->config = event->attr.config1 & (0xff << reg1->idx); } return 0; } static struct intel_uncore_ops snr_uncore_pcu_ops = { IVBEP_UNCORE_MSR_OPS_COMMON_INIT(), .hw_config = snr_pcu_hw_config, .get_constraint = snbep_pcu_get_constraint, .put_constraint = snbep_pcu_put_constraint, }; static struct intel_uncore_type snr_uncore_pcu = { .name = "pcu", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = SNR_PCU_MSR_PMON_CTR0, .event_ctl = SNR_PCU_MSR_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNR_PCU_MSR_PMON_BOX_CTL, .num_shared_regs = 1, .ops = &snr_uncore_pcu_ops, .format_group = &skx_uncore_pcu_format_group, }; enum perf_uncore_snr_iio_freerunning_type_id { SNR_IIO_MSR_IOCLK, SNR_IIO_MSR_BW_IN, SNR_IIO_FREERUNNING_TYPE_MAX, }; static struct freerunning_counters snr_iio_freerunning[] = { [SNR_IIO_MSR_IOCLK] = { 0x1eac, 0x1, 0x10, 1, 48 }, [SNR_IIO_MSR_BW_IN] = { 0x1f00, 0x1, 0x10, 8, 48 }, }; static struct uncore_event_desc snr_uncore_iio_freerunning_events[] = { /* Free-Running IIO CLOCKS Counter */ INTEL_UNCORE_EVENT_DESC(ioclk, "event=0xff,umask=0x10"), /* Free-Running IIO BANDWIDTH IN Counters */ INTEL_UNCORE_EVENT_DESC(bw_in_port0, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port1, "event=0xff,umask=0x21"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port2, "event=0xff,umask=0x22"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port3, "event=0xff,umask=0x23"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port4, "event=0xff,umask=0x24"), INTEL_UNCORE_EVENT_DESC(bw_in_port4.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port4.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port5, "event=0xff,umask=0x25"), INTEL_UNCORE_EVENT_DESC(bw_in_port5.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port5.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port6, "event=0xff,umask=0x26"), INTEL_UNCORE_EVENT_DESC(bw_in_port6.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port6.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port7, "event=0xff,umask=0x27"), INTEL_UNCORE_EVENT_DESC(bw_in_port7.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port7.unit, "MiB"), { /* end: all zeroes */ }, }; static struct intel_uncore_type snr_uncore_iio_free_running = { .name = "iio_free_running", .num_counters = 9, .num_boxes = 5, .num_freerunning_types = SNR_IIO_FREERUNNING_TYPE_MAX, .freerunning = snr_iio_freerunning, .ops = &skx_uncore_iio_freerunning_ops, .event_descs = snr_uncore_iio_freerunning_events, .format_group = &skx_uncore_iio_freerunning_format_group, }; static struct intel_uncore_type *snr_msr_uncores[] = { &snr_uncore_ubox, &snr_uncore_chabox, &snr_uncore_iio, &snr_uncore_irp, &snr_uncore_m2pcie, &snr_uncore_pcu, &snr_uncore_iio_free_running, NULL, }; void snr_uncore_cpu_init(void) { uncore_msr_uncores = snr_msr_uncores; } static void snr_m2m_uncore_pci_init_box(struct intel_uncore_box *box) { struct pci_dev *pdev = box->pci_dev; int box_ctl = uncore_pci_box_ctl(box); __set_bit(UNCORE_BOX_FLAG_CTL_OFFS8, &box->flags); pci_write_config_dword(pdev, box_ctl, IVBEP_PMON_BOX_CTL_INT); } static struct intel_uncore_ops snr_m2m_uncore_pci_ops = { .init_box = snr_m2m_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = snbep_uncore_pci_disable_event, .enable_event = snbep_uncore_pci_enable_event, .read_counter = snbep_uncore_pci_read_counter, }; static struct attribute *snr_m2m_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask_ext3.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group snr_m2m_uncore_format_group = { .name = "format", .attrs = snr_m2m_uncore_formats_attr, }; static struct intel_uncore_type snr_uncore_m2m = { .name = "m2m", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = SNR_M2M_PCI_PMON_CTR0, .event_ctl = SNR_M2M_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = SNR_M2M_PCI_PMON_UMASK_EXT, .box_ctl = SNR_M2M_PCI_PMON_BOX_CTL, .ops = &snr_m2m_uncore_pci_ops, .format_group = &snr_m2m_uncore_format_group, }; static void snr_uncore_pci_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, hwc->config_base, (u32)(hwc->config | SNBEP_PMON_CTL_EN)); pci_write_config_dword(pdev, hwc->config_base + 4, (u32)(hwc->config >> 32)); } static struct intel_uncore_ops snr_pcie3_uncore_pci_ops = { .init_box = snr_m2m_uncore_pci_init_box, .disable_box = snbep_uncore_pci_disable_box, .enable_box = snbep_uncore_pci_enable_box, .disable_event = snbep_uncore_pci_disable_event, .enable_event = snr_uncore_pci_enable_event, .read_counter = snbep_uncore_pci_read_counter, }; static struct intel_uncore_type snr_uncore_pcie3 = { .name = "pcie3", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .perf_ctr = SNR_PCIE3_PCI_PMON_CTR0, .event_ctl = SNR_PCIE3_PCI_PMON_CTL0, .event_mask = SKX_IIO_PMON_RAW_EVENT_MASK, .event_mask_ext = SKX_IIO_PMON_RAW_EVENT_MASK_EXT, .box_ctl = SNR_PCIE3_PCI_PMON_BOX_CTL, .ops = &snr_pcie3_uncore_pci_ops, .format_group = &skx_uncore_iio_format_group, }; enum { SNR_PCI_UNCORE_M2M, SNR_PCI_UNCORE_PCIE3, }; static struct intel_uncore_type *snr_pci_uncores[] = { [SNR_PCI_UNCORE_M2M] = &snr_uncore_m2m, [SNR_PCI_UNCORE_PCIE3] = &snr_uncore_pcie3, NULL, }; static const struct pci_device_id snr_uncore_pci_ids[] = { { /* M2M */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x344a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(12, 0, SNR_PCI_UNCORE_M2M, 0), }, { /* end: all zeroes */ } }; static struct pci_driver snr_uncore_pci_driver = { .name = "snr_uncore", .id_table = snr_uncore_pci_ids, }; static const struct pci_device_id snr_uncore_pci_sub_ids[] = { { /* PCIe3 RP */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x334a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(4, 0, SNR_PCI_UNCORE_PCIE3, 0), }, { /* end: all zeroes */ } }; static struct pci_driver snr_uncore_pci_sub_driver = { .name = "snr_uncore_sub", .id_table = snr_uncore_pci_sub_ids, }; int snr_uncore_pci_init(void) { /* SNR UBOX DID */ int ret = snbep_pci2phy_map_init(0x3460, SKX_CPUNODEID, SKX_GIDNIDMAP, true); if (ret) return ret; uncore_pci_uncores = snr_pci_uncores; uncore_pci_driver = &snr_uncore_pci_driver; uncore_pci_sub_driver = &snr_uncore_pci_sub_driver; return 0; } #define SNR_MC_DEVICE_ID 0x3451 static struct pci_dev *snr_uncore_get_mc_dev(unsigned int device, int id) { struct pci_dev *mc_dev = NULL; int pkg; while (1) { mc_dev = pci_get_device(PCI_VENDOR_ID_INTEL, device, mc_dev); if (!mc_dev) break; pkg = uncore_pcibus_to_dieid(mc_dev->bus); if (pkg == id) break; } return mc_dev; } static int snr_uncore_mmio_map(struct intel_uncore_box *box, unsigned int box_ctl, int mem_offset, unsigned int device) { struct pci_dev *pdev = snr_uncore_get_mc_dev(device, box->dieid); struct intel_uncore_type *type = box->pmu->type; resource_size_t addr; u32 pci_dword; if (!pdev) return -ENODEV; pci_read_config_dword(pdev, SNR_IMC_MMIO_BASE_OFFSET, &pci_dword); addr = ((resource_size_t)pci_dword & SNR_IMC_MMIO_BASE_MASK) << 23; pci_read_config_dword(pdev, mem_offset, &pci_dword); addr |= (pci_dword & SNR_IMC_MMIO_MEM0_MASK) << 12; addr += box_ctl; pci_dev_put(pdev); box->io_addr = ioremap(addr, type->mmio_map_size); if (!box->io_addr) { pr_warn("perf uncore: Failed to ioremap for %s.\n", type->name); return -EINVAL; } return 0; } static void __snr_uncore_mmio_init_box(struct intel_uncore_box *box, unsigned int box_ctl, int mem_offset, unsigned int device) { if (!snr_uncore_mmio_map(box, box_ctl, mem_offset, device)) writel(IVBEP_PMON_BOX_CTL_INT, box->io_addr); } static void snr_uncore_mmio_init_box(struct intel_uncore_box *box) { __snr_uncore_mmio_init_box(box, uncore_mmio_box_ctl(box), SNR_IMC_MMIO_MEM0_OFFSET, SNR_MC_DEVICE_ID); } static void snr_uncore_mmio_disable_box(struct intel_uncore_box *box) { u32 config; if (!box->io_addr) return; config = readl(box->io_addr); config |= SNBEP_PMON_BOX_CTL_FRZ; writel(config, box->io_addr); } static void snr_uncore_mmio_enable_box(struct intel_uncore_box *box) { u32 config; if (!box->io_addr) return; config = readl(box->io_addr); config &= ~SNBEP_PMON_BOX_CTL_FRZ; writel(config, box->io_addr); } static void snr_uncore_mmio_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (!box->io_addr) return; if (!uncore_mmio_is_valid_offset(box, hwc->config_base)) return; writel(hwc->config | SNBEP_PMON_CTL_EN, box->io_addr + hwc->config_base); } static void snr_uncore_mmio_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (!box->io_addr) return; if (!uncore_mmio_is_valid_offset(box, hwc->config_base)) return; writel(hwc->config, box->io_addr + hwc->config_base); } static struct intel_uncore_ops snr_uncore_mmio_ops = { .init_box = snr_uncore_mmio_init_box, .exit_box = uncore_mmio_exit_box, .disable_box = snr_uncore_mmio_disable_box, .enable_box = snr_uncore_mmio_enable_box, .disable_event = snr_uncore_mmio_disable_event, .enable_event = snr_uncore_mmio_enable_event, .read_counter = uncore_mmio_read_counter, }; static struct uncore_event_desc snr_uncore_imc_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0x00,umask=0x00"), INTEL_UNCORE_EVENT_DESC(cas_count_read, "event=0x04,umask=0x0f"), INTEL_UNCORE_EVENT_DESC(cas_count_read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(cas_count_write, "event=0x04,umask=0x30"), INTEL_UNCORE_EVENT_DESC(cas_count_write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_write.unit, "MiB"), { /* end: all zeroes */ }, }; static struct intel_uncore_type snr_uncore_imc = { .name = "imc", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .fixed_ctr = SNR_IMC_MMIO_PMON_FIXED_CTR, .fixed_ctl = SNR_IMC_MMIO_PMON_FIXED_CTL, .event_descs = snr_uncore_imc_events, .perf_ctr = SNR_IMC_MMIO_PMON_CTR0, .event_ctl = SNR_IMC_MMIO_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNR_IMC_MMIO_PMON_BOX_CTL, .mmio_offset = SNR_IMC_MMIO_OFFSET, .mmio_map_size = SNR_IMC_MMIO_SIZE, .ops = &snr_uncore_mmio_ops, .format_group = &skx_uncore_format_group, }; enum perf_uncore_snr_imc_freerunning_type_id { SNR_IMC_DCLK, SNR_IMC_DDR, SNR_IMC_FREERUNNING_TYPE_MAX, }; static struct freerunning_counters snr_imc_freerunning[] = { [SNR_IMC_DCLK] = { 0x22b0, 0x0, 0, 1, 48 }, [SNR_IMC_DDR] = { 0x2290, 0x8, 0, 2, 48 }, }; static struct uncore_event_desc snr_uncore_imc_freerunning_events[] = { INTEL_UNCORE_EVENT_DESC(dclk, "event=0xff,umask=0x10"), INTEL_UNCORE_EVENT_DESC(read, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(write, "event=0xff,umask=0x21"), INTEL_UNCORE_EVENT_DESC(write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(write.unit, "MiB"), { /* end: all zeroes */ }, }; static struct intel_uncore_ops snr_uncore_imc_freerunning_ops = { .init_box = snr_uncore_mmio_init_box, .exit_box = uncore_mmio_exit_box, .read_counter = uncore_mmio_read_counter, .hw_config = uncore_freerunning_hw_config, }; static struct intel_uncore_type snr_uncore_imc_free_running = { .name = "imc_free_running", .num_counters = 3, .num_boxes = 1, .num_freerunning_types = SNR_IMC_FREERUNNING_TYPE_MAX, .mmio_map_size = SNR_IMC_MMIO_SIZE, .freerunning = snr_imc_freerunning, .ops = &snr_uncore_imc_freerunning_ops, .event_descs = snr_uncore_imc_freerunning_events, .format_group = &skx_uncore_iio_freerunning_format_group, }; static struct intel_uncore_type *snr_mmio_uncores[] = { &snr_uncore_imc, &snr_uncore_imc_free_running, NULL, }; void snr_uncore_mmio_init(void) { uncore_mmio_uncores = snr_mmio_uncores; } /* end of SNR uncore support */ /* ICX uncore support */ static unsigned icx_cha_msr_offsets[] = { 0x2a0, 0x2ae, 0x2bc, 0x2ca, 0x2d8, 0x2e6, 0x2f4, 0x302, 0x310, 0x31e, 0x32c, 0x33a, 0x348, 0x356, 0x364, 0x372, 0x380, 0x38e, 0x3aa, 0x3b8, 0x3c6, 0x3d4, 0x3e2, 0x3f0, 0x3fe, 0x40c, 0x41a, 0x428, 0x436, 0x444, 0x452, 0x460, 0x46e, 0x47c, 0x0, 0xe, 0x1c, 0x2a, 0x38, 0x46, }; static int icx_cha_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; bool tie_en = !!(event->hw.config & SNBEP_CBO_PMON_CTL_TID_EN); if (tie_en) { reg1->reg = ICX_C34_MSR_PMON_BOX_FILTER0 + icx_cha_msr_offsets[box->pmu->pmu_idx]; reg1->config = event->attr.config1 & SKX_CHA_MSR_PMON_BOX_FILTER_TID; reg1->idx = 0; } return 0; } static struct intel_uncore_ops icx_uncore_chabox_ops = { .init_box = ivbep_uncore_msr_init_box, .disable_box = snbep_uncore_msr_disable_box, .enable_box = snbep_uncore_msr_enable_box, .disable_event = snbep_uncore_msr_disable_event, .enable_event = snr_cha_enable_event, .read_counter = uncore_msr_read_counter, .hw_config = icx_cha_hw_config, }; static struct intel_uncore_type icx_uncore_chabox = { .name = "cha", .num_counters = 4, .perf_ctr_bits = 48, .event_ctl = ICX_C34_MSR_PMON_CTL0, .perf_ctr = ICX_C34_MSR_PMON_CTR0, .box_ctl = ICX_C34_MSR_PMON_BOX_CTL, .msr_offsets = icx_cha_msr_offsets, .event_mask = HSWEP_S_MSR_PMON_RAW_EVENT_MASK, .event_mask_ext = SNR_CHA_RAW_EVENT_MASK_EXT, .constraints = skx_uncore_chabox_constraints, .ops = &icx_uncore_chabox_ops, .format_group = &snr_uncore_chabox_format_group, }; static unsigned icx_msr_offsets[] = { 0x0, 0x20, 0x40, 0x90, 0xb0, 0xd0, }; static struct event_constraint icx_uncore_iio_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x02, 0x3), UNCORE_EVENT_CONSTRAINT(0x03, 0x3), UNCORE_EVENT_CONSTRAINT(0x83, 0x3), UNCORE_EVENT_CONSTRAINT(0x88, 0xc), UNCORE_EVENT_CONSTRAINT(0xc0, 0xc), UNCORE_EVENT_CONSTRAINT(0xc5, 0xc), UNCORE_EVENT_CONSTRAINT(0xd5, 0xc), EVENT_CONSTRAINT_END }; static umode_t icx_iio_mapping_visible(struct kobject *kobj, struct attribute *attr, int die) { /* Root bus 0x00 is valid only for pmu_idx = 5. */ return pmu_iio_mapping_visible(kobj, attr, die, 5); } static struct attribute_group icx_iio_mapping_group = { .is_visible = icx_iio_mapping_visible, }; static const struct attribute_group *icx_iio_attr_update[] = { &icx_iio_mapping_group, NULL, }; /* * ICX has a static mapping of stack IDs from SAD_CONTROL_CFG notation to PMON */ enum { ICX_PCIE1_PMON_ID, ICX_PCIE2_PMON_ID, ICX_PCIE3_PMON_ID, ICX_PCIE4_PMON_ID, ICX_PCIE5_PMON_ID, ICX_CBDMA_DMI_PMON_ID }; static u8 icx_sad_pmon_mapping[] = { ICX_CBDMA_DMI_PMON_ID, ICX_PCIE1_PMON_ID, ICX_PCIE2_PMON_ID, ICX_PCIE3_PMON_ID, ICX_PCIE4_PMON_ID, ICX_PCIE5_PMON_ID, }; static int icx_iio_get_topology(struct intel_uncore_type *type) { return sad_cfg_iio_topology(type, icx_sad_pmon_mapping); } static void icx_iio_set_mapping(struct intel_uncore_type *type) { /* Detect ICX-D system. This case is not supported */ if (boot_cpu_data.x86_model == INTEL_FAM6_ICELAKE_D) { pmu_clear_mapping_attr(type->attr_update, &icx_iio_mapping_group); return; } pmu_iio_set_mapping(type, &icx_iio_mapping_group); } static void icx_iio_cleanup_mapping(struct intel_uncore_type *type) { pmu_cleanup_mapping(type, &icx_iio_mapping_group); } static struct intel_uncore_type icx_uncore_iio = { .name = "iio", .num_counters = 4, .num_boxes = 6, .perf_ctr_bits = 48, .event_ctl = ICX_IIO_MSR_PMON_CTL0, .perf_ctr = ICX_IIO_MSR_PMON_CTR0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = SNR_IIO_PMON_RAW_EVENT_MASK_EXT, .box_ctl = ICX_IIO_MSR_PMON_BOX_CTL, .msr_offsets = icx_msr_offsets, .constraints = icx_uncore_iio_constraints, .ops = &skx_uncore_iio_ops, .format_group = &snr_uncore_iio_format_group, .attr_update = icx_iio_attr_update, .get_topology = icx_iio_get_topology, .set_mapping = icx_iio_set_mapping, .cleanup_mapping = icx_iio_cleanup_mapping, }; static struct intel_uncore_type icx_uncore_irp = { .name = "irp", .num_counters = 2, .num_boxes = 6, .perf_ctr_bits = 48, .event_ctl = ICX_IRP0_MSR_PMON_CTL0, .perf_ctr = ICX_IRP0_MSR_PMON_CTR0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = ICX_IRP0_MSR_PMON_BOX_CTL, .msr_offsets = icx_msr_offsets, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_format_group, }; static struct event_constraint icx_uncore_m2pcie_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x14, 0x3), UNCORE_EVENT_CONSTRAINT(0x23, 0x3), UNCORE_EVENT_CONSTRAINT(0x2d, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type icx_uncore_m2pcie = { .name = "m2pcie", .num_counters = 4, .num_boxes = 6, .perf_ctr_bits = 48, .event_ctl = ICX_M2PCIE_MSR_PMON_CTL0, .perf_ctr = ICX_M2PCIE_MSR_PMON_CTR0, .box_ctl = ICX_M2PCIE_MSR_PMON_BOX_CTL, .msr_offsets = icx_msr_offsets, .constraints = icx_uncore_m2pcie_constraints, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .ops = &ivbep_uncore_msr_ops, .format_group = &ivbep_uncore_format_group, }; enum perf_uncore_icx_iio_freerunning_type_id { ICX_IIO_MSR_IOCLK, ICX_IIO_MSR_BW_IN, ICX_IIO_FREERUNNING_TYPE_MAX, }; static unsigned icx_iio_clk_freerunning_box_offsets[] = { 0x0, 0x20, 0x40, 0x90, 0xb0, 0xd0, }; static unsigned icx_iio_bw_freerunning_box_offsets[] = { 0x0, 0x10, 0x20, 0x90, 0xa0, 0xb0, }; static struct freerunning_counters icx_iio_freerunning[] = { [ICX_IIO_MSR_IOCLK] = { 0xa55, 0x1, 0x20, 1, 48, icx_iio_clk_freerunning_box_offsets }, [ICX_IIO_MSR_BW_IN] = { 0xaa0, 0x1, 0x10, 8, 48, icx_iio_bw_freerunning_box_offsets }, }; static struct uncore_event_desc icx_uncore_iio_freerunning_events[] = { /* Free-Running IIO CLOCKS Counter */ INTEL_UNCORE_EVENT_DESC(ioclk, "event=0xff,umask=0x10"), /* Free-Running IIO BANDWIDTH IN Counters */ INTEL_UNCORE_EVENT_DESC(bw_in_port0, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port1, "event=0xff,umask=0x21"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port2, "event=0xff,umask=0x22"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port3, "event=0xff,umask=0x23"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port4, "event=0xff,umask=0x24"), INTEL_UNCORE_EVENT_DESC(bw_in_port4.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port4.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port5, "event=0xff,umask=0x25"), INTEL_UNCORE_EVENT_DESC(bw_in_port5.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port5.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port6, "event=0xff,umask=0x26"), INTEL_UNCORE_EVENT_DESC(bw_in_port6.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port6.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port7, "event=0xff,umask=0x27"), INTEL_UNCORE_EVENT_DESC(bw_in_port7.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port7.unit, "MiB"), { /* end: all zeroes */ }, }; static struct intel_uncore_type icx_uncore_iio_free_running = { .name = "iio_free_running", .num_counters = 9, .num_boxes = 6, .num_freerunning_types = ICX_IIO_FREERUNNING_TYPE_MAX, .freerunning = icx_iio_freerunning, .ops = &skx_uncore_iio_freerunning_ops, .event_descs = icx_uncore_iio_freerunning_events, .format_group = &skx_uncore_iio_freerunning_format_group, }; static struct intel_uncore_type *icx_msr_uncores[] = { &skx_uncore_ubox, &icx_uncore_chabox, &icx_uncore_iio, &icx_uncore_irp, &icx_uncore_m2pcie, &skx_uncore_pcu, &icx_uncore_iio_free_running, NULL, }; /* * To determine the number of CHAs, it should read CAPID6(Low) and CAPID7 (High) * registers which located at Device 30, Function 3 */ #define ICX_CAPID6 0x9c #define ICX_CAPID7 0xa0 static u64 icx_count_chabox(void) { struct pci_dev *dev = NULL; u64 caps = 0; dev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x345b, dev); if (!dev) goto out; pci_read_config_dword(dev, ICX_CAPID6, (u32 *)&caps); pci_read_config_dword(dev, ICX_CAPID7, (u32 *)&caps + 1); out: pci_dev_put(dev); return hweight64(caps); } void icx_uncore_cpu_init(void) { u64 num_boxes = icx_count_chabox(); if (WARN_ON(num_boxes > ARRAY_SIZE(icx_cha_msr_offsets))) return; icx_uncore_chabox.num_boxes = num_boxes; uncore_msr_uncores = icx_msr_uncores; } static struct intel_uncore_type icx_uncore_m2m = { .name = "m2m", .num_counters = 4, .num_boxes = 4, .perf_ctr_bits = 48, .perf_ctr = SNR_M2M_PCI_PMON_CTR0, .event_ctl = SNR_M2M_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = SNR_M2M_PCI_PMON_UMASK_EXT, .box_ctl = SNR_M2M_PCI_PMON_BOX_CTL, .ops = &snr_m2m_uncore_pci_ops, .format_group = &snr_m2m_uncore_format_group, }; static struct attribute *icx_upi_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask_ext4.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group icx_upi_uncore_format_group = { .name = "format", .attrs = icx_upi_uncore_formats_attr, }; #define ICX_UPI_REGS_ADDR_DEVICE_LINK0 0x02 #define ICX_UPI_REGS_ADDR_FUNCTION 0x01 static int discover_upi_topology(struct intel_uncore_type *type, int ubox_did, int dev_link0) { struct pci_dev *ubox = NULL; struct pci_dev *dev = NULL; u32 nid, gid; int i, idx, ret = -EPERM; struct intel_uncore_topology *upi; unsigned int devfn; /* GIDNIDMAP method supports machines which have less than 8 sockets. */ if (uncore_max_dies() > 8) goto err; while ((ubox = pci_get_device(PCI_VENDOR_ID_INTEL, ubox_did, ubox))) { ret = upi_nodeid_groupid(ubox, SKX_CPUNODEID, SKX_GIDNIDMAP, &nid, &gid); if (ret) { ret = pcibios_err_to_errno(ret); break; } for (i = 0; i < 8; i++) { if (nid != GIDNIDMAP(gid, i)) continue; for (idx = 0; idx < type->num_boxes; idx++) { upi = &type->topology[nid][idx]; devfn = PCI_DEVFN(dev_link0 + idx, ICX_UPI_REGS_ADDR_FUNCTION); dev = pci_get_domain_bus_and_slot(pci_domain_nr(ubox->bus), ubox->bus->number, devfn); if (dev) { ret = upi_fill_topology(dev, upi, idx); if (ret) goto err; } } } } err: pci_dev_put(ubox); pci_dev_put(dev); return ret; } static int icx_upi_get_topology(struct intel_uncore_type *type) { return discover_upi_topology(type, ICX_UBOX_DID, ICX_UPI_REGS_ADDR_DEVICE_LINK0); } static struct attribute_group icx_upi_mapping_group = { .is_visible = skx_upi_mapping_visible, }; static const struct attribute_group *icx_upi_attr_update[] = { &icx_upi_mapping_group, NULL }; static void icx_upi_set_mapping(struct intel_uncore_type *type) { pmu_upi_set_mapping(type, &icx_upi_mapping_group); } static void icx_upi_cleanup_mapping(struct intel_uncore_type *type) { pmu_cleanup_mapping(type, &icx_upi_mapping_group); } static struct intel_uncore_type icx_uncore_upi = { .name = "upi", .num_counters = 4, .num_boxes = 3, .perf_ctr_bits = 48, .perf_ctr = ICX_UPI_PCI_PMON_CTR0, .event_ctl = ICX_UPI_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = ICX_UPI_CTL_UMASK_EXT, .box_ctl = ICX_UPI_PCI_PMON_BOX_CTL, .ops = &skx_upi_uncore_pci_ops, .format_group = &icx_upi_uncore_format_group, .attr_update = icx_upi_attr_update, .get_topology = icx_upi_get_topology, .set_mapping = icx_upi_set_mapping, .cleanup_mapping = icx_upi_cleanup_mapping, }; static struct event_constraint icx_uncore_m3upi_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x1c, 0x1), UNCORE_EVENT_CONSTRAINT(0x1d, 0x1), UNCORE_EVENT_CONSTRAINT(0x1e, 0x1), UNCORE_EVENT_CONSTRAINT(0x1f, 0x1), UNCORE_EVENT_CONSTRAINT(0x40, 0x7), UNCORE_EVENT_CONSTRAINT(0x4e, 0x7), UNCORE_EVENT_CONSTRAINT(0x4f, 0x7), UNCORE_EVENT_CONSTRAINT(0x50, 0x7), EVENT_CONSTRAINT_END }; static struct intel_uncore_type icx_uncore_m3upi = { .name = "m3upi", .num_counters = 4, .num_boxes = 3, .perf_ctr_bits = 48, .perf_ctr = ICX_M3UPI_PCI_PMON_CTR0, .event_ctl = ICX_M3UPI_PCI_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = ICX_M3UPI_PCI_PMON_BOX_CTL, .constraints = icx_uncore_m3upi_constraints, .ops = &ivbep_uncore_pci_ops, .format_group = &skx_uncore_format_group, }; enum { ICX_PCI_UNCORE_M2M, ICX_PCI_UNCORE_UPI, ICX_PCI_UNCORE_M3UPI, }; static struct intel_uncore_type *icx_pci_uncores[] = { [ICX_PCI_UNCORE_M2M] = &icx_uncore_m2m, [ICX_PCI_UNCORE_UPI] = &icx_uncore_upi, [ICX_PCI_UNCORE_M3UPI] = &icx_uncore_m3upi, NULL, }; static const struct pci_device_id icx_uncore_pci_ids[] = { { /* M2M 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x344a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(12, 0, ICX_PCI_UNCORE_M2M, 0), }, { /* M2M 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x344a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(13, 0, ICX_PCI_UNCORE_M2M, 1), }, { /* M2M 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x344a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(14, 0, ICX_PCI_UNCORE_M2M, 2), }, { /* M2M 3 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x344a), .driver_data = UNCORE_PCI_DEV_FULL_DATA(15, 0, ICX_PCI_UNCORE_M2M, 3), }, { /* UPI Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3441), .driver_data = UNCORE_PCI_DEV_FULL_DATA(2, 1, ICX_PCI_UNCORE_UPI, 0), }, { /* UPI Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3441), .driver_data = UNCORE_PCI_DEV_FULL_DATA(3, 1, ICX_PCI_UNCORE_UPI, 1), }, { /* UPI Link 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3441), .driver_data = UNCORE_PCI_DEV_FULL_DATA(4, 1, ICX_PCI_UNCORE_UPI, 2), }, { /* M3UPI Link 0 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3446), .driver_data = UNCORE_PCI_DEV_FULL_DATA(5, 1, ICX_PCI_UNCORE_M3UPI, 0), }, { /* M3UPI Link 1 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3446), .driver_data = UNCORE_PCI_DEV_FULL_DATA(6, 1, ICX_PCI_UNCORE_M3UPI, 1), }, { /* M3UPI Link 2 */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x3446), .driver_data = UNCORE_PCI_DEV_FULL_DATA(7, 1, ICX_PCI_UNCORE_M3UPI, 2), }, { /* end: all zeroes */ } }; static struct pci_driver icx_uncore_pci_driver = { .name = "icx_uncore", .id_table = icx_uncore_pci_ids, }; int icx_uncore_pci_init(void) { /* ICX UBOX DID */ int ret = snbep_pci2phy_map_init(0x3450, SKX_CPUNODEID, SKX_GIDNIDMAP, true); if (ret) return ret; uncore_pci_uncores = icx_pci_uncores; uncore_pci_driver = &icx_uncore_pci_driver; return 0; } static void icx_uncore_imc_init_box(struct intel_uncore_box *box) { unsigned int box_ctl = box->pmu->type->box_ctl + box->pmu->type->mmio_offset * (box->pmu->pmu_idx % ICX_NUMBER_IMC_CHN); int mem_offset = (box->pmu->pmu_idx / ICX_NUMBER_IMC_CHN) * ICX_IMC_MEM_STRIDE + SNR_IMC_MMIO_MEM0_OFFSET; __snr_uncore_mmio_init_box(box, box_ctl, mem_offset, SNR_MC_DEVICE_ID); } static struct intel_uncore_ops icx_uncore_mmio_ops = { .init_box = icx_uncore_imc_init_box, .exit_box = uncore_mmio_exit_box, .disable_box = snr_uncore_mmio_disable_box, .enable_box = snr_uncore_mmio_enable_box, .disable_event = snr_uncore_mmio_disable_event, .enable_event = snr_uncore_mmio_enable_event, .read_counter = uncore_mmio_read_counter, }; static struct intel_uncore_type icx_uncore_imc = { .name = "imc", .num_counters = 4, .num_boxes = 12, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .fixed_ctr = SNR_IMC_MMIO_PMON_FIXED_CTR, .fixed_ctl = SNR_IMC_MMIO_PMON_FIXED_CTL, .event_descs = snr_uncore_imc_events, .perf_ctr = SNR_IMC_MMIO_PMON_CTR0, .event_ctl = SNR_IMC_MMIO_PMON_CTL0, .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .box_ctl = SNR_IMC_MMIO_PMON_BOX_CTL, .mmio_offset = SNR_IMC_MMIO_OFFSET, .mmio_map_size = SNR_IMC_MMIO_SIZE, .ops = &icx_uncore_mmio_ops, .format_group = &skx_uncore_format_group, }; enum perf_uncore_icx_imc_freerunning_type_id { ICX_IMC_DCLK, ICX_IMC_DDR, ICX_IMC_DDRT, ICX_IMC_FREERUNNING_TYPE_MAX, }; static struct freerunning_counters icx_imc_freerunning[] = { [ICX_IMC_DCLK] = { 0x22b0, 0x0, 0, 1, 48 }, [ICX_IMC_DDR] = { 0x2290, 0x8, 0, 2, 48 }, [ICX_IMC_DDRT] = { 0x22a0, 0x8, 0, 2, 48 }, }; static struct uncore_event_desc icx_uncore_imc_freerunning_events[] = { INTEL_UNCORE_EVENT_DESC(dclk, "event=0xff,umask=0x10"), INTEL_UNCORE_EVENT_DESC(read, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(write, "event=0xff,umask=0x21"), INTEL_UNCORE_EVENT_DESC(write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(write.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(ddrt_read, "event=0xff,umask=0x30"), INTEL_UNCORE_EVENT_DESC(ddrt_read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(ddrt_read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(ddrt_write, "event=0xff,umask=0x31"), INTEL_UNCORE_EVENT_DESC(ddrt_write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(ddrt_write.unit, "MiB"), { /* end: all zeroes */ }, }; static void icx_uncore_imc_freerunning_init_box(struct intel_uncore_box *box) { int mem_offset = box->pmu->pmu_idx * ICX_IMC_MEM_STRIDE + SNR_IMC_MMIO_MEM0_OFFSET; snr_uncore_mmio_map(box, uncore_mmio_box_ctl(box), mem_offset, SNR_MC_DEVICE_ID); } static struct intel_uncore_ops icx_uncore_imc_freerunning_ops = { .init_box = icx_uncore_imc_freerunning_init_box, .exit_box = uncore_mmio_exit_box, .read_counter = uncore_mmio_read_counter, .hw_config = uncore_freerunning_hw_config, }; static struct intel_uncore_type icx_uncore_imc_free_running = { .name = "imc_free_running", .num_counters = 5, .num_boxes = 4, .num_freerunning_types = ICX_IMC_FREERUNNING_TYPE_MAX, .mmio_map_size = SNR_IMC_MMIO_SIZE, .freerunning = icx_imc_freerunning, .ops = &icx_uncore_imc_freerunning_ops, .event_descs = icx_uncore_imc_freerunning_events, .format_group = &skx_uncore_iio_freerunning_format_group, }; static struct intel_uncore_type *icx_mmio_uncores[] = { &icx_uncore_imc, &icx_uncore_imc_free_running, NULL, }; void icx_uncore_mmio_init(void) { uncore_mmio_uncores = icx_mmio_uncores; } /* end of ICX uncore support */ /* SPR uncore support */ static void spr_uncore_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; if (reg1->idx != EXTRA_REG_NONE) wrmsrl(reg1->reg, reg1->config); wrmsrl(hwc->config_base, hwc->config); } static void spr_uncore_msr_disable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; if (reg1->idx != EXTRA_REG_NONE) wrmsrl(reg1->reg, 0); wrmsrl(hwc->config_base, 0); } static int spr_cha_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; bool tie_en = !!(event->hw.config & SPR_CHA_PMON_CTL_TID_EN); struct intel_uncore_type *type = box->pmu->type; if (tie_en) { reg1->reg = SPR_C0_MSR_PMON_BOX_FILTER0 + HSWEP_CBO_MSR_OFFSET * type->box_ids[box->pmu->pmu_idx]; reg1->config = event->attr.config1 & SPR_CHA_PMON_BOX_FILTER_TID; reg1->idx = 0; } return 0; } static struct intel_uncore_ops spr_uncore_chabox_ops = { .init_box = intel_generic_uncore_msr_init_box, .disable_box = intel_generic_uncore_msr_disable_box, .enable_box = intel_generic_uncore_msr_enable_box, .disable_event = spr_uncore_msr_disable_event, .enable_event = spr_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, .hw_config = spr_cha_hw_config, .get_constraint = uncore_get_constraint, .put_constraint = uncore_put_constraint, }; static struct attribute *spr_uncore_cha_formats_attr[] = { &format_attr_event.attr, &format_attr_umask_ext4.attr, &format_attr_tid_en2.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_filter_tid5.attr, NULL, }; static const struct attribute_group spr_uncore_chabox_format_group = { .name = "format", .attrs = spr_uncore_cha_formats_attr, }; static ssize_t alias_show(struct device *dev, struct device_attribute *attr, char *buf) { struct intel_uncore_pmu *pmu = dev_to_uncore_pmu(dev); char pmu_name[UNCORE_PMU_NAME_LEN]; uncore_get_alias_name(pmu_name, pmu); return sysfs_emit(buf, "%s\n", pmu_name); } static DEVICE_ATTR_RO(alias); static struct attribute *uncore_alias_attrs[] = { &dev_attr_alias.attr, NULL }; ATTRIBUTE_GROUPS(uncore_alias); static struct intel_uncore_type spr_uncore_chabox = { .name = "cha", .event_mask = SPR_CHA_PMON_EVENT_MASK, .event_mask_ext = SPR_RAW_EVENT_MASK_EXT, .num_shared_regs = 1, .constraints = skx_uncore_chabox_constraints, .ops = &spr_uncore_chabox_ops, .format_group = &spr_uncore_chabox_format_group, .attr_update = uncore_alias_groups, }; static struct intel_uncore_type spr_uncore_iio = { .name = "iio", .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = SNR_IIO_PMON_RAW_EVENT_MASK_EXT, .format_group = &snr_uncore_iio_format_group, .attr_update = uncore_alias_groups, .constraints = icx_uncore_iio_constraints, }; static struct attribute *spr_uncore_raw_formats_attr[] = { &format_attr_event.attr, &format_attr_umask_ext4.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group spr_uncore_raw_format_group = { .name = "format", .attrs = spr_uncore_raw_formats_attr, }; #define SPR_UNCORE_COMMON_FORMAT() \ .event_mask = SNBEP_PMON_RAW_EVENT_MASK, \ .event_mask_ext = SPR_RAW_EVENT_MASK_EXT, \ .format_group = &spr_uncore_raw_format_group, \ .attr_update = uncore_alias_groups static struct intel_uncore_type spr_uncore_irp = { SPR_UNCORE_COMMON_FORMAT(), .name = "irp", }; static struct event_constraint spr_uncore_m2pcie_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x14, 0x3), UNCORE_EVENT_CONSTRAINT(0x2d, 0x3), EVENT_CONSTRAINT_END }; static struct intel_uncore_type spr_uncore_m2pcie = { SPR_UNCORE_COMMON_FORMAT(), .name = "m2pcie", .constraints = spr_uncore_m2pcie_constraints, }; static struct intel_uncore_type spr_uncore_pcu = { .name = "pcu", .attr_update = uncore_alias_groups, }; static void spr_uncore_mmio_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (!box->io_addr) return; if (uncore_pmc_fixed(hwc->idx)) writel(SNBEP_PMON_CTL_EN, box->io_addr + hwc->config_base); else writel(hwc->config, box->io_addr + hwc->config_base); } static struct intel_uncore_ops spr_uncore_mmio_ops = { .init_box = intel_generic_uncore_mmio_init_box, .exit_box = uncore_mmio_exit_box, .disable_box = intel_generic_uncore_mmio_disable_box, .enable_box = intel_generic_uncore_mmio_enable_box, .disable_event = intel_generic_uncore_mmio_disable_event, .enable_event = spr_uncore_mmio_enable_event, .read_counter = uncore_mmio_read_counter, }; static struct uncore_event_desc spr_uncore_imc_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0x01,umask=0x00"), INTEL_UNCORE_EVENT_DESC(cas_count_read, "event=0x05,umask=0xcf"), INTEL_UNCORE_EVENT_DESC(cas_count_read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(cas_count_write, "event=0x05,umask=0xf0"), INTEL_UNCORE_EVENT_DESC(cas_count_write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(cas_count_write.unit, "MiB"), { /* end: all zeroes */ }, }; static struct intel_uncore_type spr_uncore_imc = { SPR_UNCORE_COMMON_FORMAT(), .name = "imc", .fixed_ctr_bits = 48, .fixed_ctr = SNR_IMC_MMIO_PMON_FIXED_CTR, .fixed_ctl = SNR_IMC_MMIO_PMON_FIXED_CTL, .ops = &spr_uncore_mmio_ops, .event_descs = spr_uncore_imc_events, }; static void spr_uncore_pci_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct pci_dev *pdev = box->pci_dev; struct hw_perf_event *hwc = &event->hw; pci_write_config_dword(pdev, hwc->config_base + 4, (u32)(hwc->config >> 32)); pci_write_config_dword(pdev, hwc->config_base, (u32)hwc->config); } static struct intel_uncore_ops spr_uncore_pci_ops = { .init_box = intel_generic_uncore_pci_init_box, .disable_box = intel_generic_uncore_pci_disable_box, .enable_box = intel_generic_uncore_pci_enable_box, .disable_event = intel_generic_uncore_pci_disable_event, .enable_event = spr_uncore_pci_enable_event, .read_counter = intel_generic_uncore_pci_read_counter, }; #define SPR_UNCORE_PCI_COMMON_FORMAT() \ SPR_UNCORE_COMMON_FORMAT(), \ .ops = &spr_uncore_pci_ops static struct intel_uncore_type spr_uncore_m2m = { SPR_UNCORE_PCI_COMMON_FORMAT(), .name = "m2m", }; static struct attribute_group spr_upi_mapping_group = { .is_visible = skx_upi_mapping_visible, }; static const struct attribute_group *spr_upi_attr_update[] = { &uncore_alias_group, &spr_upi_mapping_group, NULL }; #define SPR_UPI_REGS_ADDR_DEVICE_LINK0 0x01 static void spr_upi_set_mapping(struct intel_uncore_type *type) { pmu_upi_set_mapping(type, &spr_upi_mapping_group); } static void spr_upi_cleanup_mapping(struct intel_uncore_type *type) { pmu_cleanup_mapping(type, &spr_upi_mapping_group); } static int spr_upi_get_topology(struct intel_uncore_type *type) { return discover_upi_topology(type, SPR_UBOX_DID, SPR_UPI_REGS_ADDR_DEVICE_LINK0); } static struct intel_uncore_type spr_uncore_mdf = { SPR_UNCORE_COMMON_FORMAT(), .name = "mdf", }; #define UNCORE_SPR_NUM_UNCORE_TYPES 12 #define UNCORE_SPR_CHA 0 #define UNCORE_SPR_IIO 1 #define UNCORE_SPR_IMC 6 #define UNCORE_SPR_UPI 8 #define UNCORE_SPR_M3UPI 9 /* * The uncore units, which are supported by the discovery table, * are defined here. */ static struct intel_uncore_type *spr_uncores[UNCORE_SPR_NUM_UNCORE_TYPES] = { &spr_uncore_chabox, &spr_uncore_iio, &spr_uncore_irp, &spr_uncore_m2pcie, &spr_uncore_pcu, NULL, &spr_uncore_imc, &spr_uncore_m2m, NULL, NULL, NULL, &spr_uncore_mdf, }; /* * The uncore units, which are not supported by the discovery table, * are implemented from here. */ #define SPR_UNCORE_UPI_NUM_BOXES 4 static unsigned int spr_upi_pci_offsets[SPR_UNCORE_UPI_NUM_BOXES] = { 0, 0x8000, 0x10000, 0x18000 }; static struct intel_uncore_type spr_uncore_upi = { .event_mask = SNBEP_PMON_RAW_EVENT_MASK, .event_mask_ext = SPR_RAW_EVENT_MASK_EXT, .format_group = &spr_uncore_raw_format_group, .ops = &spr_uncore_pci_ops, .name = "upi", .attr_update = spr_upi_attr_update, .get_topology = spr_upi_get_topology, .set_mapping = spr_upi_set_mapping, .cleanup_mapping = spr_upi_cleanup_mapping, .type_id = UNCORE_SPR_UPI, .num_counters = 4, .num_boxes = SPR_UNCORE_UPI_NUM_BOXES, .perf_ctr_bits = 48, .perf_ctr = ICX_UPI_PCI_PMON_CTR0, .event_ctl = ICX_UPI_PCI_PMON_CTL0, .box_ctl = ICX_UPI_PCI_PMON_BOX_CTL, .pci_offsets = spr_upi_pci_offsets, }; static struct intel_uncore_type spr_uncore_m3upi = { SPR_UNCORE_PCI_COMMON_FORMAT(), .name = "m3upi", .type_id = UNCORE_SPR_M3UPI, .num_counters = 4, .num_boxes = SPR_UNCORE_UPI_NUM_BOXES, .perf_ctr_bits = 48, .perf_ctr = ICX_M3UPI_PCI_PMON_CTR0, .event_ctl = ICX_M3UPI_PCI_PMON_CTL0, .box_ctl = ICX_M3UPI_PCI_PMON_BOX_CTL, .pci_offsets = spr_upi_pci_offsets, .constraints = icx_uncore_m3upi_constraints, }; enum perf_uncore_spr_iio_freerunning_type_id { SPR_IIO_MSR_IOCLK, SPR_IIO_MSR_BW_IN, SPR_IIO_MSR_BW_OUT, SPR_IIO_FREERUNNING_TYPE_MAX, }; static struct freerunning_counters spr_iio_freerunning[] = { [SPR_IIO_MSR_IOCLK] = { 0x340e, 0x1, 0x10, 1, 48 }, [SPR_IIO_MSR_BW_IN] = { 0x3800, 0x1, 0x10, 8, 48 }, [SPR_IIO_MSR_BW_OUT] = { 0x3808, 0x1, 0x10, 8, 48 }, }; static struct uncore_event_desc spr_uncore_iio_freerunning_events[] = { /* Free-Running IIO CLOCKS Counter */ INTEL_UNCORE_EVENT_DESC(ioclk, "event=0xff,umask=0x10"), /* Free-Running IIO BANDWIDTH IN Counters */ INTEL_UNCORE_EVENT_DESC(bw_in_port0, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port0.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port1, "event=0xff,umask=0x21"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port1.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port2, "event=0xff,umask=0x22"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port2.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port3, "event=0xff,umask=0x23"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port3.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port4, "event=0xff,umask=0x24"), INTEL_UNCORE_EVENT_DESC(bw_in_port4.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port4.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port5, "event=0xff,umask=0x25"), INTEL_UNCORE_EVENT_DESC(bw_in_port5.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port5.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port6, "event=0xff,umask=0x26"), INTEL_UNCORE_EVENT_DESC(bw_in_port6.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port6.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_in_port7, "event=0xff,umask=0x27"), INTEL_UNCORE_EVENT_DESC(bw_in_port7.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_in_port7.unit, "MiB"), /* Free-Running IIO BANDWIDTH OUT Counters */ INTEL_UNCORE_EVENT_DESC(bw_out_port0, "event=0xff,umask=0x30"), INTEL_UNCORE_EVENT_DESC(bw_out_port0.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port0.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port1, "event=0xff,umask=0x31"), INTEL_UNCORE_EVENT_DESC(bw_out_port1.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port1.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port2, "event=0xff,umask=0x32"), INTEL_UNCORE_EVENT_DESC(bw_out_port2.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port2.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port3, "event=0xff,umask=0x33"), INTEL_UNCORE_EVENT_DESC(bw_out_port3.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port3.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port4, "event=0xff,umask=0x34"), INTEL_UNCORE_EVENT_DESC(bw_out_port4.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port4.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port5, "event=0xff,umask=0x35"), INTEL_UNCORE_EVENT_DESC(bw_out_port5.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port5.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port6, "event=0xff,umask=0x36"), INTEL_UNCORE_EVENT_DESC(bw_out_port6.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port6.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(bw_out_port7, "event=0xff,umask=0x37"), INTEL_UNCORE_EVENT_DESC(bw_out_port7.scale, "3.814697266e-6"), INTEL_UNCORE_EVENT_DESC(bw_out_port7.unit, "MiB"), { /* end: all zeroes */ }, }; static struct intel_uncore_type spr_uncore_iio_free_running = { .name = "iio_free_running", .num_counters = 17, .num_freerunning_types = SPR_IIO_FREERUNNING_TYPE_MAX, .freerunning = spr_iio_freerunning, .ops = &skx_uncore_iio_freerunning_ops, .event_descs = spr_uncore_iio_freerunning_events, .format_group = &skx_uncore_iio_freerunning_format_group, }; enum perf_uncore_spr_imc_freerunning_type_id { SPR_IMC_DCLK, SPR_IMC_PQ_CYCLES, SPR_IMC_FREERUNNING_TYPE_MAX, }; static struct freerunning_counters spr_imc_freerunning[] = { [SPR_IMC_DCLK] = { 0x22b0, 0x0, 0, 1, 48 }, [SPR_IMC_PQ_CYCLES] = { 0x2318, 0x8, 0, 2, 48 }, }; static struct uncore_event_desc spr_uncore_imc_freerunning_events[] = { INTEL_UNCORE_EVENT_DESC(dclk, "event=0xff,umask=0x10"), INTEL_UNCORE_EVENT_DESC(rpq_cycles, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(wpq_cycles, "event=0xff,umask=0x21"), { /* end: all zeroes */ }, }; #define SPR_MC_DEVICE_ID 0x3251 static void spr_uncore_imc_freerunning_init_box(struct intel_uncore_box *box) { int mem_offset = box->pmu->pmu_idx * ICX_IMC_MEM_STRIDE + SNR_IMC_MMIO_MEM0_OFFSET; snr_uncore_mmio_map(box, uncore_mmio_box_ctl(box), mem_offset, SPR_MC_DEVICE_ID); } static struct intel_uncore_ops spr_uncore_imc_freerunning_ops = { .init_box = spr_uncore_imc_freerunning_init_box, .exit_box = uncore_mmio_exit_box, .read_counter = uncore_mmio_read_counter, .hw_config = uncore_freerunning_hw_config, }; static struct intel_uncore_type spr_uncore_imc_free_running = { .name = "imc_free_running", .num_counters = 3, .mmio_map_size = SNR_IMC_MMIO_SIZE, .num_freerunning_types = SPR_IMC_FREERUNNING_TYPE_MAX, .freerunning = spr_imc_freerunning, .ops = &spr_uncore_imc_freerunning_ops, .event_descs = spr_uncore_imc_freerunning_events, .format_group = &skx_uncore_iio_freerunning_format_group, }; #define UNCORE_SPR_MSR_EXTRA_UNCORES 1 #define UNCORE_SPR_MMIO_EXTRA_UNCORES 1 #define UNCORE_SPR_PCI_EXTRA_UNCORES 2 static struct intel_uncore_type *spr_msr_uncores[UNCORE_SPR_MSR_EXTRA_UNCORES] = { &spr_uncore_iio_free_running, }; static struct intel_uncore_type *spr_mmio_uncores[UNCORE_SPR_MMIO_EXTRA_UNCORES] = { &spr_uncore_imc_free_running, }; static struct intel_uncore_type *spr_pci_uncores[UNCORE_SPR_PCI_EXTRA_UNCORES] = { &spr_uncore_upi, &spr_uncore_m3upi }; int spr_uncore_units_ignore[] = { UNCORE_SPR_UPI, UNCORE_SPR_M3UPI, UNCORE_IGNORE_END }; static void uncore_type_customized_copy(struct intel_uncore_type *to_type, struct intel_uncore_type *from_type) { if (!to_type || !from_type) return; if (from_type->name) to_type->name = from_type->name; if (from_type->fixed_ctr_bits) to_type->fixed_ctr_bits = from_type->fixed_ctr_bits; if (from_type->event_mask) to_type->event_mask = from_type->event_mask; if (from_type->event_mask_ext) to_type->event_mask_ext = from_type->event_mask_ext; if (from_type->fixed_ctr) to_type->fixed_ctr = from_type->fixed_ctr; if (from_type->fixed_ctl) to_type->fixed_ctl = from_type->fixed_ctl; if (from_type->fixed_ctr_bits) to_type->fixed_ctr_bits = from_type->fixed_ctr_bits; if (from_type->num_shared_regs) to_type->num_shared_regs = from_type->num_shared_regs; if (from_type->constraints) to_type->constraints = from_type->constraints; if (from_type->ops) to_type->ops = from_type->ops; if (from_type->event_descs) to_type->event_descs = from_type->event_descs; if (from_type->format_group) to_type->format_group = from_type->format_group; if (from_type->attr_update) to_type->attr_update = from_type->attr_update; if (from_type->set_mapping) to_type->set_mapping = from_type->set_mapping; if (from_type->get_topology) to_type->get_topology = from_type->get_topology; if (from_type->cleanup_mapping) to_type->cleanup_mapping = from_type->cleanup_mapping; } static struct intel_uncore_type ** uncore_get_uncores(enum uncore_access_type type_id, int num_extra, struct intel_uncore_type **extra) { struct intel_uncore_type **types, **start_types; int i; start_types = types = intel_uncore_generic_init_uncores(type_id, num_extra); /* Only copy the customized features */ for (; *types; types++) { if ((*types)->type_id >= UNCORE_SPR_NUM_UNCORE_TYPES) continue; uncore_type_customized_copy(*types, spr_uncores[(*types)->type_id]); } for (i = 0; i < num_extra; i++, types++) *types = extra[i]; return start_types; } static struct intel_uncore_type * uncore_find_type_by_id(struct intel_uncore_type **types, int type_id) { for (; *types; types++) { if (type_id == (*types)->type_id) return *types; } return NULL; } static int uncore_type_max_boxes(struct intel_uncore_type **types, int type_id) { struct intel_uncore_type *type; int i, max = 0; type = uncore_find_type_by_id(types, type_id); if (!type) return 0; for (i = 0; i < type->num_boxes; i++) { if (type->box_ids[i] > max) max = type->box_ids[i]; } return max + 1; } #define SPR_MSR_UNC_CBO_CONFIG 0x2FFE void spr_uncore_cpu_init(void) { struct intel_uncore_type *type; u64 num_cbo; uncore_msr_uncores = uncore_get_uncores(UNCORE_ACCESS_MSR, UNCORE_SPR_MSR_EXTRA_UNCORES, spr_msr_uncores); type = uncore_find_type_by_id(uncore_msr_uncores, UNCORE_SPR_CHA); if (type) { /* * The value from the discovery table (stored in the type->num_boxes * of UNCORE_SPR_CHA) is incorrect on some SPR variants because of a * firmware bug. Using the value from SPR_MSR_UNC_CBO_CONFIG to replace it. */ rdmsrl(SPR_MSR_UNC_CBO_CONFIG, num_cbo); /* * The MSR doesn't work on the EMR XCC, but the firmware bug doesn't impact * the EMR XCC. Don't let the value from the MSR replace the existing value. */ if (num_cbo) type->num_boxes = num_cbo; } spr_uncore_iio_free_running.num_boxes = uncore_type_max_boxes(uncore_msr_uncores, UNCORE_SPR_IIO); } #define SPR_UNCORE_UPI_PCIID 0x3241 #define SPR_UNCORE_UPI0_DEVFN 0x9 #define SPR_UNCORE_M3UPI_PCIID 0x3246 #define SPR_UNCORE_M3UPI0_DEVFN 0x29 static void spr_update_device_location(int type_id) { struct intel_uncore_type *type; struct pci_dev *dev = NULL; u32 device, devfn; u64 *ctls; int die; if (type_id == UNCORE_SPR_UPI) { type = &spr_uncore_upi; device = SPR_UNCORE_UPI_PCIID; devfn = SPR_UNCORE_UPI0_DEVFN; } else if (type_id == UNCORE_SPR_M3UPI) { type = &spr_uncore_m3upi; device = SPR_UNCORE_M3UPI_PCIID; devfn = SPR_UNCORE_M3UPI0_DEVFN; } else return; ctls = kcalloc(__uncore_max_dies, sizeof(u64), GFP_KERNEL); if (!ctls) { type->num_boxes = 0; return; } while ((dev = pci_get_device(PCI_VENDOR_ID_INTEL, device, dev)) != NULL) { if (devfn != dev->devfn) continue; die = uncore_device_to_die(dev); if (die < 0) continue; ctls[die] = pci_domain_nr(dev->bus) << UNCORE_DISCOVERY_PCI_DOMAIN_OFFSET | dev->bus->number << UNCORE_DISCOVERY_PCI_BUS_OFFSET | devfn << UNCORE_DISCOVERY_PCI_DEVFN_OFFSET | type->box_ctl; } type->box_ctls = ctls; } int spr_uncore_pci_init(void) { /* * The discovery table of UPI on some SPR variant is broken, * which impacts the detection of both UPI and M3UPI uncore PMON. * Use the pre-defined UPI and M3UPI table to replace. * * The accurate location, e.g., domain and BUS number, * can only be retrieved at load time. * Update the location of UPI and M3UPI. */ spr_update_device_location(UNCORE_SPR_UPI); spr_update_device_location(UNCORE_SPR_M3UPI); uncore_pci_uncores = uncore_get_uncores(UNCORE_ACCESS_PCI, UNCORE_SPR_PCI_EXTRA_UNCORES, spr_pci_uncores); return 0; } void spr_uncore_mmio_init(void) { int ret = snbep_pci2phy_map_init(0x3250, SKX_CPUNODEID, SKX_GIDNIDMAP, true); if (ret) uncore_mmio_uncores = uncore_get_uncores(UNCORE_ACCESS_MMIO, 0, NULL); else { uncore_mmio_uncores = uncore_get_uncores(UNCORE_ACCESS_MMIO, UNCORE_SPR_MMIO_EXTRA_UNCORES, spr_mmio_uncores); spr_uncore_imc_free_running.num_boxes = uncore_type_max_boxes(uncore_mmio_uncores, UNCORE_SPR_IMC) / 2; } } /* end of SPR uncore support */
linux-master
arch/x86/events/intel/uncore_snbep.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/perf_event.h> #include <linux/types.h> #include <asm/perf_event.h> #include <asm/msr.h> #include "../perf_event.h" /* * Intel LBR_SELECT bits * Intel Vol3a, April 2011, Section 16.7 Table 16-10 * * Hardware branch filter (not available on all CPUs) */ #define LBR_KERNEL_BIT 0 /* do not capture at ring0 */ #define LBR_USER_BIT 1 /* do not capture at ring > 0 */ #define LBR_JCC_BIT 2 /* do not capture conditional branches */ #define LBR_REL_CALL_BIT 3 /* do not capture relative calls */ #define LBR_IND_CALL_BIT 4 /* do not capture indirect calls */ #define LBR_RETURN_BIT 5 /* do not capture near returns */ #define LBR_IND_JMP_BIT 6 /* do not capture indirect jumps */ #define LBR_REL_JMP_BIT 7 /* do not capture relative jumps */ #define LBR_FAR_BIT 8 /* do not capture far branches */ #define LBR_CALL_STACK_BIT 9 /* enable call stack */ /* * Following bit only exists in Linux; we mask it out before writing it to * the actual MSR. But it helps the constraint perf code to understand * that this is a separate configuration. */ #define LBR_NO_INFO_BIT 63 /* don't read LBR_INFO. */ #define LBR_KERNEL (1 << LBR_KERNEL_BIT) #define LBR_USER (1 << LBR_USER_BIT) #define LBR_JCC (1 << LBR_JCC_BIT) #define LBR_REL_CALL (1 << LBR_REL_CALL_BIT) #define LBR_IND_CALL (1 << LBR_IND_CALL_BIT) #define LBR_RETURN (1 << LBR_RETURN_BIT) #define LBR_REL_JMP (1 << LBR_REL_JMP_BIT) #define LBR_IND_JMP (1 << LBR_IND_JMP_BIT) #define LBR_FAR (1 << LBR_FAR_BIT) #define LBR_CALL_STACK (1 << LBR_CALL_STACK_BIT) #define LBR_NO_INFO (1ULL << LBR_NO_INFO_BIT) #define LBR_PLM (LBR_KERNEL | LBR_USER) #define LBR_SEL_MASK 0x3ff /* valid bits in LBR_SELECT */ #define LBR_NOT_SUPP -1 /* LBR filter not supported */ #define LBR_IGN 0 /* ignored */ #define LBR_ANY \ (LBR_JCC |\ LBR_REL_CALL |\ LBR_IND_CALL |\ LBR_RETURN |\ LBR_REL_JMP |\ LBR_IND_JMP |\ LBR_FAR) #define LBR_FROM_FLAG_MISPRED BIT_ULL(63) #define LBR_FROM_FLAG_IN_TX BIT_ULL(62) #define LBR_FROM_FLAG_ABORT BIT_ULL(61) #define LBR_FROM_SIGNEXT_2MSB (BIT_ULL(60) | BIT_ULL(59)) /* * Intel LBR_CTL bits * * Hardware branch filter for Arch LBR */ #define ARCH_LBR_KERNEL_BIT 1 /* capture at ring0 */ #define ARCH_LBR_USER_BIT 2 /* capture at ring > 0 */ #define ARCH_LBR_CALL_STACK_BIT 3 /* enable call stack */ #define ARCH_LBR_JCC_BIT 16 /* capture conditional branches */ #define ARCH_LBR_REL_JMP_BIT 17 /* capture relative jumps */ #define ARCH_LBR_IND_JMP_BIT 18 /* capture indirect jumps */ #define ARCH_LBR_REL_CALL_BIT 19 /* capture relative calls */ #define ARCH_LBR_IND_CALL_BIT 20 /* capture indirect calls */ #define ARCH_LBR_RETURN_BIT 21 /* capture near returns */ #define ARCH_LBR_OTHER_BRANCH_BIT 22 /* capture other branches */ #define ARCH_LBR_KERNEL (1ULL << ARCH_LBR_KERNEL_BIT) #define ARCH_LBR_USER (1ULL << ARCH_LBR_USER_BIT) #define ARCH_LBR_CALL_STACK (1ULL << ARCH_LBR_CALL_STACK_BIT) #define ARCH_LBR_JCC (1ULL << ARCH_LBR_JCC_BIT) #define ARCH_LBR_REL_JMP (1ULL << ARCH_LBR_REL_JMP_BIT) #define ARCH_LBR_IND_JMP (1ULL << ARCH_LBR_IND_JMP_BIT) #define ARCH_LBR_REL_CALL (1ULL << ARCH_LBR_REL_CALL_BIT) #define ARCH_LBR_IND_CALL (1ULL << ARCH_LBR_IND_CALL_BIT) #define ARCH_LBR_RETURN (1ULL << ARCH_LBR_RETURN_BIT) #define ARCH_LBR_OTHER_BRANCH (1ULL << ARCH_LBR_OTHER_BRANCH_BIT) #define ARCH_LBR_ANY \ (ARCH_LBR_JCC |\ ARCH_LBR_REL_JMP |\ ARCH_LBR_IND_JMP |\ ARCH_LBR_REL_CALL |\ ARCH_LBR_IND_CALL |\ ARCH_LBR_RETURN |\ ARCH_LBR_OTHER_BRANCH) #define ARCH_LBR_CTL_MASK 0x7f000e static void intel_pmu_lbr_filter(struct cpu_hw_events *cpuc); static __always_inline bool is_lbr_call_stack_bit_set(u64 config) { if (static_cpu_has(X86_FEATURE_ARCH_LBR)) return !!(config & ARCH_LBR_CALL_STACK); return !!(config & LBR_CALL_STACK); } /* * We only support LBR implementations that have FREEZE_LBRS_ON_PMI * otherwise it becomes near impossible to get a reliable stack. */ static void __intel_pmu_lbr_enable(bool pmi) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); u64 debugctl, lbr_select = 0, orig_debugctl; /* * No need to unfreeze manually, as v4 can do that as part * of the GLOBAL_STATUS ack. */ if (pmi && x86_pmu.version >= 4) return; /* * No need to reprogram LBR_SELECT in a PMI, as it * did not change. */ if (cpuc->lbr_sel) lbr_select = cpuc->lbr_sel->config & x86_pmu.lbr_sel_mask; if (!static_cpu_has(X86_FEATURE_ARCH_LBR) && !pmi && cpuc->lbr_sel) wrmsrl(MSR_LBR_SELECT, lbr_select); rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); orig_debugctl = debugctl; if (!static_cpu_has(X86_FEATURE_ARCH_LBR)) debugctl |= DEBUGCTLMSR_LBR; /* * LBR callstack does not work well with FREEZE_LBRS_ON_PMI. * If FREEZE_LBRS_ON_PMI is set, PMI near call/return instructions * may cause superfluous increase/decrease of LBR_TOS. */ if (is_lbr_call_stack_bit_set(lbr_select)) debugctl &= ~DEBUGCTLMSR_FREEZE_LBRS_ON_PMI; else debugctl |= DEBUGCTLMSR_FREEZE_LBRS_ON_PMI; if (orig_debugctl != debugctl) wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); if (static_cpu_has(X86_FEATURE_ARCH_LBR)) wrmsrl(MSR_ARCH_LBR_CTL, lbr_select | ARCH_LBR_CTL_LBREN); } void intel_pmu_lbr_reset_32(void) { int i; for (i = 0; i < x86_pmu.lbr_nr; i++) wrmsrl(x86_pmu.lbr_from + i, 0); } void intel_pmu_lbr_reset_64(void) { int i; for (i = 0; i < x86_pmu.lbr_nr; i++) { wrmsrl(x86_pmu.lbr_from + i, 0); wrmsrl(x86_pmu.lbr_to + i, 0); if (x86_pmu.lbr_has_info) wrmsrl(x86_pmu.lbr_info + i, 0); } } static void intel_pmu_arch_lbr_reset(void) { /* Write to ARCH_LBR_DEPTH MSR, all LBR entries are reset to 0 */ wrmsrl(MSR_ARCH_LBR_DEPTH, x86_pmu.lbr_nr); } void intel_pmu_lbr_reset(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (!x86_pmu.lbr_nr) return; x86_pmu.lbr_reset(); cpuc->last_task_ctx = NULL; cpuc->last_log_id = 0; if (!static_cpu_has(X86_FEATURE_ARCH_LBR) && cpuc->lbr_select) wrmsrl(MSR_LBR_SELECT, 0); } /* * TOS = most recently recorded branch */ static inline u64 intel_pmu_lbr_tos(void) { u64 tos; rdmsrl(x86_pmu.lbr_tos, tos); return tos; } enum { LBR_NONE, LBR_VALID, }; /* * For format LBR_FORMAT_EIP_FLAGS2, bits 61:62 in MSR_LAST_BRANCH_FROM_x * are the TSX flags when TSX is supported, but when TSX is not supported * they have no consistent behavior: * * - For wrmsr(), bits 61:62 are considered part of the sign extension. * - For HW updates (branch captures) bits 61:62 are always OFF and are not * part of the sign extension. * * Therefore, if: * * 1) LBR format LBR_FORMAT_EIP_FLAGS2 * 2) CPU has no TSX support enabled * * ... then any value passed to wrmsr() must be sign extended to 63 bits and any * value from rdmsr() must be converted to have a 61 bits sign extension, * ignoring the TSX flags. */ static inline bool lbr_from_signext_quirk_needed(void) { bool tsx_support = boot_cpu_has(X86_FEATURE_HLE) || boot_cpu_has(X86_FEATURE_RTM); return !tsx_support; } static DEFINE_STATIC_KEY_FALSE(lbr_from_quirk_key); /* If quirk is enabled, ensure sign extension is 63 bits: */ inline u64 lbr_from_signext_quirk_wr(u64 val) { if (static_branch_unlikely(&lbr_from_quirk_key)) { /* * Sign extend into bits 61:62 while preserving bit 63. * * Quirk is enabled when TSX is disabled. Therefore TSX bits * in val are always OFF and must be changed to be sign * extension bits. Since bits 59:60 are guaranteed to be * part of the sign extension bits, we can just copy them * to 61:62. */ val |= (LBR_FROM_SIGNEXT_2MSB & val) << 2; } return val; } /* * If quirk is needed, ensure sign extension is 61 bits: */ static u64 lbr_from_signext_quirk_rd(u64 val) { if (static_branch_unlikely(&lbr_from_quirk_key)) { /* * Quirk is on when TSX is not enabled. Therefore TSX * flags must be read as OFF. */ val &= ~(LBR_FROM_FLAG_IN_TX | LBR_FROM_FLAG_ABORT); } return val; } static __always_inline void wrlbr_from(unsigned int idx, u64 val) { val = lbr_from_signext_quirk_wr(val); wrmsrl(x86_pmu.lbr_from + idx, val); } static __always_inline void wrlbr_to(unsigned int idx, u64 val) { wrmsrl(x86_pmu.lbr_to + idx, val); } static __always_inline void wrlbr_info(unsigned int idx, u64 val) { wrmsrl(x86_pmu.lbr_info + idx, val); } static __always_inline u64 rdlbr_from(unsigned int idx, struct lbr_entry *lbr) { u64 val; if (lbr) return lbr->from; rdmsrl(x86_pmu.lbr_from + idx, val); return lbr_from_signext_quirk_rd(val); } static __always_inline u64 rdlbr_to(unsigned int idx, struct lbr_entry *lbr) { u64 val; if (lbr) return lbr->to; rdmsrl(x86_pmu.lbr_to + idx, val); return val; } static __always_inline u64 rdlbr_info(unsigned int idx, struct lbr_entry *lbr) { u64 val; if (lbr) return lbr->info; rdmsrl(x86_pmu.lbr_info + idx, val); return val; } static inline void wrlbr_all(struct lbr_entry *lbr, unsigned int idx, bool need_info) { wrlbr_from(idx, lbr->from); wrlbr_to(idx, lbr->to); if (need_info) wrlbr_info(idx, lbr->info); } static inline bool rdlbr_all(struct lbr_entry *lbr, unsigned int idx, bool need_info) { u64 from = rdlbr_from(idx, NULL); /* Don't read invalid entry */ if (!from) return false; lbr->from = from; lbr->to = rdlbr_to(idx, NULL); if (need_info) lbr->info = rdlbr_info(idx, NULL); return true; } void intel_pmu_lbr_restore(void *ctx) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct x86_perf_task_context *task_ctx = ctx; bool need_info = x86_pmu.lbr_has_info; u64 tos = task_ctx->tos; unsigned lbr_idx, mask; int i; mask = x86_pmu.lbr_nr - 1; for (i = 0; i < task_ctx->valid_lbrs; i++) { lbr_idx = (tos - i) & mask; wrlbr_all(&task_ctx->lbr[i], lbr_idx, need_info); } for (; i < x86_pmu.lbr_nr; i++) { lbr_idx = (tos - i) & mask; wrlbr_from(lbr_idx, 0); wrlbr_to(lbr_idx, 0); if (need_info) wrlbr_info(lbr_idx, 0); } wrmsrl(x86_pmu.lbr_tos, tos); if (cpuc->lbr_select) wrmsrl(MSR_LBR_SELECT, task_ctx->lbr_sel); } static void intel_pmu_arch_lbr_restore(void *ctx) { struct x86_perf_task_context_arch_lbr *task_ctx = ctx; struct lbr_entry *entries = task_ctx->entries; int i; /* Fast reset the LBRs before restore if the call stack is not full. */ if (!entries[x86_pmu.lbr_nr - 1].from) intel_pmu_arch_lbr_reset(); for (i = 0; i < x86_pmu.lbr_nr; i++) { if (!entries[i].from) break; wrlbr_all(&entries[i], i, true); } } /* * Restore the Architecture LBR state from the xsave area in the perf * context data for the task via the XRSTORS instruction. */ static void intel_pmu_arch_lbr_xrstors(void *ctx) { struct x86_perf_task_context_arch_lbr_xsave *task_ctx = ctx; xrstors(&task_ctx->xsave, XFEATURE_MASK_LBR); } static __always_inline bool lbr_is_reset_in_cstate(void *ctx) { if (static_cpu_has(X86_FEATURE_ARCH_LBR)) return x86_pmu.lbr_deep_c_reset && !rdlbr_from(0, NULL); return !rdlbr_from(((struct x86_perf_task_context *)ctx)->tos, NULL); } static void __intel_pmu_lbr_restore(void *ctx) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (task_context_opt(ctx)->lbr_callstack_users == 0 || task_context_opt(ctx)->lbr_stack_state == LBR_NONE) { intel_pmu_lbr_reset(); return; } /* * Does not restore the LBR registers, if * - No one else touched them, and * - Was not cleared in Cstate */ if ((ctx == cpuc->last_task_ctx) && (task_context_opt(ctx)->log_id == cpuc->last_log_id) && !lbr_is_reset_in_cstate(ctx)) { task_context_opt(ctx)->lbr_stack_state = LBR_NONE; return; } x86_pmu.lbr_restore(ctx); task_context_opt(ctx)->lbr_stack_state = LBR_NONE; } void intel_pmu_lbr_save(void *ctx) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct x86_perf_task_context *task_ctx = ctx; bool need_info = x86_pmu.lbr_has_info; unsigned lbr_idx, mask; u64 tos; int i; mask = x86_pmu.lbr_nr - 1; tos = intel_pmu_lbr_tos(); for (i = 0; i < x86_pmu.lbr_nr; i++) { lbr_idx = (tos - i) & mask; if (!rdlbr_all(&task_ctx->lbr[i], lbr_idx, need_info)) break; } task_ctx->valid_lbrs = i; task_ctx->tos = tos; if (cpuc->lbr_select) rdmsrl(MSR_LBR_SELECT, task_ctx->lbr_sel); } static void intel_pmu_arch_lbr_save(void *ctx) { struct x86_perf_task_context_arch_lbr *task_ctx = ctx; struct lbr_entry *entries = task_ctx->entries; int i; for (i = 0; i < x86_pmu.lbr_nr; i++) { if (!rdlbr_all(&entries[i], i, true)) break; } /* LBR call stack is not full. Reset is required in restore. */ if (i < x86_pmu.lbr_nr) entries[x86_pmu.lbr_nr - 1].from = 0; } /* * Save the Architecture LBR state to the xsave area in the perf * context data for the task via the XSAVES instruction. */ static void intel_pmu_arch_lbr_xsaves(void *ctx) { struct x86_perf_task_context_arch_lbr_xsave *task_ctx = ctx; xsaves(&task_ctx->xsave, XFEATURE_MASK_LBR); } static void __intel_pmu_lbr_save(void *ctx) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (task_context_opt(ctx)->lbr_callstack_users == 0) { task_context_opt(ctx)->lbr_stack_state = LBR_NONE; return; } x86_pmu.lbr_save(ctx); task_context_opt(ctx)->lbr_stack_state = LBR_VALID; cpuc->last_task_ctx = ctx; cpuc->last_log_id = ++task_context_opt(ctx)->log_id; } void intel_pmu_lbr_swap_task_ctx(struct perf_event_pmu_context *prev_epc, struct perf_event_pmu_context *next_epc) { void *prev_ctx_data, *next_ctx_data; swap(prev_epc->task_ctx_data, next_epc->task_ctx_data); /* * Architecture specific synchronization makes sense in case * both prev_epc->task_ctx_data and next_epc->task_ctx_data * pointers are allocated. */ prev_ctx_data = next_epc->task_ctx_data; next_ctx_data = prev_epc->task_ctx_data; if (!prev_ctx_data || !next_ctx_data) return; swap(task_context_opt(prev_ctx_data)->lbr_callstack_users, task_context_opt(next_ctx_data)->lbr_callstack_users); } void intel_pmu_lbr_sched_task(struct perf_event_pmu_context *pmu_ctx, bool sched_in) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); void *task_ctx; if (!cpuc->lbr_users) return; /* * If LBR callstack feature is enabled and the stack was saved when * the task was scheduled out, restore the stack. Otherwise flush * the LBR stack. */ task_ctx = pmu_ctx ? pmu_ctx->task_ctx_data : NULL; if (task_ctx) { if (sched_in) __intel_pmu_lbr_restore(task_ctx); else __intel_pmu_lbr_save(task_ctx); return; } /* * Since a context switch can flip the address space and LBR entries * are not tagged with an identifier, we need to wipe the LBR, even for * per-cpu events. You simply cannot resolve the branches from the old * address space. */ if (sched_in) intel_pmu_lbr_reset(); } static inline bool branch_user_callstack(unsigned br_sel) { return (br_sel & X86_BR_USER) && (br_sel & X86_BR_CALL_STACK); } void intel_pmu_lbr_add(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (!x86_pmu.lbr_nr) return; if (event->hw.flags & PERF_X86_EVENT_LBR_SELECT) cpuc->lbr_select = 1; cpuc->br_sel = event->hw.branch_reg.reg; if (branch_user_callstack(cpuc->br_sel) && event->pmu_ctx->task_ctx_data) task_context_opt(event->pmu_ctx->task_ctx_data)->lbr_callstack_users++; /* * Request pmu::sched_task() callback, which will fire inside the * regular perf event scheduling, so that call will: * * - restore or wipe; when LBR-callstack, * - wipe; otherwise, * * when this is from __perf_event_task_sched_in(). * * However, if this is from perf_install_in_context(), no such callback * will follow and we'll need to reset the LBR here if this is the * first LBR event. * * The problem is, we cannot tell these cases apart... but we can * exclude the biggest chunk of cases by looking at * event->total_time_running. An event that has accrued runtime cannot * be 'new'. Conversely, a new event can get installed through the * context switch path for the first time. */ if (x86_pmu.intel_cap.pebs_baseline && event->attr.precise_ip > 0) cpuc->lbr_pebs_users++; perf_sched_cb_inc(event->pmu); if (!cpuc->lbr_users++ && !event->total_time_running) intel_pmu_lbr_reset(); } void release_lbr_buffers(void) { struct kmem_cache *kmem_cache; struct cpu_hw_events *cpuc; int cpu; if (!static_cpu_has(X86_FEATURE_ARCH_LBR)) return; for_each_possible_cpu(cpu) { cpuc = per_cpu_ptr(&cpu_hw_events, cpu); kmem_cache = x86_get_pmu(cpu)->task_ctx_cache; if (kmem_cache && cpuc->lbr_xsave) { kmem_cache_free(kmem_cache, cpuc->lbr_xsave); cpuc->lbr_xsave = NULL; } } } void reserve_lbr_buffers(void) { struct kmem_cache *kmem_cache; struct cpu_hw_events *cpuc; int cpu; if (!static_cpu_has(X86_FEATURE_ARCH_LBR)) return; for_each_possible_cpu(cpu) { cpuc = per_cpu_ptr(&cpu_hw_events, cpu); kmem_cache = x86_get_pmu(cpu)->task_ctx_cache; if (!kmem_cache || cpuc->lbr_xsave) continue; cpuc->lbr_xsave = kmem_cache_alloc_node(kmem_cache, GFP_KERNEL | __GFP_ZERO, cpu_to_node(cpu)); } } void intel_pmu_lbr_del(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (!x86_pmu.lbr_nr) return; if (branch_user_callstack(cpuc->br_sel) && event->pmu_ctx->task_ctx_data) task_context_opt(event->pmu_ctx->task_ctx_data)->lbr_callstack_users--; if (event->hw.flags & PERF_X86_EVENT_LBR_SELECT) cpuc->lbr_select = 0; if (x86_pmu.intel_cap.pebs_baseline && event->attr.precise_ip > 0) cpuc->lbr_pebs_users--; cpuc->lbr_users--; WARN_ON_ONCE(cpuc->lbr_users < 0); WARN_ON_ONCE(cpuc->lbr_pebs_users < 0); perf_sched_cb_dec(event->pmu); } static inline bool vlbr_exclude_host(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); return test_bit(INTEL_PMC_IDX_FIXED_VLBR, (unsigned long *)&cpuc->intel_ctrl_guest_mask); } void intel_pmu_lbr_enable_all(bool pmi) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (cpuc->lbr_users && !vlbr_exclude_host()) __intel_pmu_lbr_enable(pmi); } void intel_pmu_lbr_disable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (cpuc->lbr_users && !vlbr_exclude_host()) { if (static_cpu_has(X86_FEATURE_ARCH_LBR)) return __intel_pmu_arch_lbr_disable(); __intel_pmu_lbr_disable(); } } void intel_pmu_lbr_read_32(struct cpu_hw_events *cpuc) { unsigned long mask = x86_pmu.lbr_nr - 1; struct perf_branch_entry *br = cpuc->lbr_entries; u64 tos = intel_pmu_lbr_tos(); int i; for (i = 0; i < x86_pmu.lbr_nr; i++) { unsigned long lbr_idx = (tos - i) & mask; union { struct { u32 from; u32 to; }; u64 lbr; } msr_lastbranch; rdmsrl(x86_pmu.lbr_from + lbr_idx, msr_lastbranch.lbr); perf_clear_branch_entry_bitfields(br); br->from = msr_lastbranch.from; br->to = msr_lastbranch.to; br++; } cpuc->lbr_stack.nr = i; cpuc->lbr_stack.hw_idx = tos; } /* * Due to lack of segmentation in Linux the effective address (offset) * is the same as the linear address, allowing us to merge the LIP and EIP * LBR formats. */ void intel_pmu_lbr_read_64(struct cpu_hw_events *cpuc) { bool need_info = false, call_stack = false; unsigned long mask = x86_pmu.lbr_nr - 1; struct perf_branch_entry *br = cpuc->lbr_entries; u64 tos = intel_pmu_lbr_tos(); int i; int out = 0; int num = x86_pmu.lbr_nr; if (cpuc->lbr_sel) { need_info = !(cpuc->lbr_sel->config & LBR_NO_INFO); if (cpuc->lbr_sel->config & LBR_CALL_STACK) call_stack = true; } for (i = 0; i < num; i++) { unsigned long lbr_idx = (tos - i) & mask; u64 from, to, mis = 0, pred = 0, in_tx = 0, abort = 0; u16 cycles = 0; from = rdlbr_from(lbr_idx, NULL); to = rdlbr_to(lbr_idx, NULL); /* * Read LBR call stack entries * until invalid entry (0s) is detected. */ if (call_stack && !from) break; if (x86_pmu.lbr_has_info) { if (need_info) { u64 info; info = rdlbr_info(lbr_idx, NULL); mis = !!(info & LBR_INFO_MISPRED); pred = !mis; cycles = (info & LBR_INFO_CYCLES); if (x86_pmu.lbr_has_tsx) { in_tx = !!(info & LBR_INFO_IN_TX); abort = !!(info & LBR_INFO_ABORT); } } } else { int skip = 0; if (x86_pmu.lbr_from_flags) { mis = !!(from & LBR_FROM_FLAG_MISPRED); pred = !mis; skip = 1; } if (x86_pmu.lbr_has_tsx) { in_tx = !!(from & LBR_FROM_FLAG_IN_TX); abort = !!(from & LBR_FROM_FLAG_ABORT); skip = 3; } from = (u64)((((s64)from) << skip) >> skip); if (x86_pmu.lbr_to_cycles) { cycles = ((to >> 48) & LBR_INFO_CYCLES); to = (u64)((((s64)to) << 16) >> 16); } } /* * Some CPUs report duplicated abort records, * with the second entry not having an abort bit set. * Skip them here. This loop runs backwards, * so we need to undo the previous record. * If the abort just happened outside the window * the extra entry cannot be removed. */ if (abort && x86_pmu.lbr_double_abort && out > 0) out--; perf_clear_branch_entry_bitfields(br+out); br[out].from = from; br[out].to = to; br[out].mispred = mis; br[out].predicted = pred; br[out].in_tx = in_tx; br[out].abort = abort; br[out].cycles = cycles; out++; } cpuc->lbr_stack.nr = out; cpuc->lbr_stack.hw_idx = tos; } static DEFINE_STATIC_KEY_FALSE(x86_lbr_mispred); static DEFINE_STATIC_KEY_FALSE(x86_lbr_cycles); static DEFINE_STATIC_KEY_FALSE(x86_lbr_type); static __always_inline int get_lbr_br_type(u64 info) { int type = 0; if (static_branch_likely(&x86_lbr_type)) type = (info & LBR_INFO_BR_TYPE) >> LBR_INFO_BR_TYPE_OFFSET; return type; } static __always_inline bool get_lbr_mispred(u64 info) { bool mispred = 0; if (static_branch_likely(&x86_lbr_mispred)) mispred = !!(info & LBR_INFO_MISPRED); return mispred; } static __always_inline u16 get_lbr_cycles(u64 info) { u16 cycles = info & LBR_INFO_CYCLES; if (static_cpu_has(X86_FEATURE_ARCH_LBR) && (!static_branch_likely(&x86_lbr_cycles) || !(info & LBR_INFO_CYC_CNT_VALID))) cycles = 0; return cycles; } static void intel_pmu_store_lbr(struct cpu_hw_events *cpuc, struct lbr_entry *entries) { struct perf_branch_entry *e; struct lbr_entry *lbr; u64 from, to, info; int i; for (i = 0; i < x86_pmu.lbr_nr; i++) { lbr = entries ? &entries[i] : NULL; e = &cpuc->lbr_entries[i]; from = rdlbr_from(i, lbr); /* * Read LBR entries until invalid entry (0s) is detected. */ if (!from) break; to = rdlbr_to(i, lbr); info = rdlbr_info(i, lbr); perf_clear_branch_entry_bitfields(e); e->from = from; e->to = to; e->mispred = get_lbr_mispred(info); e->predicted = !e->mispred; e->in_tx = !!(info & LBR_INFO_IN_TX); e->abort = !!(info & LBR_INFO_ABORT); e->cycles = get_lbr_cycles(info); e->type = get_lbr_br_type(info); } cpuc->lbr_stack.nr = i; } static void intel_pmu_arch_lbr_read(struct cpu_hw_events *cpuc) { intel_pmu_store_lbr(cpuc, NULL); } static void intel_pmu_arch_lbr_read_xsave(struct cpu_hw_events *cpuc) { struct x86_perf_task_context_arch_lbr_xsave *xsave = cpuc->lbr_xsave; if (!xsave) { intel_pmu_store_lbr(cpuc, NULL); return; } xsaves(&xsave->xsave, XFEATURE_MASK_LBR); intel_pmu_store_lbr(cpuc, xsave->lbr.entries); } void intel_pmu_lbr_read(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* * Don't read when all LBRs users are using adaptive PEBS. * * This could be smarter and actually check the event, * but this simple approach seems to work for now. */ if (!cpuc->lbr_users || vlbr_exclude_host() || cpuc->lbr_users == cpuc->lbr_pebs_users) return; x86_pmu.lbr_read(cpuc); intel_pmu_lbr_filter(cpuc); } /* * SW filter is used: * - in case there is no HW filter * - in case the HW filter has errata or limitations */ static int intel_pmu_setup_sw_lbr_filter(struct perf_event *event) { u64 br_type = event->attr.branch_sample_type; int mask = 0; if (br_type & PERF_SAMPLE_BRANCH_USER) mask |= X86_BR_USER; if (br_type & PERF_SAMPLE_BRANCH_KERNEL) mask |= X86_BR_KERNEL; /* we ignore BRANCH_HV here */ if (br_type & PERF_SAMPLE_BRANCH_ANY) mask |= X86_BR_ANY; if (br_type & PERF_SAMPLE_BRANCH_ANY_CALL) mask |= X86_BR_ANY_CALL; if (br_type & PERF_SAMPLE_BRANCH_ANY_RETURN) mask |= X86_BR_RET | X86_BR_IRET | X86_BR_SYSRET; if (br_type & PERF_SAMPLE_BRANCH_IND_CALL) mask |= X86_BR_IND_CALL; if (br_type & PERF_SAMPLE_BRANCH_ABORT_TX) mask |= X86_BR_ABORT; if (br_type & PERF_SAMPLE_BRANCH_IN_TX) mask |= X86_BR_IN_TX; if (br_type & PERF_SAMPLE_BRANCH_NO_TX) mask |= X86_BR_NO_TX; if (br_type & PERF_SAMPLE_BRANCH_COND) mask |= X86_BR_JCC; if (br_type & PERF_SAMPLE_BRANCH_CALL_STACK) { if (!x86_pmu_has_lbr_callstack()) return -EOPNOTSUPP; if (mask & ~(X86_BR_USER | X86_BR_KERNEL)) return -EINVAL; mask |= X86_BR_CALL | X86_BR_IND_CALL | X86_BR_RET | X86_BR_CALL_STACK; } if (br_type & PERF_SAMPLE_BRANCH_IND_JUMP) mask |= X86_BR_IND_JMP; if (br_type & PERF_SAMPLE_BRANCH_CALL) mask |= X86_BR_CALL | X86_BR_ZERO_CALL; if (br_type & PERF_SAMPLE_BRANCH_TYPE_SAVE) mask |= X86_BR_TYPE_SAVE; /* * stash actual user request into reg, it may * be used by fixup code for some CPU */ event->hw.branch_reg.reg = mask; return 0; } /* * setup the HW LBR filter * Used only when available, may not be enough to disambiguate * all branches, may need the help of the SW filter */ static int intel_pmu_setup_hw_lbr_filter(struct perf_event *event) { struct hw_perf_event_extra *reg; u64 br_type = event->attr.branch_sample_type; u64 mask = 0, v; int i; for (i = 0; i < PERF_SAMPLE_BRANCH_MAX_SHIFT; i++) { if (!(br_type & (1ULL << i))) continue; v = x86_pmu.lbr_sel_map[i]; if (v == LBR_NOT_SUPP) return -EOPNOTSUPP; if (v != LBR_IGN) mask |= v; } reg = &event->hw.branch_reg; reg->idx = EXTRA_REG_LBR; if (static_cpu_has(X86_FEATURE_ARCH_LBR)) { reg->config = mask; /* * The Arch LBR HW can retrieve the common branch types * from the LBR_INFO. It doesn't require the high overhead * SW disassemble. * Enable the branch type by default for the Arch LBR. */ reg->reg |= X86_BR_TYPE_SAVE; return 0; } /* * The first 9 bits (LBR_SEL_MASK) in LBR_SELECT operate * in suppress mode. So LBR_SELECT should be set to * (~mask & LBR_SEL_MASK) | (mask & ~LBR_SEL_MASK) * But the 10th bit LBR_CALL_STACK does not operate * in suppress mode. */ reg->config = mask ^ (x86_pmu.lbr_sel_mask & ~LBR_CALL_STACK); if ((br_type & PERF_SAMPLE_BRANCH_NO_CYCLES) && (br_type & PERF_SAMPLE_BRANCH_NO_FLAGS) && x86_pmu.lbr_has_info) reg->config |= LBR_NO_INFO; return 0; } int intel_pmu_setup_lbr_filter(struct perf_event *event) { int ret = 0; /* * no LBR on this PMU */ if (!x86_pmu.lbr_nr) return -EOPNOTSUPP; /* * setup SW LBR filter */ ret = intel_pmu_setup_sw_lbr_filter(event); if (ret) return ret; /* * setup HW LBR filter, if any */ if (x86_pmu.lbr_sel_map) ret = intel_pmu_setup_hw_lbr_filter(event); return ret; } enum { ARCH_LBR_BR_TYPE_JCC = 0, ARCH_LBR_BR_TYPE_NEAR_IND_JMP = 1, ARCH_LBR_BR_TYPE_NEAR_REL_JMP = 2, ARCH_LBR_BR_TYPE_NEAR_IND_CALL = 3, ARCH_LBR_BR_TYPE_NEAR_REL_CALL = 4, ARCH_LBR_BR_TYPE_NEAR_RET = 5, ARCH_LBR_BR_TYPE_KNOWN_MAX = ARCH_LBR_BR_TYPE_NEAR_RET, ARCH_LBR_BR_TYPE_MAP_MAX = 16, }; static const int arch_lbr_br_type_map[ARCH_LBR_BR_TYPE_MAP_MAX] = { [ARCH_LBR_BR_TYPE_JCC] = X86_BR_JCC, [ARCH_LBR_BR_TYPE_NEAR_IND_JMP] = X86_BR_IND_JMP, [ARCH_LBR_BR_TYPE_NEAR_REL_JMP] = X86_BR_JMP, [ARCH_LBR_BR_TYPE_NEAR_IND_CALL] = X86_BR_IND_CALL, [ARCH_LBR_BR_TYPE_NEAR_REL_CALL] = X86_BR_CALL, [ARCH_LBR_BR_TYPE_NEAR_RET] = X86_BR_RET, }; /* * implement actual branch filter based on user demand. * Hardware may not exactly satisfy that request, thus * we need to inspect opcodes. Mismatched branches are * discarded. Therefore, the number of branches returned * in PERF_SAMPLE_BRANCH_STACK sample may vary. */ static void intel_pmu_lbr_filter(struct cpu_hw_events *cpuc) { u64 from, to; int br_sel = cpuc->br_sel; int i, j, type, to_plm; bool compress = false; /* if sampling all branches, then nothing to filter */ if (((br_sel & X86_BR_ALL) == X86_BR_ALL) && ((br_sel & X86_BR_TYPE_SAVE) != X86_BR_TYPE_SAVE)) return; for (i = 0; i < cpuc->lbr_stack.nr; i++) { from = cpuc->lbr_entries[i].from; to = cpuc->lbr_entries[i].to; type = cpuc->lbr_entries[i].type; /* * Parse the branch type recorded in LBR_x_INFO MSR. * Doesn't support OTHER_BRANCH decoding for now. * OTHER_BRANCH branch type still rely on software decoding. */ if (static_cpu_has(X86_FEATURE_ARCH_LBR) && type <= ARCH_LBR_BR_TYPE_KNOWN_MAX) { to_plm = kernel_ip(to) ? X86_BR_KERNEL : X86_BR_USER; type = arch_lbr_br_type_map[type] | to_plm; } else type = branch_type(from, to, cpuc->lbr_entries[i].abort); if (type != X86_BR_NONE && (br_sel & X86_BR_ANYTX)) { if (cpuc->lbr_entries[i].in_tx) type |= X86_BR_IN_TX; else type |= X86_BR_NO_TX; } /* if type does not correspond, then discard */ if (type == X86_BR_NONE || (br_sel & type) != type) { cpuc->lbr_entries[i].from = 0; compress = true; } if ((br_sel & X86_BR_TYPE_SAVE) == X86_BR_TYPE_SAVE) cpuc->lbr_entries[i].type = common_branch_type(type); } if (!compress) return; /* remove all entries with from=0 */ for (i = 0; i < cpuc->lbr_stack.nr; ) { if (!cpuc->lbr_entries[i].from) { j = i; while (++j < cpuc->lbr_stack.nr) cpuc->lbr_entries[j-1] = cpuc->lbr_entries[j]; cpuc->lbr_stack.nr--; if (!cpuc->lbr_entries[i].from) continue; } i++; } } void intel_pmu_store_pebs_lbrs(struct lbr_entry *lbr) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* Cannot get TOS for large PEBS and Arch LBR */ if (static_cpu_has(X86_FEATURE_ARCH_LBR) || (cpuc->n_pebs == cpuc->n_large_pebs)) cpuc->lbr_stack.hw_idx = -1ULL; else cpuc->lbr_stack.hw_idx = intel_pmu_lbr_tos(); intel_pmu_store_lbr(cpuc, lbr); intel_pmu_lbr_filter(cpuc); } /* * Map interface branch filters onto LBR filters */ static const int nhm_lbr_sel_map[PERF_SAMPLE_BRANCH_MAX_SHIFT] = { [PERF_SAMPLE_BRANCH_ANY_SHIFT] = LBR_ANY, [PERF_SAMPLE_BRANCH_USER_SHIFT] = LBR_USER, [PERF_SAMPLE_BRANCH_KERNEL_SHIFT] = LBR_KERNEL, [PERF_SAMPLE_BRANCH_HV_SHIFT] = LBR_IGN, [PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT] = LBR_RETURN | LBR_REL_JMP | LBR_IND_JMP | LBR_FAR, /* * NHM/WSM erratum: must include REL_JMP+IND_JMP to get CALL branches */ [PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT] = LBR_REL_CALL | LBR_IND_CALL | LBR_REL_JMP | LBR_IND_JMP | LBR_FAR, /* * NHM/WSM erratum: must include IND_JMP to capture IND_CALL */ [PERF_SAMPLE_BRANCH_IND_CALL_SHIFT] = LBR_IND_CALL | LBR_IND_JMP, [PERF_SAMPLE_BRANCH_COND_SHIFT] = LBR_JCC, [PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT] = LBR_IND_JMP, }; static const int snb_lbr_sel_map[PERF_SAMPLE_BRANCH_MAX_SHIFT] = { [PERF_SAMPLE_BRANCH_ANY_SHIFT] = LBR_ANY, [PERF_SAMPLE_BRANCH_USER_SHIFT] = LBR_USER, [PERF_SAMPLE_BRANCH_KERNEL_SHIFT] = LBR_KERNEL, [PERF_SAMPLE_BRANCH_HV_SHIFT] = LBR_IGN, [PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT] = LBR_RETURN | LBR_FAR, [PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT] = LBR_REL_CALL | LBR_IND_CALL | LBR_FAR, [PERF_SAMPLE_BRANCH_IND_CALL_SHIFT] = LBR_IND_CALL, [PERF_SAMPLE_BRANCH_COND_SHIFT] = LBR_JCC, [PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT] = LBR_IND_JMP, [PERF_SAMPLE_BRANCH_CALL_SHIFT] = LBR_REL_CALL, }; static const int hsw_lbr_sel_map[PERF_SAMPLE_BRANCH_MAX_SHIFT] = { [PERF_SAMPLE_BRANCH_ANY_SHIFT] = LBR_ANY, [PERF_SAMPLE_BRANCH_USER_SHIFT] = LBR_USER, [PERF_SAMPLE_BRANCH_KERNEL_SHIFT] = LBR_KERNEL, [PERF_SAMPLE_BRANCH_HV_SHIFT] = LBR_IGN, [PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT] = LBR_RETURN | LBR_FAR, [PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT] = LBR_REL_CALL | LBR_IND_CALL | LBR_FAR, [PERF_SAMPLE_BRANCH_IND_CALL_SHIFT] = LBR_IND_CALL, [PERF_SAMPLE_BRANCH_COND_SHIFT] = LBR_JCC, [PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT] = LBR_REL_CALL | LBR_IND_CALL | LBR_RETURN | LBR_CALL_STACK, [PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT] = LBR_IND_JMP, [PERF_SAMPLE_BRANCH_CALL_SHIFT] = LBR_REL_CALL, }; static int arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_MAX_SHIFT] = { [PERF_SAMPLE_BRANCH_ANY_SHIFT] = ARCH_LBR_ANY, [PERF_SAMPLE_BRANCH_USER_SHIFT] = ARCH_LBR_USER, [PERF_SAMPLE_BRANCH_KERNEL_SHIFT] = ARCH_LBR_KERNEL, [PERF_SAMPLE_BRANCH_HV_SHIFT] = LBR_IGN, [PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT] = ARCH_LBR_RETURN | ARCH_LBR_OTHER_BRANCH, [PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT] = ARCH_LBR_REL_CALL | ARCH_LBR_IND_CALL | ARCH_LBR_OTHER_BRANCH, [PERF_SAMPLE_BRANCH_IND_CALL_SHIFT] = ARCH_LBR_IND_CALL, [PERF_SAMPLE_BRANCH_COND_SHIFT] = ARCH_LBR_JCC, [PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT] = ARCH_LBR_REL_CALL | ARCH_LBR_IND_CALL | ARCH_LBR_RETURN | ARCH_LBR_CALL_STACK, [PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT] = ARCH_LBR_IND_JMP, [PERF_SAMPLE_BRANCH_CALL_SHIFT] = ARCH_LBR_REL_CALL, }; /* core */ void __init intel_pmu_lbr_init_core(void) { x86_pmu.lbr_nr = 4; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_CORE_FROM; x86_pmu.lbr_to = MSR_LBR_CORE_TO; /* * SW branch filter usage: * - compensate for lack of HW filter */ } /* nehalem/westmere */ void __init intel_pmu_lbr_init_nhm(void) { x86_pmu.lbr_nr = 16; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_NHM_FROM; x86_pmu.lbr_to = MSR_LBR_NHM_TO; x86_pmu.lbr_sel_mask = LBR_SEL_MASK; x86_pmu.lbr_sel_map = nhm_lbr_sel_map; /* * SW branch filter usage: * - workaround LBR_SEL errata (see above) * - support syscall, sysret capture. * That requires LBR_FAR but that means far * jmp need to be filtered out */ } /* sandy bridge */ void __init intel_pmu_lbr_init_snb(void) { x86_pmu.lbr_nr = 16; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_NHM_FROM; x86_pmu.lbr_to = MSR_LBR_NHM_TO; x86_pmu.lbr_sel_mask = LBR_SEL_MASK; x86_pmu.lbr_sel_map = snb_lbr_sel_map; /* * SW branch filter usage: * - support syscall, sysret capture. * That requires LBR_FAR but that means far * jmp need to be filtered out */ } static inline struct kmem_cache * create_lbr_kmem_cache(size_t size, size_t align) { return kmem_cache_create("x86_lbr", size, align, 0, NULL); } /* haswell */ void intel_pmu_lbr_init_hsw(void) { size_t size = sizeof(struct x86_perf_task_context); x86_pmu.lbr_nr = 16; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_NHM_FROM; x86_pmu.lbr_to = MSR_LBR_NHM_TO; x86_pmu.lbr_sel_mask = LBR_SEL_MASK; x86_pmu.lbr_sel_map = hsw_lbr_sel_map; x86_get_pmu(smp_processor_id())->task_ctx_cache = create_lbr_kmem_cache(size, 0); } /* skylake */ __init void intel_pmu_lbr_init_skl(void) { size_t size = sizeof(struct x86_perf_task_context); x86_pmu.lbr_nr = 32; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_NHM_FROM; x86_pmu.lbr_to = MSR_LBR_NHM_TO; x86_pmu.lbr_info = MSR_LBR_INFO_0; x86_pmu.lbr_sel_mask = LBR_SEL_MASK; x86_pmu.lbr_sel_map = hsw_lbr_sel_map; x86_get_pmu(smp_processor_id())->task_ctx_cache = create_lbr_kmem_cache(size, 0); /* * SW branch filter usage: * - support syscall, sysret capture. * That requires LBR_FAR but that means far * jmp need to be filtered out */ } /* atom */ void __init intel_pmu_lbr_init_atom(void) { /* * only models starting at stepping 10 seems * to have an operational LBR which can freeze * on PMU interrupt */ if (boot_cpu_data.x86_model == 28 && boot_cpu_data.x86_stepping < 10) { pr_cont("LBR disabled due to erratum"); return; } x86_pmu.lbr_nr = 8; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_CORE_FROM; x86_pmu.lbr_to = MSR_LBR_CORE_TO; /* * SW branch filter usage: * - compensate for lack of HW filter */ } /* slm */ void __init intel_pmu_lbr_init_slm(void) { x86_pmu.lbr_nr = 8; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_CORE_FROM; x86_pmu.lbr_to = MSR_LBR_CORE_TO; x86_pmu.lbr_sel_mask = LBR_SEL_MASK; x86_pmu.lbr_sel_map = nhm_lbr_sel_map; /* * SW branch filter usage: * - compensate for lack of HW filter */ pr_cont("8-deep LBR, "); } /* Knights Landing */ void intel_pmu_lbr_init_knl(void) { x86_pmu.lbr_nr = 8; x86_pmu.lbr_tos = MSR_LBR_TOS; x86_pmu.lbr_from = MSR_LBR_NHM_FROM; x86_pmu.lbr_to = MSR_LBR_NHM_TO; x86_pmu.lbr_sel_mask = LBR_SEL_MASK; x86_pmu.lbr_sel_map = snb_lbr_sel_map; /* Knights Landing does have MISPREDICT bit */ if (x86_pmu.intel_cap.lbr_format == LBR_FORMAT_LIP) x86_pmu.intel_cap.lbr_format = LBR_FORMAT_EIP_FLAGS; } void intel_pmu_lbr_init(void) { switch (x86_pmu.intel_cap.lbr_format) { case LBR_FORMAT_EIP_FLAGS2: x86_pmu.lbr_has_tsx = 1; x86_pmu.lbr_from_flags = 1; if (lbr_from_signext_quirk_needed()) static_branch_enable(&lbr_from_quirk_key); break; case LBR_FORMAT_EIP_FLAGS: x86_pmu.lbr_from_flags = 1; break; case LBR_FORMAT_INFO: x86_pmu.lbr_has_tsx = 1; fallthrough; case LBR_FORMAT_INFO2: x86_pmu.lbr_has_info = 1; break; case LBR_FORMAT_TIME: x86_pmu.lbr_from_flags = 1; x86_pmu.lbr_to_cycles = 1; break; } if (x86_pmu.lbr_has_info) { /* * Only used in combination with baseline pebs. */ static_branch_enable(&x86_lbr_mispred); static_branch_enable(&x86_lbr_cycles); } } /* * LBR state size is variable based on the max number of registers. * This calculates the expected state size, which should match * what the hardware enumerates for the size of XFEATURE_LBR. */ static inline unsigned int get_lbr_state_size(void) { return sizeof(struct arch_lbr_state) + x86_pmu.lbr_nr * sizeof(struct lbr_entry); } static bool is_arch_lbr_xsave_available(void) { if (!boot_cpu_has(X86_FEATURE_XSAVES)) return false; /* * Check the LBR state with the corresponding software structure. * Disable LBR XSAVES support if the size doesn't match. */ if (xfeature_size(XFEATURE_LBR) == 0) return false; if (WARN_ON(xfeature_size(XFEATURE_LBR) != get_lbr_state_size())) return false; return true; } void __init intel_pmu_arch_lbr_init(void) { struct pmu *pmu = x86_get_pmu(smp_processor_id()); union cpuid28_eax eax; union cpuid28_ebx ebx; union cpuid28_ecx ecx; unsigned int unused_edx; bool arch_lbr_xsave; size_t size; u64 lbr_nr; /* Arch LBR Capabilities */ cpuid(28, &eax.full, &ebx.full, &ecx.full, &unused_edx); lbr_nr = fls(eax.split.lbr_depth_mask) * 8; if (!lbr_nr) goto clear_arch_lbr; /* Apply the max depth of Arch LBR */ if (wrmsrl_safe(MSR_ARCH_LBR_DEPTH, lbr_nr)) goto clear_arch_lbr; x86_pmu.lbr_depth_mask = eax.split.lbr_depth_mask; x86_pmu.lbr_deep_c_reset = eax.split.lbr_deep_c_reset; x86_pmu.lbr_lip = eax.split.lbr_lip; x86_pmu.lbr_cpl = ebx.split.lbr_cpl; x86_pmu.lbr_filter = ebx.split.lbr_filter; x86_pmu.lbr_call_stack = ebx.split.lbr_call_stack; x86_pmu.lbr_mispred = ecx.split.lbr_mispred; x86_pmu.lbr_timed_lbr = ecx.split.lbr_timed_lbr; x86_pmu.lbr_br_type = ecx.split.lbr_br_type; x86_pmu.lbr_nr = lbr_nr; if (x86_pmu.lbr_mispred) static_branch_enable(&x86_lbr_mispred); if (x86_pmu.lbr_timed_lbr) static_branch_enable(&x86_lbr_cycles); if (x86_pmu.lbr_br_type) static_branch_enable(&x86_lbr_type); arch_lbr_xsave = is_arch_lbr_xsave_available(); if (arch_lbr_xsave) { size = sizeof(struct x86_perf_task_context_arch_lbr_xsave) + get_lbr_state_size(); pmu->task_ctx_cache = create_lbr_kmem_cache(size, XSAVE_ALIGNMENT); } if (!pmu->task_ctx_cache) { arch_lbr_xsave = false; size = sizeof(struct x86_perf_task_context_arch_lbr) + lbr_nr * sizeof(struct lbr_entry); pmu->task_ctx_cache = create_lbr_kmem_cache(size, 0); } x86_pmu.lbr_from = MSR_ARCH_LBR_FROM_0; x86_pmu.lbr_to = MSR_ARCH_LBR_TO_0; x86_pmu.lbr_info = MSR_ARCH_LBR_INFO_0; /* LBR callstack requires both CPL and Branch Filtering support */ if (!x86_pmu.lbr_cpl || !x86_pmu.lbr_filter || !x86_pmu.lbr_call_stack) arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT] = LBR_NOT_SUPP; if (!x86_pmu.lbr_cpl) { arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_USER_SHIFT] = LBR_NOT_SUPP; arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_KERNEL_SHIFT] = LBR_NOT_SUPP; } else if (!x86_pmu.lbr_filter) { arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_ANY_SHIFT] = LBR_NOT_SUPP; arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT] = LBR_NOT_SUPP; arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT] = LBR_NOT_SUPP; arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_IND_CALL_SHIFT] = LBR_NOT_SUPP; arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_COND_SHIFT] = LBR_NOT_SUPP; arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT] = LBR_NOT_SUPP; arch_lbr_ctl_map[PERF_SAMPLE_BRANCH_CALL_SHIFT] = LBR_NOT_SUPP; } x86_pmu.lbr_ctl_mask = ARCH_LBR_CTL_MASK; x86_pmu.lbr_ctl_map = arch_lbr_ctl_map; if (!x86_pmu.lbr_cpl && !x86_pmu.lbr_filter) x86_pmu.lbr_ctl_map = NULL; x86_pmu.lbr_reset = intel_pmu_arch_lbr_reset; if (arch_lbr_xsave) { x86_pmu.lbr_save = intel_pmu_arch_lbr_xsaves; x86_pmu.lbr_restore = intel_pmu_arch_lbr_xrstors; x86_pmu.lbr_read = intel_pmu_arch_lbr_read_xsave; pr_cont("XSAVE "); } else { x86_pmu.lbr_save = intel_pmu_arch_lbr_save; x86_pmu.lbr_restore = intel_pmu_arch_lbr_restore; x86_pmu.lbr_read = intel_pmu_arch_lbr_read; } pr_cont("Architectural LBR, "); return; clear_arch_lbr: setup_clear_cpu_cap(X86_FEATURE_ARCH_LBR); } /** * x86_perf_get_lbr - get the LBR records information * * @lbr: the caller's memory to store the LBR records information */ void x86_perf_get_lbr(struct x86_pmu_lbr *lbr) { lbr->nr = x86_pmu.lbr_nr; lbr->from = x86_pmu.lbr_from; lbr->to = x86_pmu.lbr_to; lbr->info = x86_pmu.lbr_info; } EXPORT_SYMBOL_GPL(x86_perf_get_lbr); struct event_constraint vlbr_constraint = __EVENT_CONSTRAINT(INTEL_FIXED_VLBR_EVENT, (1ULL << INTEL_PMC_IDX_FIXED_VLBR), FIXED_EVENT_FLAGS, 1, 0, PERF_X86_EVENT_LBR_SELECT);
linux-master
arch/x86/events/intel/lbr.c
// SPDX-License-Identifier: GPL-2.0 /* Nehalem-EX/Westmere-EX uncore support */ #include "uncore.h" /* NHM-EX event control */ #define NHMEX_PMON_CTL_EV_SEL_MASK 0x000000ff #define NHMEX_PMON_CTL_UMASK_MASK 0x0000ff00 #define NHMEX_PMON_CTL_EN_BIT0 (1 << 0) #define NHMEX_PMON_CTL_EDGE_DET (1 << 18) #define NHMEX_PMON_CTL_PMI_EN (1 << 20) #define NHMEX_PMON_CTL_EN_BIT22 (1 << 22) #define NHMEX_PMON_CTL_INVERT (1 << 23) #define NHMEX_PMON_CTL_TRESH_MASK 0xff000000 #define NHMEX_PMON_RAW_EVENT_MASK (NHMEX_PMON_CTL_EV_SEL_MASK | \ NHMEX_PMON_CTL_UMASK_MASK | \ NHMEX_PMON_CTL_EDGE_DET | \ NHMEX_PMON_CTL_INVERT | \ NHMEX_PMON_CTL_TRESH_MASK) /* NHM-EX Ubox */ #define NHMEX_U_MSR_PMON_GLOBAL_CTL 0xc00 #define NHMEX_U_MSR_PMON_CTR 0xc11 #define NHMEX_U_MSR_PMON_EV_SEL 0xc10 #define NHMEX_U_PMON_GLOBAL_EN (1 << 0) #define NHMEX_U_PMON_GLOBAL_PMI_CORE_SEL 0x0000001e #define NHMEX_U_PMON_GLOBAL_EN_ALL (1 << 28) #define NHMEX_U_PMON_GLOBAL_RST_ALL (1 << 29) #define NHMEX_U_PMON_GLOBAL_FRZ_ALL (1 << 31) #define NHMEX_U_PMON_RAW_EVENT_MASK \ (NHMEX_PMON_CTL_EV_SEL_MASK | \ NHMEX_PMON_CTL_EDGE_DET) /* NHM-EX Cbox */ #define NHMEX_C0_MSR_PMON_GLOBAL_CTL 0xd00 #define NHMEX_C0_MSR_PMON_CTR0 0xd11 #define NHMEX_C0_MSR_PMON_EV_SEL0 0xd10 #define NHMEX_C_MSR_OFFSET 0x20 /* NHM-EX Bbox */ #define NHMEX_B0_MSR_PMON_GLOBAL_CTL 0xc20 #define NHMEX_B0_MSR_PMON_CTR0 0xc31 #define NHMEX_B0_MSR_PMON_CTL0 0xc30 #define NHMEX_B_MSR_OFFSET 0x40 #define NHMEX_B0_MSR_MATCH 0xe45 #define NHMEX_B0_MSR_MASK 0xe46 #define NHMEX_B1_MSR_MATCH 0xe4d #define NHMEX_B1_MSR_MASK 0xe4e #define NHMEX_B_PMON_CTL_EN (1 << 0) #define NHMEX_B_PMON_CTL_EV_SEL_SHIFT 1 #define NHMEX_B_PMON_CTL_EV_SEL_MASK \ (0x1f << NHMEX_B_PMON_CTL_EV_SEL_SHIFT) #define NHMEX_B_PMON_CTR_SHIFT 6 #define NHMEX_B_PMON_CTR_MASK \ (0x3 << NHMEX_B_PMON_CTR_SHIFT) #define NHMEX_B_PMON_RAW_EVENT_MASK \ (NHMEX_B_PMON_CTL_EV_SEL_MASK | \ NHMEX_B_PMON_CTR_MASK) /* NHM-EX Sbox */ #define NHMEX_S0_MSR_PMON_GLOBAL_CTL 0xc40 #define NHMEX_S0_MSR_PMON_CTR0 0xc51 #define NHMEX_S0_MSR_PMON_CTL0 0xc50 #define NHMEX_S_MSR_OFFSET 0x80 #define NHMEX_S0_MSR_MM_CFG 0xe48 #define NHMEX_S0_MSR_MATCH 0xe49 #define NHMEX_S0_MSR_MASK 0xe4a #define NHMEX_S1_MSR_MM_CFG 0xe58 #define NHMEX_S1_MSR_MATCH 0xe59 #define NHMEX_S1_MSR_MASK 0xe5a #define NHMEX_S_PMON_MM_CFG_EN (0x1ULL << 63) #define NHMEX_S_EVENT_TO_R_PROG_EV 0 /* NHM-EX Mbox */ #define NHMEX_M0_MSR_GLOBAL_CTL 0xca0 #define NHMEX_M0_MSR_PMU_DSP 0xca5 #define NHMEX_M0_MSR_PMU_ISS 0xca6 #define NHMEX_M0_MSR_PMU_MAP 0xca7 #define NHMEX_M0_MSR_PMU_MSC_THR 0xca8 #define NHMEX_M0_MSR_PMU_PGT 0xca9 #define NHMEX_M0_MSR_PMU_PLD 0xcaa #define NHMEX_M0_MSR_PMU_ZDP_CTL_FVC 0xcab #define NHMEX_M0_MSR_PMU_CTL0 0xcb0 #define NHMEX_M0_MSR_PMU_CNT0 0xcb1 #define NHMEX_M_MSR_OFFSET 0x40 #define NHMEX_M0_MSR_PMU_MM_CFG 0xe54 #define NHMEX_M1_MSR_PMU_MM_CFG 0xe5c #define NHMEX_M_PMON_MM_CFG_EN (1ULL << 63) #define NHMEX_M_PMON_ADDR_MATCH_MASK 0x3ffffffffULL #define NHMEX_M_PMON_ADDR_MASK_MASK 0x7ffffffULL #define NHMEX_M_PMON_ADDR_MASK_SHIFT 34 #define NHMEX_M_PMON_CTL_EN (1 << 0) #define NHMEX_M_PMON_CTL_PMI_EN (1 << 1) #define NHMEX_M_PMON_CTL_COUNT_MODE_SHIFT 2 #define NHMEX_M_PMON_CTL_COUNT_MODE_MASK \ (0x3 << NHMEX_M_PMON_CTL_COUNT_MODE_SHIFT) #define NHMEX_M_PMON_CTL_STORAGE_MODE_SHIFT 4 #define NHMEX_M_PMON_CTL_STORAGE_MODE_MASK \ (0x3 << NHMEX_M_PMON_CTL_STORAGE_MODE_SHIFT) #define NHMEX_M_PMON_CTL_WRAP_MODE (1 << 6) #define NHMEX_M_PMON_CTL_FLAG_MODE (1 << 7) #define NHMEX_M_PMON_CTL_INC_SEL_SHIFT 9 #define NHMEX_M_PMON_CTL_INC_SEL_MASK \ (0x1f << NHMEX_M_PMON_CTL_INC_SEL_SHIFT) #define NHMEX_M_PMON_CTL_SET_FLAG_SEL_SHIFT 19 #define NHMEX_M_PMON_CTL_SET_FLAG_SEL_MASK \ (0x7 << NHMEX_M_PMON_CTL_SET_FLAG_SEL_SHIFT) #define NHMEX_M_PMON_RAW_EVENT_MASK \ (NHMEX_M_PMON_CTL_COUNT_MODE_MASK | \ NHMEX_M_PMON_CTL_STORAGE_MODE_MASK | \ NHMEX_M_PMON_CTL_WRAP_MODE | \ NHMEX_M_PMON_CTL_FLAG_MODE | \ NHMEX_M_PMON_CTL_INC_SEL_MASK | \ NHMEX_M_PMON_CTL_SET_FLAG_SEL_MASK) #define NHMEX_M_PMON_ZDP_CTL_FVC_MASK (((1 << 11) - 1) | (1 << 23)) #define NHMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(n) (0x7ULL << (11 + 3 * (n))) #define WSMEX_M_PMON_ZDP_CTL_FVC_MASK (((1 << 12) - 1) | (1 << 24)) #define WSMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(n) (0x7ULL << (12 + 3 * (n))) /* * use the 9~13 bits to select event If the 7th bit is not set, * otherwise use the 19~21 bits to select event. */ #define MBOX_INC_SEL(x) ((x) << NHMEX_M_PMON_CTL_INC_SEL_SHIFT) #define MBOX_SET_FLAG_SEL(x) (((x) << NHMEX_M_PMON_CTL_SET_FLAG_SEL_SHIFT) | \ NHMEX_M_PMON_CTL_FLAG_MODE) #define MBOX_INC_SEL_MASK (NHMEX_M_PMON_CTL_INC_SEL_MASK | \ NHMEX_M_PMON_CTL_FLAG_MODE) #define MBOX_SET_FLAG_SEL_MASK (NHMEX_M_PMON_CTL_SET_FLAG_SEL_MASK | \ NHMEX_M_PMON_CTL_FLAG_MODE) #define MBOX_INC_SEL_EXTAR_REG(c, r) \ EVENT_EXTRA_REG(MBOX_INC_SEL(c), NHMEX_M0_MSR_PMU_##r, \ MBOX_INC_SEL_MASK, (u64)-1, NHMEX_M_##r) #define MBOX_SET_FLAG_SEL_EXTRA_REG(c, r) \ EVENT_EXTRA_REG(MBOX_SET_FLAG_SEL(c), NHMEX_M0_MSR_PMU_##r, \ MBOX_SET_FLAG_SEL_MASK, \ (u64)-1, NHMEX_M_##r) /* NHM-EX Rbox */ #define NHMEX_R_MSR_GLOBAL_CTL 0xe00 #define NHMEX_R_MSR_PMON_CTL0 0xe10 #define NHMEX_R_MSR_PMON_CNT0 0xe11 #define NHMEX_R_MSR_OFFSET 0x20 #define NHMEX_R_MSR_PORTN_QLX_CFG(n) \ ((n) < 4 ? (0xe0c + (n)) : (0xe2c + (n) - 4)) #define NHMEX_R_MSR_PORTN_IPERF_CFG0(n) (0xe04 + (n)) #define NHMEX_R_MSR_PORTN_IPERF_CFG1(n) (0xe24 + (n)) #define NHMEX_R_MSR_PORTN_XBR_OFFSET(n) \ (((n) < 4 ? 0 : 0x10) + (n) * 4) #define NHMEX_R_MSR_PORTN_XBR_SET1_MM_CFG(n) \ (0xe60 + NHMEX_R_MSR_PORTN_XBR_OFFSET(n)) #define NHMEX_R_MSR_PORTN_XBR_SET1_MATCH(n) \ (NHMEX_R_MSR_PORTN_XBR_SET1_MM_CFG(n) + 1) #define NHMEX_R_MSR_PORTN_XBR_SET1_MASK(n) \ (NHMEX_R_MSR_PORTN_XBR_SET1_MM_CFG(n) + 2) #define NHMEX_R_MSR_PORTN_XBR_SET2_MM_CFG(n) \ (0xe70 + NHMEX_R_MSR_PORTN_XBR_OFFSET(n)) #define NHMEX_R_MSR_PORTN_XBR_SET2_MATCH(n) \ (NHMEX_R_MSR_PORTN_XBR_SET2_MM_CFG(n) + 1) #define NHMEX_R_MSR_PORTN_XBR_SET2_MASK(n) \ (NHMEX_R_MSR_PORTN_XBR_SET2_MM_CFG(n) + 2) #define NHMEX_R_PMON_CTL_EN (1 << 0) #define NHMEX_R_PMON_CTL_EV_SEL_SHIFT 1 #define NHMEX_R_PMON_CTL_EV_SEL_MASK \ (0x1f << NHMEX_R_PMON_CTL_EV_SEL_SHIFT) #define NHMEX_R_PMON_CTL_PMI_EN (1 << 6) #define NHMEX_R_PMON_RAW_EVENT_MASK NHMEX_R_PMON_CTL_EV_SEL_MASK /* NHM-EX Wbox */ #define NHMEX_W_MSR_GLOBAL_CTL 0xc80 #define NHMEX_W_MSR_PMON_CNT0 0xc90 #define NHMEX_W_MSR_PMON_EVT_SEL0 0xc91 #define NHMEX_W_MSR_PMON_FIXED_CTR 0x394 #define NHMEX_W_MSR_PMON_FIXED_CTL 0x395 #define NHMEX_W_PMON_GLOBAL_FIXED_EN (1ULL << 31) #define __BITS_VALUE(x, i, n) ((typeof(x))(((x) >> ((i) * (n))) & \ ((1ULL << (n)) - 1))) DEFINE_UNCORE_FORMAT_ATTR(event, event, "config:0-7"); DEFINE_UNCORE_FORMAT_ATTR(event5, event, "config:1-5"); DEFINE_UNCORE_FORMAT_ATTR(umask, umask, "config:8-15"); DEFINE_UNCORE_FORMAT_ATTR(edge, edge, "config:18"); DEFINE_UNCORE_FORMAT_ATTR(inv, inv, "config:23"); DEFINE_UNCORE_FORMAT_ATTR(thresh8, thresh, "config:24-31"); DEFINE_UNCORE_FORMAT_ATTR(counter, counter, "config:6-7"); DEFINE_UNCORE_FORMAT_ATTR(match, match, "config1:0-63"); DEFINE_UNCORE_FORMAT_ATTR(mask, mask, "config2:0-63"); static void nhmex_uncore_msr_init_box(struct intel_uncore_box *box) { wrmsrl(NHMEX_U_MSR_PMON_GLOBAL_CTL, NHMEX_U_PMON_GLOBAL_EN_ALL); } static void nhmex_uncore_msr_exit_box(struct intel_uncore_box *box) { wrmsrl(NHMEX_U_MSR_PMON_GLOBAL_CTL, 0); } static void nhmex_uncore_msr_disable_box(struct intel_uncore_box *box) { unsigned msr = uncore_msr_box_ctl(box); u64 config; if (msr) { rdmsrl(msr, config); config &= ~((1ULL << uncore_num_counters(box)) - 1); /* WBox has a fixed counter */ if (uncore_msr_fixed_ctl(box)) config &= ~NHMEX_W_PMON_GLOBAL_FIXED_EN; wrmsrl(msr, config); } } static void nhmex_uncore_msr_enable_box(struct intel_uncore_box *box) { unsigned msr = uncore_msr_box_ctl(box); u64 config; if (msr) { rdmsrl(msr, config); config |= (1ULL << uncore_num_counters(box)) - 1; /* WBox has a fixed counter */ if (uncore_msr_fixed_ctl(box)) config |= NHMEX_W_PMON_GLOBAL_FIXED_EN; wrmsrl(msr, config); } } static void nhmex_uncore_msr_disable_event(struct intel_uncore_box *box, struct perf_event *event) { wrmsrl(event->hw.config_base, 0); } static void nhmex_uncore_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (hwc->idx == UNCORE_PMC_IDX_FIXED) wrmsrl(hwc->config_base, NHMEX_PMON_CTL_EN_BIT0); else if (box->pmu->type->event_mask & NHMEX_PMON_CTL_EN_BIT0) wrmsrl(hwc->config_base, hwc->config | NHMEX_PMON_CTL_EN_BIT22); else wrmsrl(hwc->config_base, hwc->config | NHMEX_PMON_CTL_EN_BIT0); } #define NHMEX_UNCORE_OPS_COMMON_INIT() \ .init_box = nhmex_uncore_msr_init_box, \ .exit_box = nhmex_uncore_msr_exit_box, \ .disable_box = nhmex_uncore_msr_disable_box, \ .enable_box = nhmex_uncore_msr_enable_box, \ .disable_event = nhmex_uncore_msr_disable_event, \ .read_counter = uncore_msr_read_counter static struct intel_uncore_ops nhmex_uncore_ops = { NHMEX_UNCORE_OPS_COMMON_INIT(), .enable_event = nhmex_uncore_msr_enable_event, }; static struct attribute *nhmex_uncore_ubox_formats_attr[] = { &format_attr_event.attr, &format_attr_edge.attr, NULL, }; static const struct attribute_group nhmex_uncore_ubox_format_group = { .name = "format", .attrs = nhmex_uncore_ubox_formats_attr, }; static struct intel_uncore_type nhmex_uncore_ubox = { .name = "ubox", .num_counters = 1, .num_boxes = 1, .perf_ctr_bits = 48, .event_ctl = NHMEX_U_MSR_PMON_EV_SEL, .perf_ctr = NHMEX_U_MSR_PMON_CTR, .event_mask = NHMEX_U_PMON_RAW_EVENT_MASK, .box_ctl = NHMEX_U_MSR_PMON_GLOBAL_CTL, .ops = &nhmex_uncore_ops, .format_group = &nhmex_uncore_ubox_format_group }; static struct attribute *nhmex_uncore_cbox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, NULL, }; static const struct attribute_group nhmex_uncore_cbox_format_group = { .name = "format", .attrs = nhmex_uncore_cbox_formats_attr, }; /* msr offset for each instance of cbox */ static unsigned nhmex_cbox_msr_offsets[] = { 0x0, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x240, 0x2c0, }; static struct intel_uncore_type nhmex_uncore_cbox = { .name = "cbox", .num_counters = 6, .num_boxes = 10, .perf_ctr_bits = 48, .event_ctl = NHMEX_C0_MSR_PMON_EV_SEL0, .perf_ctr = NHMEX_C0_MSR_PMON_CTR0, .event_mask = NHMEX_PMON_RAW_EVENT_MASK, .box_ctl = NHMEX_C0_MSR_PMON_GLOBAL_CTL, .msr_offsets = nhmex_cbox_msr_offsets, .pair_ctr_ctl = 1, .ops = &nhmex_uncore_ops, .format_group = &nhmex_uncore_cbox_format_group }; static struct uncore_event_desc nhmex_uncore_wbox_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0xff,umask=0"), { /* end: all zeroes */ }, }; static struct intel_uncore_type nhmex_uncore_wbox = { .name = "wbox", .num_counters = 4, .num_boxes = 1, .perf_ctr_bits = 48, .event_ctl = NHMEX_W_MSR_PMON_CNT0, .perf_ctr = NHMEX_W_MSR_PMON_EVT_SEL0, .fixed_ctr = NHMEX_W_MSR_PMON_FIXED_CTR, .fixed_ctl = NHMEX_W_MSR_PMON_FIXED_CTL, .event_mask = NHMEX_PMON_RAW_EVENT_MASK, .box_ctl = NHMEX_W_MSR_GLOBAL_CTL, .pair_ctr_ctl = 1, .event_descs = nhmex_uncore_wbox_events, .ops = &nhmex_uncore_ops, .format_group = &nhmex_uncore_cbox_format_group }; static int nhmex_bbox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; int ctr, ev_sel; ctr = (hwc->config & NHMEX_B_PMON_CTR_MASK) >> NHMEX_B_PMON_CTR_SHIFT; ev_sel = (hwc->config & NHMEX_B_PMON_CTL_EV_SEL_MASK) >> NHMEX_B_PMON_CTL_EV_SEL_SHIFT; /* events that do not use the match/mask registers */ if ((ctr == 0 && ev_sel > 0x3) || (ctr == 1 && ev_sel > 0x6) || (ctr == 2 && ev_sel != 0x4) || ctr == 3) return 0; if (box->pmu->pmu_idx == 0) reg1->reg = NHMEX_B0_MSR_MATCH; else reg1->reg = NHMEX_B1_MSR_MATCH; reg1->idx = 0; reg1->config = event->attr.config1; reg2->config = event->attr.config2; return 0; } static void nhmex_bbox_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; if (reg1->idx != EXTRA_REG_NONE) { wrmsrl(reg1->reg, reg1->config); wrmsrl(reg1->reg + 1, reg2->config); } wrmsrl(hwc->config_base, NHMEX_PMON_CTL_EN_BIT0 | (hwc->config & NHMEX_B_PMON_CTL_EV_SEL_MASK)); } /* * The Bbox has 4 counters, but each counter monitors different events. * Use bits 6-7 in the event config to select counter. */ static struct event_constraint nhmex_uncore_bbox_constraints[] = { EVENT_CONSTRAINT(0 , 1, 0xc0), EVENT_CONSTRAINT(0x40, 2, 0xc0), EVENT_CONSTRAINT(0x80, 4, 0xc0), EVENT_CONSTRAINT(0xc0, 8, 0xc0), EVENT_CONSTRAINT_END, }; static struct attribute *nhmex_uncore_bbox_formats_attr[] = { &format_attr_event5.attr, &format_attr_counter.attr, &format_attr_match.attr, &format_attr_mask.attr, NULL, }; static const struct attribute_group nhmex_uncore_bbox_format_group = { .name = "format", .attrs = nhmex_uncore_bbox_formats_attr, }; static struct intel_uncore_ops nhmex_uncore_bbox_ops = { NHMEX_UNCORE_OPS_COMMON_INIT(), .enable_event = nhmex_bbox_msr_enable_event, .hw_config = nhmex_bbox_hw_config, .get_constraint = uncore_get_constraint, .put_constraint = uncore_put_constraint, }; static struct intel_uncore_type nhmex_uncore_bbox = { .name = "bbox", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, .event_ctl = NHMEX_B0_MSR_PMON_CTL0, .perf_ctr = NHMEX_B0_MSR_PMON_CTR0, .event_mask = NHMEX_B_PMON_RAW_EVENT_MASK, .box_ctl = NHMEX_B0_MSR_PMON_GLOBAL_CTL, .msr_offset = NHMEX_B_MSR_OFFSET, .pair_ctr_ctl = 1, .num_shared_regs = 1, .constraints = nhmex_uncore_bbox_constraints, .ops = &nhmex_uncore_bbox_ops, .format_group = &nhmex_uncore_bbox_format_group }; static int nhmex_sbox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; /* only TO_R_PROG_EV event uses the match/mask register */ if ((hwc->config & NHMEX_PMON_CTL_EV_SEL_MASK) != NHMEX_S_EVENT_TO_R_PROG_EV) return 0; if (box->pmu->pmu_idx == 0) reg1->reg = NHMEX_S0_MSR_MM_CFG; else reg1->reg = NHMEX_S1_MSR_MM_CFG; reg1->idx = 0; reg1->config = event->attr.config1; reg2->config = event->attr.config2; return 0; } static void nhmex_sbox_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; if (reg1->idx != EXTRA_REG_NONE) { wrmsrl(reg1->reg, 0); wrmsrl(reg1->reg + 1, reg1->config); wrmsrl(reg1->reg + 2, reg2->config); wrmsrl(reg1->reg, NHMEX_S_PMON_MM_CFG_EN); } wrmsrl(hwc->config_base, hwc->config | NHMEX_PMON_CTL_EN_BIT22); } static struct attribute *nhmex_uncore_sbox_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_thresh8.attr, &format_attr_match.attr, &format_attr_mask.attr, NULL, }; static const struct attribute_group nhmex_uncore_sbox_format_group = { .name = "format", .attrs = nhmex_uncore_sbox_formats_attr, }; static struct intel_uncore_ops nhmex_uncore_sbox_ops = { NHMEX_UNCORE_OPS_COMMON_INIT(), .enable_event = nhmex_sbox_msr_enable_event, .hw_config = nhmex_sbox_hw_config, .get_constraint = uncore_get_constraint, .put_constraint = uncore_put_constraint, }; static struct intel_uncore_type nhmex_uncore_sbox = { .name = "sbox", .num_counters = 4, .num_boxes = 2, .perf_ctr_bits = 48, .event_ctl = NHMEX_S0_MSR_PMON_CTL0, .perf_ctr = NHMEX_S0_MSR_PMON_CTR0, .event_mask = NHMEX_PMON_RAW_EVENT_MASK, .box_ctl = NHMEX_S0_MSR_PMON_GLOBAL_CTL, .msr_offset = NHMEX_S_MSR_OFFSET, .pair_ctr_ctl = 1, .num_shared_regs = 1, .ops = &nhmex_uncore_sbox_ops, .format_group = &nhmex_uncore_sbox_format_group }; enum { EXTRA_REG_NHMEX_M_FILTER, EXTRA_REG_NHMEX_M_DSP, EXTRA_REG_NHMEX_M_ISS, EXTRA_REG_NHMEX_M_MAP, EXTRA_REG_NHMEX_M_MSC_THR, EXTRA_REG_NHMEX_M_PGT, EXTRA_REG_NHMEX_M_PLD, EXTRA_REG_NHMEX_M_ZDP_CTL_FVC, }; static struct extra_reg nhmex_uncore_mbox_extra_regs[] = { MBOX_INC_SEL_EXTAR_REG(0x0, DSP), MBOX_INC_SEL_EXTAR_REG(0x4, MSC_THR), MBOX_INC_SEL_EXTAR_REG(0x5, MSC_THR), MBOX_INC_SEL_EXTAR_REG(0x9, ISS), /* event 0xa uses two extra registers */ MBOX_INC_SEL_EXTAR_REG(0xa, ISS), MBOX_INC_SEL_EXTAR_REG(0xa, PLD), MBOX_INC_SEL_EXTAR_REG(0xb, PLD), /* events 0xd ~ 0x10 use the same extra register */ MBOX_INC_SEL_EXTAR_REG(0xd, ZDP_CTL_FVC), MBOX_INC_SEL_EXTAR_REG(0xe, ZDP_CTL_FVC), MBOX_INC_SEL_EXTAR_REG(0xf, ZDP_CTL_FVC), MBOX_INC_SEL_EXTAR_REG(0x10, ZDP_CTL_FVC), MBOX_INC_SEL_EXTAR_REG(0x16, PGT), MBOX_SET_FLAG_SEL_EXTRA_REG(0x0, DSP), MBOX_SET_FLAG_SEL_EXTRA_REG(0x1, ISS), MBOX_SET_FLAG_SEL_EXTRA_REG(0x5, PGT), MBOX_SET_FLAG_SEL_EXTRA_REG(0x6, MAP), EVENT_EXTRA_END }; /* Nehalem-EX or Westmere-EX ? */ static bool uncore_nhmex; static bool nhmex_mbox_get_shared_reg(struct intel_uncore_box *box, int idx, u64 config) { struct intel_uncore_extra_reg *er; unsigned long flags; bool ret = false; u64 mask; if (idx < EXTRA_REG_NHMEX_M_ZDP_CTL_FVC) { er = &box->shared_regs[idx]; raw_spin_lock_irqsave(&er->lock, flags); if (!atomic_read(&er->ref) || er->config == config) { atomic_inc(&er->ref); er->config = config; ret = true; } raw_spin_unlock_irqrestore(&er->lock, flags); return ret; } /* * The ZDP_CTL_FVC MSR has 4 fields which are used to control * events 0xd ~ 0x10. Besides these 4 fields, there are additional * fields which are shared. */ idx -= EXTRA_REG_NHMEX_M_ZDP_CTL_FVC; if (WARN_ON_ONCE(idx >= 4)) return false; /* mask of the shared fields */ if (uncore_nhmex) mask = NHMEX_M_PMON_ZDP_CTL_FVC_MASK; else mask = WSMEX_M_PMON_ZDP_CTL_FVC_MASK; er = &box->shared_regs[EXTRA_REG_NHMEX_M_ZDP_CTL_FVC]; raw_spin_lock_irqsave(&er->lock, flags); /* add mask of the non-shared field if it's in use */ if (__BITS_VALUE(atomic_read(&er->ref), idx, 8)) { if (uncore_nhmex) mask |= NHMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(idx); else mask |= WSMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(idx); } if (!atomic_read(&er->ref) || !((er->config ^ config) & mask)) { atomic_add(1 << (idx * 8), &er->ref); if (uncore_nhmex) mask = NHMEX_M_PMON_ZDP_CTL_FVC_MASK | NHMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(idx); else mask = WSMEX_M_PMON_ZDP_CTL_FVC_MASK | WSMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(idx); er->config &= ~mask; er->config |= (config & mask); ret = true; } raw_spin_unlock_irqrestore(&er->lock, flags); return ret; } static void nhmex_mbox_put_shared_reg(struct intel_uncore_box *box, int idx) { struct intel_uncore_extra_reg *er; if (idx < EXTRA_REG_NHMEX_M_ZDP_CTL_FVC) { er = &box->shared_regs[idx]; atomic_dec(&er->ref); return; } idx -= EXTRA_REG_NHMEX_M_ZDP_CTL_FVC; er = &box->shared_regs[EXTRA_REG_NHMEX_M_ZDP_CTL_FVC]; atomic_sub(1 << (idx * 8), &er->ref); } static u64 nhmex_mbox_alter_er(struct perf_event *event, int new_idx, bool modify) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; u64 idx, orig_idx = __BITS_VALUE(reg1->idx, 0, 8); u64 config = reg1->config; /* get the non-shared control bits and shift them */ idx = orig_idx - EXTRA_REG_NHMEX_M_ZDP_CTL_FVC; if (uncore_nhmex) config &= NHMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(idx); else config &= WSMEX_M_PMON_ZDP_CTL_FVC_EVENT_MASK(idx); if (new_idx > orig_idx) { idx = new_idx - orig_idx; config <<= 3 * idx; } else { idx = orig_idx - new_idx; config >>= 3 * idx; } /* add the shared control bits back */ if (uncore_nhmex) config |= NHMEX_M_PMON_ZDP_CTL_FVC_MASK & reg1->config; else config |= WSMEX_M_PMON_ZDP_CTL_FVC_MASK & reg1->config; config |= NHMEX_M_PMON_ZDP_CTL_FVC_MASK & reg1->config; if (modify) { /* adjust the main event selector */ if (new_idx > orig_idx) hwc->config += idx << NHMEX_M_PMON_CTL_INC_SEL_SHIFT; else hwc->config -= idx << NHMEX_M_PMON_CTL_INC_SEL_SHIFT; reg1->config = config; reg1->idx = ~0xff | new_idx; } return config; } static struct event_constraint * nhmex_mbox_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct hw_perf_event_extra *reg2 = &event->hw.branch_reg; int i, idx[2], alloc = 0; u64 config1 = reg1->config; idx[0] = __BITS_VALUE(reg1->idx, 0, 8); idx[1] = __BITS_VALUE(reg1->idx, 1, 8); again: for (i = 0; i < 2; i++) { if (!uncore_box_is_fake(box) && (reg1->alloc & (0x1 << i))) idx[i] = 0xff; if (idx[i] == 0xff) continue; if (!nhmex_mbox_get_shared_reg(box, idx[i], __BITS_VALUE(config1, i, 32))) goto fail; alloc |= (0x1 << i); } /* for the match/mask registers */ if (reg2->idx != EXTRA_REG_NONE && (uncore_box_is_fake(box) || !reg2->alloc) && !nhmex_mbox_get_shared_reg(box, reg2->idx, reg2->config)) goto fail; /* * If it's a fake box -- as per validate_{group,event}() we * shouldn't touch event state and we can avoid doing so * since both will only call get_event_constraints() once * on each event, this avoids the need for reg->alloc. */ if (!uncore_box_is_fake(box)) { if (idx[0] != 0xff && idx[0] != __BITS_VALUE(reg1->idx, 0, 8)) nhmex_mbox_alter_er(event, idx[0], true); reg1->alloc |= alloc; if (reg2->idx != EXTRA_REG_NONE) reg2->alloc = 1; } return NULL; fail: if (idx[0] != 0xff && !(alloc & 0x1) && idx[0] >= EXTRA_REG_NHMEX_M_ZDP_CTL_FVC) { /* * events 0xd ~ 0x10 are functional identical, but are * controlled by different fields in the ZDP_CTL_FVC * register. If we failed to take one field, try the * rest 3 choices. */ BUG_ON(__BITS_VALUE(reg1->idx, 1, 8) != 0xff); idx[0] -= EXTRA_REG_NHMEX_M_ZDP_CTL_FVC; idx[0] = (idx[0] + 1) % 4; idx[0] += EXTRA_REG_NHMEX_M_ZDP_CTL_FVC; if (idx[0] != __BITS_VALUE(reg1->idx, 0, 8)) { config1 = nhmex_mbox_alter_er(event, idx[0], false); goto again; } } if (alloc & 0x1) nhmex_mbox_put_shared_reg(box, idx[0]); if (alloc & 0x2) nhmex_mbox_put_shared_reg(box, idx[1]); return &uncore_constraint_empty; } static void nhmex_mbox_put_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct hw_perf_event_extra *reg2 = &event->hw.branch_reg; if (uncore_box_is_fake(box)) return; if (reg1->alloc & 0x1) nhmex_mbox_put_shared_reg(box, __BITS_VALUE(reg1->idx, 0, 8)); if (reg1->alloc & 0x2) nhmex_mbox_put_shared_reg(box, __BITS_VALUE(reg1->idx, 1, 8)); reg1->alloc = 0; if (reg2->alloc) { nhmex_mbox_put_shared_reg(box, reg2->idx); reg2->alloc = 0; } } static int nhmex_mbox_extra_reg_idx(struct extra_reg *er) { if (er->idx < EXTRA_REG_NHMEX_M_ZDP_CTL_FVC) return er->idx; return er->idx + (er->event >> NHMEX_M_PMON_CTL_INC_SEL_SHIFT) - 0xd; } static int nhmex_mbox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct intel_uncore_type *type = box->pmu->type; struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct hw_perf_event_extra *reg2 = &event->hw.branch_reg; struct extra_reg *er; unsigned msr; int reg_idx = 0; /* * The mbox events may require 2 extra MSRs at the most. But only * the lower 32 bits in these MSRs are significant, so we can use * config1 to pass two MSRs' config. */ for (er = nhmex_uncore_mbox_extra_regs; er->msr; er++) { if (er->event != (event->hw.config & er->config_mask)) continue; if (event->attr.config1 & ~er->valid_mask) return -EINVAL; msr = er->msr + type->msr_offset * box->pmu->pmu_idx; if (WARN_ON_ONCE(msr >= 0xffff || er->idx >= 0xff)) return -EINVAL; /* always use the 32~63 bits to pass the PLD config */ if (er->idx == EXTRA_REG_NHMEX_M_PLD) reg_idx = 1; else if (WARN_ON_ONCE(reg_idx > 0)) return -EINVAL; reg1->idx &= ~(0xff << (reg_idx * 8)); reg1->reg &= ~(0xffff << (reg_idx * 16)); reg1->idx |= nhmex_mbox_extra_reg_idx(er) << (reg_idx * 8); reg1->reg |= msr << (reg_idx * 16); reg1->config = event->attr.config1; reg_idx++; } /* * The mbox only provides ability to perform address matching * for the PLD events. */ if (reg_idx == 2) { reg2->idx = EXTRA_REG_NHMEX_M_FILTER; if (event->attr.config2 & NHMEX_M_PMON_MM_CFG_EN) reg2->config = event->attr.config2; else reg2->config = ~0ULL; if (box->pmu->pmu_idx == 0) reg2->reg = NHMEX_M0_MSR_PMU_MM_CFG; else reg2->reg = NHMEX_M1_MSR_PMU_MM_CFG; } return 0; } static u64 nhmex_mbox_shared_reg_config(struct intel_uncore_box *box, int idx) { struct intel_uncore_extra_reg *er; unsigned long flags; u64 config; if (idx < EXTRA_REG_NHMEX_M_ZDP_CTL_FVC) return box->shared_regs[idx].config; er = &box->shared_regs[EXTRA_REG_NHMEX_M_ZDP_CTL_FVC]; raw_spin_lock_irqsave(&er->lock, flags); config = er->config; raw_spin_unlock_irqrestore(&er->lock, flags); return config; } static void nhmex_mbox_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; int idx; idx = __BITS_VALUE(reg1->idx, 0, 8); if (idx != 0xff) wrmsrl(__BITS_VALUE(reg1->reg, 0, 16), nhmex_mbox_shared_reg_config(box, idx)); idx = __BITS_VALUE(reg1->idx, 1, 8); if (idx != 0xff) wrmsrl(__BITS_VALUE(reg1->reg, 1, 16), nhmex_mbox_shared_reg_config(box, idx)); if (reg2->idx != EXTRA_REG_NONE) { wrmsrl(reg2->reg, 0); if (reg2->config != ~0ULL) { wrmsrl(reg2->reg + 1, reg2->config & NHMEX_M_PMON_ADDR_MATCH_MASK); wrmsrl(reg2->reg + 2, NHMEX_M_PMON_ADDR_MASK_MASK & (reg2->config >> NHMEX_M_PMON_ADDR_MASK_SHIFT)); wrmsrl(reg2->reg, NHMEX_M_PMON_MM_CFG_EN); } } wrmsrl(hwc->config_base, hwc->config | NHMEX_PMON_CTL_EN_BIT0); } DEFINE_UNCORE_FORMAT_ATTR(count_mode, count_mode, "config:2-3"); DEFINE_UNCORE_FORMAT_ATTR(storage_mode, storage_mode, "config:4-5"); DEFINE_UNCORE_FORMAT_ATTR(wrap_mode, wrap_mode, "config:6"); DEFINE_UNCORE_FORMAT_ATTR(flag_mode, flag_mode, "config:7"); DEFINE_UNCORE_FORMAT_ATTR(inc_sel, inc_sel, "config:9-13"); DEFINE_UNCORE_FORMAT_ATTR(set_flag_sel, set_flag_sel, "config:19-21"); DEFINE_UNCORE_FORMAT_ATTR(filter_cfg_en, filter_cfg_en, "config2:63"); DEFINE_UNCORE_FORMAT_ATTR(filter_match, filter_match, "config2:0-33"); DEFINE_UNCORE_FORMAT_ATTR(filter_mask, filter_mask, "config2:34-61"); DEFINE_UNCORE_FORMAT_ATTR(dsp, dsp, "config1:0-31"); DEFINE_UNCORE_FORMAT_ATTR(thr, thr, "config1:0-31"); DEFINE_UNCORE_FORMAT_ATTR(fvc, fvc, "config1:0-31"); DEFINE_UNCORE_FORMAT_ATTR(pgt, pgt, "config1:0-31"); DEFINE_UNCORE_FORMAT_ATTR(map, map, "config1:0-31"); DEFINE_UNCORE_FORMAT_ATTR(iss, iss, "config1:0-31"); DEFINE_UNCORE_FORMAT_ATTR(pld, pld, "config1:32-63"); static struct attribute *nhmex_uncore_mbox_formats_attr[] = { &format_attr_count_mode.attr, &format_attr_storage_mode.attr, &format_attr_wrap_mode.attr, &format_attr_flag_mode.attr, &format_attr_inc_sel.attr, &format_attr_set_flag_sel.attr, &format_attr_filter_cfg_en.attr, &format_attr_filter_match.attr, &format_attr_filter_mask.attr, &format_attr_dsp.attr, &format_attr_thr.attr, &format_attr_fvc.attr, &format_attr_pgt.attr, &format_attr_map.attr, &format_attr_iss.attr, &format_attr_pld.attr, NULL, }; static const struct attribute_group nhmex_uncore_mbox_format_group = { .name = "format", .attrs = nhmex_uncore_mbox_formats_attr, }; static struct uncore_event_desc nhmex_uncore_mbox_events[] = { INTEL_UNCORE_EVENT_DESC(bbox_cmds_read, "inc_sel=0xd,fvc=0x2800"), INTEL_UNCORE_EVENT_DESC(bbox_cmds_write, "inc_sel=0xd,fvc=0x2820"), { /* end: all zeroes */ }, }; static struct uncore_event_desc wsmex_uncore_mbox_events[] = { INTEL_UNCORE_EVENT_DESC(bbox_cmds_read, "inc_sel=0xd,fvc=0x5000"), INTEL_UNCORE_EVENT_DESC(bbox_cmds_write, "inc_sel=0xd,fvc=0x5040"), { /* end: all zeroes */ }, }; static struct intel_uncore_ops nhmex_uncore_mbox_ops = { NHMEX_UNCORE_OPS_COMMON_INIT(), .enable_event = nhmex_mbox_msr_enable_event, .hw_config = nhmex_mbox_hw_config, .get_constraint = nhmex_mbox_get_constraint, .put_constraint = nhmex_mbox_put_constraint, }; static struct intel_uncore_type nhmex_uncore_mbox = { .name = "mbox", .num_counters = 6, .num_boxes = 2, .perf_ctr_bits = 48, .event_ctl = NHMEX_M0_MSR_PMU_CTL0, .perf_ctr = NHMEX_M0_MSR_PMU_CNT0, .event_mask = NHMEX_M_PMON_RAW_EVENT_MASK, .box_ctl = NHMEX_M0_MSR_GLOBAL_CTL, .msr_offset = NHMEX_M_MSR_OFFSET, .pair_ctr_ctl = 1, .num_shared_regs = 8, .event_descs = nhmex_uncore_mbox_events, .ops = &nhmex_uncore_mbox_ops, .format_group = &nhmex_uncore_mbox_format_group, }; static void nhmex_rbox_alter_er(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; /* adjust the main event selector and extra register index */ if (reg1->idx % 2) { reg1->idx--; hwc->config -= 1 << NHMEX_R_PMON_CTL_EV_SEL_SHIFT; } else { reg1->idx++; hwc->config += 1 << NHMEX_R_PMON_CTL_EV_SEL_SHIFT; } /* adjust extra register config */ switch (reg1->idx % 6) { case 2: /* shift the 8~15 bits to the 0~7 bits */ reg1->config >>= 8; break; case 3: /* shift the 0~7 bits to the 8~15 bits */ reg1->config <<= 8; break; } } /* * Each rbox has 4 event set which monitor PQI port 0~3 or 4~7. * An event set consists of 6 events, the 3rd and 4th events in * an event set use the same extra register. So an event set uses * 5 extra registers. */ static struct event_constraint * nhmex_rbox_get_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; struct intel_uncore_extra_reg *er; unsigned long flags; int idx, er_idx; u64 config1; bool ok = false; if (!uncore_box_is_fake(box) && reg1->alloc) return NULL; idx = reg1->idx % 6; config1 = reg1->config; again: er_idx = idx; /* the 3rd and 4th events use the same extra register */ if (er_idx > 2) er_idx--; er_idx += (reg1->idx / 6) * 5; er = &box->shared_regs[er_idx]; raw_spin_lock_irqsave(&er->lock, flags); if (idx < 2) { if (!atomic_read(&er->ref) || er->config == reg1->config) { atomic_inc(&er->ref); er->config = reg1->config; ok = true; } } else if (idx == 2 || idx == 3) { /* * these two events use different fields in a extra register, * the 0~7 bits and the 8~15 bits respectively. */ u64 mask = 0xff << ((idx - 2) * 8); if (!__BITS_VALUE(atomic_read(&er->ref), idx - 2, 8) || !((er->config ^ config1) & mask)) { atomic_add(1 << ((idx - 2) * 8), &er->ref); er->config &= ~mask; er->config |= config1 & mask; ok = true; } } else { if (!atomic_read(&er->ref) || (er->config == (hwc->config >> 32) && er->config1 == reg1->config && er->config2 == reg2->config)) { atomic_inc(&er->ref); er->config = (hwc->config >> 32); er->config1 = reg1->config; er->config2 = reg2->config; ok = true; } } raw_spin_unlock_irqrestore(&er->lock, flags); if (!ok) { /* * The Rbox events are always in pairs. The paired * events are functional identical, but use different * extra registers. If we failed to take an extra * register, try the alternative. */ idx ^= 1; if (idx != reg1->idx % 6) { if (idx == 2) config1 >>= 8; else if (idx == 3) config1 <<= 8; goto again; } } else { if (!uncore_box_is_fake(box)) { if (idx != reg1->idx % 6) nhmex_rbox_alter_er(box, event); reg1->alloc = 1; } return NULL; } return &uncore_constraint_empty; } static void nhmex_rbox_put_constraint(struct intel_uncore_box *box, struct perf_event *event) { struct intel_uncore_extra_reg *er; struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; int idx, er_idx; if (uncore_box_is_fake(box) || !reg1->alloc) return; idx = reg1->idx % 6; er_idx = idx; if (er_idx > 2) er_idx--; er_idx += (reg1->idx / 6) * 5; er = &box->shared_regs[er_idx]; if (idx == 2 || idx == 3) atomic_sub(1 << ((idx - 2) * 8), &er->ref); else atomic_dec(&er->ref); reg1->alloc = 0; } static int nhmex_rbox_hw_config(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &event->hw.extra_reg; struct hw_perf_event_extra *reg2 = &event->hw.branch_reg; int idx; idx = (event->hw.config & NHMEX_R_PMON_CTL_EV_SEL_MASK) >> NHMEX_R_PMON_CTL_EV_SEL_SHIFT; if (idx >= 0x18) return -EINVAL; reg1->idx = idx; reg1->config = event->attr.config1; switch (idx % 6) { case 4: case 5: hwc->config |= event->attr.config & (~0ULL << 32); reg2->config = event->attr.config2; break; } return 0; } static void nhmex_rbox_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct hw_perf_event_extra *reg1 = &hwc->extra_reg; struct hw_perf_event_extra *reg2 = &hwc->branch_reg; int idx, port; idx = reg1->idx; port = idx / 6 + box->pmu->pmu_idx * 4; switch (idx % 6) { case 0: wrmsrl(NHMEX_R_MSR_PORTN_IPERF_CFG0(port), reg1->config); break; case 1: wrmsrl(NHMEX_R_MSR_PORTN_IPERF_CFG1(port), reg1->config); break; case 2: case 3: wrmsrl(NHMEX_R_MSR_PORTN_QLX_CFG(port), uncore_shared_reg_config(box, 2 + (idx / 6) * 5)); break; case 4: wrmsrl(NHMEX_R_MSR_PORTN_XBR_SET1_MM_CFG(port), hwc->config >> 32); wrmsrl(NHMEX_R_MSR_PORTN_XBR_SET1_MATCH(port), reg1->config); wrmsrl(NHMEX_R_MSR_PORTN_XBR_SET1_MASK(port), reg2->config); break; case 5: wrmsrl(NHMEX_R_MSR_PORTN_XBR_SET2_MM_CFG(port), hwc->config >> 32); wrmsrl(NHMEX_R_MSR_PORTN_XBR_SET2_MATCH(port), reg1->config); wrmsrl(NHMEX_R_MSR_PORTN_XBR_SET2_MASK(port), reg2->config); break; } wrmsrl(hwc->config_base, NHMEX_PMON_CTL_EN_BIT0 | (hwc->config & NHMEX_R_PMON_CTL_EV_SEL_MASK)); } DEFINE_UNCORE_FORMAT_ATTR(xbr_mm_cfg, xbr_mm_cfg, "config:32-63"); DEFINE_UNCORE_FORMAT_ATTR(xbr_match, xbr_match, "config1:0-63"); DEFINE_UNCORE_FORMAT_ATTR(xbr_mask, xbr_mask, "config2:0-63"); DEFINE_UNCORE_FORMAT_ATTR(qlx_cfg, qlx_cfg, "config1:0-15"); DEFINE_UNCORE_FORMAT_ATTR(iperf_cfg, iperf_cfg, "config1:0-31"); static struct attribute *nhmex_uncore_rbox_formats_attr[] = { &format_attr_event5.attr, &format_attr_xbr_mm_cfg.attr, &format_attr_xbr_match.attr, &format_attr_xbr_mask.attr, &format_attr_qlx_cfg.attr, &format_attr_iperf_cfg.attr, NULL, }; static const struct attribute_group nhmex_uncore_rbox_format_group = { .name = "format", .attrs = nhmex_uncore_rbox_formats_attr, }; static struct uncore_event_desc nhmex_uncore_rbox_events[] = { INTEL_UNCORE_EVENT_DESC(qpi0_flit_send, "event=0x0,iperf_cfg=0x80000000"), INTEL_UNCORE_EVENT_DESC(qpi1_filt_send, "event=0x6,iperf_cfg=0x80000000"), INTEL_UNCORE_EVENT_DESC(qpi0_idle_filt, "event=0x0,iperf_cfg=0x40000000"), INTEL_UNCORE_EVENT_DESC(qpi1_idle_filt, "event=0x6,iperf_cfg=0x40000000"), INTEL_UNCORE_EVENT_DESC(qpi0_date_response, "event=0x0,iperf_cfg=0xc4"), INTEL_UNCORE_EVENT_DESC(qpi1_date_response, "event=0x6,iperf_cfg=0xc4"), { /* end: all zeroes */ }, }; static struct intel_uncore_ops nhmex_uncore_rbox_ops = { NHMEX_UNCORE_OPS_COMMON_INIT(), .enable_event = nhmex_rbox_msr_enable_event, .hw_config = nhmex_rbox_hw_config, .get_constraint = nhmex_rbox_get_constraint, .put_constraint = nhmex_rbox_put_constraint, }; static struct intel_uncore_type nhmex_uncore_rbox = { .name = "rbox", .num_counters = 8, .num_boxes = 2, .perf_ctr_bits = 48, .event_ctl = NHMEX_R_MSR_PMON_CTL0, .perf_ctr = NHMEX_R_MSR_PMON_CNT0, .event_mask = NHMEX_R_PMON_RAW_EVENT_MASK, .box_ctl = NHMEX_R_MSR_GLOBAL_CTL, .msr_offset = NHMEX_R_MSR_OFFSET, .pair_ctr_ctl = 1, .num_shared_regs = 20, .event_descs = nhmex_uncore_rbox_events, .ops = &nhmex_uncore_rbox_ops, .format_group = &nhmex_uncore_rbox_format_group }; static struct intel_uncore_type *nhmex_msr_uncores[] = { &nhmex_uncore_ubox, &nhmex_uncore_cbox, &nhmex_uncore_bbox, &nhmex_uncore_sbox, &nhmex_uncore_mbox, &nhmex_uncore_rbox, &nhmex_uncore_wbox, NULL, }; void nhmex_uncore_cpu_init(void) { if (boot_cpu_data.x86_model == 46) uncore_nhmex = true; else nhmex_uncore_mbox.event_descs = wsmex_uncore_mbox_events; if (nhmex_uncore_cbox.num_boxes > boot_cpu_data.x86_max_cores) nhmex_uncore_cbox.num_boxes = boot_cpu_data.x86_max_cores; uncore_msr_uncores = nhmex_msr_uncores; } /* end of Nehalem-EX uncore support */
linux-master
arch/x86/events/intel/uncore_nhmex.c
// SPDX-License-Identifier: GPL-2.0 /* Nehalem/SandBridge/Haswell/Broadwell/Skylake uncore support */ #include "uncore.h" #include "uncore_discovery.h" /* Uncore IMC PCI IDs */ #define PCI_DEVICE_ID_INTEL_SNB_IMC 0x0100 #define PCI_DEVICE_ID_INTEL_IVB_IMC 0x0154 #define PCI_DEVICE_ID_INTEL_IVB_E3_IMC 0x0150 #define PCI_DEVICE_ID_INTEL_HSW_IMC 0x0c00 #define PCI_DEVICE_ID_INTEL_HSW_U_IMC 0x0a04 #define PCI_DEVICE_ID_INTEL_BDW_IMC 0x1604 #define PCI_DEVICE_ID_INTEL_SKL_U_IMC 0x1904 #define PCI_DEVICE_ID_INTEL_SKL_Y_IMC 0x190c #define PCI_DEVICE_ID_INTEL_SKL_HD_IMC 0x1900 #define PCI_DEVICE_ID_INTEL_SKL_HQ_IMC 0x1910 #define PCI_DEVICE_ID_INTEL_SKL_SD_IMC 0x190f #define PCI_DEVICE_ID_INTEL_SKL_SQ_IMC 0x191f #define PCI_DEVICE_ID_INTEL_SKL_E3_IMC 0x1918 #define PCI_DEVICE_ID_INTEL_KBL_Y_IMC 0x590c #define PCI_DEVICE_ID_INTEL_KBL_U_IMC 0x5904 #define PCI_DEVICE_ID_INTEL_KBL_UQ_IMC 0x5914 #define PCI_DEVICE_ID_INTEL_KBL_SD_IMC 0x590f #define PCI_DEVICE_ID_INTEL_KBL_SQ_IMC 0x591f #define PCI_DEVICE_ID_INTEL_KBL_HQ_IMC 0x5910 #define PCI_DEVICE_ID_INTEL_KBL_WQ_IMC 0x5918 #define PCI_DEVICE_ID_INTEL_CFL_2U_IMC 0x3ecc #define PCI_DEVICE_ID_INTEL_CFL_4U_IMC 0x3ed0 #define PCI_DEVICE_ID_INTEL_CFL_4H_IMC 0x3e10 #define PCI_DEVICE_ID_INTEL_CFL_6H_IMC 0x3ec4 #define PCI_DEVICE_ID_INTEL_CFL_2S_D_IMC 0x3e0f #define PCI_DEVICE_ID_INTEL_CFL_4S_D_IMC 0x3e1f #define PCI_DEVICE_ID_INTEL_CFL_6S_D_IMC 0x3ec2 #define PCI_DEVICE_ID_INTEL_CFL_8S_D_IMC 0x3e30 #define PCI_DEVICE_ID_INTEL_CFL_4S_W_IMC 0x3e18 #define PCI_DEVICE_ID_INTEL_CFL_6S_W_IMC 0x3ec6 #define PCI_DEVICE_ID_INTEL_CFL_8S_W_IMC 0x3e31 #define PCI_DEVICE_ID_INTEL_CFL_4S_S_IMC 0x3e33 #define PCI_DEVICE_ID_INTEL_CFL_6S_S_IMC 0x3eca #define PCI_DEVICE_ID_INTEL_CFL_8S_S_IMC 0x3e32 #define PCI_DEVICE_ID_INTEL_AML_YD_IMC 0x590c #define PCI_DEVICE_ID_INTEL_AML_YQ_IMC 0x590d #define PCI_DEVICE_ID_INTEL_WHL_UQ_IMC 0x3ed0 #define PCI_DEVICE_ID_INTEL_WHL_4_UQ_IMC 0x3e34 #define PCI_DEVICE_ID_INTEL_WHL_UD_IMC 0x3e35 #define PCI_DEVICE_ID_INTEL_CML_H1_IMC 0x9b44 #define PCI_DEVICE_ID_INTEL_CML_H2_IMC 0x9b54 #define PCI_DEVICE_ID_INTEL_CML_H3_IMC 0x9b64 #define PCI_DEVICE_ID_INTEL_CML_U1_IMC 0x9b51 #define PCI_DEVICE_ID_INTEL_CML_U2_IMC 0x9b61 #define PCI_DEVICE_ID_INTEL_CML_U3_IMC 0x9b71 #define PCI_DEVICE_ID_INTEL_CML_S1_IMC 0x9b33 #define PCI_DEVICE_ID_INTEL_CML_S2_IMC 0x9b43 #define PCI_DEVICE_ID_INTEL_CML_S3_IMC 0x9b53 #define PCI_DEVICE_ID_INTEL_CML_S4_IMC 0x9b63 #define PCI_DEVICE_ID_INTEL_CML_S5_IMC 0x9b73 #define PCI_DEVICE_ID_INTEL_ICL_U_IMC 0x8a02 #define PCI_DEVICE_ID_INTEL_ICL_U2_IMC 0x8a12 #define PCI_DEVICE_ID_INTEL_TGL_U1_IMC 0x9a02 #define PCI_DEVICE_ID_INTEL_TGL_U2_IMC 0x9a04 #define PCI_DEVICE_ID_INTEL_TGL_U3_IMC 0x9a12 #define PCI_DEVICE_ID_INTEL_TGL_U4_IMC 0x9a14 #define PCI_DEVICE_ID_INTEL_TGL_H_IMC 0x9a36 #define PCI_DEVICE_ID_INTEL_RKL_1_IMC 0x4c43 #define PCI_DEVICE_ID_INTEL_RKL_2_IMC 0x4c53 #define PCI_DEVICE_ID_INTEL_ADL_1_IMC 0x4660 #define PCI_DEVICE_ID_INTEL_ADL_2_IMC 0x4641 #define PCI_DEVICE_ID_INTEL_ADL_3_IMC 0x4601 #define PCI_DEVICE_ID_INTEL_ADL_4_IMC 0x4602 #define PCI_DEVICE_ID_INTEL_ADL_5_IMC 0x4609 #define PCI_DEVICE_ID_INTEL_ADL_6_IMC 0x460a #define PCI_DEVICE_ID_INTEL_ADL_7_IMC 0x4621 #define PCI_DEVICE_ID_INTEL_ADL_8_IMC 0x4623 #define PCI_DEVICE_ID_INTEL_ADL_9_IMC 0x4629 #define PCI_DEVICE_ID_INTEL_ADL_10_IMC 0x4637 #define PCI_DEVICE_ID_INTEL_ADL_11_IMC 0x463b #define PCI_DEVICE_ID_INTEL_ADL_12_IMC 0x4648 #define PCI_DEVICE_ID_INTEL_ADL_13_IMC 0x4649 #define PCI_DEVICE_ID_INTEL_ADL_14_IMC 0x4650 #define PCI_DEVICE_ID_INTEL_ADL_15_IMC 0x4668 #define PCI_DEVICE_ID_INTEL_ADL_16_IMC 0x4670 #define PCI_DEVICE_ID_INTEL_ADL_17_IMC 0x4614 #define PCI_DEVICE_ID_INTEL_ADL_18_IMC 0x4617 #define PCI_DEVICE_ID_INTEL_ADL_19_IMC 0x4618 #define PCI_DEVICE_ID_INTEL_ADL_20_IMC 0x461B #define PCI_DEVICE_ID_INTEL_ADL_21_IMC 0x461C #define PCI_DEVICE_ID_INTEL_RPL_1_IMC 0xA700 #define PCI_DEVICE_ID_INTEL_RPL_2_IMC 0xA702 #define PCI_DEVICE_ID_INTEL_RPL_3_IMC 0xA706 #define PCI_DEVICE_ID_INTEL_RPL_4_IMC 0xA709 #define PCI_DEVICE_ID_INTEL_RPL_5_IMC 0xA701 #define PCI_DEVICE_ID_INTEL_RPL_6_IMC 0xA703 #define PCI_DEVICE_ID_INTEL_RPL_7_IMC 0xA704 #define PCI_DEVICE_ID_INTEL_RPL_8_IMC 0xA705 #define PCI_DEVICE_ID_INTEL_RPL_9_IMC 0xA706 #define PCI_DEVICE_ID_INTEL_RPL_10_IMC 0xA707 #define PCI_DEVICE_ID_INTEL_RPL_11_IMC 0xA708 #define PCI_DEVICE_ID_INTEL_RPL_12_IMC 0xA709 #define PCI_DEVICE_ID_INTEL_RPL_13_IMC 0xA70a #define PCI_DEVICE_ID_INTEL_RPL_14_IMC 0xA70b #define PCI_DEVICE_ID_INTEL_RPL_15_IMC 0xA715 #define PCI_DEVICE_ID_INTEL_RPL_16_IMC 0xA716 #define PCI_DEVICE_ID_INTEL_RPL_17_IMC 0xA717 #define PCI_DEVICE_ID_INTEL_RPL_18_IMC 0xA718 #define PCI_DEVICE_ID_INTEL_RPL_19_IMC 0xA719 #define PCI_DEVICE_ID_INTEL_RPL_20_IMC 0xA71A #define PCI_DEVICE_ID_INTEL_RPL_21_IMC 0xA71B #define PCI_DEVICE_ID_INTEL_RPL_22_IMC 0xA71C #define PCI_DEVICE_ID_INTEL_RPL_23_IMC 0xA728 #define PCI_DEVICE_ID_INTEL_RPL_24_IMC 0xA729 #define PCI_DEVICE_ID_INTEL_RPL_25_IMC 0xA72A #define PCI_DEVICE_ID_INTEL_MTL_1_IMC 0x7d00 #define PCI_DEVICE_ID_INTEL_MTL_2_IMC 0x7d01 #define PCI_DEVICE_ID_INTEL_MTL_3_IMC 0x7d02 #define PCI_DEVICE_ID_INTEL_MTL_4_IMC 0x7d05 #define PCI_DEVICE_ID_INTEL_MTL_5_IMC 0x7d10 #define PCI_DEVICE_ID_INTEL_MTL_6_IMC 0x7d14 #define PCI_DEVICE_ID_INTEL_MTL_7_IMC 0x7d15 #define PCI_DEVICE_ID_INTEL_MTL_8_IMC 0x7d16 #define PCI_DEVICE_ID_INTEL_MTL_9_IMC 0x7d21 #define PCI_DEVICE_ID_INTEL_MTL_10_IMC 0x7d22 #define PCI_DEVICE_ID_INTEL_MTL_11_IMC 0x7d23 #define PCI_DEVICE_ID_INTEL_MTL_12_IMC 0x7d24 #define PCI_DEVICE_ID_INTEL_MTL_13_IMC 0x7d28 #define IMC_UNCORE_DEV(a) \ { \ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_##a##_IMC), \ .driver_data = UNCORE_PCI_DEV_DATA(SNB_PCI_UNCORE_IMC, 0), \ } /* SNB event control */ #define SNB_UNC_CTL_EV_SEL_MASK 0x000000ff #define SNB_UNC_CTL_UMASK_MASK 0x0000ff00 #define SNB_UNC_CTL_EDGE_DET (1 << 18) #define SNB_UNC_CTL_EN (1 << 22) #define SNB_UNC_CTL_INVERT (1 << 23) #define SNB_UNC_CTL_CMASK_MASK 0x1f000000 #define NHM_UNC_CTL_CMASK_MASK 0xff000000 #define NHM_UNC_FIXED_CTR_CTL_EN (1 << 0) #define SNB_UNC_RAW_EVENT_MASK (SNB_UNC_CTL_EV_SEL_MASK | \ SNB_UNC_CTL_UMASK_MASK | \ SNB_UNC_CTL_EDGE_DET | \ SNB_UNC_CTL_INVERT | \ SNB_UNC_CTL_CMASK_MASK) #define NHM_UNC_RAW_EVENT_MASK (SNB_UNC_CTL_EV_SEL_MASK | \ SNB_UNC_CTL_UMASK_MASK | \ SNB_UNC_CTL_EDGE_DET | \ SNB_UNC_CTL_INVERT | \ NHM_UNC_CTL_CMASK_MASK) /* SNB global control register */ #define SNB_UNC_PERF_GLOBAL_CTL 0x391 #define SNB_UNC_FIXED_CTR_CTRL 0x394 #define SNB_UNC_FIXED_CTR 0x395 /* SNB uncore global control */ #define SNB_UNC_GLOBAL_CTL_CORE_ALL ((1 << 4) - 1) #define SNB_UNC_GLOBAL_CTL_EN (1 << 29) /* SNB Cbo register */ #define SNB_UNC_CBO_0_PERFEVTSEL0 0x700 #define SNB_UNC_CBO_0_PER_CTR0 0x706 #define SNB_UNC_CBO_MSR_OFFSET 0x10 /* SNB ARB register */ #define SNB_UNC_ARB_PER_CTR0 0x3b0 #define SNB_UNC_ARB_PERFEVTSEL0 0x3b2 #define SNB_UNC_ARB_MSR_OFFSET 0x10 /* NHM global control register */ #define NHM_UNC_PERF_GLOBAL_CTL 0x391 #define NHM_UNC_FIXED_CTR 0x394 #define NHM_UNC_FIXED_CTR_CTRL 0x395 /* NHM uncore global control */ #define NHM_UNC_GLOBAL_CTL_EN_PC_ALL ((1ULL << 8) - 1) #define NHM_UNC_GLOBAL_CTL_EN_FC (1ULL << 32) /* NHM uncore register */ #define NHM_UNC_PERFEVTSEL0 0x3c0 #define NHM_UNC_UNCORE_PMC0 0x3b0 /* SKL uncore global control */ #define SKL_UNC_PERF_GLOBAL_CTL 0xe01 #define SKL_UNC_GLOBAL_CTL_CORE_ALL ((1 << 5) - 1) /* ICL Cbo register */ #define ICL_UNC_CBO_CONFIG 0x396 #define ICL_UNC_NUM_CBO_MASK 0xf #define ICL_UNC_CBO_0_PER_CTR0 0x702 #define ICL_UNC_CBO_MSR_OFFSET 0x8 /* ICL ARB register */ #define ICL_UNC_ARB_PER_CTR 0x3b1 #define ICL_UNC_ARB_PERFEVTSEL 0x3b3 /* ADL uncore global control */ #define ADL_UNC_PERF_GLOBAL_CTL 0x2ff0 #define ADL_UNC_FIXED_CTR_CTRL 0x2fde #define ADL_UNC_FIXED_CTR 0x2fdf /* ADL Cbo register */ #define ADL_UNC_CBO_0_PER_CTR0 0x2002 #define ADL_UNC_CBO_0_PERFEVTSEL0 0x2000 #define ADL_UNC_CTL_THRESHOLD 0x3f000000 #define ADL_UNC_RAW_EVENT_MASK (SNB_UNC_CTL_EV_SEL_MASK | \ SNB_UNC_CTL_UMASK_MASK | \ SNB_UNC_CTL_EDGE_DET | \ SNB_UNC_CTL_INVERT | \ ADL_UNC_CTL_THRESHOLD) /* ADL ARB register */ #define ADL_UNC_ARB_PER_CTR0 0x2FD2 #define ADL_UNC_ARB_PERFEVTSEL0 0x2FD0 #define ADL_UNC_ARB_MSR_OFFSET 0x8 /* MTL Cbo register */ #define MTL_UNC_CBO_0_PER_CTR0 0x2448 #define MTL_UNC_CBO_0_PERFEVTSEL0 0x2442 /* MTL HAC_ARB register */ #define MTL_UNC_HAC_ARB_CTR 0x2018 #define MTL_UNC_HAC_ARB_CTRL 0x2012 /* MTL ARB register */ #define MTL_UNC_ARB_CTR 0x2418 #define MTL_UNC_ARB_CTRL 0x2412 /* MTL cNCU register */ #define MTL_UNC_CNCU_FIXED_CTR 0x2408 #define MTL_UNC_CNCU_FIXED_CTRL 0x2402 #define MTL_UNC_CNCU_BOX_CTL 0x240e /* MTL sNCU register */ #define MTL_UNC_SNCU_FIXED_CTR 0x2008 #define MTL_UNC_SNCU_FIXED_CTRL 0x2002 #define MTL_UNC_SNCU_BOX_CTL 0x200e /* MTL HAC_CBO register */ #define MTL_UNC_HBO_CTR 0x2048 #define MTL_UNC_HBO_CTRL 0x2042 DEFINE_UNCORE_FORMAT_ATTR(event, event, "config:0-7"); DEFINE_UNCORE_FORMAT_ATTR(umask, umask, "config:8-15"); DEFINE_UNCORE_FORMAT_ATTR(chmask, chmask, "config:8-11"); DEFINE_UNCORE_FORMAT_ATTR(edge, edge, "config:18"); DEFINE_UNCORE_FORMAT_ATTR(inv, inv, "config:23"); DEFINE_UNCORE_FORMAT_ATTR(cmask5, cmask, "config:24-28"); DEFINE_UNCORE_FORMAT_ATTR(cmask8, cmask, "config:24-31"); DEFINE_UNCORE_FORMAT_ATTR(threshold, threshold, "config:24-29"); /* Sandy Bridge uncore support */ static void snb_uncore_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (hwc->idx < UNCORE_PMC_IDX_FIXED) wrmsrl(hwc->config_base, hwc->config | SNB_UNC_CTL_EN); else wrmsrl(hwc->config_base, SNB_UNC_CTL_EN); } static void snb_uncore_msr_disable_event(struct intel_uncore_box *box, struct perf_event *event) { wrmsrl(event->hw.config_base, 0); } static void snb_uncore_msr_init_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) { wrmsrl(SNB_UNC_PERF_GLOBAL_CTL, SNB_UNC_GLOBAL_CTL_EN | SNB_UNC_GLOBAL_CTL_CORE_ALL); } } static void snb_uncore_msr_enable_box(struct intel_uncore_box *box) { wrmsrl(SNB_UNC_PERF_GLOBAL_CTL, SNB_UNC_GLOBAL_CTL_EN | SNB_UNC_GLOBAL_CTL_CORE_ALL); } static void snb_uncore_msr_exit_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) wrmsrl(SNB_UNC_PERF_GLOBAL_CTL, 0); } static struct uncore_event_desc snb_uncore_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0xff,umask=0x00"), { /* end: all zeroes */ }, }; static struct attribute *snb_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_cmask5.attr, NULL, }; static const struct attribute_group snb_uncore_format_group = { .name = "format", .attrs = snb_uncore_formats_attr, }; static struct intel_uncore_ops snb_uncore_msr_ops = { .init_box = snb_uncore_msr_init_box, .enable_box = snb_uncore_msr_enable_box, .exit_box = snb_uncore_msr_exit_box, .disable_event = snb_uncore_msr_disable_event, .enable_event = snb_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, }; static struct event_constraint snb_uncore_arb_constraints[] = { UNCORE_EVENT_CONSTRAINT(0x80, 0x1), UNCORE_EVENT_CONSTRAINT(0x83, 0x1), EVENT_CONSTRAINT_END }; static struct intel_uncore_type snb_uncore_cbox = { .name = "cbox", .num_counters = 2, .num_boxes = 4, .perf_ctr_bits = 44, .fixed_ctr_bits = 48, .perf_ctr = SNB_UNC_CBO_0_PER_CTR0, .event_ctl = SNB_UNC_CBO_0_PERFEVTSEL0, .fixed_ctr = SNB_UNC_FIXED_CTR, .fixed_ctl = SNB_UNC_FIXED_CTR_CTRL, .single_fixed = 1, .event_mask = SNB_UNC_RAW_EVENT_MASK, .msr_offset = SNB_UNC_CBO_MSR_OFFSET, .ops = &snb_uncore_msr_ops, .format_group = &snb_uncore_format_group, .event_descs = snb_uncore_events, }; static struct intel_uncore_type snb_uncore_arb = { .name = "arb", .num_counters = 2, .num_boxes = 1, .perf_ctr_bits = 44, .perf_ctr = SNB_UNC_ARB_PER_CTR0, .event_ctl = SNB_UNC_ARB_PERFEVTSEL0, .event_mask = SNB_UNC_RAW_EVENT_MASK, .msr_offset = SNB_UNC_ARB_MSR_OFFSET, .constraints = snb_uncore_arb_constraints, .ops = &snb_uncore_msr_ops, .format_group = &snb_uncore_format_group, }; static struct intel_uncore_type *snb_msr_uncores[] = { &snb_uncore_cbox, &snb_uncore_arb, NULL, }; void snb_uncore_cpu_init(void) { uncore_msr_uncores = snb_msr_uncores; if (snb_uncore_cbox.num_boxes > boot_cpu_data.x86_max_cores) snb_uncore_cbox.num_boxes = boot_cpu_data.x86_max_cores; } static void skl_uncore_msr_init_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) { wrmsrl(SKL_UNC_PERF_GLOBAL_CTL, SNB_UNC_GLOBAL_CTL_EN | SKL_UNC_GLOBAL_CTL_CORE_ALL); } /* The 8th CBOX has different MSR space */ if (box->pmu->pmu_idx == 7) __set_bit(UNCORE_BOX_FLAG_CFL8_CBOX_MSR_OFFS, &box->flags); } static void skl_uncore_msr_enable_box(struct intel_uncore_box *box) { wrmsrl(SKL_UNC_PERF_GLOBAL_CTL, SNB_UNC_GLOBAL_CTL_EN | SKL_UNC_GLOBAL_CTL_CORE_ALL); } static void skl_uncore_msr_exit_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) wrmsrl(SKL_UNC_PERF_GLOBAL_CTL, 0); } static struct intel_uncore_ops skl_uncore_msr_ops = { .init_box = skl_uncore_msr_init_box, .enable_box = skl_uncore_msr_enable_box, .exit_box = skl_uncore_msr_exit_box, .disable_event = snb_uncore_msr_disable_event, .enable_event = snb_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, }; static struct intel_uncore_type skl_uncore_cbox = { .name = "cbox", .num_counters = 4, .num_boxes = 8, .perf_ctr_bits = 44, .fixed_ctr_bits = 48, .perf_ctr = SNB_UNC_CBO_0_PER_CTR0, .event_ctl = SNB_UNC_CBO_0_PERFEVTSEL0, .fixed_ctr = SNB_UNC_FIXED_CTR, .fixed_ctl = SNB_UNC_FIXED_CTR_CTRL, .single_fixed = 1, .event_mask = SNB_UNC_RAW_EVENT_MASK, .msr_offset = SNB_UNC_CBO_MSR_OFFSET, .ops = &skl_uncore_msr_ops, .format_group = &snb_uncore_format_group, .event_descs = snb_uncore_events, }; static struct intel_uncore_type *skl_msr_uncores[] = { &skl_uncore_cbox, &snb_uncore_arb, NULL, }; void skl_uncore_cpu_init(void) { uncore_msr_uncores = skl_msr_uncores; if (skl_uncore_cbox.num_boxes > boot_cpu_data.x86_max_cores) skl_uncore_cbox.num_boxes = boot_cpu_data.x86_max_cores; snb_uncore_arb.ops = &skl_uncore_msr_ops; } static struct intel_uncore_ops icl_uncore_msr_ops = { .disable_event = snb_uncore_msr_disable_event, .enable_event = snb_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, }; static struct intel_uncore_type icl_uncore_cbox = { .name = "cbox", .num_counters = 2, .perf_ctr_bits = 44, .perf_ctr = ICL_UNC_CBO_0_PER_CTR0, .event_ctl = SNB_UNC_CBO_0_PERFEVTSEL0, .event_mask = SNB_UNC_RAW_EVENT_MASK, .msr_offset = ICL_UNC_CBO_MSR_OFFSET, .ops = &icl_uncore_msr_ops, .format_group = &snb_uncore_format_group, }; static struct uncore_event_desc icl_uncore_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0xff"), { /* end: all zeroes */ }, }; static struct attribute *icl_uncore_clock_formats_attr[] = { &format_attr_event.attr, NULL, }; static struct attribute_group icl_uncore_clock_format_group = { .name = "format", .attrs = icl_uncore_clock_formats_attr, }; static struct intel_uncore_type icl_uncore_clockbox = { .name = "clock", .num_counters = 1, .num_boxes = 1, .fixed_ctr_bits = 48, .fixed_ctr = SNB_UNC_FIXED_CTR, .fixed_ctl = SNB_UNC_FIXED_CTR_CTRL, .single_fixed = 1, .event_mask = SNB_UNC_CTL_EV_SEL_MASK, .format_group = &icl_uncore_clock_format_group, .ops = &icl_uncore_msr_ops, .event_descs = icl_uncore_events, }; static struct intel_uncore_type icl_uncore_arb = { .name = "arb", .num_counters = 1, .num_boxes = 1, .perf_ctr_bits = 44, .perf_ctr = ICL_UNC_ARB_PER_CTR, .event_ctl = ICL_UNC_ARB_PERFEVTSEL, .event_mask = SNB_UNC_RAW_EVENT_MASK, .ops = &icl_uncore_msr_ops, .format_group = &snb_uncore_format_group, }; static struct intel_uncore_type *icl_msr_uncores[] = { &icl_uncore_cbox, &icl_uncore_arb, &icl_uncore_clockbox, NULL, }; static int icl_get_cbox_num(void) { u64 num_boxes; rdmsrl(ICL_UNC_CBO_CONFIG, num_boxes); return num_boxes & ICL_UNC_NUM_CBO_MASK; } void icl_uncore_cpu_init(void) { uncore_msr_uncores = icl_msr_uncores; icl_uncore_cbox.num_boxes = icl_get_cbox_num(); } static struct intel_uncore_type *tgl_msr_uncores[] = { &icl_uncore_cbox, &snb_uncore_arb, &icl_uncore_clockbox, NULL, }; static void rkl_uncore_msr_init_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) wrmsrl(SKL_UNC_PERF_GLOBAL_CTL, SNB_UNC_GLOBAL_CTL_EN); } void tgl_uncore_cpu_init(void) { uncore_msr_uncores = tgl_msr_uncores; icl_uncore_cbox.num_boxes = icl_get_cbox_num(); icl_uncore_cbox.ops = &skl_uncore_msr_ops; icl_uncore_clockbox.ops = &skl_uncore_msr_ops; snb_uncore_arb.ops = &skl_uncore_msr_ops; skl_uncore_msr_ops.init_box = rkl_uncore_msr_init_box; } static void adl_uncore_msr_init_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) wrmsrl(ADL_UNC_PERF_GLOBAL_CTL, SNB_UNC_GLOBAL_CTL_EN); } static void adl_uncore_msr_enable_box(struct intel_uncore_box *box) { wrmsrl(ADL_UNC_PERF_GLOBAL_CTL, SNB_UNC_GLOBAL_CTL_EN); } static void adl_uncore_msr_disable_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) wrmsrl(ADL_UNC_PERF_GLOBAL_CTL, 0); } static void adl_uncore_msr_exit_box(struct intel_uncore_box *box) { if (box->pmu->pmu_idx == 0) wrmsrl(ADL_UNC_PERF_GLOBAL_CTL, 0); } static struct intel_uncore_ops adl_uncore_msr_ops = { .init_box = adl_uncore_msr_init_box, .enable_box = adl_uncore_msr_enable_box, .disable_box = adl_uncore_msr_disable_box, .exit_box = adl_uncore_msr_exit_box, .disable_event = snb_uncore_msr_disable_event, .enable_event = snb_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, }; static struct attribute *adl_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_threshold.attr, NULL, }; static const struct attribute_group adl_uncore_format_group = { .name = "format", .attrs = adl_uncore_formats_attr, }; static struct intel_uncore_type adl_uncore_cbox = { .name = "cbox", .num_counters = 2, .perf_ctr_bits = 44, .perf_ctr = ADL_UNC_CBO_0_PER_CTR0, .event_ctl = ADL_UNC_CBO_0_PERFEVTSEL0, .event_mask = ADL_UNC_RAW_EVENT_MASK, .msr_offset = ICL_UNC_CBO_MSR_OFFSET, .ops = &adl_uncore_msr_ops, .format_group = &adl_uncore_format_group, }; static struct intel_uncore_type adl_uncore_arb = { .name = "arb", .num_counters = 2, .num_boxes = 2, .perf_ctr_bits = 44, .perf_ctr = ADL_UNC_ARB_PER_CTR0, .event_ctl = ADL_UNC_ARB_PERFEVTSEL0, .event_mask = SNB_UNC_RAW_EVENT_MASK, .msr_offset = ADL_UNC_ARB_MSR_OFFSET, .constraints = snb_uncore_arb_constraints, .ops = &adl_uncore_msr_ops, .format_group = &snb_uncore_format_group, }; static struct intel_uncore_type adl_uncore_clockbox = { .name = "clock", .num_counters = 1, .num_boxes = 1, .fixed_ctr_bits = 48, .fixed_ctr = ADL_UNC_FIXED_CTR, .fixed_ctl = ADL_UNC_FIXED_CTR_CTRL, .single_fixed = 1, .event_mask = SNB_UNC_CTL_EV_SEL_MASK, .format_group = &icl_uncore_clock_format_group, .ops = &adl_uncore_msr_ops, .event_descs = icl_uncore_events, }; static struct intel_uncore_type *adl_msr_uncores[] = { &adl_uncore_cbox, &adl_uncore_arb, &adl_uncore_clockbox, NULL, }; void adl_uncore_cpu_init(void) { adl_uncore_cbox.num_boxes = icl_get_cbox_num(); uncore_msr_uncores = adl_msr_uncores; } static struct intel_uncore_type mtl_uncore_cbox = { .name = "cbox", .num_counters = 2, .perf_ctr_bits = 48, .perf_ctr = MTL_UNC_CBO_0_PER_CTR0, .event_ctl = MTL_UNC_CBO_0_PERFEVTSEL0, .event_mask = ADL_UNC_RAW_EVENT_MASK, .msr_offset = SNB_UNC_CBO_MSR_OFFSET, .ops = &icl_uncore_msr_ops, .format_group = &adl_uncore_format_group, }; static struct intel_uncore_type mtl_uncore_hac_arb = { .name = "hac_arb", .num_counters = 2, .num_boxes = 2, .perf_ctr_bits = 48, .perf_ctr = MTL_UNC_HAC_ARB_CTR, .event_ctl = MTL_UNC_HAC_ARB_CTRL, .event_mask = ADL_UNC_RAW_EVENT_MASK, .msr_offset = SNB_UNC_CBO_MSR_OFFSET, .ops = &icl_uncore_msr_ops, .format_group = &adl_uncore_format_group, }; static struct intel_uncore_type mtl_uncore_arb = { .name = "arb", .num_counters = 2, .num_boxes = 2, .perf_ctr_bits = 48, .perf_ctr = MTL_UNC_ARB_CTR, .event_ctl = MTL_UNC_ARB_CTRL, .event_mask = ADL_UNC_RAW_EVENT_MASK, .msr_offset = SNB_UNC_CBO_MSR_OFFSET, .ops = &icl_uncore_msr_ops, .format_group = &adl_uncore_format_group, }; static struct intel_uncore_type mtl_uncore_hac_cbox = { .name = "hac_cbox", .num_counters = 2, .num_boxes = 2, .perf_ctr_bits = 48, .perf_ctr = MTL_UNC_HBO_CTR, .event_ctl = MTL_UNC_HBO_CTRL, .event_mask = ADL_UNC_RAW_EVENT_MASK, .msr_offset = SNB_UNC_CBO_MSR_OFFSET, .ops = &icl_uncore_msr_ops, .format_group = &adl_uncore_format_group, }; static void mtl_uncore_msr_init_box(struct intel_uncore_box *box) { wrmsrl(uncore_msr_box_ctl(box), SNB_UNC_GLOBAL_CTL_EN); } static struct intel_uncore_ops mtl_uncore_msr_ops = { .init_box = mtl_uncore_msr_init_box, .disable_event = snb_uncore_msr_disable_event, .enable_event = snb_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, }; static struct intel_uncore_type mtl_uncore_cncu = { .name = "cncu", .num_counters = 1, .num_boxes = 1, .box_ctl = MTL_UNC_CNCU_BOX_CTL, .fixed_ctr_bits = 48, .fixed_ctr = MTL_UNC_CNCU_FIXED_CTR, .fixed_ctl = MTL_UNC_CNCU_FIXED_CTRL, .single_fixed = 1, .event_mask = SNB_UNC_CTL_EV_SEL_MASK, .format_group = &icl_uncore_clock_format_group, .ops = &mtl_uncore_msr_ops, .event_descs = icl_uncore_events, }; static struct intel_uncore_type mtl_uncore_sncu = { .name = "sncu", .num_counters = 1, .num_boxes = 1, .box_ctl = MTL_UNC_SNCU_BOX_CTL, .fixed_ctr_bits = 48, .fixed_ctr = MTL_UNC_SNCU_FIXED_CTR, .fixed_ctl = MTL_UNC_SNCU_FIXED_CTRL, .single_fixed = 1, .event_mask = SNB_UNC_CTL_EV_SEL_MASK, .format_group = &icl_uncore_clock_format_group, .ops = &mtl_uncore_msr_ops, .event_descs = icl_uncore_events, }; static struct intel_uncore_type *mtl_msr_uncores[] = { &mtl_uncore_cbox, &mtl_uncore_hac_arb, &mtl_uncore_arb, &mtl_uncore_hac_cbox, &mtl_uncore_cncu, &mtl_uncore_sncu, NULL }; void mtl_uncore_cpu_init(void) { mtl_uncore_cbox.num_boxes = icl_get_cbox_num(); uncore_msr_uncores = mtl_msr_uncores; } enum { SNB_PCI_UNCORE_IMC, }; static struct uncore_event_desc snb_uncore_imc_events[] = { INTEL_UNCORE_EVENT_DESC(data_reads, "event=0x01"), INTEL_UNCORE_EVENT_DESC(data_reads.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(data_reads.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(data_writes, "event=0x02"), INTEL_UNCORE_EVENT_DESC(data_writes.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(data_writes.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(gt_requests, "event=0x03"), INTEL_UNCORE_EVENT_DESC(gt_requests.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(gt_requests.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(ia_requests, "event=0x04"), INTEL_UNCORE_EVENT_DESC(ia_requests.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(ia_requests.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(io_requests, "event=0x05"), INTEL_UNCORE_EVENT_DESC(io_requests.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(io_requests.unit, "MiB"), { /* end: all zeroes */ }, }; #define SNB_UNCORE_PCI_IMC_EVENT_MASK 0xff #define SNB_UNCORE_PCI_IMC_BAR_OFFSET 0x48 /* page size multiple covering all config regs */ #define SNB_UNCORE_PCI_IMC_MAP_SIZE 0x6000 #define SNB_UNCORE_PCI_IMC_DATA_READS 0x1 #define SNB_UNCORE_PCI_IMC_DATA_READS_BASE 0x5050 #define SNB_UNCORE_PCI_IMC_DATA_WRITES 0x2 #define SNB_UNCORE_PCI_IMC_DATA_WRITES_BASE 0x5054 #define SNB_UNCORE_PCI_IMC_CTR_BASE SNB_UNCORE_PCI_IMC_DATA_READS_BASE /* BW break down- legacy counters */ #define SNB_UNCORE_PCI_IMC_GT_REQUESTS 0x3 #define SNB_UNCORE_PCI_IMC_GT_REQUESTS_BASE 0x5040 #define SNB_UNCORE_PCI_IMC_IA_REQUESTS 0x4 #define SNB_UNCORE_PCI_IMC_IA_REQUESTS_BASE 0x5044 #define SNB_UNCORE_PCI_IMC_IO_REQUESTS 0x5 #define SNB_UNCORE_PCI_IMC_IO_REQUESTS_BASE 0x5048 enum perf_snb_uncore_imc_freerunning_types { SNB_PCI_UNCORE_IMC_DATA_READS = 0, SNB_PCI_UNCORE_IMC_DATA_WRITES, SNB_PCI_UNCORE_IMC_GT_REQUESTS, SNB_PCI_UNCORE_IMC_IA_REQUESTS, SNB_PCI_UNCORE_IMC_IO_REQUESTS, SNB_PCI_UNCORE_IMC_FREERUNNING_TYPE_MAX, }; static struct freerunning_counters snb_uncore_imc_freerunning[] = { [SNB_PCI_UNCORE_IMC_DATA_READS] = { SNB_UNCORE_PCI_IMC_DATA_READS_BASE, 0x0, 0x0, 1, 32 }, [SNB_PCI_UNCORE_IMC_DATA_WRITES] = { SNB_UNCORE_PCI_IMC_DATA_WRITES_BASE, 0x0, 0x0, 1, 32 }, [SNB_PCI_UNCORE_IMC_GT_REQUESTS] = { SNB_UNCORE_PCI_IMC_GT_REQUESTS_BASE, 0x0, 0x0, 1, 32 }, [SNB_PCI_UNCORE_IMC_IA_REQUESTS] = { SNB_UNCORE_PCI_IMC_IA_REQUESTS_BASE, 0x0, 0x0, 1, 32 }, [SNB_PCI_UNCORE_IMC_IO_REQUESTS] = { SNB_UNCORE_PCI_IMC_IO_REQUESTS_BASE, 0x0, 0x0, 1, 32 }, }; static struct attribute *snb_uncore_imc_formats_attr[] = { &format_attr_event.attr, NULL, }; static const struct attribute_group snb_uncore_imc_format_group = { .name = "format", .attrs = snb_uncore_imc_formats_attr, }; static void snb_uncore_imc_init_box(struct intel_uncore_box *box) { struct intel_uncore_type *type = box->pmu->type; struct pci_dev *pdev = box->pci_dev; int where = SNB_UNCORE_PCI_IMC_BAR_OFFSET; resource_size_t addr; u32 pci_dword; pci_read_config_dword(pdev, where, &pci_dword); addr = pci_dword; #ifdef CONFIG_PHYS_ADDR_T_64BIT pci_read_config_dword(pdev, where + 4, &pci_dword); addr |= ((resource_size_t)pci_dword << 32); #endif addr &= ~(PAGE_SIZE - 1); box->io_addr = ioremap(addr, type->mmio_map_size); if (!box->io_addr) pr_warn("perf uncore: Failed to ioremap for %s.\n", type->name); box->hrtimer_duration = UNCORE_SNB_IMC_HRTIMER_INTERVAL; } static void snb_uncore_imc_enable_box(struct intel_uncore_box *box) {} static void snb_uncore_imc_disable_box(struct intel_uncore_box *box) {} static void snb_uncore_imc_enable_event(struct intel_uncore_box *box, struct perf_event *event) {} static void snb_uncore_imc_disable_event(struct intel_uncore_box *box, struct perf_event *event) {} /* * Keep the custom event_init() function compatible with old event * encoding for free running counters. */ static int snb_uncore_imc_event_init(struct perf_event *event) { struct intel_uncore_pmu *pmu; struct intel_uncore_box *box; struct hw_perf_event *hwc = &event->hw; u64 cfg = event->attr.config & SNB_UNCORE_PCI_IMC_EVENT_MASK; int idx, base; if (event->attr.type != event->pmu->type) return -ENOENT; pmu = uncore_event_to_pmu(event); /* no device found for this pmu */ if (pmu->func_id < 0) return -ENOENT; /* Sampling not supported yet */ if (hwc->sample_period) return -EINVAL; /* unsupported modes and filters */ if (event->attr.sample_period) /* no sampling */ return -EINVAL; /* * Place all uncore events for a particular physical package * onto a single cpu */ if (event->cpu < 0) return -EINVAL; /* check only supported bits are set */ if (event->attr.config & ~SNB_UNCORE_PCI_IMC_EVENT_MASK) return -EINVAL; box = uncore_pmu_to_box(pmu, event->cpu); if (!box || box->cpu < 0) return -EINVAL; event->cpu = box->cpu; event->pmu_private = box; event->event_caps |= PERF_EV_CAP_READ_ACTIVE_PKG; event->hw.idx = -1; event->hw.last_tag = ~0ULL; event->hw.extra_reg.idx = EXTRA_REG_NONE; event->hw.branch_reg.idx = EXTRA_REG_NONE; /* * check event is known (whitelist, determines counter) */ switch (cfg) { case SNB_UNCORE_PCI_IMC_DATA_READS: base = SNB_UNCORE_PCI_IMC_DATA_READS_BASE; idx = UNCORE_PMC_IDX_FREERUNNING; break; case SNB_UNCORE_PCI_IMC_DATA_WRITES: base = SNB_UNCORE_PCI_IMC_DATA_WRITES_BASE; idx = UNCORE_PMC_IDX_FREERUNNING; break; case SNB_UNCORE_PCI_IMC_GT_REQUESTS: base = SNB_UNCORE_PCI_IMC_GT_REQUESTS_BASE; idx = UNCORE_PMC_IDX_FREERUNNING; break; case SNB_UNCORE_PCI_IMC_IA_REQUESTS: base = SNB_UNCORE_PCI_IMC_IA_REQUESTS_BASE; idx = UNCORE_PMC_IDX_FREERUNNING; break; case SNB_UNCORE_PCI_IMC_IO_REQUESTS: base = SNB_UNCORE_PCI_IMC_IO_REQUESTS_BASE; idx = UNCORE_PMC_IDX_FREERUNNING; break; default: return -EINVAL; } /* must be done before validate_group */ event->hw.event_base = base; event->hw.idx = idx; /* Convert to standard encoding format for freerunning counters */ event->hw.config = ((cfg - 1) << 8) | 0x10ff; /* no group validation needed, we have free running counters */ return 0; } static int snb_uncore_imc_hw_config(struct intel_uncore_box *box, struct perf_event *event) { return 0; } int snb_pci2phy_map_init(int devid) { struct pci_dev *dev = NULL; struct pci2phy_map *map; int bus, segment; dev = pci_get_device(PCI_VENDOR_ID_INTEL, devid, dev); if (!dev) return -ENOTTY; bus = dev->bus->number; segment = pci_domain_nr(dev->bus); raw_spin_lock(&pci2phy_map_lock); map = __find_pci2phy_map(segment); if (!map) { raw_spin_unlock(&pci2phy_map_lock); pci_dev_put(dev); return -ENOMEM; } map->pbus_to_dieid[bus] = 0; raw_spin_unlock(&pci2phy_map_lock); pci_dev_put(dev); return 0; } static u64 snb_uncore_imc_read_counter(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; /* * SNB IMC counters are 32-bit and are laid out back to back * in MMIO space. Therefore we must use a 32-bit accessor function * using readq() from uncore_mmio_read_counter() causes problems * because it is reading 64-bit at a time. This is okay for the * uncore_perf_event_update() function because it drops the upper * 32-bits but not okay for plain uncore_read_counter() as invoked * in uncore_pmu_event_start(). */ return (u64)readl(box->io_addr + hwc->event_base); } static struct pmu snb_uncore_imc_pmu = { .task_ctx_nr = perf_invalid_context, .event_init = snb_uncore_imc_event_init, .add = uncore_pmu_event_add, .del = uncore_pmu_event_del, .start = uncore_pmu_event_start, .stop = uncore_pmu_event_stop, .read = uncore_pmu_event_read, .capabilities = PERF_PMU_CAP_NO_EXCLUDE, }; static struct intel_uncore_ops snb_uncore_imc_ops = { .init_box = snb_uncore_imc_init_box, .exit_box = uncore_mmio_exit_box, .enable_box = snb_uncore_imc_enable_box, .disable_box = snb_uncore_imc_disable_box, .disable_event = snb_uncore_imc_disable_event, .enable_event = snb_uncore_imc_enable_event, .hw_config = snb_uncore_imc_hw_config, .read_counter = snb_uncore_imc_read_counter, }; static struct intel_uncore_type snb_uncore_imc = { .name = "imc", .num_counters = 5, .num_boxes = 1, .num_freerunning_types = SNB_PCI_UNCORE_IMC_FREERUNNING_TYPE_MAX, .mmio_map_size = SNB_UNCORE_PCI_IMC_MAP_SIZE, .freerunning = snb_uncore_imc_freerunning, .event_descs = snb_uncore_imc_events, .format_group = &snb_uncore_imc_format_group, .ops = &snb_uncore_imc_ops, .pmu = &snb_uncore_imc_pmu, }; static struct intel_uncore_type *snb_pci_uncores[] = { [SNB_PCI_UNCORE_IMC] = &snb_uncore_imc, NULL, }; static const struct pci_device_id snb_uncore_pci_ids[] = { IMC_UNCORE_DEV(SNB), { /* end: all zeroes */ }, }; static const struct pci_device_id ivb_uncore_pci_ids[] = { IMC_UNCORE_DEV(IVB), IMC_UNCORE_DEV(IVB_E3), { /* end: all zeroes */ }, }; static const struct pci_device_id hsw_uncore_pci_ids[] = { IMC_UNCORE_DEV(HSW), IMC_UNCORE_DEV(HSW_U), { /* end: all zeroes */ }, }; static const struct pci_device_id bdw_uncore_pci_ids[] = { IMC_UNCORE_DEV(BDW), { /* end: all zeroes */ }, }; static const struct pci_device_id skl_uncore_pci_ids[] = { IMC_UNCORE_DEV(SKL_Y), IMC_UNCORE_DEV(SKL_U), IMC_UNCORE_DEV(SKL_HD), IMC_UNCORE_DEV(SKL_HQ), IMC_UNCORE_DEV(SKL_SD), IMC_UNCORE_DEV(SKL_SQ), IMC_UNCORE_DEV(SKL_E3), IMC_UNCORE_DEV(KBL_Y), IMC_UNCORE_DEV(KBL_U), IMC_UNCORE_DEV(KBL_UQ), IMC_UNCORE_DEV(KBL_SD), IMC_UNCORE_DEV(KBL_SQ), IMC_UNCORE_DEV(KBL_HQ), IMC_UNCORE_DEV(KBL_WQ), IMC_UNCORE_DEV(CFL_2U), IMC_UNCORE_DEV(CFL_4U), IMC_UNCORE_DEV(CFL_4H), IMC_UNCORE_DEV(CFL_6H), IMC_UNCORE_DEV(CFL_2S_D), IMC_UNCORE_DEV(CFL_4S_D), IMC_UNCORE_DEV(CFL_6S_D), IMC_UNCORE_DEV(CFL_8S_D), IMC_UNCORE_DEV(CFL_4S_W), IMC_UNCORE_DEV(CFL_6S_W), IMC_UNCORE_DEV(CFL_8S_W), IMC_UNCORE_DEV(CFL_4S_S), IMC_UNCORE_DEV(CFL_6S_S), IMC_UNCORE_DEV(CFL_8S_S), IMC_UNCORE_DEV(AML_YD), IMC_UNCORE_DEV(AML_YQ), IMC_UNCORE_DEV(WHL_UQ), IMC_UNCORE_DEV(WHL_4_UQ), IMC_UNCORE_DEV(WHL_UD), IMC_UNCORE_DEV(CML_H1), IMC_UNCORE_DEV(CML_H2), IMC_UNCORE_DEV(CML_H3), IMC_UNCORE_DEV(CML_U1), IMC_UNCORE_DEV(CML_U2), IMC_UNCORE_DEV(CML_U3), IMC_UNCORE_DEV(CML_S1), IMC_UNCORE_DEV(CML_S2), IMC_UNCORE_DEV(CML_S3), IMC_UNCORE_DEV(CML_S4), IMC_UNCORE_DEV(CML_S5), { /* end: all zeroes */ }, }; static const struct pci_device_id icl_uncore_pci_ids[] = { IMC_UNCORE_DEV(ICL_U), IMC_UNCORE_DEV(ICL_U2), IMC_UNCORE_DEV(RKL_1), IMC_UNCORE_DEV(RKL_2), { /* end: all zeroes */ }, }; static struct pci_driver snb_uncore_pci_driver = { .name = "snb_uncore", .id_table = snb_uncore_pci_ids, }; static struct pci_driver ivb_uncore_pci_driver = { .name = "ivb_uncore", .id_table = ivb_uncore_pci_ids, }; static struct pci_driver hsw_uncore_pci_driver = { .name = "hsw_uncore", .id_table = hsw_uncore_pci_ids, }; static struct pci_driver bdw_uncore_pci_driver = { .name = "bdw_uncore", .id_table = bdw_uncore_pci_ids, }; static struct pci_driver skl_uncore_pci_driver = { .name = "skl_uncore", .id_table = skl_uncore_pci_ids, }; static struct pci_driver icl_uncore_pci_driver = { .name = "icl_uncore", .id_table = icl_uncore_pci_ids, }; struct imc_uncore_pci_dev { __u32 pci_id; struct pci_driver *driver; }; #define IMC_DEV(a, d) \ { .pci_id = PCI_DEVICE_ID_INTEL_##a, .driver = (d) } static const struct imc_uncore_pci_dev desktop_imc_pci_ids[] = { IMC_DEV(SNB_IMC, &snb_uncore_pci_driver), IMC_DEV(IVB_IMC, &ivb_uncore_pci_driver), /* 3rd Gen Core processor */ IMC_DEV(IVB_E3_IMC, &ivb_uncore_pci_driver), /* Xeon E3-1200 v2/3rd Gen Core processor */ IMC_DEV(HSW_IMC, &hsw_uncore_pci_driver), /* 4th Gen Core Processor */ IMC_DEV(HSW_U_IMC, &hsw_uncore_pci_driver), /* 4th Gen Core ULT Mobile Processor */ IMC_DEV(BDW_IMC, &bdw_uncore_pci_driver), /* 5th Gen Core U */ IMC_DEV(SKL_Y_IMC, &skl_uncore_pci_driver), /* 6th Gen Core Y */ IMC_DEV(SKL_U_IMC, &skl_uncore_pci_driver), /* 6th Gen Core U */ IMC_DEV(SKL_HD_IMC, &skl_uncore_pci_driver), /* 6th Gen Core H Dual Core */ IMC_DEV(SKL_HQ_IMC, &skl_uncore_pci_driver), /* 6th Gen Core H Quad Core */ IMC_DEV(SKL_SD_IMC, &skl_uncore_pci_driver), /* 6th Gen Core S Dual Core */ IMC_DEV(SKL_SQ_IMC, &skl_uncore_pci_driver), /* 6th Gen Core S Quad Core */ IMC_DEV(SKL_E3_IMC, &skl_uncore_pci_driver), /* Xeon E3 V5 Gen Core processor */ IMC_DEV(KBL_Y_IMC, &skl_uncore_pci_driver), /* 7th Gen Core Y */ IMC_DEV(KBL_U_IMC, &skl_uncore_pci_driver), /* 7th Gen Core U */ IMC_DEV(KBL_UQ_IMC, &skl_uncore_pci_driver), /* 7th Gen Core U Quad Core */ IMC_DEV(KBL_SD_IMC, &skl_uncore_pci_driver), /* 7th Gen Core S Dual Core */ IMC_DEV(KBL_SQ_IMC, &skl_uncore_pci_driver), /* 7th Gen Core S Quad Core */ IMC_DEV(KBL_HQ_IMC, &skl_uncore_pci_driver), /* 7th Gen Core H Quad Core */ IMC_DEV(KBL_WQ_IMC, &skl_uncore_pci_driver), /* 7th Gen Core S 4 cores Work Station */ IMC_DEV(CFL_2U_IMC, &skl_uncore_pci_driver), /* 8th Gen Core U 2 Cores */ IMC_DEV(CFL_4U_IMC, &skl_uncore_pci_driver), /* 8th Gen Core U 4 Cores */ IMC_DEV(CFL_4H_IMC, &skl_uncore_pci_driver), /* 8th Gen Core H 4 Cores */ IMC_DEV(CFL_6H_IMC, &skl_uncore_pci_driver), /* 8th Gen Core H 6 Cores */ IMC_DEV(CFL_2S_D_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 2 Cores Desktop */ IMC_DEV(CFL_4S_D_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 4 Cores Desktop */ IMC_DEV(CFL_6S_D_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 6 Cores Desktop */ IMC_DEV(CFL_8S_D_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 8 Cores Desktop */ IMC_DEV(CFL_4S_W_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 4 Cores Work Station */ IMC_DEV(CFL_6S_W_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 6 Cores Work Station */ IMC_DEV(CFL_8S_W_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 8 Cores Work Station */ IMC_DEV(CFL_4S_S_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 4 Cores Server */ IMC_DEV(CFL_6S_S_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 6 Cores Server */ IMC_DEV(CFL_8S_S_IMC, &skl_uncore_pci_driver), /* 8th Gen Core S 8 Cores Server */ IMC_DEV(AML_YD_IMC, &skl_uncore_pci_driver), /* 8th Gen Core Y Mobile Dual Core */ IMC_DEV(AML_YQ_IMC, &skl_uncore_pci_driver), /* 8th Gen Core Y Mobile Quad Core */ IMC_DEV(WHL_UQ_IMC, &skl_uncore_pci_driver), /* 8th Gen Core U Mobile Quad Core */ IMC_DEV(WHL_4_UQ_IMC, &skl_uncore_pci_driver), /* 8th Gen Core U Mobile Quad Core */ IMC_DEV(WHL_UD_IMC, &skl_uncore_pci_driver), /* 8th Gen Core U Mobile Dual Core */ IMC_DEV(CML_H1_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_H2_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_H3_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_U1_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_U2_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_U3_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_S1_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_S2_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_S3_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_S4_IMC, &skl_uncore_pci_driver), IMC_DEV(CML_S5_IMC, &skl_uncore_pci_driver), IMC_DEV(ICL_U_IMC, &icl_uncore_pci_driver), /* 10th Gen Core Mobile */ IMC_DEV(ICL_U2_IMC, &icl_uncore_pci_driver), /* 10th Gen Core Mobile */ IMC_DEV(RKL_1_IMC, &icl_uncore_pci_driver), IMC_DEV(RKL_2_IMC, &icl_uncore_pci_driver), { /* end marker */ } }; #define for_each_imc_pci_id(x, t) \ for (x = (t); (x)->pci_id; x++) static struct pci_driver *imc_uncore_find_dev(void) { const struct imc_uncore_pci_dev *p; int ret; for_each_imc_pci_id(p, desktop_imc_pci_ids) { ret = snb_pci2phy_map_init(p->pci_id); if (ret == 0) return p->driver; } return NULL; } static int imc_uncore_pci_init(void) { struct pci_driver *imc_drv = imc_uncore_find_dev(); if (!imc_drv) return -ENODEV; uncore_pci_uncores = snb_pci_uncores; uncore_pci_driver = imc_drv; return 0; } int snb_uncore_pci_init(void) { return imc_uncore_pci_init(); } int ivb_uncore_pci_init(void) { return imc_uncore_pci_init(); } int hsw_uncore_pci_init(void) { return imc_uncore_pci_init(); } int bdw_uncore_pci_init(void) { return imc_uncore_pci_init(); } int skl_uncore_pci_init(void) { return imc_uncore_pci_init(); } /* end of Sandy Bridge uncore support */ /* Nehalem uncore support */ static void nhm_uncore_msr_disable_box(struct intel_uncore_box *box) { wrmsrl(NHM_UNC_PERF_GLOBAL_CTL, 0); } static void nhm_uncore_msr_enable_box(struct intel_uncore_box *box) { wrmsrl(NHM_UNC_PERF_GLOBAL_CTL, NHM_UNC_GLOBAL_CTL_EN_PC_ALL | NHM_UNC_GLOBAL_CTL_EN_FC); } static void nhm_uncore_msr_enable_event(struct intel_uncore_box *box, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (hwc->idx < UNCORE_PMC_IDX_FIXED) wrmsrl(hwc->config_base, hwc->config | SNB_UNC_CTL_EN); else wrmsrl(hwc->config_base, NHM_UNC_FIXED_CTR_CTL_EN); } static struct attribute *nhm_uncore_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_cmask8.attr, NULL, }; static const struct attribute_group nhm_uncore_format_group = { .name = "format", .attrs = nhm_uncore_formats_attr, }; static struct uncore_event_desc nhm_uncore_events[] = { INTEL_UNCORE_EVENT_DESC(clockticks, "event=0xff,umask=0x00"), INTEL_UNCORE_EVENT_DESC(qmc_writes_full_any, "event=0x2f,umask=0x0f"), INTEL_UNCORE_EVENT_DESC(qmc_normal_reads_any, "event=0x2c,umask=0x0f"), INTEL_UNCORE_EVENT_DESC(qhl_request_ioh_reads, "event=0x20,umask=0x01"), INTEL_UNCORE_EVENT_DESC(qhl_request_ioh_writes, "event=0x20,umask=0x02"), INTEL_UNCORE_EVENT_DESC(qhl_request_remote_reads, "event=0x20,umask=0x04"), INTEL_UNCORE_EVENT_DESC(qhl_request_remote_writes, "event=0x20,umask=0x08"), INTEL_UNCORE_EVENT_DESC(qhl_request_local_reads, "event=0x20,umask=0x10"), INTEL_UNCORE_EVENT_DESC(qhl_request_local_writes, "event=0x20,umask=0x20"), { /* end: all zeroes */ }, }; static struct intel_uncore_ops nhm_uncore_msr_ops = { .disable_box = nhm_uncore_msr_disable_box, .enable_box = nhm_uncore_msr_enable_box, .disable_event = snb_uncore_msr_disable_event, .enable_event = nhm_uncore_msr_enable_event, .read_counter = uncore_msr_read_counter, }; static struct intel_uncore_type nhm_uncore = { .name = "", .num_counters = 8, .num_boxes = 1, .perf_ctr_bits = 48, .fixed_ctr_bits = 48, .event_ctl = NHM_UNC_PERFEVTSEL0, .perf_ctr = NHM_UNC_UNCORE_PMC0, .fixed_ctr = NHM_UNC_FIXED_CTR, .fixed_ctl = NHM_UNC_FIXED_CTR_CTRL, .event_mask = NHM_UNC_RAW_EVENT_MASK, .event_descs = nhm_uncore_events, .ops = &nhm_uncore_msr_ops, .format_group = &nhm_uncore_format_group, }; static struct intel_uncore_type *nhm_msr_uncores[] = { &nhm_uncore, NULL, }; void nhm_uncore_cpu_init(void) { uncore_msr_uncores = nhm_msr_uncores; } /* end of Nehalem uncore support */ /* Tiger Lake MMIO uncore support */ static const struct pci_device_id tgl_uncore_pci_ids[] = { IMC_UNCORE_DEV(TGL_U1), IMC_UNCORE_DEV(TGL_U2), IMC_UNCORE_DEV(TGL_U3), IMC_UNCORE_DEV(TGL_U4), IMC_UNCORE_DEV(TGL_H), IMC_UNCORE_DEV(ADL_1), IMC_UNCORE_DEV(ADL_2), IMC_UNCORE_DEV(ADL_3), IMC_UNCORE_DEV(ADL_4), IMC_UNCORE_DEV(ADL_5), IMC_UNCORE_DEV(ADL_6), IMC_UNCORE_DEV(ADL_7), IMC_UNCORE_DEV(ADL_8), IMC_UNCORE_DEV(ADL_9), IMC_UNCORE_DEV(ADL_10), IMC_UNCORE_DEV(ADL_11), IMC_UNCORE_DEV(ADL_12), IMC_UNCORE_DEV(ADL_13), IMC_UNCORE_DEV(ADL_14), IMC_UNCORE_DEV(ADL_15), IMC_UNCORE_DEV(ADL_16), IMC_UNCORE_DEV(ADL_17), IMC_UNCORE_DEV(ADL_18), IMC_UNCORE_DEV(ADL_19), IMC_UNCORE_DEV(ADL_20), IMC_UNCORE_DEV(ADL_21), IMC_UNCORE_DEV(RPL_1), IMC_UNCORE_DEV(RPL_2), IMC_UNCORE_DEV(RPL_3), IMC_UNCORE_DEV(RPL_4), IMC_UNCORE_DEV(RPL_5), IMC_UNCORE_DEV(RPL_6), IMC_UNCORE_DEV(RPL_7), IMC_UNCORE_DEV(RPL_8), IMC_UNCORE_DEV(RPL_9), IMC_UNCORE_DEV(RPL_10), IMC_UNCORE_DEV(RPL_11), IMC_UNCORE_DEV(RPL_12), IMC_UNCORE_DEV(RPL_13), IMC_UNCORE_DEV(RPL_14), IMC_UNCORE_DEV(RPL_15), IMC_UNCORE_DEV(RPL_16), IMC_UNCORE_DEV(RPL_17), IMC_UNCORE_DEV(RPL_18), IMC_UNCORE_DEV(RPL_19), IMC_UNCORE_DEV(RPL_20), IMC_UNCORE_DEV(RPL_21), IMC_UNCORE_DEV(RPL_22), IMC_UNCORE_DEV(RPL_23), IMC_UNCORE_DEV(RPL_24), IMC_UNCORE_DEV(RPL_25), IMC_UNCORE_DEV(MTL_1), IMC_UNCORE_DEV(MTL_2), IMC_UNCORE_DEV(MTL_3), IMC_UNCORE_DEV(MTL_4), IMC_UNCORE_DEV(MTL_5), IMC_UNCORE_DEV(MTL_6), IMC_UNCORE_DEV(MTL_7), IMC_UNCORE_DEV(MTL_8), IMC_UNCORE_DEV(MTL_9), IMC_UNCORE_DEV(MTL_10), IMC_UNCORE_DEV(MTL_11), IMC_UNCORE_DEV(MTL_12), IMC_UNCORE_DEV(MTL_13), { /* end: all zeroes */ } }; enum perf_tgl_uncore_imc_freerunning_types { TGL_MMIO_UNCORE_IMC_DATA_TOTAL, TGL_MMIO_UNCORE_IMC_DATA_READ, TGL_MMIO_UNCORE_IMC_DATA_WRITE, TGL_MMIO_UNCORE_IMC_FREERUNNING_TYPE_MAX }; static struct freerunning_counters tgl_l_uncore_imc_freerunning[] = { [TGL_MMIO_UNCORE_IMC_DATA_TOTAL] = { 0x5040, 0x0, 0x0, 1, 64 }, [TGL_MMIO_UNCORE_IMC_DATA_READ] = { 0x5058, 0x0, 0x0, 1, 64 }, [TGL_MMIO_UNCORE_IMC_DATA_WRITE] = { 0x50A0, 0x0, 0x0, 1, 64 }, }; static struct freerunning_counters tgl_uncore_imc_freerunning[] = { [TGL_MMIO_UNCORE_IMC_DATA_TOTAL] = { 0xd840, 0x0, 0x0, 1, 64 }, [TGL_MMIO_UNCORE_IMC_DATA_READ] = { 0xd858, 0x0, 0x0, 1, 64 }, [TGL_MMIO_UNCORE_IMC_DATA_WRITE] = { 0xd8A0, 0x0, 0x0, 1, 64 }, }; static struct uncore_event_desc tgl_uncore_imc_events[] = { INTEL_UNCORE_EVENT_DESC(data_total, "event=0xff,umask=0x10"), INTEL_UNCORE_EVENT_DESC(data_total.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(data_total.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(data_read, "event=0xff,umask=0x20"), INTEL_UNCORE_EVENT_DESC(data_read.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(data_read.unit, "MiB"), INTEL_UNCORE_EVENT_DESC(data_write, "event=0xff,umask=0x30"), INTEL_UNCORE_EVENT_DESC(data_write.scale, "6.103515625e-5"), INTEL_UNCORE_EVENT_DESC(data_write.unit, "MiB"), { /* end: all zeroes */ } }; static struct pci_dev *tgl_uncore_get_mc_dev(void) { const struct pci_device_id *ids = tgl_uncore_pci_ids; struct pci_dev *mc_dev = NULL; while (ids && ids->vendor) { mc_dev = pci_get_device(PCI_VENDOR_ID_INTEL, ids->device, NULL); if (mc_dev) return mc_dev; ids++; } return mc_dev; } #define TGL_UNCORE_MMIO_IMC_MEM_OFFSET 0x10000 #define TGL_UNCORE_PCI_IMC_MAP_SIZE 0xe000 static void __uncore_imc_init_box(struct intel_uncore_box *box, unsigned int base_offset) { struct pci_dev *pdev = tgl_uncore_get_mc_dev(); struct intel_uncore_pmu *pmu = box->pmu; struct intel_uncore_type *type = pmu->type; resource_size_t addr; u32 mch_bar; if (!pdev) { pr_warn("perf uncore: Cannot find matched IMC device.\n"); return; } pci_read_config_dword(pdev, SNB_UNCORE_PCI_IMC_BAR_OFFSET, &mch_bar); /* MCHBAR is disabled */ if (!(mch_bar & BIT(0))) { pr_warn("perf uncore: MCHBAR is disabled. Failed to map IMC free-running counters.\n"); pci_dev_put(pdev); return; } mch_bar &= ~BIT(0); addr = (resource_size_t)(mch_bar + TGL_UNCORE_MMIO_IMC_MEM_OFFSET * pmu->pmu_idx); #ifdef CONFIG_PHYS_ADDR_T_64BIT pci_read_config_dword(pdev, SNB_UNCORE_PCI_IMC_BAR_OFFSET + 4, &mch_bar); addr |= ((resource_size_t)mch_bar << 32); #endif addr += base_offset; box->io_addr = ioremap(addr, type->mmio_map_size); if (!box->io_addr) pr_warn("perf uncore: Failed to ioremap for %s.\n", type->name); pci_dev_put(pdev); } static void tgl_uncore_imc_freerunning_init_box(struct intel_uncore_box *box) { __uncore_imc_init_box(box, 0); } static struct intel_uncore_ops tgl_uncore_imc_freerunning_ops = { .init_box = tgl_uncore_imc_freerunning_init_box, .exit_box = uncore_mmio_exit_box, .read_counter = uncore_mmio_read_counter, .hw_config = uncore_freerunning_hw_config, }; static struct attribute *tgl_uncore_imc_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, NULL }; static const struct attribute_group tgl_uncore_imc_format_group = { .name = "format", .attrs = tgl_uncore_imc_formats_attr, }; static struct intel_uncore_type tgl_uncore_imc_free_running = { .name = "imc_free_running", .num_counters = 3, .num_boxes = 2, .num_freerunning_types = TGL_MMIO_UNCORE_IMC_FREERUNNING_TYPE_MAX, .mmio_map_size = TGL_UNCORE_PCI_IMC_MAP_SIZE, .freerunning = tgl_uncore_imc_freerunning, .ops = &tgl_uncore_imc_freerunning_ops, .event_descs = tgl_uncore_imc_events, .format_group = &tgl_uncore_imc_format_group, }; static struct intel_uncore_type *tgl_mmio_uncores[] = { &tgl_uncore_imc_free_running, NULL }; void tgl_l_uncore_mmio_init(void) { tgl_uncore_imc_free_running.freerunning = tgl_l_uncore_imc_freerunning; uncore_mmio_uncores = tgl_mmio_uncores; } void tgl_uncore_mmio_init(void) { uncore_mmio_uncores = tgl_mmio_uncores; } /* end of Tiger Lake MMIO uncore support */ /* Alder Lake MMIO uncore support */ #define ADL_UNCORE_IMC_BASE 0xd900 #define ADL_UNCORE_IMC_MAP_SIZE 0x200 #define ADL_UNCORE_IMC_CTR 0xe8 #define ADL_UNCORE_IMC_CTRL 0xd0 #define ADL_UNCORE_IMC_GLOBAL_CTL 0xc0 #define ADL_UNCORE_IMC_BOX_CTL 0xc4 #define ADL_UNCORE_IMC_FREERUNNING_BASE 0xd800 #define ADL_UNCORE_IMC_FREERUNNING_MAP_SIZE 0x100 #define ADL_UNCORE_IMC_CTL_FRZ (1 << 0) #define ADL_UNCORE_IMC_CTL_RST_CTRL (1 << 1) #define ADL_UNCORE_IMC_CTL_RST_CTRS (1 << 2) #define ADL_UNCORE_IMC_CTL_INT (ADL_UNCORE_IMC_CTL_RST_CTRL | \ ADL_UNCORE_IMC_CTL_RST_CTRS) static void adl_uncore_imc_init_box(struct intel_uncore_box *box) { __uncore_imc_init_box(box, ADL_UNCORE_IMC_BASE); /* The global control in MC1 can control both MCs. */ if (box->io_addr && (box->pmu->pmu_idx == 1)) writel(ADL_UNCORE_IMC_CTL_INT, box->io_addr + ADL_UNCORE_IMC_GLOBAL_CTL); } static void adl_uncore_mmio_disable_box(struct intel_uncore_box *box) { if (!box->io_addr) return; writel(ADL_UNCORE_IMC_CTL_FRZ, box->io_addr + uncore_mmio_box_ctl(box)); } static void adl_uncore_mmio_enable_box(struct intel_uncore_box *box) { if (!box->io_addr) return; writel(0, box->io_addr + uncore_mmio_box_ctl(box)); } static struct intel_uncore_ops adl_uncore_mmio_ops = { .init_box = adl_uncore_imc_init_box, .exit_box = uncore_mmio_exit_box, .disable_box = adl_uncore_mmio_disable_box, .enable_box = adl_uncore_mmio_enable_box, .disable_event = intel_generic_uncore_mmio_disable_event, .enable_event = intel_generic_uncore_mmio_enable_event, .read_counter = uncore_mmio_read_counter, }; #define ADL_UNC_CTL_CHMASK_MASK 0x00000f00 #define ADL_UNC_IMC_EVENT_MASK (SNB_UNC_CTL_EV_SEL_MASK | \ ADL_UNC_CTL_CHMASK_MASK | \ SNB_UNC_CTL_EDGE_DET) static struct attribute *adl_uncore_imc_formats_attr[] = { &format_attr_event.attr, &format_attr_chmask.attr, &format_attr_edge.attr, NULL, }; static const struct attribute_group adl_uncore_imc_format_group = { .name = "format", .attrs = adl_uncore_imc_formats_attr, }; static struct intel_uncore_type adl_uncore_imc = { .name = "imc", .num_counters = 5, .num_boxes = 2, .perf_ctr_bits = 64, .perf_ctr = ADL_UNCORE_IMC_CTR, .event_ctl = ADL_UNCORE_IMC_CTRL, .event_mask = ADL_UNC_IMC_EVENT_MASK, .box_ctl = ADL_UNCORE_IMC_BOX_CTL, .mmio_offset = 0, .mmio_map_size = ADL_UNCORE_IMC_MAP_SIZE, .ops = &adl_uncore_mmio_ops, .format_group = &adl_uncore_imc_format_group, }; enum perf_adl_uncore_imc_freerunning_types { ADL_MMIO_UNCORE_IMC_DATA_TOTAL, ADL_MMIO_UNCORE_IMC_DATA_READ, ADL_MMIO_UNCORE_IMC_DATA_WRITE, ADL_MMIO_UNCORE_IMC_FREERUNNING_TYPE_MAX }; static struct freerunning_counters adl_uncore_imc_freerunning[] = { [ADL_MMIO_UNCORE_IMC_DATA_TOTAL] = { 0x40, 0x0, 0x0, 1, 64 }, [ADL_MMIO_UNCORE_IMC_DATA_READ] = { 0x58, 0x0, 0x0, 1, 64 }, [ADL_MMIO_UNCORE_IMC_DATA_WRITE] = { 0xA0, 0x0, 0x0, 1, 64 }, }; static void adl_uncore_imc_freerunning_init_box(struct intel_uncore_box *box) { __uncore_imc_init_box(box, ADL_UNCORE_IMC_FREERUNNING_BASE); } static struct intel_uncore_ops adl_uncore_imc_freerunning_ops = { .init_box = adl_uncore_imc_freerunning_init_box, .exit_box = uncore_mmio_exit_box, .read_counter = uncore_mmio_read_counter, .hw_config = uncore_freerunning_hw_config, }; static struct intel_uncore_type adl_uncore_imc_free_running = { .name = "imc_free_running", .num_counters = 3, .num_boxes = 2, .num_freerunning_types = ADL_MMIO_UNCORE_IMC_FREERUNNING_TYPE_MAX, .mmio_map_size = ADL_UNCORE_IMC_FREERUNNING_MAP_SIZE, .freerunning = adl_uncore_imc_freerunning, .ops = &adl_uncore_imc_freerunning_ops, .event_descs = tgl_uncore_imc_events, .format_group = &tgl_uncore_imc_format_group, }; static struct intel_uncore_type *adl_mmio_uncores[] = { &adl_uncore_imc, &adl_uncore_imc_free_running, NULL }; void adl_uncore_mmio_init(void) { uncore_mmio_uncores = adl_mmio_uncores; } /* end of Alder Lake MMIO uncore support */
linux-master
arch/x86/events/intel/uncore_snb.c
/* * Netburst Performance Events (P4, old Xeon) * * Copyright (C) 2010 Parallels, Inc., Cyrill Gorcunov <[email protected]> * Copyright (C) 2010 Intel Corporation, Lin Ming <[email protected]> * * For licencing details see kernel-base/COPYING */ #include <linux/perf_event.h> #include <asm/perf_event_p4.h> #include <asm/hardirq.h> #include <asm/apic.h> #include "../perf_event.h" #define P4_CNTR_LIMIT 3 /* * array indices: 0,1 - HT threads, used with HT enabled cpu */ struct p4_event_bind { unsigned int opcode; /* Event code and ESCR selector */ unsigned int escr_msr[2]; /* ESCR MSR for this event */ unsigned int escr_emask; /* valid ESCR EventMask bits */ unsigned int shared; /* event is shared across threads */ signed char cntr[2][P4_CNTR_LIMIT]; /* counter index (offset), -1 on absence */ }; struct p4_pebs_bind { unsigned int metric_pebs; unsigned int metric_vert; }; /* it sets P4_PEBS_ENABLE_UOP_TAG as well */ #define P4_GEN_PEBS_BIND(name, pebs, vert) \ [P4_PEBS_METRIC__##name] = { \ .metric_pebs = pebs | P4_PEBS_ENABLE_UOP_TAG, \ .metric_vert = vert, \ } /* * note we have P4_PEBS_ENABLE_UOP_TAG always set here * * it's needed for mapping P4_PEBS_CONFIG_METRIC_MASK bits of * event configuration to find out which values are to be * written into MSR_IA32_PEBS_ENABLE and MSR_P4_PEBS_MATRIX_VERT * registers */ static struct p4_pebs_bind p4_pebs_bind_map[] = { P4_GEN_PEBS_BIND(1stl_cache_load_miss_retired, 0x0000001, 0x0000001), P4_GEN_PEBS_BIND(2ndl_cache_load_miss_retired, 0x0000002, 0x0000001), P4_GEN_PEBS_BIND(dtlb_load_miss_retired, 0x0000004, 0x0000001), P4_GEN_PEBS_BIND(dtlb_store_miss_retired, 0x0000004, 0x0000002), P4_GEN_PEBS_BIND(dtlb_all_miss_retired, 0x0000004, 0x0000003), P4_GEN_PEBS_BIND(tagged_mispred_branch, 0x0018000, 0x0000010), P4_GEN_PEBS_BIND(mob_load_replay_retired, 0x0000200, 0x0000001), P4_GEN_PEBS_BIND(split_load_retired, 0x0000400, 0x0000001), P4_GEN_PEBS_BIND(split_store_retired, 0x0000400, 0x0000002), }; /* * Note that we don't use CCCR1 here, there is an * exception for P4_BSQ_ALLOCATION but we just have * no workaround * * consider this binding as resources which particular * event may borrow, it doesn't contain EventMask, * Tags and friends -- they are left to a caller */ static struct p4_event_bind p4_event_bind_map[] = { [P4_EVENT_TC_DELIVER_MODE] = { .opcode = P4_OPCODE(P4_EVENT_TC_DELIVER_MODE), .escr_msr = { MSR_P4_TC_ESCR0, MSR_P4_TC_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_TC_DELIVER_MODE, DD) | P4_ESCR_EMASK_BIT(P4_EVENT_TC_DELIVER_MODE, DB) | P4_ESCR_EMASK_BIT(P4_EVENT_TC_DELIVER_MODE, DI) | P4_ESCR_EMASK_BIT(P4_EVENT_TC_DELIVER_MODE, BD) | P4_ESCR_EMASK_BIT(P4_EVENT_TC_DELIVER_MODE, BB) | P4_ESCR_EMASK_BIT(P4_EVENT_TC_DELIVER_MODE, BI) | P4_ESCR_EMASK_BIT(P4_EVENT_TC_DELIVER_MODE, ID), .shared = 1, .cntr = { {4, 5, -1}, {6, 7, -1} }, }, [P4_EVENT_BPU_FETCH_REQUEST] = { .opcode = P4_OPCODE(P4_EVENT_BPU_FETCH_REQUEST), .escr_msr = { MSR_P4_BPU_ESCR0, MSR_P4_BPU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_BPU_FETCH_REQUEST, TCMISS), .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_ITLB_REFERENCE] = { .opcode = P4_OPCODE(P4_EVENT_ITLB_REFERENCE), .escr_msr = { MSR_P4_ITLB_ESCR0, MSR_P4_ITLB_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_ITLB_REFERENCE, HIT) | P4_ESCR_EMASK_BIT(P4_EVENT_ITLB_REFERENCE, MISS) | P4_ESCR_EMASK_BIT(P4_EVENT_ITLB_REFERENCE, HIT_UK), .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_MEMORY_CANCEL] = { .opcode = P4_OPCODE(P4_EVENT_MEMORY_CANCEL), .escr_msr = { MSR_P4_DAC_ESCR0, MSR_P4_DAC_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_MEMORY_CANCEL, ST_RB_FULL) | P4_ESCR_EMASK_BIT(P4_EVENT_MEMORY_CANCEL, 64K_CONF), .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_MEMORY_COMPLETE] = { .opcode = P4_OPCODE(P4_EVENT_MEMORY_COMPLETE), .escr_msr = { MSR_P4_SAAT_ESCR0 , MSR_P4_SAAT_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_MEMORY_COMPLETE, LSC) | P4_ESCR_EMASK_BIT(P4_EVENT_MEMORY_COMPLETE, SSC), .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_LOAD_PORT_REPLAY] = { .opcode = P4_OPCODE(P4_EVENT_LOAD_PORT_REPLAY), .escr_msr = { MSR_P4_SAAT_ESCR0, MSR_P4_SAAT_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_LOAD_PORT_REPLAY, SPLIT_LD), .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_STORE_PORT_REPLAY] = { .opcode = P4_OPCODE(P4_EVENT_STORE_PORT_REPLAY), .escr_msr = { MSR_P4_SAAT_ESCR0 , MSR_P4_SAAT_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_STORE_PORT_REPLAY, SPLIT_ST), .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_MOB_LOAD_REPLAY] = { .opcode = P4_OPCODE(P4_EVENT_MOB_LOAD_REPLAY), .escr_msr = { MSR_P4_MOB_ESCR0, MSR_P4_MOB_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_MOB_LOAD_REPLAY, NO_STA) | P4_ESCR_EMASK_BIT(P4_EVENT_MOB_LOAD_REPLAY, NO_STD) | P4_ESCR_EMASK_BIT(P4_EVENT_MOB_LOAD_REPLAY, PARTIAL_DATA) | P4_ESCR_EMASK_BIT(P4_EVENT_MOB_LOAD_REPLAY, UNALGN_ADDR), .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_PAGE_WALK_TYPE] = { .opcode = P4_OPCODE(P4_EVENT_PAGE_WALK_TYPE), .escr_msr = { MSR_P4_PMH_ESCR0, MSR_P4_PMH_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_PAGE_WALK_TYPE, DTMISS) | P4_ESCR_EMASK_BIT(P4_EVENT_PAGE_WALK_TYPE, ITMISS), .shared = 1, .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_BSQ_CACHE_REFERENCE] = { .opcode = P4_OPCODE(P4_EVENT_BSQ_CACHE_REFERENCE), .escr_msr = { MSR_P4_BSU_ESCR0, MSR_P4_BSU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_HITS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_HITE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_HITM) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_HITS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_HITE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_HITM) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_MISS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_MISS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, WR_2ndL_MISS), .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_IOQ_ALLOCATION] = { .opcode = P4_OPCODE(P4_EVENT_IOQ_ALLOCATION), .escr_msr = { MSR_P4_FSB_ESCR0, MSR_P4_FSB_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, DEFAULT) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, ALL_READ) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, ALL_WRITE) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, MEM_UC) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, MEM_WC) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, MEM_WT) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, MEM_WP) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, MEM_WB) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, OWN) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, OTHER) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ALLOCATION, PREFETCH), .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_IOQ_ACTIVE_ENTRIES] = { /* shared ESCR */ .opcode = P4_OPCODE(P4_EVENT_IOQ_ACTIVE_ENTRIES), .escr_msr = { MSR_P4_FSB_ESCR1, MSR_P4_FSB_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, DEFAULT) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, ALL_READ) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, ALL_WRITE) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, MEM_UC) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, MEM_WC) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, MEM_WT) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, MEM_WP) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, MEM_WB) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, OWN) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, OTHER) | P4_ESCR_EMASK_BIT(P4_EVENT_IOQ_ACTIVE_ENTRIES, PREFETCH), .cntr = { {2, -1, -1}, {3, -1, -1} }, }, [P4_EVENT_FSB_DATA_ACTIVITY] = { .opcode = P4_OPCODE(P4_EVENT_FSB_DATA_ACTIVITY), .escr_msr = { MSR_P4_FSB_ESCR0, MSR_P4_FSB_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DRDY_DRV) | P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DRDY_OWN) | P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DRDY_OTHER) | P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DBSY_DRV) | P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DBSY_OWN) | P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DBSY_OTHER), .shared = 1, .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_BSQ_ALLOCATION] = { /* shared ESCR, broken CCCR1 */ .opcode = P4_OPCODE(P4_EVENT_BSQ_ALLOCATION), .escr_msr = { MSR_P4_BSU_ESCR0, MSR_P4_BSU_ESCR0 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_TYPE0) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_TYPE1) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_LEN0) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_LEN1) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_IO_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_LOCK_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_CACHE_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_SPLIT_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_DEM_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, REQ_ORD_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, MEM_TYPE0) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, MEM_TYPE1) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ALLOCATION, MEM_TYPE2), .cntr = { {0, -1, -1}, {1, -1, -1} }, }, [P4_EVENT_BSQ_ACTIVE_ENTRIES] = { /* shared ESCR */ .opcode = P4_OPCODE(P4_EVENT_BSQ_ACTIVE_ENTRIES), .escr_msr = { MSR_P4_BSU_ESCR1 , MSR_P4_BSU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_TYPE0) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_TYPE1) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_LEN0) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_LEN1) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_IO_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_LOCK_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_CACHE_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_SPLIT_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_DEM_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, REQ_ORD_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, MEM_TYPE0) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, MEM_TYPE1) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_ACTIVE_ENTRIES, MEM_TYPE2), .cntr = { {2, -1, -1}, {3, -1, -1} }, }, [P4_EVENT_SSE_INPUT_ASSIST] = { .opcode = P4_OPCODE(P4_EVENT_SSE_INPUT_ASSIST), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_SSE_INPUT_ASSIST, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_PACKED_SP_UOP] = { .opcode = P4_OPCODE(P4_EVENT_PACKED_SP_UOP), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_PACKED_SP_UOP, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_PACKED_DP_UOP] = { .opcode = P4_OPCODE(P4_EVENT_PACKED_DP_UOP), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_PACKED_DP_UOP, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_SCALAR_SP_UOP] = { .opcode = P4_OPCODE(P4_EVENT_SCALAR_SP_UOP), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_SCALAR_SP_UOP, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_SCALAR_DP_UOP] = { .opcode = P4_OPCODE(P4_EVENT_SCALAR_DP_UOP), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_SCALAR_DP_UOP, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_64BIT_MMX_UOP] = { .opcode = P4_OPCODE(P4_EVENT_64BIT_MMX_UOP), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_64BIT_MMX_UOP, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_128BIT_MMX_UOP] = { .opcode = P4_OPCODE(P4_EVENT_128BIT_MMX_UOP), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_128BIT_MMX_UOP, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_X87_FP_UOP] = { .opcode = P4_OPCODE(P4_EVENT_X87_FP_UOP), .escr_msr = { MSR_P4_FIRM_ESCR0, MSR_P4_FIRM_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_X87_FP_UOP, ALL), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_TC_MISC] = { .opcode = P4_OPCODE(P4_EVENT_TC_MISC), .escr_msr = { MSR_P4_TC_ESCR0, MSR_P4_TC_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_TC_MISC, FLUSH), .cntr = { {4, 5, -1}, {6, 7, -1} }, }, [P4_EVENT_GLOBAL_POWER_EVENTS] = { .opcode = P4_OPCODE(P4_EVENT_GLOBAL_POWER_EVENTS), .escr_msr = { MSR_P4_FSB_ESCR0, MSR_P4_FSB_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_GLOBAL_POWER_EVENTS, RUNNING), .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_TC_MS_XFER] = { .opcode = P4_OPCODE(P4_EVENT_TC_MS_XFER), .escr_msr = { MSR_P4_MS_ESCR0, MSR_P4_MS_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_TC_MS_XFER, CISC), .cntr = { {4, 5, -1}, {6, 7, -1} }, }, [P4_EVENT_UOP_QUEUE_WRITES] = { .opcode = P4_OPCODE(P4_EVENT_UOP_QUEUE_WRITES), .escr_msr = { MSR_P4_MS_ESCR0, MSR_P4_MS_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_UOP_QUEUE_WRITES, FROM_TC_BUILD) | P4_ESCR_EMASK_BIT(P4_EVENT_UOP_QUEUE_WRITES, FROM_TC_DELIVER) | P4_ESCR_EMASK_BIT(P4_EVENT_UOP_QUEUE_WRITES, FROM_ROM), .cntr = { {4, 5, -1}, {6, 7, -1} }, }, [P4_EVENT_RETIRED_MISPRED_BRANCH_TYPE] = { .opcode = P4_OPCODE(P4_EVENT_RETIRED_MISPRED_BRANCH_TYPE), .escr_msr = { MSR_P4_TBPU_ESCR0 , MSR_P4_TBPU_ESCR0 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_MISPRED_BRANCH_TYPE, CONDITIONAL) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_MISPRED_BRANCH_TYPE, CALL) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_MISPRED_BRANCH_TYPE, RETURN) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_MISPRED_BRANCH_TYPE, INDIRECT), .cntr = { {4, 5, -1}, {6, 7, -1} }, }, [P4_EVENT_RETIRED_BRANCH_TYPE] = { .opcode = P4_OPCODE(P4_EVENT_RETIRED_BRANCH_TYPE), .escr_msr = { MSR_P4_TBPU_ESCR0 , MSR_P4_TBPU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, CONDITIONAL) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, CALL) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, RETURN) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, INDIRECT), .cntr = { {4, 5, -1}, {6, 7, -1} }, }, [P4_EVENT_RESOURCE_STALL] = { .opcode = P4_OPCODE(P4_EVENT_RESOURCE_STALL), .escr_msr = { MSR_P4_ALF_ESCR0, MSR_P4_ALF_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_RESOURCE_STALL, SBFULL), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_WC_BUFFER] = { .opcode = P4_OPCODE(P4_EVENT_WC_BUFFER), .escr_msr = { MSR_P4_DAC_ESCR0, MSR_P4_DAC_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_WC_BUFFER, WCB_EVICTS) | P4_ESCR_EMASK_BIT(P4_EVENT_WC_BUFFER, WCB_FULL_EVICTS), .shared = 1, .cntr = { {8, 9, -1}, {10, 11, -1} }, }, [P4_EVENT_B2B_CYCLES] = { .opcode = P4_OPCODE(P4_EVENT_B2B_CYCLES), .escr_msr = { MSR_P4_FSB_ESCR0, MSR_P4_FSB_ESCR1 }, .escr_emask = 0, .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_BNR] = { .opcode = P4_OPCODE(P4_EVENT_BNR), .escr_msr = { MSR_P4_FSB_ESCR0, MSR_P4_FSB_ESCR1 }, .escr_emask = 0, .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_SNOOP] = { .opcode = P4_OPCODE(P4_EVENT_SNOOP), .escr_msr = { MSR_P4_FSB_ESCR0, MSR_P4_FSB_ESCR1 }, .escr_emask = 0, .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_RESPONSE] = { .opcode = P4_OPCODE(P4_EVENT_RESPONSE), .escr_msr = { MSR_P4_FSB_ESCR0, MSR_P4_FSB_ESCR1 }, .escr_emask = 0, .cntr = { {0, -1, -1}, {2, -1, -1} }, }, [P4_EVENT_FRONT_END_EVENT] = { .opcode = P4_OPCODE(P4_EVENT_FRONT_END_EVENT), .escr_msr = { MSR_P4_CRU_ESCR2, MSR_P4_CRU_ESCR3 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_FRONT_END_EVENT, NBOGUS) | P4_ESCR_EMASK_BIT(P4_EVENT_FRONT_END_EVENT, BOGUS), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_EXECUTION_EVENT] = { .opcode = P4_OPCODE(P4_EVENT_EXECUTION_EVENT), .escr_msr = { MSR_P4_CRU_ESCR2, MSR_P4_CRU_ESCR3 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS0) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS1) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS2) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS3) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS0) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS1) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS2) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS3), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_REPLAY_EVENT] = { .opcode = P4_OPCODE(P4_EVENT_REPLAY_EVENT), .escr_msr = { MSR_P4_CRU_ESCR2, MSR_P4_CRU_ESCR3 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_REPLAY_EVENT, NBOGUS) | P4_ESCR_EMASK_BIT(P4_EVENT_REPLAY_EVENT, BOGUS), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_INSTR_RETIRED] = { .opcode = P4_OPCODE(P4_EVENT_INSTR_RETIRED), .escr_msr = { MSR_P4_CRU_ESCR0, MSR_P4_CRU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_RETIRED, NBOGUSNTAG) | P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_RETIRED, NBOGUSTAG) | P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_RETIRED, BOGUSNTAG) | P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_RETIRED, BOGUSTAG), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_UOPS_RETIRED] = { .opcode = P4_OPCODE(P4_EVENT_UOPS_RETIRED), .escr_msr = { MSR_P4_CRU_ESCR0, MSR_P4_CRU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_UOPS_RETIRED, NBOGUS) | P4_ESCR_EMASK_BIT(P4_EVENT_UOPS_RETIRED, BOGUS), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_UOP_TYPE] = { .opcode = P4_OPCODE(P4_EVENT_UOP_TYPE), .escr_msr = { MSR_P4_RAT_ESCR0, MSR_P4_RAT_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_UOP_TYPE, TAGLOADS) | P4_ESCR_EMASK_BIT(P4_EVENT_UOP_TYPE, TAGSTORES), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_BRANCH_RETIRED] = { .opcode = P4_OPCODE(P4_EVENT_BRANCH_RETIRED), .escr_msr = { MSR_P4_CRU_ESCR2, MSR_P4_CRU_ESCR3 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_BRANCH_RETIRED, MMNP) | P4_ESCR_EMASK_BIT(P4_EVENT_BRANCH_RETIRED, MMNM) | P4_ESCR_EMASK_BIT(P4_EVENT_BRANCH_RETIRED, MMTP) | P4_ESCR_EMASK_BIT(P4_EVENT_BRANCH_RETIRED, MMTM), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_MISPRED_BRANCH_RETIRED] = { .opcode = P4_OPCODE(P4_EVENT_MISPRED_BRANCH_RETIRED), .escr_msr = { MSR_P4_CRU_ESCR0, MSR_P4_CRU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_MISPRED_BRANCH_RETIRED, NBOGUS), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_X87_ASSIST] = { .opcode = P4_OPCODE(P4_EVENT_X87_ASSIST), .escr_msr = { MSR_P4_CRU_ESCR2, MSR_P4_CRU_ESCR3 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_X87_ASSIST, FPSU) | P4_ESCR_EMASK_BIT(P4_EVENT_X87_ASSIST, FPSO) | P4_ESCR_EMASK_BIT(P4_EVENT_X87_ASSIST, POAO) | P4_ESCR_EMASK_BIT(P4_EVENT_X87_ASSIST, POAU) | P4_ESCR_EMASK_BIT(P4_EVENT_X87_ASSIST, PREA), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_MACHINE_CLEAR] = { .opcode = P4_OPCODE(P4_EVENT_MACHINE_CLEAR), .escr_msr = { MSR_P4_CRU_ESCR2, MSR_P4_CRU_ESCR3 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_MACHINE_CLEAR, CLEAR) | P4_ESCR_EMASK_BIT(P4_EVENT_MACHINE_CLEAR, MOCLEAR) | P4_ESCR_EMASK_BIT(P4_EVENT_MACHINE_CLEAR, SMCLEAR), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, [P4_EVENT_INSTR_COMPLETED] = { .opcode = P4_OPCODE(P4_EVENT_INSTR_COMPLETED), .escr_msr = { MSR_P4_CRU_ESCR0, MSR_P4_CRU_ESCR1 }, .escr_emask = P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_COMPLETED, NBOGUS) | P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_COMPLETED, BOGUS), .cntr = { {12, 13, 16}, {14, 15, 17} }, }, }; #define P4_GEN_CACHE_EVENT(event, bit, metric) \ p4_config_pack_escr(P4_ESCR_EVENT(event) | \ P4_ESCR_EMASK_BIT(event, bit)) | \ p4_config_pack_cccr(metric | \ P4_CCCR_ESEL(P4_OPCODE_ESEL(P4_OPCODE(event)))) static __initconst const u64 p4_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = P4_GEN_CACHE_EVENT(P4_EVENT_REPLAY_EVENT, NBOGUS, P4_PEBS_METRIC__1stl_cache_load_miss_retired), }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = P4_GEN_CACHE_EVENT(P4_EVENT_REPLAY_EVENT, NBOGUS, P4_PEBS_METRIC__2ndl_cache_load_miss_retired), }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = P4_GEN_CACHE_EVENT(P4_EVENT_REPLAY_EVENT, NBOGUS, P4_PEBS_METRIC__dtlb_load_miss_retired), }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x0, [ C(RESULT_MISS) ] = P4_GEN_CACHE_EVENT(P4_EVENT_REPLAY_EVENT, NBOGUS, P4_PEBS_METRIC__dtlb_store_miss_retired), }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = P4_GEN_CACHE_EVENT(P4_EVENT_ITLB_REFERENCE, HIT, P4_PEBS_METRIC__none), [ C(RESULT_MISS) ] = P4_GEN_CACHE_EVENT(P4_EVENT_ITLB_REFERENCE, MISS, P4_PEBS_METRIC__none), }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, }; /* * Because of Netburst being quite restricted in how many * identical events may run simultaneously, we introduce event aliases, * ie the different events which have the same functionality but * utilize non-intersected resources (ESCR/CCCR/counter registers). * * This allow us to relax restrictions a bit and run two or more * identical events together. * * Never set any custom internal bits such as P4_CONFIG_HT, * P4_CONFIG_ALIASABLE or bits for P4_PEBS_METRIC, they are * either up to date automatically or not applicable at all. */ static struct p4_event_alias { u64 original; u64 alternative; } p4_event_aliases[] = { { /* * Non-halted cycles can be substituted with non-sleeping cycles (see * Intel SDM Vol3b for details). We need this alias to be able * to run nmi-watchdog and 'perf top' (or any other user space tool * which is interested in running PERF_COUNT_HW_CPU_CYCLES) * simultaneously. */ .original = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_GLOBAL_POWER_EVENTS) | P4_ESCR_EMASK_BIT(P4_EVENT_GLOBAL_POWER_EVENTS, RUNNING)), .alternative = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_EXECUTION_EVENT) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS0)| P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS1)| P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS2)| P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, NBOGUS3)| P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS0) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS1) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS2) | P4_ESCR_EMASK_BIT(P4_EVENT_EXECUTION_EVENT, BOGUS3))| p4_config_pack_cccr(P4_CCCR_THRESHOLD(15) | P4_CCCR_COMPLEMENT | P4_CCCR_COMPARE), }, }; static u64 p4_get_alias_event(u64 config) { u64 config_match; int i; /* * Only event with special mark is allowed, * we're to be sure it didn't come as malformed * RAW event. */ if (!(config & P4_CONFIG_ALIASABLE)) return 0; config_match = config & P4_CONFIG_EVENT_ALIAS_MASK; for (i = 0; i < ARRAY_SIZE(p4_event_aliases); i++) { if (config_match == p4_event_aliases[i].original) { config_match = p4_event_aliases[i].alternative; break; } else if (config_match == p4_event_aliases[i].alternative) { config_match = p4_event_aliases[i].original; break; } } if (i >= ARRAY_SIZE(p4_event_aliases)) return 0; return config_match | (config & P4_CONFIG_EVENT_ALIAS_IMMUTABLE_BITS); } static u64 p4_general_events[PERF_COUNT_HW_MAX] = { /* non-halted CPU clocks */ [PERF_COUNT_HW_CPU_CYCLES] = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_GLOBAL_POWER_EVENTS) | P4_ESCR_EMASK_BIT(P4_EVENT_GLOBAL_POWER_EVENTS, RUNNING)) | P4_CONFIG_ALIASABLE, /* * retired instructions * in a sake of simplicity we don't use the FSB tagging */ [PERF_COUNT_HW_INSTRUCTIONS] = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_INSTR_RETIRED) | P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_RETIRED, NBOGUSNTAG) | P4_ESCR_EMASK_BIT(P4_EVENT_INSTR_RETIRED, BOGUSNTAG)), /* cache hits */ [PERF_COUNT_HW_CACHE_REFERENCES] = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_BSQ_CACHE_REFERENCE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_HITS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_HITE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_HITM) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_HITS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_HITE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_HITM)), /* cache misses */ [PERF_COUNT_HW_CACHE_MISSES] = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_BSQ_CACHE_REFERENCE) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_2ndL_MISS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, RD_3rdL_MISS) | P4_ESCR_EMASK_BIT(P4_EVENT_BSQ_CACHE_REFERENCE, WR_2ndL_MISS)), /* branch instructions retired */ [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_RETIRED_BRANCH_TYPE) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, CONDITIONAL) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, CALL) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, RETURN) | P4_ESCR_EMASK_BIT(P4_EVENT_RETIRED_BRANCH_TYPE, INDIRECT)), /* mispredicted branches retired */ [PERF_COUNT_HW_BRANCH_MISSES] = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_MISPRED_BRANCH_RETIRED) | P4_ESCR_EMASK_BIT(P4_EVENT_MISPRED_BRANCH_RETIRED, NBOGUS)), /* bus ready clocks (cpu is driving #DRDY_DRV\#DRDY_OWN): */ [PERF_COUNT_HW_BUS_CYCLES] = p4_config_pack_escr(P4_ESCR_EVENT(P4_EVENT_FSB_DATA_ACTIVITY) | P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DRDY_DRV) | P4_ESCR_EMASK_BIT(P4_EVENT_FSB_DATA_ACTIVITY, DRDY_OWN)) | p4_config_pack_cccr(P4_CCCR_EDGE | P4_CCCR_COMPARE), }; static struct p4_event_bind *p4_config_get_bind(u64 config) { unsigned int evnt = p4_config_unpack_event(config); struct p4_event_bind *bind = NULL; if (evnt < ARRAY_SIZE(p4_event_bind_map)) bind = &p4_event_bind_map[evnt]; return bind; } static u64 p4_pmu_event_map(int hw_event) { struct p4_event_bind *bind; unsigned int esel; u64 config; config = p4_general_events[hw_event]; bind = p4_config_get_bind(config); esel = P4_OPCODE_ESEL(bind->opcode); config |= p4_config_pack_cccr(P4_CCCR_ESEL(esel)); return config; } /* check cpu model specifics */ static bool p4_event_match_cpu_model(unsigned int event_idx) { /* INSTR_COMPLETED event only exist for model 3, 4, 6 (Prescott) */ if (event_idx == P4_EVENT_INSTR_COMPLETED) { if (boot_cpu_data.x86_model != 3 && boot_cpu_data.x86_model != 4 && boot_cpu_data.x86_model != 6) return false; } /* * For info * - IQ_ESCR0, IQ_ESCR1 only for models 1 and 2 */ return true; } static int p4_validate_raw_event(struct perf_event *event) { unsigned int v, emask; /* User data may have out-of-bound event index */ v = p4_config_unpack_event(event->attr.config); if (v >= ARRAY_SIZE(p4_event_bind_map)) return -EINVAL; /* It may be unsupported: */ if (!p4_event_match_cpu_model(v)) return -EINVAL; /* * NOTE: P4_CCCR_THREAD_ANY has not the same meaning as * in Architectural Performance Monitoring, it means not * on _which_ logical cpu to count but rather _when_, ie it * depends on logical cpu state -- count event if one cpu active, * none, both or any, so we just allow user to pass any value * desired. * * In turn we always set Tx_OS/Tx_USR bits bound to logical * cpu without their propagation to another cpu */ /* * if an event is shared across the logical threads * the user needs special permissions to be able to use it */ if (p4_ht_active() && p4_event_bind_map[v].shared) { v = perf_allow_cpu(&event->attr); if (v) return v; } /* ESCR EventMask bits may be invalid */ emask = p4_config_unpack_escr(event->attr.config) & P4_ESCR_EVENTMASK_MASK; if (emask & ~p4_event_bind_map[v].escr_emask) return -EINVAL; /* * it may have some invalid PEBS bits */ if (p4_config_pebs_has(event->attr.config, P4_PEBS_CONFIG_ENABLE)) return -EINVAL; v = p4_config_unpack_metric(event->attr.config); if (v >= ARRAY_SIZE(p4_pebs_bind_map)) return -EINVAL; return 0; } static int p4_hw_config(struct perf_event *event) { int cpu = get_cpu(); int rc = 0; u32 escr, cccr; /* * the reason we use cpu that early is that: if we get scheduled * first time on the same cpu -- we will not need swap thread * specific flags in config (and will save some cpu cycles) */ cccr = p4_default_cccr_conf(cpu); escr = p4_default_escr_conf(cpu, event->attr.exclude_kernel, event->attr.exclude_user); event->hw.config = p4_config_pack_escr(escr) | p4_config_pack_cccr(cccr); if (p4_ht_active() && p4_ht_thread(cpu)) event->hw.config = p4_set_ht_bit(event->hw.config); if (event->attr.type == PERF_TYPE_RAW) { struct p4_event_bind *bind; unsigned int esel; /* * Clear bits we reserve to be managed by kernel itself * and never allowed from a user space */ event->attr.config &= P4_CONFIG_MASK; rc = p4_validate_raw_event(event); if (rc) goto out; /* * Note that for RAW events we allow user to use P4_CCCR_RESERVED * bits since we keep additional info here (for cache events and etc) */ event->hw.config |= event->attr.config; bind = p4_config_get_bind(event->attr.config); if (!bind) { rc = -EINVAL; goto out; } esel = P4_OPCODE_ESEL(bind->opcode); event->hw.config |= p4_config_pack_cccr(P4_CCCR_ESEL(esel)); } rc = x86_setup_perfctr(event); out: put_cpu(); return rc; } static inline int p4_pmu_clear_cccr_ovf(struct hw_perf_event *hwc) { u64 v; /* an official way for overflow indication */ rdmsrl(hwc->config_base, v); if (v & P4_CCCR_OVF) { wrmsrl(hwc->config_base, v & ~P4_CCCR_OVF); return 1; } /* * In some circumstances the overflow might issue an NMI but did * not set P4_CCCR_OVF bit. Because a counter holds a negative value * we simply check for high bit being set, if it's cleared it means * the counter has reached zero value and continued counting before * real NMI signal was received: */ rdmsrl(hwc->event_base, v); if (!(v & ARCH_P4_UNFLAGGED_BIT)) return 1; return 0; } static void p4_pmu_disable_pebs(void) { /* * FIXME * * It's still allowed that two threads setup same cache * events so we can't simply clear metrics until we knew * no one is depending on us, so we need kind of counter * for "ReplayEvent" users. * * What is more complex -- RAW events, if user (for some * reason) will pass some cache event metric with improper * event opcode -- it's fine from hardware point of view * but completely nonsense from "meaning" of such action. * * So at moment let leave metrics turned on forever -- it's * ok for now but need to be revisited! * * (void)wrmsrl_safe(MSR_IA32_PEBS_ENABLE, 0); * (void)wrmsrl_safe(MSR_P4_PEBS_MATRIX_VERT, 0); */ } static inline void p4_pmu_disable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; /* * If event gets disabled while counter is in overflowed * state we need to clear P4_CCCR_OVF, otherwise interrupt get * asserted again and again */ (void)wrmsrl_safe(hwc->config_base, p4_config_unpack_cccr(hwc->config) & ~P4_CCCR_ENABLE & ~P4_CCCR_OVF & ~P4_CCCR_RESERVED); } static void p4_pmu_disable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int idx; for (idx = 0; idx < x86_pmu.num_counters; idx++) { struct perf_event *event = cpuc->events[idx]; if (!test_bit(idx, cpuc->active_mask)) continue; p4_pmu_disable_event(event); } p4_pmu_disable_pebs(); } /* configuration must be valid */ static void p4_pmu_enable_pebs(u64 config) { struct p4_pebs_bind *bind; unsigned int idx; BUILD_BUG_ON(P4_PEBS_METRIC__max > P4_PEBS_CONFIG_METRIC_MASK); idx = p4_config_unpack_metric(config); if (idx == P4_PEBS_METRIC__none) return; bind = &p4_pebs_bind_map[idx]; (void)wrmsrl_safe(MSR_IA32_PEBS_ENABLE, (u64)bind->metric_pebs); (void)wrmsrl_safe(MSR_P4_PEBS_MATRIX_VERT, (u64)bind->metric_vert); } static void __p4_pmu_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int thread = p4_ht_config_thread(hwc->config); u64 escr_conf = p4_config_unpack_escr(p4_clear_ht_bit(hwc->config)); unsigned int idx = p4_config_unpack_event(hwc->config); struct p4_event_bind *bind; u64 escr_addr, cccr; bind = &p4_event_bind_map[idx]; escr_addr = bind->escr_msr[thread]; /* * - we dont support cascaded counters yet * - and counter 1 is broken (erratum) */ WARN_ON_ONCE(p4_is_event_cascaded(hwc->config)); WARN_ON_ONCE(hwc->idx == 1); /* we need a real Event value */ escr_conf &= ~P4_ESCR_EVENT_MASK; escr_conf |= P4_ESCR_EVENT(P4_OPCODE_EVNT(bind->opcode)); cccr = p4_config_unpack_cccr(hwc->config); /* * it could be Cache event so we need to write metrics * into additional MSRs */ p4_pmu_enable_pebs(hwc->config); (void)wrmsrl_safe(escr_addr, escr_conf); (void)wrmsrl_safe(hwc->config_base, (cccr & ~P4_CCCR_RESERVED) | P4_CCCR_ENABLE); } static DEFINE_PER_CPU(unsigned long [BITS_TO_LONGS(X86_PMC_IDX_MAX)], p4_running); static void p4_pmu_enable_event(struct perf_event *event) { int idx = event->hw.idx; __set_bit(idx, per_cpu(p4_running, smp_processor_id())); __p4_pmu_enable_event(event); } static void p4_pmu_enable_all(int added) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int idx; for (idx = 0; idx < x86_pmu.num_counters; idx++) { struct perf_event *event = cpuc->events[idx]; if (!test_bit(idx, cpuc->active_mask)) continue; __p4_pmu_enable_event(event); } } static int p4_pmu_set_period(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; s64 left = this_cpu_read(pmc_prev_left[hwc->idx]); int ret; ret = x86_perf_event_set_period(event); if (hwc->event_base) { /* * This handles erratum N15 in intel doc 249199-029, * the counter may not be updated correctly on write * so we need a second write operation to do the trick * (the official workaround didn't work) * * the former idea is taken from OProfile code */ wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask); } return ret; } static int p4_pmu_handle_irq(struct pt_regs *regs) { struct perf_sample_data data; struct cpu_hw_events *cpuc; struct perf_event *event; struct hw_perf_event *hwc; int idx, handled = 0; u64 val; cpuc = this_cpu_ptr(&cpu_hw_events); for (idx = 0; idx < x86_pmu.num_counters; idx++) { int overflow; if (!test_bit(idx, cpuc->active_mask)) { /* catch in-flight IRQs */ if (__test_and_clear_bit(idx, per_cpu(p4_running, smp_processor_id()))) handled++; continue; } event = cpuc->events[idx]; hwc = &event->hw; WARN_ON_ONCE(hwc->idx != idx); /* it might be unflagged overflow */ overflow = p4_pmu_clear_cccr_ovf(hwc); val = x86_perf_event_update(event); if (!overflow && (val & (1ULL << (x86_pmu.cntval_bits - 1)))) continue; handled += overflow; /* event overflow for sure */ perf_sample_data_init(&data, 0, hwc->last_period); if (!static_call(x86_pmu_set_period)(event)) continue; if (perf_event_overflow(event, &data, regs)) x86_pmu_stop(event, 0); } if (handled) inc_irq_stat(apic_perf_irqs); /* * When dealing with the unmasking of the LVTPC on P4 perf hw, it has * been observed that the OVF bit flag has to be cleared first _before_ * the LVTPC can be unmasked. * * The reason is the NMI line will continue to be asserted while the OVF * bit is set. This causes a second NMI to generate if the LVTPC is * unmasked before the OVF bit is cleared, leading to unknown NMI * messages. */ apic_write(APIC_LVTPC, APIC_DM_NMI); return handled; } /* * swap thread specific fields according to a thread * we are going to run on */ static void p4_pmu_swap_config_ts(struct hw_perf_event *hwc, int cpu) { u32 escr, cccr; /* * we either lucky and continue on same cpu or no HT support */ if (!p4_should_swap_ts(hwc->config, cpu)) return; /* * the event is migrated from an another logical * cpu, so we need to swap thread specific flags */ escr = p4_config_unpack_escr(hwc->config); cccr = p4_config_unpack_cccr(hwc->config); if (p4_ht_thread(cpu)) { cccr &= ~P4_CCCR_OVF_PMI_T0; cccr |= P4_CCCR_OVF_PMI_T1; if (escr & P4_ESCR_T0_OS) { escr &= ~P4_ESCR_T0_OS; escr |= P4_ESCR_T1_OS; } if (escr & P4_ESCR_T0_USR) { escr &= ~P4_ESCR_T0_USR; escr |= P4_ESCR_T1_USR; } hwc->config = p4_config_pack_escr(escr); hwc->config |= p4_config_pack_cccr(cccr); hwc->config |= P4_CONFIG_HT; } else { cccr &= ~P4_CCCR_OVF_PMI_T1; cccr |= P4_CCCR_OVF_PMI_T0; if (escr & P4_ESCR_T1_OS) { escr &= ~P4_ESCR_T1_OS; escr |= P4_ESCR_T0_OS; } if (escr & P4_ESCR_T1_USR) { escr &= ~P4_ESCR_T1_USR; escr |= P4_ESCR_T0_USR; } hwc->config = p4_config_pack_escr(escr); hwc->config |= p4_config_pack_cccr(cccr); hwc->config &= ~P4_CONFIG_HT; } } /* * ESCR address hashing is tricky, ESCRs are not sequential * in memory but all starts from MSR_P4_BSU_ESCR0 (0x03a0) and * the metric between any ESCRs is laid in range [0xa0,0xe1] * * so we make ~70% filled hashtable */ #define P4_ESCR_MSR_BASE 0x000003a0 #define P4_ESCR_MSR_MAX 0x000003e1 #define P4_ESCR_MSR_TABLE_SIZE (P4_ESCR_MSR_MAX - P4_ESCR_MSR_BASE + 1) #define P4_ESCR_MSR_IDX(msr) (msr - P4_ESCR_MSR_BASE) #define P4_ESCR_MSR_TABLE_ENTRY(msr) [P4_ESCR_MSR_IDX(msr)] = msr static const unsigned int p4_escr_table[P4_ESCR_MSR_TABLE_SIZE] = { P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_ALF_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_ALF_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_BPU_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_BPU_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_BSU_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_BSU_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_CRU_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_CRU_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_CRU_ESCR2), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_CRU_ESCR3), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_CRU_ESCR4), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_CRU_ESCR5), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_DAC_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_DAC_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_FIRM_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_FIRM_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_FLAME_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_FLAME_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_FSB_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_FSB_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_IQ_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_IQ_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_IS_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_IS_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_ITLB_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_ITLB_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_IX_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_IX_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_MOB_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_MOB_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_MS_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_MS_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_PMH_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_PMH_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_RAT_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_RAT_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_SAAT_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_SAAT_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_SSU_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_SSU_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_TBPU_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_TBPU_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_TC_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_TC_ESCR1), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_U2L_ESCR0), P4_ESCR_MSR_TABLE_ENTRY(MSR_P4_U2L_ESCR1), }; static int p4_get_escr_idx(unsigned int addr) { unsigned int idx = P4_ESCR_MSR_IDX(addr); if (unlikely(idx >= P4_ESCR_MSR_TABLE_SIZE || !p4_escr_table[idx] || p4_escr_table[idx] != addr)) { WARN_ONCE(1, "P4 PMU: Wrong address passed: %x\n", addr); return -1; } return idx; } static int p4_next_cntr(int thread, unsigned long *used_mask, struct p4_event_bind *bind) { int i, j; for (i = 0; i < P4_CNTR_LIMIT; i++) { j = bind->cntr[thread][i]; if (j != -1 && !test_bit(j, used_mask)) return j; } return -1; } static int p4_pmu_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign) { unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)]; unsigned long escr_mask[BITS_TO_LONGS(P4_ESCR_MSR_TABLE_SIZE)]; int cpu = smp_processor_id(); struct hw_perf_event *hwc; struct p4_event_bind *bind; unsigned int i, thread, num; int cntr_idx, escr_idx; u64 config_alias; int pass; bitmap_zero(used_mask, X86_PMC_IDX_MAX); bitmap_zero(escr_mask, P4_ESCR_MSR_TABLE_SIZE); for (i = 0, num = n; i < n; i++, num--) { hwc = &cpuc->event_list[i]->hw; thread = p4_ht_thread(cpu); pass = 0; again: /* * It's possible to hit a circular lock * between original and alternative events * if both are scheduled already. */ if (pass > 2) goto done; bind = p4_config_get_bind(hwc->config); escr_idx = p4_get_escr_idx(bind->escr_msr[thread]); if (unlikely(escr_idx == -1)) goto done; if (hwc->idx != -1 && !p4_should_swap_ts(hwc->config, cpu)) { cntr_idx = hwc->idx; if (assign) assign[i] = hwc->idx; goto reserve; } cntr_idx = p4_next_cntr(thread, used_mask, bind); if (cntr_idx == -1 || test_bit(escr_idx, escr_mask)) { /* * Check whether an event alias is still available. */ config_alias = p4_get_alias_event(hwc->config); if (!config_alias) goto done; hwc->config = config_alias; pass++; goto again; } /* * Perf does test runs to see if a whole group can be assigned * together successfully. There can be multiple rounds of this. * Unfortunately, p4_pmu_swap_config_ts touches the hwc->config * bits, such that the next round of group assignments will * cause the above p4_should_swap_ts to pass instead of fail. * This leads to counters exclusive to thread0 being used by * thread1. * * Solve this with a cheap hack, reset the idx back to -1 to * force a new lookup (p4_next_cntr) to get the right counter * for the right thread. * * This probably doesn't comply with the general spirit of how * perf wants to work, but P4 is special. :-( */ if (p4_should_swap_ts(hwc->config, cpu)) hwc->idx = -1; p4_pmu_swap_config_ts(hwc, cpu); if (assign) assign[i] = cntr_idx; reserve: set_bit(cntr_idx, used_mask); set_bit(escr_idx, escr_mask); } done: return num ? -EINVAL : 0; } PMU_FORMAT_ATTR(cccr, "config:0-31" ); PMU_FORMAT_ATTR(escr, "config:32-62"); PMU_FORMAT_ATTR(ht, "config:63" ); static struct attribute *intel_p4_formats_attr[] = { &format_attr_cccr.attr, &format_attr_escr.attr, &format_attr_ht.attr, NULL, }; static __initconst const struct x86_pmu p4_pmu = { .name = "Netburst P4/Xeon", .handle_irq = p4_pmu_handle_irq, .disable_all = p4_pmu_disable_all, .enable_all = p4_pmu_enable_all, .enable = p4_pmu_enable_event, .disable = p4_pmu_disable_event, .set_period = p4_pmu_set_period, .eventsel = MSR_P4_BPU_CCCR0, .perfctr = MSR_P4_BPU_PERFCTR0, .event_map = p4_pmu_event_map, .max_events = ARRAY_SIZE(p4_general_events), .get_event_constraints = x86_get_event_constraints, /* * IF HT disabled we may need to use all * ARCH_P4_MAX_CCCR counters simultaneously * though leave it restricted at moment assuming * HT is on */ .num_counters = ARCH_P4_MAX_CCCR, .apic = 1, .cntval_bits = ARCH_P4_CNTRVAL_BITS, .cntval_mask = ARCH_P4_CNTRVAL_MASK, .max_period = (1ULL << (ARCH_P4_CNTRVAL_BITS - 1)) - 1, .hw_config = p4_hw_config, .schedule_events = p4_pmu_schedule_events, .format_attrs = intel_p4_formats_attr, }; __init int p4_pmu_init(void) { unsigned int low, high; int i, reg; /* If we get stripped -- indexing fails */ BUILD_BUG_ON(ARCH_P4_MAX_CCCR > INTEL_PMC_MAX_GENERIC); rdmsr(MSR_IA32_MISC_ENABLE, low, high); if (!(low & (1 << 7))) { pr_cont("unsupported Netburst CPU model %d ", boot_cpu_data.x86_model); return -ENODEV; } memcpy(hw_cache_event_ids, p4_hw_cache_event_ids, sizeof(hw_cache_event_ids)); pr_cont("Netburst events, "); x86_pmu = p4_pmu; /* * Even though the counters are configured to interrupt a particular * logical processor when an overflow happens, testing has shown that * on kdump kernels (which uses a single cpu), thread1's counter * continues to run and will report an NMI on thread0. Due to the * overflow bug, this leads to a stream of unknown NMIs. * * Solve this by zero'ing out the registers to mimic a reset. */ for (i = 0; i < x86_pmu.num_counters; i++) { reg = x86_pmu_config_addr(i); wrmsrl_safe(reg, 0ULL); } return 0; }
linux-master
arch/x86/events/intel/p4.c
/* * Performance events - AMD IBS * * Copyright (C) 2011 Advanced Micro Devices, Inc., Robert Richter * * For licencing details see kernel-base/COPYING */ #include <linux/perf_event.h> #include <linux/init.h> #include <linux/export.h> #include <linux/pci.h> #include <linux/ptrace.h> #include <linux/syscore_ops.h> #include <linux/sched/clock.h> #include <asm/apic.h> #include "../perf_event.h" static u32 ibs_caps; #if defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_AMD) #include <linux/kprobes.h> #include <linux/hardirq.h> #include <asm/nmi.h> #include <asm/amd-ibs.h> #define IBS_FETCH_CONFIG_MASK (IBS_FETCH_RAND_EN | IBS_FETCH_MAX_CNT) #define IBS_OP_CONFIG_MASK IBS_OP_MAX_CNT /* * IBS states: * * ENABLED; tracks the pmu::add(), pmu::del() state, when set the counter is taken * and any further add()s must fail. * * STARTED/STOPPING/STOPPED; deal with pmu::start(), pmu::stop() state but are * complicated by the fact that the IBS hardware can send late NMIs (ie. after * we've cleared the EN bit). * * In order to consume these late NMIs we have the STOPPED state, any NMI that * happens after we've cleared the EN state will clear this bit and report the * NMI handled (this is fundamentally racy in the face or multiple NMI sources, * someone else can consume our BIT and our NMI will go unhandled). * * And since we cannot set/clear this separate bit together with the EN bit, * there are races; if we cleared STARTED early, an NMI could land in * between clearing STARTED and clearing the EN bit (in fact multiple NMIs * could happen if the period is small enough), and consume our STOPPED bit * and trigger streams of unhandled NMIs. * * If, however, we clear STARTED late, an NMI can hit between clearing the * EN bit and clearing STARTED, still see STARTED set and process the event. * If this event will have the VALID bit clear, we bail properly, but this * is not a given. With VALID set we can end up calling pmu::stop() again * (the throttle logic) and trigger the WARNs in there. * * So what we do is set STOPPING before clearing EN to avoid the pmu::stop() * nesting, and clear STARTED late, so that we have a well defined state over * the clearing of the EN bit. * * XXX: we could probably be using !atomic bitops for all this. */ enum ibs_states { IBS_ENABLED = 0, IBS_STARTED = 1, IBS_STOPPING = 2, IBS_STOPPED = 3, IBS_MAX_STATES, }; struct cpu_perf_ibs { struct perf_event *event; unsigned long state[BITS_TO_LONGS(IBS_MAX_STATES)]; }; struct perf_ibs { struct pmu pmu; unsigned int msr; u64 config_mask; u64 cnt_mask; u64 enable_mask; u64 valid_mask; u64 max_period; unsigned long offset_mask[1]; int offset_max; unsigned int fetch_count_reset_broken : 1; unsigned int fetch_ignore_if_zero_rip : 1; struct cpu_perf_ibs __percpu *pcpu; u64 (*get_count)(u64 config); }; static int perf_event_set_period(struct hw_perf_event *hwc, u64 min, u64 max, u64 *hw_period) { s64 left = local64_read(&hwc->period_left); s64 period = hwc->sample_period; int overflow = 0; /* * If we are way outside a reasonable range then just skip forward: */ if (unlikely(left <= -period)) { left = period; local64_set(&hwc->period_left, left); hwc->last_period = period; overflow = 1; } if (unlikely(left < (s64)min)) { left += period; local64_set(&hwc->period_left, left); hwc->last_period = period; overflow = 1; } /* * If the hw period that triggers the sw overflow is too short * we might hit the irq handler. This biases the results. * Thus we shorten the next-to-last period and set the last * period to the max period. */ if (left > max) { left -= max; if (left > max) left = max; else if (left < min) left = min; } *hw_period = (u64)left; return overflow; } static int perf_event_try_update(struct perf_event *event, u64 new_raw_count, int width) { struct hw_perf_event *hwc = &event->hw; int shift = 64 - width; u64 prev_raw_count; u64 delta; /* * Careful: an NMI might modify the previous event value. * * Our tactic to handle this is to first atomically read and * exchange a new raw count - then add that new-prev delta * count to the generic event atomically: */ prev_raw_count = local64_read(&hwc->prev_count); if (!local64_try_cmpxchg(&hwc->prev_count, &prev_raw_count, new_raw_count)) return 0; /* * Now we have the new raw value and have updated the prev * timestamp already. We can now calculate the elapsed delta * (event-)time and add that to the generic event. * * Careful, not all hw sign-extends above the physical width * of the count. */ delta = (new_raw_count << shift) - (prev_raw_count << shift); delta >>= shift; local64_add(delta, &event->count); local64_sub(delta, &hwc->period_left); return 1; } static struct perf_ibs perf_ibs_fetch; static struct perf_ibs perf_ibs_op; static struct perf_ibs *get_ibs_pmu(int type) { if (perf_ibs_fetch.pmu.type == type) return &perf_ibs_fetch; if (perf_ibs_op.pmu.type == type) return &perf_ibs_op; return NULL; } /* * core pmu config -> IBS config * * perf record -a -e cpu-cycles:p ... # use ibs op counting cycle count * perf record -a -e r076:p ... # same as -e cpu-cycles:p * perf record -a -e r0C1:p ... # use ibs op counting micro-ops * * IbsOpCntCtl (bit 19) of IBS Execution Control Register (IbsOpCtl, * MSRC001_1033) is used to select either cycle or micro-ops counting * mode. */ static int core_pmu_ibs_config(struct perf_event *event, u64 *config) { switch (event->attr.type) { case PERF_TYPE_HARDWARE: switch (event->attr.config) { case PERF_COUNT_HW_CPU_CYCLES: *config = 0; return 0; } break; case PERF_TYPE_RAW: switch (event->attr.config) { case 0x0076: *config = 0; return 0; case 0x00C1: *config = IBS_OP_CNT_CTL; return 0; } break; default: return -ENOENT; } return -EOPNOTSUPP; } /* * The rip of IBS samples has skid 0. Thus, IBS supports precise * levels 1 and 2 and the PERF_EFLAGS_EXACT is set. In rare cases the * rip is invalid when IBS was not able to record the rip correctly. * We clear PERF_EFLAGS_EXACT and take the rip from pt_regs then. */ int forward_event_to_ibs(struct perf_event *event) { u64 config = 0; if (!event->attr.precise_ip || event->attr.precise_ip > 2) return -EOPNOTSUPP; if (!core_pmu_ibs_config(event, &config)) { event->attr.type = perf_ibs_op.pmu.type; event->attr.config = config; } return -ENOENT; } /* * Grouping of IBS events is not possible since IBS can have only * one event active at any point in time. */ static int validate_group(struct perf_event *event) { struct perf_event *sibling; if (event->group_leader == event) return 0; if (event->group_leader->pmu == event->pmu) return -EINVAL; for_each_sibling_event(sibling, event->group_leader) { if (sibling->pmu == event->pmu) return -EINVAL; } return 0; } static int perf_ibs_init(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; struct perf_ibs *perf_ibs; u64 max_cnt, config; int ret; perf_ibs = get_ibs_pmu(event->attr.type); if (!perf_ibs) return -ENOENT; config = event->attr.config; if (event->pmu != &perf_ibs->pmu) return -ENOENT; if (config & ~perf_ibs->config_mask) return -EINVAL; ret = validate_group(event); if (ret) return ret; if (hwc->sample_period) { if (config & perf_ibs->cnt_mask) /* raw max_cnt may not be set */ return -EINVAL; if (!event->attr.sample_freq && hwc->sample_period & 0x0f) /* * lower 4 bits can not be set in ibs max cnt, * but allowing it in case we adjust the * sample period to set a frequency. */ return -EINVAL; hwc->sample_period &= ~0x0FULL; if (!hwc->sample_period) hwc->sample_period = 0x10; } else { max_cnt = config & perf_ibs->cnt_mask; config &= ~perf_ibs->cnt_mask; event->attr.sample_period = max_cnt << 4; hwc->sample_period = event->attr.sample_period; } if (!hwc->sample_period) return -EINVAL; /* * If we modify hwc->sample_period, we also need to update * hwc->last_period and hwc->period_left. */ hwc->last_period = hwc->sample_period; local64_set(&hwc->period_left, hwc->sample_period); hwc->config_base = perf_ibs->msr; hwc->config = config; return 0; } static int perf_ibs_set_period(struct perf_ibs *perf_ibs, struct hw_perf_event *hwc, u64 *period) { int overflow; /* ignore lower 4 bits in min count: */ overflow = perf_event_set_period(hwc, 1<<4, perf_ibs->max_period, period); local64_set(&hwc->prev_count, 0); return overflow; } static u64 get_ibs_fetch_count(u64 config) { union ibs_fetch_ctl fetch_ctl = (union ibs_fetch_ctl)config; return fetch_ctl.fetch_cnt << 4; } static u64 get_ibs_op_count(u64 config) { union ibs_op_ctl op_ctl = (union ibs_op_ctl)config; u64 count = 0; /* * If the internal 27-bit counter rolled over, the count is MaxCnt * and the lower 7 bits of CurCnt are randomized. * Otherwise CurCnt has the full 27-bit current counter value. */ if (op_ctl.op_val) { count = op_ctl.opmaxcnt << 4; if (ibs_caps & IBS_CAPS_OPCNTEXT) count += op_ctl.opmaxcnt_ext << 20; } else if (ibs_caps & IBS_CAPS_RDWROPCNT) { count = op_ctl.opcurcnt; } return count; } static void perf_ibs_event_update(struct perf_ibs *perf_ibs, struct perf_event *event, u64 *config) { u64 count = perf_ibs->get_count(*config); /* * Set width to 64 since we do not overflow on max width but * instead on max count. In perf_ibs_set_period() we clear * prev count manually on overflow. */ while (!perf_event_try_update(event, count, 64)) { rdmsrl(event->hw.config_base, *config); count = perf_ibs->get_count(*config); } } static inline void perf_ibs_enable_event(struct perf_ibs *perf_ibs, struct hw_perf_event *hwc, u64 config) { u64 tmp = hwc->config | config; if (perf_ibs->fetch_count_reset_broken) wrmsrl(hwc->config_base, tmp & ~perf_ibs->enable_mask); wrmsrl(hwc->config_base, tmp | perf_ibs->enable_mask); } /* * Erratum #420 Instruction-Based Sampling Engine May Generate * Interrupt that Cannot Be Cleared: * * Must clear counter mask first, then clear the enable bit. See * Revision Guide for AMD Family 10h Processors, Publication #41322. */ static inline void perf_ibs_disable_event(struct perf_ibs *perf_ibs, struct hw_perf_event *hwc, u64 config) { config &= ~perf_ibs->cnt_mask; if (boot_cpu_data.x86 == 0x10) wrmsrl(hwc->config_base, config); config &= ~perf_ibs->enable_mask; wrmsrl(hwc->config_base, config); } /* * We cannot restore the ibs pmu state, so we always needs to update * the event while stopping it and then reset the state when starting * again. Thus, ignoring PERF_EF_RELOAD and PERF_EF_UPDATE flags in * perf_ibs_start()/perf_ibs_stop() and instead always do it. */ static void perf_ibs_start(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu); struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu); u64 period, config = 0; if (WARN_ON_ONCE(!(hwc->state & PERF_HES_STOPPED))) return; WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE)); hwc->state = 0; perf_ibs_set_period(perf_ibs, hwc, &period); if (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_OPCNTEXT)) { config |= period & IBS_OP_MAX_CNT_EXT_MASK; period &= ~IBS_OP_MAX_CNT_EXT_MASK; } config |= period >> 4; /* * Set STARTED before enabling the hardware, such that a subsequent NMI * must observe it. */ set_bit(IBS_STARTED, pcpu->state); clear_bit(IBS_STOPPING, pcpu->state); perf_ibs_enable_event(perf_ibs, hwc, config); perf_event_update_userpage(event); } static void perf_ibs_stop(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu); struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu); u64 config; int stopping; if (test_and_set_bit(IBS_STOPPING, pcpu->state)) return; stopping = test_bit(IBS_STARTED, pcpu->state); if (!stopping && (hwc->state & PERF_HES_UPTODATE)) return; rdmsrl(hwc->config_base, config); if (stopping) { /* * Set STOPPED before disabling the hardware, such that it * must be visible to NMIs the moment we clear the EN bit, * at which point we can generate an !VALID sample which * we need to consume. */ set_bit(IBS_STOPPED, pcpu->state); perf_ibs_disable_event(perf_ibs, hwc, config); /* * Clear STARTED after disabling the hardware; if it were * cleared before an NMI hitting after the clear but before * clearing the EN bit might think it a spurious NMI and not * handle it. * * Clearing it after, however, creates the problem of the NMI * handler seeing STARTED but not having a valid sample. */ clear_bit(IBS_STARTED, pcpu->state); WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED); hwc->state |= PERF_HES_STOPPED; } if (hwc->state & PERF_HES_UPTODATE) return; /* * Clear valid bit to not count rollovers on update, rollovers * are only updated in the irq handler. */ config &= ~perf_ibs->valid_mask; perf_ibs_event_update(perf_ibs, event, &config); hwc->state |= PERF_HES_UPTODATE; } static int perf_ibs_add(struct perf_event *event, int flags) { struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu); struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu); if (test_and_set_bit(IBS_ENABLED, pcpu->state)) return -ENOSPC; event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED; pcpu->event = event; if (flags & PERF_EF_START) perf_ibs_start(event, PERF_EF_RELOAD); return 0; } static void perf_ibs_del(struct perf_event *event, int flags) { struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu); struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu); if (!test_and_clear_bit(IBS_ENABLED, pcpu->state)) return; perf_ibs_stop(event, PERF_EF_UPDATE); pcpu->event = NULL; perf_event_update_userpage(event); } static void perf_ibs_read(struct perf_event *event) { } /* * We need to initialize with empty group if all attributes in the * group are dynamic. */ static struct attribute *attrs_empty[] = { NULL, }; static struct attribute_group empty_format_group = { .name = "format", .attrs = attrs_empty, }; static struct attribute_group empty_caps_group = { .name = "caps", .attrs = attrs_empty, }; static const struct attribute_group *empty_attr_groups[] = { &empty_format_group, &empty_caps_group, NULL, }; PMU_FORMAT_ATTR(rand_en, "config:57"); PMU_FORMAT_ATTR(cnt_ctl, "config:19"); PMU_EVENT_ATTR_STRING(l3missonly, fetch_l3missonly, "config:59"); PMU_EVENT_ATTR_STRING(l3missonly, op_l3missonly, "config:16"); PMU_EVENT_ATTR_STRING(zen4_ibs_extensions, zen4_ibs_extensions, "1"); static umode_t zen4_ibs_extensions_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return ibs_caps & IBS_CAPS_ZEN4 ? attr->mode : 0; } static struct attribute *rand_en_attrs[] = { &format_attr_rand_en.attr, NULL, }; static struct attribute *fetch_l3missonly_attrs[] = { &fetch_l3missonly.attr.attr, NULL, }; static struct attribute *zen4_ibs_extensions_attrs[] = { &zen4_ibs_extensions.attr.attr, NULL, }; static struct attribute_group group_rand_en = { .name = "format", .attrs = rand_en_attrs, }; static struct attribute_group group_fetch_l3missonly = { .name = "format", .attrs = fetch_l3missonly_attrs, .is_visible = zen4_ibs_extensions_is_visible, }; static struct attribute_group group_zen4_ibs_extensions = { .name = "caps", .attrs = zen4_ibs_extensions_attrs, .is_visible = zen4_ibs_extensions_is_visible, }; static const struct attribute_group *fetch_attr_groups[] = { &group_rand_en, &empty_caps_group, NULL, }; static const struct attribute_group *fetch_attr_update[] = { &group_fetch_l3missonly, &group_zen4_ibs_extensions, NULL, }; static umode_t cnt_ctl_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return ibs_caps & IBS_CAPS_OPCNT ? attr->mode : 0; } static struct attribute *cnt_ctl_attrs[] = { &format_attr_cnt_ctl.attr, NULL, }; static struct attribute *op_l3missonly_attrs[] = { &op_l3missonly.attr.attr, NULL, }; static struct attribute_group group_cnt_ctl = { .name = "format", .attrs = cnt_ctl_attrs, .is_visible = cnt_ctl_is_visible, }; static struct attribute_group group_op_l3missonly = { .name = "format", .attrs = op_l3missonly_attrs, .is_visible = zen4_ibs_extensions_is_visible, }; static const struct attribute_group *op_attr_update[] = { &group_cnt_ctl, &group_op_l3missonly, &group_zen4_ibs_extensions, NULL, }; static struct perf_ibs perf_ibs_fetch = { .pmu = { .task_ctx_nr = perf_hw_context, .event_init = perf_ibs_init, .add = perf_ibs_add, .del = perf_ibs_del, .start = perf_ibs_start, .stop = perf_ibs_stop, .read = perf_ibs_read, .capabilities = PERF_PMU_CAP_NO_EXCLUDE, }, .msr = MSR_AMD64_IBSFETCHCTL, .config_mask = IBS_FETCH_CONFIG_MASK, .cnt_mask = IBS_FETCH_MAX_CNT, .enable_mask = IBS_FETCH_ENABLE, .valid_mask = IBS_FETCH_VAL, .max_period = IBS_FETCH_MAX_CNT << 4, .offset_mask = { MSR_AMD64_IBSFETCH_REG_MASK }, .offset_max = MSR_AMD64_IBSFETCH_REG_COUNT, .get_count = get_ibs_fetch_count, }; static struct perf_ibs perf_ibs_op = { .pmu = { .task_ctx_nr = perf_hw_context, .event_init = perf_ibs_init, .add = perf_ibs_add, .del = perf_ibs_del, .start = perf_ibs_start, .stop = perf_ibs_stop, .read = perf_ibs_read, .capabilities = PERF_PMU_CAP_NO_EXCLUDE, }, .msr = MSR_AMD64_IBSOPCTL, .config_mask = IBS_OP_CONFIG_MASK, .cnt_mask = IBS_OP_MAX_CNT | IBS_OP_CUR_CNT | IBS_OP_CUR_CNT_RAND, .enable_mask = IBS_OP_ENABLE, .valid_mask = IBS_OP_VAL, .max_period = IBS_OP_MAX_CNT << 4, .offset_mask = { MSR_AMD64_IBSOP_REG_MASK }, .offset_max = MSR_AMD64_IBSOP_REG_COUNT, .get_count = get_ibs_op_count, }; static void perf_ibs_get_mem_op(union ibs_op_data3 *op_data3, struct perf_sample_data *data) { union perf_mem_data_src *data_src = &data->data_src; data_src->mem_op = PERF_MEM_OP_NA; if (op_data3->ld_op) data_src->mem_op = PERF_MEM_OP_LOAD; else if (op_data3->st_op) data_src->mem_op = PERF_MEM_OP_STORE; } /* * Processors having CPUID_Fn8000001B_EAX[11] aka IBS_CAPS_ZEN4 has * more fine granular DataSrc encodings. Others have coarse. */ static u8 perf_ibs_data_src(union ibs_op_data2 *op_data2) { if (ibs_caps & IBS_CAPS_ZEN4) return (op_data2->data_src_hi << 3) | op_data2->data_src_lo; return op_data2->data_src_lo; } #define L(x) (PERF_MEM_S(LVL, x) | PERF_MEM_S(LVL, HIT)) #define LN(x) PERF_MEM_S(LVLNUM, x) #define REM PERF_MEM_S(REMOTE, REMOTE) #define HOPS(x) PERF_MEM_S(HOPS, x) static u64 g_data_src[8] = { [IBS_DATA_SRC_LOC_CACHE] = L(L3) | L(REM_CCE1) | LN(ANY_CACHE) | HOPS(0), [IBS_DATA_SRC_DRAM] = L(LOC_RAM) | LN(RAM), [IBS_DATA_SRC_REM_CACHE] = L(REM_CCE2) | LN(ANY_CACHE) | REM | HOPS(1), [IBS_DATA_SRC_IO] = L(IO) | LN(IO), }; #define RMT_NODE_BITS (1 << IBS_DATA_SRC_DRAM) #define RMT_NODE_APPLICABLE(x) (RMT_NODE_BITS & (1 << x)) static u64 g_zen4_data_src[32] = { [IBS_DATA_SRC_EXT_LOC_CACHE] = L(L3) | LN(L3), [IBS_DATA_SRC_EXT_NEAR_CCX_CACHE] = L(REM_CCE1) | LN(ANY_CACHE) | REM | HOPS(0), [IBS_DATA_SRC_EXT_DRAM] = L(LOC_RAM) | LN(RAM), [IBS_DATA_SRC_EXT_FAR_CCX_CACHE] = L(REM_CCE2) | LN(ANY_CACHE) | REM | HOPS(1), [IBS_DATA_SRC_EXT_PMEM] = LN(PMEM), [IBS_DATA_SRC_EXT_IO] = L(IO) | LN(IO), [IBS_DATA_SRC_EXT_EXT_MEM] = LN(CXL), }; #define ZEN4_RMT_NODE_BITS ((1 << IBS_DATA_SRC_EXT_DRAM) | \ (1 << IBS_DATA_SRC_EXT_PMEM) | \ (1 << IBS_DATA_SRC_EXT_EXT_MEM)) #define ZEN4_RMT_NODE_APPLICABLE(x) (ZEN4_RMT_NODE_BITS & (1 << x)) static __u64 perf_ibs_get_mem_lvl(union ibs_op_data2 *op_data2, union ibs_op_data3 *op_data3, struct perf_sample_data *data) { union perf_mem_data_src *data_src = &data->data_src; u8 ibs_data_src = perf_ibs_data_src(op_data2); data_src->mem_lvl = 0; data_src->mem_lvl_num = 0; /* * DcMiss, L2Miss, DataSrc, DcMissLat etc. are all invalid for Uncached * memory accesses. So, check DcUcMemAcc bit early. */ if (op_data3->dc_uc_mem_acc && ibs_data_src != IBS_DATA_SRC_EXT_IO) return L(UNC) | LN(UNC); /* L1 Hit */ if (op_data3->dc_miss == 0) return L(L1) | LN(L1); /* L2 Hit */ if (op_data3->l2_miss == 0) { /* Erratum #1293 */ if (boot_cpu_data.x86 != 0x19 || boot_cpu_data.x86_model > 0xF || !(op_data3->sw_pf || op_data3->dc_miss_no_mab_alloc)) return L(L2) | LN(L2); } /* * OP_DATA2 is valid only for load ops. Skip all checks which * uses OP_DATA2[DataSrc]. */ if (data_src->mem_op != PERF_MEM_OP_LOAD) goto check_mab; if (ibs_caps & IBS_CAPS_ZEN4) { u64 val = g_zen4_data_src[ibs_data_src]; if (!val) goto check_mab; /* HOPS_1 because IBS doesn't provide remote socket detail */ if (op_data2->rmt_node && ZEN4_RMT_NODE_APPLICABLE(ibs_data_src)) { if (ibs_data_src == IBS_DATA_SRC_EXT_DRAM) val = L(REM_RAM1) | LN(RAM) | REM | HOPS(1); else val |= REM | HOPS(1); } return val; } else { u64 val = g_data_src[ibs_data_src]; if (!val) goto check_mab; /* HOPS_1 because IBS doesn't provide remote socket detail */ if (op_data2->rmt_node && RMT_NODE_APPLICABLE(ibs_data_src)) { if (ibs_data_src == IBS_DATA_SRC_DRAM) val = L(REM_RAM1) | LN(RAM) | REM | HOPS(1); else val |= REM | HOPS(1); } return val; } check_mab: /* * MAB (Miss Address Buffer) Hit. MAB keeps track of outstanding * DC misses. However, such data may come from any level in mem * hierarchy. IBS provides detail about both MAB as well as actual * DataSrc simultaneously. Prioritize DataSrc over MAB, i.e. set * MAB only when IBS fails to provide DataSrc. */ if (op_data3->dc_miss_no_mab_alloc) return L(LFB) | LN(LFB); /* Don't set HIT with NA */ return PERF_MEM_S(LVL, NA) | LN(NA); } static bool perf_ibs_cache_hit_st_valid(void) { /* 0: Uninitialized, 1: Valid, -1: Invalid */ static int cache_hit_st_valid; if (unlikely(!cache_hit_st_valid)) { if (boot_cpu_data.x86 == 0x19 && (boot_cpu_data.x86_model <= 0xF || (boot_cpu_data.x86_model >= 0x20 && boot_cpu_data.x86_model <= 0x5F))) { cache_hit_st_valid = -1; } else { cache_hit_st_valid = 1; } } return cache_hit_st_valid == 1; } static void perf_ibs_get_mem_snoop(union ibs_op_data2 *op_data2, struct perf_sample_data *data) { union perf_mem_data_src *data_src = &data->data_src; u8 ibs_data_src; data_src->mem_snoop = PERF_MEM_SNOOP_NA; if (!perf_ibs_cache_hit_st_valid() || data_src->mem_op != PERF_MEM_OP_LOAD || data_src->mem_lvl & PERF_MEM_LVL_L1 || data_src->mem_lvl & PERF_MEM_LVL_L2 || op_data2->cache_hit_st) return; ibs_data_src = perf_ibs_data_src(op_data2); if (ibs_caps & IBS_CAPS_ZEN4) { if (ibs_data_src == IBS_DATA_SRC_EXT_LOC_CACHE || ibs_data_src == IBS_DATA_SRC_EXT_NEAR_CCX_CACHE || ibs_data_src == IBS_DATA_SRC_EXT_FAR_CCX_CACHE) data_src->mem_snoop = PERF_MEM_SNOOP_HITM; } else if (ibs_data_src == IBS_DATA_SRC_LOC_CACHE) { data_src->mem_snoop = PERF_MEM_SNOOP_HITM; } } static void perf_ibs_get_tlb_lvl(union ibs_op_data3 *op_data3, struct perf_sample_data *data) { union perf_mem_data_src *data_src = &data->data_src; data_src->mem_dtlb = PERF_MEM_TLB_NA; if (!op_data3->dc_lin_addr_valid) return; if (!op_data3->dc_l1tlb_miss) { data_src->mem_dtlb = PERF_MEM_TLB_L1 | PERF_MEM_TLB_HIT; return; } if (!op_data3->dc_l2tlb_miss) { data_src->mem_dtlb = PERF_MEM_TLB_L2 | PERF_MEM_TLB_HIT; return; } data_src->mem_dtlb = PERF_MEM_TLB_L2 | PERF_MEM_TLB_MISS; } static void perf_ibs_get_mem_lock(union ibs_op_data3 *op_data3, struct perf_sample_data *data) { union perf_mem_data_src *data_src = &data->data_src; data_src->mem_lock = PERF_MEM_LOCK_NA; if (op_data3->dc_locked_op) data_src->mem_lock = PERF_MEM_LOCK_LOCKED; } #define ibs_op_msr_idx(msr) (msr - MSR_AMD64_IBSOPCTL) static void perf_ibs_get_data_src(struct perf_ibs_data *ibs_data, struct perf_sample_data *data, union ibs_op_data2 *op_data2, union ibs_op_data3 *op_data3) { union perf_mem_data_src *data_src = &data->data_src; data_src->val |= perf_ibs_get_mem_lvl(op_data2, op_data3, data); perf_ibs_get_mem_snoop(op_data2, data); perf_ibs_get_tlb_lvl(op_data3, data); perf_ibs_get_mem_lock(op_data3, data); } static __u64 perf_ibs_get_op_data2(struct perf_ibs_data *ibs_data, union ibs_op_data3 *op_data3) { __u64 val = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSOPDATA2)]; /* Erratum #1293 */ if (boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model <= 0xF && (op_data3->sw_pf || op_data3->dc_miss_no_mab_alloc)) { /* * OP_DATA2 has only two fields on Zen3: DataSrc and RmtNode. * DataSrc=0 is 'No valid status' and RmtNode is invalid when * DataSrc=0. */ val = 0; } return val; } static void perf_ibs_parse_ld_st_data(__u64 sample_type, struct perf_ibs_data *ibs_data, struct perf_sample_data *data) { union ibs_op_data3 op_data3; union ibs_op_data2 op_data2; union ibs_op_data op_data; data->data_src.val = PERF_MEM_NA; op_data3.val = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSOPDATA3)]; perf_ibs_get_mem_op(&op_data3, data); if (data->data_src.mem_op != PERF_MEM_OP_LOAD && data->data_src.mem_op != PERF_MEM_OP_STORE) return; op_data2.val = perf_ibs_get_op_data2(ibs_data, &op_data3); if (sample_type & PERF_SAMPLE_DATA_SRC) { perf_ibs_get_data_src(ibs_data, data, &op_data2, &op_data3); data->sample_flags |= PERF_SAMPLE_DATA_SRC; } if (sample_type & PERF_SAMPLE_WEIGHT_TYPE && op_data3.dc_miss && data->data_src.mem_op == PERF_MEM_OP_LOAD) { op_data.val = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSOPDATA)]; if (sample_type & PERF_SAMPLE_WEIGHT_STRUCT) { data->weight.var1_dw = op_data3.dc_miss_lat; data->weight.var2_w = op_data.tag_to_ret_ctr; } else if (sample_type & PERF_SAMPLE_WEIGHT) { data->weight.full = op_data3.dc_miss_lat; } data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; } if (sample_type & PERF_SAMPLE_ADDR && op_data3.dc_lin_addr_valid) { data->addr = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSDCLINAD)]; data->sample_flags |= PERF_SAMPLE_ADDR; } if (sample_type & PERF_SAMPLE_PHYS_ADDR && op_data3.dc_phy_addr_valid) { data->phys_addr = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSDCPHYSAD)]; data->sample_flags |= PERF_SAMPLE_PHYS_ADDR; } } static int perf_ibs_get_offset_max(struct perf_ibs *perf_ibs, u64 sample_type, int check_rip) { if (sample_type & PERF_SAMPLE_RAW || (perf_ibs == &perf_ibs_op && (sample_type & PERF_SAMPLE_DATA_SRC || sample_type & PERF_SAMPLE_WEIGHT_TYPE || sample_type & PERF_SAMPLE_ADDR || sample_type & PERF_SAMPLE_PHYS_ADDR))) return perf_ibs->offset_max; else if (check_rip) return 3; return 1; } static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs) { struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu); struct perf_event *event = pcpu->event; struct hw_perf_event *hwc; struct perf_sample_data data; struct perf_raw_record raw; struct pt_regs regs; struct perf_ibs_data ibs_data; int offset, size, check_rip, offset_max, throttle = 0; unsigned int msr; u64 *buf, *config, period, new_config = 0; if (!test_bit(IBS_STARTED, pcpu->state)) { fail: /* * Catch spurious interrupts after stopping IBS: After * disabling IBS there could be still incoming NMIs * with samples that even have the valid bit cleared. * Mark all this NMIs as handled. */ if (test_and_clear_bit(IBS_STOPPED, pcpu->state)) return 1; return 0; } if (WARN_ON_ONCE(!event)) goto fail; hwc = &event->hw; msr = hwc->config_base; buf = ibs_data.regs; rdmsrl(msr, *buf); if (!(*buf++ & perf_ibs->valid_mask)) goto fail; config = &ibs_data.regs[0]; perf_ibs_event_update(perf_ibs, event, config); perf_sample_data_init(&data, 0, hwc->last_period); if (!perf_ibs_set_period(perf_ibs, hwc, &period)) goto out; /* no sw counter overflow */ ibs_data.caps = ibs_caps; size = 1; offset = 1; check_rip = (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_RIPINVALIDCHK)); offset_max = perf_ibs_get_offset_max(perf_ibs, event->attr.sample_type, check_rip); do { rdmsrl(msr + offset, *buf++); size++; offset = find_next_bit(perf_ibs->offset_mask, perf_ibs->offset_max, offset + 1); } while (offset < offset_max); /* * Read IbsBrTarget, IbsOpData4, and IbsExtdCtl separately * depending on their availability. * Can't add to offset_max as they are staggered */ if (event->attr.sample_type & PERF_SAMPLE_RAW) { if (perf_ibs == &perf_ibs_op) { if (ibs_caps & IBS_CAPS_BRNTRGT) { rdmsrl(MSR_AMD64_IBSBRTARGET, *buf++); size++; } if (ibs_caps & IBS_CAPS_OPDATA4) { rdmsrl(MSR_AMD64_IBSOPDATA4, *buf++); size++; } } if (perf_ibs == &perf_ibs_fetch && (ibs_caps & IBS_CAPS_FETCHCTLEXTD)) { rdmsrl(MSR_AMD64_ICIBSEXTDCTL, *buf++); size++; } } ibs_data.size = sizeof(u64) * size; regs = *iregs; if (check_rip && (ibs_data.regs[2] & IBS_RIP_INVALID)) { regs.flags &= ~PERF_EFLAGS_EXACT; } else { /* Workaround for erratum #1197 */ if (perf_ibs->fetch_ignore_if_zero_rip && !(ibs_data.regs[1])) goto out; set_linear_ip(&regs, ibs_data.regs[1]); regs.flags |= PERF_EFLAGS_EXACT; } if (event->attr.sample_type & PERF_SAMPLE_RAW) { raw = (struct perf_raw_record){ .frag = { .size = sizeof(u32) + ibs_data.size, .data = ibs_data.data, }, }; perf_sample_save_raw_data(&data, &raw); } if (perf_ibs == &perf_ibs_op) perf_ibs_parse_ld_st_data(event->attr.sample_type, &ibs_data, &data); /* * rip recorded by IbsOpRip will not be consistent with rsp and rbp * recorded as part of interrupt regs. Thus we need to use rip from * interrupt regs while unwinding call stack. */ if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) perf_sample_save_callchain(&data, event, iregs); throttle = perf_event_overflow(event, &data, &regs); out: if (throttle) { perf_ibs_stop(event, 0); } else { if (perf_ibs == &perf_ibs_op) { if (ibs_caps & IBS_CAPS_OPCNTEXT) { new_config = period & IBS_OP_MAX_CNT_EXT_MASK; period &= ~IBS_OP_MAX_CNT_EXT_MASK; } if ((ibs_caps & IBS_CAPS_RDWROPCNT) && (*config & IBS_OP_CNT_CTL)) new_config |= *config & IBS_OP_CUR_CNT_RAND; } new_config |= period >> 4; perf_ibs_enable_event(perf_ibs, hwc, new_config); } perf_event_update_userpage(event); return 1; } static int perf_ibs_nmi_handler(unsigned int cmd, struct pt_regs *regs) { u64 stamp = sched_clock(); int handled = 0; handled += perf_ibs_handle_irq(&perf_ibs_fetch, regs); handled += perf_ibs_handle_irq(&perf_ibs_op, regs); if (handled) inc_irq_stat(apic_perf_irqs); perf_sample_event_took(sched_clock() - stamp); return handled; } NOKPROBE_SYMBOL(perf_ibs_nmi_handler); static __init int perf_ibs_pmu_init(struct perf_ibs *perf_ibs, char *name) { struct cpu_perf_ibs __percpu *pcpu; int ret; pcpu = alloc_percpu(struct cpu_perf_ibs); if (!pcpu) return -ENOMEM; perf_ibs->pcpu = pcpu; ret = perf_pmu_register(&perf_ibs->pmu, name, -1); if (ret) { perf_ibs->pcpu = NULL; free_percpu(pcpu); } return ret; } static __init int perf_ibs_fetch_init(void) { /* * Some chips fail to reset the fetch count when it is written; instead * they need a 0-1 transition of IbsFetchEn. */ if (boot_cpu_data.x86 >= 0x16 && boot_cpu_data.x86 <= 0x18) perf_ibs_fetch.fetch_count_reset_broken = 1; if (boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model < 0x10) perf_ibs_fetch.fetch_ignore_if_zero_rip = 1; if (ibs_caps & IBS_CAPS_ZEN4) perf_ibs_fetch.config_mask |= IBS_FETCH_L3MISSONLY; perf_ibs_fetch.pmu.attr_groups = fetch_attr_groups; perf_ibs_fetch.pmu.attr_update = fetch_attr_update; return perf_ibs_pmu_init(&perf_ibs_fetch, "ibs_fetch"); } static __init int perf_ibs_op_init(void) { if (ibs_caps & IBS_CAPS_OPCNT) perf_ibs_op.config_mask |= IBS_OP_CNT_CTL; if (ibs_caps & IBS_CAPS_OPCNTEXT) { perf_ibs_op.max_period |= IBS_OP_MAX_CNT_EXT_MASK; perf_ibs_op.config_mask |= IBS_OP_MAX_CNT_EXT_MASK; perf_ibs_op.cnt_mask |= IBS_OP_MAX_CNT_EXT_MASK; } if (ibs_caps & IBS_CAPS_ZEN4) perf_ibs_op.config_mask |= IBS_OP_L3MISSONLY; perf_ibs_op.pmu.attr_groups = empty_attr_groups; perf_ibs_op.pmu.attr_update = op_attr_update; return perf_ibs_pmu_init(&perf_ibs_op, "ibs_op"); } static __init int perf_event_ibs_init(void) { int ret; ret = perf_ibs_fetch_init(); if (ret) return ret; ret = perf_ibs_op_init(); if (ret) goto err_op; ret = register_nmi_handler(NMI_LOCAL, perf_ibs_nmi_handler, 0, "perf_ibs"); if (ret) goto err_nmi; pr_info("perf: AMD IBS detected (0x%08x)\n", ibs_caps); return 0; err_nmi: perf_pmu_unregister(&perf_ibs_op.pmu); free_percpu(perf_ibs_op.pcpu); perf_ibs_op.pcpu = NULL; err_op: perf_pmu_unregister(&perf_ibs_fetch.pmu); free_percpu(perf_ibs_fetch.pcpu); perf_ibs_fetch.pcpu = NULL; return ret; } #else /* defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_AMD) */ static __init int perf_event_ibs_init(void) { return 0; } #endif /* IBS - apic initialization, for perf and oprofile */ static __init u32 __get_ibs_caps(void) { u32 caps; unsigned int max_level; if (!boot_cpu_has(X86_FEATURE_IBS)) return 0; /* check IBS cpuid feature flags */ max_level = cpuid_eax(0x80000000); if (max_level < IBS_CPUID_FEATURES) return IBS_CAPS_DEFAULT; caps = cpuid_eax(IBS_CPUID_FEATURES); if (!(caps & IBS_CAPS_AVAIL)) /* cpuid flags not valid */ return IBS_CAPS_DEFAULT; return caps; } u32 get_ibs_caps(void) { return ibs_caps; } EXPORT_SYMBOL(get_ibs_caps); static inline int get_eilvt(int offset) { return !setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 1); } static inline int put_eilvt(int offset) { return !setup_APIC_eilvt(offset, 0, 0, 1); } /* * Check and reserve APIC extended interrupt LVT offset for IBS if available. */ static inline int ibs_eilvt_valid(void) { int offset; u64 val; int valid = 0; preempt_disable(); rdmsrl(MSR_AMD64_IBSCTL, val); offset = val & IBSCTL_LVT_OFFSET_MASK; if (!(val & IBSCTL_LVT_OFFSET_VALID)) { pr_err(FW_BUG "cpu %d, invalid IBS interrupt offset %d (MSR%08X=0x%016llx)\n", smp_processor_id(), offset, MSR_AMD64_IBSCTL, val); goto out; } if (!get_eilvt(offset)) { pr_err(FW_BUG "cpu %d, IBS interrupt offset %d not available (MSR%08X=0x%016llx)\n", smp_processor_id(), offset, MSR_AMD64_IBSCTL, val); goto out; } valid = 1; out: preempt_enable(); return valid; } static int setup_ibs_ctl(int ibs_eilvt_off) { struct pci_dev *cpu_cfg; int nodes; u32 value = 0; nodes = 0; cpu_cfg = NULL; do { cpu_cfg = pci_get_device(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_10H_NB_MISC, cpu_cfg); if (!cpu_cfg) break; ++nodes; pci_write_config_dword(cpu_cfg, IBSCTL, ibs_eilvt_off | IBSCTL_LVT_OFFSET_VALID); pci_read_config_dword(cpu_cfg, IBSCTL, &value); if (value != (ibs_eilvt_off | IBSCTL_LVT_OFFSET_VALID)) { pci_dev_put(cpu_cfg); pr_debug("Failed to setup IBS LVT offset, IBSCTL = 0x%08x\n", value); return -EINVAL; } } while (1); if (!nodes) { pr_debug("No CPU node configured for IBS\n"); return -ENODEV; } return 0; } /* * This runs only on the current cpu. We try to find an LVT offset and * setup the local APIC. For this we must disable preemption. On * success we initialize all nodes with this offset. This updates then * the offset in the IBS_CTL per-node msr. The per-core APIC setup of * the IBS interrupt vector is handled by perf_ibs_cpu_notifier that * is using the new offset. */ static void force_ibs_eilvt_setup(void) { int offset; int ret; preempt_disable(); /* find the next free available EILVT entry, skip offset 0 */ for (offset = 1; offset < APIC_EILVT_NR_MAX; offset++) { if (get_eilvt(offset)) break; } preempt_enable(); if (offset == APIC_EILVT_NR_MAX) { pr_debug("No EILVT entry available\n"); return; } ret = setup_ibs_ctl(offset); if (ret) goto out; if (!ibs_eilvt_valid()) goto out; pr_info("LVT offset %d assigned\n", offset); return; out: preempt_disable(); put_eilvt(offset); preempt_enable(); return; } static void ibs_eilvt_setup(void) { /* * Force LVT offset assignment for family 10h: The offsets are * not assigned by the BIOS for this family, so the OS is * responsible for doing it. If the OS assignment fails, fall * back to BIOS settings and try to setup this. */ if (boot_cpu_data.x86 == 0x10) force_ibs_eilvt_setup(); } static inline int get_ibs_lvt_offset(void) { u64 val; rdmsrl(MSR_AMD64_IBSCTL, val); if (!(val & IBSCTL_LVT_OFFSET_VALID)) return -EINVAL; return val & IBSCTL_LVT_OFFSET_MASK; } static void setup_APIC_ibs(void) { int offset; offset = get_ibs_lvt_offset(); if (offset < 0) goto failed; if (!setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 0)) return; failed: pr_warn("perf: IBS APIC setup failed on cpu #%d\n", smp_processor_id()); } static void clear_APIC_ibs(void) { int offset; offset = get_ibs_lvt_offset(); if (offset >= 0) setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_FIX, 1); } static int x86_pmu_amd_ibs_starting_cpu(unsigned int cpu) { setup_APIC_ibs(); return 0; } #ifdef CONFIG_PM static int perf_ibs_suspend(void) { clear_APIC_ibs(); return 0; } static void perf_ibs_resume(void) { ibs_eilvt_setup(); setup_APIC_ibs(); } static struct syscore_ops perf_ibs_syscore_ops = { .resume = perf_ibs_resume, .suspend = perf_ibs_suspend, }; static void perf_ibs_pm_init(void) { register_syscore_ops(&perf_ibs_syscore_ops); } #else static inline void perf_ibs_pm_init(void) { } #endif static int x86_pmu_amd_ibs_dying_cpu(unsigned int cpu) { clear_APIC_ibs(); return 0; } static __init int amd_ibs_init(void) { u32 caps; caps = __get_ibs_caps(); if (!caps) return -ENODEV; /* ibs not supported by the cpu */ ibs_eilvt_setup(); if (!ibs_eilvt_valid()) return -EINVAL; perf_ibs_pm_init(); ibs_caps = caps; /* make ibs_caps visible to other cpus: */ smp_mb(); /* * x86_pmu_amd_ibs_starting_cpu will be called from core on * all online cpus. */ cpuhp_setup_state(CPUHP_AP_PERF_X86_AMD_IBS_STARTING, "perf/x86/amd/ibs:starting", x86_pmu_amd_ibs_starting_cpu, x86_pmu_amd_ibs_dying_cpu); return perf_event_ibs_init(); } /* Since we need the pci subsystem to init ibs we can't do this earlier: */ device_initcall(amd_ibs_init);
linux-master
arch/x86/events/amd/ibs.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2013 Advanced Micro Devices, Inc. * * Author: Jacob Shin <[email protected]> */ #include <linux/perf_event.h> #include <linux/percpu.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/cpu.h> #include <linux/cpumask.h> #include <linux/cpufeature.h> #include <linux/smp.h> #include <asm/perf_event.h> #include <asm/msr.h> #define NUM_COUNTERS_NB 4 #define NUM_COUNTERS_L2 4 #define NUM_COUNTERS_L3 6 #define RDPMC_BASE_NB 6 #define RDPMC_BASE_LLC 10 #define COUNTER_SHIFT 16 #undef pr_fmt #define pr_fmt(fmt) "amd_uncore: " fmt static int pmu_version; static int num_counters_llc; static int num_counters_nb; static bool l3_mask; static HLIST_HEAD(uncore_unused_list); struct amd_uncore { int id; int refcnt; int cpu; int num_counters; int rdpmc_base; u32 msr_base; cpumask_t *active_mask; struct pmu *pmu; struct perf_event **events; struct hlist_node node; }; static struct amd_uncore * __percpu *amd_uncore_nb; static struct amd_uncore * __percpu *amd_uncore_llc; static struct pmu amd_nb_pmu; static struct pmu amd_llc_pmu; static cpumask_t amd_nb_active_mask; static cpumask_t amd_llc_active_mask; static bool is_nb_event(struct perf_event *event) { return event->pmu->type == amd_nb_pmu.type; } static bool is_llc_event(struct perf_event *event) { return event->pmu->type == amd_llc_pmu.type; } static struct amd_uncore *event_to_amd_uncore(struct perf_event *event) { if (is_nb_event(event) && amd_uncore_nb) return *per_cpu_ptr(amd_uncore_nb, event->cpu); else if (is_llc_event(event) && amd_uncore_llc) return *per_cpu_ptr(amd_uncore_llc, event->cpu); return NULL; } static void amd_uncore_read(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 prev, new; s64 delta; /* * since we do not enable counter overflow interrupts, * we do not have to worry about prev_count changing on us */ prev = local64_read(&hwc->prev_count); rdpmcl(hwc->event_base_rdpmc, new); local64_set(&hwc->prev_count, new); delta = (new << COUNTER_SHIFT) - (prev << COUNTER_SHIFT); delta >>= COUNTER_SHIFT; local64_add(delta, &event->count); } static void amd_uncore_start(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; if (flags & PERF_EF_RELOAD) wrmsrl(hwc->event_base, (u64)local64_read(&hwc->prev_count)); hwc->state = 0; wrmsrl(hwc->config_base, (hwc->config | ARCH_PERFMON_EVENTSEL_ENABLE)); perf_event_update_userpage(event); } static void amd_uncore_stop(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; wrmsrl(hwc->config_base, hwc->config); hwc->state |= PERF_HES_STOPPED; if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) { amd_uncore_read(event); hwc->state |= PERF_HES_UPTODATE; } } static int amd_uncore_add(struct perf_event *event, int flags) { int i; struct amd_uncore *uncore = event_to_amd_uncore(event); struct hw_perf_event *hwc = &event->hw; /* are we already assigned? */ if (hwc->idx != -1 && uncore->events[hwc->idx] == event) goto out; for (i = 0; i < uncore->num_counters; i++) { if (uncore->events[i] == event) { hwc->idx = i; goto out; } } /* if not, take the first available counter */ hwc->idx = -1; for (i = 0; i < uncore->num_counters; i++) { if (cmpxchg(&uncore->events[i], NULL, event) == NULL) { hwc->idx = i; break; } } out: if (hwc->idx == -1) return -EBUSY; hwc->config_base = uncore->msr_base + (2 * hwc->idx); hwc->event_base = uncore->msr_base + 1 + (2 * hwc->idx); hwc->event_base_rdpmc = uncore->rdpmc_base + hwc->idx; hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED; /* * The first four DF counters are accessible via RDPMC index 6 to 9 * followed by the L3 counters from index 10 to 15. For processors * with more than four DF counters, the DF RDPMC assignments become * discontiguous as the additional counters are accessible starting * from index 16. */ if (is_nb_event(event) && hwc->idx >= NUM_COUNTERS_NB) hwc->event_base_rdpmc += NUM_COUNTERS_L3; if (flags & PERF_EF_START) amd_uncore_start(event, PERF_EF_RELOAD); return 0; } static void amd_uncore_del(struct perf_event *event, int flags) { int i; struct amd_uncore *uncore = event_to_amd_uncore(event); struct hw_perf_event *hwc = &event->hw; amd_uncore_stop(event, PERF_EF_UPDATE); for (i = 0; i < uncore->num_counters; i++) { if (cmpxchg(&uncore->events[i], event, NULL) == event) break; } hwc->idx = -1; } /* * Return a full thread and slice mask unless user * has provided them */ static u64 l3_thread_slice_mask(u64 config) { if (boot_cpu_data.x86 <= 0x18) return ((config & AMD64_L3_SLICE_MASK) ? : AMD64_L3_SLICE_MASK) | ((config & AMD64_L3_THREAD_MASK) ? : AMD64_L3_THREAD_MASK); /* * If the user doesn't specify a threadmask, they're not trying to * count core 0, so we enable all cores & threads. * We'll also assume that they want to count slice 0 if they specify * a threadmask and leave sliceid and enallslices unpopulated. */ if (!(config & AMD64_L3_F19H_THREAD_MASK)) return AMD64_L3_F19H_THREAD_MASK | AMD64_L3_EN_ALL_SLICES | AMD64_L3_EN_ALL_CORES; return config & (AMD64_L3_F19H_THREAD_MASK | AMD64_L3_SLICEID_MASK | AMD64_L3_EN_ALL_CORES | AMD64_L3_EN_ALL_SLICES | AMD64_L3_COREID_MASK); } static int amd_uncore_event_init(struct perf_event *event) { struct amd_uncore *uncore; struct hw_perf_event *hwc = &event->hw; u64 event_mask = AMD64_RAW_EVENT_MASK_NB; if (event->attr.type != event->pmu->type) return -ENOENT; if (pmu_version >= 2 && is_nb_event(event)) event_mask = AMD64_PERFMON_V2_RAW_EVENT_MASK_NB; /* * NB and Last level cache counters (MSRs) are shared across all cores * that share the same NB / Last level cache. On family 16h and below, * Interrupts can be directed to a single target core, however, event * counts generated by processes running on other cores cannot be masked * out. So we do not support sampling and per-thread events via * CAP_NO_INTERRUPT, and we do not enable counter overflow interrupts: */ hwc->config = event->attr.config & event_mask; hwc->idx = -1; if (event->cpu < 0) return -EINVAL; /* * SliceMask and ThreadMask need to be set for certain L3 events. * For other events, the two fields do not affect the count. */ if (l3_mask && is_llc_event(event)) hwc->config |= l3_thread_slice_mask(event->attr.config); uncore = event_to_amd_uncore(event); if (!uncore) return -ENODEV; /* * since request can come in to any of the shared cores, we will remap * to a single common cpu. */ event->cpu = uncore->cpu; return 0; } static umode_t amd_f17h_uncore_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return boot_cpu_data.x86 >= 0x17 && boot_cpu_data.x86 < 0x19 ? attr->mode : 0; } static umode_t amd_f19h_uncore_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return boot_cpu_data.x86 >= 0x19 ? attr->mode : 0; } static ssize_t amd_uncore_attr_show_cpumask(struct device *dev, struct device_attribute *attr, char *buf) { cpumask_t *active_mask; struct pmu *pmu = dev_get_drvdata(dev); if (pmu->type == amd_nb_pmu.type) active_mask = &amd_nb_active_mask; else if (pmu->type == amd_llc_pmu.type) active_mask = &amd_llc_active_mask; else return 0; return cpumap_print_to_pagebuf(true, buf, active_mask); } static DEVICE_ATTR(cpumask, S_IRUGO, amd_uncore_attr_show_cpumask, NULL); static struct attribute *amd_uncore_attrs[] = { &dev_attr_cpumask.attr, NULL, }; static struct attribute_group amd_uncore_attr_group = { .attrs = amd_uncore_attrs, }; #define DEFINE_UNCORE_FORMAT_ATTR(_var, _name, _format) \ static ssize_t __uncore_##_var##_show(struct device *dev, \ struct device_attribute *attr, \ char *page) \ { \ BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE); \ return sprintf(page, _format "\n"); \ } \ static struct device_attribute format_attr_##_var = \ __ATTR(_name, 0444, __uncore_##_var##_show, NULL) DEFINE_UNCORE_FORMAT_ATTR(event12, event, "config:0-7,32-35"); DEFINE_UNCORE_FORMAT_ATTR(event14, event, "config:0-7,32-35,59-60"); /* F17h+ DF */ DEFINE_UNCORE_FORMAT_ATTR(event14v2, event, "config:0-7,32-37"); /* PerfMonV2 DF */ DEFINE_UNCORE_FORMAT_ATTR(event8, event, "config:0-7"); /* F17h+ L3 */ DEFINE_UNCORE_FORMAT_ATTR(umask8, umask, "config:8-15"); DEFINE_UNCORE_FORMAT_ATTR(umask12, umask, "config:8-15,24-27"); /* PerfMonV2 DF */ DEFINE_UNCORE_FORMAT_ATTR(coreid, coreid, "config:42-44"); /* F19h L3 */ DEFINE_UNCORE_FORMAT_ATTR(slicemask, slicemask, "config:48-51"); /* F17h L3 */ DEFINE_UNCORE_FORMAT_ATTR(threadmask8, threadmask, "config:56-63"); /* F17h L3 */ DEFINE_UNCORE_FORMAT_ATTR(threadmask2, threadmask, "config:56-57"); /* F19h L3 */ DEFINE_UNCORE_FORMAT_ATTR(enallslices, enallslices, "config:46"); /* F19h L3 */ DEFINE_UNCORE_FORMAT_ATTR(enallcores, enallcores, "config:47"); /* F19h L3 */ DEFINE_UNCORE_FORMAT_ATTR(sliceid, sliceid, "config:48-50"); /* F19h L3 */ /* Common DF and NB attributes */ static struct attribute *amd_uncore_df_format_attr[] = { &format_attr_event12.attr, /* event */ &format_attr_umask8.attr, /* umask */ NULL, }; /* Common L2 and L3 attributes */ static struct attribute *amd_uncore_l3_format_attr[] = { &format_attr_event12.attr, /* event */ &format_attr_umask8.attr, /* umask */ NULL, /* threadmask */ NULL, }; /* F17h unique L3 attributes */ static struct attribute *amd_f17h_uncore_l3_format_attr[] = { &format_attr_slicemask.attr, /* slicemask */ NULL, }; /* F19h unique L3 attributes */ static struct attribute *amd_f19h_uncore_l3_format_attr[] = { &format_attr_coreid.attr, /* coreid */ &format_attr_enallslices.attr, /* enallslices */ &format_attr_enallcores.attr, /* enallcores */ &format_attr_sliceid.attr, /* sliceid */ NULL, }; static struct attribute_group amd_uncore_df_format_group = { .name = "format", .attrs = amd_uncore_df_format_attr, }; static struct attribute_group amd_uncore_l3_format_group = { .name = "format", .attrs = amd_uncore_l3_format_attr, }; static struct attribute_group amd_f17h_uncore_l3_format_group = { .name = "format", .attrs = amd_f17h_uncore_l3_format_attr, .is_visible = amd_f17h_uncore_is_visible, }; static struct attribute_group amd_f19h_uncore_l3_format_group = { .name = "format", .attrs = amd_f19h_uncore_l3_format_attr, .is_visible = amd_f19h_uncore_is_visible, }; static const struct attribute_group *amd_uncore_df_attr_groups[] = { &amd_uncore_attr_group, &amd_uncore_df_format_group, NULL, }; static const struct attribute_group *amd_uncore_l3_attr_groups[] = { &amd_uncore_attr_group, &amd_uncore_l3_format_group, NULL, }; static const struct attribute_group *amd_uncore_l3_attr_update[] = { &amd_f17h_uncore_l3_format_group, &amd_f19h_uncore_l3_format_group, NULL, }; static struct pmu amd_nb_pmu = { .task_ctx_nr = perf_invalid_context, .attr_groups = amd_uncore_df_attr_groups, .name = "amd_nb", .event_init = amd_uncore_event_init, .add = amd_uncore_add, .del = amd_uncore_del, .start = amd_uncore_start, .stop = amd_uncore_stop, .read = amd_uncore_read, .capabilities = PERF_PMU_CAP_NO_EXCLUDE | PERF_PMU_CAP_NO_INTERRUPT, .module = THIS_MODULE, }; static struct pmu amd_llc_pmu = { .task_ctx_nr = perf_invalid_context, .attr_groups = amd_uncore_l3_attr_groups, .attr_update = amd_uncore_l3_attr_update, .name = "amd_l2", .event_init = amd_uncore_event_init, .add = amd_uncore_add, .del = amd_uncore_del, .start = amd_uncore_start, .stop = amd_uncore_stop, .read = amd_uncore_read, .capabilities = PERF_PMU_CAP_NO_EXCLUDE | PERF_PMU_CAP_NO_INTERRUPT, .module = THIS_MODULE, }; static struct amd_uncore *amd_uncore_alloc(unsigned int cpu) { return kzalloc_node(sizeof(struct amd_uncore), GFP_KERNEL, cpu_to_node(cpu)); } static inline struct perf_event ** amd_uncore_events_alloc(unsigned int num, unsigned int cpu) { return kzalloc_node(sizeof(struct perf_event *) * num, GFP_KERNEL, cpu_to_node(cpu)); } static int amd_uncore_cpu_up_prepare(unsigned int cpu) { struct amd_uncore *uncore_nb = NULL, *uncore_llc = NULL; if (amd_uncore_nb) { *per_cpu_ptr(amd_uncore_nb, cpu) = NULL; uncore_nb = amd_uncore_alloc(cpu); if (!uncore_nb) goto fail; uncore_nb->cpu = cpu; uncore_nb->num_counters = num_counters_nb; uncore_nb->rdpmc_base = RDPMC_BASE_NB; uncore_nb->msr_base = MSR_F15H_NB_PERF_CTL; uncore_nb->active_mask = &amd_nb_active_mask; uncore_nb->pmu = &amd_nb_pmu; uncore_nb->events = amd_uncore_events_alloc(num_counters_nb, cpu); if (!uncore_nb->events) goto fail; uncore_nb->id = -1; *per_cpu_ptr(amd_uncore_nb, cpu) = uncore_nb; } if (amd_uncore_llc) { *per_cpu_ptr(amd_uncore_llc, cpu) = NULL; uncore_llc = amd_uncore_alloc(cpu); if (!uncore_llc) goto fail; uncore_llc->cpu = cpu; uncore_llc->num_counters = num_counters_llc; uncore_llc->rdpmc_base = RDPMC_BASE_LLC; uncore_llc->msr_base = MSR_F16H_L2I_PERF_CTL; uncore_llc->active_mask = &amd_llc_active_mask; uncore_llc->pmu = &amd_llc_pmu; uncore_llc->events = amd_uncore_events_alloc(num_counters_llc, cpu); if (!uncore_llc->events) goto fail; uncore_llc->id = -1; *per_cpu_ptr(amd_uncore_llc, cpu) = uncore_llc; } return 0; fail: if (uncore_nb) { kfree(uncore_nb->events); kfree(uncore_nb); } if (uncore_llc) { kfree(uncore_llc->events); kfree(uncore_llc); } return -ENOMEM; } static struct amd_uncore * amd_uncore_find_online_sibling(struct amd_uncore *this, struct amd_uncore * __percpu *uncores) { unsigned int cpu; struct amd_uncore *that; for_each_online_cpu(cpu) { that = *per_cpu_ptr(uncores, cpu); if (!that) continue; if (this == that) continue; if (this->id == that->id) { hlist_add_head(&this->node, &uncore_unused_list); this = that; break; } } this->refcnt++; return this; } static int amd_uncore_cpu_starting(unsigned int cpu) { unsigned int eax, ebx, ecx, edx; struct amd_uncore *uncore; if (amd_uncore_nb) { uncore = *per_cpu_ptr(amd_uncore_nb, cpu); cpuid(0x8000001e, &eax, &ebx, &ecx, &edx); uncore->id = ecx & 0xff; uncore = amd_uncore_find_online_sibling(uncore, amd_uncore_nb); *per_cpu_ptr(amd_uncore_nb, cpu) = uncore; } if (amd_uncore_llc) { uncore = *per_cpu_ptr(amd_uncore_llc, cpu); uncore->id = get_llc_id(cpu); uncore = amd_uncore_find_online_sibling(uncore, amd_uncore_llc); *per_cpu_ptr(amd_uncore_llc, cpu) = uncore; } return 0; } static void uncore_clean_online(void) { struct amd_uncore *uncore; struct hlist_node *n; hlist_for_each_entry_safe(uncore, n, &uncore_unused_list, node) { hlist_del(&uncore->node); kfree(uncore->events); kfree(uncore); } } static void uncore_online(unsigned int cpu, struct amd_uncore * __percpu *uncores) { struct amd_uncore *uncore = *per_cpu_ptr(uncores, cpu); uncore_clean_online(); if (cpu == uncore->cpu) cpumask_set_cpu(cpu, uncore->active_mask); } static int amd_uncore_cpu_online(unsigned int cpu) { if (amd_uncore_nb) uncore_online(cpu, amd_uncore_nb); if (amd_uncore_llc) uncore_online(cpu, amd_uncore_llc); return 0; } static void uncore_down_prepare(unsigned int cpu, struct amd_uncore * __percpu *uncores) { unsigned int i; struct amd_uncore *this = *per_cpu_ptr(uncores, cpu); if (this->cpu != cpu) return; /* this cpu is going down, migrate to a shared sibling if possible */ for_each_online_cpu(i) { struct amd_uncore *that = *per_cpu_ptr(uncores, i); if (cpu == i) continue; if (this == that) { perf_pmu_migrate_context(this->pmu, cpu, i); cpumask_clear_cpu(cpu, that->active_mask); cpumask_set_cpu(i, that->active_mask); that->cpu = i; break; } } } static int amd_uncore_cpu_down_prepare(unsigned int cpu) { if (amd_uncore_nb) uncore_down_prepare(cpu, amd_uncore_nb); if (amd_uncore_llc) uncore_down_prepare(cpu, amd_uncore_llc); return 0; } static void uncore_dead(unsigned int cpu, struct amd_uncore * __percpu *uncores) { struct amd_uncore *uncore = *per_cpu_ptr(uncores, cpu); if (cpu == uncore->cpu) cpumask_clear_cpu(cpu, uncore->active_mask); if (!--uncore->refcnt) { kfree(uncore->events); kfree(uncore); } *per_cpu_ptr(uncores, cpu) = NULL; } static int amd_uncore_cpu_dead(unsigned int cpu) { if (amd_uncore_nb) uncore_dead(cpu, amd_uncore_nb); if (amd_uncore_llc) uncore_dead(cpu, amd_uncore_llc); return 0; } static int __init amd_uncore_init(void) { struct attribute **df_attr = amd_uncore_df_format_attr; struct attribute **l3_attr = amd_uncore_l3_format_attr; union cpuid_0x80000022_ebx ebx; int ret = -ENODEV; if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD && boot_cpu_data.x86_vendor != X86_VENDOR_HYGON) return -ENODEV; if (!boot_cpu_has(X86_FEATURE_TOPOEXT)) return -ENODEV; if (boot_cpu_has(X86_FEATURE_PERFMON_V2)) pmu_version = 2; num_counters_nb = NUM_COUNTERS_NB; num_counters_llc = NUM_COUNTERS_L2; if (boot_cpu_data.x86 >= 0x17) { /* * For F17h and above, the Northbridge counters are * repurposed as Data Fabric counters. Also, L3 * counters are supported too. The PMUs are exported * based on family as either L2 or L3 and NB or DF. */ num_counters_llc = NUM_COUNTERS_L3; amd_nb_pmu.name = "amd_df"; amd_llc_pmu.name = "amd_l3"; l3_mask = true; } if (boot_cpu_has(X86_FEATURE_PERFCTR_NB)) { if (pmu_version >= 2) { *df_attr++ = &format_attr_event14v2.attr; *df_attr++ = &format_attr_umask12.attr; } else if (boot_cpu_data.x86 >= 0x17) { *df_attr = &format_attr_event14.attr; } amd_uncore_nb = alloc_percpu(struct amd_uncore *); if (!amd_uncore_nb) { ret = -ENOMEM; goto fail_nb; } ret = perf_pmu_register(&amd_nb_pmu, amd_nb_pmu.name, -1); if (ret) goto fail_nb; if (pmu_version >= 2) { ebx.full = cpuid_ebx(EXT_PERFMON_DEBUG_FEATURES); num_counters_nb = ebx.split.num_df_pmc; } pr_info("%d %s %s counters detected\n", num_counters_nb, boot_cpu_data.x86_vendor == X86_VENDOR_HYGON ? "HYGON" : "", amd_nb_pmu.name); ret = 0; } if (boot_cpu_has(X86_FEATURE_PERFCTR_LLC)) { if (boot_cpu_data.x86 >= 0x19) { *l3_attr++ = &format_attr_event8.attr; *l3_attr++ = &format_attr_umask8.attr; *l3_attr++ = &format_attr_threadmask2.attr; } else if (boot_cpu_data.x86 >= 0x17) { *l3_attr++ = &format_attr_event8.attr; *l3_attr++ = &format_attr_umask8.attr; *l3_attr++ = &format_attr_threadmask8.attr; } amd_uncore_llc = alloc_percpu(struct amd_uncore *); if (!amd_uncore_llc) { ret = -ENOMEM; goto fail_llc; } ret = perf_pmu_register(&amd_llc_pmu, amd_llc_pmu.name, -1); if (ret) goto fail_llc; pr_info("%d %s %s counters detected\n", num_counters_llc, boot_cpu_data.x86_vendor == X86_VENDOR_HYGON ? "HYGON" : "", amd_llc_pmu.name); ret = 0; } /* * Install callbacks. Core will call them for each online cpu. */ if (cpuhp_setup_state(CPUHP_PERF_X86_AMD_UNCORE_PREP, "perf/x86/amd/uncore:prepare", amd_uncore_cpu_up_prepare, amd_uncore_cpu_dead)) goto fail_llc; if (cpuhp_setup_state(CPUHP_AP_PERF_X86_AMD_UNCORE_STARTING, "perf/x86/amd/uncore:starting", amd_uncore_cpu_starting, NULL)) goto fail_prep; if (cpuhp_setup_state(CPUHP_AP_PERF_X86_AMD_UNCORE_ONLINE, "perf/x86/amd/uncore:online", amd_uncore_cpu_online, amd_uncore_cpu_down_prepare)) goto fail_start; return 0; fail_start: cpuhp_remove_state(CPUHP_AP_PERF_X86_AMD_UNCORE_STARTING); fail_prep: cpuhp_remove_state(CPUHP_PERF_X86_AMD_UNCORE_PREP); fail_llc: if (boot_cpu_has(X86_FEATURE_PERFCTR_NB)) perf_pmu_unregister(&amd_nb_pmu); free_percpu(amd_uncore_llc); fail_nb: free_percpu(amd_uncore_nb); return ret; } static void __exit amd_uncore_exit(void) { cpuhp_remove_state(CPUHP_AP_PERF_X86_AMD_UNCORE_ONLINE); cpuhp_remove_state(CPUHP_AP_PERF_X86_AMD_UNCORE_STARTING); cpuhp_remove_state(CPUHP_PERF_X86_AMD_UNCORE_PREP); if (boot_cpu_has(X86_FEATURE_PERFCTR_LLC)) { perf_pmu_unregister(&amd_llc_pmu); free_percpu(amd_uncore_llc); amd_uncore_llc = NULL; } if (boot_cpu_has(X86_FEATURE_PERFCTR_NB)) { perf_pmu_unregister(&amd_nb_pmu); free_percpu(amd_uncore_nb); amd_uncore_nb = NULL; } } module_init(amd_uncore_init); module_exit(amd_uncore_exit); MODULE_DESCRIPTION("AMD Uncore Driver"); MODULE_LICENSE("GPL v2");
linux-master
arch/x86/events/amd/uncore.c
// SPDX-License-Identifier: GPL-2.0 /* * Implement support for AMD Fam19h Branch Sampling feature * Based on specifications published in AMD PPR Fam19 Model 01 * * Copyright 2021 Google LLC * Contributed by Stephane Eranian <[email protected]> */ #include <linux/kernel.h> #include <linux/jump_label.h> #include <asm/msr.h> #include <asm/cpufeature.h> #include "../perf_event.h" #define BRS_POISON 0xFFFFFFFFFFFFFFFEULL /* mark limit of valid entries */ /* Debug Extension Configuration register layout */ union amd_debug_extn_cfg { __u64 val; struct { __u64 rsvd0:2, /* reserved */ brsmen:1, /* branch sample enable */ rsvd4_3:2,/* reserved - must be 0x3 */ vb:1, /* valid branches recorded */ rsvd2:10, /* reserved */ msroff:4, /* index of next entry to write */ rsvd3:4, /* reserved */ pmc:3, /* #PMC holding the sampling event */ rsvd4:37; /* reserved */ }; }; static inline unsigned int brs_from(int idx) { return MSR_AMD_SAMP_BR_FROM + 2 * idx; } static inline unsigned int brs_to(int idx) { return MSR_AMD_SAMP_BR_FROM + 2 * idx + 1; } static __always_inline void set_debug_extn_cfg(u64 val) { /* bits[4:3] must always be set to 11b */ __wrmsr(MSR_AMD_DBG_EXTN_CFG, val | 3ULL << 3, val >> 32); } static __always_inline u64 get_debug_extn_cfg(void) { return __rdmsr(MSR_AMD_DBG_EXTN_CFG); } static bool __init amd_brs_detect(void) { if (!cpu_feature_enabled(X86_FEATURE_BRS)) return false; switch (boot_cpu_data.x86) { case 0x19: /* AMD Fam19h (Zen3) */ x86_pmu.lbr_nr = 16; /* No hardware filtering supported */ x86_pmu.lbr_sel_map = NULL; x86_pmu.lbr_sel_mask = 0; break; default: return false; } return true; } /* * Current BRS implementation does not support branch type or privilege level * filtering. Therefore, this function simply enforces these limitations. No need for * a br_sel_map. Software filtering is not supported because it would not correlate well * with a sampling period. */ static int amd_brs_setup_filter(struct perf_event *event) { u64 type = event->attr.branch_sample_type; /* No BRS support */ if (!x86_pmu.lbr_nr) return -EOPNOTSUPP; /* Can only capture all branches, i.e., no filtering */ if ((type & ~PERF_SAMPLE_BRANCH_PLM_ALL) != PERF_SAMPLE_BRANCH_ANY) return -EINVAL; return 0; } static inline int amd_is_brs_event(struct perf_event *e) { return (e->hw.config & AMD64_RAW_EVENT_MASK) == AMD_FAM19H_BRS_EVENT; } int amd_brs_hw_config(struct perf_event *event) { int ret = 0; /* * Due to interrupt holding, BRS is not recommended in * counting mode. */ if (!is_sampling_event(event)) return -EINVAL; /* * Due to the way BRS operates by holding the interrupt until * lbr_nr entries have been captured, it does not make sense * to allow sampling on BRS with an event that does not match * what BRS is capturing, i.e., retired taken branches. * Otherwise the correlation with the event's period is even * more loose: * * With retired taken branch: * Effective P = P + 16 + X * With any other event: * Effective P = P + Y + X * * Where X is the number of taken branches due to interrupt * skid. Skid is large. * * Where Y is the occurences of the event while BRS is * capturing the lbr_nr entries. * * By using retired taken branches, we limit the impact on the * Y variable. We know it cannot be more than the depth of * BRS. */ if (!amd_is_brs_event(event)) return -EINVAL; /* * BRS implementation does not work with frequency mode * reprogramming of the period. */ if (event->attr.freq) return -EINVAL; /* * The kernel subtracts BRS depth from period, so it must * be big enough. */ if (event->attr.sample_period <= x86_pmu.lbr_nr) return -EINVAL; /* * Check if we can allow PERF_SAMPLE_BRANCH_STACK */ ret = amd_brs_setup_filter(event); /* only set in case of success */ if (!ret) event->hw.flags |= PERF_X86_EVENT_AMD_BRS; return ret; } /* tos = top of stack, i.e., last valid entry written */ static inline int amd_brs_get_tos(union amd_debug_extn_cfg *cfg) { /* * msroff: index of next entry to write so top-of-stack is one off * if BRS is full then msroff is set back to 0. */ return (cfg->msroff ? cfg->msroff : x86_pmu.lbr_nr) - 1; } /* * make sure we have a sane BRS offset to begin with * especially with kexec */ void amd_brs_reset(void) { if (!cpu_feature_enabled(X86_FEATURE_BRS)) return; /* * Reset config */ set_debug_extn_cfg(0); /* * Mark first entry as poisoned */ wrmsrl(brs_to(0), BRS_POISON); } int __init amd_brs_init(void) { if (!amd_brs_detect()) return -EOPNOTSUPP; pr_cont("%d-deep BRS, ", x86_pmu.lbr_nr); return 0; } void amd_brs_enable(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); union amd_debug_extn_cfg cfg; /* Activate only on first user */ if (++cpuc->brs_active > 1) return; cfg.val = 0; /* reset all fields */ cfg.brsmen = 1; /* enable branch sampling */ /* Set enable bit */ set_debug_extn_cfg(cfg.val); } void amd_brs_enable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (cpuc->lbr_users) amd_brs_enable(); } void amd_brs_disable(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); union amd_debug_extn_cfg cfg; /* Check if active (could be disabled via x86_pmu_disable_all()) */ if (!cpuc->brs_active) return; /* Only disable for last user */ if (--cpuc->brs_active) return; /* * Clear the brsmen bit but preserve the others as they contain * useful state such as vb and msroff */ cfg.val = get_debug_extn_cfg(); /* * When coming in on interrupt and BRS is full, then hw will have * already stopped BRS, no need to issue wrmsr again */ if (cfg.brsmen) { cfg.brsmen = 0; set_debug_extn_cfg(cfg.val); } } void amd_brs_disable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (cpuc->lbr_users) amd_brs_disable(); } static bool amd_brs_match_plm(struct perf_event *event, u64 to) { int type = event->attr.branch_sample_type; int plm_k = PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_HV; int plm_u = PERF_SAMPLE_BRANCH_USER; if (!(type & plm_k) && kernel_ip(to)) return 0; if (!(type & plm_u) && !kernel_ip(to)) return 0; return 1; } /* * Caller must ensure amd_brs_inuse() is true before calling * return: */ void amd_brs_drain(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_event *event = cpuc->events[0]; struct perf_branch_entry *br = cpuc->lbr_entries; union amd_debug_extn_cfg cfg; u32 i, nr = 0, num, tos, start; u32 shift = 64 - boot_cpu_data.x86_virt_bits; /* * BRS event forced on PMC0, * so check if there is an event. * It is possible to have lbr_users > 0 but the event * not yet scheduled due to long latency PMU irq */ if (!event) goto empty; cfg.val = get_debug_extn_cfg(); /* Sanity check [0-x86_pmu.lbr_nr] */ if (WARN_ON_ONCE(cfg.msroff >= x86_pmu.lbr_nr)) goto empty; /* No valid branch */ if (cfg.vb == 0) goto empty; /* * msr.off points to next entry to be written * tos = most recent entry index = msr.off - 1 * BRS register buffer saturates, so we know we have * start < tos and that we have to read from start to tos */ start = 0; tos = amd_brs_get_tos(&cfg); num = tos - start + 1; /* * BRS is only one pass (saturation) from MSROFF to depth-1 * MSROFF wraps to zero when buffer is full */ for (i = 0; i < num; i++) { u32 brs_idx = tos - i; u64 from, to; rdmsrl(brs_to(brs_idx), to); /* Entry does not belong to us (as marked by kernel) */ if (to == BRS_POISON) break; /* * Sign-extend SAMP_BR_TO to 64 bits, bits 61-63 are reserved. * Necessary to generate proper virtual addresses suitable for * symbolization */ to = (u64)(((s64)to << shift) >> shift); if (!amd_brs_match_plm(event, to)) continue; rdmsrl(brs_from(brs_idx), from); perf_clear_branch_entry_bitfields(br+nr); br[nr].from = from; br[nr].to = to; nr++; } empty: /* Record number of sampled branches */ cpuc->lbr_stack.nr = nr; } /* * Poison most recent entry to prevent reuse by next task * required because BRS entry are not tagged by PID */ static void amd_brs_poison_buffer(void) { union amd_debug_extn_cfg cfg; unsigned int idx; /* Get current state */ cfg.val = get_debug_extn_cfg(); /* idx is most recently written entry */ idx = amd_brs_get_tos(&cfg); /* Poison target of entry */ wrmsrl(brs_to(idx), BRS_POISON); } /* * On context switch in, we need to make sure no samples from previous user * are left in the BRS. * * On ctxswin, sched_in = true, called after the PMU has started * On ctxswout, sched_in = false, called before the PMU is stopped */ void amd_pmu_brs_sched_task(struct perf_event_pmu_context *pmu_ctx, bool sched_in) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* no active users */ if (!cpuc->lbr_users) return; /* * On context switch in, we need to ensure we do not use entries * from previous BRS user on that CPU, so we poison the buffer as * a faster way compared to resetting all entries. */ if (sched_in) amd_brs_poison_buffer(); } /* * called from ACPI processor_idle.c or acpi_pad.c * with interrupts disabled */ void noinstr perf_amd_brs_lopwr_cb(bool lopwr_in) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); union amd_debug_extn_cfg cfg; /* * on mwait in, we may end up in non C0 state. * we must disable branch sampling to avoid holding the NMI * for too long. We disable it in hardware but we * keep the state in cpuc, so we can re-enable. * * The hardware will deliver the NMI if needed when brsmen cleared */ if (cpuc->brs_active) { cfg.val = get_debug_extn_cfg(); cfg.brsmen = !lopwr_in; set_debug_extn_cfg(cfg.val); } } DEFINE_STATIC_CALL_NULL(perf_lopwr_cb, perf_amd_brs_lopwr_cb); EXPORT_STATIC_CALL_TRAMP_GPL(perf_lopwr_cb); void __init amd_brs_lopwr_init(void) { static_call_update(perf_lopwr_cb, perf_amd_brs_lopwr_cb); }
linux-master
arch/x86/events/amd/brs.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/perf_event.h> #include <linux/jump_label.h> #include <linux/export.h> #include <linux/types.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/jiffies.h> #include <asm/apicdef.h> #include <asm/apic.h> #include <asm/nmi.h> #include "../perf_event.h" static DEFINE_PER_CPU(unsigned long, perf_nmi_tstamp); static unsigned long perf_nmi_window; /* AMD Event 0xFFF: Merge. Used with Large Increment per Cycle events */ #define AMD_MERGE_EVENT ((0xFULL << 32) | 0xFFULL) #define AMD_MERGE_EVENT_ENABLE (AMD_MERGE_EVENT | ARCH_PERFMON_EVENTSEL_ENABLE) /* PMC Enable and Overflow bits for PerfCntrGlobal* registers */ static u64 amd_pmu_global_cntr_mask __read_mostly; static __initconst const u64 amd_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [ C(L1D) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0040, /* Data Cache Accesses */ [ C(RESULT_MISS) ] = 0x0141, /* Data Cache Misses */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x0267, /* Data Prefetcher :attempts */ [ C(RESULT_MISS) ] = 0x0167, /* Data Prefetcher :cancelled */ }, }, [ C(L1I ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0080, /* Instruction cache fetches */ [ C(RESULT_MISS) ] = 0x0081, /* Instruction cache misses */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0x014B, /* Prefetch Instructions :Load */ [ C(RESULT_MISS) ] = 0, }, }, [ C(LL ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x037D, /* Requests to L2 Cache :IC+DC */ [ C(RESULT_MISS) ] = 0x037E, /* L2 Cache Misses : IC+DC */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0x017F, /* L2 Fill/Writeback */ [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(DTLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0040, /* Data Cache Accesses */ [ C(RESULT_MISS) ] = 0x0746, /* L1_DTLB_AND_L2_DLTB_MISS.ALL */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = 0, [ C(RESULT_MISS) ] = 0, }, }, [ C(ITLB) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x0080, /* Instruction fecthes */ [ C(RESULT_MISS) ] = 0x0385, /* L1_ITLB_AND_L2_ITLB_MISS.ALL */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(BPU ) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0x00c2, /* Retired Branch Instr. */ [ C(RESULT_MISS) ] = 0x00c3, /* Retired Mispredicted BI */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, [ C(NODE) ] = { [ C(OP_READ) ] = { [ C(RESULT_ACCESS) ] = 0xb8e9, /* CPU Request to Memory, l+r */ [ C(RESULT_MISS) ] = 0x98e9, /* CPU Request to Memory, r */ }, [ C(OP_WRITE) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, [ C(OP_PREFETCH) ] = { [ C(RESULT_ACCESS) ] = -1, [ C(RESULT_MISS) ] = -1, }, }, }; static __initconst const u64 amd_hw_cache_event_ids_f17h [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0040, /* Data Cache Accesses */ [C(RESULT_MISS)] = 0xc860, /* L2$ access from DC Miss */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0xff5a, /* h/w prefetch DC Fills */ [C(RESULT_MISS)] = 0, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0080, /* Instruction cache fetches */ [C(RESULT_MISS)] = 0x0081, /* Instruction cache misses */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0xff45, /* All L2 DTLB accesses */ [C(RESULT_MISS)] = 0xf045, /* L2 DTLB misses (PT walks) */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0084, /* L1 ITLB misses, L2 ITLB hits */ [C(RESULT_MISS)] = 0xff85, /* L1 ITLB misses, L2 misses */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x00c2, /* Retired Branch Instr. */ [C(RESULT_MISS)] = 0x00c3, /* Retired Mispredicted BI */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(NODE)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0, [C(RESULT_MISS)] = 0, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, }; /* * AMD Performance Monitor K7 and later, up to and including Family 16h: */ static const u64 amd_perfmon_event_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_CPU_CYCLES] = 0x0076, [PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0, [PERF_COUNT_HW_CACHE_REFERENCES] = 0x077d, [PERF_COUNT_HW_CACHE_MISSES] = 0x077e, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c2, [PERF_COUNT_HW_BRANCH_MISSES] = 0x00c3, [PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = 0x00d0, /* "Decoder empty" event */ [PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = 0x00d1, /* "Dispatch stalls" event */ }; /* * AMD Performance Monitor Family 17h and later: */ static const u64 amd_f17h_perfmon_event_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_CPU_CYCLES] = 0x0076, [PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0, [PERF_COUNT_HW_CACHE_REFERENCES] = 0xff60, [PERF_COUNT_HW_CACHE_MISSES] = 0x0964, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c2, [PERF_COUNT_HW_BRANCH_MISSES] = 0x00c3, [PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = 0x0287, [PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = 0x0187, }; static u64 amd_pmu_event_map(int hw_event) { if (boot_cpu_data.x86 >= 0x17) return amd_f17h_perfmon_event_map[hw_event]; return amd_perfmon_event_map[hw_event]; } /* * Previously calculated offsets */ static unsigned int event_offsets[X86_PMC_IDX_MAX] __read_mostly; static unsigned int count_offsets[X86_PMC_IDX_MAX] __read_mostly; /* * Legacy CPUs: * 4 counters starting at 0xc0010000 each offset by 1 * * CPUs with core performance counter extensions: * 6 counters starting at 0xc0010200 each offset by 2 */ static inline int amd_pmu_addr_offset(int index, bool eventsel) { int offset; if (!index) return index; if (eventsel) offset = event_offsets[index]; else offset = count_offsets[index]; if (offset) return offset; if (!boot_cpu_has(X86_FEATURE_PERFCTR_CORE)) offset = index; else offset = index << 1; if (eventsel) event_offsets[index] = offset; else count_offsets[index] = offset; return offset; } /* * AMD64 events are detected based on their event codes. */ static inline unsigned int amd_get_event_code(struct hw_perf_event *hwc) { return ((hwc->config >> 24) & 0x0f00) | (hwc->config & 0x00ff); } static inline bool amd_is_pair_event_code(struct hw_perf_event *hwc) { if (!(x86_pmu.flags & PMU_FL_PAIR)) return false; switch (amd_get_event_code(hwc)) { case 0x003: return true; /* Retired SSE/AVX FLOPs */ default: return false; } } DEFINE_STATIC_CALL_RET0(amd_pmu_branch_hw_config, *x86_pmu.hw_config); static int amd_core_hw_config(struct perf_event *event) { if (event->attr.exclude_host && event->attr.exclude_guest) /* * When HO == GO == 1 the hardware treats that as GO == HO == 0 * and will count in both modes. We don't want to count in that * case so we emulate no-counting by setting US = OS = 0. */ event->hw.config &= ~(ARCH_PERFMON_EVENTSEL_USR | ARCH_PERFMON_EVENTSEL_OS); else if (event->attr.exclude_host) event->hw.config |= AMD64_EVENTSEL_GUESTONLY; else if (event->attr.exclude_guest) event->hw.config |= AMD64_EVENTSEL_HOSTONLY; if ((x86_pmu.flags & PMU_FL_PAIR) && amd_is_pair_event_code(&event->hw)) event->hw.flags |= PERF_X86_EVENT_PAIR; if (has_branch_stack(event)) return static_call(amd_pmu_branch_hw_config)(event); return 0; } static inline int amd_is_nb_event(struct hw_perf_event *hwc) { return (hwc->config & 0xe0) == 0xe0; } static inline int amd_has_nb(struct cpu_hw_events *cpuc) { struct amd_nb *nb = cpuc->amd_nb; return nb && nb->nb_id != -1; } static int amd_pmu_hw_config(struct perf_event *event) { int ret; /* pass precise event sampling to ibs: */ if (event->attr.precise_ip && get_ibs_caps()) return forward_event_to_ibs(event); if (has_branch_stack(event) && !x86_pmu.lbr_nr) return -EOPNOTSUPP; ret = x86_pmu_hw_config(event); if (ret) return ret; if (event->attr.type == PERF_TYPE_RAW) event->hw.config |= event->attr.config & AMD64_RAW_EVENT_MASK; return amd_core_hw_config(event); } static void __amd_put_nb_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event) { struct amd_nb *nb = cpuc->amd_nb; int i; /* * need to scan whole list because event may not have * been assigned during scheduling * * no race condition possible because event can only * be removed on one CPU at a time AND PMU is disabled * when we come here */ for (i = 0; i < x86_pmu.num_counters; i++) { if (cmpxchg(nb->owners + i, event, NULL) == event) break; } } /* * AMD64 NorthBridge events need special treatment because * counter access needs to be synchronized across all cores * of a package. Refer to BKDG section 3.12 * * NB events are events measuring L3 cache, Hypertransport * traffic. They are identified by an event code >= 0xe00. * They measure events on the NorthBride which is shared * by all cores on a package. NB events are counted on a * shared set of counters. When a NB event is programmed * in a counter, the data actually comes from a shared * counter. Thus, access to those counters needs to be * synchronized. * * We implement the synchronization such that no two cores * can be measuring NB events using the same counters. Thus, * we maintain a per-NB allocation table. The available slot * is propagated using the event_constraint structure. * * We provide only one choice for each NB event based on * the fact that only NB events have restrictions. Consequently, * if a counter is available, there is a guarantee the NB event * will be assigned to it. If no slot is available, an empty * constraint is returned and scheduling will eventually fail * for this event. * * Note that all cores attached the same NB compete for the same * counters to host NB events, this is why we use atomic ops. Some * multi-chip CPUs may have more than one NB. * * Given that resources are allocated (cmpxchg), they must be * eventually freed for others to use. This is accomplished by * calling __amd_put_nb_event_constraints() * * Non NB events are not impacted by this restriction. */ static struct event_constraint * __amd_get_nb_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event, struct event_constraint *c) { struct hw_perf_event *hwc = &event->hw; struct amd_nb *nb = cpuc->amd_nb; struct perf_event *old; int idx, new = -1; if (!c) c = &unconstrained; if (cpuc->is_fake) return c; /* * detect if already present, if so reuse * * cannot merge with actual allocation * because of possible holes * * event can already be present yet not assigned (in hwc->idx) * because of successive calls to x86_schedule_events() from * hw_perf_group_sched_in() without hw_perf_enable() */ for_each_set_bit(idx, c->idxmsk, x86_pmu.num_counters) { if (new == -1 || hwc->idx == idx) /* assign free slot, prefer hwc->idx */ old = cmpxchg(nb->owners + idx, NULL, event); else if (nb->owners[idx] == event) /* event already present */ old = event; else continue; if (old && old != event) continue; /* reassign to this slot */ if (new != -1) cmpxchg(nb->owners + new, event, NULL); new = idx; /* already present, reuse */ if (old == event) break; } if (new == -1) return &emptyconstraint; return &nb->event_constraints[new]; } static struct amd_nb *amd_alloc_nb(int cpu) { struct amd_nb *nb; int i; nb = kzalloc_node(sizeof(struct amd_nb), GFP_KERNEL, cpu_to_node(cpu)); if (!nb) return NULL; nb->nb_id = -1; /* * initialize all possible NB constraints */ for (i = 0; i < x86_pmu.num_counters; i++) { __set_bit(i, nb->event_constraints[i].idxmsk); nb->event_constraints[i].weight = 1; } return nb; } typedef void (amd_pmu_branch_reset_t)(void); DEFINE_STATIC_CALL_NULL(amd_pmu_branch_reset, amd_pmu_branch_reset_t); static void amd_pmu_cpu_reset(int cpu) { if (x86_pmu.lbr_nr) static_call(amd_pmu_branch_reset)(); if (x86_pmu.version < 2) return; /* Clear enable bits i.e. PerfCntrGlobalCtl.PerfCntrEn */ wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_CTL, 0); /* Clear overflow bits i.e. PerfCntrGLobalStatus.PerfCntrOvfl */ wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR, amd_pmu_global_cntr_mask); } static int amd_pmu_cpu_prepare(int cpu) { struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu); cpuc->lbr_sel = kzalloc_node(sizeof(struct er_account), GFP_KERNEL, cpu_to_node(cpu)); if (!cpuc->lbr_sel) return -ENOMEM; WARN_ON_ONCE(cpuc->amd_nb); if (!x86_pmu.amd_nb_constraints) return 0; cpuc->amd_nb = amd_alloc_nb(cpu); if (cpuc->amd_nb) return 0; kfree(cpuc->lbr_sel); cpuc->lbr_sel = NULL; return -ENOMEM; } static void amd_pmu_cpu_starting(int cpu) { struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu); void **onln = &cpuc->kfree_on_online[X86_PERF_KFREE_SHARED]; struct amd_nb *nb; int i, nb_id; cpuc->perf_ctr_virt_mask = AMD64_EVENTSEL_HOSTONLY; if (!x86_pmu.amd_nb_constraints) return; nb_id = topology_die_id(cpu); WARN_ON_ONCE(nb_id == BAD_APICID); for_each_online_cpu(i) { nb = per_cpu(cpu_hw_events, i).amd_nb; if (WARN_ON_ONCE(!nb)) continue; if (nb->nb_id == nb_id) { *onln = cpuc->amd_nb; cpuc->amd_nb = nb; break; } } cpuc->amd_nb->nb_id = nb_id; cpuc->amd_nb->refcnt++; amd_pmu_cpu_reset(cpu); } static void amd_pmu_cpu_dead(int cpu) { struct cpu_hw_events *cpuhw = &per_cpu(cpu_hw_events, cpu); kfree(cpuhw->lbr_sel); cpuhw->lbr_sel = NULL; if (!x86_pmu.amd_nb_constraints) return; if (cpuhw->amd_nb) { struct amd_nb *nb = cpuhw->amd_nb; if (nb->nb_id == -1 || --nb->refcnt == 0) kfree(nb); cpuhw->amd_nb = NULL; } amd_pmu_cpu_reset(cpu); } static inline void amd_pmu_set_global_ctl(u64 ctl) { wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_CTL, ctl); } static inline u64 amd_pmu_get_global_status(void) { u64 status; /* PerfCntrGlobalStatus is read-only */ rdmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_STATUS, status); return status; } static inline void amd_pmu_ack_global_status(u64 status) { /* * PerfCntrGlobalStatus is read-only but an overflow acknowledgment * mechanism exists; writing 1 to a bit in PerfCntrGlobalStatusClr * clears the same bit in PerfCntrGlobalStatus */ wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR, status); } static bool amd_pmu_test_overflow_topbit(int idx) { u64 counter; rdmsrl(x86_pmu_event_addr(idx), counter); return !(counter & BIT_ULL(x86_pmu.cntval_bits - 1)); } static bool amd_pmu_test_overflow_status(int idx) { return amd_pmu_get_global_status() & BIT_ULL(idx); } DEFINE_STATIC_CALL(amd_pmu_test_overflow, amd_pmu_test_overflow_topbit); /* * When a PMC counter overflows, an NMI is used to process the event and * reset the counter. NMI latency can result in the counter being updated * before the NMI can run, which can result in what appear to be spurious * NMIs. This function is intended to wait for the NMI to run and reset * the counter to avoid possible unhandled NMI messages. */ #define OVERFLOW_WAIT_COUNT 50 static void amd_pmu_wait_on_overflow(int idx) { unsigned int i; /* * Wait for the counter to be reset if it has overflowed. This loop * should exit very, very quickly, but just in case, don't wait * forever... */ for (i = 0; i < OVERFLOW_WAIT_COUNT; i++) { if (!static_call(amd_pmu_test_overflow)(idx)) break; /* Might be in IRQ context, so can't sleep */ udelay(1); } } static void amd_pmu_check_overflow(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int idx; /* * This shouldn't be called from NMI context, but add a safeguard here * to return, since if we're in NMI context we can't wait for an NMI * to reset an overflowed counter value. */ if (in_nmi()) return; /* * Check each counter for overflow and wait for it to be reset by the * NMI if it has overflowed. This relies on the fact that all active * counters are always enabled when this function is called and * ARCH_PERFMON_EVENTSEL_INT is always set. */ for (idx = 0; idx < x86_pmu.num_counters; idx++) { if (!test_bit(idx, cpuc->active_mask)) continue; amd_pmu_wait_on_overflow(idx); } } static void amd_pmu_enable_event(struct perf_event *event) { x86_pmu_enable_event(event); } static void amd_pmu_enable_all(int added) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int idx; amd_brs_enable_all(); for (idx = 0; idx < x86_pmu.num_counters; idx++) { /* only activate events which are marked as active */ if (!test_bit(idx, cpuc->active_mask)) continue; amd_pmu_enable_event(cpuc->events[idx]); } } static void amd_pmu_v2_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; /* * Testing cpu_hw_events.enabled should be skipped in this case unlike * in x86_pmu_enable_event(). * * Since cpu_hw_events.enabled is set only after returning from * x86_pmu_start(), the PMCs must be programmed and kept ready. * Counting starts only after x86_pmu_enable_all() is called. */ __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE); } static __always_inline void amd_pmu_core_enable_all(void) { amd_pmu_set_global_ctl(amd_pmu_global_cntr_mask); } static void amd_pmu_v2_enable_all(int added) { amd_pmu_lbr_enable_all(); amd_pmu_core_enable_all(); } static void amd_pmu_disable_event(struct perf_event *event) { x86_pmu_disable_event(event); /* * This can be called from NMI context (via x86_pmu_stop). The counter * may have overflowed, but either way, we'll never see it get reset * by the NMI if we're already in the NMI. And the NMI latency support * below will take care of any pending NMI that might have been * generated by the overflow. */ if (in_nmi()) return; amd_pmu_wait_on_overflow(event->hw.idx); } static void amd_pmu_disable_all(void) { amd_brs_disable_all(); x86_pmu_disable_all(); amd_pmu_check_overflow(); } static __always_inline void amd_pmu_core_disable_all(void) { amd_pmu_set_global_ctl(0); } static void amd_pmu_v2_disable_all(void) { amd_pmu_core_disable_all(); amd_pmu_lbr_disable_all(); amd_pmu_check_overflow(); } DEFINE_STATIC_CALL_NULL(amd_pmu_branch_add, *x86_pmu.add); static void amd_pmu_add_event(struct perf_event *event) { if (needs_branch_stack(event)) static_call(amd_pmu_branch_add)(event); } DEFINE_STATIC_CALL_NULL(amd_pmu_branch_del, *x86_pmu.del); static void amd_pmu_del_event(struct perf_event *event) { if (needs_branch_stack(event)) static_call(amd_pmu_branch_del)(event); } /* * Because of NMI latency, if multiple PMC counters are active or other sources * of NMIs are received, the perf NMI handler can handle one or more overflowed * PMC counters outside of the NMI associated with the PMC overflow. If the NMI * doesn't arrive at the LAPIC in time to become a pending NMI, then the kernel * back-to-back NMI support won't be active. This PMC handler needs to take into * account that this can occur, otherwise this could result in unknown NMI * messages being issued. Examples of this is PMC overflow while in the NMI * handler when multiple PMCs are active or PMC overflow while handling some * other source of an NMI. * * Attempt to mitigate this by creating an NMI window in which un-handled NMIs * received during this window will be claimed. This prevents extending the * window past when it is possible that latent NMIs should be received. The * per-CPU perf_nmi_tstamp will be set to the window end time whenever perf has * handled a counter. When an un-handled NMI is received, it will be claimed * only if arriving within that window. */ static inline int amd_pmu_adjust_nmi_window(int handled) { /* * If a counter was handled, record a timestamp such that un-handled * NMIs will be claimed if arriving within that window. */ if (handled) { this_cpu_write(perf_nmi_tstamp, jiffies + perf_nmi_window); return handled; } if (time_after(jiffies, this_cpu_read(perf_nmi_tstamp))) return NMI_DONE; return NMI_HANDLED; } static int amd_pmu_handle_irq(struct pt_regs *regs) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int handled; int pmu_enabled; /* * Save the PMU state. * It needs to be restored when leaving the handler. */ pmu_enabled = cpuc->enabled; cpuc->enabled = 0; amd_brs_disable_all(); /* Drain BRS is in use (could be inactive) */ if (cpuc->lbr_users) amd_brs_drain(); /* Process any counter overflows */ handled = x86_pmu_handle_irq(regs); cpuc->enabled = pmu_enabled; if (pmu_enabled) amd_brs_enable_all(); return amd_pmu_adjust_nmi_window(handled); } static int amd_pmu_v2_handle_irq(struct pt_regs *regs) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_sample_data data; struct hw_perf_event *hwc; struct perf_event *event; int handled = 0, idx; u64 status, mask; bool pmu_enabled; /* * Save the PMU state as it needs to be restored when leaving the * handler */ pmu_enabled = cpuc->enabled; cpuc->enabled = 0; /* Stop counting but do not disable LBR */ amd_pmu_core_disable_all(); status = amd_pmu_get_global_status(); /* Check if any overflows are pending */ if (!status) goto done; /* Read branch records before unfreezing */ if (status & GLOBAL_STATUS_LBRS_FROZEN) { amd_pmu_lbr_read(); status &= ~GLOBAL_STATUS_LBRS_FROZEN; } for (idx = 0; idx < x86_pmu.num_counters; idx++) { if (!test_bit(idx, cpuc->active_mask)) continue; event = cpuc->events[idx]; hwc = &event->hw; x86_perf_event_update(event); mask = BIT_ULL(idx); if (!(status & mask)) continue; /* Event overflow */ handled++; status &= ~mask; perf_sample_data_init(&data, 0, hwc->last_period); if (!x86_perf_event_set_period(event)) continue; if (has_branch_stack(event)) perf_sample_save_brstack(&data, event, &cpuc->lbr_stack); if (perf_event_overflow(event, &data, regs)) x86_pmu_stop(event, 0); } /* * It should never be the case that some overflows are not handled as * the corresponding PMCs are expected to be inactive according to the * active_mask */ WARN_ON(status > 0); /* Clear overflow and freeze bits */ amd_pmu_ack_global_status(~status); /* * Unmasking the LVTPC is not required as the Mask (M) bit of the LVT * PMI entry is not set by the local APIC when a PMC overflow occurs */ inc_irq_stat(apic_perf_irqs); done: cpuc->enabled = pmu_enabled; /* Resume counting only if PMU is active */ if (pmu_enabled) amd_pmu_core_enable_all(); return amd_pmu_adjust_nmi_window(handled); } static struct event_constraint * amd_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { /* * if not NB event or no NB, then no constraints */ if (!(amd_has_nb(cpuc) && amd_is_nb_event(&event->hw))) return &unconstrained; return __amd_get_nb_event_constraints(cpuc, event, NULL); } static void amd_put_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event) { if (amd_has_nb(cpuc) && amd_is_nb_event(&event->hw)) __amd_put_nb_event_constraints(cpuc, event); } PMU_FORMAT_ATTR(event, "config:0-7,32-35"); PMU_FORMAT_ATTR(umask, "config:8-15" ); PMU_FORMAT_ATTR(edge, "config:18" ); PMU_FORMAT_ATTR(inv, "config:23" ); PMU_FORMAT_ATTR(cmask, "config:24-31" ); static struct attribute *amd_format_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_cmask.attr, NULL, }; /* AMD Family 15h */ #define AMD_EVENT_TYPE_MASK 0x000000F0ULL #define AMD_EVENT_FP 0x00000000ULL ... 0x00000010ULL #define AMD_EVENT_LS 0x00000020ULL ... 0x00000030ULL #define AMD_EVENT_DC 0x00000040ULL ... 0x00000050ULL #define AMD_EVENT_CU 0x00000060ULL ... 0x00000070ULL #define AMD_EVENT_IC_DE 0x00000080ULL ... 0x00000090ULL #define AMD_EVENT_EX_LS 0x000000C0ULL #define AMD_EVENT_DE 0x000000D0ULL #define AMD_EVENT_NB 0x000000E0ULL ... 0x000000F0ULL /* * AMD family 15h event code/PMC mappings: * * type = event_code & 0x0F0: * * 0x000 FP PERF_CTL[5:3] * 0x010 FP PERF_CTL[5:3] * 0x020 LS PERF_CTL[5:0] * 0x030 LS PERF_CTL[5:0] * 0x040 DC PERF_CTL[5:0] * 0x050 DC PERF_CTL[5:0] * 0x060 CU PERF_CTL[2:0] * 0x070 CU PERF_CTL[2:0] * 0x080 IC/DE PERF_CTL[2:0] * 0x090 IC/DE PERF_CTL[2:0] * 0x0A0 --- * 0x0B0 --- * 0x0C0 EX/LS PERF_CTL[5:0] * 0x0D0 DE PERF_CTL[2:0] * 0x0E0 NB NB_PERF_CTL[3:0] * 0x0F0 NB NB_PERF_CTL[3:0] * * Exceptions: * * 0x000 FP PERF_CTL[3], PERF_CTL[5:3] (*) * 0x003 FP PERF_CTL[3] * 0x004 FP PERF_CTL[3], PERF_CTL[5:3] (*) * 0x00B FP PERF_CTL[3] * 0x00D FP PERF_CTL[3] * 0x023 DE PERF_CTL[2:0] * 0x02D LS PERF_CTL[3] * 0x02E LS PERF_CTL[3,0] * 0x031 LS PERF_CTL[2:0] (**) * 0x043 CU PERF_CTL[2:0] * 0x045 CU PERF_CTL[2:0] * 0x046 CU PERF_CTL[2:0] * 0x054 CU PERF_CTL[2:0] * 0x055 CU PERF_CTL[2:0] * 0x08F IC PERF_CTL[0] * 0x187 DE PERF_CTL[0] * 0x188 DE PERF_CTL[0] * 0x0DB EX PERF_CTL[5:0] * 0x0DC LS PERF_CTL[5:0] * 0x0DD LS PERF_CTL[5:0] * 0x0DE LS PERF_CTL[5:0] * 0x0DF LS PERF_CTL[5:0] * 0x1C0 EX PERF_CTL[5:3] * 0x1D6 EX PERF_CTL[5:0] * 0x1D8 EX PERF_CTL[5:0] * * (*) depending on the umask all FPU counters may be used * (**) only one unitmask enabled at a time */ static struct event_constraint amd_f15_PMC0 = EVENT_CONSTRAINT(0, 0x01, 0); static struct event_constraint amd_f15_PMC20 = EVENT_CONSTRAINT(0, 0x07, 0); static struct event_constraint amd_f15_PMC3 = EVENT_CONSTRAINT(0, 0x08, 0); static struct event_constraint amd_f15_PMC30 = EVENT_CONSTRAINT_OVERLAP(0, 0x09, 0); static struct event_constraint amd_f15_PMC50 = EVENT_CONSTRAINT(0, 0x3F, 0); static struct event_constraint amd_f15_PMC53 = EVENT_CONSTRAINT(0, 0x38, 0); static struct event_constraint * amd_get_event_constraints_f15h(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; unsigned int event_code = amd_get_event_code(hwc); switch (event_code & AMD_EVENT_TYPE_MASK) { case AMD_EVENT_FP: switch (event_code) { case 0x000: if (!(hwc->config & 0x0000F000ULL)) break; if (!(hwc->config & 0x00000F00ULL)) break; return &amd_f15_PMC3; case 0x004: if (hweight_long(hwc->config & ARCH_PERFMON_EVENTSEL_UMASK) <= 1) break; return &amd_f15_PMC3; case 0x003: case 0x00B: case 0x00D: return &amd_f15_PMC3; } return &amd_f15_PMC53; case AMD_EVENT_LS: case AMD_EVENT_DC: case AMD_EVENT_EX_LS: switch (event_code) { case 0x023: case 0x043: case 0x045: case 0x046: case 0x054: case 0x055: return &amd_f15_PMC20; case 0x02D: return &amd_f15_PMC3; case 0x02E: return &amd_f15_PMC30; case 0x031: if (hweight_long(hwc->config & ARCH_PERFMON_EVENTSEL_UMASK) <= 1) return &amd_f15_PMC20; return &emptyconstraint; case 0x1C0: return &amd_f15_PMC53; default: return &amd_f15_PMC50; } case AMD_EVENT_CU: case AMD_EVENT_IC_DE: case AMD_EVENT_DE: switch (event_code) { case 0x08F: case 0x187: case 0x188: return &amd_f15_PMC0; case 0x0DB ... 0x0DF: case 0x1D6: case 0x1D8: return &amd_f15_PMC50; default: return &amd_f15_PMC20; } case AMD_EVENT_NB: /* moved to uncore.c */ return &emptyconstraint; default: return &emptyconstraint; } } static struct event_constraint pair_constraint; static struct event_constraint * amd_get_event_constraints_f17h(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (amd_is_pair_event_code(hwc)) return &pair_constraint; return &unconstrained; } static void amd_put_event_constraints_f17h(struct cpu_hw_events *cpuc, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (is_counter_pair(hwc)) --cpuc->n_pair; } /* * Because of the way BRS operates with an inactive and active phases, and * the link to one counter, it is not possible to have two events using BRS * scheduled at the same time. There would be an issue with enforcing the * period of each one and given that the BRS saturates, it would not be possible * to guarantee correlated content for all events. Therefore, in situations * where multiple events want to use BRS, the kernel enforces mutual exclusion. * Exclusion is enforced by chosing only one counter for events using BRS. * The event scheduling logic will then automatically multiplex the * events and ensure that at most one event is actively using BRS. * * The BRS counter could be any counter, but there is no constraint on Fam19h, * therefore all counters are equal and thus we pick the first one: PMC0 */ static struct event_constraint amd_fam19h_brs_cntr0_constraint = EVENT_CONSTRAINT(0, 0x1, AMD64_RAW_EVENT_MASK); static struct event_constraint amd_fam19h_brs_pair_cntr0_constraint = __EVENT_CONSTRAINT(0, 0x1, AMD64_RAW_EVENT_MASK, 1, 0, PERF_X86_EVENT_PAIR); static struct event_constraint * amd_get_event_constraints_f19h(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; bool has_brs = has_amd_brs(hwc); /* * In case BRS is used with an event requiring a counter pair, * the kernel allows it but only on counter 0 & 1 to enforce * multiplexing requiring to protect BRS in case of multiple * BRS users */ if (amd_is_pair_event_code(hwc)) { return has_brs ? &amd_fam19h_brs_pair_cntr0_constraint : &pair_constraint; } if (has_brs) return &amd_fam19h_brs_cntr0_constraint; return &unconstrained; } static ssize_t amd_event_sysfs_show(char *page, u64 config) { u64 event = (config & ARCH_PERFMON_EVENTSEL_EVENT) | (config & AMD64_EVENTSEL_EVENT) >> 24; return x86_event_sysfs_show(page, config, event); } static void amd_pmu_limit_period(struct perf_event *event, s64 *left) { /* * Decrease period by the depth of the BRS feature to get the last N * taken branches and approximate the desired period */ if (has_branch_stack(event) && *left > x86_pmu.lbr_nr) *left -= x86_pmu.lbr_nr; } static __initconst const struct x86_pmu amd_pmu = { .name = "AMD", .handle_irq = amd_pmu_handle_irq, .disable_all = amd_pmu_disable_all, .enable_all = amd_pmu_enable_all, .enable = amd_pmu_enable_event, .disable = amd_pmu_disable_event, .hw_config = amd_pmu_hw_config, .schedule_events = x86_schedule_events, .eventsel = MSR_K7_EVNTSEL0, .perfctr = MSR_K7_PERFCTR0, .addr_offset = amd_pmu_addr_offset, .event_map = amd_pmu_event_map, .max_events = ARRAY_SIZE(amd_perfmon_event_map), .num_counters = AMD64_NUM_COUNTERS, .add = amd_pmu_add_event, .del = amd_pmu_del_event, .cntval_bits = 48, .cntval_mask = (1ULL << 48) - 1, .apic = 1, /* use highest bit to detect overflow */ .max_period = (1ULL << 47) - 1, .get_event_constraints = amd_get_event_constraints, .put_event_constraints = amd_put_event_constraints, .format_attrs = amd_format_attr, .events_sysfs_show = amd_event_sysfs_show, .cpu_prepare = amd_pmu_cpu_prepare, .cpu_starting = amd_pmu_cpu_starting, .cpu_dead = amd_pmu_cpu_dead, .amd_nb_constraints = 1, }; static ssize_t branches_show(struct device *cdev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", x86_pmu.lbr_nr); } static DEVICE_ATTR_RO(branches); static struct attribute *amd_pmu_branches_attrs[] = { &dev_attr_branches.attr, NULL, }; static umode_t amd_branches_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return x86_pmu.lbr_nr ? attr->mode : 0; } static struct attribute_group group_caps_amd_branches = { .name = "caps", .attrs = amd_pmu_branches_attrs, .is_visible = amd_branches_is_visible, }; #ifdef CONFIG_PERF_EVENTS_AMD_BRS EVENT_ATTR_STR(branch-brs, amd_branch_brs, "event=" __stringify(AMD_FAM19H_BRS_EVENT)"\n"); static struct attribute *amd_brs_events_attrs[] = { EVENT_PTR(amd_branch_brs), NULL, }; static umode_t amd_brs_is_visible(struct kobject *kobj, struct attribute *attr, int i) { return static_cpu_has(X86_FEATURE_BRS) && x86_pmu.lbr_nr ? attr->mode : 0; } static struct attribute_group group_events_amd_brs = { .name = "events", .attrs = amd_brs_events_attrs, .is_visible = amd_brs_is_visible, }; #endif /* CONFIG_PERF_EVENTS_AMD_BRS */ static const struct attribute_group *amd_attr_update[] = { &group_caps_amd_branches, #ifdef CONFIG_PERF_EVENTS_AMD_BRS &group_events_amd_brs, #endif NULL, }; static int __init amd_core_pmu_init(void) { union cpuid_0x80000022_ebx ebx; u64 even_ctr_mask = 0ULL; int i; if (!boot_cpu_has(X86_FEATURE_PERFCTR_CORE)) return 0; /* Avoid calculating the value each time in the NMI handler */ perf_nmi_window = msecs_to_jiffies(100); /* * If core performance counter extensions exists, we must use * MSR_F15H_PERF_CTL/MSR_F15H_PERF_CTR msrs. See also * amd_pmu_addr_offset(). */ x86_pmu.eventsel = MSR_F15H_PERF_CTL; x86_pmu.perfctr = MSR_F15H_PERF_CTR; x86_pmu.num_counters = AMD64_NUM_COUNTERS_CORE; /* Check for Performance Monitoring v2 support */ if (boot_cpu_has(X86_FEATURE_PERFMON_V2)) { ebx.full = cpuid_ebx(EXT_PERFMON_DEBUG_FEATURES); /* Update PMU version for later usage */ x86_pmu.version = 2; /* Find the number of available Core PMCs */ x86_pmu.num_counters = ebx.split.num_core_pmc; amd_pmu_global_cntr_mask = (1ULL << x86_pmu.num_counters) - 1; /* Update PMC handling functions */ x86_pmu.enable_all = amd_pmu_v2_enable_all; x86_pmu.disable_all = amd_pmu_v2_disable_all; x86_pmu.enable = amd_pmu_v2_enable_event; x86_pmu.handle_irq = amd_pmu_v2_handle_irq; static_call_update(amd_pmu_test_overflow, amd_pmu_test_overflow_status); } /* * AMD Core perfctr has separate MSRs for the NB events, see * the amd/uncore.c driver. */ x86_pmu.amd_nb_constraints = 0; if (boot_cpu_data.x86 == 0x15) { pr_cont("Fam15h "); x86_pmu.get_event_constraints = amd_get_event_constraints_f15h; } if (boot_cpu_data.x86 >= 0x17) { pr_cont("Fam17h+ "); /* * Family 17h and compatibles have constraints for Large * Increment per Cycle events: they may only be assigned an * even numbered counter that has a consecutive adjacent odd * numbered counter following it. */ for (i = 0; i < x86_pmu.num_counters - 1; i += 2) even_ctr_mask |= BIT_ULL(i); pair_constraint = (struct event_constraint) __EVENT_CONSTRAINT(0, even_ctr_mask, 0, x86_pmu.num_counters / 2, 0, PERF_X86_EVENT_PAIR); x86_pmu.get_event_constraints = amd_get_event_constraints_f17h; x86_pmu.put_event_constraints = amd_put_event_constraints_f17h; x86_pmu.perf_ctr_pair_en = AMD_MERGE_EVENT_ENABLE; x86_pmu.flags |= PMU_FL_PAIR; } /* LBR and BRS are mutually exclusive features */ if (!amd_pmu_lbr_init()) { /* LBR requires flushing on context switch */ x86_pmu.sched_task = amd_pmu_lbr_sched_task; static_call_update(amd_pmu_branch_hw_config, amd_pmu_lbr_hw_config); static_call_update(amd_pmu_branch_reset, amd_pmu_lbr_reset); static_call_update(amd_pmu_branch_add, amd_pmu_lbr_add); static_call_update(amd_pmu_branch_del, amd_pmu_lbr_del); } else if (!amd_brs_init()) { /* * BRS requires special event constraints and flushing on ctxsw. */ x86_pmu.get_event_constraints = amd_get_event_constraints_f19h; x86_pmu.sched_task = amd_pmu_brs_sched_task; x86_pmu.limit_period = amd_pmu_limit_period; static_call_update(amd_pmu_branch_hw_config, amd_brs_hw_config); static_call_update(amd_pmu_branch_reset, amd_brs_reset); static_call_update(amd_pmu_branch_add, amd_pmu_brs_add); static_call_update(amd_pmu_branch_del, amd_pmu_brs_del); /* * put_event_constraints callback same as Fam17h, set above */ /* branch sampling must be stopped when entering low power */ amd_brs_lopwr_init(); } x86_pmu.attr_update = amd_attr_update; pr_cont("core perfctr, "); return 0; } __init int amd_pmu_init(void) { int ret; /* Performance-monitoring supported from K7 and later: */ if (boot_cpu_data.x86 < 6) return -ENODEV; x86_pmu = amd_pmu; ret = amd_core_pmu_init(); if (ret) return ret; if (num_possible_cpus() == 1) { /* * No point in allocating data structures to serialize * against other CPUs, when there is only the one CPU. */ x86_pmu.amd_nb_constraints = 0; } if (boot_cpu_data.x86 >= 0x17) memcpy(hw_cache_event_ids, amd_hw_cache_event_ids_f17h, sizeof(hw_cache_event_ids)); else memcpy(hw_cache_event_ids, amd_hw_cache_event_ids, sizeof(hw_cache_event_ids)); return 0; } static inline void amd_pmu_reload_virt(void) { if (x86_pmu.version >= 2) { /* * Clear global enable bits, reprogram the PERF_CTL * registers with updated perf_ctr_virt_mask and then * set global enable bits once again */ amd_pmu_v2_disable_all(); amd_pmu_enable_all(0); amd_pmu_v2_enable_all(0); return; } amd_pmu_disable_all(); amd_pmu_enable_all(0); } void amd_pmu_enable_virt(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); cpuc->perf_ctr_virt_mask = 0; /* Reload all events */ amd_pmu_reload_virt(); } EXPORT_SYMBOL_GPL(amd_pmu_enable_virt); void amd_pmu_disable_virt(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* * We only mask out the Host-only bit so that host-only counting works * when SVM is disabled. If someone sets up a guest-only counter when * SVM is disabled the Guest-only bits still gets set and the counter * will not count anything. */ cpuc->perf_ctr_virt_mask = AMD64_EVENTSEL_HOSTONLY; /* Reload all events */ amd_pmu_reload_virt(); } EXPORT_SYMBOL_GPL(amd_pmu_disable_virt);
linux-master
arch/x86/events/amd/core.c
// SPDX-License-Identifier: GPL-2.0-only /* * Performance events - AMD Processor Power Reporting Mechanism * * Copyright (C) 2016 Advanced Micro Devices, Inc. * * Author: Huang Rui <[email protected]> */ #include <linux/module.h> #include <linux/slab.h> #include <linux/perf_event.h> #include <asm/cpu_device_id.h> #include "../perf_event.h" /* Event code: LSB 8 bits, passed in attr->config any other bit is reserved. */ #define AMD_POWER_EVENT_MASK 0xFFULL /* * Accumulated power status counters. */ #define AMD_POWER_EVENTSEL_PKG 1 /* * The ratio of compute unit power accumulator sample period to the * PTSC period. */ static unsigned int cpu_pwr_sample_ratio; /* Maximum accumulated power of a compute unit. */ static u64 max_cu_acc_power; static struct pmu pmu_class; /* * Accumulated power represents the sum of each compute unit's (CU) power * consumption. On any core of each CU we read the total accumulated power from * MSR_F15H_CU_PWR_ACCUMULATOR. cpu_mask represents CPU bit map of all cores * which are picked to measure the power for the CUs they belong to. */ static cpumask_t cpu_mask; static void event_update(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 prev_pwr_acc, new_pwr_acc, prev_ptsc, new_ptsc; u64 delta, tdelta; prev_pwr_acc = hwc->pwr_acc; prev_ptsc = hwc->ptsc; rdmsrl(MSR_F15H_CU_PWR_ACCUMULATOR, new_pwr_acc); rdmsrl(MSR_F15H_PTSC, new_ptsc); /* * Calculate the CU power consumption over a time period, the unit of * final value (delta) is micro-Watts. Then add it to the event count. */ if (new_pwr_acc < prev_pwr_acc) { delta = max_cu_acc_power + new_pwr_acc; delta -= prev_pwr_acc; } else delta = new_pwr_acc - prev_pwr_acc; delta *= cpu_pwr_sample_ratio * 1000; tdelta = new_ptsc - prev_ptsc; do_div(delta, tdelta); local64_add(delta, &event->count); } static void __pmu_event_start(struct perf_event *event) { if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED))) return; event->hw.state = 0; rdmsrl(MSR_F15H_PTSC, event->hw.ptsc); rdmsrl(MSR_F15H_CU_PWR_ACCUMULATOR, event->hw.pwr_acc); } static void pmu_event_start(struct perf_event *event, int mode) { __pmu_event_start(event); } static void pmu_event_stop(struct perf_event *event, int mode) { struct hw_perf_event *hwc = &event->hw; /* Mark event as deactivated and stopped. */ if (!(hwc->state & PERF_HES_STOPPED)) hwc->state |= PERF_HES_STOPPED; /* Check if software counter update is necessary. */ if ((mode & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) { /* * Drain the remaining delta count out of an event * that we are disabling: */ event_update(event); hwc->state |= PERF_HES_UPTODATE; } } static int pmu_event_add(struct perf_event *event, int mode) { struct hw_perf_event *hwc = &event->hw; hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED; if (mode & PERF_EF_START) __pmu_event_start(event); return 0; } static void pmu_event_del(struct perf_event *event, int flags) { pmu_event_stop(event, PERF_EF_UPDATE); } static int pmu_event_init(struct perf_event *event) { u64 cfg = event->attr.config & AMD_POWER_EVENT_MASK; /* Only look at AMD power events. */ if (event->attr.type != pmu_class.type) return -ENOENT; /* Unsupported modes and filters. */ if (event->attr.sample_period) return -EINVAL; if (cfg != AMD_POWER_EVENTSEL_PKG) return -EINVAL; return 0; } static void pmu_event_read(struct perf_event *event) { event_update(event); } static ssize_t get_attr_cpumask(struct device *dev, struct device_attribute *attr, char *buf) { return cpumap_print_to_pagebuf(true, buf, &cpu_mask); } static DEVICE_ATTR(cpumask, S_IRUGO, get_attr_cpumask, NULL); static struct attribute *pmu_attrs[] = { &dev_attr_cpumask.attr, NULL, }; static struct attribute_group pmu_attr_group = { .attrs = pmu_attrs, }; /* * Currently it only supports to report the power of each * processor/package. */ EVENT_ATTR_STR(power-pkg, power_pkg, "event=0x01"); EVENT_ATTR_STR(power-pkg.unit, power_pkg_unit, "mWatts"); /* Convert the count from micro-Watts to milli-Watts. */ EVENT_ATTR_STR(power-pkg.scale, power_pkg_scale, "1.000000e-3"); static struct attribute *events_attr[] = { EVENT_PTR(power_pkg), EVENT_PTR(power_pkg_unit), EVENT_PTR(power_pkg_scale), NULL, }; static struct attribute_group pmu_events_group = { .name = "events", .attrs = events_attr, }; PMU_FORMAT_ATTR(event, "config:0-7"); static struct attribute *formats_attr[] = { &format_attr_event.attr, NULL, }; static struct attribute_group pmu_format_group = { .name = "format", .attrs = formats_attr, }; static const struct attribute_group *attr_groups[] = { &pmu_attr_group, &pmu_format_group, &pmu_events_group, NULL, }; static struct pmu pmu_class = { .attr_groups = attr_groups, /* system-wide only */ .task_ctx_nr = perf_invalid_context, .event_init = pmu_event_init, .add = pmu_event_add, .del = pmu_event_del, .start = pmu_event_start, .stop = pmu_event_stop, .read = pmu_event_read, .capabilities = PERF_PMU_CAP_NO_EXCLUDE, .module = THIS_MODULE, }; static int power_cpu_exit(unsigned int cpu) { int target; if (!cpumask_test_and_clear_cpu(cpu, &cpu_mask)) return 0; /* * Find a new CPU on the same compute unit, if was set in cpumask * and still some CPUs on compute unit. Then migrate event and * context to new CPU. */ target = cpumask_any_but(topology_sibling_cpumask(cpu), cpu); if (target < nr_cpumask_bits) { cpumask_set_cpu(target, &cpu_mask); perf_pmu_migrate_context(&pmu_class, cpu, target); } return 0; } static int power_cpu_init(unsigned int cpu) { int target; /* * 1) If any CPU is set at cpu_mask in the same compute unit, do * nothing. * 2) If no CPU is set at cpu_mask in the same compute unit, * set current ONLINE CPU. * * Note: if there is a CPU aside of the new one already in the * sibling mask, then it is also in cpu_mask. */ target = cpumask_any_but(topology_sibling_cpumask(cpu), cpu); if (target >= nr_cpumask_bits) cpumask_set_cpu(cpu, &cpu_mask); return 0; } static const struct x86_cpu_id cpu_match[] = { X86_MATCH_VENDOR_FAM(AMD, 0x15, NULL), {}, }; static int __init amd_power_pmu_init(void) { int ret; if (!x86_match_cpu(cpu_match)) return -ENODEV; if (!boot_cpu_has(X86_FEATURE_ACC_POWER)) return -ENODEV; cpu_pwr_sample_ratio = cpuid_ecx(0x80000007); if (rdmsrl_safe(MSR_F15H_CU_MAX_PWR_ACCUMULATOR, &max_cu_acc_power)) { pr_err("Failed to read max compute unit power accumulator MSR\n"); return -ENODEV; } cpuhp_setup_state(CPUHP_AP_PERF_X86_AMD_POWER_ONLINE, "perf/x86/amd/power:online", power_cpu_init, power_cpu_exit); ret = perf_pmu_register(&pmu_class, "power", -1); if (WARN_ON(ret)) { pr_warn("AMD Power PMU registration failed\n"); return ret; } pr_info("AMD Power PMU detected\n"); return ret; } module_init(amd_power_pmu_init); static void __exit amd_power_pmu_exit(void) { cpuhp_remove_state_nocalls(CPUHP_AP_PERF_X86_AMD_POWER_ONLINE); perf_pmu_unregister(&pmu_class); } module_exit(amd_power_pmu_exit); MODULE_AUTHOR("Huang Rui <[email protected]>"); MODULE_DESCRIPTION("AMD Processor Power Reporting Mechanism"); MODULE_LICENSE("GPL v2");
linux-master
arch/x86/events/amd/power.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2013 Advanced Micro Devices, Inc. * * Author: Steven Kinney <[email protected]> * Author: Suravee Suthikulpanit <[email protected]> * * Perf: amd_iommu - AMD IOMMU Performance Counter PMU implementation */ #define pr_fmt(fmt) "perf/amd_iommu: " fmt #include <linux/perf_event.h> #include <linux/init.h> #include <linux/cpumask.h> #include <linux/slab.h> #include <linux/amd-iommu.h> #include "../perf_event.h" #include "iommu.h" /* iommu pmu conf masks */ #define GET_CSOURCE(x) ((x)->conf & 0xFFULL) #define GET_DEVID(x) (((x)->conf >> 8) & 0xFFFFULL) #define GET_DOMID(x) (((x)->conf >> 24) & 0xFFFFULL) #define GET_PASID(x) (((x)->conf >> 40) & 0xFFFFFULL) /* iommu pmu conf1 masks */ #define GET_DEVID_MASK(x) ((x)->conf1 & 0xFFFFULL) #define GET_DOMID_MASK(x) (((x)->conf1 >> 16) & 0xFFFFULL) #define GET_PASID_MASK(x) (((x)->conf1 >> 32) & 0xFFFFFULL) #define IOMMU_NAME_SIZE 16 struct perf_amd_iommu { struct list_head list; struct pmu pmu; struct amd_iommu *iommu; char name[IOMMU_NAME_SIZE]; u8 max_banks; u8 max_counters; u64 cntr_assign_mask; raw_spinlock_t lock; }; static LIST_HEAD(perf_amd_iommu_list); /*--------------------------------------------- * sysfs format attributes *---------------------------------------------*/ PMU_FORMAT_ATTR(csource, "config:0-7"); PMU_FORMAT_ATTR(devid, "config:8-23"); PMU_FORMAT_ATTR(domid, "config:24-39"); PMU_FORMAT_ATTR(pasid, "config:40-59"); PMU_FORMAT_ATTR(devid_mask, "config1:0-15"); PMU_FORMAT_ATTR(domid_mask, "config1:16-31"); PMU_FORMAT_ATTR(pasid_mask, "config1:32-51"); static struct attribute *iommu_format_attrs[] = { &format_attr_csource.attr, &format_attr_devid.attr, &format_attr_pasid.attr, &format_attr_domid.attr, &format_attr_devid_mask.attr, &format_attr_pasid_mask.attr, &format_attr_domid_mask.attr, NULL, }; static struct attribute_group amd_iommu_format_group = { .name = "format", .attrs = iommu_format_attrs, }; /*--------------------------------------------- * sysfs events attributes *---------------------------------------------*/ static struct attribute_group amd_iommu_events_group = { .name = "events", }; struct amd_iommu_event_desc { struct device_attribute attr; const char *event; }; static ssize_t _iommu_event_show(struct device *dev, struct device_attribute *attr, char *buf) { struct amd_iommu_event_desc *event = container_of(attr, struct amd_iommu_event_desc, attr); return sprintf(buf, "%s\n", event->event); } #define AMD_IOMMU_EVENT_DESC(_name, _event) \ { \ .attr = __ATTR(_name, 0444, _iommu_event_show, NULL), \ .event = _event, \ } static struct amd_iommu_event_desc amd_iommu_v2_event_descs[] = { AMD_IOMMU_EVENT_DESC(mem_pass_untrans, "csource=0x01"), AMD_IOMMU_EVENT_DESC(mem_pass_pretrans, "csource=0x02"), AMD_IOMMU_EVENT_DESC(mem_pass_excl, "csource=0x03"), AMD_IOMMU_EVENT_DESC(mem_target_abort, "csource=0x04"), AMD_IOMMU_EVENT_DESC(mem_trans_total, "csource=0x05"), AMD_IOMMU_EVENT_DESC(mem_iommu_tlb_pte_hit, "csource=0x06"), AMD_IOMMU_EVENT_DESC(mem_iommu_tlb_pte_mis, "csource=0x07"), AMD_IOMMU_EVENT_DESC(mem_iommu_tlb_pde_hit, "csource=0x08"), AMD_IOMMU_EVENT_DESC(mem_iommu_tlb_pde_mis, "csource=0x09"), AMD_IOMMU_EVENT_DESC(mem_dte_hit, "csource=0x0a"), AMD_IOMMU_EVENT_DESC(mem_dte_mis, "csource=0x0b"), AMD_IOMMU_EVENT_DESC(page_tbl_read_tot, "csource=0x0c"), AMD_IOMMU_EVENT_DESC(page_tbl_read_nst, "csource=0x0d"), AMD_IOMMU_EVENT_DESC(page_tbl_read_gst, "csource=0x0e"), AMD_IOMMU_EVENT_DESC(int_dte_hit, "csource=0x0f"), AMD_IOMMU_EVENT_DESC(int_dte_mis, "csource=0x10"), AMD_IOMMU_EVENT_DESC(cmd_processed, "csource=0x11"), AMD_IOMMU_EVENT_DESC(cmd_processed_inv, "csource=0x12"), AMD_IOMMU_EVENT_DESC(tlb_inv, "csource=0x13"), AMD_IOMMU_EVENT_DESC(ign_rd_wr_mmio_1ff8h, "csource=0x14"), AMD_IOMMU_EVENT_DESC(vapic_int_non_guest, "csource=0x15"), AMD_IOMMU_EVENT_DESC(vapic_int_guest, "csource=0x16"), AMD_IOMMU_EVENT_DESC(smi_recv, "csource=0x17"), AMD_IOMMU_EVENT_DESC(smi_blk, "csource=0x18"), { /* end: all zeroes */ }, }; /*--------------------------------------------- * sysfs cpumask attributes *---------------------------------------------*/ static cpumask_t iommu_cpumask; static ssize_t _iommu_cpumask_show(struct device *dev, struct device_attribute *attr, char *buf) { return cpumap_print_to_pagebuf(true, buf, &iommu_cpumask); } static DEVICE_ATTR(cpumask, S_IRUGO, _iommu_cpumask_show, NULL); static struct attribute *iommu_cpumask_attrs[] = { &dev_attr_cpumask.attr, NULL, }; static struct attribute_group amd_iommu_cpumask_group = { .attrs = iommu_cpumask_attrs, }; /*---------------------------------------------*/ static int get_next_avail_iommu_bnk_cntr(struct perf_event *event) { struct perf_amd_iommu *piommu = container_of(event->pmu, struct perf_amd_iommu, pmu); int max_cntrs = piommu->max_counters; int max_banks = piommu->max_banks; u32 shift, bank, cntr; unsigned long flags; int retval; raw_spin_lock_irqsave(&piommu->lock, flags); for (bank = 0; bank < max_banks; bank++) { for (cntr = 0; cntr < max_cntrs; cntr++) { shift = bank + (bank*3) + cntr; if (piommu->cntr_assign_mask & BIT_ULL(shift)) { continue; } else { piommu->cntr_assign_mask |= BIT_ULL(shift); event->hw.iommu_bank = bank; event->hw.iommu_cntr = cntr; retval = 0; goto out; } } } retval = -ENOSPC; out: raw_spin_unlock_irqrestore(&piommu->lock, flags); return retval; } static int clear_avail_iommu_bnk_cntr(struct perf_amd_iommu *perf_iommu, u8 bank, u8 cntr) { unsigned long flags; int max_banks, max_cntrs; int shift = 0; max_banks = perf_iommu->max_banks; max_cntrs = perf_iommu->max_counters; if ((bank > max_banks) || (cntr > max_cntrs)) return -EINVAL; shift = bank + cntr + (bank*3); raw_spin_lock_irqsave(&perf_iommu->lock, flags); perf_iommu->cntr_assign_mask &= ~(1ULL<<shift); raw_spin_unlock_irqrestore(&perf_iommu->lock, flags); return 0; } static int perf_iommu_event_init(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; /* test the event attr type check for PMU enumeration */ if (event->attr.type != event->pmu->type) return -ENOENT; /* * IOMMU counters are shared across all cores. * Therefore, it does not support per-process mode. * Also, it does not support event sampling mode. */ if (is_sampling_event(event) || event->attach_state & PERF_ATTACH_TASK) return -EINVAL; if (event->cpu < 0) return -EINVAL; /* update the hw_perf_event struct with the iommu config data */ hwc->conf = event->attr.config; hwc->conf1 = event->attr.config1; return 0; } static inline struct amd_iommu *perf_event_2_iommu(struct perf_event *ev) { return (container_of(ev->pmu, struct perf_amd_iommu, pmu))->iommu; } static void perf_iommu_enable_event(struct perf_event *ev) { struct amd_iommu *iommu = perf_event_2_iommu(ev); struct hw_perf_event *hwc = &ev->hw; u8 bank = hwc->iommu_bank; u8 cntr = hwc->iommu_cntr; u64 reg = 0ULL; reg = GET_CSOURCE(hwc); amd_iommu_pc_set_reg(iommu, bank, cntr, IOMMU_PC_COUNTER_SRC_REG, &reg); reg = GET_DEVID_MASK(hwc); reg = GET_DEVID(hwc) | (reg << 32); if (reg) reg |= BIT(31); amd_iommu_pc_set_reg(iommu, bank, cntr, IOMMU_PC_DEVID_MATCH_REG, &reg); reg = GET_PASID_MASK(hwc); reg = GET_PASID(hwc) | (reg << 32); if (reg) reg |= BIT(31); amd_iommu_pc_set_reg(iommu, bank, cntr, IOMMU_PC_PASID_MATCH_REG, &reg); reg = GET_DOMID_MASK(hwc); reg = GET_DOMID(hwc) | (reg << 32); if (reg) reg |= BIT(31); amd_iommu_pc_set_reg(iommu, bank, cntr, IOMMU_PC_DOMID_MATCH_REG, &reg); } static void perf_iommu_disable_event(struct perf_event *event) { struct amd_iommu *iommu = perf_event_2_iommu(event); struct hw_perf_event *hwc = &event->hw; u64 reg = 0ULL; amd_iommu_pc_set_reg(iommu, hwc->iommu_bank, hwc->iommu_cntr, IOMMU_PC_COUNTER_SRC_REG, &reg); } static void perf_iommu_start(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; if (WARN_ON_ONCE(!(hwc->state & PERF_HES_STOPPED))) return; WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE)); hwc->state = 0; /* * To account for power-gating, which prevents write to * the counter, we need to enable the counter * before setting up counter register. */ perf_iommu_enable_event(event); if (flags & PERF_EF_RELOAD) { u64 count = 0; struct amd_iommu *iommu = perf_event_2_iommu(event); /* * Since the IOMMU PMU only support counting mode, * the counter always start with value zero. */ amd_iommu_pc_set_reg(iommu, hwc->iommu_bank, hwc->iommu_cntr, IOMMU_PC_COUNTER_REG, &count); } perf_event_update_userpage(event); } static void perf_iommu_read(struct perf_event *event) { u64 count; struct hw_perf_event *hwc = &event->hw; struct amd_iommu *iommu = perf_event_2_iommu(event); if (amd_iommu_pc_get_reg(iommu, hwc->iommu_bank, hwc->iommu_cntr, IOMMU_PC_COUNTER_REG, &count)) return; /* IOMMU pc counter register is only 48 bits */ count &= GENMASK_ULL(47, 0); /* * Since the counter always start with value zero, * simply just accumulate the count for the event. */ local64_add(count, &event->count); } static void perf_iommu_stop(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; if (hwc->state & PERF_HES_UPTODATE) return; /* * To account for power-gating, in which reading the counter would * return zero, we need to read the register before disabling. */ perf_iommu_read(event); hwc->state |= PERF_HES_UPTODATE; perf_iommu_disable_event(event); WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED); hwc->state |= PERF_HES_STOPPED; } static int perf_iommu_add(struct perf_event *event, int flags) { int retval; event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED; /* request an iommu bank/counter */ retval = get_next_avail_iommu_bnk_cntr(event); if (retval) return retval; if (flags & PERF_EF_START) perf_iommu_start(event, PERF_EF_RELOAD); return 0; } static void perf_iommu_del(struct perf_event *event, int flags) { struct hw_perf_event *hwc = &event->hw; struct perf_amd_iommu *perf_iommu = container_of(event->pmu, struct perf_amd_iommu, pmu); perf_iommu_stop(event, PERF_EF_UPDATE); /* clear the assigned iommu bank/counter */ clear_avail_iommu_bnk_cntr(perf_iommu, hwc->iommu_bank, hwc->iommu_cntr); perf_event_update_userpage(event); } static __init int _init_events_attrs(void) { int i = 0, j; struct attribute **attrs; while (amd_iommu_v2_event_descs[i].attr.attr.name) i++; attrs = kcalloc(i + 1, sizeof(*attrs), GFP_KERNEL); if (!attrs) return -ENOMEM; for (j = 0; j < i; j++) attrs[j] = &amd_iommu_v2_event_descs[j].attr.attr; amd_iommu_events_group.attrs = attrs; return 0; } static const struct attribute_group *amd_iommu_attr_groups[] = { &amd_iommu_format_group, &amd_iommu_cpumask_group, &amd_iommu_events_group, NULL, }; static const struct pmu iommu_pmu __initconst = { .event_init = perf_iommu_event_init, .add = perf_iommu_add, .del = perf_iommu_del, .start = perf_iommu_start, .stop = perf_iommu_stop, .read = perf_iommu_read, .task_ctx_nr = perf_invalid_context, .attr_groups = amd_iommu_attr_groups, .capabilities = PERF_PMU_CAP_NO_EXCLUDE, }; static __init int init_one_iommu(unsigned int idx) { struct perf_amd_iommu *perf_iommu; int ret; perf_iommu = kzalloc(sizeof(struct perf_amd_iommu), GFP_KERNEL); if (!perf_iommu) return -ENOMEM; raw_spin_lock_init(&perf_iommu->lock); perf_iommu->pmu = iommu_pmu; perf_iommu->iommu = get_amd_iommu(idx); perf_iommu->max_banks = amd_iommu_pc_get_max_banks(idx); perf_iommu->max_counters = amd_iommu_pc_get_max_counters(idx); if (!perf_iommu->iommu || !perf_iommu->max_banks || !perf_iommu->max_counters) { kfree(perf_iommu); return -EINVAL; } snprintf(perf_iommu->name, IOMMU_NAME_SIZE, "amd_iommu_%u", idx); ret = perf_pmu_register(&perf_iommu->pmu, perf_iommu->name, -1); if (!ret) { pr_info("Detected AMD IOMMU #%d (%d banks, %d counters/bank).\n", idx, perf_iommu->max_banks, perf_iommu->max_counters); list_add_tail(&perf_iommu->list, &perf_amd_iommu_list); } else { pr_warn("Error initializing IOMMU %d.\n", idx); kfree(perf_iommu); } return ret; } static __init int amd_iommu_pc_init(void) { unsigned int i, cnt = 0; int ret; /* Make sure the IOMMU PC resource is available */ if (!amd_iommu_pc_supported()) return -ENODEV; ret = _init_events_attrs(); if (ret) return ret; /* * An IOMMU PMU is specific to an IOMMU, and can function independently. * So we go through all IOMMUs and ignore the one that fails init * unless all IOMMU are failing. */ for (i = 0; i < amd_iommu_get_num_iommus(); i++) { ret = init_one_iommu(i); if (!ret) cnt++; } if (!cnt) { kfree(amd_iommu_events_group.attrs); return -ENODEV; } /* Init cpumask attributes to only core 0 */ cpumask_set_cpu(0, &iommu_cpumask); return 0; } device_initcall(amd_iommu_pc_init);
linux-master
arch/x86/events/amd/iommu.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/perf_event.h> #include <asm/perf_event.h> #include "../perf_event.h" /* LBR Branch Select valid bits */ #define LBR_SELECT_MASK 0x1ff /* * LBR Branch Select filter bits which when set, ensures that the * corresponding type of branches are not recorded */ #define LBR_SELECT_KERNEL 0 /* Branches ending in CPL = 0 */ #define LBR_SELECT_USER 1 /* Branches ending in CPL > 0 */ #define LBR_SELECT_JCC 2 /* Conditional branches */ #define LBR_SELECT_CALL_NEAR_REL 3 /* Near relative calls */ #define LBR_SELECT_CALL_NEAR_IND 4 /* Indirect relative calls */ #define LBR_SELECT_RET_NEAR 5 /* Near returns */ #define LBR_SELECT_JMP_NEAR_IND 6 /* Near indirect jumps (excl. calls and returns) */ #define LBR_SELECT_JMP_NEAR_REL 7 /* Near relative jumps (excl. calls) */ #define LBR_SELECT_FAR_BRANCH 8 /* Far branches */ #define LBR_KERNEL BIT(LBR_SELECT_KERNEL) #define LBR_USER BIT(LBR_SELECT_USER) #define LBR_JCC BIT(LBR_SELECT_JCC) #define LBR_REL_CALL BIT(LBR_SELECT_CALL_NEAR_REL) #define LBR_IND_CALL BIT(LBR_SELECT_CALL_NEAR_IND) #define LBR_RETURN BIT(LBR_SELECT_RET_NEAR) #define LBR_REL_JMP BIT(LBR_SELECT_JMP_NEAR_REL) #define LBR_IND_JMP BIT(LBR_SELECT_JMP_NEAR_IND) #define LBR_FAR BIT(LBR_SELECT_FAR_BRANCH) #define LBR_NOT_SUPP -1 /* unsupported filter */ #define LBR_IGNORE 0 #define LBR_ANY \ (LBR_JCC | LBR_REL_CALL | LBR_IND_CALL | LBR_RETURN | \ LBR_REL_JMP | LBR_IND_JMP | LBR_FAR) struct branch_entry { union { struct { u64 ip:58; u64 ip_sign_ext:5; u64 mispredict:1; } split; u64 full; } from; union { struct { u64 ip:58; u64 ip_sign_ext:3; u64 reserved:1; u64 spec:1; u64 valid:1; } split; u64 full; } to; }; static __always_inline void amd_pmu_lbr_set_from(unsigned int idx, u64 val) { wrmsrl(MSR_AMD_SAMP_BR_FROM + idx * 2, val); } static __always_inline void amd_pmu_lbr_set_to(unsigned int idx, u64 val) { wrmsrl(MSR_AMD_SAMP_BR_FROM + idx * 2 + 1, val); } static __always_inline u64 amd_pmu_lbr_get_from(unsigned int idx) { u64 val; rdmsrl(MSR_AMD_SAMP_BR_FROM + idx * 2, val); return val; } static __always_inline u64 amd_pmu_lbr_get_to(unsigned int idx) { u64 val; rdmsrl(MSR_AMD_SAMP_BR_FROM + idx * 2 + 1, val); return val; } static __always_inline u64 sign_ext_branch_ip(u64 ip) { u32 shift = 64 - boot_cpu_data.x86_virt_bits; return (u64)(((s64)ip << shift) >> shift); } static void amd_pmu_lbr_filter(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int br_sel = cpuc->br_sel, offset, type, i, j; bool compress = false; bool fused_only = false; u64 from, to; /* If sampling all branches, there is nothing to filter */ if (((br_sel & X86_BR_ALL) == X86_BR_ALL) && ((br_sel & X86_BR_TYPE_SAVE) != X86_BR_TYPE_SAVE)) fused_only = true; for (i = 0; i < cpuc->lbr_stack.nr; i++) { from = cpuc->lbr_entries[i].from; to = cpuc->lbr_entries[i].to; type = branch_type_fused(from, to, 0, &offset); /* * Adjust the branch from address in case of instruction * fusion where it points to an instruction preceding the * actual branch */ if (offset) { cpuc->lbr_entries[i].from += offset; if (fused_only) continue; } /* If type does not correspond, then discard */ if (type == X86_BR_NONE || (br_sel & type) != type) { cpuc->lbr_entries[i].from = 0; /* mark invalid */ compress = true; } if ((br_sel & X86_BR_TYPE_SAVE) == X86_BR_TYPE_SAVE) cpuc->lbr_entries[i].type = common_branch_type(type); } if (!compress) return; /* Remove all invalid entries */ for (i = 0; i < cpuc->lbr_stack.nr; ) { if (!cpuc->lbr_entries[i].from) { j = i; while (++j < cpuc->lbr_stack.nr) cpuc->lbr_entries[j - 1] = cpuc->lbr_entries[j]; cpuc->lbr_stack.nr--; if (!cpuc->lbr_entries[i].from) continue; } i++; } } static const int lbr_spec_map[PERF_BR_SPEC_MAX] = { PERF_BR_SPEC_NA, PERF_BR_SPEC_WRONG_PATH, PERF_BR_NON_SPEC_CORRECT_PATH, PERF_BR_SPEC_CORRECT_PATH, }; void amd_pmu_lbr_read(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_branch_entry *br = cpuc->lbr_entries; struct branch_entry entry; int out = 0, idx, i; if (!cpuc->lbr_users) return; for (i = 0; i < x86_pmu.lbr_nr; i++) { entry.from.full = amd_pmu_lbr_get_from(i); entry.to.full = amd_pmu_lbr_get_to(i); /* * Check if a branch has been logged; if valid = 0, spec = 0 * then no branch was recorded */ if (!entry.to.split.valid && !entry.to.split.spec) continue; perf_clear_branch_entry_bitfields(br + out); br[out].from = sign_ext_branch_ip(entry.from.split.ip); br[out].to = sign_ext_branch_ip(entry.to.split.ip); br[out].mispred = entry.from.split.mispredict; br[out].predicted = !br[out].mispred; /* * Set branch speculation information using the status of * the valid and spec bits. * * When valid = 0, spec = 0, no branch was recorded and the * entry is discarded as seen above. * * When valid = 0, spec = 1, the recorded branch was * speculative but took the wrong path. * * When valid = 1, spec = 0, the recorded branch was * non-speculative but took the correct path. * * When valid = 1, spec = 1, the recorded branch was * speculative and took the correct path */ idx = (entry.to.split.valid << 1) | entry.to.split.spec; br[out].spec = lbr_spec_map[idx]; out++; } cpuc->lbr_stack.nr = out; /* * Internal register renaming always ensures that LBR From[0] and * LBR To[0] always represent the TOS */ cpuc->lbr_stack.hw_idx = 0; /* Perform further software filtering */ amd_pmu_lbr_filter(); } static const int lbr_select_map[PERF_SAMPLE_BRANCH_MAX_SHIFT] = { [PERF_SAMPLE_BRANCH_USER_SHIFT] = LBR_USER, [PERF_SAMPLE_BRANCH_KERNEL_SHIFT] = LBR_KERNEL, [PERF_SAMPLE_BRANCH_HV_SHIFT] = LBR_IGNORE, [PERF_SAMPLE_BRANCH_ANY_SHIFT] = LBR_ANY, [PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT] = LBR_REL_CALL | LBR_IND_CALL | LBR_FAR, [PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT] = LBR_RETURN | LBR_FAR, [PERF_SAMPLE_BRANCH_IND_CALL_SHIFT] = LBR_IND_CALL, [PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT] = LBR_NOT_SUPP, [PERF_SAMPLE_BRANCH_IN_TX_SHIFT] = LBR_NOT_SUPP, [PERF_SAMPLE_BRANCH_NO_TX_SHIFT] = LBR_NOT_SUPP, [PERF_SAMPLE_BRANCH_COND_SHIFT] = LBR_JCC, [PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT] = LBR_NOT_SUPP, [PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT] = LBR_IND_JMP, [PERF_SAMPLE_BRANCH_CALL_SHIFT] = LBR_REL_CALL, [PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT] = LBR_NOT_SUPP, [PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT] = LBR_NOT_SUPP, }; static int amd_pmu_lbr_setup_filter(struct perf_event *event) { struct hw_perf_event_extra *reg = &event->hw.branch_reg; u64 br_type = event->attr.branch_sample_type; u64 mask = 0, v; int i; /* No LBR support */ if (!x86_pmu.lbr_nr) return -EOPNOTSUPP; if (br_type & PERF_SAMPLE_BRANCH_USER) mask |= X86_BR_USER; if (br_type & PERF_SAMPLE_BRANCH_KERNEL) mask |= X86_BR_KERNEL; /* Ignore BRANCH_HV here */ if (br_type & PERF_SAMPLE_BRANCH_ANY) mask |= X86_BR_ANY; if (br_type & PERF_SAMPLE_BRANCH_ANY_CALL) mask |= X86_BR_ANY_CALL; if (br_type & PERF_SAMPLE_BRANCH_ANY_RETURN) mask |= X86_BR_RET | X86_BR_IRET | X86_BR_SYSRET; if (br_type & PERF_SAMPLE_BRANCH_IND_CALL) mask |= X86_BR_IND_CALL; if (br_type & PERF_SAMPLE_BRANCH_COND) mask |= X86_BR_JCC; if (br_type & PERF_SAMPLE_BRANCH_IND_JUMP) mask |= X86_BR_IND_JMP; if (br_type & PERF_SAMPLE_BRANCH_CALL) mask |= X86_BR_CALL | X86_BR_ZERO_CALL; if (br_type & PERF_SAMPLE_BRANCH_TYPE_SAVE) mask |= X86_BR_TYPE_SAVE; reg->reg = mask; mask = 0; for (i = 0; i < PERF_SAMPLE_BRANCH_MAX_SHIFT; i++) { if (!(br_type & BIT_ULL(i))) continue; v = lbr_select_map[i]; if (v == LBR_NOT_SUPP) return -EOPNOTSUPP; if (v != LBR_IGNORE) mask |= v; } /* Filter bits operate in suppress mode */ reg->config = mask ^ LBR_SELECT_MASK; return 0; } int amd_pmu_lbr_hw_config(struct perf_event *event) { int ret = 0; /* LBR is not recommended in counting mode */ if (!is_sampling_event(event)) return -EINVAL; ret = amd_pmu_lbr_setup_filter(event); if (!ret) event->attach_state |= PERF_ATTACH_SCHED_CB; return ret; } void amd_pmu_lbr_reset(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int i; if (!x86_pmu.lbr_nr) return; /* Reset all branch records individually */ for (i = 0; i < x86_pmu.lbr_nr; i++) { amd_pmu_lbr_set_from(i, 0); amd_pmu_lbr_set_to(i, 0); } cpuc->last_task_ctx = NULL; cpuc->last_log_id = 0; wrmsrl(MSR_AMD64_LBR_SELECT, 0); } void amd_pmu_lbr_add(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event_extra *reg = &event->hw.branch_reg; if (!x86_pmu.lbr_nr) return; if (has_branch_stack(event)) { cpuc->lbr_select = 1; cpuc->lbr_sel->config = reg->config; cpuc->br_sel = reg->reg; } perf_sched_cb_inc(event->pmu); if (!cpuc->lbr_users++ && !event->total_time_running) amd_pmu_lbr_reset(); } void amd_pmu_lbr_del(struct perf_event *event) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); if (!x86_pmu.lbr_nr) return; if (has_branch_stack(event)) cpuc->lbr_select = 0; cpuc->lbr_users--; WARN_ON_ONCE(cpuc->lbr_users < 0); perf_sched_cb_dec(event->pmu); } void amd_pmu_lbr_sched_task(struct perf_event_pmu_context *pmu_ctx, bool sched_in) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); /* * A context switch can flip the address space and LBR entries are * not tagged with an identifier. Hence, branches cannot be resolved * from the old address space and the LBR records should be wiped. */ if (cpuc->lbr_users && sched_in) amd_pmu_lbr_reset(); } void amd_pmu_lbr_enable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); u64 lbr_select, dbg_ctl, dbg_extn_cfg; if (!cpuc->lbr_users || !x86_pmu.lbr_nr) return; /* Set hardware branch filter */ if (cpuc->lbr_select) { lbr_select = cpuc->lbr_sel->config & LBR_SELECT_MASK; wrmsrl(MSR_AMD64_LBR_SELECT, lbr_select); } rdmsrl(MSR_IA32_DEBUGCTLMSR, dbg_ctl); rdmsrl(MSR_AMD_DBG_EXTN_CFG, dbg_extn_cfg); wrmsrl(MSR_IA32_DEBUGCTLMSR, dbg_ctl | DEBUGCTLMSR_FREEZE_LBRS_ON_PMI); wrmsrl(MSR_AMD_DBG_EXTN_CFG, dbg_extn_cfg | DBG_EXTN_CFG_LBRV2EN); } void amd_pmu_lbr_disable_all(void) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); u64 dbg_ctl, dbg_extn_cfg; if (!cpuc->lbr_users || !x86_pmu.lbr_nr) return; rdmsrl(MSR_AMD_DBG_EXTN_CFG, dbg_extn_cfg); rdmsrl(MSR_IA32_DEBUGCTLMSR, dbg_ctl); wrmsrl(MSR_AMD_DBG_EXTN_CFG, dbg_extn_cfg & ~DBG_EXTN_CFG_LBRV2EN); wrmsrl(MSR_IA32_DEBUGCTLMSR, dbg_ctl & ~DEBUGCTLMSR_FREEZE_LBRS_ON_PMI); } __init int amd_pmu_lbr_init(void) { union cpuid_0x80000022_ebx ebx; if (x86_pmu.version < 2 || !boot_cpu_has(X86_FEATURE_AMD_LBR_V2)) return -EOPNOTSUPP; /* Set number of entries */ ebx.full = cpuid_ebx(EXT_PERFMON_DEBUG_FEATURES); x86_pmu.lbr_nr = ebx.split.lbr_v2_stack_sz; pr_cont("%d-deep LBR, ", x86_pmu.lbr_nr); return 0; }
linux-master
arch/x86/events/amd/lbr.c
// SPDX-License-Identifier: GPL-2.0-only /* * Zhaoxin PMU; like Intel Architectural PerfMon-v2 */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/stddef.h> #include <linux/types.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/export.h> #include <linux/nmi.h> #include <asm/cpufeature.h> #include <asm/hardirq.h> #include <asm/apic.h> #include "../perf_event.h" /* * Zhaoxin PerfMon, used on zxc and later. */ static u64 zx_pmon_event_map[PERF_COUNT_HW_MAX] __read_mostly = { [PERF_COUNT_HW_CPU_CYCLES] = 0x0082, [PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0, [PERF_COUNT_HW_CACHE_REFERENCES] = 0x0515, [PERF_COUNT_HW_CACHE_MISSES] = 0x051a, [PERF_COUNT_HW_BUS_CYCLES] = 0x0083, }; static struct event_constraint zxc_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x0082, 1), /* unhalted core clock cycles */ EVENT_CONSTRAINT_END }; static struct event_constraint zxd_event_constraints[] __read_mostly = { FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* retired instructions */ FIXED_EVENT_CONSTRAINT(0x0082, 1), /* unhalted core clock cycles */ FIXED_EVENT_CONSTRAINT(0x0083, 2), /* unhalted bus clock cycles */ EVENT_CONSTRAINT_END }; static __initconst const u64 zxd_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0042, [C(RESULT_MISS)] = 0x0538, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x0043, [C(RESULT_MISS)] = 0x0562, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0300, [C(RESULT_MISS)] = 0x0301, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x030a, [C(RESULT_MISS)] = 0x030b, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0042, [C(RESULT_MISS)] = 0x052c, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x0043, [C(RESULT_MISS)] = 0x0530, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0564, [C(RESULT_MISS)] = 0x0565, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x00c0, [C(RESULT_MISS)] = 0x0534, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0700, [C(RESULT_MISS)] = 0x0709, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(NODE)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, }; static __initconst const u64 zxe_hw_cache_event_ids [PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0568, [C(RESULT_MISS)] = 0x054b, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x0669, [C(RESULT_MISS)] = 0x0562, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0300, [C(RESULT_MISS)] = 0x0301, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x030a, [C(RESULT_MISS)] = 0x030b, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0, [C(RESULT_MISS)] = 0x0, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0568, [C(RESULT_MISS)] = 0x052c, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x0669, [C(RESULT_MISS)] = 0x0530, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = 0x0564, [C(RESULT_MISS)] = 0x0565, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x00c0, [C(RESULT_MISS)] = 0x0534, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x0028, [C(RESULT_MISS)] = 0x0029, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, [C(NODE)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = -1, [C(RESULT_MISS)] = -1, }, }, }; static void zhaoxin_pmu_disable_all(void) { wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0); } static void zhaoxin_pmu_enable_all(int added) { wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, x86_pmu.intel_ctrl); } static inline u64 zhaoxin_pmu_get_status(void) { u64 status; rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status); return status; } static inline void zhaoxin_pmu_ack_status(u64 ack) { wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack); } static inline void zxc_pmu_ack_status(u64 ack) { /* * ZXC needs global control enabled in order to clear status bits. */ zhaoxin_pmu_enable_all(0); zhaoxin_pmu_ack_status(ack); zhaoxin_pmu_disable_all(); } static void zhaoxin_pmu_disable_fixed(struct hw_perf_event *hwc) { int idx = hwc->idx - INTEL_PMC_IDX_FIXED; u64 ctrl_val, mask; mask = 0xfULL << (idx * 4); rdmsrl(hwc->config_base, ctrl_val); ctrl_val &= ~mask; wrmsrl(hwc->config_base, ctrl_val); } static void zhaoxin_pmu_disable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) { zhaoxin_pmu_disable_fixed(hwc); return; } x86_pmu_disable_event(event); } static void zhaoxin_pmu_enable_fixed(struct hw_perf_event *hwc) { int idx = hwc->idx - INTEL_PMC_IDX_FIXED; u64 ctrl_val, bits, mask; /* * Enable IRQ generation (0x8), * and enable ring-3 counting (0x2) and ring-0 counting (0x1) * if requested: */ bits = 0x8ULL; if (hwc->config & ARCH_PERFMON_EVENTSEL_USR) bits |= 0x2; if (hwc->config & ARCH_PERFMON_EVENTSEL_OS) bits |= 0x1; bits <<= (idx * 4); mask = 0xfULL << (idx * 4); rdmsrl(hwc->config_base, ctrl_val); ctrl_val &= ~mask; ctrl_val |= bits; wrmsrl(hwc->config_base, ctrl_val); } static void zhaoxin_pmu_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) { zhaoxin_pmu_enable_fixed(hwc); return; } __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE); } /* * This handler is triggered by the local APIC, so the APIC IRQ handling * rules apply: */ static int zhaoxin_pmu_handle_irq(struct pt_regs *regs) { struct perf_sample_data data; struct cpu_hw_events *cpuc; int handled = 0; u64 status; int bit; cpuc = this_cpu_ptr(&cpu_hw_events); apic_write(APIC_LVTPC, APIC_DM_NMI); zhaoxin_pmu_disable_all(); status = zhaoxin_pmu_get_status(); if (!status) goto done; again: if (x86_pmu.enabled_ack) zxc_pmu_ack_status(status); else zhaoxin_pmu_ack_status(status); inc_irq_stat(apic_perf_irqs); /* * CondChgd bit 63 doesn't mean any overflow status. Ignore * and clear the bit. */ if (__test_and_clear_bit(63, (unsigned long *)&status)) { if (!status) goto done; } for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) { struct perf_event *event = cpuc->events[bit]; handled++; if (!test_bit(bit, cpuc->active_mask)) continue; x86_perf_event_update(event); perf_sample_data_init(&data, 0, event->hw.last_period); if (!x86_perf_event_set_period(event)) continue; if (perf_event_overflow(event, &data, regs)) x86_pmu_stop(event, 0); } /* * Repeat if there is more work to be done: */ status = zhaoxin_pmu_get_status(); if (status) goto again; done: zhaoxin_pmu_enable_all(0); return handled; } static u64 zhaoxin_pmu_event_map(int hw_event) { return zx_pmon_event_map[hw_event]; } static struct event_constraint * zhaoxin_get_event_constraints(struct cpu_hw_events *cpuc, int idx, struct perf_event *event) { struct event_constraint *c; if (x86_pmu.event_constraints) { for_each_event_constraint(c, x86_pmu.event_constraints) { if ((event->hw.config & c->cmask) == c->code) return c; } } return &unconstrained; } PMU_FORMAT_ATTR(event, "config:0-7"); PMU_FORMAT_ATTR(umask, "config:8-15"); PMU_FORMAT_ATTR(edge, "config:18"); PMU_FORMAT_ATTR(inv, "config:23"); PMU_FORMAT_ATTR(cmask, "config:24-31"); static struct attribute *zx_arch_formats_attr[] = { &format_attr_event.attr, &format_attr_umask.attr, &format_attr_edge.attr, &format_attr_inv.attr, &format_attr_cmask.attr, NULL, }; static ssize_t zhaoxin_event_sysfs_show(char *page, u64 config) { u64 event = (config & ARCH_PERFMON_EVENTSEL_EVENT); return x86_event_sysfs_show(page, config, event); } static const struct x86_pmu zhaoxin_pmu __initconst = { .name = "zhaoxin", .handle_irq = zhaoxin_pmu_handle_irq, .disable_all = zhaoxin_pmu_disable_all, .enable_all = zhaoxin_pmu_enable_all, .enable = zhaoxin_pmu_enable_event, .disable = zhaoxin_pmu_disable_event, .hw_config = x86_pmu_hw_config, .schedule_events = x86_schedule_events, .eventsel = MSR_ARCH_PERFMON_EVENTSEL0, .perfctr = MSR_ARCH_PERFMON_PERFCTR0, .event_map = zhaoxin_pmu_event_map, .max_events = ARRAY_SIZE(zx_pmon_event_map), .apic = 1, /* * For zxd/zxe, read/write operation for PMCx MSR is 48 bits. */ .max_period = (1ULL << 47) - 1, .get_event_constraints = zhaoxin_get_event_constraints, .format_attrs = zx_arch_formats_attr, .events_sysfs_show = zhaoxin_event_sysfs_show, }; static const struct { int id; char *name; } zx_arch_events_map[] __initconst = { { PERF_COUNT_HW_CPU_CYCLES, "cpu cycles" }, { PERF_COUNT_HW_INSTRUCTIONS, "instructions" }, { PERF_COUNT_HW_BUS_CYCLES, "bus cycles" }, { PERF_COUNT_HW_CACHE_REFERENCES, "cache references" }, { PERF_COUNT_HW_CACHE_MISSES, "cache misses" }, { PERF_COUNT_HW_BRANCH_INSTRUCTIONS, "branch instructions" }, { PERF_COUNT_HW_BRANCH_MISSES, "branch misses" }, }; static __init void zhaoxin_arch_events_quirk(void) { int bit; /* disable event that reported as not present by cpuid */ for_each_set_bit(bit, x86_pmu.events_mask, ARRAY_SIZE(zx_arch_events_map)) { zx_pmon_event_map[zx_arch_events_map[bit].id] = 0; pr_warn("CPUID marked event: \'%s\' unavailable\n", zx_arch_events_map[bit].name); } } __init int zhaoxin_pmu_init(void) { union cpuid10_edx edx; union cpuid10_eax eax; union cpuid10_ebx ebx; struct event_constraint *c; unsigned int unused; int version; pr_info("Welcome to zhaoxin pmu!\n"); /* * Check whether the Architectural PerfMon supports * hw_event or not. */ cpuid(10, &eax.full, &ebx.full, &unused, &edx.full); if (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT - 1) return -ENODEV; version = eax.split.version_id; if (version != 2) return -ENODEV; x86_pmu = zhaoxin_pmu; pr_info("Version check pass!\n"); x86_pmu.version = version; x86_pmu.num_counters = eax.split.num_counters; x86_pmu.cntval_bits = eax.split.bit_width; x86_pmu.cntval_mask = (1ULL << eax.split.bit_width) - 1; x86_pmu.events_maskl = ebx.full; x86_pmu.events_mask_len = eax.split.mask_length; x86_pmu.num_counters_fixed = edx.split.num_counters_fixed; x86_add_quirk(zhaoxin_arch_events_quirk); switch (boot_cpu_data.x86) { case 0x06: /* * Support Zhaoxin CPU from ZXC series, exclude Nano series through FMS. * Nano FMS: Family=6, Model=F, Stepping=[0-A][C-D] * ZXC FMS: Family=6, Model=F, Stepping=E-F OR Family=6, Model=0x19, Stepping=0-3 */ if ((boot_cpu_data.x86_model == 0x0f && boot_cpu_data.x86_stepping >= 0x0e) || boot_cpu_data.x86_model == 0x19) { x86_pmu.max_period = x86_pmu.cntval_mask >> 1; /* Clearing status works only if the global control is enable on zxc. */ x86_pmu.enabled_ack = 1; x86_pmu.event_constraints = zxc_event_constraints; zx_pmon_event_map[PERF_COUNT_HW_INSTRUCTIONS] = 0; zx_pmon_event_map[PERF_COUNT_HW_CACHE_REFERENCES] = 0; zx_pmon_event_map[PERF_COUNT_HW_CACHE_MISSES] = 0; zx_pmon_event_map[PERF_COUNT_HW_BUS_CYCLES] = 0; pr_cont("ZXC events, "); break; } return -ENODEV; case 0x07: zx_pmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = X86_CONFIG(.event = 0x01, .umask = 0x01, .inv = 0x01, .cmask = 0x01); zx_pmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = X86_CONFIG(.event = 0x0f, .umask = 0x04, .inv = 0, .cmask = 0); switch (boot_cpu_data.x86_model) { case 0x1b: memcpy(hw_cache_event_ids, zxd_hw_cache_event_ids, sizeof(hw_cache_event_ids)); x86_pmu.event_constraints = zxd_event_constraints; zx_pmon_event_map[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x0700; zx_pmon_event_map[PERF_COUNT_HW_BRANCH_MISSES] = 0x0709; pr_cont("ZXD events, "); break; case 0x3b: memcpy(hw_cache_event_ids, zxe_hw_cache_event_ids, sizeof(hw_cache_event_ids)); x86_pmu.event_constraints = zxd_event_constraints; zx_pmon_event_map[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x0028; zx_pmon_event_map[PERF_COUNT_HW_BRANCH_MISSES] = 0x0029; pr_cont("ZXE events, "); break; default: return -ENODEV; } break; default: return -ENODEV; } x86_pmu.intel_ctrl = (1 << (x86_pmu.num_counters)) - 1; x86_pmu.intel_ctrl |= ((1LL << x86_pmu.num_counters_fixed)-1) << INTEL_PMC_IDX_FIXED; if (x86_pmu.event_constraints) { for_each_event_constraint(c, x86_pmu.event_constraints) { c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1; c->weight += x86_pmu.num_counters; } } return 0; }
linux-master
arch/x86/events/zhaoxin/core.c
// SPDX-License-Identifier: GPL-2.0 /* * Dynamic function tracing support. * * Copyright (C) 2007-2008 Steven Rostedt <[email protected]> * * Thanks goes to Ingo Molnar, for suggesting the idea. * Mathieu Desnoyers, for suggesting postponing the modifications. * Arjan van de Ven, for keeping me straight, and explaining to me * the dangers of modifying code on the run. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/spinlock.h> #include <linux/hardirq.h> #include <linux/uaccess.h> #include <linux/ftrace.h> #include <linux/percpu.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/list.h> #include <linux/module.h> #include <linux/memory.h> #include <linux/vmalloc.h> #include <linux/set_memory.h> #include <trace/syscall.h> #include <asm/kprobes.h> #include <asm/ftrace.h> #include <asm/nops.h> #include <asm/text-patching.h> #ifdef CONFIG_DYNAMIC_FTRACE static int ftrace_poke_late = 0; void ftrace_arch_code_modify_prepare(void) __acquires(&text_mutex) { /* * Need to grab text_mutex to prevent a race from module loading * and live kernel patching from changing the text permissions while * ftrace has it set to "read/write". */ mutex_lock(&text_mutex); ftrace_poke_late = 1; } void ftrace_arch_code_modify_post_process(void) __releases(&text_mutex) { /* * ftrace_make_{call,nop}() may be called during * module load, and we need to finish the text_poke_queue() * that they do, here. */ text_poke_finish(); ftrace_poke_late = 0; mutex_unlock(&text_mutex); } static const char *ftrace_nop_replace(void) { return x86_nops[5]; } static const char *ftrace_call_replace(unsigned long ip, unsigned long addr) { /* * No need to translate into a callthunk. The trampoline does * the depth accounting itself. */ return text_gen_insn(CALL_INSN_OPCODE, (void *)ip, (void *)addr); } static int ftrace_verify_code(unsigned long ip, const char *old_code) { char cur_code[MCOUNT_INSN_SIZE]; /* * Note: * We are paranoid about modifying text, as if a bug was to happen, it * could cause us to read or write to someplace that could cause harm. * Carefully read and modify the code with probe_kernel_*(), and make * sure what we read is what we expected it to be before modifying it. */ /* read the text we want to modify */ if (copy_from_kernel_nofault(cur_code, (void *)ip, MCOUNT_INSN_SIZE)) { WARN_ON(1); return -EFAULT; } /* Make sure it is what we expect it to be */ if (memcmp(cur_code, old_code, MCOUNT_INSN_SIZE) != 0) { ftrace_expected = old_code; WARN_ON(1); return -EINVAL; } return 0; } /* * Marked __ref because it calls text_poke_early() which is .init.text. That is * ok because that call will happen early, during boot, when .init sections are * still present. */ static int __ref ftrace_modify_code_direct(unsigned long ip, const char *old_code, const char *new_code) { int ret = ftrace_verify_code(ip, old_code); if (ret) return ret; /* replace the text with the new text */ if (ftrace_poke_late) text_poke_queue((void *)ip, new_code, MCOUNT_INSN_SIZE, NULL); else text_poke_early((void *)ip, new_code, MCOUNT_INSN_SIZE); return 0; } int ftrace_make_nop(struct module *mod, struct dyn_ftrace *rec, unsigned long addr) { unsigned long ip = rec->ip; const char *new, *old; old = ftrace_call_replace(ip, addr); new = ftrace_nop_replace(); /* * On boot up, and when modules are loaded, the MCOUNT_ADDR * is converted to a nop, and will never become MCOUNT_ADDR * again. This code is either running before SMP (on boot up) * or before the code will ever be executed (module load). * We do not want to use the breakpoint version in this case, * just modify the code directly. */ if (addr == MCOUNT_ADDR) return ftrace_modify_code_direct(ip, old, new); /* * x86 overrides ftrace_replace_code -- this function will never be used * in this case. */ WARN_ONCE(1, "invalid use of ftrace_make_nop"); return -EINVAL; } int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr) { unsigned long ip = rec->ip; const char *new, *old; old = ftrace_nop_replace(); new = ftrace_call_replace(ip, addr); /* Should only be called when module is loaded */ return ftrace_modify_code_direct(rec->ip, old, new); } /* * Should never be called: * As it is only called by __ftrace_replace_code() which is called by * ftrace_replace_code() that x86 overrides, and by ftrace_update_code() * which is called to turn mcount into nops or nops into function calls * but not to convert a function from not using regs to one that uses * regs, which ftrace_modify_call() is for. */ int ftrace_modify_call(struct dyn_ftrace *rec, unsigned long old_addr, unsigned long addr) { WARN_ON(1); return -EINVAL; } int ftrace_update_ftrace_func(ftrace_func_t func) { unsigned long ip; const char *new; ip = (unsigned long)(&ftrace_call); new = ftrace_call_replace(ip, (unsigned long)func); text_poke_bp((void *)ip, new, MCOUNT_INSN_SIZE, NULL); ip = (unsigned long)(&ftrace_regs_call); new = ftrace_call_replace(ip, (unsigned long)func); text_poke_bp((void *)ip, new, MCOUNT_INSN_SIZE, NULL); return 0; } void ftrace_replace_code(int enable) { struct ftrace_rec_iter *iter; struct dyn_ftrace *rec; const char *new, *old; int ret; for_ftrace_rec_iter(iter) { rec = ftrace_rec_iter_record(iter); switch (ftrace_test_record(rec, enable)) { case FTRACE_UPDATE_IGNORE: default: continue; case FTRACE_UPDATE_MAKE_CALL: old = ftrace_nop_replace(); break; case FTRACE_UPDATE_MODIFY_CALL: case FTRACE_UPDATE_MAKE_NOP: old = ftrace_call_replace(rec->ip, ftrace_get_addr_curr(rec)); break; } ret = ftrace_verify_code(rec->ip, old); if (ret) { ftrace_expected = old; ftrace_bug(ret, rec); ftrace_expected = NULL; return; } } for_ftrace_rec_iter(iter) { rec = ftrace_rec_iter_record(iter); switch (ftrace_test_record(rec, enable)) { case FTRACE_UPDATE_IGNORE: default: continue; case FTRACE_UPDATE_MAKE_CALL: case FTRACE_UPDATE_MODIFY_CALL: new = ftrace_call_replace(rec->ip, ftrace_get_addr_new(rec)); break; case FTRACE_UPDATE_MAKE_NOP: new = ftrace_nop_replace(); break; } text_poke_queue((void *)rec->ip, new, MCOUNT_INSN_SIZE, NULL); ftrace_update_record(rec, enable); } text_poke_finish(); } void arch_ftrace_update_code(int command) { ftrace_modify_all_code(command); } /* Currently only x86_64 supports dynamic trampolines */ #ifdef CONFIG_X86_64 #ifdef CONFIG_MODULES #include <linux/moduleloader.h> /* Module allocation simplifies allocating memory for code */ static inline void *alloc_tramp(unsigned long size) { return module_alloc(size); } static inline void tramp_free(void *tramp) { module_memfree(tramp); } #else /* Trampolines can only be created if modules are supported */ static inline void *alloc_tramp(unsigned long size) { return NULL; } static inline void tramp_free(void *tramp) { } #endif /* Defined as markers to the end of the ftrace default trampolines */ extern void ftrace_regs_caller_end(void); extern void ftrace_caller_end(void); extern void ftrace_caller_op_ptr(void); extern void ftrace_regs_caller_op_ptr(void); extern void ftrace_regs_caller_jmp(void); /* movq function_trace_op(%rip), %rdx */ /* 0x48 0x8b 0x15 <offset-to-ftrace_trace_op (4 bytes)> */ #define OP_REF_SIZE 7 /* * The ftrace_ops is passed to the function callback. Since the * trampoline only services a single ftrace_ops, we can pass in * that ops directly. * * The ftrace_op_code_union is used to create a pointer to the * ftrace_ops that will be passed to the callback function. */ union ftrace_op_code_union { char code[OP_REF_SIZE]; struct { char op[3]; int offset; } __attribute__((packed)); }; #define RET_SIZE (IS_ENABLED(CONFIG_RETPOLINE) ? 5 : 1 + IS_ENABLED(CONFIG_SLS)) static unsigned long create_trampoline(struct ftrace_ops *ops, unsigned int *tramp_size) { unsigned long start_offset; unsigned long end_offset; unsigned long op_offset; unsigned long call_offset; unsigned long jmp_offset; unsigned long offset; unsigned long npages; unsigned long size; unsigned long *ptr; void *trampoline; void *ip, *dest; /* 48 8b 15 <offset> is movq <offset>(%rip), %rdx */ unsigned const char op_ref[] = { 0x48, 0x8b, 0x15 }; unsigned const char retq[] = { RET_INSN_OPCODE, INT3_INSN_OPCODE }; union ftrace_op_code_union op_ptr; int ret; if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) { start_offset = (unsigned long)ftrace_regs_caller; end_offset = (unsigned long)ftrace_regs_caller_end; op_offset = (unsigned long)ftrace_regs_caller_op_ptr; call_offset = (unsigned long)ftrace_regs_call; jmp_offset = (unsigned long)ftrace_regs_caller_jmp; } else { start_offset = (unsigned long)ftrace_caller; end_offset = (unsigned long)ftrace_caller_end; op_offset = (unsigned long)ftrace_caller_op_ptr; call_offset = (unsigned long)ftrace_call; jmp_offset = 0; } size = end_offset - start_offset; /* * Allocate enough size to store the ftrace_caller code, * the iret , as well as the address of the ftrace_ops this * trampoline is used for. */ trampoline = alloc_tramp(size + RET_SIZE + sizeof(void *)); if (!trampoline) return 0; *tramp_size = size + RET_SIZE + sizeof(void *); npages = DIV_ROUND_UP(*tramp_size, PAGE_SIZE); /* Copy ftrace_caller onto the trampoline memory */ ret = copy_from_kernel_nofault(trampoline, (void *)start_offset, size); if (WARN_ON(ret < 0)) goto fail; ip = trampoline + size; if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) __text_gen_insn(ip, JMP32_INSN_OPCODE, ip, x86_return_thunk, JMP32_INSN_SIZE); else memcpy(ip, retq, sizeof(retq)); /* No need to test direct calls on created trampolines */ if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) { /* NOP the jnz 1f; but make sure it's a 2 byte jnz */ ip = trampoline + (jmp_offset - start_offset); if (WARN_ON(*(char *)ip != 0x75)) goto fail; ret = copy_from_kernel_nofault(ip, x86_nops[2], 2); if (ret < 0) goto fail; } /* * The address of the ftrace_ops that is used for this trampoline * is stored at the end of the trampoline. This will be used to * load the third parameter for the callback. Basically, that * location at the end of the trampoline takes the place of * the global function_trace_op variable. */ ptr = (unsigned long *)(trampoline + size + RET_SIZE); *ptr = (unsigned long)ops; op_offset -= start_offset; memcpy(&op_ptr, trampoline + op_offset, OP_REF_SIZE); /* Are we pointing to the reference? */ if (WARN_ON(memcmp(op_ptr.op, op_ref, 3) != 0)) goto fail; /* Load the contents of ptr into the callback parameter */ offset = (unsigned long)ptr; offset -= (unsigned long)trampoline + op_offset + OP_REF_SIZE; op_ptr.offset = offset; /* put in the new offset to the ftrace_ops */ memcpy(trampoline + op_offset, &op_ptr, OP_REF_SIZE); /* put in the call to the function */ mutex_lock(&text_mutex); call_offset -= start_offset; /* * No need to translate into a callthunk. The trampoline does * the depth accounting before the call already. */ dest = ftrace_ops_get_func(ops); memcpy(trampoline + call_offset, text_gen_insn(CALL_INSN_OPCODE, trampoline + call_offset, dest), CALL_INSN_SIZE); mutex_unlock(&text_mutex); /* ALLOC_TRAMP flags lets us know we created it */ ops->flags |= FTRACE_OPS_FL_ALLOC_TRAMP; set_memory_rox((unsigned long)trampoline, npages); return (unsigned long)trampoline; fail: tramp_free(trampoline); return 0; } void set_ftrace_ops_ro(void) { struct ftrace_ops *ops; unsigned long start_offset; unsigned long end_offset; unsigned long npages; unsigned long size; do_for_each_ftrace_op(ops, ftrace_ops_list) { if (!(ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP)) continue; if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) { start_offset = (unsigned long)ftrace_regs_caller; end_offset = (unsigned long)ftrace_regs_caller_end; } else { start_offset = (unsigned long)ftrace_caller; end_offset = (unsigned long)ftrace_caller_end; } size = end_offset - start_offset; size = size + RET_SIZE + sizeof(void *); npages = DIV_ROUND_UP(size, PAGE_SIZE); set_memory_ro((unsigned long)ops->trampoline, npages); } while_for_each_ftrace_op(ops); } static unsigned long calc_trampoline_call_offset(bool save_regs) { unsigned long start_offset; unsigned long call_offset; if (save_regs) { start_offset = (unsigned long)ftrace_regs_caller; call_offset = (unsigned long)ftrace_regs_call; } else { start_offset = (unsigned long)ftrace_caller; call_offset = (unsigned long)ftrace_call; } return call_offset - start_offset; } void arch_ftrace_update_trampoline(struct ftrace_ops *ops) { ftrace_func_t func; unsigned long offset; unsigned long ip; unsigned int size; const char *new; if (!ops->trampoline) { ops->trampoline = create_trampoline(ops, &size); if (!ops->trampoline) return; ops->trampoline_size = size; return; } /* * The ftrace_ops caller may set up its own trampoline. * In such a case, this code must not modify it. */ if (!(ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP)) return; offset = calc_trampoline_call_offset(ops->flags & FTRACE_OPS_FL_SAVE_REGS); ip = ops->trampoline + offset; func = ftrace_ops_get_func(ops); mutex_lock(&text_mutex); /* Do a safe modify in case the trampoline is executing */ new = ftrace_call_replace(ip, (unsigned long)func); text_poke_bp((void *)ip, new, MCOUNT_INSN_SIZE, NULL); mutex_unlock(&text_mutex); } /* Return the address of the function the trampoline calls */ static void *addr_from_call(void *ptr) { union text_poke_insn call; int ret; ret = copy_from_kernel_nofault(&call, ptr, CALL_INSN_SIZE); if (WARN_ON_ONCE(ret < 0)) return NULL; /* Make sure this is a call */ if (WARN_ON_ONCE(call.opcode != CALL_INSN_OPCODE)) { pr_warn("Expected E8, got %x\n", call.opcode); return NULL; } return ptr + CALL_INSN_SIZE + call.disp; } /* * If the ops->trampoline was not allocated, then it probably * has a static trampoline func, or is the ftrace caller itself. */ static void *static_tramp_func(struct ftrace_ops *ops, struct dyn_ftrace *rec) { unsigned long offset; bool save_regs = rec->flags & FTRACE_FL_REGS_EN; void *ptr; if (ops && ops->trampoline) { #if !defined(CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS) && \ defined(CONFIG_FUNCTION_GRAPH_TRACER) /* * We only know about function graph tracer setting as static * trampoline. */ if (ops->trampoline == FTRACE_GRAPH_ADDR) return (void *)prepare_ftrace_return; #endif return NULL; } offset = calc_trampoline_call_offset(save_regs); if (save_regs) ptr = (void *)FTRACE_REGS_ADDR + offset; else ptr = (void *)FTRACE_ADDR + offset; return addr_from_call(ptr); } void *arch_ftrace_trampoline_func(struct ftrace_ops *ops, struct dyn_ftrace *rec) { unsigned long offset; /* If we didn't allocate this trampoline, consider it static */ if (!ops || !(ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP)) return static_tramp_func(ops, rec); offset = calc_trampoline_call_offset(ops->flags & FTRACE_OPS_FL_SAVE_REGS); return addr_from_call((void *)ops->trampoline + offset); } void arch_ftrace_trampoline_free(struct ftrace_ops *ops) { if (!ops || !(ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP)) return; tramp_free((void *)ops->trampoline); ops->trampoline = 0; } #endif /* CONFIG_X86_64 */ #endif /* CONFIG_DYNAMIC_FTRACE */ #ifdef CONFIG_FUNCTION_GRAPH_TRACER #if defined(CONFIG_DYNAMIC_FTRACE) && !defined(CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS) extern void ftrace_graph_call(void); static const char *ftrace_jmp_replace(unsigned long ip, unsigned long addr) { return text_gen_insn(JMP32_INSN_OPCODE, (void *)ip, (void *)addr); } static int ftrace_mod_jmp(unsigned long ip, void *func) { const char *new; new = ftrace_jmp_replace(ip, (unsigned long)func); text_poke_bp((void *)ip, new, MCOUNT_INSN_SIZE, NULL); return 0; } int ftrace_enable_ftrace_graph_caller(void) { unsigned long ip = (unsigned long)(&ftrace_graph_call); return ftrace_mod_jmp(ip, &ftrace_graph_caller); } int ftrace_disable_ftrace_graph_caller(void) { unsigned long ip = (unsigned long)(&ftrace_graph_call); return ftrace_mod_jmp(ip, &ftrace_stub); } #endif /* CONFIG_DYNAMIC_FTRACE && !CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS */ /* * Hook the return address and push it in the stack of return addrs * in current thread info. */ void prepare_ftrace_return(unsigned long ip, unsigned long *parent, unsigned long frame_pointer) { unsigned long return_hooker = (unsigned long)&return_to_handler; int bit; /* * When resuming from suspend-to-ram, this function can be indirectly * called from early CPU startup code while the CPU is in real mode, * which would fail miserably. Make sure the stack pointer is a * virtual address. * * This check isn't as accurate as virt_addr_valid(), but it should be * good enough for this purpose, and it's fast. */ if (unlikely((long)__builtin_frame_address(0) >= 0)) return; if (unlikely(ftrace_graph_is_dead())) return; if (unlikely(atomic_read(&current->tracing_graph_pause))) return; bit = ftrace_test_recursion_trylock(ip, *parent); if (bit < 0) return; if (!function_graph_enter(*parent, ip, frame_pointer, parent)) *parent = return_hooker; ftrace_test_recursion_unlock(bit); } #ifdef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS void ftrace_graph_func(unsigned long ip, unsigned long parent_ip, struct ftrace_ops *op, struct ftrace_regs *fregs) { struct pt_regs *regs = &fregs->regs; unsigned long *stack = (unsigned long *)kernel_stack_pointer(regs); prepare_ftrace_return(ip, (unsigned long *)stack, 0); } #endif #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
linux-master
arch/x86/kernel/ftrace.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs */ #include <linux/sched/debug.h> #include <linux/kallsyms.h> #include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/hardirq.h> #include <linux/kdebug.h> #include <linux/export.h> #include <linux/ptrace.h> #include <linux/kexec.h> #include <linux/sysfs.h> #include <linux/bug.h> #include <linux/nmi.h> #include <asm/stacktrace.h> const char *stack_type_name(enum stack_type type) { if (type == STACK_TYPE_IRQ) return "IRQ"; if (type == STACK_TYPE_SOFTIRQ) return "SOFTIRQ"; if (type == STACK_TYPE_ENTRY) return "ENTRY_TRAMPOLINE"; if (type == STACK_TYPE_EXCEPTION) return "#DF"; return NULL; } static bool in_hardirq_stack(unsigned long *stack, struct stack_info *info) { unsigned long *begin = (unsigned long *)this_cpu_read(pcpu_hot.hardirq_stack_ptr); unsigned long *end = begin + (THREAD_SIZE / sizeof(long)); /* * This is a software stack, so 'end' can be a valid stack pointer. * It just means the stack is empty. */ if (stack < begin || stack > end) return false; info->type = STACK_TYPE_IRQ; info->begin = begin; info->end = end; /* * See irq_32.c -- the next stack pointer is stored at the beginning of * the stack. */ info->next_sp = (unsigned long *)*begin; return true; } static bool in_softirq_stack(unsigned long *stack, struct stack_info *info) { unsigned long *begin = (unsigned long *)this_cpu_read(pcpu_hot.softirq_stack_ptr); unsigned long *end = begin + (THREAD_SIZE / sizeof(long)); /* * This is a software stack, so 'end' can be a valid stack pointer. * It just means the stack is empty. */ if (stack < begin || stack > end) return false; info->type = STACK_TYPE_SOFTIRQ; info->begin = begin; info->end = end; /* * The next stack pointer is stored at the beginning of the stack. * See irq_32.c. */ info->next_sp = (unsigned long *)*begin; return true; } static bool in_doublefault_stack(unsigned long *stack, struct stack_info *info) { struct cpu_entry_area *cea = get_cpu_entry_area(raw_smp_processor_id()); struct doublefault_stack *ss = &cea->doublefault_stack; void *begin = ss->stack; void *end = begin + sizeof(ss->stack); if ((void *)stack < begin || (void *)stack >= end) return false; info->type = STACK_TYPE_EXCEPTION; info->begin = begin; info->end = end; info->next_sp = (unsigned long *)this_cpu_read(cpu_tss_rw.x86_tss.sp); return true; } int get_stack_info(unsigned long *stack, struct task_struct *task, struct stack_info *info, unsigned long *visit_mask) { if (!stack) goto unknown; task = task ? : current; if (in_task_stack(stack, task, info)) goto recursion_check; if (task != current) goto unknown; if (in_entry_stack(stack, info)) goto recursion_check; if (in_hardirq_stack(stack, info)) goto recursion_check; if (in_softirq_stack(stack, info)) goto recursion_check; if (in_doublefault_stack(stack, info)) goto recursion_check; goto unknown; recursion_check: /* * Make sure we don't iterate through any given stack more than once. * If it comes up a second time then there's something wrong going on: * just break out and report an unknown stack type. */ if (visit_mask) { if (*visit_mask & (1UL << info->type)) { printk_deferred_once(KERN_WARNING "WARNING: stack recursion on stack type %d\n", info->type); goto unknown; } *visit_mask |= 1UL << info->type; } return 0; unknown: info->type = STACK_TYPE_UNKNOWN; return -EINVAL; }
linux-master
arch/x86/kernel/dumpstack_32.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 1991, 1992 Linus Torvalds * * 1997-11-28 Modified for POSIX.1b signals by Richard Henderson * 2000-06-20 Pentium III FXSR, SSE support by Gareth Hughes * 2000-12-* x86-64 compatibility mode signal handling by Andi Kleen */ #include <linux/sched.h> #include <linux/sched/task_stack.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/wait.h> #include <linux/unistd.h> #include <linux/stddef.h> #include <linux/personality.h> #include <linux/compat.h> #include <linux/binfmts.h> #include <linux/syscalls.h> #include <asm/ucontext.h> #include <linux/uaccess.h> #include <asm/fpu/signal.h> #include <asm/ptrace.h> #include <asm/user32.h> #include <uapi/asm/sigcontext.h> #include <asm/proto.h> #include <asm/vdso.h> #include <asm/sigframe.h> #include <asm/sighandling.h> #include <asm/smap.h> #include <asm/gsseg.h> #ifdef CONFIG_IA32_EMULATION #include <asm/ia32_unistd.h> static inline void reload_segments(struct sigcontext_32 *sc) { unsigned int cur; savesegment(gs, cur); if ((sc->gs | 0x03) != cur) load_gs_index(sc->gs | 0x03); savesegment(fs, cur); if ((sc->fs | 0x03) != cur) loadsegment(fs, sc->fs | 0x03); savesegment(ds, cur); if ((sc->ds | 0x03) != cur) loadsegment(ds, sc->ds | 0x03); savesegment(es, cur); if ((sc->es | 0x03) != cur) loadsegment(es, sc->es | 0x03); } #define sigset32_t compat_sigset_t #define siginfo32_t compat_siginfo_t #define restore_altstack32 compat_restore_altstack #define unsafe_save_altstack32 unsafe_compat_save_altstack #else #define sigset32_t sigset_t #define siginfo32_t siginfo_t #define __NR_ia32_sigreturn __NR_sigreturn #define __NR_ia32_rt_sigreturn __NR_rt_sigreturn #define restore_altstack32 restore_altstack #define unsafe_save_altstack32 unsafe_save_altstack #define __copy_siginfo_to_user32 copy_siginfo_to_user #endif /* * Do a signal return; undo the signal stack. */ static bool ia32_restore_sigcontext(struct pt_regs *regs, struct sigcontext_32 __user *usc) { struct sigcontext_32 sc; /* Always make any pending restarted system calls return -EINTR */ current->restart_block.fn = do_no_restart_syscall; if (unlikely(copy_from_user(&sc, usc, sizeof(sc)))) return false; /* Get only the ia32 registers. */ regs->bx = sc.bx; regs->cx = sc.cx; regs->dx = sc.dx; regs->si = sc.si; regs->di = sc.di; regs->bp = sc.bp; regs->ax = sc.ax; regs->sp = sc.sp; regs->ip = sc.ip; /* Get CS/SS and force CPL3 */ regs->cs = sc.cs | 0x03; regs->ss = sc.ss | 0x03; regs->flags = (regs->flags & ~FIX_EFLAGS) | (sc.flags & FIX_EFLAGS); /* disable syscall checks */ regs->orig_ax = -1; #ifdef CONFIG_IA32_EMULATION /* * Reload fs and gs if they have changed in the signal * handler. This does not handle long fs/gs base changes in * the handler, but does not clobber them at least in the * normal case. */ reload_segments(&sc); #else loadsegment(gs, sc.gs); regs->fs = sc.fs; regs->es = sc.es; regs->ds = sc.ds; #endif return fpu__restore_sig(compat_ptr(sc.fpstate), 1); } SYSCALL32_DEFINE0(sigreturn) { struct pt_regs *regs = current_pt_regs(); struct sigframe_ia32 __user *frame = (struct sigframe_ia32 __user *)(regs->sp-8); sigset_t set; if (!access_ok(frame, sizeof(*frame))) goto badframe; if (__get_user(set.sig[0], &frame->sc.oldmask) || __get_user(((__u32 *)&set)[1], &frame->extramask[0])) goto badframe; set_current_blocked(&set); if (!ia32_restore_sigcontext(regs, &frame->sc)) goto badframe; return regs->ax; badframe: signal_fault(regs, frame, "32bit sigreturn"); return 0; } SYSCALL32_DEFINE0(rt_sigreturn) { struct pt_regs *regs = current_pt_regs(); struct rt_sigframe_ia32 __user *frame; sigset_t set; frame = (struct rt_sigframe_ia32 __user *)(regs->sp - 4); if (!access_ok(frame, sizeof(*frame))) goto badframe; if (__get_user(*(__u64 *)&set, (__u64 __user *)&frame->uc.uc_sigmask)) goto badframe; set_current_blocked(&set); if (!ia32_restore_sigcontext(regs, &frame->uc.uc_mcontext)) goto badframe; if (restore_altstack32(&frame->uc.uc_stack)) goto badframe; return regs->ax; badframe: signal_fault(regs, frame, "32bit rt sigreturn"); return 0; } /* * Set up a signal frame. */ #define get_user_seg(seg) ({ unsigned int v; savesegment(seg, v); v; }) static __always_inline int __unsafe_setup_sigcontext32(struct sigcontext_32 __user *sc, void __user *fpstate, struct pt_regs *regs, unsigned int mask) { unsafe_put_user(get_user_seg(gs), (unsigned int __user *)&sc->gs, Efault); #ifdef CONFIG_IA32_EMULATION unsafe_put_user(get_user_seg(fs), (unsigned int __user *)&sc->fs, Efault); unsafe_put_user(get_user_seg(ds), (unsigned int __user *)&sc->ds, Efault); unsafe_put_user(get_user_seg(es), (unsigned int __user *)&sc->es, Efault); #else unsafe_put_user(regs->fs, (unsigned int __user *)&sc->fs, Efault); unsafe_put_user(regs->es, (unsigned int __user *)&sc->es, Efault); unsafe_put_user(regs->ds, (unsigned int __user *)&sc->ds, Efault); #endif unsafe_put_user(regs->di, &sc->di, Efault); unsafe_put_user(regs->si, &sc->si, Efault); unsafe_put_user(regs->bp, &sc->bp, Efault); unsafe_put_user(regs->sp, &sc->sp, Efault); unsafe_put_user(regs->bx, &sc->bx, Efault); unsafe_put_user(regs->dx, &sc->dx, Efault); unsafe_put_user(regs->cx, &sc->cx, Efault); unsafe_put_user(regs->ax, &sc->ax, Efault); unsafe_put_user(current->thread.trap_nr, &sc->trapno, Efault); unsafe_put_user(current->thread.error_code, &sc->err, Efault); unsafe_put_user(regs->ip, &sc->ip, Efault); unsafe_put_user(regs->cs, (unsigned int __user *)&sc->cs, Efault); unsafe_put_user(regs->flags, &sc->flags, Efault); unsafe_put_user(regs->sp, &sc->sp_at_signal, Efault); unsafe_put_user(regs->ss, (unsigned int __user *)&sc->ss, Efault); unsafe_put_user(ptr_to_compat(fpstate), &sc->fpstate, Efault); /* non-iBCS2 extensions.. */ unsafe_put_user(mask, &sc->oldmask, Efault); unsafe_put_user(current->thread.cr2, &sc->cr2, Efault); return 0; Efault: return -EFAULT; } #define unsafe_put_sigcontext32(sc, fp, regs, set, label) \ do { \ if (__unsafe_setup_sigcontext32(sc, fp, regs, set->sig[0])) \ goto label; \ } while(0) int ia32_setup_frame(struct ksignal *ksig, struct pt_regs *regs) { sigset32_t *set = (sigset32_t *) sigmask_to_save(); struct sigframe_ia32 __user *frame; void __user *restorer; void __user *fp = NULL; /* copy_to_user optimizes that into a single 8 byte store */ static const struct { u16 poplmovl; u32 val; u16 int80; } __attribute__((packed)) code = { 0xb858, /* popl %eax ; movl $...,%eax */ __NR_ia32_sigreturn, 0x80cd, /* int $0x80 */ }; frame = get_sigframe(ksig, regs, sizeof(*frame), &fp); if (ksig->ka.sa.sa_flags & SA_RESTORER) { restorer = ksig->ka.sa.sa_restorer; } else { /* Return stub is in 32bit vsyscall page */ if (current->mm->context.vdso) restorer = current->mm->context.vdso + vdso_image_32.sym___kernel_sigreturn; else restorer = &frame->retcode; } if (!user_access_begin(frame, sizeof(*frame))) return -EFAULT; unsafe_put_user(ksig->sig, &frame->sig, Efault); unsafe_put_sigcontext32(&frame->sc, fp, regs, set, Efault); unsafe_put_user(set->sig[1], &frame->extramask[0], Efault); unsafe_put_user(ptr_to_compat(restorer), &frame->pretcode, Efault); /* * These are actually not used anymore, but left because some * gdb versions depend on them as a marker. */ unsafe_put_user(*((u64 *)&code), (u64 __user *)frame->retcode, Efault); user_access_end(); /* Set up registers for signal handler */ regs->sp = (unsigned long) frame; regs->ip = (unsigned long) ksig->ka.sa.sa_handler; /* Make -mregparm=3 work */ regs->ax = ksig->sig; regs->dx = 0; regs->cx = 0; #ifdef CONFIG_IA32_EMULATION loadsegment(ds, __USER_DS); loadsegment(es, __USER_DS); #else regs->ds = __USER_DS; regs->es = __USER_DS; #endif regs->cs = __USER32_CS; regs->ss = __USER_DS; return 0; Efault: user_access_end(); return -EFAULT; } int ia32_setup_rt_frame(struct ksignal *ksig, struct pt_regs *regs) { sigset32_t *set = (sigset32_t *) sigmask_to_save(); struct rt_sigframe_ia32 __user *frame; void __user *restorer; void __user *fp = NULL; /* unsafe_put_user optimizes that into a single 8 byte store */ static const struct { u8 movl; u32 val; u16 int80; u8 pad; } __attribute__((packed)) code = { 0xb8, __NR_ia32_rt_sigreturn, 0x80cd, 0, }; frame = get_sigframe(ksig, regs, sizeof(*frame), &fp); if (!user_access_begin(frame, sizeof(*frame))) return -EFAULT; unsafe_put_user(ksig->sig, &frame->sig, Efault); unsafe_put_user(ptr_to_compat(&frame->info), &frame->pinfo, Efault); unsafe_put_user(ptr_to_compat(&frame->uc), &frame->puc, Efault); /* Create the ucontext. */ if (static_cpu_has(X86_FEATURE_XSAVE)) unsafe_put_user(UC_FP_XSTATE, &frame->uc.uc_flags, Efault); else unsafe_put_user(0, &frame->uc.uc_flags, Efault); unsafe_put_user(0, &frame->uc.uc_link, Efault); unsafe_save_altstack32(&frame->uc.uc_stack, regs->sp, Efault); if (ksig->ka.sa.sa_flags & SA_RESTORER) restorer = ksig->ka.sa.sa_restorer; else restorer = current->mm->context.vdso + vdso_image_32.sym___kernel_rt_sigreturn; unsafe_put_user(ptr_to_compat(restorer), &frame->pretcode, Efault); /* * Not actually used anymore, but left because some gdb * versions need it. */ unsafe_put_user(*((u64 *)&code), (u64 __user *)frame->retcode, Efault); unsafe_put_sigcontext32(&frame->uc.uc_mcontext, fp, regs, set, Efault); unsafe_put_user(*(__u64 *)set, (__u64 __user *)&frame->uc.uc_sigmask, Efault); user_access_end(); if (__copy_siginfo_to_user32(&frame->info, &ksig->info)) return -EFAULT; /* Set up registers for signal handler */ regs->sp = (unsigned long) frame; regs->ip = (unsigned long) ksig->ka.sa.sa_handler; /* Make -mregparm=3 work */ regs->ax = ksig->sig; regs->dx = (unsigned long) &frame->info; regs->cx = (unsigned long) &frame->uc; #ifdef CONFIG_IA32_EMULATION loadsegment(ds, __USER_DS); loadsegment(es, __USER_DS); #else regs->ds = __USER_DS; regs->es = __USER_DS; #endif regs->cs = __USER32_CS; regs->ss = __USER_DS; return 0; Efault: user_access_end(); return -EFAULT; } /* * The siginfo_t structure and handing code is very easy * to break in several ways. It must always be updated when new * updates are made to the main siginfo_t, and * copy_siginfo_to_user32() must be updated when the * (arch-independent) copy_siginfo_to_user() is updated. * * It is also easy to put a new member in the siginfo_t * which has implicit alignment which can move internal structure * alignment around breaking the ABI. This can happen if you, * for instance, put a plain 64-bit value in there. */ /* * If adding a new si_code, there is probably new data in * the siginfo. Make sure folks bumping the si_code * limits also have to look at this code. Make sure any * new fields are handled in copy_siginfo_to_user32()! */ static_assert(NSIGILL == 11); static_assert(NSIGFPE == 15); static_assert(NSIGSEGV == 10); static_assert(NSIGBUS == 5); static_assert(NSIGTRAP == 6); static_assert(NSIGCHLD == 6); static_assert(NSIGSYS == 2); /* This is part of the ABI and can never change in size: */ static_assert(sizeof(siginfo32_t) == 128); /* This is a part of the ABI and can never change in alignment */ static_assert(__alignof__(siginfo32_t) == 4); /* * The offsets of all the (unioned) si_fields are fixed * in the ABI, of course. Make sure none of them ever * move and are always at the beginning: */ static_assert(offsetof(siginfo32_t, _sifields) == 3 * sizeof(int)); static_assert(offsetof(siginfo32_t, si_signo) == 0); static_assert(offsetof(siginfo32_t, si_errno) == 4); static_assert(offsetof(siginfo32_t, si_code) == 8); /* * Ensure that the size of each si_field never changes. * If it does, it is a sign that the * copy_siginfo_to_user32() code below needs to updated * along with the size in the CHECK_SI_SIZE(). * * We repeat this check for both the generic and compat * siginfos. * * Note: it is OK for these to grow as long as the whole * structure stays within the padding size (checked * above). */ #define CHECK_SI_OFFSET(name) \ static_assert(offsetof(siginfo32_t, _sifields) == \ offsetof(siginfo32_t, _sifields.name)) #define CHECK_SI_SIZE(name, size) \ static_assert(sizeof_field(siginfo32_t, _sifields.name) == size) CHECK_SI_OFFSET(_kill); CHECK_SI_SIZE (_kill, 2*sizeof(int)); static_assert(offsetof(siginfo32_t, si_pid) == 0xC); static_assert(offsetof(siginfo32_t, si_uid) == 0x10); CHECK_SI_OFFSET(_timer); #ifdef CONFIG_COMPAT /* compat_siginfo_t doesn't have si_sys_private */ CHECK_SI_SIZE (_timer, 3*sizeof(int)); #else CHECK_SI_SIZE (_timer, 4*sizeof(int)); #endif static_assert(offsetof(siginfo32_t, si_tid) == 0x0C); static_assert(offsetof(siginfo32_t, si_overrun) == 0x10); static_assert(offsetof(siginfo32_t, si_value) == 0x14); CHECK_SI_OFFSET(_rt); CHECK_SI_SIZE (_rt, 3*sizeof(int)); static_assert(offsetof(siginfo32_t, si_pid) == 0x0C); static_assert(offsetof(siginfo32_t, si_uid) == 0x10); static_assert(offsetof(siginfo32_t, si_value) == 0x14); CHECK_SI_OFFSET(_sigchld); CHECK_SI_SIZE (_sigchld, 5*sizeof(int)); static_assert(offsetof(siginfo32_t, si_pid) == 0x0C); static_assert(offsetof(siginfo32_t, si_uid) == 0x10); static_assert(offsetof(siginfo32_t, si_status) == 0x14); static_assert(offsetof(siginfo32_t, si_utime) == 0x18); static_assert(offsetof(siginfo32_t, si_stime) == 0x1C); CHECK_SI_OFFSET(_sigfault); CHECK_SI_SIZE (_sigfault, 4*sizeof(int)); static_assert(offsetof(siginfo32_t, si_addr) == 0x0C); static_assert(offsetof(siginfo32_t, si_trapno) == 0x10); static_assert(offsetof(siginfo32_t, si_addr_lsb) == 0x10); static_assert(offsetof(siginfo32_t, si_lower) == 0x14); static_assert(offsetof(siginfo32_t, si_upper) == 0x18); static_assert(offsetof(siginfo32_t, si_pkey) == 0x14); static_assert(offsetof(siginfo32_t, si_perf_data) == 0x10); static_assert(offsetof(siginfo32_t, si_perf_type) == 0x14); static_assert(offsetof(siginfo32_t, si_perf_flags) == 0x18); CHECK_SI_OFFSET(_sigpoll); CHECK_SI_SIZE (_sigpoll, 2*sizeof(int)); static_assert(offsetof(siginfo32_t, si_band) == 0x0C); static_assert(offsetof(siginfo32_t, si_fd) == 0x10); CHECK_SI_OFFSET(_sigsys); CHECK_SI_SIZE (_sigsys, 3*sizeof(int)); static_assert(offsetof(siginfo32_t, si_call_addr) == 0x0C); static_assert(offsetof(siginfo32_t, si_syscall) == 0x10); static_assert(offsetof(siginfo32_t, si_arch) == 0x14); /* any new si_fields should be added here */
linux-master
arch/x86/kernel/signal_32.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/console.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/string.h> #include <linux/screen_info.h> #include <linux/usb/ch9.h> #include <linux/pci_regs.h> #include <linux/pci_ids.h> #include <linux/errno.h> #include <linux/pgtable.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/fcntl.h> #include <asm/setup.h> #include <xen/hvc-console.h> #include <asm/pci-direct.h> #include <asm/fixmap.h> #include <linux/usb/ehci_def.h> #include <linux/usb/xhci-dbgp.h> #include <asm/pci_x86.h> /* Simple VGA output */ #define VGABASE (__ISA_IO_base + 0xb8000) static int max_ypos = 25, max_xpos = 80; static int current_ypos = 25, current_xpos; static void early_vga_write(struct console *con, const char *str, unsigned n) { char c; int i, k, j; while ((c = *str++) != '\0' && n-- > 0) { if (current_ypos >= max_ypos) { /* scroll 1 line up */ for (k = 1, j = 0; k < max_ypos; k++, j++) { for (i = 0; i < max_xpos; i++) { writew(readw(VGABASE+2*(max_xpos*k+i)), VGABASE + 2*(max_xpos*j + i)); } } for (i = 0; i < max_xpos; i++) writew(0x720, VGABASE + 2*(max_xpos*j + i)); current_ypos = max_ypos-1; } #ifdef CONFIG_KGDB_KDB if (c == '\b') { if (current_xpos > 0) current_xpos--; } else if (c == '\r') { current_xpos = 0; } else #endif if (c == '\n') { current_xpos = 0; current_ypos++; } else if (c != '\r') { writew(((0x7 << 8) | (unsigned short) c), VGABASE + 2*(max_xpos*current_ypos + current_xpos++)); if (current_xpos >= max_xpos) { current_xpos = 0; current_ypos++; } } } } static struct console early_vga_console = { .name = "earlyvga", .write = early_vga_write, .flags = CON_PRINTBUFFER, .index = -1, }; /* Serial functions loosely based on a similar package from Klaus P. Gerlicher */ static unsigned long early_serial_base = 0x3f8; /* ttyS0 */ #define XMTRDY 0x20 #define DLAB 0x80 #define TXR 0 /* Transmit register (WRITE) */ #define RXR 0 /* Receive register (READ) */ #define IER 1 /* Interrupt Enable */ #define IIR 2 /* Interrupt ID */ #define FCR 2 /* FIFO control */ #define LCR 3 /* Line control */ #define MCR 4 /* Modem control */ #define LSR 5 /* Line Status */ #define MSR 6 /* Modem Status */ #define DLL 0 /* Divisor Latch Low */ #define DLH 1 /* Divisor latch High */ static unsigned int io_serial_in(unsigned long addr, int offset) { return inb(addr + offset); } static void io_serial_out(unsigned long addr, int offset, int value) { outb(value, addr + offset); } static unsigned int (*serial_in)(unsigned long addr, int offset) = io_serial_in; static void (*serial_out)(unsigned long addr, int offset, int value) = io_serial_out; static int early_serial_putc(unsigned char ch) { unsigned timeout = 0xffff; while ((serial_in(early_serial_base, LSR) & XMTRDY) == 0 && --timeout) cpu_relax(); serial_out(early_serial_base, TXR, ch); return timeout ? 0 : -1; } static void early_serial_write(struct console *con, const char *s, unsigned n) { while (*s && n-- > 0) { if (*s == '\n') early_serial_putc('\r'); early_serial_putc(*s); s++; } } static __init void early_serial_hw_init(unsigned divisor) { unsigned char c; serial_out(early_serial_base, LCR, 0x3); /* 8n1 */ serial_out(early_serial_base, IER, 0); /* no interrupt */ serial_out(early_serial_base, FCR, 0); /* no fifo */ serial_out(early_serial_base, MCR, 0x3); /* DTR + RTS */ c = serial_in(early_serial_base, LCR); serial_out(early_serial_base, LCR, c | DLAB); serial_out(early_serial_base, DLL, divisor & 0xff); serial_out(early_serial_base, DLH, (divisor >> 8) & 0xff); serial_out(early_serial_base, LCR, c & ~DLAB); } #define DEFAULT_BAUD 9600 static __init void early_serial_init(char *s) { unsigned divisor; unsigned long baud = DEFAULT_BAUD; char *e; if (*s == ',') ++s; if (*s) { unsigned port; if (!strncmp(s, "0x", 2)) { early_serial_base = simple_strtoul(s, &e, 16); } else { static const int __initconst bases[] = { 0x3f8, 0x2f8 }; if (!strncmp(s, "ttyS", 4)) s += 4; port = simple_strtoul(s, &e, 10); if (port > 1 || s == e) port = 0; early_serial_base = bases[port]; } s += strcspn(s, ","); if (*s == ',') s++; } if (*s) { baud = simple_strtoull(s, &e, 0); if (baud == 0 || s == e) baud = DEFAULT_BAUD; } /* Convert from baud to divisor value */ divisor = 115200 / baud; /* These will always be IO based ports */ serial_in = io_serial_in; serial_out = io_serial_out; /* Set up the HW */ early_serial_hw_init(divisor); } #ifdef CONFIG_PCI static void mem32_serial_out(unsigned long addr, int offset, int value) { u32 __iomem *vaddr = (u32 __iomem *)addr; /* shift implied by pointer type */ writel(value, vaddr + offset); } static unsigned int mem32_serial_in(unsigned long addr, int offset) { u32 __iomem *vaddr = (u32 __iomem *)addr; /* shift implied by pointer type */ return readl(vaddr + offset); } /* * early_pci_serial_init() * * This function is invoked when the early_printk param starts with "pciserial" * The rest of the param should be "[force],B:D.F,baud", where B, D & F describe * the location of a PCI device that must be a UART device. "force" is optional * and overrides the use of an UART device with a wrong PCI class code. */ static __init void early_pci_serial_init(char *s) { unsigned divisor; unsigned long baud = DEFAULT_BAUD; u8 bus, slot, func; u32 classcode, bar0; u16 cmdreg; char *e; int force = 0; if (*s == ',') ++s; if (*s == 0) return; /* Force the use of an UART device with wrong class code */ if (!strncmp(s, "force,", 6)) { force = 1; s += 6; } /* * Part the param to get the BDF values */ bus = (u8)simple_strtoul(s, &e, 16); s = e; if (*s != ':') return; ++s; slot = (u8)simple_strtoul(s, &e, 16); s = e; if (*s != '.') return; ++s; func = (u8)simple_strtoul(s, &e, 16); s = e; /* A baud might be following */ if (*s == ',') s++; /* * Find the device from the BDF */ cmdreg = read_pci_config(bus, slot, func, PCI_COMMAND); classcode = read_pci_config(bus, slot, func, PCI_CLASS_REVISION); bar0 = read_pci_config(bus, slot, func, PCI_BASE_ADDRESS_0); /* * Verify it is a 16550-UART type device */ if (((classcode >> 16 != PCI_CLASS_COMMUNICATION_MODEM) && (classcode >> 16 != PCI_CLASS_COMMUNICATION_SERIAL)) || (((classcode >> 8) & 0xff) != PCI_SERIAL_16550_COMPATIBLE)) { if (!force) return; } /* * Determine if it is IO or memory mapped */ if ((bar0 & PCI_BASE_ADDRESS_SPACE) == PCI_BASE_ADDRESS_SPACE_IO) { /* it is IO mapped */ serial_in = io_serial_in; serial_out = io_serial_out; early_serial_base = bar0 & PCI_BASE_ADDRESS_IO_MASK; write_pci_config(bus, slot, func, PCI_COMMAND, cmdreg|PCI_COMMAND_IO); } else { /* It is memory mapped - assume 32-bit alignment */ serial_in = mem32_serial_in; serial_out = mem32_serial_out; /* WARNING! assuming the address is always in the first 4G */ early_serial_base = (unsigned long)early_ioremap(bar0 & PCI_BASE_ADDRESS_MEM_MASK, 0x10); write_pci_config(bus, slot, func, PCI_COMMAND, cmdreg|PCI_COMMAND_MEMORY); } /* * Initialize the hardware */ if (*s) { if (strcmp(s, "nocfg") == 0) /* Sometimes, we want to leave the UART alone * and assume the BIOS has set it up correctly. * "nocfg" tells us this is the case, and we * should do no more setup. */ return; if (kstrtoul(s, 0, &baud) < 0 || baud == 0) baud = DEFAULT_BAUD; } /* Convert from baud to divisor value */ divisor = 115200 / baud; /* Set up the HW */ early_serial_hw_init(divisor); } #endif static struct console early_serial_console = { .name = "earlyser", .write = early_serial_write, .flags = CON_PRINTBUFFER, .index = -1, }; static void early_console_register(struct console *con, int keep_early) { if (con->index != -1) { printk(KERN_CRIT "ERROR: earlyprintk= %s already used\n", con->name); return; } early_console = con; if (keep_early) early_console->flags &= ~CON_BOOT; else early_console->flags |= CON_BOOT; register_console(early_console); } static int __init setup_early_printk(char *buf) { int keep; if (!buf) return 0; if (early_console) return 0; keep = (strstr(buf, "keep") != NULL); while (*buf != '\0') { if (!strncmp(buf, "serial", 6)) { buf += 6; early_serial_init(buf); early_console_register(&early_serial_console, keep); if (!strncmp(buf, ",ttyS", 5)) buf += 5; } if (!strncmp(buf, "ttyS", 4)) { early_serial_init(buf + 4); early_console_register(&early_serial_console, keep); } #ifdef CONFIG_PCI if (!strncmp(buf, "pciserial", 9)) { early_pci_serial_init(buf + 9); early_console_register(&early_serial_console, keep); buf += 9; /* Keep from match the above "serial" */ } #endif if (!strncmp(buf, "vga", 3) && boot_params.screen_info.orig_video_isVGA == 1) { max_xpos = boot_params.screen_info.orig_video_cols; max_ypos = boot_params.screen_info.orig_video_lines; current_ypos = boot_params.screen_info.orig_y; early_console_register(&early_vga_console, keep); } #ifdef CONFIG_EARLY_PRINTK_DBGP if (!strncmp(buf, "dbgp", 4) && !early_dbgp_init(buf + 4)) early_console_register(&early_dbgp_console, keep); #endif #ifdef CONFIG_HVC_XEN if (!strncmp(buf, "xen", 3)) early_console_register(&xenboot_console, keep); #endif #ifdef CONFIG_EARLY_PRINTK_USB_XDBC if (!strncmp(buf, "xdbc", 4)) early_xdbc_parse_parameter(buf + 4, keep); #endif buf++; } return 0; } early_param("earlyprintk", setup_early_printk);
linux-master
arch/x86/kernel/early_printk.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/crash_core.h> #include <linux/pgtable.h> #include <asm/setup.h> void arch_crash_save_vmcoreinfo(void) { u64 sme_mask = sme_me_mask; VMCOREINFO_NUMBER(phys_base); VMCOREINFO_SYMBOL(init_top_pgt); vmcoreinfo_append_str("NUMBER(pgtable_l5_enabled)=%d\n", pgtable_l5_enabled()); #ifdef CONFIG_NUMA VMCOREINFO_SYMBOL(node_data); VMCOREINFO_LENGTH(node_data, MAX_NUMNODES); #endif vmcoreinfo_append_str("KERNELOFFSET=%lx\n", kaslr_offset()); VMCOREINFO_NUMBER(KERNEL_IMAGE_SIZE); VMCOREINFO_NUMBER(sme_mask); }
linux-master
arch/x86/kernel/crash_core_64.c
#include <asm/trace/irq_vectors.h> #include <linux/trace.h> #if defined(CONFIG_OSNOISE_TRACER) && defined(CONFIG_X86_LOCAL_APIC) /* * trace_intel_irq_entry - record intel specific IRQ entry */ static void trace_intel_irq_entry(void *data, int vector) { osnoise_trace_irq_entry(vector); } /* * trace_intel_irq_exit - record intel specific IRQ exit */ static void trace_intel_irq_exit(void *data, int vector) { char *vector_desc = (char *) data; osnoise_trace_irq_exit(vector, vector_desc); } /* * register_intel_irq_tp - Register intel specific IRQ entry tracepoints */ int osnoise_arch_register(void) { int ret; ret = register_trace_local_timer_entry(trace_intel_irq_entry, NULL); if (ret) goto out_err; ret = register_trace_local_timer_exit(trace_intel_irq_exit, "local_timer"); if (ret) goto out_timer_entry; #ifdef CONFIG_X86_THERMAL_VECTOR ret = register_trace_thermal_apic_entry(trace_intel_irq_entry, NULL); if (ret) goto out_timer_exit; ret = register_trace_thermal_apic_exit(trace_intel_irq_exit, "thermal_apic"); if (ret) goto out_thermal_entry; #endif /* CONFIG_X86_THERMAL_VECTOR */ #ifdef CONFIG_X86_MCE_AMD ret = register_trace_deferred_error_apic_entry(trace_intel_irq_entry, NULL); if (ret) goto out_thermal_exit; ret = register_trace_deferred_error_apic_exit(trace_intel_irq_exit, "deferred_error"); if (ret) goto out_deferred_entry; #endif #ifdef CONFIG_X86_MCE_THRESHOLD ret = register_trace_threshold_apic_entry(trace_intel_irq_entry, NULL); if (ret) goto out_deferred_exit; ret = register_trace_threshold_apic_exit(trace_intel_irq_exit, "threshold_apic"); if (ret) goto out_threshold_entry; #endif /* CONFIG_X86_MCE_THRESHOLD */ #ifdef CONFIG_SMP ret = register_trace_call_function_single_entry(trace_intel_irq_entry, NULL); if (ret) goto out_threshold_exit; ret = register_trace_call_function_single_exit(trace_intel_irq_exit, "call_function_single"); if (ret) goto out_call_function_single_entry; ret = register_trace_call_function_entry(trace_intel_irq_entry, NULL); if (ret) goto out_call_function_single_exit; ret = register_trace_call_function_exit(trace_intel_irq_exit, "call_function"); if (ret) goto out_call_function_entry; ret = register_trace_reschedule_entry(trace_intel_irq_entry, NULL); if (ret) goto out_call_function_exit; ret = register_trace_reschedule_exit(trace_intel_irq_exit, "reschedule"); if (ret) goto out_reschedule_entry; #endif /* CONFIG_SMP */ #ifdef CONFIG_IRQ_WORK ret = register_trace_irq_work_entry(trace_intel_irq_entry, NULL); if (ret) goto out_reschedule_exit; ret = register_trace_irq_work_exit(trace_intel_irq_exit, "irq_work"); if (ret) goto out_irq_work_entry; #endif ret = register_trace_x86_platform_ipi_entry(trace_intel_irq_entry, NULL); if (ret) goto out_irq_work_exit; ret = register_trace_x86_platform_ipi_exit(trace_intel_irq_exit, "x86_platform_ipi"); if (ret) goto out_x86_ipi_entry; ret = register_trace_error_apic_entry(trace_intel_irq_entry, NULL); if (ret) goto out_x86_ipi_exit; ret = register_trace_error_apic_exit(trace_intel_irq_exit, "error_apic"); if (ret) goto out_error_apic_entry; ret = register_trace_spurious_apic_entry(trace_intel_irq_entry, NULL); if (ret) goto out_error_apic_exit; ret = register_trace_spurious_apic_exit(trace_intel_irq_exit, "spurious_apic"); if (ret) goto out_spurious_apic_entry; return 0; out_spurious_apic_entry: unregister_trace_spurious_apic_entry(trace_intel_irq_entry, NULL); out_error_apic_exit: unregister_trace_error_apic_exit(trace_intel_irq_exit, "error_apic"); out_error_apic_entry: unregister_trace_error_apic_entry(trace_intel_irq_entry, NULL); out_x86_ipi_exit: unregister_trace_x86_platform_ipi_exit(trace_intel_irq_exit, "x86_platform_ipi"); out_x86_ipi_entry: unregister_trace_x86_platform_ipi_entry(trace_intel_irq_entry, NULL); out_irq_work_exit: #ifdef CONFIG_IRQ_WORK unregister_trace_irq_work_exit(trace_intel_irq_exit, "irq_work"); out_irq_work_entry: unregister_trace_irq_work_entry(trace_intel_irq_entry, NULL); out_reschedule_exit: #endif #ifdef CONFIG_SMP unregister_trace_reschedule_exit(trace_intel_irq_exit, "reschedule"); out_reschedule_entry: unregister_trace_reschedule_entry(trace_intel_irq_entry, NULL); out_call_function_exit: unregister_trace_call_function_exit(trace_intel_irq_exit, "call_function"); out_call_function_entry: unregister_trace_call_function_entry(trace_intel_irq_entry, NULL); out_call_function_single_exit: unregister_trace_call_function_single_exit(trace_intel_irq_exit, "call_function_single"); out_call_function_single_entry: unregister_trace_call_function_single_entry(trace_intel_irq_entry, NULL); out_threshold_exit: #endif #ifdef CONFIG_X86_MCE_THRESHOLD unregister_trace_threshold_apic_exit(trace_intel_irq_exit, "threshold_apic"); out_threshold_entry: unregister_trace_threshold_apic_entry(trace_intel_irq_entry, NULL); out_deferred_exit: #endif #ifdef CONFIG_X86_MCE_AMD unregister_trace_deferred_error_apic_exit(trace_intel_irq_exit, "deferred_error"); out_deferred_entry: unregister_trace_deferred_error_apic_entry(trace_intel_irq_entry, NULL); out_thermal_exit: #endif /* CONFIG_X86_MCE_AMD */ #ifdef CONFIG_X86_THERMAL_VECTOR unregister_trace_thermal_apic_exit(trace_intel_irq_exit, "thermal_apic"); out_thermal_entry: unregister_trace_thermal_apic_entry(trace_intel_irq_entry, NULL); out_timer_exit: #endif /* CONFIG_X86_THERMAL_VECTOR */ unregister_trace_local_timer_exit(trace_intel_irq_exit, "local_timer"); out_timer_entry: unregister_trace_local_timer_entry(trace_intel_irq_entry, NULL); out_err: return -EINVAL; } void osnoise_arch_unregister(void) { unregister_trace_spurious_apic_exit(trace_intel_irq_exit, "spurious_apic"); unregister_trace_spurious_apic_entry(trace_intel_irq_entry, NULL); unregister_trace_error_apic_exit(trace_intel_irq_exit, "error_apic"); unregister_trace_error_apic_entry(trace_intel_irq_entry, NULL); unregister_trace_x86_platform_ipi_exit(trace_intel_irq_exit, "x86_platform_ipi"); unregister_trace_x86_platform_ipi_entry(trace_intel_irq_entry, NULL); #ifdef CONFIG_IRQ_WORK unregister_trace_irq_work_exit(trace_intel_irq_exit, "irq_work"); unregister_trace_irq_work_entry(trace_intel_irq_entry, NULL); #endif #ifdef CONFIG_SMP unregister_trace_reschedule_exit(trace_intel_irq_exit, "reschedule"); unregister_trace_reschedule_entry(trace_intel_irq_entry, NULL); unregister_trace_call_function_exit(trace_intel_irq_exit, "call_function"); unregister_trace_call_function_entry(trace_intel_irq_entry, NULL); unregister_trace_call_function_single_exit(trace_intel_irq_exit, "call_function_single"); unregister_trace_call_function_single_entry(trace_intel_irq_entry, NULL); #endif #ifdef CONFIG_X86_MCE_THRESHOLD unregister_trace_threshold_apic_exit(trace_intel_irq_exit, "threshold_apic"); unregister_trace_threshold_apic_entry(trace_intel_irq_entry, NULL); #endif #ifdef CONFIG_X86_MCE_AMD unregister_trace_deferred_error_apic_exit(trace_intel_irq_exit, "deferred_error"); unregister_trace_deferred_error_apic_entry(trace_intel_irq_entry, NULL); #endif #ifdef CONFIG_X86_THERMAL_VECTOR unregister_trace_thermal_apic_exit(trace_intel_irq_exit, "thermal_apic"); unregister_trace_thermal_apic_entry(trace_intel_irq_entry, NULL); #endif /* CONFIG_X86_THERMAL_VECTOR */ unregister_trace_local_timer_exit(trace_intel_irq_exit, "local_timer"); unregister_trace_local_timer_entry(trace_intel_irq_entry, NULL); } #endif /* CONFIG_OSNOISE_TRACER && CONFIG_X86_LOCAL_APIC */
linux-master
arch/x86/kernel/trace.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * KVM paravirt_ops implementation * * Copyright (C) 2007, Red Hat, Inc., Ingo Molnar <[email protected]> * Copyright IBM Corporation, 2007 * Authors: Anthony Liguori <[email protected]> */ #define pr_fmt(fmt) "kvm-guest: " fmt #include <linux/context_tracking.h> #include <linux/init.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/kvm_para.h> #include <linux/cpu.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/hardirq.h> #include <linux/notifier.h> #include <linux/reboot.h> #include <linux/hash.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/kprobes.h> #include <linux/nmi.h> #include <linux/swait.h> #include <linux/syscore_ops.h> #include <linux/cc_platform.h> #include <linux/efi.h> #include <asm/timer.h> #include <asm/cpu.h> #include <asm/traps.h> #include <asm/desc.h> #include <asm/tlbflush.h> #include <asm/apic.h> #include <asm/apicdef.h> #include <asm/hypervisor.h> #include <asm/tlb.h> #include <asm/cpuidle_haltpoll.h> #include <asm/ptrace.h> #include <asm/reboot.h> #include <asm/svm.h> #include <asm/e820/api.h> DEFINE_STATIC_KEY_FALSE(kvm_async_pf_enabled); static int kvmapf = 1; static int __init parse_no_kvmapf(char *arg) { kvmapf = 0; return 0; } early_param("no-kvmapf", parse_no_kvmapf); static int steal_acc = 1; static int __init parse_no_stealacc(char *arg) { steal_acc = 0; return 0; } early_param("no-steal-acc", parse_no_stealacc); static DEFINE_PER_CPU_DECRYPTED(struct kvm_vcpu_pv_apf_data, apf_reason) __aligned(64); DEFINE_PER_CPU_DECRYPTED(struct kvm_steal_time, steal_time) __aligned(64) __visible; static int has_steal_clock = 0; static int has_guest_poll = 0; /* * No need for any "IO delay" on KVM */ static void kvm_io_delay(void) { } #define KVM_TASK_SLEEP_HASHBITS 8 #define KVM_TASK_SLEEP_HASHSIZE (1<<KVM_TASK_SLEEP_HASHBITS) struct kvm_task_sleep_node { struct hlist_node link; struct swait_queue_head wq; u32 token; int cpu; }; static struct kvm_task_sleep_head { raw_spinlock_t lock; struct hlist_head list; } async_pf_sleepers[KVM_TASK_SLEEP_HASHSIZE]; static struct kvm_task_sleep_node *_find_apf_task(struct kvm_task_sleep_head *b, u32 token) { struct hlist_node *p; hlist_for_each(p, &b->list) { struct kvm_task_sleep_node *n = hlist_entry(p, typeof(*n), link); if (n->token == token) return n; } return NULL; } static bool kvm_async_pf_queue_task(u32 token, struct kvm_task_sleep_node *n) { u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS); struct kvm_task_sleep_head *b = &async_pf_sleepers[key]; struct kvm_task_sleep_node *e; raw_spin_lock(&b->lock); e = _find_apf_task(b, token); if (e) { /* dummy entry exist -> wake up was delivered ahead of PF */ hlist_del(&e->link); raw_spin_unlock(&b->lock); kfree(e); return false; } n->token = token; n->cpu = smp_processor_id(); init_swait_queue_head(&n->wq); hlist_add_head(&n->link, &b->list); raw_spin_unlock(&b->lock); return true; } /* * kvm_async_pf_task_wait_schedule - Wait for pagefault to be handled * @token: Token to identify the sleep node entry * * Invoked from the async pagefault handling code or from the VM exit page * fault handler. In both cases RCU is watching. */ void kvm_async_pf_task_wait_schedule(u32 token) { struct kvm_task_sleep_node n; DECLARE_SWAITQUEUE(wait); lockdep_assert_irqs_disabled(); if (!kvm_async_pf_queue_task(token, &n)) return; for (;;) { prepare_to_swait_exclusive(&n.wq, &wait, TASK_UNINTERRUPTIBLE); if (hlist_unhashed(&n.link)) break; local_irq_enable(); schedule(); local_irq_disable(); } finish_swait(&n.wq, &wait); } EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait_schedule); static void apf_task_wake_one(struct kvm_task_sleep_node *n) { hlist_del_init(&n->link); if (swq_has_sleeper(&n->wq)) swake_up_one(&n->wq); } static void apf_task_wake_all(void) { int i; for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) { struct kvm_task_sleep_head *b = &async_pf_sleepers[i]; struct kvm_task_sleep_node *n; struct hlist_node *p, *next; raw_spin_lock(&b->lock); hlist_for_each_safe(p, next, &b->list) { n = hlist_entry(p, typeof(*n), link); if (n->cpu == smp_processor_id()) apf_task_wake_one(n); } raw_spin_unlock(&b->lock); } } void kvm_async_pf_task_wake(u32 token) { u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS); struct kvm_task_sleep_head *b = &async_pf_sleepers[key]; struct kvm_task_sleep_node *n, *dummy = NULL; if (token == ~0) { apf_task_wake_all(); return; } again: raw_spin_lock(&b->lock); n = _find_apf_task(b, token); if (!n) { /* * Async #PF not yet handled, add a dummy entry for the token. * Allocating the token must be down outside of the raw lock * as the allocator is preemptible on PREEMPT_RT kernels. */ if (!dummy) { raw_spin_unlock(&b->lock); dummy = kzalloc(sizeof(*dummy), GFP_ATOMIC); /* * Continue looping on allocation failure, eventually * the async #PF will be handled and allocating a new * node will be unnecessary. */ if (!dummy) cpu_relax(); /* * Recheck for async #PF completion before enqueueing * the dummy token to avoid duplicate list entries. */ goto again; } dummy->token = token; dummy->cpu = smp_processor_id(); init_swait_queue_head(&dummy->wq); hlist_add_head(&dummy->link, &b->list); dummy = NULL; } else { apf_task_wake_one(n); } raw_spin_unlock(&b->lock); /* A dummy token might be allocated and ultimately not used. */ kfree(dummy); } EXPORT_SYMBOL_GPL(kvm_async_pf_task_wake); noinstr u32 kvm_read_and_reset_apf_flags(void) { u32 flags = 0; if (__this_cpu_read(apf_reason.enabled)) { flags = __this_cpu_read(apf_reason.flags); __this_cpu_write(apf_reason.flags, 0); } return flags; } EXPORT_SYMBOL_GPL(kvm_read_and_reset_apf_flags); noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token) { u32 flags = kvm_read_and_reset_apf_flags(); irqentry_state_t state; if (!flags) return false; state = irqentry_enter(regs); instrumentation_begin(); /* * If the host managed to inject an async #PF into an interrupt * disabled region, then die hard as this is not going to end well * and the host side is seriously broken. */ if (unlikely(!(regs->flags & X86_EFLAGS_IF))) panic("Host injected async #PF in interrupt disabled region\n"); if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) { if (unlikely(!(user_mode(regs)))) panic("Host injected async #PF in kernel mode\n"); /* Page is swapped out by the host. */ kvm_async_pf_task_wait_schedule(token); } else { WARN_ONCE(1, "Unexpected async PF flags: %x\n", flags); } instrumentation_end(); irqentry_exit(regs, state); return true; } DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_asyncpf_interrupt) { struct pt_regs *old_regs = set_irq_regs(regs); u32 token; apic_eoi(); inc_irq_stat(irq_hv_callback_count); if (__this_cpu_read(apf_reason.enabled)) { token = __this_cpu_read(apf_reason.token); kvm_async_pf_task_wake(token); __this_cpu_write(apf_reason.token, 0); wrmsrl(MSR_KVM_ASYNC_PF_ACK, 1); } set_irq_regs(old_regs); } static void __init paravirt_ops_setup(void) { pv_info.name = "KVM"; if (kvm_para_has_feature(KVM_FEATURE_NOP_IO_DELAY)) pv_ops.cpu.io_delay = kvm_io_delay; #ifdef CONFIG_X86_IO_APIC no_timer_check = 1; #endif } static void kvm_register_steal_time(void) { int cpu = smp_processor_id(); struct kvm_steal_time *st = &per_cpu(steal_time, cpu); if (!has_steal_clock) return; wrmsrl(MSR_KVM_STEAL_TIME, (slow_virt_to_phys(st) | KVM_MSR_ENABLED)); pr_debug("stealtime: cpu %d, msr %llx\n", cpu, (unsigned long long) slow_virt_to_phys(st)); } static DEFINE_PER_CPU_DECRYPTED(unsigned long, kvm_apic_eoi) = KVM_PV_EOI_DISABLED; static notrace __maybe_unused void kvm_guest_apic_eoi_write(void) { /** * This relies on __test_and_clear_bit to modify the memory * in a way that is atomic with respect to the local CPU. * The hypervisor only accesses this memory from the local CPU so * there's no need for lock or memory barriers. * An optimization barrier is implied in apic write. */ if (__test_and_clear_bit(KVM_PV_EOI_BIT, this_cpu_ptr(&kvm_apic_eoi))) return; apic_native_eoi(); } static void kvm_guest_cpu_init(void) { if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) { u64 pa; WARN_ON_ONCE(!static_branch_likely(&kvm_async_pf_enabled)); pa = slow_virt_to_phys(this_cpu_ptr(&apf_reason)); pa |= KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT; if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_VMEXIT)) pa |= KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT; wrmsrl(MSR_KVM_ASYNC_PF_INT, HYPERVISOR_CALLBACK_VECTOR); wrmsrl(MSR_KVM_ASYNC_PF_EN, pa); __this_cpu_write(apf_reason.enabled, 1); pr_debug("setup async PF for cpu %d\n", smp_processor_id()); } if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) { unsigned long pa; /* Size alignment is implied but just to make it explicit. */ BUILD_BUG_ON(__alignof__(kvm_apic_eoi) < 4); __this_cpu_write(kvm_apic_eoi, 0); pa = slow_virt_to_phys(this_cpu_ptr(&kvm_apic_eoi)) | KVM_MSR_ENABLED; wrmsrl(MSR_KVM_PV_EOI_EN, pa); } if (has_steal_clock) kvm_register_steal_time(); } static void kvm_pv_disable_apf(void) { if (!__this_cpu_read(apf_reason.enabled)) return; wrmsrl(MSR_KVM_ASYNC_PF_EN, 0); __this_cpu_write(apf_reason.enabled, 0); pr_debug("disable async PF for cpu %d\n", smp_processor_id()); } static void kvm_disable_steal_time(void) { if (!has_steal_clock) return; wrmsr(MSR_KVM_STEAL_TIME, 0, 0); } static u64 kvm_steal_clock(int cpu) { u64 steal; struct kvm_steal_time *src; int version; src = &per_cpu(steal_time, cpu); do { version = src->version; virt_rmb(); steal = src->steal; virt_rmb(); } while ((version & 1) || (version != src->version)); return steal; } static inline void __set_percpu_decrypted(void *ptr, unsigned long size) { early_set_memory_decrypted((unsigned long) ptr, size); } /* * Iterate through all possible CPUs and map the memory region pointed * by apf_reason, steal_time and kvm_apic_eoi as decrypted at once. * * Note: we iterate through all possible CPUs to ensure that CPUs * hotplugged will have their per-cpu variable already mapped as * decrypted. */ static void __init sev_map_percpu_data(void) { int cpu; if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) return; for_each_possible_cpu(cpu) { __set_percpu_decrypted(&per_cpu(apf_reason, cpu), sizeof(apf_reason)); __set_percpu_decrypted(&per_cpu(steal_time, cpu), sizeof(steal_time)); __set_percpu_decrypted(&per_cpu(kvm_apic_eoi, cpu), sizeof(kvm_apic_eoi)); } } static void kvm_guest_cpu_offline(bool shutdown) { kvm_disable_steal_time(); if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) wrmsrl(MSR_KVM_PV_EOI_EN, 0); if (kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) wrmsrl(MSR_KVM_MIGRATION_CONTROL, 0); kvm_pv_disable_apf(); if (!shutdown) apf_task_wake_all(); kvmclock_disable(); } static int kvm_cpu_online(unsigned int cpu) { unsigned long flags; local_irq_save(flags); kvm_guest_cpu_init(); local_irq_restore(flags); return 0; } #ifdef CONFIG_SMP static DEFINE_PER_CPU(cpumask_var_t, __pv_cpu_mask); static bool pv_tlb_flush_supported(void) { return (kvm_para_has_feature(KVM_FEATURE_PV_TLB_FLUSH) && !kvm_para_has_hint(KVM_HINTS_REALTIME) && kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) && !boot_cpu_has(X86_FEATURE_MWAIT) && (num_possible_cpus() != 1)); } static bool pv_ipi_supported(void) { return (kvm_para_has_feature(KVM_FEATURE_PV_SEND_IPI) && (num_possible_cpus() != 1)); } static bool pv_sched_yield_supported(void) { return (kvm_para_has_feature(KVM_FEATURE_PV_SCHED_YIELD) && !kvm_para_has_hint(KVM_HINTS_REALTIME) && kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) && !boot_cpu_has(X86_FEATURE_MWAIT) && (num_possible_cpus() != 1)); } #define KVM_IPI_CLUSTER_SIZE (2 * BITS_PER_LONG) static void __send_ipi_mask(const struct cpumask *mask, int vector) { unsigned long flags; int cpu, apic_id, icr; int min = 0, max = 0; #ifdef CONFIG_X86_64 __uint128_t ipi_bitmap = 0; #else u64 ipi_bitmap = 0; #endif long ret; if (cpumask_empty(mask)) return; local_irq_save(flags); switch (vector) { default: icr = APIC_DM_FIXED | vector; break; case NMI_VECTOR: icr = APIC_DM_NMI; break; } for_each_cpu(cpu, mask) { apic_id = per_cpu(x86_cpu_to_apicid, cpu); if (!ipi_bitmap) { min = max = apic_id; } else if (apic_id < min && max - apic_id < KVM_IPI_CLUSTER_SIZE) { ipi_bitmap <<= min - apic_id; min = apic_id; } else if (apic_id > min && apic_id < min + KVM_IPI_CLUSTER_SIZE) { max = apic_id < max ? max : apic_id; } else { ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap, (unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr); WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld", ret); min = max = apic_id; ipi_bitmap = 0; } __set_bit(apic_id - min, (unsigned long *)&ipi_bitmap); } if (ipi_bitmap) { ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap, (unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr); WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld", ret); } local_irq_restore(flags); } static void kvm_send_ipi_mask(const struct cpumask *mask, int vector) { __send_ipi_mask(mask, vector); } static void kvm_send_ipi_mask_allbutself(const struct cpumask *mask, int vector) { unsigned int this_cpu = smp_processor_id(); struct cpumask *new_mask = this_cpu_cpumask_var_ptr(__pv_cpu_mask); const struct cpumask *local_mask; cpumask_copy(new_mask, mask); cpumask_clear_cpu(this_cpu, new_mask); local_mask = new_mask; __send_ipi_mask(local_mask, vector); } static int __init setup_efi_kvm_sev_migration(void) { efi_char16_t efi_sev_live_migration_enabled[] = L"SevLiveMigrationEnabled"; efi_guid_t efi_variable_guid = AMD_SEV_MEM_ENCRYPT_GUID; efi_status_t status; unsigned long size; bool enabled; if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) || !kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) return 0; if (!efi_enabled(EFI_BOOT)) return 0; if (!efi_enabled(EFI_RUNTIME_SERVICES)) { pr_info("%s : EFI runtime services are not enabled\n", __func__); return 0; } size = sizeof(enabled); /* Get variable contents into buffer */ status = efi.get_variable(efi_sev_live_migration_enabled, &efi_variable_guid, NULL, &size, &enabled); if (status == EFI_NOT_FOUND) { pr_info("%s : EFI live migration variable not found\n", __func__); return 0; } if (status != EFI_SUCCESS) { pr_info("%s : EFI variable retrieval failed\n", __func__); return 0; } if (enabled == 0) { pr_info("%s: live migration disabled in EFI\n", __func__); return 0; } pr_info("%s : live migration enabled in EFI\n", __func__); wrmsrl(MSR_KVM_MIGRATION_CONTROL, KVM_MIGRATION_READY); return 1; } late_initcall(setup_efi_kvm_sev_migration); /* * Set the IPI entry points */ static __init void kvm_setup_pv_ipi(void) { apic_update_callback(send_IPI_mask, kvm_send_ipi_mask); apic_update_callback(send_IPI_mask_allbutself, kvm_send_ipi_mask_allbutself); pr_info("setup PV IPIs\n"); } static void kvm_smp_send_call_func_ipi(const struct cpumask *mask) { int cpu; native_send_call_func_ipi(mask); /* Make sure other vCPUs get a chance to run if they need to. */ for_each_cpu(cpu, mask) { if (!idle_cpu(cpu) && vcpu_is_preempted(cpu)) { kvm_hypercall1(KVM_HC_SCHED_YIELD, per_cpu(x86_cpu_to_apicid, cpu)); break; } } } static void kvm_flush_tlb_multi(const struct cpumask *cpumask, const struct flush_tlb_info *info) { u8 state; int cpu; struct kvm_steal_time *src; struct cpumask *flushmask = this_cpu_cpumask_var_ptr(__pv_cpu_mask); cpumask_copy(flushmask, cpumask); /* * We have to call flush only on online vCPUs. And * queue flush_on_enter for pre-empted vCPUs */ for_each_cpu(cpu, flushmask) { /* * The local vCPU is never preempted, so we do not explicitly * skip check for local vCPU - it will never be cleared from * flushmask. */ src = &per_cpu(steal_time, cpu); state = READ_ONCE(src->preempted); if ((state & KVM_VCPU_PREEMPTED)) { if (try_cmpxchg(&src->preempted, &state, state | KVM_VCPU_FLUSH_TLB)) __cpumask_clear_cpu(cpu, flushmask); } } native_flush_tlb_multi(flushmask, info); } static __init int kvm_alloc_cpumask(void) { int cpu; if (!kvm_para_available() || nopv) return 0; if (pv_tlb_flush_supported() || pv_ipi_supported()) for_each_possible_cpu(cpu) { zalloc_cpumask_var_node(per_cpu_ptr(&__pv_cpu_mask, cpu), GFP_KERNEL, cpu_to_node(cpu)); } return 0; } arch_initcall(kvm_alloc_cpumask); static void __init kvm_smp_prepare_boot_cpu(void) { /* * Map the per-cpu variables as decrypted before kvm_guest_cpu_init() * shares the guest physical address with the hypervisor. */ sev_map_percpu_data(); kvm_guest_cpu_init(); native_smp_prepare_boot_cpu(); kvm_spinlock_init(); } static int kvm_cpu_down_prepare(unsigned int cpu) { unsigned long flags; local_irq_save(flags); kvm_guest_cpu_offline(false); local_irq_restore(flags); return 0; } #endif static int kvm_suspend(void) { u64 val = 0; kvm_guest_cpu_offline(false); #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) rdmsrl(MSR_KVM_POLL_CONTROL, val); has_guest_poll = !(val & 1); #endif return 0; } static void kvm_resume(void) { kvm_cpu_online(raw_smp_processor_id()); #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL) && has_guest_poll) wrmsrl(MSR_KVM_POLL_CONTROL, 0); #endif } static struct syscore_ops kvm_syscore_ops = { .suspend = kvm_suspend, .resume = kvm_resume, }; static void kvm_pv_guest_cpu_reboot(void *unused) { kvm_guest_cpu_offline(true); } static int kvm_pv_reboot_notify(struct notifier_block *nb, unsigned long code, void *unused) { if (code == SYS_RESTART) on_each_cpu(kvm_pv_guest_cpu_reboot, NULL, 1); return NOTIFY_DONE; } static struct notifier_block kvm_pv_reboot_nb = { .notifier_call = kvm_pv_reboot_notify, }; /* * After a PV feature is registered, the host will keep writing to the * registered memory location. If the guest happens to shutdown, this memory * won't be valid. In cases like kexec, in which you install a new kernel, this * means a random memory location will be kept being written. */ #ifdef CONFIG_KEXEC_CORE static void kvm_crash_shutdown(struct pt_regs *regs) { kvm_guest_cpu_offline(true); native_machine_crash_shutdown(regs); } #endif #if defined(CONFIG_X86_32) || !defined(CONFIG_SMP) bool __kvm_vcpu_is_preempted(long cpu); __visible bool __kvm_vcpu_is_preempted(long cpu) { struct kvm_steal_time *src = &per_cpu(steal_time, cpu); return !!(src->preempted & KVM_VCPU_PREEMPTED); } PV_CALLEE_SAVE_REGS_THUNK(__kvm_vcpu_is_preempted); #else #include <asm/asm-offsets.h> extern bool __raw_callee_save___kvm_vcpu_is_preempted(long); /* * Hand-optimize version for x86-64 to avoid 8 64-bit register saving and * restoring to/from the stack. */ #define PV_VCPU_PREEMPTED_ASM \ "movq __per_cpu_offset(,%rdi,8), %rax\n\t" \ "cmpb $0, " __stringify(KVM_STEAL_TIME_preempted) "+steal_time(%rax)\n\t" \ "setne %al\n\t" DEFINE_PARAVIRT_ASM(__raw_callee_save___kvm_vcpu_is_preempted, PV_VCPU_PREEMPTED_ASM, .text); #endif static void __init kvm_guest_init(void) { int i; paravirt_ops_setup(); register_reboot_notifier(&kvm_pv_reboot_nb); for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) raw_spin_lock_init(&async_pf_sleepers[i].lock); if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) { has_steal_clock = 1; static_call_update(pv_steal_clock, kvm_steal_clock); pv_ops.lock.vcpu_is_preempted = PV_CALLEE_SAVE(__kvm_vcpu_is_preempted); } if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) apic_update_callback(eoi, kvm_guest_apic_eoi_write); if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) { static_branch_enable(&kvm_async_pf_enabled); alloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_kvm_asyncpf_interrupt); } #ifdef CONFIG_SMP if (pv_tlb_flush_supported()) { pv_ops.mmu.flush_tlb_multi = kvm_flush_tlb_multi; pv_ops.mmu.tlb_remove_table = tlb_remove_table; pr_info("KVM setup pv remote TLB flush\n"); } smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu; if (pv_sched_yield_supported()) { smp_ops.send_call_func_ipi = kvm_smp_send_call_func_ipi; pr_info("setup PV sched yield\n"); } if (cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "x86/kvm:online", kvm_cpu_online, kvm_cpu_down_prepare) < 0) pr_err("failed to install cpu hotplug callbacks\n"); #else sev_map_percpu_data(); kvm_guest_cpu_init(); #endif #ifdef CONFIG_KEXEC_CORE machine_ops.crash_shutdown = kvm_crash_shutdown; #endif register_syscore_ops(&kvm_syscore_ops); /* * Hard lockup detection is enabled by default. Disable it, as guests * can get false positives too easily, for example if the host is * overcommitted. */ hardlockup_detector_disable(); } static noinline uint32_t __kvm_cpuid_base(void) { if (boot_cpu_data.cpuid_level < 0) return 0; /* So we don't blow up on old processors */ if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) return hypervisor_cpuid_base(KVM_SIGNATURE, 0); return 0; } static inline uint32_t kvm_cpuid_base(void) { static int kvm_cpuid_base = -1; if (kvm_cpuid_base == -1) kvm_cpuid_base = __kvm_cpuid_base(); return kvm_cpuid_base; } bool kvm_para_available(void) { return kvm_cpuid_base() != 0; } EXPORT_SYMBOL_GPL(kvm_para_available); unsigned int kvm_arch_para_features(void) { return cpuid_eax(kvm_cpuid_base() | KVM_CPUID_FEATURES); } unsigned int kvm_arch_para_hints(void) { return cpuid_edx(kvm_cpuid_base() | KVM_CPUID_FEATURES); } EXPORT_SYMBOL_GPL(kvm_arch_para_hints); static uint32_t __init kvm_detect(void) { return kvm_cpuid_base(); } static void __init kvm_apic_init(void) { #ifdef CONFIG_SMP if (pv_ipi_supported()) kvm_setup_pv_ipi(); #endif } static bool __init kvm_msi_ext_dest_id(void) { return kvm_para_has_feature(KVM_FEATURE_MSI_EXT_DEST_ID); } static void kvm_sev_hc_page_enc_status(unsigned long pfn, int npages, bool enc) { kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, pfn << PAGE_SHIFT, npages, KVM_MAP_GPA_RANGE_ENC_STAT(enc) | KVM_MAP_GPA_RANGE_PAGE_SZ_4K); } static void __init kvm_init_platform(void) { if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) && kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) { unsigned long nr_pages; int i; pv_ops.mmu.notify_page_enc_status_changed = kvm_sev_hc_page_enc_status; /* * Reset the host's shared pages list related to kernel * specific page encryption status settings before we load a * new kernel by kexec. Reset the page encryption status * during early boot intead of just before kexec to avoid SMP * races during kvm_pv_guest_cpu_reboot(). * NOTE: We cannot reset the complete shared pages list * here as we need to retain the UEFI/OVMF firmware * specific settings. */ for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; if (entry->type != E820_TYPE_RAM) continue; nr_pages = DIV_ROUND_UP(entry->size, PAGE_SIZE); kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, entry->addr, nr_pages, KVM_MAP_GPA_RANGE_ENCRYPTED | KVM_MAP_GPA_RANGE_PAGE_SZ_4K); } /* * Ensure that _bss_decrypted section is marked as decrypted in the * shared pages list. */ early_set_mem_enc_dec_hypercall((unsigned long)__start_bss_decrypted, __end_bss_decrypted - __start_bss_decrypted, 0); /* * If not booted using EFI, enable Live migration support. */ if (!efi_enabled(EFI_BOOT)) wrmsrl(MSR_KVM_MIGRATION_CONTROL, KVM_MIGRATION_READY); } kvmclock_init(); x86_platform.apic_post_init = kvm_apic_init; } #if defined(CONFIG_AMD_MEM_ENCRYPT) static void kvm_sev_es_hcall_prepare(struct ghcb *ghcb, struct pt_regs *regs) { /* RAX and CPL are already in the GHCB */ ghcb_set_rbx(ghcb, regs->bx); ghcb_set_rcx(ghcb, regs->cx); ghcb_set_rdx(ghcb, regs->dx); ghcb_set_rsi(ghcb, regs->si); } static bool kvm_sev_es_hcall_finish(struct ghcb *ghcb, struct pt_regs *regs) { /* No checking of the return state needed */ return true; } #endif const __initconst struct hypervisor_x86 x86_hyper_kvm = { .name = "KVM", .detect = kvm_detect, .type = X86_HYPER_KVM, .init.guest_late_init = kvm_guest_init, .init.x2apic_available = kvm_para_available, .init.msi_ext_dest_id = kvm_msi_ext_dest_id, .init.init_platform = kvm_init_platform, #if defined(CONFIG_AMD_MEM_ENCRYPT) .runtime.sev_es_hcall_prepare = kvm_sev_es_hcall_prepare, .runtime.sev_es_hcall_finish = kvm_sev_es_hcall_finish, #endif }; static __init int activate_jump_labels(void) { if (has_steal_clock) { static_key_slow_inc(&paravirt_steal_enabled); if (steal_acc) static_key_slow_inc(&paravirt_steal_rq_enabled); } return 0; } arch_initcall(activate_jump_labels); #ifdef CONFIG_PARAVIRT_SPINLOCKS /* Kick a cpu by its apicid. Used to wake up a halted vcpu */ static void kvm_kick_cpu(int cpu) { int apicid; unsigned long flags = 0; apicid = per_cpu(x86_cpu_to_apicid, cpu); kvm_hypercall2(KVM_HC_KICK_CPU, flags, apicid); } #include <asm/qspinlock.h> static void kvm_wait(u8 *ptr, u8 val) { if (in_nmi()) return; /* * halt until it's our turn and kicked. Note that we do safe halt * for irq enabled case to avoid hang when lock info is overwritten * in irq spinlock slowpath and no spurious interrupt occur to save us. */ if (irqs_disabled()) { if (READ_ONCE(*ptr) == val) halt(); } else { local_irq_disable(); /* safe_halt() will enable IRQ */ if (READ_ONCE(*ptr) == val) safe_halt(); else local_irq_enable(); } } /* * Setup pv_lock_ops to exploit KVM_FEATURE_PV_UNHALT if present. */ void __init kvm_spinlock_init(void) { /* * In case host doesn't support KVM_FEATURE_PV_UNHALT there is still an * advantage of keeping virt_spin_lock_key enabled: virt_spin_lock() is * preferred over native qspinlock when vCPU is preempted. */ if (!kvm_para_has_feature(KVM_FEATURE_PV_UNHALT)) { pr_info("PV spinlocks disabled, no host support\n"); return; } /* * Disable PV spinlocks and use native qspinlock when dedicated pCPUs * are available. */ if (kvm_para_has_hint(KVM_HINTS_REALTIME)) { pr_info("PV spinlocks disabled with KVM_HINTS_REALTIME hints\n"); goto out; } if (num_possible_cpus() == 1) { pr_info("PV spinlocks disabled, single CPU\n"); goto out; } if (nopvspin) { pr_info("PV spinlocks disabled, forced by \"nopvspin\" parameter\n"); goto out; } pr_info("PV spinlocks enabled\n"); __pv_init_lock_hash(); pv_ops.lock.queued_spin_lock_slowpath = __pv_queued_spin_lock_slowpath; pv_ops.lock.queued_spin_unlock = PV_CALLEE_SAVE(__pv_queued_spin_unlock); pv_ops.lock.wait = kvm_wait; pv_ops.lock.kick = kvm_kick_cpu; /* * When PV spinlock is enabled which is preferred over * virt_spin_lock(), virt_spin_lock_key's value is meaningless. * Just disable it anyway. */ out: static_branch_disable(&virt_spin_lock_key); } #endif /* CONFIG_PARAVIRT_SPINLOCKS */ #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL static void kvm_disable_host_haltpoll(void *i) { wrmsrl(MSR_KVM_POLL_CONTROL, 0); } static void kvm_enable_host_haltpoll(void *i) { wrmsrl(MSR_KVM_POLL_CONTROL, 1); } void arch_haltpoll_enable(unsigned int cpu) { if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) { pr_err_once("host does not support poll control\n"); pr_err_once("host upgrade recommended\n"); return; } /* Enable guest halt poll disables host halt poll */ smp_call_function_single(cpu, kvm_disable_host_haltpoll, NULL, 1); } EXPORT_SYMBOL_GPL(arch_haltpoll_enable); void arch_haltpoll_disable(unsigned int cpu) { if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) return; /* Disable guest halt poll enables host halt poll */ smp_call_function_single(cpu, kvm_enable_host_haltpoll, NULL, 1); } EXPORT_SYMBOL_GPL(arch_haltpoll_disable); #endif
linux-master
arch/x86/kernel/kvm.c
// SPDX-License-Identifier: GPL-2.0 /* * linux/arch/i386/kernel/head32.c -- prepare to run common code * * Copyright (C) 2000 Andrea Arcangeli <[email protected]> SuSE * Copyright (C) 2007 Eric Biederman <[email protected]> */ #include <linux/init.h> #include <linux/start_kernel.h> #include <linux/mm.h> #include <linux/memblock.h> #include <asm/desc.h> #include <asm/setup.h> #include <asm/sections.h> #include <asm/e820/api.h> #include <asm/page.h> #include <asm/apic.h> #include <asm/io_apic.h> #include <asm/bios_ebda.h> #include <asm/tlbflush.h> #include <asm/bootparam_utils.h> static void __init i386_default_early_setup(void) { /* Initialize 32bit specific setup functions */ x86_init.resources.reserve_resources = i386_reserve_resources; x86_init.mpparse.setup_ioapic_ids = setup_ioapic_ids_from_mpc; } asmlinkage __visible void __init __noreturn i386_start_kernel(void) { /* Make sure IDT is set up before any exception happens */ idt_setup_early_handler(); cr4_init_shadow(); sanitize_boot_params(&boot_params); x86_early_init_platform_quirks(); /* Call the subarch specific early setup function */ switch (boot_params.hdr.hardware_subarch) { case X86_SUBARCH_INTEL_MID: x86_intel_mid_early_setup(); break; case X86_SUBARCH_CE4100: x86_ce4100_early_setup(); break; default: i386_default_early_setup(); break; } start_kernel(); } /* * Initialize page tables. This creates a PDE and a set of page * tables, which are located immediately beyond __brk_base. The variable * _brk_end is set up to point to the first "safe" location. * Mappings are created both at virtual address 0 (identity mapping) * and PAGE_OFFSET for up to _end. * * In PAE mode initial_page_table is statically defined to contain * enough entries to cover the VMSPLIT option (that is the top 1, 2 or 3 * entries). The identity mapping is handled by pointing two PGD entries * to the first kernel PMD. Note the upper half of each PMD or PTE are * always zero at this stage. */ void __init mk_early_pgtbl_32(void); void __init mk_early_pgtbl_32(void) { #ifdef __pa #undef __pa #endif #define __pa(x) ((unsigned long)(x) - PAGE_OFFSET) pte_t pte, *ptep; int i; unsigned long *ptr; /* Enough space to fit pagetables for the low memory linear map */ const unsigned long limit = __pa(_end) + (PAGE_TABLE_SIZE(LOWMEM_PAGES) << PAGE_SHIFT); #ifdef CONFIG_X86_PAE pmd_t pl2, *pl2p = (pmd_t *)__pa(initial_pg_pmd); #define SET_PL2(pl2, val) { (pl2).pmd = (val); } #else pgd_t pl2, *pl2p = (pgd_t *)__pa(initial_page_table); #define SET_PL2(pl2, val) { (pl2).pgd = (val); } #endif ptep = (pte_t *)__pa(__brk_base); pte.pte = PTE_IDENT_ATTR; while ((pte.pte & PTE_PFN_MASK) < limit) { SET_PL2(pl2, (unsigned long)ptep | PDE_IDENT_ATTR); *pl2p = pl2; #ifndef CONFIG_X86_PAE /* Kernel PDE entry */ *(pl2p + ((PAGE_OFFSET >> PGDIR_SHIFT))) = pl2; #endif for (i = 0; i < PTRS_PER_PTE; i++) { *ptep = pte; pte.pte += PAGE_SIZE; ptep++; } pl2p++; } ptr = (unsigned long *)__pa(&max_pfn_mapped); /* Can't use pte_pfn() since it's a call with CONFIG_PARAVIRT */ *ptr = (pte.pte & PTE_PFN_MASK) >> PAGE_SHIFT; ptr = (unsigned long *)__pa(&_brk_end); *ptr = (unsigned long)ptep + PAGE_OFFSET; }
linux-master
arch/x86/kernel/head32.c
// SPDX-License-Identifier: GPL-2.0 #ifndef __LINUX_KBUILD_H # error "Please do not build this file directly, build asm-offsets.c instead" #endif #include <linux/efi.h> #include <asm/ucontext.h> /* workaround for a warning with -Wmissing-prototypes */ void foo(void); void foo(void) { OFFSET(CPUINFO_x86, cpuinfo_x86, x86); OFFSET(CPUINFO_x86_vendor, cpuinfo_x86, x86_vendor); OFFSET(CPUINFO_x86_model, cpuinfo_x86, x86_model); OFFSET(CPUINFO_x86_stepping, cpuinfo_x86, x86_stepping); OFFSET(CPUINFO_cpuid_level, cpuinfo_x86, cpuid_level); OFFSET(CPUINFO_x86_capability, cpuinfo_x86, x86_capability); OFFSET(CPUINFO_x86_vendor_id, cpuinfo_x86, x86_vendor_id); BLANK(); OFFSET(PT_EBX, pt_regs, bx); OFFSET(PT_ECX, pt_regs, cx); OFFSET(PT_EDX, pt_regs, dx); OFFSET(PT_ESI, pt_regs, si); OFFSET(PT_EDI, pt_regs, di); OFFSET(PT_EBP, pt_regs, bp); OFFSET(PT_EAX, pt_regs, ax); OFFSET(PT_DS, pt_regs, ds); OFFSET(PT_ES, pt_regs, es); OFFSET(PT_FS, pt_regs, fs); OFFSET(PT_GS, pt_regs, gs); OFFSET(PT_ORIG_EAX, pt_regs, orig_ax); OFFSET(PT_EIP, pt_regs, ip); OFFSET(PT_CS, pt_regs, cs); OFFSET(PT_EFLAGS, pt_regs, flags); OFFSET(PT_OLDESP, pt_regs, sp); OFFSET(PT_OLDSS, pt_regs, ss); BLANK(); OFFSET(saved_context_gdt_desc, saved_context, gdt_desc); BLANK(); /* * Offset from the entry stack to task stack stored in TSS. Kernel entry * happens on the per-cpu entry-stack, and the asm code switches to the * task-stack pointer stored in x86_tss.sp1, which is a copy of * task->thread.sp0 where entry code can find it. */ DEFINE(TSS_entry2task_stack, offsetof(struct cpu_entry_area, tss.x86_tss.sp1) - offsetofend(struct cpu_entry_area, entry_stack_page.stack)); BLANK(); DEFINE(EFI_svam, offsetof(efi_runtime_services_t, set_virtual_address_map)); }
linux-master
arch/x86/kernel/asm-offsets_32.c
// SPDX-License-Identifier: GPL-2.0-only #define pr_fmt(fmt) "callthunks: " fmt #include <linux/debugfs.h> #include <linux/kallsyms.h> #include <linux/memory.h> #include <linux/moduleloader.h> #include <linux/static_call.h> #include <asm/alternative.h> #include <asm/asm-offsets.h> #include <asm/cpu.h> #include <asm/ftrace.h> #include <asm/insn.h> #include <asm/kexec.h> #include <asm/nospec-branch.h> #include <asm/paravirt.h> #include <asm/sections.h> #include <asm/switch_to.h> #include <asm/sync_core.h> #include <asm/text-patching.h> #include <asm/xen/hypercall.h> static int __initdata_or_module debug_callthunks; #define prdbg(fmt, args...) \ do { \ if (debug_callthunks) \ printk(KERN_DEBUG pr_fmt(fmt), ##args); \ } while(0) static int __init debug_thunks(char *str) { debug_callthunks = 1; return 1; } __setup("debug-callthunks", debug_thunks); #ifdef CONFIG_CALL_THUNKS_DEBUG DEFINE_PER_CPU(u64, __x86_call_count); DEFINE_PER_CPU(u64, __x86_ret_count); DEFINE_PER_CPU(u64, __x86_stuffs_count); DEFINE_PER_CPU(u64, __x86_ctxsw_count); EXPORT_SYMBOL_GPL(__x86_ctxsw_count); EXPORT_SYMBOL_GPL(__x86_call_count); #endif extern s32 __call_sites[], __call_sites_end[]; struct thunk_desc { void *template; unsigned int template_size; }; struct core_text { unsigned long base; unsigned long end; const char *name; }; static bool thunks_initialized __ro_after_init; static const struct core_text builtin_coretext = { .base = (unsigned long)_text, .end = (unsigned long)_etext, .name = "builtin", }; asm ( ".pushsection .rodata \n" ".global skl_call_thunk_template \n" "skl_call_thunk_template: \n" __stringify(INCREMENT_CALL_DEPTH)" \n" ".global skl_call_thunk_tail \n" "skl_call_thunk_tail: \n" ".popsection \n" ); extern u8 skl_call_thunk_template[]; extern u8 skl_call_thunk_tail[]; #define SKL_TMPL_SIZE \ ((unsigned int)(skl_call_thunk_tail - skl_call_thunk_template)) extern void error_entry(void); extern void xen_error_entry(void); extern void paranoid_entry(void); static inline bool within_coretext(const struct core_text *ct, void *addr) { unsigned long p = (unsigned long)addr; return ct->base <= p && p < ct->end; } static inline bool within_module_coretext(void *addr) { bool ret = false; #ifdef CONFIG_MODULES struct module *mod; preempt_disable(); mod = __module_address((unsigned long)addr); if (mod && within_module_core((unsigned long)addr, mod)) ret = true; preempt_enable(); #endif return ret; } static bool is_coretext(const struct core_text *ct, void *addr) { if (ct && within_coretext(ct, addr)) return true; if (within_coretext(&builtin_coretext, addr)) return true; return within_module_coretext(addr); } static bool skip_addr(void *dest) { if (dest == error_entry) return true; if (dest == paranoid_entry) return true; if (dest == xen_error_entry) return true; /* Does FILL_RSB... */ if (dest == __switch_to_asm) return true; /* Accounts directly */ if (dest == ret_from_fork) return true; #if defined(CONFIG_HOTPLUG_CPU) && defined(CONFIG_AMD_MEM_ENCRYPT) if (dest == soft_restart_cpu) return true; #endif #ifdef CONFIG_FUNCTION_TRACER if (dest == __fentry__) return true; #endif #ifdef CONFIG_KEXEC_CORE if (dest >= (void *)relocate_kernel && dest < (void*)relocate_kernel + KEXEC_CONTROL_CODE_MAX_SIZE) return true; #endif #ifdef CONFIG_XEN if (dest >= (void *)hypercall_page && dest < (void*)hypercall_page + PAGE_SIZE) return true; #endif return false; } static __init_or_module void *call_get_dest(void *addr) { struct insn insn; void *dest; int ret; ret = insn_decode_kernel(&insn, addr); if (ret) return ERR_PTR(ret); /* Patched out call? */ if (insn.opcode.bytes[0] != CALL_INSN_OPCODE) return NULL; dest = addr + insn.length + insn.immediate.value; if (skip_addr(dest)) return NULL; return dest; } static const u8 nops[] = { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, }; static void *patch_dest(void *dest, bool direct) { unsigned int tsize = SKL_TMPL_SIZE; u8 *pad = dest - tsize; /* Already patched? */ if (!bcmp(pad, skl_call_thunk_template, tsize)) return pad; /* Ensure there are nops */ if (bcmp(pad, nops, tsize)) { pr_warn_once("Invalid padding area for %pS\n", dest); return NULL; } if (direct) memcpy(pad, skl_call_thunk_template, tsize); else text_poke_copy_locked(pad, skl_call_thunk_template, tsize, true); return pad; } static __init_or_module void patch_call(void *addr, const struct core_text *ct) { void *pad, *dest; u8 bytes[8]; if (!within_coretext(ct, addr)) return; dest = call_get_dest(addr); if (!dest || WARN_ON_ONCE(IS_ERR(dest))) return; if (!is_coretext(ct, dest)) return; pad = patch_dest(dest, within_coretext(ct, dest)); if (!pad) return; prdbg("Patch call at: %pS %px to %pS %px -> %px \n", addr, addr, dest, dest, pad); __text_gen_insn(bytes, CALL_INSN_OPCODE, addr, pad, CALL_INSN_SIZE); text_poke_early(addr, bytes, CALL_INSN_SIZE); } static __init_or_module void patch_call_sites(s32 *start, s32 *end, const struct core_text *ct) { s32 *s; for (s = start; s < end; s++) patch_call((void *)s + *s, ct); } static __init_or_module void patch_paravirt_call_sites(struct paravirt_patch_site *start, struct paravirt_patch_site *end, const struct core_text *ct) { struct paravirt_patch_site *p; for (p = start; p < end; p++) patch_call(p->instr, ct); } static __init_or_module void callthunks_setup(struct callthunk_sites *cs, const struct core_text *ct) { prdbg("Patching call sites %s\n", ct->name); patch_call_sites(cs->call_start, cs->call_end, ct); patch_paravirt_call_sites(cs->pv_start, cs->pv_end, ct); prdbg("Patching call sites done%s\n", ct->name); } void __init callthunks_patch_builtin_calls(void) { struct callthunk_sites cs = { .call_start = __call_sites, .call_end = __call_sites_end, .pv_start = __parainstructions, .pv_end = __parainstructions_end }; if (!cpu_feature_enabled(X86_FEATURE_CALL_DEPTH)) return; pr_info("Setting up call depth tracking\n"); mutex_lock(&text_mutex); callthunks_setup(&cs, &builtin_coretext); thunks_initialized = true; mutex_unlock(&text_mutex); } void *callthunks_translate_call_dest(void *dest) { void *target; lockdep_assert_held(&text_mutex); if (!thunks_initialized || skip_addr(dest)) return dest; if (!is_coretext(NULL, dest)) return dest; target = patch_dest(dest, false); return target ? : dest; } #ifdef CONFIG_BPF_JIT static bool is_callthunk(void *addr) { unsigned int tmpl_size = SKL_TMPL_SIZE; void *tmpl = skl_call_thunk_template; unsigned long dest; dest = roundup((unsigned long)addr, CONFIG_FUNCTION_ALIGNMENT); if (!thunks_initialized || skip_addr((void *)dest)) return false; return !bcmp((void *)(dest - tmpl_size), tmpl, tmpl_size); } int x86_call_depth_emit_accounting(u8 **pprog, void *func) { unsigned int tmpl_size = SKL_TMPL_SIZE; void *tmpl = skl_call_thunk_template; if (!thunks_initialized) return 0; /* Is function call target a thunk? */ if (func && is_callthunk(func)) return 0; memcpy(*pprog, tmpl, tmpl_size); *pprog += tmpl_size; return tmpl_size; } #endif #ifdef CONFIG_MODULES void noinline callthunks_patch_module_calls(struct callthunk_sites *cs, struct module *mod) { struct core_text ct = { .base = (unsigned long)mod->mem[MOD_TEXT].base, .end = (unsigned long)mod->mem[MOD_TEXT].base + mod->mem[MOD_TEXT].size, .name = mod->name, }; if (!thunks_initialized) return; mutex_lock(&text_mutex); callthunks_setup(cs, &ct); mutex_unlock(&text_mutex); } #endif /* CONFIG_MODULES */ #if defined(CONFIG_CALL_THUNKS_DEBUG) && defined(CONFIG_DEBUG_FS) static int callthunks_debug_show(struct seq_file *m, void *p) { unsigned long cpu = (unsigned long)m->private; seq_printf(m, "C: %16llu R: %16llu S: %16llu X: %16llu\n,", per_cpu(__x86_call_count, cpu), per_cpu(__x86_ret_count, cpu), per_cpu(__x86_stuffs_count, cpu), per_cpu(__x86_ctxsw_count, cpu)); return 0; } static int callthunks_debug_open(struct inode *inode, struct file *file) { return single_open(file, callthunks_debug_show, inode->i_private); } static const struct file_operations dfs_ops = { .open = callthunks_debug_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int __init callthunks_debugfs_init(void) { struct dentry *dir; unsigned long cpu; dir = debugfs_create_dir("callthunks", NULL); for_each_possible_cpu(cpu) { void *arg = (void *)cpu; char name [10]; sprintf(name, "cpu%lu", cpu); debugfs_create_file(name, 0644, dir, arg, &dfs_ops); } return 0; } __initcall(callthunks_debugfs_init); #endif
linux-master
arch/x86/kernel/callthunks.c
// SPDX-License-Identifier: GPL-2.0 /* * 8253/PIT functions * */ #include <linux/clockchips.h> #include <linux/init.h> #include <linux/timex.h> #include <linux/i8253.h> #include <asm/apic.h> #include <asm/hpet.h> #include <asm/time.h> #include <asm/smp.h> /* * HPET replaces the PIT, when enabled. So we need to know, which of * the two timers is used */ struct clock_event_device *global_clock_event; /* * Modern chipsets can disable the PIT clock which makes it unusable. It * would be possible to enable the clock but the registers are chipset * specific and not discoverable. Avoid the whack a mole game. * * These platforms have discoverable TSC/CPU frequencies but this also * requires to know the local APIC timer frequency as it normally is * calibrated against the PIT interrupt. */ static bool __init use_pit(void) { if (!IS_ENABLED(CONFIG_X86_TSC) || !boot_cpu_has(X86_FEATURE_TSC)) return true; /* This also returns true when APIC is disabled */ return apic_needs_pit(); } bool __init pit_timer_init(void) { if (!use_pit()) return false; clockevent_i8253_init(true); global_clock_event = &i8253_clockevent; return true; } #ifndef CONFIG_X86_64 static int __init init_pit_clocksource(void) { /* * Several reasons not to register PIT as a clocksource: * * - On SMP PIT does not scale due to i8253_lock * - when HPET is enabled * - when local APIC timer is active (PIT is switched off) */ if (num_possible_cpus() > 1 || is_hpet_enabled() || !clockevent_state_periodic(&i8253_clockevent)) return 0; return clocksource_i8253_init(); } arch_initcall(init_pit_clocksource); #endif /* !CONFIG_X86_64 */
linux-master
arch/x86/kernel/i8253.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/linkage.h> #include <linux/errno.h> #include <linux/signal.h> #include <linux/sched.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/timex.h> #include <linux/random.h> #include <linux/init.h> #include <linux/kernel_stat.h> #include <linux/syscore_ops.h> #include <linux/bitops.h> #include <linux/acpi.h> #include <linux/io.h> #include <linux/delay.h> #include <linux/pgtable.h> #include <linux/atomic.h> #include <asm/timer.h> #include <asm/hw_irq.h> #include <asm/desc.h> #include <asm/apic.h> #include <asm/i8259.h> /* * This is the 'legacy' 8259A Programmable Interrupt Controller, * present in the majority of PC/AT boxes. * plus some generic x86 specific things if generic specifics makes * any sense at all. */ static void init_8259A(int auto_eoi); static int i8259A_auto_eoi; DEFINE_RAW_SPINLOCK(i8259A_lock); /* * 8259A PIC functions to handle ISA devices: */ /* * This contains the irq mask for both 8259A irq controllers, */ unsigned int cached_irq_mask = 0xffff; /* * Not all IRQs can be routed through the IO-APIC, eg. on certain (older) * boards the timer interrupt is not really connected to any IO-APIC pin, * it's fed to the master 8259A's IR0 line only. * * Any '1' bit in this mask means the IRQ is routed through the IO-APIC. * this 'mixed mode' IRQ handling costs nothing because it's only used * at IRQ setup time. */ unsigned long io_apic_irqs; static void mask_8259A_irq(unsigned int irq) { unsigned int mask = 1 << irq; unsigned long flags; raw_spin_lock_irqsave(&i8259A_lock, flags); cached_irq_mask |= mask; if (irq & 8) outb(cached_slave_mask, PIC_SLAVE_IMR); else outb(cached_master_mask, PIC_MASTER_IMR); raw_spin_unlock_irqrestore(&i8259A_lock, flags); } static void disable_8259A_irq(struct irq_data *data) { mask_8259A_irq(data->irq); } static void unmask_8259A_irq(unsigned int irq) { unsigned int mask = ~(1 << irq); unsigned long flags; raw_spin_lock_irqsave(&i8259A_lock, flags); cached_irq_mask &= mask; if (irq & 8) outb(cached_slave_mask, PIC_SLAVE_IMR); else outb(cached_master_mask, PIC_MASTER_IMR); raw_spin_unlock_irqrestore(&i8259A_lock, flags); } static void enable_8259A_irq(struct irq_data *data) { unmask_8259A_irq(data->irq); } static int i8259A_irq_pending(unsigned int irq) { unsigned int mask = 1<<irq; unsigned long flags; int ret; raw_spin_lock_irqsave(&i8259A_lock, flags); if (irq < 8) ret = inb(PIC_MASTER_CMD) & mask; else ret = inb(PIC_SLAVE_CMD) & (mask >> 8); raw_spin_unlock_irqrestore(&i8259A_lock, flags); return ret; } static void make_8259A_irq(unsigned int irq) { disable_irq_nosync(irq); io_apic_irqs &= ~(1<<irq); irq_set_chip_and_handler(irq, &i8259A_chip, handle_level_irq); irq_set_status_flags(irq, IRQ_LEVEL); enable_irq(irq); lapic_assign_legacy_vector(irq, true); } /* * This function assumes to be called rarely. Switching between * 8259A registers is slow. * This has to be protected by the irq controller spinlock * before being called. */ static inline int i8259A_irq_real(unsigned int irq) { int value; int irqmask = 1<<irq; if (irq < 8) { outb(0x0B, PIC_MASTER_CMD); /* ISR register */ value = inb(PIC_MASTER_CMD) & irqmask; outb(0x0A, PIC_MASTER_CMD); /* back to the IRR register */ return value; } outb(0x0B, PIC_SLAVE_CMD); /* ISR register */ value = inb(PIC_SLAVE_CMD) & (irqmask >> 8); outb(0x0A, PIC_SLAVE_CMD); /* back to the IRR register */ return value; } /* * Careful! The 8259A is a fragile beast, it pretty * much _has_ to be done exactly like this (mask it * first, _then_ send the EOI, and the order of EOI * to the two 8259s is important! */ static void mask_and_ack_8259A(struct irq_data *data) { unsigned int irq = data->irq; unsigned int irqmask = 1 << irq; unsigned long flags; raw_spin_lock_irqsave(&i8259A_lock, flags); /* * Lightweight spurious IRQ detection. We do not want * to overdo spurious IRQ handling - it's usually a sign * of hardware problems, so we only do the checks we can * do without slowing down good hardware unnecessarily. * * Note that IRQ7 and IRQ15 (the two spurious IRQs * usually resulting from the 8259A-1|2 PICs) occur * even if the IRQ is masked in the 8259A. Thus we * can check spurious 8259A IRQs without doing the * quite slow i8259A_irq_real() call for every IRQ. * This does not cover 100% of spurious interrupts, * but should be enough to warn the user that there * is something bad going on ... */ if (cached_irq_mask & irqmask) goto spurious_8259A_irq; cached_irq_mask |= irqmask; handle_real_irq: if (irq & 8) { inb(PIC_SLAVE_IMR); /* DUMMY - (do we need this?) */ outb(cached_slave_mask, PIC_SLAVE_IMR); /* 'Specific EOI' to slave */ outb(0x60+(irq&7), PIC_SLAVE_CMD); /* 'Specific EOI' to master-IRQ2 */ outb(0x60+PIC_CASCADE_IR, PIC_MASTER_CMD); } else { inb(PIC_MASTER_IMR); /* DUMMY - (do we need this?) */ outb(cached_master_mask, PIC_MASTER_IMR); outb(0x60+irq, PIC_MASTER_CMD); /* 'Specific EOI to master */ } raw_spin_unlock_irqrestore(&i8259A_lock, flags); return; spurious_8259A_irq: /* * this is the slow path - should happen rarely. */ if (i8259A_irq_real(irq)) /* * oops, the IRQ _is_ in service according to the * 8259A - not spurious, go handle it. */ goto handle_real_irq; { static int spurious_irq_mask; /* * At this point we can be sure the IRQ is spurious, * lets ACK and report it. [once per IRQ] */ if (!(spurious_irq_mask & irqmask)) { printk_deferred(KERN_DEBUG "spurious 8259A interrupt: IRQ%d.\n", irq); spurious_irq_mask |= irqmask; } atomic_inc(&irq_err_count); /* * Theoretically we do not have to handle this IRQ, * but in Linux this does not cause problems and is * simpler for us. */ goto handle_real_irq; } } struct irq_chip i8259A_chip = { .name = "XT-PIC", .irq_mask = disable_8259A_irq, .irq_disable = disable_8259A_irq, .irq_unmask = enable_8259A_irq, .irq_mask_ack = mask_and_ack_8259A, }; static char irq_trigger[2]; /* ELCR registers (0x4d0, 0x4d1) control edge/level of IRQ */ static void restore_ELCR(char *trigger) { outb(trigger[0], PIC_ELCR1); outb(trigger[1], PIC_ELCR2); } static void save_ELCR(char *trigger) { /* IRQ 0,1,2,8,13 are marked as reserved */ trigger[0] = inb(PIC_ELCR1) & 0xF8; trigger[1] = inb(PIC_ELCR2) & 0xDE; } static void i8259A_resume(void) { init_8259A(i8259A_auto_eoi); restore_ELCR(irq_trigger); } static int i8259A_suspend(void) { save_ELCR(irq_trigger); return 0; } static void i8259A_shutdown(void) { /* Put the i8259A into a quiescent state that * the kernel initialization code can get it * out of. */ outb(0xff, PIC_MASTER_IMR); /* mask all of 8259A-1 */ outb(0xff, PIC_SLAVE_IMR); /* mask all of 8259A-2 */ } static struct syscore_ops i8259_syscore_ops = { .suspend = i8259A_suspend, .resume = i8259A_resume, .shutdown = i8259A_shutdown, }; static void mask_8259A(void) { unsigned long flags; raw_spin_lock_irqsave(&i8259A_lock, flags); outb(0xff, PIC_MASTER_IMR); /* mask all of 8259A-1 */ outb(0xff, PIC_SLAVE_IMR); /* mask all of 8259A-2 */ raw_spin_unlock_irqrestore(&i8259A_lock, flags); } static void unmask_8259A(void) { unsigned long flags; raw_spin_lock_irqsave(&i8259A_lock, flags); outb(cached_master_mask, PIC_MASTER_IMR); /* restore master IRQ mask */ outb(cached_slave_mask, PIC_SLAVE_IMR); /* restore slave IRQ mask */ raw_spin_unlock_irqrestore(&i8259A_lock, flags); } static int probe_8259A(void) { unsigned long flags; unsigned char probe_val = ~(1 << PIC_CASCADE_IR); unsigned char new_val; /* * Check to see if we have a PIC. * Mask all except the cascade and read * back the value we just wrote. If we don't * have a PIC, we will read 0xff as opposed to the * value we wrote. */ raw_spin_lock_irqsave(&i8259A_lock, flags); outb(0xff, PIC_SLAVE_IMR); /* mask all of 8259A-2 */ outb(probe_val, PIC_MASTER_IMR); new_val = inb(PIC_MASTER_IMR); if (new_val != probe_val) { printk(KERN_INFO "Using NULL legacy PIC\n"); legacy_pic = &null_legacy_pic; } raw_spin_unlock_irqrestore(&i8259A_lock, flags); return nr_legacy_irqs(); } static void init_8259A(int auto_eoi) { unsigned long flags; i8259A_auto_eoi = auto_eoi; raw_spin_lock_irqsave(&i8259A_lock, flags); outb(0xff, PIC_MASTER_IMR); /* mask all of 8259A-1 */ /* * outb_pic - this has to work on a wide range of PC hardware. */ outb_pic(0x11, PIC_MASTER_CMD); /* ICW1: select 8259A-1 init */ /* ICW2: 8259A-1 IR0-7 mapped to ISA_IRQ_VECTOR(0) */ outb_pic(ISA_IRQ_VECTOR(0), PIC_MASTER_IMR); /* 8259A-1 (the master) has a slave on IR2 */ outb_pic(1U << PIC_CASCADE_IR, PIC_MASTER_IMR); if (auto_eoi) /* master does Auto EOI */ outb_pic(MASTER_ICW4_DEFAULT | PIC_ICW4_AEOI, PIC_MASTER_IMR); else /* master expects normal EOI */ outb_pic(MASTER_ICW4_DEFAULT, PIC_MASTER_IMR); outb_pic(0x11, PIC_SLAVE_CMD); /* ICW1: select 8259A-2 init */ /* ICW2: 8259A-2 IR0-7 mapped to ISA_IRQ_VECTOR(8) */ outb_pic(ISA_IRQ_VECTOR(8), PIC_SLAVE_IMR); /* 8259A-2 is a slave on master's IR2 */ outb_pic(PIC_CASCADE_IR, PIC_SLAVE_IMR); /* (slave's support for AEOI in flat mode is to be investigated) */ outb_pic(SLAVE_ICW4_DEFAULT, PIC_SLAVE_IMR); if (auto_eoi) /* * In AEOI mode we just have to mask the interrupt * when acking. */ i8259A_chip.irq_mask_ack = disable_8259A_irq; else i8259A_chip.irq_mask_ack = mask_and_ack_8259A; udelay(100); /* wait for 8259A to initialize */ outb(cached_master_mask, PIC_MASTER_IMR); /* restore master IRQ mask */ outb(cached_slave_mask, PIC_SLAVE_IMR); /* restore slave IRQ mask */ raw_spin_unlock_irqrestore(&i8259A_lock, flags); } /* * make i8259 a driver so that we can select pic functions at run time. the goal * is to make x86 binary compatible among pc compatible and non-pc compatible * platforms, such as x86 MID. */ static void legacy_pic_noop(void) { }; static void legacy_pic_uint_noop(unsigned int unused) { }; static void legacy_pic_int_noop(int unused) { }; static int legacy_pic_irq_pending_noop(unsigned int irq) { return 0; } static int legacy_pic_probe(void) { return 0; } struct legacy_pic null_legacy_pic = { .nr_legacy_irqs = 0, .chip = &dummy_irq_chip, .mask = legacy_pic_uint_noop, .unmask = legacy_pic_uint_noop, .mask_all = legacy_pic_noop, .restore_mask = legacy_pic_noop, .init = legacy_pic_int_noop, .probe = legacy_pic_probe, .irq_pending = legacy_pic_irq_pending_noop, .make_irq = legacy_pic_uint_noop, }; static struct legacy_pic default_legacy_pic = { .nr_legacy_irqs = NR_IRQS_LEGACY, .chip = &i8259A_chip, .mask = mask_8259A_irq, .unmask = unmask_8259A_irq, .mask_all = mask_8259A, .restore_mask = unmask_8259A, .init = init_8259A, .probe = probe_8259A, .irq_pending = i8259A_irq_pending, .make_irq = make_8259A_irq, }; struct legacy_pic *legacy_pic = &default_legacy_pic; EXPORT_SYMBOL(legacy_pic); static int __init i8259A_init_ops(void) { if (legacy_pic == &default_legacy_pic) register_syscore_ops(&i8259_syscore_ops); return 0; } device_initcall(i8259A_init_ops);
linux-master
arch/x86/kernel/i8259.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/dma-map-ops.h> #include <linux/dma-direct.h> #include <linux/iommu.h> #include <linux/dmar.h> #include <linux/export.h> #include <linux/memblock.h> #include <linux/gfp.h> #include <linux/pci.h> #include <linux/amd-iommu.h> #include <asm/proto.h> #include <asm/dma.h> #include <asm/iommu.h> #include <asm/gart.h> #include <asm/x86_init.h> #include <xen/xen.h> #include <xen/swiotlb-xen.h> static bool disable_dac_quirk __read_mostly; const struct dma_map_ops *dma_ops; EXPORT_SYMBOL(dma_ops); #ifdef CONFIG_IOMMU_DEBUG int panic_on_overflow __read_mostly = 1; int force_iommu __read_mostly = 1; #else int panic_on_overflow __read_mostly = 0; int force_iommu __read_mostly = 0; #endif int iommu_merge __read_mostly = 0; int no_iommu __read_mostly; /* Set this to 1 if there is a HW IOMMU in the system */ int iommu_detected __read_mostly = 0; #ifdef CONFIG_SWIOTLB bool x86_swiotlb_enable; static unsigned int x86_swiotlb_flags; static void __init pci_swiotlb_detect(void) { /* don't initialize swiotlb if iommu=off (no_iommu=1) */ if (!no_iommu && max_possible_pfn > MAX_DMA32_PFN) x86_swiotlb_enable = true; /* * Set swiotlb to 1 so that bounce buffers are allocated and used for * devices that can't support DMA to encrypted memory. */ if (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT)) x86_swiotlb_enable = true; /* * Guest with guest memory encryption currently perform all DMA through * bounce buffers as the hypervisor can't access arbitrary VM memory * that is not explicitly shared with it. */ if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) { x86_swiotlb_enable = true; x86_swiotlb_flags |= SWIOTLB_FORCE; } } #else static inline void __init pci_swiotlb_detect(void) { } #define x86_swiotlb_flags 0 #endif /* CONFIG_SWIOTLB */ #ifdef CONFIG_SWIOTLB_XEN static bool xen_swiotlb_enabled(void) { return xen_initial_domain() || x86_swiotlb_enable || (IS_ENABLED(CONFIG_XEN_PCIDEV_FRONTEND) && xen_pv_pci_possible); } static void __init pci_xen_swiotlb_init(void) { if (!xen_swiotlb_enabled()) return; x86_swiotlb_enable = true; x86_swiotlb_flags |= SWIOTLB_ANY; swiotlb_init_remap(true, x86_swiotlb_flags, xen_swiotlb_fixup); dma_ops = &xen_swiotlb_dma_ops; if (IS_ENABLED(CONFIG_PCI)) pci_request_acs(); } #else static inline void __init pci_xen_swiotlb_init(void) { } #endif /* CONFIG_SWIOTLB_XEN */ void __init pci_iommu_alloc(void) { if (xen_pv_domain()) { pci_xen_swiotlb_init(); return; } pci_swiotlb_detect(); gart_iommu_hole_init(); amd_iommu_detect(); detect_intel_iommu(); swiotlb_init(x86_swiotlb_enable, x86_swiotlb_flags); } /* * See <Documentation/arch/x86/x86_64/boot-options.rst> for the iommu kernel * parameter documentation. */ static __init int iommu_setup(char *p) { iommu_merge = 1; if (!p) return -EINVAL; while (*p) { if (!strncmp(p, "off", 3)) no_iommu = 1; /* gart_parse_options has more force support */ if (!strncmp(p, "force", 5)) force_iommu = 1; if (!strncmp(p, "noforce", 7)) { iommu_merge = 0; force_iommu = 0; } if (!strncmp(p, "biomerge", 8)) { iommu_merge = 1; force_iommu = 1; } if (!strncmp(p, "panic", 5)) panic_on_overflow = 1; if (!strncmp(p, "nopanic", 7)) panic_on_overflow = 0; if (!strncmp(p, "merge", 5)) { iommu_merge = 1; force_iommu = 1; } if (!strncmp(p, "nomerge", 7)) iommu_merge = 0; if (!strncmp(p, "forcesac", 8)) pr_warn("forcesac option ignored.\n"); if (!strncmp(p, "allowdac", 8)) pr_warn("allowdac option ignored.\n"); if (!strncmp(p, "nodac", 5)) pr_warn("nodac option ignored.\n"); if (!strncmp(p, "usedac", 6)) { disable_dac_quirk = true; return 1; } #ifdef CONFIG_SWIOTLB if (!strncmp(p, "soft", 4)) x86_swiotlb_enable = true; #endif if (!strncmp(p, "pt", 2)) iommu_set_default_passthrough(true); if (!strncmp(p, "nopt", 4)) iommu_set_default_translated(true); gart_parse_options(p); p += strcspn(p, ","); if (*p == ',') ++p; } return 0; } early_param("iommu", iommu_setup); static int __init pci_iommu_init(void) { x86_init.iommu.iommu_init(); #ifdef CONFIG_SWIOTLB /* An IOMMU turned us off. */ if (x86_swiotlb_enable) { pr_info("PCI-DMA: Using software bounce buffering for IO (SWIOTLB)\n"); swiotlb_print_info(); } else { swiotlb_exit(); } #endif return 0; } /* Must execute after PCI subsystem */ rootfs_initcall(pci_iommu_init); #ifdef CONFIG_PCI /* Many VIA bridges seem to corrupt data for DAC. Disable it here */ static int via_no_dac_cb(struct pci_dev *pdev, void *data) { pdev->dev.bus_dma_limit = DMA_BIT_MASK(32); return 0; } static void via_no_dac(struct pci_dev *dev) { if (!disable_dac_quirk) { dev_info(&dev->dev, "disabling DAC on VIA PCI bridge\n"); pci_walk_bus(dev->subordinate, via_no_dac_cb, NULL); } } DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_VIA, PCI_ANY_ID, PCI_CLASS_BRIDGE_PCI, 8, via_no_dac); #endif
linux-master
arch/x86/kernel/pci-dma.c
// SPDX-License-Identifier: GPL-2.0 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/errno.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/cpu.h> #include <linux/prctl.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/idle.h> #include <linux/sched/debug.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/init.h> #include <linux/export.h> #include <linux/pm.h> #include <linux/tick.h> #include <linux/random.h> #include <linux/user-return-notifier.h> #include <linux/dmi.h> #include <linux/utsname.h> #include <linux/stackprotector.h> #include <linux/cpuidle.h> #include <linux/acpi.h> #include <linux/elf-randomize.h> #include <linux/static_call.h> #include <trace/events/power.h> #include <linux/hw_breakpoint.h> #include <linux/entry-common.h> #include <asm/cpu.h> #include <asm/apic.h> #include <linux/uaccess.h> #include <asm/mwait.h> #include <asm/fpu/api.h> #include <asm/fpu/sched.h> #include <asm/fpu/xstate.h> #include <asm/debugreg.h> #include <asm/nmi.h> #include <asm/tlbflush.h> #include <asm/mce.h> #include <asm/vm86.h> #include <asm/switch_to.h> #include <asm/desc.h> #include <asm/prctl.h> #include <asm/spec-ctrl.h> #include <asm/io_bitmap.h> #include <asm/proto.h> #include <asm/frame.h> #include <asm/unwind.h> #include <asm/tdx.h> #include <asm/mmu_context.h> #include <asm/shstk.h> #include "process.h" /* * per-CPU TSS segments. Threads are completely 'soft' on Linux, * no more per-task TSS's. The TSS size is kept cacheline-aligned * so they are allowed to end up in the .data..cacheline_aligned * section. Since TSS's are completely CPU-local, we want them * on exact cacheline boundaries, to eliminate cacheline ping-pong. */ __visible DEFINE_PER_CPU_PAGE_ALIGNED(struct tss_struct, cpu_tss_rw) = { .x86_tss = { /* * .sp0 is only used when entering ring 0 from a lower * privilege level. Since the init task never runs anything * but ring 0 code, there is no need for a valid value here. * Poison it. */ .sp0 = (1UL << (BITS_PER_LONG-1)) + 1, #ifdef CONFIG_X86_32 .sp1 = TOP_OF_INIT_STACK, .ss0 = __KERNEL_DS, .ss1 = __KERNEL_CS, #endif .io_bitmap_base = IO_BITMAP_OFFSET_INVALID, }, }; EXPORT_PER_CPU_SYMBOL(cpu_tss_rw); DEFINE_PER_CPU(bool, __tss_limit_invalid); EXPORT_PER_CPU_SYMBOL_GPL(__tss_limit_invalid); /* * this gets called so that we can store lazy state into memory and copy the * current task into the new thread. */ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { memcpy(dst, src, arch_task_struct_size); #ifdef CONFIG_VM86 dst->thread.vm86 = NULL; #endif /* Drop the copied pointer to current's fpstate */ dst->thread.fpu.fpstate = NULL; return 0; } #ifdef CONFIG_X86_64 void arch_release_task_struct(struct task_struct *tsk) { if (fpu_state_size_dynamic()) fpstate_free(&tsk->thread.fpu); } #endif /* * Free thread data structures etc.. */ void exit_thread(struct task_struct *tsk) { struct thread_struct *t = &tsk->thread; struct fpu *fpu = &t->fpu; if (test_thread_flag(TIF_IO_BITMAP)) io_bitmap_exit(tsk); free_vm86(t); shstk_free(tsk); fpu__drop(fpu); } static int set_new_tls(struct task_struct *p, unsigned long tls) { struct user_desc __user *utls = (struct user_desc __user *)tls; if (in_ia32_syscall()) return do_set_thread_area(p, -1, utls, 0); else return do_set_thread_area_64(p, ARCH_SET_FS, tls); } __visible void ret_from_fork(struct task_struct *prev, struct pt_regs *regs, int (*fn)(void *), void *fn_arg) { schedule_tail(prev); /* Is this a kernel thread? */ if (unlikely(fn)) { fn(fn_arg); /* * A kernel thread is allowed to return here after successfully * calling kernel_execve(). Exit to userspace to complete the * execve() syscall. */ regs->ax = 0; } syscall_exit_to_user_mode(regs); } int copy_thread(struct task_struct *p, const struct kernel_clone_args *args) { unsigned long clone_flags = args->flags; unsigned long sp = args->stack; unsigned long tls = args->tls; struct inactive_task_frame *frame; struct fork_frame *fork_frame; struct pt_regs *childregs; unsigned long new_ssp; int ret = 0; childregs = task_pt_regs(p); fork_frame = container_of(childregs, struct fork_frame, regs); frame = &fork_frame->frame; frame->bp = encode_frame_pointer(childregs); frame->ret_addr = (unsigned long) ret_from_fork_asm; p->thread.sp = (unsigned long) fork_frame; p->thread.io_bitmap = NULL; p->thread.iopl_warn = 0; memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps)); #ifdef CONFIG_X86_64 current_save_fsgs(); p->thread.fsindex = current->thread.fsindex; p->thread.fsbase = current->thread.fsbase; p->thread.gsindex = current->thread.gsindex; p->thread.gsbase = current->thread.gsbase; savesegment(es, p->thread.es); savesegment(ds, p->thread.ds); if (p->mm && (clone_flags & (CLONE_VM | CLONE_VFORK)) == CLONE_VM) set_bit(MM_CONTEXT_LOCK_LAM, &p->mm->context.flags); #else p->thread.sp0 = (unsigned long) (childregs + 1); savesegment(gs, p->thread.gs); /* * Clear all status flags including IF and set fixed bit. 64bit * does not have this initialization as the frame does not contain * flags. The flags consistency (especially vs. AC) is there * ensured via objtool, which lacks 32bit support. */ frame->flags = X86_EFLAGS_FIXED; #endif /* * Allocate a new shadow stack for thread if needed. If shadow stack, * is disabled, new_ssp will remain 0, and fpu_clone() will know not to * update it. */ new_ssp = shstk_alloc_thread_stack(p, clone_flags, args->stack_size); if (IS_ERR_VALUE(new_ssp)) return PTR_ERR((void *)new_ssp); fpu_clone(p, clone_flags, args->fn, new_ssp); /* Kernel thread ? */ if (unlikely(p->flags & PF_KTHREAD)) { p->thread.pkru = pkru_get_init_value(); memset(childregs, 0, sizeof(struct pt_regs)); kthread_frame_init(frame, args->fn, args->fn_arg); return 0; } /* * Clone current's PKRU value from hardware. tsk->thread.pkru * is only valid when scheduled out. */ p->thread.pkru = read_pkru(); frame->bx = 0; *childregs = *current_pt_regs(); childregs->ax = 0; if (sp) childregs->sp = sp; if (unlikely(args->fn)) { /* * A user space thread, but it doesn't return to * ret_after_fork(). * * In order to indicate that to tools like gdb, * we reset the stack and instruction pointers. * * It does the same kernel frame setup to return to a kernel * function that a kernel thread does. */ childregs->sp = 0; childregs->ip = 0; kthread_frame_init(frame, args->fn, args->fn_arg); return 0; } /* Set a new TLS for the child thread? */ if (clone_flags & CLONE_SETTLS) ret = set_new_tls(p, tls); if (!ret && unlikely(test_tsk_thread_flag(current, TIF_IO_BITMAP))) io_bitmap_share(p); return ret; } static void pkru_flush_thread(void) { /* * If PKRU is enabled the default PKRU value has to be loaded into * the hardware right here (similar to context switch). */ pkru_write_default(); } void flush_thread(void) { struct task_struct *tsk = current; flush_ptrace_hw_breakpoint(tsk); memset(tsk->thread.tls_array, 0, sizeof(tsk->thread.tls_array)); fpu_flush_thread(); pkru_flush_thread(); } void disable_TSC(void) { preempt_disable(); if (!test_and_set_thread_flag(TIF_NOTSC)) /* * Must flip the CPU state synchronously with * TIF_NOTSC in the current running context. */ cr4_set_bits(X86_CR4_TSD); preempt_enable(); } static void enable_TSC(void) { preempt_disable(); if (test_and_clear_thread_flag(TIF_NOTSC)) /* * Must flip the CPU state synchronously with * TIF_NOTSC in the current running context. */ cr4_clear_bits(X86_CR4_TSD); preempt_enable(); } int get_tsc_mode(unsigned long adr) { unsigned int val; if (test_thread_flag(TIF_NOTSC)) val = PR_TSC_SIGSEGV; else val = PR_TSC_ENABLE; return put_user(val, (unsigned int __user *)adr); } int set_tsc_mode(unsigned int val) { if (val == PR_TSC_SIGSEGV) disable_TSC(); else if (val == PR_TSC_ENABLE) enable_TSC(); else return -EINVAL; return 0; } DEFINE_PER_CPU(u64, msr_misc_features_shadow); static void set_cpuid_faulting(bool on) { u64 msrval; msrval = this_cpu_read(msr_misc_features_shadow); msrval &= ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT; msrval |= (on << MSR_MISC_FEATURES_ENABLES_CPUID_FAULT_BIT); this_cpu_write(msr_misc_features_shadow, msrval); wrmsrl(MSR_MISC_FEATURES_ENABLES, msrval); } static void disable_cpuid(void) { preempt_disable(); if (!test_and_set_thread_flag(TIF_NOCPUID)) { /* * Must flip the CPU state synchronously with * TIF_NOCPUID in the current running context. */ set_cpuid_faulting(true); } preempt_enable(); } static void enable_cpuid(void) { preempt_disable(); if (test_and_clear_thread_flag(TIF_NOCPUID)) { /* * Must flip the CPU state synchronously with * TIF_NOCPUID in the current running context. */ set_cpuid_faulting(false); } preempt_enable(); } static int get_cpuid_mode(void) { return !test_thread_flag(TIF_NOCPUID); } static int set_cpuid_mode(unsigned long cpuid_enabled) { if (!boot_cpu_has(X86_FEATURE_CPUID_FAULT)) return -ENODEV; if (cpuid_enabled) enable_cpuid(); else disable_cpuid(); return 0; } /* * Called immediately after a successful exec. */ void arch_setup_new_exec(void) { /* If cpuid was previously disabled for this task, re-enable it. */ if (test_thread_flag(TIF_NOCPUID)) enable_cpuid(); /* * Don't inherit TIF_SSBD across exec boundary when * PR_SPEC_DISABLE_NOEXEC is used. */ if (test_thread_flag(TIF_SSBD) && task_spec_ssb_noexec(current)) { clear_thread_flag(TIF_SSBD); task_clear_spec_ssb_disable(current); task_clear_spec_ssb_noexec(current); speculation_ctrl_update(read_thread_flags()); } mm_reset_untag_mask(current->mm); } #ifdef CONFIG_X86_IOPL_IOPERM static inline void switch_to_bitmap(unsigned long tifp) { /* * Invalidate I/O bitmap if the previous task used it. This prevents * any possible leakage of an active I/O bitmap. * * If the next task has an I/O bitmap it will handle it on exit to * user mode. */ if (tifp & _TIF_IO_BITMAP) tss_invalidate_io_bitmap(); } static void tss_copy_io_bitmap(struct tss_struct *tss, struct io_bitmap *iobm) { /* * Copy at least the byte range of the incoming tasks bitmap which * covers the permitted I/O ports. * * If the previous task which used an I/O bitmap had more bits * permitted, then the copy needs to cover those as well so they * get turned off. */ memcpy(tss->io_bitmap.bitmap, iobm->bitmap, max(tss->io_bitmap.prev_max, iobm->max)); /* * Store the new max and the sequence number of this bitmap * and a pointer to the bitmap itself. */ tss->io_bitmap.prev_max = iobm->max; tss->io_bitmap.prev_sequence = iobm->sequence; } /** * native_tss_update_io_bitmap - Update I/O bitmap before exiting to user mode */ void native_tss_update_io_bitmap(void) { struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw); struct thread_struct *t = &current->thread; u16 *base = &tss->x86_tss.io_bitmap_base; if (!test_thread_flag(TIF_IO_BITMAP)) { native_tss_invalidate_io_bitmap(); return; } if (IS_ENABLED(CONFIG_X86_IOPL_IOPERM) && t->iopl_emul == 3) { *base = IO_BITMAP_OFFSET_VALID_ALL; } else { struct io_bitmap *iobm = t->io_bitmap; /* * Only copy bitmap data when the sequence number differs. The * update time is accounted to the incoming task. */ if (tss->io_bitmap.prev_sequence != iobm->sequence) tss_copy_io_bitmap(tss, iobm); /* Enable the bitmap */ *base = IO_BITMAP_OFFSET_VALID_MAP; } /* * Make sure that the TSS limit is covering the IO bitmap. It might have * been cut down by a VMEXIT to 0x67 which would cause a subsequent I/O * access from user space to trigger a #GP because tbe bitmap is outside * the TSS limit. */ refresh_tss_limit(); } #else /* CONFIG_X86_IOPL_IOPERM */ static inline void switch_to_bitmap(unsigned long tifp) { } #endif #ifdef CONFIG_SMP struct ssb_state { struct ssb_state *shared_state; raw_spinlock_t lock; unsigned int disable_state; unsigned long local_state; }; #define LSTATE_SSB 0 static DEFINE_PER_CPU(struct ssb_state, ssb_state); void speculative_store_bypass_ht_init(void) { struct ssb_state *st = this_cpu_ptr(&ssb_state); unsigned int this_cpu = smp_processor_id(); unsigned int cpu; st->local_state = 0; /* * Shared state setup happens once on the first bringup * of the CPU. It's not destroyed on CPU hotunplug. */ if (st->shared_state) return; raw_spin_lock_init(&st->lock); /* * Go over HT siblings and check whether one of them has set up the * shared state pointer already. */ for_each_cpu(cpu, topology_sibling_cpumask(this_cpu)) { if (cpu == this_cpu) continue; if (!per_cpu(ssb_state, cpu).shared_state) continue; /* Link it to the state of the sibling: */ st->shared_state = per_cpu(ssb_state, cpu).shared_state; return; } /* * First HT sibling to come up on the core. Link shared state of * the first HT sibling to itself. The siblings on the same core * which come up later will see the shared state pointer and link * themselves to the state of this CPU. */ st->shared_state = st; } /* * Logic is: First HT sibling enables SSBD for both siblings in the core * and last sibling to disable it, disables it for the whole core. This how * MSR_SPEC_CTRL works in "hardware": * * CORE_SPEC_CTRL = THREAD0_SPEC_CTRL | THREAD1_SPEC_CTRL */ static __always_inline void amd_set_core_ssb_state(unsigned long tifn) { struct ssb_state *st = this_cpu_ptr(&ssb_state); u64 msr = x86_amd_ls_cfg_base; if (!static_cpu_has(X86_FEATURE_ZEN)) { msr |= ssbd_tif_to_amd_ls_cfg(tifn); wrmsrl(MSR_AMD64_LS_CFG, msr); return; } if (tifn & _TIF_SSBD) { /* * Since this can race with prctl(), block reentry on the * same CPU. */ if (__test_and_set_bit(LSTATE_SSB, &st->local_state)) return; msr |= x86_amd_ls_cfg_ssbd_mask; raw_spin_lock(&st->shared_state->lock); /* First sibling enables SSBD: */ if (!st->shared_state->disable_state) wrmsrl(MSR_AMD64_LS_CFG, msr); st->shared_state->disable_state++; raw_spin_unlock(&st->shared_state->lock); } else { if (!__test_and_clear_bit(LSTATE_SSB, &st->local_state)) return; raw_spin_lock(&st->shared_state->lock); st->shared_state->disable_state--; if (!st->shared_state->disable_state) wrmsrl(MSR_AMD64_LS_CFG, msr); raw_spin_unlock(&st->shared_state->lock); } } #else static __always_inline void amd_set_core_ssb_state(unsigned long tifn) { u64 msr = x86_amd_ls_cfg_base | ssbd_tif_to_amd_ls_cfg(tifn); wrmsrl(MSR_AMD64_LS_CFG, msr); } #endif static __always_inline void amd_set_ssb_virt_state(unsigned long tifn) { /* * SSBD has the same definition in SPEC_CTRL and VIRT_SPEC_CTRL, * so ssbd_tif_to_spec_ctrl() just works. */ wrmsrl(MSR_AMD64_VIRT_SPEC_CTRL, ssbd_tif_to_spec_ctrl(tifn)); } /* * Update the MSRs managing speculation control, during context switch. * * tifp: Previous task's thread flags * tifn: Next task's thread flags */ static __always_inline void __speculation_ctrl_update(unsigned long tifp, unsigned long tifn) { unsigned long tif_diff = tifp ^ tifn; u64 msr = x86_spec_ctrl_base; bool updmsr = false; lockdep_assert_irqs_disabled(); /* Handle change of TIF_SSBD depending on the mitigation method. */ if (static_cpu_has(X86_FEATURE_VIRT_SSBD)) { if (tif_diff & _TIF_SSBD) amd_set_ssb_virt_state(tifn); } else if (static_cpu_has(X86_FEATURE_LS_CFG_SSBD)) { if (tif_diff & _TIF_SSBD) amd_set_core_ssb_state(tifn); } else if (static_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) || static_cpu_has(X86_FEATURE_AMD_SSBD)) { updmsr |= !!(tif_diff & _TIF_SSBD); msr |= ssbd_tif_to_spec_ctrl(tifn); } /* Only evaluate TIF_SPEC_IB if conditional STIBP is enabled. */ if (IS_ENABLED(CONFIG_SMP) && static_branch_unlikely(&switch_to_cond_stibp)) { updmsr |= !!(tif_diff & _TIF_SPEC_IB); msr |= stibp_tif_to_spec_ctrl(tifn); } if (updmsr) update_spec_ctrl_cond(msr); } static unsigned long speculation_ctrl_update_tif(struct task_struct *tsk) { if (test_and_clear_tsk_thread_flag(tsk, TIF_SPEC_FORCE_UPDATE)) { if (task_spec_ssb_disable(tsk)) set_tsk_thread_flag(tsk, TIF_SSBD); else clear_tsk_thread_flag(tsk, TIF_SSBD); if (task_spec_ib_disable(tsk)) set_tsk_thread_flag(tsk, TIF_SPEC_IB); else clear_tsk_thread_flag(tsk, TIF_SPEC_IB); } /* Return the updated threadinfo flags*/ return read_task_thread_flags(tsk); } void speculation_ctrl_update(unsigned long tif) { unsigned long flags; /* Forced update. Make sure all relevant TIF flags are different */ local_irq_save(flags); __speculation_ctrl_update(~tif, tif); local_irq_restore(flags); } /* Called from seccomp/prctl update */ void speculation_ctrl_update_current(void) { preempt_disable(); speculation_ctrl_update(speculation_ctrl_update_tif(current)); preempt_enable(); } static inline void cr4_toggle_bits_irqsoff(unsigned long mask) { unsigned long newval, cr4 = this_cpu_read(cpu_tlbstate.cr4); newval = cr4 ^ mask; if (newval != cr4) { this_cpu_write(cpu_tlbstate.cr4, newval); __write_cr4(newval); } } void __switch_to_xtra(struct task_struct *prev_p, struct task_struct *next_p) { unsigned long tifp, tifn; tifn = read_task_thread_flags(next_p); tifp = read_task_thread_flags(prev_p); switch_to_bitmap(tifp); propagate_user_return_notify(prev_p, next_p); if ((tifp & _TIF_BLOCKSTEP || tifn & _TIF_BLOCKSTEP) && arch_has_block_step()) { unsigned long debugctl, msk; rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); debugctl &= ~DEBUGCTLMSR_BTF; msk = tifn & _TIF_BLOCKSTEP; debugctl |= (msk >> TIF_BLOCKSTEP) << DEBUGCTLMSR_BTF_SHIFT; wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); } if ((tifp ^ tifn) & _TIF_NOTSC) cr4_toggle_bits_irqsoff(X86_CR4_TSD); if ((tifp ^ tifn) & _TIF_NOCPUID) set_cpuid_faulting(!!(tifn & _TIF_NOCPUID)); if (likely(!((tifp | tifn) & _TIF_SPEC_FORCE_UPDATE))) { __speculation_ctrl_update(tifp, tifn); } else { speculation_ctrl_update_tif(prev_p); tifn = speculation_ctrl_update_tif(next_p); /* Enforce MSR update to ensure consistent state */ __speculation_ctrl_update(~tifn, tifn); } } /* * Idle related variables and functions */ unsigned long boot_option_idle_override = IDLE_NO_OVERRIDE; EXPORT_SYMBOL(boot_option_idle_override); /* * We use this if we don't have any better idle routine.. */ void __cpuidle default_idle(void) { raw_safe_halt(); raw_local_irq_disable(); } #if defined(CONFIG_APM_MODULE) || defined(CONFIG_HALTPOLL_CPUIDLE_MODULE) EXPORT_SYMBOL(default_idle); #endif DEFINE_STATIC_CALL_NULL(x86_idle, default_idle); static bool x86_idle_set(void) { return !!static_call_query(x86_idle); } #ifndef CONFIG_SMP static inline void __noreturn play_dead(void) { BUG(); } #endif void arch_cpu_idle_enter(void) { tsc_verify_tsc_adjust(false); local_touch_nmi(); } void __noreturn arch_cpu_idle_dead(void) { play_dead(); } /* * Called from the generic idle code. */ void __cpuidle arch_cpu_idle(void) { static_call(x86_idle)(); } EXPORT_SYMBOL_GPL(arch_cpu_idle); #ifdef CONFIG_XEN bool xen_set_default_idle(void) { bool ret = x86_idle_set(); static_call_update(x86_idle, default_idle); return ret; } #endif struct cpumask cpus_stop_mask; void __noreturn stop_this_cpu(void *dummy) { struct cpuinfo_x86 *c = this_cpu_ptr(&cpu_info); unsigned int cpu = smp_processor_id(); local_irq_disable(); /* * Remove this CPU from the online mask and disable it * unconditionally. This might be redundant in case that the reboot * vector was handled late and stop_other_cpus() sent an NMI. * * According to SDM and APM NMIs can be accepted even after soft * disabling the local APIC. */ set_cpu_online(cpu, false); disable_local_APIC(); mcheck_cpu_clear(c); /* * Use wbinvd on processors that support SME. This provides support * for performing a successful kexec when going from SME inactive * to SME active (or vice-versa). The cache must be cleared so that * if there are entries with the same physical address, both with and * without the encryption bit, they don't race each other when flushed * and potentially end up with the wrong entry being committed to * memory. * * Test the CPUID bit directly because the machine might've cleared * X86_FEATURE_SME due to cmdline options. */ if (c->extended_cpuid_level >= 0x8000001f && (cpuid_eax(0x8000001f) & BIT(0))) native_wbinvd(); /* * This brings a cache line back and dirties it, but * native_stop_other_cpus() will overwrite cpus_stop_mask after it * observed that all CPUs reported stop. This write will invalidate * the related cache line on this CPU. */ cpumask_clear_cpu(cpu, &cpus_stop_mask); for (;;) { /* * Use native_halt() so that memory contents don't change * (stack usage and variables) after possibly issuing the * native_wbinvd() above. */ native_halt(); } } /* * AMD Erratum 400 aware idle routine. We handle it the same way as C3 power * states (local apic timer and TSC stop). * * XXX this function is completely buggered vs RCU and tracing. */ static void amd_e400_idle(void) { /* * We cannot use static_cpu_has_bug() here because X86_BUG_AMD_APIC_C1E * gets set after static_cpu_has() places have been converted via * alternatives. */ if (!boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) { default_idle(); return; } tick_broadcast_enter(); default_idle(); tick_broadcast_exit(); } /* * Prefer MWAIT over HALT if MWAIT is supported, MWAIT_CPUID leaf * exists and whenever MONITOR/MWAIT extensions are present there is at * least one C1 substate. * * Do not prefer MWAIT if MONITOR instruction has a bug or idle=nomwait * is passed to kernel commandline parameter. */ static int prefer_mwait_c1_over_halt(const struct cpuinfo_x86 *c) { u32 eax, ebx, ecx, edx; /* User has disallowed the use of MWAIT. Fallback to HALT */ if (boot_option_idle_override == IDLE_NOMWAIT) return 0; /* MWAIT is not supported on this platform. Fallback to HALT */ if (!cpu_has(c, X86_FEATURE_MWAIT)) return 0; /* Monitor has a bug. Fallback to HALT */ if (boot_cpu_has_bug(X86_BUG_MONITOR)) return 0; cpuid(CPUID_MWAIT_LEAF, &eax, &ebx, &ecx, &edx); /* * If MWAIT extensions are not available, it is safe to use MWAIT * with EAX=0, ECX=0. */ if (!(ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED)) return 1; /* * If MWAIT extensions are available, there should be at least one * MWAIT C1 substate present. */ return (edx & MWAIT_C1_SUBSTATE_MASK); } /* * MONITOR/MWAIT with no hints, used for default C1 state. This invokes MWAIT * with interrupts enabled and no flags, which is backwards compatible with the * original MWAIT implementation. */ static __cpuidle void mwait_idle(void) { if (!current_set_polling_and_test()) { if (this_cpu_has(X86_BUG_CLFLUSH_MONITOR)) { mb(); /* quirk */ clflush((void *)&current_thread_info()->flags); mb(); /* quirk */ } __monitor((void *)&current_thread_info()->flags, 0, 0); if (!need_resched()) { __sti_mwait(0, 0); raw_local_irq_disable(); } } __current_clr_polling(); } void select_idle_routine(const struct cpuinfo_x86 *c) { #ifdef CONFIG_SMP if (boot_option_idle_override == IDLE_POLL && smp_num_siblings > 1) pr_warn_once("WARNING: polling idle and HT enabled, performance may degrade\n"); #endif if (x86_idle_set() || boot_option_idle_override == IDLE_POLL) return; if (boot_cpu_has_bug(X86_BUG_AMD_E400)) { pr_info("using AMD E400 aware idle routine\n"); static_call_update(x86_idle, amd_e400_idle); } else if (prefer_mwait_c1_over_halt(c)) { pr_info("using mwait in idle threads\n"); static_call_update(x86_idle, mwait_idle); } else if (cpu_feature_enabled(X86_FEATURE_TDX_GUEST)) { pr_info("using TDX aware idle routine\n"); static_call_update(x86_idle, tdx_safe_halt); } else static_call_update(x86_idle, default_idle); } void amd_e400_c1e_apic_setup(void) { if (boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) { pr_info("Switch to broadcast mode on CPU%d\n", smp_processor_id()); local_irq_disable(); tick_broadcast_force(); local_irq_enable(); } } void __init arch_post_acpi_subsys_init(void) { u32 lo, hi; if (!boot_cpu_has_bug(X86_BUG_AMD_E400)) return; /* * AMD E400 detection needs to happen after ACPI has been enabled. If * the machine is affected K8_INTP_C1E_ACTIVE_MASK bits are set in * MSR_K8_INT_PENDING_MSG. */ rdmsr(MSR_K8_INT_PENDING_MSG, lo, hi); if (!(lo & K8_INTP_C1E_ACTIVE_MASK)) return; boot_cpu_set_bug(X86_BUG_AMD_APIC_C1E); if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC)) mark_tsc_unstable("TSC halt in AMD C1E"); pr_info("System has AMD C1E enabled\n"); } static int __init idle_setup(char *str) { if (!str) return -EINVAL; if (!strcmp(str, "poll")) { pr_info("using polling idle threads\n"); boot_option_idle_override = IDLE_POLL; cpu_idle_poll_ctrl(true); } else if (!strcmp(str, "halt")) { /* * When the boot option of idle=halt is added, halt is * forced to be used for CPU idle. In such case CPU C2/C3 * won't be used again. * To continue to load the CPU idle driver, don't touch * the boot_option_idle_override. */ static_call_update(x86_idle, default_idle); boot_option_idle_override = IDLE_HALT; } else if (!strcmp(str, "nomwait")) { /* * If the boot option of "idle=nomwait" is added, * it means that mwait will be disabled for CPU C1/C2/C3 * states. */ boot_option_idle_override = IDLE_NOMWAIT; } else return -1; return 0; } early_param("idle", idle_setup); unsigned long arch_align_stack(unsigned long sp) { if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space) sp -= get_random_u32_below(8192); return sp & ~0xf; } unsigned long arch_randomize_brk(struct mm_struct *mm) { return randomize_page(mm->brk, 0x02000000); } /* * Called from fs/proc with a reference on @p to find the function * which called into schedule(). This needs to be done carefully * because the task might wake up and we might look at a stack * changing under us. */ unsigned long __get_wchan(struct task_struct *p) { struct unwind_state state; unsigned long addr = 0; if (!try_get_task_stack(p)) return 0; for (unwind_start(&state, p, NULL, NULL); !unwind_done(&state); unwind_next_frame(&state)) { addr = unwind_get_return_address(&state); if (!addr) break; if (in_sched_functions(addr)) continue; break; } put_task_stack(p); return addr; } long do_arch_prctl_common(int option, unsigned long arg2) { switch (option) { case ARCH_GET_CPUID: return get_cpuid_mode(); case ARCH_SET_CPUID: return set_cpuid_mode(arg2); case ARCH_GET_XCOMP_SUPP: case ARCH_GET_XCOMP_PERM: case ARCH_REQ_XCOMP_PERM: case ARCH_GET_XCOMP_GUEST_PERM: case ARCH_REQ_XCOMP_GUEST_PERM: return fpu_xstate_prctl(option, arg2); } return -EINVAL; }
linux-master
arch/x86/kernel/process.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2015, Christoph Hellwig. * Copyright (c) 2015, Intel Corporation. */ #include <linux/platform_device.h> #include <linux/init.h> #include <linux/ioport.h> static int found(struct resource *res, void *data) { return 1; } static __init int register_e820_pmem(void) { struct platform_device *pdev; int rc; rc = walk_iomem_res_desc(IORES_DESC_PERSISTENT_MEMORY_LEGACY, IORESOURCE_MEM, 0, -1, NULL, found); if (rc <= 0) return 0; /* * See drivers/nvdimm/e820.c for the implementation, this is * simply here to trigger the module to load on demand. */ pdev = platform_device_alloc("e820_pmem", -1); rc = platform_device_add(pdev); if (rc) platform_device_put(pdev); return rc; } device_initcall(register_e820_pmem);
linux-master
arch/x86/kernel/pmem.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * x86 SMP booting functions * * (c) 1995 Alan Cox, Building #3 <[email protected]> * (c) 1998, 1999, 2000, 2009 Ingo Molnar <[email protected]> * Copyright 2001 Andi Kleen, SuSE Labs. * * Much of the core SMP work is based on previous work by Thomas Radke, to * whom a great many thanks are extended. * * Thanks to Intel for making available several different Pentium, * Pentium Pro and Pentium-II/Xeon MP machines. * Original development of Linux SMP code supported by Caldera. * * Fixes * Felix Koop : NR_CPUS used properly * Jose Renau : Handle single CPU case. * Alan Cox : By repeated request 8) - Total BogoMIPS report. * Greg Wright : Fix for kernel stacks panic. * Erich Boleyn : MP v1.4 and additional changes. * Matthias Sattler : Changes for 2.1 kernel map. * Michel Lespinasse : Changes for 2.1 kernel map. * Michael Chastain : Change trampoline.S to gnu as. * Alan Cox : Dumb bug: 'B' step PPro's are fine * Ingo Molnar : Added APIC timers, based on code * from Jose Renau * Ingo Molnar : various cleanups and rewrites * Tigran Aivazian : fixed "0.00 in /proc/uptime on SMP" bug. * Maciej W. Rozycki : Bits for genuine 82489DX APICs * Andi Kleen : Changed for SMP boot into long mode. * Martin J. Bligh : Added support for multi-quad systems * Dave Jones : Report invalid combinations of Athlon CPUs. * Rusty Russell : Hacked into shape for new "hotplug" boot process. * Andi Kleen : Converted to new state machine. * Ashok Raj : CPU hotplug support * Glauber Costa : i386 and x86_64 integration */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/init.h> #include <linux/smp.h> #include <linux/export.h> #include <linux/sched.h> #include <linux/sched/topology.h> #include <linux/sched/hotplug.h> #include <linux/sched/task_stack.h> #include <linux/percpu.h> #include <linux/memblock.h> #include <linux/err.h> #include <linux/nmi.h> #include <linux/tboot.h> #include <linux/gfp.h> #include <linux/cpuidle.h> #include <linux/kexec.h> #include <linux/numa.h> #include <linux/pgtable.h> #include <linux/overflow.h> #include <linux/stackprotector.h> #include <linux/cpuhotplug.h> #include <linux/mc146818rtc.h> #include <asm/acpi.h> #include <asm/cacheinfo.h> #include <asm/desc.h> #include <asm/nmi.h> #include <asm/irq.h> #include <asm/realmode.h> #include <asm/cpu.h> #include <asm/numa.h> #include <asm/tlbflush.h> #include <asm/mtrr.h> #include <asm/mwait.h> #include <asm/apic.h> #include <asm/io_apic.h> #include <asm/fpu/api.h> #include <asm/setup.h> #include <asm/uv/uv.h> #include <asm/microcode.h> #include <asm/i8259.h> #include <asm/misc.h> #include <asm/qspinlock.h> #include <asm/intel-family.h> #include <asm/cpu_device_id.h> #include <asm/spec-ctrl.h> #include <asm/hw_irq.h> #include <asm/stackprotector.h> #include <asm/sev.h> /* representing HT siblings of each logical CPU */ DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_sibling_map); EXPORT_PER_CPU_SYMBOL(cpu_sibling_map); /* representing HT and core siblings of each logical CPU */ DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_core_map); EXPORT_PER_CPU_SYMBOL(cpu_core_map); /* representing HT, core, and die siblings of each logical CPU */ DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_die_map); EXPORT_PER_CPU_SYMBOL(cpu_die_map); /* Per CPU bogomips and other parameters */ DEFINE_PER_CPU_READ_MOSTLY(struct cpuinfo_x86, cpu_info); EXPORT_PER_CPU_SYMBOL(cpu_info); /* CPUs which are the primary SMT threads */ struct cpumask __cpu_primary_thread_mask __read_mostly; /* Representing CPUs for which sibling maps can be computed */ static cpumask_var_t cpu_sibling_setup_mask; struct mwait_cpu_dead { unsigned int control; unsigned int status; }; #define CPUDEAD_MWAIT_WAIT 0xDEADBEEF #define CPUDEAD_MWAIT_KEXEC_HLT 0x4A17DEAD /* * Cache line aligned data for mwait_play_dead(). Separate on purpose so * that it's unlikely to be touched by other CPUs. */ static DEFINE_PER_CPU_ALIGNED(struct mwait_cpu_dead, mwait_cpu_dead); /* Logical package management. We might want to allocate that dynamically */ unsigned int __max_logical_packages __read_mostly; EXPORT_SYMBOL(__max_logical_packages); static unsigned int logical_packages __read_mostly; static unsigned int logical_die __read_mostly; /* Maximum number of SMT threads on any online core */ int __read_mostly __max_smt_threads = 1; /* Flag to indicate if a complete sched domain rebuild is required */ bool x86_topology_update; int arch_update_cpu_topology(void) { int retval = x86_topology_update; x86_topology_update = false; return retval; } static unsigned int smpboot_warm_reset_vector_count; static inline void smpboot_setup_warm_reset_vector(unsigned long start_eip) { unsigned long flags; spin_lock_irqsave(&rtc_lock, flags); if (!smpboot_warm_reset_vector_count++) { CMOS_WRITE(0xa, 0xf); *((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_HIGH)) = start_eip >> 4; *((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) = start_eip & 0xf; } spin_unlock_irqrestore(&rtc_lock, flags); } static inline void smpboot_restore_warm_reset_vector(void) { unsigned long flags; /* * Paranoid: Set warm reset code and vector here back * to default values. */ spin_lock_irqsave(&rtc_lock, flags); if (!--smpboot_warm_reset_vector_count) { CMOS_WRITE(0, 0xf); *((volatile u32 *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) = 0; } spin_unlock_irqrestore(&rtc_lock, flags); } /* Run the next set of setup steps for the upcoming CPU */ static void ap_starting(void) { int cpuid = smp_processor_id(); /* Mop up eventual mwait_play_dead() wreckage */ this_cpu_write(mwait_cpu_dead.status, 0); this_cpu_write(mwait_cpu_dead.control, 0); /* * If woken up by an INIT in an 82489DX configuration the alive * synchronization guarantees that the CPU does not reach this * point before an INIT_deassert IPI reaches the local APIC, so it * is now safe to touch the local APIC. * * Set up this CPU, first the APIC, which is probably redundant on * most boards. */ apic_ap_setup(); /* Save the processor parameters. */ smp_store_cpu_info(cpuid); /* * The topology information must be up to date before * notify_cpu_starting(). */ set_cpu_sibling_map(cpuid); ap_init_aperfmperf(); pr_debug("Stack at about %p\n", &cpuid); wmb(); /* * This runs the AP through all the cpuhp states to its target * state CPUHP_ONLINE. */ notify_cpu_starting(cpuid); } static void ap_calibrate_delay(void) { /* * Calibrate the delay loop and update loops_per_jiffy in cpu_data. * smp_store_cpu_info() stored a value that is close but not as * accurate as the value just calculated. * * As this is invoked after the TSC synchronization check, * calibrate_delay_is_known() will skip the calibration routine * when TSC is synchronized across sockets. */ calibrate_delay(); cpu_data(smp_processor_id()).loops_per_jiffy = loops_per_jiffy; } /* * Activate a secondary processor. */ static void notrace start_secondary(void *unused) { /* * Don't put *anything* except direct CPU state initialization * before cpu_init(), SMP booting is too fragile that we want to * limit the things done here to the most necessary things. */ cr4_init(); /* * 32-bit specific. 64-bit reaches this code with the correct page * table established. Yet another historical divergence. */ if (IS_ENABLED(CONFIG_X86_32)) { /* switch away from the initial page table */ load_cr3(swapper_pg_dir); __flush_tlb_all(); } cpu_init_exception_handling(); /* * 32-bit systems load the microcode from the ASM startup code for * historical reasons. * * On 64-bit systems load it before reaching the AP alive * synchronization point below so it is not part of the full per * CPU serialized bringup part when "parallel" bringup is enabled. * * That's even safe when hyperthreading is enabled in the CPU as * the core code starts the primary threads first and leaves the * secondary threads waiting for SIPI. Loading microcode on * physical cores concurrently is a safe operation. * * This covers both the Intel specific issue that concurrent * microcode loading on SMT siblings must be prohibited and the * vendor independent issue`that microcode loading which changes * CPUID, MSRs etc. must be strictly serialized to maintain * software state correctness. */ if (IS_ENABLED(CONFIG_X86_64)) load_ucode_ap(); /* * Synchronization point with the hotplug core. Sets this CPUs * synchronization state to ALIVE and spin-waits for the control CPU to * release this CPU for further bringup. */ cpuhp_ap_sync_alive(); cpu_init(); fpu__init_cpu(); rcu_cpu_starting(raw_smp_processor_id()); x86_cpuinit.early_percpu_clock_init(); ap_starting(); /* Check TSC synchronization with the control CPU. */ check_tsc_sync_target(); /* * Calibrate the delay loop after the TSC synchronization check. * This allows to skip the calibration when TSC is synchronized * across sockets. */ ap_calibrate_delay(); speculative_store_bypass_ht_init(); /* * Lock vector_lock, set CPU online and bring the vector * allocator online. Online must be set with vector_lock held * to prevent a concurrent irq setup/teardown from seeing a * half valid vector space. */ lock_vector_lock(); set_cpu_online(smp_processor_id(), true); lapic_online(); unlock_vector_lock(); x86_platform.nmi_init(); /* enable local interrupts */ local_irq_enable(); x86_cpuinit.setup_percpu_clockev(); wmb(); cpu_startup_entry(CPUHP_AP_ONLINE_IDLE); } /** * topology_phys_to_logical_pkg - Map a physical package id to a logical * @phys_pkg: The physical package id to map * * Returns logical package id or -1 if not found */ int topology_phys_to_logical_pkg(unsigned int phys_pkg) { int cpu; for_each_possible_cpu(cpu) { struct cpuinfo_x86 *c = &cpu_data(cpu); if (c->initialized && c->phys_proc_id == phys_pkg) return c->logical_proc_id; } return -1; } EXPORT_SYMBOL(topology_phys_to_logical_pkg); /** * topology_phys_to_logical_die - Map a physical die id to logical * @die_id: The physical die id to map * @cur_cpu: The CPU for which the mapping is done * * Returns logical die id or -1 if not found */ static int topology_phys_to_logical_die(unsigned int die_id, unsigned int cur_cpu) { int cpu, proc_id = cpu_data(cur_cpu).phys_proc_id; for_each_possible_cpu(cpu) { struct cpuinfo_x86 *c = &cpu_data(cpu); if (c->initialized && c->cpu_die_id == die_id && c->phys_proc_id == proc_id) return c->logical_die_id; } return -1; } /** * topology_update_package_map - Update the physical to logical package map * @pkg: The physical package id as retrieved via CPUID * @cpu: The cpu for which this is updated */ int topology_update_package_map(unsigned int pkg, unsigned int cpu) { int new; /* Already available somewhere? */ new = topology_phys_to_logical_pkg(pkg); if (new >= 0) goto found; new = logical_packages++; if (new != pkg) { pr_info("CPU %u Converting physical %u to logical package %u\n", cpu, pkg, new); } found: cpu_data(cpu).logical_proc_id = new; return 0; } /** * topology_update_die_map - Update the physical to logical die map * @die: The die id as retrieved via CPUID * @cpu: The cpu for which this is updated */ int topology_update_die_map(unsigned int die, unsigned int cpu) { int new; /* Already available somewhere? */ new = topology_phys_to_logical_die(die, cpu); if (new >= 0) goto found; new = logical_die++; if (new != die) { pr_info("CPU %u Converting physical %u to logical die %u\n", cpu, die, new); } found: cpu_data(cpu).logical_die_id = new; return 0; } static void __init smp_store_boot_cpu_info(void) { int id = 0; /* CPU 0 */ struct cpuinfo_x86 *c = &cpu_data(id); *c = boot_cpu_data; c->cpu_index = id; topology_update_package_map(c->phys_proc_id, id); topology_update_die_map(c->cpu_die_id, id); c->initialized = true; } /* * The bootstrap kernel entry code has set these up. Save them for * a given CPU */ void smp_store_cpu_info(int id) { struct cpuinfo_x86 *c = &cpu_data(id); /* Copy boot_cpu_data only on the first bringup */ if (!c->initialized) *c = boot_cpu_data; c->cpu_index = id; /* * During boot time, CPU0 has this setup already. Save the info when * bringing up an AP. */ identify_secondary_cpu(c); c->initialized = true; } static bool topology_same_node(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o) { int cpu1 = c->cpu_index, cpu2 = o->cpu_index; return (cpu_to_node(cpu1) == cpu_to_node(cpu2)); } static bool topology_sane(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o, const char *name) { int cpu1 = c->cpu_index, cpu2 = o->cpu_index; return !WARN_ONCE(!topology_same_node(c, o), "sched: CPU #%d's %s-sibling CPU #%d is not on the same node! " "[node: %d != %d]. Ignoring dependency.\n", cpu1, name, cpu2, cpu_to_node(cpu1), cpu_to_node(cpu2)); } #define link_mask(mfunc, c1, c2) \ do { \ cpumask_set_cpu((c1), mfunc(c2)); \ cpumask_set_cpu((c2), mfunc(c1)); \ } while (0) static bool match_smt(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o) { if (boot_cpu_has(X86_FEATURE_TOPOEXT)) { int cpu1 = c->cpu_index, cpu2 = o->cpu_index; if (c->phys_proc_id == o->phys_proc_id && c->cpu_die_id == o->cpu_die_id && per_cpu(cpu_llc_id, cpu1) == per_cpu(cpu_llc_id, cpu2)) { if (c->cpu_core_id == o->cpu_core_id) return topology_sane(c, o, "smt"); if ((c->cu_id != 0xff) && (o->cu_id != 0xff) && (c->cu_id == o->cu_id)) return topology_sane(c, o, "smt"); } } else if (c->phys_proc_id == o->phys_proc_id && c->cpu_die_id == o->cpu_die_id && c->cpu_core_id == o->cpu_core_id) { return topology_sane(c, o, "smt"); } return false; } static bool match_die(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o) { if (c->phys_proc_id == o->phys_proc_id && c->cpu_die_id == o->cpu_die_id) return true; return false; } static bool match_l2c(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o) { int cpu1 = c->cpu_index, cpu2 = o->cpu_index; /* If the arch didn't set up l2c_id, fall back to SMT */ if (per_cpu(cpu_l2c_id, cpu1) == BAD_APICID) return match_smt(c, o); /* Do not match if L2 cache id does not match: */ if (per_cpu(cpu_l2c_id, cpu1) != per_cpu(cpu_l2c_id, cpu2)) return false; return topology_sane(c, o, "l2c"); } /* * Unlike the other levels, we do not enforce keeping a * multicore group inside a NUMA node. If this happens, we will * discard the MC level of the topology later. */ static bool match_pkg(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o) { if (c->phys_proc_id == o->phys_proc_id) return true; return false; } /* * Define intel_cod_cpu[] for Intel COD (Cluster-on-Die) CPUs. * * Any Intel CPU that has multiple nodes per package and does not * match intel_cod_cpu[] has the SNC (Sub-NUMA Cluster) topology. * * When in SNC mode, these CPUs enumerate an LLC that is shared * by multiple NUMA nodes. The LLC is shared for off-package data * access but private to the NUMA node (half of the package) for * on-package access. CPUID (the source of the information about * the LLC) can only enumerate the cache as shared or unshared, * but not this particular configuration. */ static const struct x86_cpu_id intel_cod_cpu[] = { X86_MATCH_INTEL_FAM6_MODEL(HASWELL_X, 0), /* COD */ X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_X, 0), /* COD */ X86_MATCH_INTEL_FAM6_MODEL(ANY, 1), /* SNC */ {} }; static bool match_llc(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o) { const struct x86_cpu_id *id = x86_match_cpu(intel_cod_cpu); int cpu1 = c->cpu_index, cpu2 = o->cpu_index; bool intel_snc = id && id->driver_data; /* Do not match if we do not have a valid APICID for cpu: */ if (per_cpu(cpu_llc_id, cpu1) == BAD_APICID) return false; /* Do not match if LLC id does not match: */ if (per_cpu(cpu_llc_id, cpu1) != per_cpu(cpu_llc_id, cpu2)) return false; /* * Allow the SNC topology without warning. Return of false * means 'c' does not share the LLC of 'o'. This will be * reflected to userspace. */ if (match_pkg(c, o) && !topology_same_node(c, o) && intel_snc) return false; return topology_sane(c, o, "llc"); } static inline int x86_sched_itmt_flags(void) { return sysctl_sched_itmt_enabled ? SD_ASYM_PACKING : 0; } #ifdef CONFIG_SCHED_MC static int x86_core_flags(void) { return cpu_core_flags() | x86_sched_itmt_flags(); } #endif #ifdef CONFIG_SCHED_SMT static int x86_smt_flags(void) { return cpu_smt_flags(); } #endif #ifdef CONFIG_SCHED_CLUSTER static int x86_cluster_flags(void) { return cpu_cluster_flags() | x86_sched_itmt_flags(); } #endif static int x86_die_flags(void) { if (cpu_feature_enabled(X86_FEATURE_HYBRID_CPU)) return x86_sched_itmt_flags(); return 0; } /* * Set if a package/die has multiple NUMA nodes inside. * AMD Magny-Cours, Intel Cluster-on-Die, and Intel * Sub-NUMA Clustering have this. */ static bool x86_has_numa_in_package; static struct sched_domain_topology_level x86_topology[6]; static void __init build_sched_topology(void) { int i = 0; #ifdef CONFIG_SCHED_SMT x86_topology[i++] = (struct sched_domain_topology_level){ cpu_smt_mask, x86_smt_flags, SD_INIT_NAME(SMT) }; #endif #ifdef CONFIG_SCHED_CLUSTER x86_topology[i++] = (struct sched_domain_topology_level){ cpu_clustergroup_mask, x86_cluster_flags, SD_INIT_NAME(CLS) }; #endif #ifdef CONFIG_SCHED_MC x86_topology[i++] = (struct sched_domain_topology_level){ cpu_coregroup_mask, x86_core_flags, SD_INIT_NAME(MC) }; #endif /* * When there is NUMA topology inside the package skip the DIE domain * since the NUMA domains will auto-magically create the right spanning * domains based on the SLIT. */ if (!x86_has_numa_in_package) { x86_topology[i++] = (struct sched_domain_topology_level){ cpu_cpu_mask, x86_die_flags, SD_INIT_NAME(DIE) }; } /* * There must be one trailing NULL entry left. */ BUG_ON(i >= ARRAY_SIZE(x86_topology)-1); set_sched_topology(x86_topology); } void set_cpu_sibling_map(int cpu) { bool has_smt = smp_num_siblings > 1; bool has_mp = has_smt || boot_cpu_data.x86_max_cores > 1; struct cpuinfo_x86 *c = &cpu_data(cpu); struct cpuinfo_x86 *o; int i, threads; cpumask_set_cpu(cpu, cpu_sibling_setup_mask); if (!has_mp) { cpumask_set_cpu(cpu, topology_sibling_cpumask(cpu)); cpumask_set_cpu(cpu, cpu_llc_shared_mask(cpu)); cpumask_set_cpu(cpu, cpu_l2c_shared_mask(cpu)); cpumask_set_cpu(cpu, topology_core_cpumask(cpu)); cpumask_set_cpu(cpu, topology_die_cpumask(cpu)); c->booted_cores = 1; return; } for_each_cpu(i, cpu_sibling_setup_mask) { o = &cpu_data(i); if (match_pkg(c, o) && !topology_same_node(c, o)) x86_has_numa_in_package = true; if ((i == cpu) || (has_smt && match_smt(c, o))) link_mask(topology_sibling_cpumask, cpu, i); if ((i == cpu) || (has_mp && match_llc(c, o))) link_mask(cpu_llc_shared_mask, cpu, i); if ((i == cpu) || (has_mp && match_l2c(c, o))) link_mask(cpu_l2c_shared_mask, cpu, i); if ((i == cpu) || (has_mp && match_die(c, o))) link_mask(topology_die_cpumask, cpu, i); } threads = cpumask_weight(topology_sibling_cpumask(cpu)); if (threads > __max_smt_threads) __max_smt_threads = threads; for_each_cpu(i, topology_sibling_cpumask(cpu)) cpu_data(i).smt_active = threads > 1; /* * This needs a separate iteration over the cpus because we rely on all * topology_sibling_cpumask links to be set-up. */ for_each_cpu(i, cpu_sibling_setup_mask) { o = &cpu_data(i); if ((i == cpu) || (has_mp && match_pkg(c, o))) { link_mask(topology_core_cpumask, cpu, i); /* * Does this new cpu bringup a new core? */ if (threads == 1) { /* * for each core in package, increment * the booted_cores for this new cpu */ if (cpumask_first( topology_sibling_cpumask(i)) == i) c->booted_cores++; /* * increment the core count for all * the other cpus in this package */ if (i != cpu) cpu_data(i).booted_cores++; } else if (i != cpu && !c->booted_cores) c->booted_cores = cpu_data(i).booted_cores; } } } /* maps the cpu to the sched domain representing multi-core */ const struct cpumask *cpu_coregroup_mask(int cpu) { return cpu_llc_shared_mask(cpu); } const struct cpumask *cpu_clustergroup_mask(int cpu) { return cpu_l2c_shared_mask(cpu); } static void impress_friends(void) { int cpu; unsigned long bogosum = 0; /* * Allow the user to impress friends. */ pr_debug("Before bogomips\n"); for_each_online_cpu(cpu) bogosum += cpu_data(cpu).loops_per_jiffy; pr_info("Total of %d processors activated (%lu.%02lu BogoMIPS)\n", num_online_cpus(), bogosum/(500000/HZ), (bogosum/(5000/HZ))%100); pr_debug("Before bogocount - setting activated=1\n"); } /* * The Multiprocessor Specification 1.4 (1997) example code suggests * that there should be a 10ms delay between the BSP asserting INIT * and de-asserting INIT, when starting a remote processor. * But that slows boot and resume on modern processors, which include * many cores and don't require that delay. * * Cmdline "init_cpu_udelay=" is available to over-ride this delay. * Modern processor families are quirked to remove the delay entirely. */ #define UDELAY_10MS_DEFAULT 10000 static unsigned int init_udelay = UINT_MAX; static int __init cpu_init_udelay(char *str) { get_option(&str, &init_udelay); return 0; } early_param("cpu_init_udelay", cpu_init_udelay); static void __init smp_quirk_init_udelay(void) { /* if cmdline changed it from default, leave it alone */ if (init_udelay != UINT_MAX) return; /* if modern processor, use no delay */ if (((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) && (boot_cpu_data.x86 == 6)) || ((boot_cpu_data.x86_vendor == X86_VENDOR_HYGON) && (boot_cpu_data.x86 >= 0x18)) || ((boot_cpu_data.x86_vendor == X86_VENDOR_AMD) && (boot_cpu_data.x86 >= 0xF))) { init_udelay = 0; return; } /* else, use legacy delay */ init_udelay = UDELAY_10MS_DEFAULT; } /* * Wake up AP by INIT, INIT, STARTUP sequence. */ static void send_init_sequence(int phys_apicid) { int maxlvt = lapic_get_maxlvt(); /* Be paranoid about clearing APIC errors. */ if (APIC_INTEGRATED(boot_cpu_apic_version)) { /* Due to the Pentium erratum 3AP. */ if (maxlvt > 3) apic_write(APIC_ESR, 0); apic_read(APIC_ESR); } /* Assert INIT on the target CPU */ apic_icr_write(APIC_INT_LEVELTRIG | APIC_INT_ASSERT | APIC_DM_INIT, phys_apicid); safe_apic_wait_icr_idle(); udelay(init_udelay); /* Deassert INIT on the target CPU */ apic_icr_write(APIC_INT_LEVELTRIG | APIC_DM_INIT, phys_apicid); safe_apic_wait_icr_idle(); } /* * Wake up AP by INIT, INIT, STARTUP sequence. */ static int wakeup_secondary_cpu_via_init(int phys_apicid, unsigned long start_eip) { unsigned long send_status = 0, accept_status = 0; int num_starts, j, maxlvt; preempt_disable(); maxlvt = lapic_get_maxlvt(); send_init_sequence(phys_apicid); mb(); /* * Should we send STARTUP IPIs ? * * Determine this based on the APIC version. * If we don't have an integrated APIC, don't send the STARTUP IPIs. */ if (APIC_INTEGRATED(boot_cpu_apic_version)) num_starts = 2; else num_starts = 0; /* * Run STARTUP IPI loop. */ pr_debug("#startup loops: %d\n", num_starts); for (j = 1; j <= num_starts; j++) { pr_debug("Sending STARTUP #%d\n", j); if (maxlvt > 3) /* Due to the Pentium erratum 3AP. */ apic_write(APIC_ESR, 0); apic_read(APIC_ESR); pr_debug("After apic_write\n"); /* * STARTUP IPI */ /* Target chip */ /* Boot on the stack */ /* Kick the second */ apic_icr_write(APIC_DM_STARTUP | (start_eip >> 12), phys_apicid); /* * Give the other CPU some time to accept the IPI. */ if (init_udelay == 0) udelay(10); else udelay(300); pr_debug("Startup point 1\n"); pr_debug("Waiting for send to finish...\n"); send_status = safe_apic_wait_icr_idle(); /* * Give the other CPU some time to accept the IPI. */ if (init_udelay == 0) udelay(10); else udelay(200); if (maxlvt > 3) /* Due to the Pentium erratum 3AP. */ apic_write(APIC_ESR, 0); accept_status = (apic_read(APIC_ESR) & 0xEF); if (send_status || accept_status) break; } pr_debug("After Startup\n"); if (send_status) pr_err("APIC never delivered???\n"); if (accept_status) pr_err("APIC delivery error (%lx)\n", accept_status); preempt_enable(); return (send_status | accept_status); } /* reduce the number of lines printed when booting a large cpu count system */ static void announce_cpu(int cpu, int apicid) { static int width, node_width, first = 1; static int current_node = NUMA_NO_NODE; int node = early_cpu_to_node(cpu); if (!width) width = num_digits(num_possible_cpus()) + 1; /* + '#' sign */ if (!node_width) node_width = num_digits(num_possible_nodes()) + 1; /* + '#' */ if (system_state < SYSTEM_RUNNING) { if (first) pr_info("x86: Booting SMP configuration:\n"); if (node != current_node) { if (current_node > (-1)) pr_cont("\n"); current_node = node; printk(KERN_INFO ".... node %*s#%d, CPUs: ", node_width - num_digits(node), " ", node); } /* Add padding for the BSP */ if (first) pr_cont("%*s", width + 1, " "); first = 0; pr_cont("%*s#%d", width - num_digits(cpu), " ", cpu); } else pr_info("Booting Node %d Processor %d APIC 0x%x\n", node, cpu, apicid); } int common_cpu_up(unsigned int cpu, struct task_struct *idle) { int ret; /* Just in case we booted with a single CPU. */ alternatives_enable_smp(); per_cpu(pcpu_hot.current_task, cpu) = idle; cpu_init_stack_canary(cpu, idle); /* Initialize the interrupt stack(s) */ ret = irq_init_percpu_irqstack(cpu); if (ret) return ret; #ifdef CONFIG_X86_32 /* Stack for startup_32 can be just as for start_secondary onwards */ per_cpu(pcpu_hot.top_of_stack, cpu) = task_top_of_stack(idle); #endif return 0; } /* * NOTE - on most systems this is a PHYSICAL apic ID, but on multiquad * (ie clustered apic addressing mode), this is a LOGICAL apic ID. * Returns zero if startup was successfully sent, else error code from * ->wakeup_secondary_cpu. */ static int do_boot_cpu(int apicid, int cpu, struct task_struct *idle) { unsigned long start_ip = real_mode_header->trampoline_start; int ret; #ifdef CONFIG_X86_64 /* If 64-bit wakeup method exists, use the 64-bit mode trampoline IP */ if (apic->wakeup_secondary_cpu_64) start_ip = real_mode_header->trampoline_start64; #endif idle->thread.sp = (unsigned long)task_pt_regs(idle); initial_code = (unsigned long)start_secondary; if (IS_ENABLED(CONFIG_X86_32)) { early_gdt_descr.address = (unsigned long)get_cpu_gdt_rw(cpu); initial_stack = idle->thread.sp; } else if (!(smpboot_control & STARTUP_PARALLEL_MASK)) { smpboot_control = cpu; } /* Enable the espfix hack for this CPU */ init_espfix_ap(cpu); /* So we see what's up */ announce_cpu(cpu, apicid); /* * This grunge runs the startup process for * the targeted processor. */ if (x86_platform.legacy.warm_reset) { pr_debug("Setting warm reset code and vector.\n"); smpboot_setup_warm_reset_vector(start_ip); /* * Be paranoid about clearing APIC errors. */ if (APIC_INTEGRATED(boot_cpu_apic_version)) { apic_write(APIC_ESR, 0); apic_read(APIC_ESR); } } smp_mb(); /* * Wake up a CPU in difference cases: * - Use a method from the APIC driver if one defined, with wakeup * straight to 64-bit mode preferred over wakeup to RM. * Otherwise, * - Use an INIT boot APIC message */ if (apic->wakeup_secondary_cpu_64) ret = apic->wakeup_secondary_cpu_64(apicid, start_ip); else if (apic->wakeup_secondary_cpu) ret = apic->wakeup_secondary_cpu(apicid, start_ip); else ret = wakeup_secondary_cpu_via_init(apicid, start_ip); /* If the wakeup mechanism failed, cleanup the warm reset vector */ if (ret) arch_cpuhp_cleanup_kick_cpu(cpu); return ret; } int native_kick_ap(unsigned int cpu, struct task_struct *tidle) { int apicid = apic->cpu_present_to_apicid(cpu); int err; lockdep_assert_irqs_enabled(); pr_debug("++++++++++++++++++++=_---CPU UP %u\n", cpu); if (apicid == BAD_APICID || !physid_isset(apicid, phys_cpu_present_map) || !apic_id_valid(apicid)) { pr_err("%s: bad cpu %d\n", __func__, cpu); return -EINVAL; } /* * Save current MTRR state in case it was changed since early boot * (e.g. by the ACPI SMI) to initialize new CPUs with MTRRs in sync: */ mtrr_save_state(); /* the FPU context is blank, nobody can own it */ per_cpu(fpu_fpregs_owner_ctx, cpu) = NULL; err = common_cpu_up(cpu, tidle); if (err) return err; err = do_boot_cpu(apicid, cpu, tidle); if (err) pr_err("do_boot_cpu failed(%d) to wakeup CPU#%u\n", err, cpu); return err; } int arch_cpuhp_kick_ap_alive(unsigned int cpu, struct task_struct *tidle) { return smp_ops.kick_ap_alive(cpu, tidle); } void arch_cpuhp_cleanup_kick_cpu(unsigned int cpu) { /* Cleanup possible dangling ends... */ if (smp_ops.kick_ap_alive == native_kick_ap && x86_platform.legacy.warm_reset) smpboot_restore_warm_reset_vector(); } void arch_cpuhp_cleanup_dead_cpu(unsigned int cpu) { if (smp_ops.cleanup_dead_cpu) smp_ops.cleanup_dead_cpu(cpu); if (system_state == SYSTEM_RUNNING) pr_info("CPU %u is now offline\n", cpu); } void arch_cpuhp_sync_state_poll(void) { if (smp_ops.poll_sync_state) smp_ops.poll_sync_state(); } /** * arch_disable_smp_support() - Disables SMP support for x86 at boottime */ void __init arch_disable_smp_support(void) { disable_ioapic_support(); } /* * Fall back to non SMP mode after errors. * * RED-PEN audit/test this more. I bet there is more state messed up here. */ static __init void disable_smp(void) { pr_info("SMP disabled\n"); disable_ioapic_support(); init_cpu_present(cpumask_of(0)); init_cpu_possible(cpumask_of(0)); if (smp_found_config) physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map); else physid_set_mask_of_physid(0, &phys_cpu_present_map); cpumask_set_cpu(0, topology_sibling_cpumask(0)); cpumask_set_cpu(0, topology_core_cpumask(0)); cpumask_set_cpu(0, topology_die_cpumask(0)); } static void __init smp_cpu_index_default(void) { int i; struct cpuinfo_x86 *c; for_each_possible_cpu(i) { c = &cpu_data(i); /* mark all to hotplug */ c->cpu_index = nr_cpu_ids; } } void __init smp_prepare_cpus_common(void) { unsigned int i; smp_cpu_index_default(); /* * Setup boot CPU information */ smp_store_boot_cpu_info(); /* Final full version of the data */ mb(); for_each_possible_cpu(i) { zalloc_cpumask_var(&per_cpu(cpu_sibling_map, i), GFP_KERNEL); zalloc_cpumask_var(&per_cpu(cpu_core_map, i), GFP_KERNEL); zalloc_cpumask_var(&per_cpu(cpu_die_map, i), GFP_KERNEL); zalloc_cpumask_var(&per_cpu(cpu_llc_shared_map, i), GFP_KERNEL); zalloc_cpumask_var(&per_cpu(cpu_l2c_shared_map, i), GFP_KERNEL); } set_cpu_sibling_map(0); } #ifdef CONFIG_X86_64 /* Establish whether parallel bringup can be supported. */ bool __init arch_cpuhp_init_parallel_bringup(void) { if (!x86_cpuinit.parallel_bringup) { pr_info("Parallel CPU startup disabled by the platform\n"); return false; } smpboot_control = STARTUP_READ_APICID; pr_debug("Parallel CPU startup enabled: 0x%08x\n", smpboot_control); return true; } #endif /* * Prepare for SMP bootup. * @max_cpus: configured maximum number of CPUs, It is a legacy parameter * for common interface support. */ void __init native_smp_prepare_cpus(unsigned int max_cpus) { smp_prepare_cpus_common(); switch (apic_intr_mode) { case APIC_PIC: case APIC_VIRTUAL_WIRE_NO_CONFIG: disable_smp(); return; case APIC_SYMMETRIC_IO_NO_ROUTING: disable_smp(); /* Setup local timer */ x86_init.timers.setup_percpu_clockev(); return; case APIC_VIRTUAL_WIRE: case APIC_SYMMETRIC_IO: break; } /* Setup local timer */ x86_init.timers.setup_percpu_clockev(); pr_info("CPU0: "); print_cpu_info(&cpu_data(0)); uv_system_init(); smp_quirk_init_udelay(); speculative_store_bypass_ht_init(); snp_set_wakeup_secondary_cpu(); } void arch_thaw_secondary_cpus_begin(void) { set_cache_aps_delayed_init(true); } void arch_thaw_secondary_cpus_end(void) { cache_aps_init(); } bool smp_park_other_cpus_in_init(void) { unsigned int cpu, this_cpu = smp_processor_id(); unsigned int apicid; if (apic->wakeup_secondary_cpu_64 || apic->wakeup_secondary_cpu) return false; /* * If this is a crash stop which does not execute on the boot CPU, * then this cannot use the INIT mechanism because INIT to the boot * CPU will reset the machine. */ if (this_cpu) return false; for_each_cpu_and(cpu, &cpus_booted_once_mask, cpu_present_mask) { if (cpu == this_cpu) continue; apicid = apic->cpu_present_to_apicid(cpu); if (apicid == BAD_APICID) continue; send_init_sequence(apicid); } return true; } /* * Early setup to make printk work. */ void __init native_smp_prepare_boot_cpu(void) { int me = smp_processor_id(); /* SMP handles this from setup_per_cpu_areas() */ if (!IS_ENABLED(CONFIG_SMP)) switch_gdt_and_percpu_base(me); native_pv_lock_init(); } void __init calculate_max_logical_packages(void) { int ncpus; /* * Today neither Intel nor AMD support heterogeneous systems so * extrapolate the boot cpu's data to all packages. */ ncpus = cpu_data(0).booted_cores * topology_max_smt_threads(); __max_logical_packages = DIV_ROUND_UP(total_cpus, ncpus); pr_info("Max logical packages: %u\n", __max_logical_packages); } void __init native_smp_cpus_done(unsigned int max_cpus) { pr_debug("Boot done\n"); calculate_max_logical_packages(); build_sched_topology(); nmi_selftest(); impress_friends(); cache_aps_init(); } static int __initdata setup_possible_cpus = -1; static int __init _setup_possible_cpus(char *str) { get_option(&str, &setup_possible_cpus); return 0; } early_param("possible_cpus", _setup_possible_cpus); /* * cpu_possible_mask should be static, it cannot change as cpu's * are onlined, or offlined. The reason is per-cpu data-structures * are allocated by some modules at init time, and don't expect to * do this dynamically on cpu arrival/departure. * cpu_present_mask on the other hand can change dynamically. * In case when cpu_hotplug is not compiled, then we resort to current * behaviour, which is cpu_possible == cpu_present. * - Ashok Raj * * Three ways to find out the number of additional hotplug CPUs: * - If the BIOS specified disabled CPUs in ACPI/mptables use that. * - The user can overwrite it with possible_cpus=NUM * - Otherwise don't reserve additional CPUs. * We do this because additional CPUs waste a lot of memory. * -AK */ __init void prefill_possible_map(void) { int i, possible; i = setup_max_cpus ?: 1; if (setup_possible_cpus == -1) { possible = num_processors; #ifdef CONFIG_HOTPLUG_CPU if (setup_max_cpus) possible += disabled_cpus; #else if (possible > i) possible = i; #endif } else possible = setup_possible_cpus; total_cpus = max_t(int, possible, num_processors + disabled_cpus); /* nr_cpu_ids could be reduced via nr_cpus= */ if (possible > nr_cpu_ids) { pr_warn("%d Processors exceeds NR_CPUS limit of %u\n", possible, nr_cpu_ids); possible = nr_cpu_ids; } #ifdef CONFIG_HOTPLUG_CPU if (!setup_max_cpus) #endif if (possible > i) { pr_warn("%d Processors exceeds max_cpus limit of %u\n", possible, setup_max_cpus); possible = i; } set_nr_cpu_ids(possible); pr_info("Allowing %d CPUs, %d hotplug CPUs\n", possible, max_t(int, possible - num_processors, 0)); reset_cpu_possible_mask(); for (i = 0; i < possible; i++) set_cpu_possible(i, true); } /* correctly size the local cpu masks */ void __init setup_cpu_local_masks(void) { alloc_bootmem_cpumask_var(&cpu_sibling_setup_mask); } #ifdef CONFIG_HOTPLUG_CPU /* Recompute SMT state for all CPUs on offline */ static void recompute_smt_state(void) { int max_threads, cpu; max_threads = 0; for_each_online_cpu (cpu) { int threads = cpumask_weight(topology_sibling_cpumask(cpu)); if (threads > max_threads) max_threads = threads; } __max_smt_threads = max_threads; } static void remove_siblinginfo(int cpu) { int sibling; struct cpuinfo_x86 *c = &cpu_data(cpu); for_each_cpu(sibling, topology_core_cpumask(cpu)) { cpumask_clear_cpu(cpu, topology_core_cpumask(sibling)); /*/ * last thread sibling in this cpu core going down */ if (cpumask_weight(topology_sibling_cpumask(cpu)) == 1) cpu_data(sibling).booted_cores--; } for_each_cpu(sibling, topology_die_cpumask(cpu)) cpumask_clear_cpu(cpu, topology_die_cpumask(sibling)); for_each_cpu(sibling, topology_sibling_cpumask(cpu)) { cpumask_clear_cpu(cpu, topology_sibling_cpumask(sibling)); if (cpumask_weight(topology_sibling_cpumask(sibling)) == 1) cpu_data(sibling).smt_active = false; } for_each_cpu(sibling, cpu_llc_shared_mask(cpu)) cpumask_clear_cpu(cpu, cpu_llc_shared_mask(sibling)); for_each_cpu(sibling, cpu_l2c_shared_mask(cpu)) cpumask_clear_cpu(cpu, cpu_l2c_shared_mask(sibling)); cpumask_clear(cpu_llc_shared_mask(cpu)); cpumask_clear(cpu_l2c_shared_mask(cpu)); cpumask_clear(topology_sibling_cpumask(cpu)); cpumask_clear(topology_core_cpumask(cpu)); cpumask_clear(topology_die_cpumask(cpu)); c->cpu_core_id = 0; c->booted_cores = 0; cpumask_clear_cpu(cpu, cpu_sibling_setup_mask); recompute_smt_state(); } static void remove_cpu_from_maps(int cpu) { set_cpu_online(cpu, false); numa_remove_cpu(cpu); } void cpu_disable_common(void) { int cpu = smp_processor_id(); remove_siblinginfo(cpu); /* It's now safe to remove this processor from the online map */ lock_vector_lock(); remove_cpu_from_maps(cpu); unlock_vector_lock(); fixup_irqs(); lapic_offline(); } int native_cpu_disable(void) { int ret; ret = lapic_can_unplug_cpu(); if (ret) return ret; cpu_disable_common(); /* * Disable the local APIC. Otherwise IPI broadcasts will reach * it. It still responds normally to INIT, NMI, SMI, and SIPI * messages. * * Disabling the APIC must happen after cpu_disable_common() * which invokes fixup_irqs(). * * Disabling the APIC preserves already set bits in IRR, but * an interrupt arriving after disabling the local APIC does not * set the corresponding IRR bit. * * fixup_irqs() scans IRR for set bits so it can raise a not * yet handled interrupt on the new destination CPU via an IPI * but obviously it can't do so for IRR bits which are not set. * IOW, interrupts arriving after disabling the local APIC will * be lost. */ apic_soft_disable(); return 0; } void play_dead_common(void) { idle_task_exit(); cpuhp_ap_report_dead(); local_irq_disable(); } /* * We need to flush the caches before going to sleep, lest we have * dirty data in our caches when we come back up. */ static inline void mwait_play_dead(void) { struct mwait_cpu_dead *md = this_cpu_ptr(&mwait_cpu_dead); unsigned int eax, ebx, ecx, edx; unsigned int highest_cstate = 0; unsigned int highest_subcstate = 0; int i; if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD || boot_cpu_data.x86_vendor == X86_VENDOR_HYGON) return; if (!this_cpu_has(X86_FEATURE_MWAIT)) return; if (!this_cpu_has(X86_FEATURE_CLFLUSH)) return; if (__this_cpu_read(cpu_info.cpuid_level) < CPUID_MWAIT_LEAF) return; eax = CPUID_MWAIT_LEAF; ecx = 0; native_cpuid(&eax, &ebx, &ecx, &edx); /* * eax will be 0 if EDX enumeration is not valid. * Initialized below to cstate, sub_cstate value when EDX is valid. */ if (!(ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED)) { eax = 0; } else { edx >>= MWAIT_SUBSTATE_SIZE; for (i = 0; i < 7 && edx; i++, edx >>= MWAIT_SUBSTATE_SIZE) { if (edx & MWAIT_SUBSTATE_MASK) { highest_cstate = i; highest_subcstate = edx & MWAIT_SUBSTATE_MASK; } } eax = (highest_cstate << MWAIT_SUBSTATE_SIZE) | (highest_subcstate - 1); } /* Set up state for the kexec() hack below */ md->status = CPUDEAD_MWAIT_WAIT; md->control = CPUDEAD_MWAIT_WAIT; wbinvd(); while (1) { /* * The CLFLUSH is a workaround for erratum AAI65 for * the Xeon 7400 series. It's not clear it is actually * needed, but it should be harmless in either case. * The WBINVD is insufficient due to the spurious-wakeup * case where we return around the loop. */ mb(); clflush(md); mb(); __monitor(md, 0, 0); mb(); __mwait(eax, 0); if (READ_ONCE(md->control) == CPUDEAD_MWAIT_KEXEC_HLT) { /* * Kexec is about to happen. Don't go back into mwait() as * the kexec kernel might overwrite text and data including * page tables and stack. So mwait() would resume when the * monitor cache line is written to and then the CPU goes * south due to overwritten text, page tables and stack. * * Note: This does _NOT_ protect against a stray MCE, NMI, * SMI. They will resume execution at the instruction * following the HLT instruction and run into the problem * which this is trying to prevent. */ WRITE_ONCE(md->status, CPUDEAD_MWAIT_KEXEC_HLT); while(1) native_halt(); } } } /* * Kick all "offline" CPUs out of mwait on kexec(). See comment in * mwait_play_dead(). */ void smp_kick_mwait_play_dead(void) { u32 newstate = CPUDEAD_MWAIT_KEXEC_HLT; struct mwait_cpu_dead *md; unsigned int cpu, i; for_each_cpu_andnot(cpu, cpu_present_mask, cpu_online_mask) { md = per_cpu_ptr(&mwait_cpu_dead, cpu); /* Does it sit in mwait_play_dead() ? */ if (READ_ONCE(md->status) != CPUDEAD_MWAIT_WAIT) continue; /* Wait up to 5ms */ for (i = 0; READ_ONCE(md->status) != newstate && i < 1000; i++) { /* Bring it out of mwait */ WRITE_ONCE(md->control, newstate); udelay(5); } if (READ_ONCE(md->status) != newstate) pr_err_once("CPU%u is stuck in mwait_play_dead()\n", cpu); } } void __noreturn hlt_play_dead(void) { if (__this_cpu_read(cpu_info.x86) >= 4) wbinvd(); while (1) native_halt(); } void native_play_dead(void) { play_dead_common(); tboot_shutdown(TB_SHUTDOWN_WFS); mwait_play_dead(); if (cpuidle_play_dead()) hlt_play_dead(); } #else /* ... !CONFIG_HOTPLUG_CPU */ int native_cpu_disable(void) { return -ENOSYS; } void native_play_dead(void) { BUG(); } #endif
linux-master
arch/x86/kernel/smpboot.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/kernel.h> #include <linux/init.h> #include <linux/pnp.h> #include <asm/setup.h> #include <asm/bios_ebda.h> void __init x86_early_init_platform_quirks(void) { x86_platform.legacy.i8042 = X86_LEGACY_I8042_EXPECTED_PRESENT; x86_platform.legacy.rtc = 1; x86_platform.legacy.warm_reset = 1; x86_platform.legacy.reserve_bios_regions = 0; x86_platform.legacy.devices.pnpbios = 1; switch (boot_params.hdr.hardware_subarch) { case X86_SUBARCH_PC: x86_platform.legacy.reserve_bios_regions = 1; break; case X86_SUBARCH_XEN: x86_platform.legacy.devices.pnpbios = 0; x86_platform.legacy.rtc = 0; break; case X86_SUBARCH_INTEL_MID: case X86_SUBARCH_CE4100: x86_platform.legacy.devices.pnpbios = 0; x86_platform.legacy.rtc = 0; x86_platform.legacy.i8042 = X86_LEGACY_I8042_PLATFORM_ABSENT; break; } if (x86_platform.set_legacy_features) x86_platform.set_legacy_features(); } bool __init x86_pnpbios_disabled(void) { return x86_platform.legacy.devices.pnpbios == 0; } #if defined(CONFIG_PNPBIOS) bool __init arch_pnpbios_disabled(void) { return x86_pnpbios_disabled(); } #endif
linux-master
arch/x86/kernel/platform-quirks.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/ioport.h> #include <linux/printk.h> #include <asm/e820/api.h> #include <asm/pci_x86.h> static void resource_clip(struct resource *res, resource_size_t start, resource_size_t end) { resource_size_t low = 0, high = 0; if (res->end < start || res->start > end) return; /* no conflict */ if (res->start < start) low = start - res->start; if (res->end > end) high = res->end - end; /* Keep the area above or below the conflict, whichever is larger */ if (low > high) res->end = start - 1; else res->start = end + 1; } static void remove_e820_regions(struct resource *avail) { int i; struct e820_entry *entry; u64 e820_start, e820_end; struct resource orig = *avail; if (!pci_use_e820) return; for (i = 0; i < e820_table->nr_entries; i++) { entry = &e820_table->entries[i]; e820_start = entry->addr; e820_end = entry->addr + entry->size - 1; resource_clip(avail, e820_start, e820_end); if (orig.start != avail->start || orig.end != avail->end) { pr_info("resource: avoiding allocation from e820 entry [mem %#010Lx-%#010Lx]\n", e820_start, e820_end); if (avail->end > avail->start) /* * Use %pa instead of %pR because "avail" * is typically IORESOURCE_UNSET, so %pR * shows the size instead of addresses. */ pr_info("resource: remaining [mem %pa-%pa] available\n", &avail->start, &avail->end); orig = *avail; } } } void arch_remove_reservations(struct resource *avail) { /* * Trim out BIOS area (high 2MB) and E820 regions. We do not remove * the low 1MB unconditionally, as this area is needed for some ISA * cards requiring a memory range, e.g. the i82365 PCMCIA controller. */ if (avail->flags & IORESOURCE_MEM) { resource_clip(avail, BIOS_ROM_BASE, BIOS_ROM_END); remove_e820_regions(avail); } }
linux-master
arch/x86/kernel/resource.c
// SPDX-License-Identifier: GPL-2.0-only /* * Common interrupt code for 32 and 64 bit */ #include <linux/cpu.h> #include <linux/interrupt.h> #include <linux/kernel_stat.h> #include <linux/of.h> #include <linux/seq_file.h> #include <linux/smp.h> #include <linux/ftrace.h> #include <linux/delay.h> #include <linux/export.h> #include <linux/irq.h> #include <asm/irq_stack.h> #include <asm/apic.h> #include <asm/io_apic.h> #include <asm/irq.h> #include <asm/mce.h> #include <asm/hw_irq.h> #include <asm/desc.h> #include <asm/traps.h> #include <asm/thermal.h> #define CREATE_TRACE_POINTS #include <asm/trace/irq_vectors.h> DEFINE_PER_CPU_SHARED_ALIGNED(irq_cpustat_t, irq_stat); EXPORT_PER_CPU_SYMBOL(irq_stat); atomic_t irq_err_count; /* * 'what should we do if we get a hw irq event on an illegal vector'. * each architecture has to answer this themselves. */ void ack_bad_irq(unsigned int irq) { if (printk_ratelimit()) pr_err("unexpected IRQ trap at vector %02x\n", irq); /* * Currently unexpected vectors happen only on SMP and APIC. * We _must_ ack these because every local APIC has only N * irq slots per priority level, and a 'hanging, unacked' IRQ * holds up an irq slot - in excessive cases (when multiple * unexpected vectors occur) that might lock up the APIC * completely. * But only ack when the APIC is enabled -AK */ apic_eoi(); } #define irq_stats(x) (&per_cpu(irq_stat, x)) /* * /proc/interrupts printing for arch specific interrupts */ int arch_show_interrupts(struct seq_file *p, int prec) { int j; seq_printf(p, "%*s: ", prec, "NMI"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->__nmi_count); seq_puts(p, " Non-maskable interrupts\n"); #ifdef CONFIG_X86_LOCAL_APIC seq_printf(p, "%*s: ", prec, "LOC"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->apic_timer_irqs); seq_puts(p, " Local timer interrupts\n"); seq_printf(p, "%*s: ", prec, "SPU"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_spurious_count); seq_puts(p, " Spurious interrupts\n"); seq_printf(p, "%*s: ", prec, "PMI"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->apic_perf_irqs); seq_puts(p, " Performance monitoring interrupts\n"); seq_printf(p, "%*s: ", prec, "IWI"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->apic_irq_work_irqs); seq_puts(p, " IRQ work interrupts\n"); seq_printf(p, "%*s: ", prec, "RTR"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->icr_read_retry_count); seq_puts(p, " APIC ICR read retries\n"); if (x86_platform_ipi_callback) { seq_printf(p, "%*s: ", prec, "PLT"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->x86_platform_ipis); seq_puts(p, " Platform interrupts\n"); } #endif #ifdef CONFIG_SMP seq_printf(p, "%*s: ", prec, "RES"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_resched_count); seq_puts(p, " Rescheduling interrupts\n"); seq_printf(p, "%*s: ", prec, "CAL"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_call_count); seq_puts(p, " Function call interrupts\n"); seq_printf(p, "%*s: ", prec, "TLB"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_tlb_count); seq_puts(p, " TLB shootdowns\n"); #endif #ifdef CONFIG_X86_THERMAL_VECTOR seq_printf(p, "%*s: ", prec, "TRM"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_thermal_count); seq_puts(p, " Thermal event interrupts\n"); #endif #ifdef CONFIG_X86_MCE_THRESHOLD seq_printf(p, "%*s: ", prec, "THR"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_threshold_count); seq_puts(p, " Threshold APIC interrupts\n"); #endif #ifdef CONFIG_X86_MCE_AMD seq_printf(p, "%*s: ", prec, "DFR"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_deferred_error_count); seq_puts(p, " Deferred Error APIC interrupts\n"); #endif #ifdef CONFIG_X86_MCE seq_printf(p, "%*s: ", prec, "MCE"); for_each_online_cpu(j) seq_printf(p, "%10u ", per_cpu(mce_exception_count, j)); seq_puts(p, " Machine check exceptions\n"); seq_printf(p, "%*s: ", prec, "MCP"); for_each_online_cpu(j) seq_printf(p, "%10u ", per_cpu(mce_poll_count, j)); seq_puts(p, " Machine check polls\n"); #endif #ifdef CONFIG_X86_HV_CALLBACK_VECTOR if (test_bit(HYPERVISOR_CALLBACK_VECTOR, system_vectors)) { seq_printf(p, "%*s: ", prec, "HYP"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_hv_callback_count); seq_puts(p, " Hypervisor callback interrupts\n"); } #endif #if IS_ENABLED(CONFIG_HYPERV) if (test_bit(HYPERV_REENLIGHTENMENT_VECTOR, system_vectors)) { seq_printf(p, "%*s: ", prec, "HRE"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->irq_hv_reenlightenment_count); seq_puts(p, " Hyper-V reenlightenment interrupts\n"); } if (test_bit(HYPERV_STIMER0_VECTOR, system_vectors)) { seq_printf(p, "%*s: ", prec, "HVS"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->hyperv_stimer0_count); seq_puts(p, " Hyper-V stimer0 interrupts\n"); } #endif seq_printf(p, "%*s: %10u\n", prec, "ERR", atomic_read(&irq_err_count)); #if defined(CONFIG_X86_IO_APIC) seq_printf(p, "%*s: %10u\n", prec, "MIS", atomic_read(&irq_mis_count)); #endif #ifdef CONFIG_HAVE_KVM seq_printf(p, "%*s: ", prec, "PIN"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->kvm_posted_intr_ipis); seq_puts(p, " Posted-interrupt notification event\n"); seq_printf(p, "%*s: ", prec, "NPI"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->kvm_posted_intr_nested_ipis); seq_puts(p, " Nested posted-interrupt event\n"); seq_printf(p, "%*s: ", prec, "PIW"); for_each_online_cpu(j) seq_printf(p, "%10u ", irq_stats(j)->kvm_posted_intr_wakeup_ipis); seq_puts(p, " Posted-interrupt wakeup event\n"); #endif return 0; } /* * /proc/stat helpers */ u64 arch_irq_stat_cpu(unsigned int cpu) { u64 sum = irq_stats(cpu)->__nmi_count; #ifdef CONFIG_X86_LOCAL_APIC sum += irq_stats(cpu)->apic_timer_irqs; sum += irq_stats(cpu)->irq_spurious_count; sum += irq_stats(cpu)->apic_perf_irqs; sum += irq_stats(cpu)->apic_irq_work_irqs; sum += irq_stats(cpu)->icr_read_retry_count; if (x86_platform_ipi_callback) sum += irq_stats(cpu)->x86_platform_ipis; #endif #ifdef CONFIG_SMP sum += irq_stats(cpu)->irq_resched_count; sum += irq_stats(cpu)->irq_call_count; #endif #ifdef CONFIG_X86_THERMAL_VECTOR sum += irq_stats(cpu)->irq_thermal_count; #endif #ifdef CONFIG_X86_MCE_THRESHOLD sum += irq_stats(cpu)->irq_threshold_count; #endif #ifdef CONFIG_X86_HV_CALLBACK_VECTOR sum += irq_stats(cpu)->irq_hv_callback_count; #endif #if IS_ENABLED(CONFIG_HYPERV) sum += irq_stats(cpu)->irq_hv_reenlightenment_count; sum += irq_stats(cpu)->hyperv_stimer0_count; #endif #ifdef CONFIG_X86_MCE sum += per_cpu(mce_exception_count, cpu); sum += per_cpu(mce_poll_count, cpu); #endif return sum; } u64 arch_irq_stat(void) { u64 sum = atomic_read(&irq_err_count); return sum; } static __always_inline void handle_irq(struct irq_desc *desc, struct pt_regs *regs) { if (IS_ENABLED(CONFIG_X86_64)) generic_handle_irq_desc(desc); else __handle_irq(desc, regs); } /* * common_interrupt() handles all normal device IRQ's (the special SMP * cross-CPU interrupts have their own entry points). */ DEFINE_IDTENTRY_IRQ(common_interrupt) { struct pt_regs *old_regs = set_irq_regs(regs); struct irq_desc *desc; /* entry code tells RCU that we're not quiescent. Check it. */ RCU_LOCKDEP_WARN(!rcu_is_watching(), "IRQ failed to wake up RCU"); desc = __this_cpu_read(vector_irq[vector]); if (likely(!IS_ERR_OR_NULL(desc))) { handle_irq(desc, regs); } else { apic_eoi(); if (desc == VECTOR_UNUSED) { pr_emerg_ratelimited("%s: %d.%u No irq handler for vector\n", __func__, smp_processor_id(), vector); } else { __this_cpu_write(vector_irq[vector], VECTOR_UNUSED); } } set_irq_regs(old_regs); } #ifdef CONFIG_X86_LOCAL_APIC /* Function pointer for generic interrupt vector handling */ void (*x86_platform_ipi_callback)(void) = NULL; /* * Handler for X86_PLATFORM_IPI_VECTOR. */ DEFINE_IDTENTRY_SYSVEC(sysvec_x86_platform_ipi) { struct pt_regs *old_regs = set_irq_regs(regs); apic_eoi(); trace_x86_platform_ipi_entry(X86_PLATFORM_IPI_VECTOR); inc_irq_stat(x86_platform_ipis); if (x86_platform_ipi_callback) x86_platform_ipi_callback(); trace_x86_platform_ipi_exit(X86_PLATFORM_IPI_VECTOR); set_irq_regs(old_regs); } #endif #ifdef CONFIG_HAVE_KVM static void dummy_handler(void) {} static void (*kvm_posted_intr_wakeup_handler)(void) = dummy_handler; void kvm_set_posted_intr_wakeup_handler(void (*handler)(void)) { if (handler) kvm_posted_intr_wakeup_handler = handler; else { kvm_posted_intr_wakeup_handler = dummy_handler; synchronize_rcu(); } } EXPORT_SYMBOL_GPL(kvm_set_posted_intr_wakeup_handler); /* * Handler for POSTED_INTERRUPT_VECTOR. */ DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_kvm_posted_intr_ipi) { apic_eoi(); inc_irq_stat(kvm_posted_intr_ipis); } /* * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR. */ DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_posted_intr_wakeup_ipi) { apic_eoi(); inc_irq_stat(kvm_posted_intr_wakeup_ipis); kvm_posted_intr_wakeup_handler(); } /* * Handler for POSTED_INTERRUPT_NESTED_VECTOR. */ DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_kvm_posted_intr_nested_ipi) { apic_eoi(); inc_irq_stat(kvm_posted_intr_nested_ipis); } #endif #ifdef CONFIG_HOTPLUG_CPU /* A cpu has been removed from cpu_online_mask. Reset irq affinities. */ void fixup_irqs(void) { unsigned int irr, vector; struct irq_desc *desc; struct irq_data *data; struct irq_chip *chip; irq_migrate_all_off_this_cpu(); /* * We can remove mdelay() and then send spurious interrupts to * new cpu targets for all the irqs that were handled previously by * this cpu. While it works, I have seen spurious interrupt messages * (nothing wrong but still...). * * So for now, retain mdelay(1) and check the IRR and then send those * interrupts to new targets as this cpu is already offlined... */ mdelay(1); /* * We can walk the vector array of this cpu without holding * vector_lock because the cpu is already marked !online, so * nothing else will touch it. */ for (vector = FIRST_EXTERNAL_VECTOR; vector < NR_VECTORS; vector++) { if (IS_ERR_OR_NULL(__this_cpu_read(vector_irq[vector]))) continue; irr = apic_read(APIC_IRR + (vector / 32 * 0x10)); if (irr & (1 << (vector % 32))) { desc = __this_cpu_read(vector_irq[vector]); raw_spin_lock(&desc->lock); data = irq_desc_get_irq_data(desc); chip = irq_data_get_irq_chip(data); if (chip->irq_retrigger) { chip->irq_retrigger(data); __this_cpu_write(vector_irq[vector], VECTOR_RETRIGGERED); } raw_spin_unlock(&desc->lock); } if (__this_cpu_read(vector_irq[vector]) != VECTOR_RETRIGGERED) __this_cpu_write(vector_irq[vector], VECTOR_UNUSED); } } #endif #ifdef CONFIG_X86_THERMAL_VECTOR static void smp_thermal_vector(void) { if (x86_thermal_enabled()) intel_thermal_interrupt(); else pr_err("CPU%d: Unexpected LVT thermal interrupt!\n", smp_processor_id()); } DEFINE_IDTENTRY_SYSVEC(sysvec_thermal) { trace_thermal_apic_entry(THERMAL_APIC_VECTOR); inc_irq_stat(irq_thermal_count); smp_thermal_vector(); trace_thermal_apic_exit(THERMAL_APIC_VECTOR); apic_eoi(); } #endif
linux-master
arch/x86/kernel/irq.c
// SPDX-License-Identifier: GPL-2.0 /* * X86 trace clocks */ #include <asm/trace_clock.h> #include <asm/barrier.h> #include <asm/msr.h> /* * trace_clock_x86_tsc(): A clock that is just the cycle counter. * * Unlike the other clocks, this is not in nanoseconds. */ u64 notrace trace_clock_x86_tsc(void) { return rdtsc_ordered(); }
linux-master
arch/x86/kernel/trace_clock.c
// SPDX-License-Identifier: GPL-2.0 /* * Memory preserving reboot related code. * * Created by: Hariprasad Nellitheertha ([email protected]) * Copyright (C) IBM Corporation, 2004. All rights reserved */ #include <linux/slab.h> #include <linux/errno.h> #include <linux/highmem.h> #include <linux/crash_dump.h> #include <linux/uio.h> static inline bool is_crashed_pfn_valid(unsigned long pfn) { #ifndef CONFIG_X86_PAE /* * non-PAE kdump kernel executed from a PAE one will crop high pte * bits and poke unwanted space counting again from address 0, we * don't want that. pte must fit into unsigned long. In fact the * test checks high 12 bits for being zero (pfn will be shifted left * by PAGE_SHIFT). */ return pte_pfn(pfn_pte(pfn, __pgprot(0))) == pfn; #else return true; #endif } ssize_t copy_oldmem_page(struct iov_iter *iter, unsigned long pfn, size_t csize, unsigned long offset) { void *vaddr; if (!csize) return 0; if (!is_crashed_pfn_valid(pfn)) return -EFAULT; vaddr = kmap_local_pfn(pfn); csize = copy_to_iter(vaddr + offset, csize, iter); kunmap_local(vaddr); return csize; }
linux-master
arch/x86/kernel/crash_dump_32.c
// SPDX-License-Identifier: GPL-2.0 /* * Implement 'Simple Boot Flag Specification 2.0' */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/string.h> #include <linux/spinlock.h> #include <linux/acpi.h> #include <asm/io.h> #include <linux/mc146818rtc.h> #define SBF_RESERVED (0x78) #define SBF_PNPOS (1<<0) #define SBF_BOOTING (1<<1) #define SBF_DIAG (1<<2) #define SBF_PARITY (1<<7) int sbf_port __initdata = -1; /* set via acpi_boot_init() */ static int __init parity(u8 v) { int x = 0; int i; for (i = 0; i < 8; i++) { x ^= (v & 1); v >>= 1; } return x; } static void __init sbf_write(u8 v) { unsigned long flags; if (sbf_port != -1) { v &= ~SBF_PARITY; if (!parity(v)) v |= SBF_PARITY; printk(KERN_INFO "Simple Boot Flag at 0x%x set to 0x%x\n", sbf_port, v); spin_lock_irqsave(&rtc_lock, flags); CMOS_WRITE(v, sbf_port); spin_unlock_irqrestore(&rtc_lock, flags); } } static u8 __init sbf_read(void) { unsigned long flags; u8 v; if (sbf_port == -1) return 0; spin_lock_irqsave(&rtc_lock, flags); v = CMOS_READ(sbf_port); spin_unlock_irqrestore(&rtc_lock, flags); return v; } static int __init sbf_value_valid(u8 v) { if (v & SBF_RESERVED) /* Reserved bits */ return 0; if (!parity(v)) return 0; return 1; } static int __init sbf_init(void) { u8 v; if (sbf_port == -1) return 0; v = sbf_read(); if (!sbf_value_valid(v)) { printk(KERN_WARNING "Simple Boot Flag value 0x%x read from " "CMOS RAM was invalid\n", v); } v &= ~SBF_RESERVED; v &= ~SBF_BOOTING; v &= ~SBF_DIAG; #if defined(CONFIG_ISAPNP) v |= SBF_PNPOS; #endif sbf_write(v); return 0; } arch_initcall(sbf_init);
linux-master
arch/x86/kernel/bootflag.c
// SPDX-License-Identifier: GPL-2.0 /* * RTC related functions */ #include <linux/platform_device.h> #include <linux/mc146818rtc.h> #include <linux/export.h> #include <linux/pnp.h> #include <asm/vsyscall.h> #include <asm/x86_init.h> #include <asm/time.h> #include <asm/intel-mid.h> #include <asm/setup.h> #ifdef CONFIG_X86_32 /* * This is a special lock that is owned by the CPU and holds the index * register we are working with. It is required for NMI access to the * CMOS/RTC registers. See arch/x86/include/asm/mc146818rtc.h for details. */ volatile unsigned long cmos_lock; EXPORT_SYMBOL(cmos_lock); #endif /* CONFIG_X86_32 */ DEFINE_SPINLOCK(rtc_lock); EXPORT_SYMBOL(rtc_lock); /* * In order to set the CMOS clock precisely, mach_set_cmos_time has to be * called 500 ms after the second nowtime has started, because when * nowtime is written into the registers of the CMOS clock, it will * jump to the next second precisely 500 ms later. Check the Motorola * MC146818A or Dallas DS12887 data sheet for details. */ int mach_set_cmos_time(const struct timespec64 *now) { unsigned long long nowtime = now->tv_sec; struct rtc_time tm; int retval = 0; rtc_time64_to_tm(nowtime, &tm); if (!rtc_valid_tm(&tm)) { retval = mc146818_set_time(&tm); if (retval) printk(KERN_ERR "%s: RTC write failed with error %d\n", __func__, retval); } else { printk(KERN_ERR "%s: Invalid RTC value: write of %llx to RTC failed\n", __func__, nowtime); retval = -EINVAL; } return retval; } void mach_get_cmos_time(struct timespec64 *now) { struct rtc_time tm; /* * If pm_trace abused the RTC as storage, set the timespec to 0, * which tells the caller that this RTC value is unusable. */ if (!pm_trace_rtc_valid()) { now->tv_sec = now->tv_nsec = 0; return; } if (mc146818_get_time(&tm)) { pr_err("Unable to read current time from RTC\n"); now->tv_sec = now->tv_nsec = 0; return; } now->tv_sec = rtc_tm_to_time64(&tm); now->tv_nsec = 0; } /* Routines for accessing the CMOS RAM/RTC. */ unsigned char rtc_cmos_read(unsigned char addr) { unsigned char val; lock_cmos_prefix(addr); outb(addr, RTC_PORT(0)); val = inb(RTC_PORT(1)); lock_cmos_suffix(addr); return val; } EXPORT_SYMBOL(rtc_cmos_read); void rtc_cmos_write(unsigned char val, unsigned char addr) { lock_cmos_prefix(addr); outb(addr, RTC_PORT(0)); outb(val, RTC_PORT(1)); lock_cmos_suffix(addr); } EXPORT_SYMBOL(rtc_cmos_write); int update_persistent_clock64(struct timespec64 now) { return x86_platform.set_wallclock(&now); } /* not static: needed by APM */ void read_persistent_clock64(struct timespec64 *ts) { x86_platform.get_wallclock(ts); } static struct resource rtc_resources[] = { [0] = { .start = RTC_PORT(0), .end = RTC_PORT(1), .flags = IORESOURCE_IO, }, [1] = { .start = RTC_IRQ, .end = RTC_IRQ, .flags = IORESOURCE_IRQ, } }; static struct platform_device rtc_device = { .name = "rtc_cmos", .id = -1, .resource = rtc_resources, .num_resources = ARRAY_SIZE(rtc_resources), }; static __init int add_rtc_cmos(void) { #ifdef CONFIG_PNP static const char * const ids[] __initconst = { "PNP0b00", "PNP0b01", "PNP0b02", }; struct pnp_dev *dev; int i; pnp_for_each_dev(dev) { for (i = 0; i < ARRAY_SIZE(ids); i++) { if (compare_pnp_id(dev->id, ids[i]) != 0) return 0; } } #endif if (!x86_platform.legacy.rtc) return -ENODEV; platform_device_register(&rtc_device); dev_info(&rtc_device.dev, "registered platform RTC device (no PNP device found)\n"); return 0; } device_initcall(add_rtc_cmos);
linux-master
arch/x86/kernel/rtc.c
// SPDX-License-Identifier: GPL-2.0-or-later /* paravirtual clock -- common code used by kvm/xen */ #include <linux/clocksource.h> #include <linux/kernel.h> #include <linux/percpu.h> #include <linux/notifier.h> #include <linux/sched.h> #include <linux/gfp.h> #include <linux/memblock.h> #include <linux/nmi.h> #include <asm/fixmap.h> #include <asm/pvclock.h> #include <asm/vgtod.h> static u8 valid_flags __read_mostly = 0; static struct pvclock_vsyscall_time_info *pvti_cpu0_va __read_mostly; void pvclock_set_flags(u8 flags) { valid_flags = flags; } unsigned long pvclock_tsc_khz(struct pvclock_vcpu_time_info *src) { u64 pv_tsc_khz = 1000000ULL << 32; do_div(pv_tsc_khz, src->tsc_to_system_mul); if (src->tsc_shift < 0) pv_tsc_khz <<= -src->tsc_shift; else pv_tsc_khz >>= src->tsc_shift; return pv_tsc_khz; } void pvclock_touch_watchdogs(void) { touch_softlockup_watchdog_sync(); clocksource_touch_watchdog(); rcu_cpu_stall_reset(); reset_hung_task_detector(); } static atomic64_t last_value = ATOMIC64_INIT(0); void pvclock_resume(void) { atomic64_set(&last_value, 0); } u8 pvclock_read_flags(struct pvclock_vcpu_time_info *src) { unsigned version; u8 flags; do { version = pvclock_read_begin(src); flags = src->flags; } while (pvclock_read_retry(src, version)); return flags & valid_flags; } static __always_inline u64 __pvclock_clocksource_read(struct pvclock_vcpu_time_info *src, bool dowd) { unsigned version; u64 ret; u64 last; u8 flags; do { version = pvclock_read_begin(src); ret = __pvclock_read_cycles(src, rdtsc_ordered()); flags = src->flags; } while (pvclock_read_retry(src, version)); if (dowd && unlikely((flags & PVCLOCK_GUEST_STOPPED) != 0)) { src->flags &= ~PVCLOCK_GUEST_STOPPED; pvclock_touch_watchdogs(); } if ((valid_flags & PVCLOCK_TSC_STABLE_BIT) && (flags & PVCLOCK_TSC_STABLE_BIT)) return ret; /* * Assumption here is that last_value, a global accumulator, always goes * forward. If we are less than that, we should not be much smaller. * We assume there is an error margin we're inside, and then the correction * does not sacrifice accuracy. * * For reads: global may have changed between test and return, * but this means someone else updated poked the clock at a later time. * We just need to make sure we are not seeing a backwards event. * * For updates: last_value = ret is not enough, since two vcpus could be * updating at the same time, and one of them could be slightly behind, * making the assumption that last_value always go forward fail to hold. */ last = raw_atomic64_read(&last_value); do { if (ret <= last) return last; } while (!raw_atomic64_try_cmpxchg(&last_value, &last, ret)); return ret; } u64 pvclock_clocksource_read(struct pvclock_vcpu_time_info *src) { return __pvclock_clocksource_read(src, true); } noinstr u64 pvclock_clocksource_read_nowd(struct pvclock_vcpu_time_info *src) { return __pvclock_clocksource_read(src, false); } void pvclock_read_wallclock(struct pvclock_wall_clock *wall_clock, struct pvclock_vcpu_time_info *vcpu_time, struct timespec64 *ts) { u32 version; u64 delta; struct timespec64 now; /* get wallclock at system boot */ do { version = wall_clock->version; rmb(); /* fetch version before time */ /* * Note: wall_clock->sec is a u32 value, so it can * only store dates between 1970 and 2106. To allow * times beyond that, we need to create a new hypercall * interface with an extended pvclock_wall_clock structure * like ARM has. */ now.tv_sec = wall_clock->sec; now.tv_nsec = wall_clock->nsec; rmb(); /* fetch time before checking version */ } while ((wall_clock->version & 1) || (version != wall_clock->version)); delta = pvclock_clocksource_read(vcpu_time); /* time since system boot */ delta += now.tv_sec * NSEC_PER_SEC + now.tv_nsec; now.tv_nsec = do_div(delta, NSEC_PER_SEC); now.tv_sec = delta; set_normalized_timespec64(ts, now.tv_sec, now.tv_nsec); } void pvclock_set_pvti_cpu0_va(struct pvclock_vsyscall_time_info *pvti) { WARN_ON(vclock_was_used(VDSO_CLOCKMODE_PVCLOCK)); pvti_cpu0_va = pvti; } struct pvclock_vsyscall_time_info *pvclock_get_pvti_cpu0_va(void) { return pvti_cpu0_va; } EXPORT_SYMBOL_GPL(pvclock_get_pvti_cpu0_va);
linux-master
arch/x86/kernel/pvclock.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/static_call.h> #include <linux/memory.h> #include <linux/bug.h> #include <asm/text-patching.h> enum insn_type { CALL = 0, /* site call */ NOP = 1, /* site cond-call */ JMP = 2, /* tramp / site tail-call */ RET = 3, /* tramp / site cond-tail-call */ JCC = 4, }; /* * ud1 %esp, %ecx - a 3 byte #UD that is unique to trampolines, chosen such * that there is no false-positive trampoline identification while also being a * speculation stop. */ static const u8 tramp_ud[] = { 0x0f, 0xb9, 0xcc }; /* * cs cs cs xorl %eax, %eax - a single 5 byte instruction that clears %[er]ax */ static const u8 xor5rax[] = { 0x2e, 0x2e, 0x2e, 0x31, 0xc0 }; static const u8 retinsn[] = { RET_INSN_OPCODE, 0xcc, 0xcc, 0xcc, 0xcc }; static u8 __is_Jcc(u8 *insn) /* Jcc.d32 */ { u8 ret = 0; if (insn[0] == 0x0f) { u8 tmp = insn[1]; if ((tmp & 0xf0) == 0x80) ret = tmp; } return ret; } extern void __static_call_return(void); asm (".global __static_call_return\n\t" ".type __static_call_return, @function\n\t" ASM_FUNC_ALIGN "\n\t" "__static_call_return:\n\t" ANNOTATE_NOENDBR ANNOTATE_RETPOLINE_SAFE "ret; int3\n\t" ".size __static_call_return, . - __static_call_return \n\t"); static void __ref __static_call_transform(void *insn, enum insn_type type, void *func, bool modinit) { const void *emulate = NULL; int size = CALL_INSN_SIZE; const void *code; u8 op, buf[6]; if ((type == JMP || type == RET) && (op = __is_Jcc(insn))) type = JCC; switch (type) { case CALL: func = callthunks_translate_call_dest(func); code = text_gen_insn(CALL_INSN_OPCODE, insn, func); if (func == &__static_call_return0) { emulate = code; code = &xor5rax; } break; case NOP: code = x86_nops[5]; break; case JMP: code = text_gen_insn(JMP32_INSN_OPCODE, insn, func); break; case RET: if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) code = text_gen_insn(JMP32_INSN_OPCODE, insn, x86_return_thunk); else code = &retinsn; break; case JCC: if (!func) { func = __static_call_return; if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) func = x86_return_thunk; } buf[0] = 0x0f; __text_gen_insn(buf+1, op, insn+1, func, 5); code = buf; size = 6; break; } if (memcmp(insn, code, size) == 0) return; if (system_state == SYSTEM_BOOTING || modinit) return text_poke_early(insn, code, size); text_poke_bp(insn, code, size, emulate); } static void __static_call_validate(u8 *insn, bool tail, bool tramp) { u8 opcode = insn[0]; if (tramp && memcmp(insn+5, tramp_ud, 3)) { pr_err("trampoline signature fail"); BUG(); } if (tail) { if (opcode == JMP32_INSN_OPCODE || opcode == RET_INSN_OPCODE || __is_Jcc(insn)) return; } else { if (opcode == CALL_INSN_OPCODE || !memcmp(insn, x86_nops[5], 5) || !memcmp(insn, xor5rax, 5)) return; } /* * If we ever trigger this, our text is corrupt, we'll probably not live long. */ pr_err("unexpected static_call insn opcode 0x%x at %pS\n", opcode, insn); BUG(); } static inline enum insn_type __sc_insn(bool null, bool tail) { /* * Encode the following table without branches: * * tail null insn * -----+-------+------ * 0 | 0 | CALL * 0 | 1 | NOP * 1 | 0 | JMP * 1 | 1 | RET */ return 2*tail + null; } void arch_static_call_transform(void *site, void *tramp, void *func, bool tail) { mutex_lock(&text_mutex); if (tramp) { __static_call_validate(tramp, true, true); __static_call_transform(tramp, __sc_insn(!func, true), func, false); } if (IS_ENABLED(CONFIG_HAVE_STATIC_CALL_INLINE) && site) { __static_call_validate(site, tail, false); __static_call_transform(site, __sc_insn(!func, tail), func, false); } mutex_unlock(&text_mutex); } EXPORT_SYMBOL_GPL(arch_static_call_transform); #ifdef CONFIG_RETHUNK /* * This is called by apply_returns() to fix up static call trampolines, * specifically ARCH_DEFINE_STATIC_CALL_NULL_TRAMP which is recorded as * having a return trampoline. * * The problem is that static_call() is available before determining * X86_FEATURE_RETHUNK and, by implication, running alternatives. * * This means that __static_call_transform() above can have overwritten the * return trampoline and we now need to fix things up to be consistent. */ bool __static_call_fixup(void *tramp, u8 op, void *dest) { unsigned long addr = (unsigned long)tramp; /* * Not all .return_sites are a static_call trampoline (most are not). * Check if the 3 bytes after the return are still kernel text, if not, * then this definitely is not a trampoline and we need not worry * further. * * This avoids the memcmp() below tripping over pagefaults etc.. */ if (((addr >> PAGE_SHIFT) != ((addr + 7) >> PAGE_SHIFT)) && !kernel_text_address(addr + 7)) return false; if (memcmp(tramp+5, tramp_ud, 3)) { /* Not a trampoline site, not our problem. */ return false; } mutex_lock(&text_mutex); if (op == RET_INSN_OPCODE || dest == &__x86_return_thunk) __static_call_transform(tramp, RET, NULL, true); mutex_unlock(&text_mutex); return true; } #endif
linux-master
arch/x86/kernel/static_call.c
// SPDX-License-Identifier: GPL-2.0-only /* * Architecture specific (i386/x86_64) functions for kexec based crash dumps. * * Created by: Hariprasad Nellitheertha ([email protected]) * * Copyright (C) IBM Corporation, 2004. All rights reserved. * Copyright (C) Red Hat Inc., 2014. All rights reserved. * Authors: * Vivek Goyal <[email protected]> * */ #define pr_fmt(fmt) "kexec: " fmt #include <linux/types.h> #include <linux/kernel.h> #include <linux/smp.h> #include <linux/reboot.h> #include <linux/kexec.h> #include <linux/delay.h> #include <linux/elf.h> #include <linux/elfcore.h> #include <linux/export.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/memblock.h> #include <asm/processor.h> #include <asm/hardirq.h> #include <asm/nmi.h> #include <asm/hw_irq.h> #include <asm/apic.h> #include <asm/e820/types.h> #include <asm/io_apic.h> #include <asm/hpet.h> #include <linux/kdebug.h> #include <asm/cpu.h> #include <asm/reboot.h> #include <asm/intel_pt.h> #include <asm/crash.h> #include <asm/cmdline.h> /* Used while preparing memory map entries for second kernel */ struct crash_memmap_data { struct boot_params *params; /* Type of memory */ unsigned int type; }; #if defined(CONFIG_SMP) && defined(CONFIG_X86_LOCAL_APIC) static void kdump_nmi_callback(int cpu, struct pt_regs *regs) { crash_save_cpu(regs, cpu); /* * Disable Intel PT to stop its logging */ cpu_emergency_stop_pt(); disable_local_APIC(); } void kdump_nmi_shootdown_cpus(void) { nmi_shootdown_cpus(kdump_nmi_callback); disable_local_APIC(); } /* Override the weak function in kernel/panic.c */ void crash_smp_send_stop(void) { static int cpus_stopped; if (cpus_stopped) return; if (smp_ops.crash_stop_other_cpus) smp_ops.crash_stop_other_cpus(); else smp_send_stop(); cpus_stopped = 1; } #else void crash_smp_send_stop(void) { /* There are no cpus to shootdown */ } #endif void native_machine_crash_shutdown(struct pt_regs *regs) { /* This function is only called after the system * has panicked or is otherwise in a critical state. * The minimum amount of code to allow a kexec'd kernel * to run successfully needs to happen here. * * In practice this means shooting down the other cpus in * an SMP system. */ /* The kernel is broken so disable interrupts */ local_irq_disable(); crash_smp_send_stop(); cpu_emergency_disable_virtualization(); /* * Disable Intel PT to stop its logging */ cpu_emergency_stop_pt(); #ifdef CONFIG_X86_IO_APIC /* Prevent crash_kexec() from deadlocking on ioapic_lock. */ ioapic_zap_locks(); clear_IO_APIC(); #endif lapic_shutdown(); restore_boot_irq_mode(); #ifdef CONFIG_HPET_TIMER hpet_disable(); #endif crash_save_cpu(regs, safe_smp_processor_id()); } #if defined(CONFIG_KEXEC_FILE) || defined(CONFIG_CRASH_HOTPLUG) static int get_nr_ram_ranges_callback(struct resource *res, void *arg) { unsigned int *nr_ranges = arg; (*nr_ranges)++; return 0; } /* Gather all the required information to prepare elf headers for ram regions */ static struct crash_mem *fill_up_crash_elf_data(void) { unsigned int nr_ranges = 0; struct crash_mem *cmem; walk_system_ram_res(0, -1, &nr_ranges, get_nr_ram_ranges_callback); if (!nr_ranges) return NULL; /* * Exclusion of crash region and/or crashk_low_res may cause * another range split. So add extra two slots here. */ nr_ranges += 2; cmem = vzalloc(struct_size(cmem, ranges, nr_ranges)); if (!cmem) return NULL; cmem->max_nr_ranges = nr_ranges; cmem->nr_ranges = 0; return cmem; } /* * Look for any unwanted ranges between mstart, mend and remove them. This * might lead to split and split ranges are put in cmem->ranges[] array */ static int elf_header_exclude_ranges(struct crash_mem *cmem) { int ret = 0; /* Exclude the low 1M because it is always reserved */ ret = crash_exclude_mem_range(cmem, 0, (1<<20)-1); if (ret) return ret; /* Exclude crashkernel region */ ret = crash_exclude_mem_range(cmem, crashk_res.start, crashk_res.end); if (ret) return ret; if (crashk_low_res.end) ret = crash_exclude_mem_range(cmem, crashk_low_res.start, crashk_low_res.end); return ret; } static int prepare_elf64_ram_headers_callback(struct resource *res, void *arg) { struct crash_mem *cmem = arg; cmem->ranges[cmem->nr_ranges].start = res->start; cmem->ranges[cmem->nr_ranges].end = res->end; cmem->nr_ranges++; return 0; } /* Prepare elf headers. Return addr and size */ static int prepare_elf_headers(struct kimage *image, void **addr, unsigned long *sz, unsigned long *nr_mem_ranges) { struct crash_mem *cmem; int ret; cmem = fill_up_crash_elf_data(); if (!cmem) return -ENOMEM; ret = walk_system_ram_res(0, -1, cmem, prepare_elf64_ram_headers_callback); if (ret) goto out; /* Exclude unwanted mem ranges */ ret = elf_header_exclude_ranges(cmem); if (ret) goto out; /* Return the computed number of memory ranges, for hotplug usage */ *nr_mem_ranges = cmem->nr_ranges; /* By default prepare 64bit headers */ ret = crash_prepare_elf64_headers(cmem, IS_ENABLED(CONFIG_X86_64), addr, sz); out: vfree(cmem); return ret; } #endif #ifdef CONFIG_KEXEC_FILE static int add_e820_entry(struct boot_params *params, struct e820_entry *entry) { unsigned int nr_e820_entries; nr_e820_entries = params->e820_entries; if (nr_e820_entries >= E820_MAX_ENTRIES_ZEROPAGE) return 1; memcpy(&params->e820_table[nr_e820_entries], entry, sizeof(struct e820_entry)); params->e820_entries++; return 0; } static int memmap_entry_callback(struct resource *res, void *arg) { struct crash_memmap_data *cmd = arg; struct boot_params *params = cmd->params; struct e820_entry ei; ei.addr = res->start; ei.size = resource_size(res); ei.type = cmd->type; add_e820_entry(params, &ei); return 0; } static int memmap_exclude_ranges(struct kimage *image, struct crash_mem *cmem, unsigned long long mstart, unsigned long long mend) { unsigned long start, end; cmem->ranges[0].start = mstart; cmem->ranges[0].end = mend; cmem->nr_ranges = 1; /* Exclude elf header region */ start = image->elf_load_addr; end = start + image->elf_headers_sz - 1; return crash_exclude_mem_range(cmem, start, end); } /* Prepare memory map for crash dump kernel */ int crash_setup_memmap_entries(struct kimage *image, struct boot_params *params) { int i, ret = 0; unsigned long flags; struct e820_entry ei; struct crash_memmap_data cmd; struct crash_mem *cmem; cmem = vzalloc(struct_size(cmem, ranges, 1)); if (!cmem) return -ENOMEM; memset(&cmd, 0, sizeof(struct crash_memmap_data)); cmd.params = params; /* Add the low 1M */ cmd.type = E820_TYPE_RAM; flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY; walk_iomem_res_desc(IORES_DESC_NONE, flags, 0, (1<<20)-1, &cmd, memmap_entry_callback); /* Add ACPI tables */ cmd.type = E820_TYPE_ACPI; flags = IORESOURCE_MEM | IORESOURCE_BUSY; walk_iomem_res_desc(IORES_DESC_ACPI_TABLES, flags, 0, -1, &cmd, memmap_entry_callback); /* Add ACPI Non-volatile Storage */ cmd.type = E820_TYPE_NVS; walk_iomem_res_desc(IORES_DESC_ACPI_NV_STORAGE, flags, 0, -1, &cmd, memmap_entry_callback); /* Add e820 reserved ranges */ cmd.type = E820_TYPE_RESERVED; flags = IORESOURCE_MEM; walk_iomem_res_desc(IORES_DESC_RESERVED, flags, 0, -1, &cmd, memmap_entry_callback); /* Add crashk_low_res region */ if (crashk_low_res.end) { ei.addr = crashk_low_res.start; ei.size = resource_size(&crashk_low_res); ei.type = E820_TYPE_RAM; add_e820_entry(params, &ei); } /* Exclude some ranges from crashk_res and add rest to memmap */ ret = memmap_exclude_ranges(image, cmem, crashk_res.start, crashk_res.end); if (ret) goto out; for (i = 0; i < cmem->nr_ranges; i++) { ei.size = cmem->ranges[i].end - cmem->ranges[i].start + 1; /* If entry is less than a page, skip it */ if (ei.size < PAGE_SIZE) continue; ei.addr = cmem->ranges[i].start; ei.type = E820_TYPE_RAM; add_e820_entry(params, &ei); } out: vfree(cmem); return ret; } int crash_load_segments(struct kimage *image) { int ret; unsigned long pnum = 0; struct kexec_buf kbuf = { .image = image, .buf_min = 0, .buf_max = ULONG_MAX, .top_down = false }; /* Prepare elf headers and add a segment */ ret = prepare_elf_headers(image, &kbuf.buffer, &kbuf.bufsz, &pnum); if (ret) return ret; image->elf_headers = kbuf.buffer; image->elf_headers_sz = kbuf.bufsz; kbuf.memsz = kbuf.bufsz; #ifdef CONFIG_CRASH_HOTPLUG /* * The elfcorehdr segment size accounts for VMCOREINFO, kernel_map, * maximum CPUs and maximum memory ranges. */ if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) pnum = 2 + CONFIG_NR_CPUS_DEFAULT + CONFIG_CRASH_MAX_MEMORY_RANGES; else pnum += 2 + CONFIG_NR_CPUS_DEFAULT; if (pnum < (unsigned long)PN_XNUM) { kbuf.memsz = pnum * sizeof(Elf64_Phdr); kbuf.memsz += sizeof(Elf64_Ehdr); image->elfcorehdr_index = image->nr_segments; /* Mark as usable to crash kernel, else crash kernel fails on boot */ image->elf_headers_sz = kbuf.memsz; } else { pr_err("number of Phdrs %lu exceeds max\n", pnum); } #endif kbuf.buf_align = ELF_CORE_HEADER_ALIGN; kbuf.mem = KEXEC_BUF_MEM_UNKNOWN; ret = kexec_add_buffer(&kbuf); if (ret) return ret; image->elf_load_addr = kbuf.mem; pr_debug("Loaded ELF headers at 0x%lx bufsz=0x%lx memsz=0x%lx\n", image->elf_load_addr, kbuf.bufsz, kbuf.memsz); return ret; } #endif /* CONFIG_KEXEC_FILE */ #ifdef CONFIG_CRASH_HOTPLUG #undef pr_fmt #define pr_fmt(fmt) "crash hp: " fmt /* These functions provide the value for the sysfs crash_hotplug nodes */ #ifdef CONFIG_HOTPLUG_CPU int arch_crash_hotplug_cpu_support(void) { return crash_check_update_elfcorehdr(); } #endif #ifdef CONFIG_MEMORY_HOTPLUG int arch_crash_hotplug_memory_support(void) { return crash_check_update_elfcorehdr(); } #endif unsigned int arch_crash_get_elfcorehdr_size(void) { unsigned int sz; /* kernel_map, VMCOREINFO and maximum CPUs */ sz = 2 + CONFIG_NR_CPUS_DEFAULT; if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) sz += CONFIG_CRASH_MAX_MEMORY_RANGES; sz *= sizeof(Elf64_Phdr); return sz; } /** * arch_crash_handle_hotplug_event() - Handle hotplug elfcorehdr changes * @image: a pointer to kexec_crash_image * * Prepare the new elfcorehdr and replace the existing elfcorehdr. */ void arch_crash_handle_hotplug_event(struct kimage *image) { void *elfbuf = NULL, *old_elfcorehdr; unsigned long nr_mem_ranges; unsigned long mem, memsz; unsigned long elfsz = 0; /* * As crash_prepare_elf64_headers() has already described all * possible CPUs, there is no need to update the elfcorehdr * for additional CPU changes. */ if ((image->file_mode || image->elfcorehdr_updated) && ((image->hp_action == KEXEC_CRASH_HP_ADD_CPU) || (image->hp_action == KEXEC_CRASH_HP_REMOVE_CPU))) return; /* * Create the new elfcorehdr reflecting the changes to CPU and/or * memory resources. */ if (prepare_elf_headers(image, &elfbuf, &elfsz, &nr_mem_ranges)) { pr_err("unable to create new elfcorehdr"); goto out; } /* * Obtain address and size of the elfcorehdr segment, and * check it against the new elfcorehdr buffer. */ mem = image->segment[image->elfcorehdr_index].mem; memsz = image->segment[image->elfcorehdr_index].memsz; if (elfsz > memsz) { pr_err("update elfcorehdr elfsz %lu > memsz %lu", elfsz, memsz); goto out; } /* * Copy new elfcorehdr over the old elfcorehdr at destination. */ old_elfcorehdr = kmap_local_page(pfn_to_page(mem >> PAGE_SHIFT)); if (!old_elfcorehdr) { pr_err("mapping elfcorehdr segment failed\n"); goto out; } /* * Temporarily invalidate the crash image while the * elfcorehdr is updated. */ xchg(&kexec_crash_image, NULL); memcpy_flushcache(old_elfcorehdr, elfbuf, elfsz); xchg(&kexec_crash_image, image); kunmap_local(old_elfcorehdr); pr_debug("updated elfcorehdr\n"); out: vfree(elfbuf); } #endif
linux-master
arch/x86/kernel/crash.c
// SPDX-License-Identifier: GPL-2.0 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/init.h> #include <linux/sched.h> #include <linux/kthread.h> #include <linux/workqueue.h> #include <linux/memblock.h> #include <asm/proto.h> #include <asm/setup.h> /* * Some BIOSes seem to corrupt the low 64k of memory during events * like suspend/resume and unplugging an HDMI cable. Reserve all * remaining free memory in that area and fill it with a distinct * pattern. */ #define MAX_SCAN_AREAS 8 static int __read_mostly memory_corruption_check = -1; static unsigned __read_mostly corruption_check_size = 64*1024; static unsigned __read_mostly corruption_check_period = 60; /* seconds */ static struct scan_area { u64 addr; u64 size; } scan_areas[MAX_SCAN_AREAS]; static int num_scan_areas; static __init int set_corruption_check(char *arg) { ssize_t ret; unsigned long val; if (!arg) { pr_err("memory_corruption_check config string not provided\n"); return -EINVAL; } ret = kstrtoul(arg, 10, &val); if (ret) return ret; memory_corruption_check = val; return 0; } early_param("memory_corruption_check", set_corruption_check); static __init int set_corruption_check_period(char *arg) { ssize_t ret; unsigned long val; if (!arg) { pr_err("memory_corruption_check_period config string not provided\n"); return -EINVAL; } ret = kstrtoul(arg, 10, &val); if (ret) return ret; corruption_check_period = val; return 0; } early_param("memory_corruption_check_period", set_corruption_check_period); static __init int set_corruption_check_size(char *arg) { char *end; unsigned size; if (!arg) { pr_err("memory_corruption_check_size config string not provided\n"); return -EINVAL; } size = memparse(arg, &end); if (*end == '\0') corruption_check_size = size; return (size == corruption_check_size) ? 0 : -EINVAL; } early_param("memory_corruption_check_size", set_corruption_check_size); void __init setup_bios_corruption_check(void) { phys_addr_t start, end; u64 i; if (memory_corruption_check == -1) { memory_corruption_check = #ifdef CONFIG_X86_BOOTPARAM_MEMORY_CORRUPTION_CHECK 1 #else 0 #endif ; } if (corruption_check_size == 0) memory_corruption_check = 0; if (!memory_corruption_check) return; corruption_check_size = round_up(corruption_check_size, PAGE_SIZE); for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end, NULL) { start = clamp_t(phys_addr_t, round_up(start, PAGE_SIZE), PAGE_SIZE, corruption_check_size); end = clamp_t(phys_addr_t, round_down(end, PAGE_SIZE), PAGE_SIZE, corruption_check_size); if (start >= end) continue; memblock_reserve(start, end - start); scan_areas[num_scan_areas].addr = start; scan_areas[num_scan_areas].size = end - start; /* Assume we've already mapped this early memory */ memset(__va(start), 0, end - start); if (++num_scan_areas >= MAX_SCAN_AREAS) break; } if (num_scan_areas) pr_info("Scanning %d areas for low memory corruption\n", num_scan_areas); } static void check_for_bios_corruption(void) { int i; int corruption = 0; if (!memory_corruption_check) return; for (i = 0; i < num_scan_areas; i++) { unsigned long *addr = __va(scan_areas[i].addr); unsigned long size = scan_areas[i].size; for (; size; addr++, size -= sizeof(unsigned long)) { if (!*addr) continue; pr_err("Corrupted low memory at %p (%lx phys) = %08lx\n", addr, __pa(addr), *addr); corruption = 1; *addr = 0; } } WARN_ONCE(corruption, KERN_ERR "Memory corruption detected in low memory\n"); } static void check_corruption(struct work_struct *dummy); static DECLARE_DELAYED_WORK(bios_check_work, check_corruption); static void check_corruption(struct work_struct *dummy) { check_for_bios_corruption(); schedule_delayed_work(&bios_check_work, round_jiffies_relative(corruption_check_period*HZ)); } static int start_periodic_check_for_corruption(void) { if (!num_scan_areas || !memory_corruption_check || corruption_check_period == 0) return 0; pr_info("Scanning for low memory corruption every %d seconds\n", corruption_check_period); /* First time we run the checks right away */ schedule_delayed_work(&bios_check_work, 0); return 0; } device_initcall(start_periodic_check_for_corruption);
linux-master
arch/x86/kernel/check.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/clockchips.h> #include <linux/interrupt.h> #include <linux/export.h> #include <linux/delay.h> #include <linux/hpet.h> #include <linux/cpu.h> #include <linux/irq.h> #include <asm/irq_remapping.h> #include <asm/hpet.h> #include <asm/time.h> #include <asm/mwait.h> #undef pr_fmt #define pr_fmt(fmt) "hpet: " fmt enum hpet_mode { HPET_MODE_UNUSED, HPET_MODE_LEGACY, HPET_MODE_CLOCKEVT, HPET_MODE_DEVICE, }; struct hpet_channel { struct clock_event_device evt; unsigned int num; unsigned int cpu; unsigned int irq; unsigned int in_use; enum hpet_mode mode; unsigned int boot_cfg; char name[10]; }; struct hpet_base { unsigned int nr_channels; unsigned int nr_clockevents; unsigned int boot_cfg; struct hpet_channel *channels; }; #define HPET_MASK CLOCKSOURCE_MASK(32) #define HPET_MIN_CYCLES 128 #define HPET_MIN_PROG_DELTA (HPET_MIN_CYCLES + (HPET_MIN_CYCLES >> 1)) /* * HPET address is set in acpi/boot.c, when an ACPI entry exists */ unsigned long hpet_address; u8 hpet_blockid; /* OS timer block num */ bool hpet_msi_disable; #ifdef CONFIG_GENERIC_MSI_IRQ static DEFINE_PER_CPU(struct hpet_channel *, cpu_hpet_channel); static struct irq_domain *hpet_domain; #endif static void __iomem *hpet_virt_address; static struct hpet_base hpet_base; static bool hpet_legacy_int_enabled; static unsigned long hpet_freq; bool boot_hpet_disable; bool hpet_force_user; static bool hpet_verbose; static inline struct hpet_channel *clockevent_to_channel(struct clock_event_device *evt) { return container_of(evt, struct hpet_channel, evt); } inline unsigned int hpet_readl(unsigned int a) { return readl(hpet_virt_address + a); } static inline void hpet_writel(unsigned int d, unsigned int a) { writel(d, hpet_virt_address + a); } static inline void hpet_set_mapping(void) { hpet_virt_address = ioremap(hpet_address, HPET_MMAP_SIZE); } static inline void hpet_clear_mapping(void) { iounmap(hpet_virt_address); hpet_virt_address = NULL; } /* * HPET command line enable / disable */ static int __init hpet_setup(char *str) { while (str) { char *next = strchr(str, ','); if (next) *next++ = 0; if (!strncmp("disable", str, 7)) boot_hpet_disable = true; if (!strncmp("force", str, 5)) hpet_force_user = true; if (!strncmp("verbose", str, 7)) hpet_verbose = true; str = next; } return 1; } __setup("hpet=", hpet_setup); static int __init disable_hpet(char *str) { boot_hpet_disable = true; return 1; } __setup("nohpet", disable_hpet); static inline int is_hpet_capable(void) { return !boot_hpet_disable && hpet_address; } /** * is_hpet_enabled - Check whether the legacy HPET timer interrupt is enabled */ int is_hpet_enabled(void) { return is_hpet_capable() && hpet_legacy_int_enabled; } EXPORT_SYMBOL_GPL(is_hpet_enabled); static void _hpet_print_config(const char *function, int line) { u32 i, id, period, cfg, status, channels, l, h; pr_info("%s(%d):\n", function, line); id = hpet_readl(HPET_ID); period = hpet_readl(HPET_PERIOD); pr_info("ID: 0x%x, PERIOD: 0x%x\n", id, period); cfg = hpet_readl(HPET_CFG); status = hpet_readl(HPET_STATUS); pr_info("CFG: 0x%x, STATUS: 0x%x\n", cfg, status); l = hpet_readl(HPET_COUNTER); h = hpet_readl(HPET_COUNTER+4); pr_info("COUNTER_l: 0x%x, COUNTER_h: 0x%x\n", l, h); channels = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1; for (i = 0; i < channels; i++) { l = hpet_readl(HPET_Tn_CFG(i)); h = hpet_readl(HPET_Tn_CFG(i)+4); pr_info("T%d: CFG_l: 0x%x, CFG_h: 0x%x\n", i, l, h); l = hpet_readl(HPET_Tn_CMP(i)); h = hpet_readl(HPET_Tn_CMP(i)+4); pr_info("T%d: CMP_l: 0x%x, CMP_h: 0x%x\n", i, l, h); l = hpet_readl(HPET_Tn_ROUTE(i)); h = hpet_readl(HPET_Tn_ROUTE(i)+4); pr_info("T%d ROUTE_l: 0x%x, ROUTE_h: 0x%x\n", i, l, h); } } #define hpet_print_config() \ do { \ if (hpet_verbose) \ _hpet_print_config(__func__, __LINE__); \ } while (0) /* * When the HPET driver (/dev/hpet) is enabled, we need to reserve * timer 0 and timer 1 in case of RTC emulation. */ #ifdef CONFIG_HPET static void __init hpet_reserve_platform_timers(void) { struct hpet_data hd; unsigned int i; memset(&hd, 0, sizeof(hd)); hd.hd_phys_address = hpet_address; hd.hd_address = hpet_virt_address; hd.hd_nirqs = hpet_base.nr_channels; /* * NOTE that hd_irq[] reflects IOAPIC input pins (LEGACY_8254 * is wrong for i8259!) not the output IRQ. Many BIOS writers * don't bother configuring *any* comparator interrupts. */ hd.hd_irq[0] = HPET_LEGACY_8254; hd.hd_irq[1] = HPET_LEGACY_RTC; for (i = 0; i < hpet_base.nr_channels; i++) { struct hpet_channel *hc = hpet_base.channels + i; if (i >= 2) hd.hd_irq[i] = hc->irq; switch (hc->mode) { case HPET_MODE_UNUSED: case HPET_MODE_DEVICE: hc->mode = HPET_MODE_DEVICE; break; case HPET_MODE_CLOCKEVT: case HPET_MODE_LEGACY: hpet_reserve_timer(&hd, hc->num); break; } } hpet_alloc(&hd); } static void __init hpet_select_device_channel(void) { int i; for (i = 0; i < hpet_base.nr_channels; i++) { struct hpet_channel *hc = hpet_base.channels + i; /* Associate the first unused channel to /dev/hpet */ if (hc->mode == HPET_MODE_UNUSED) { hc->mode = HPET_MODE_DEVICE; return; } } } #else static inline void hpet_reserve_platform_timers(void) { } static inline void hpet_select_device_channel(void) {} #endif /* Common HPET functions */ static void hpet_stop_counter(void) { u32 cfg = hpet_readl(HPET_CFG); cfg &= ~HPET_CFG_ENABLE; hpet_writel(cfg, HPET_CFG); } static void hpet_reset_counter(void) { hpet_writel(0, HPET_COUNTER); hpet_writel(0, HPET_COUNTER + 4); } static void hpet_start_counter(void) { unsigned int cfg = hpet_readl(HPET_CFG); cfg |= HPET_CFG_ENABLE; hpet_writel(cfg, HPET_CFG); } static void hpet_restart_counter(void) { hpet_stop_counter(); hpet_reset_counter(); hpet_start_counter(); } static void hpet_resume_device(void) { force_hpet_resume(); } static void hpet_resume_counter(struct clocksource *cs) { hpet_resume_device(); hpet_restart_counter(); } static void hpet_enable_legacy_int(void) { unsigned int cfg = hpet_readl(HPET_CFG); cfg |= HPET_CFG_LEGACY; hpet_writel(cfg, HPET_CFG); hpet_legacy_int_enabled = true; } static int hpet_clkevt_set_state_periodic(struct clock_event_device *evt) { unsigned int channel = clockevent_to_channel(evt)->num; unsigned int cfg, cmp, now; uint64_t delta; hpet_stop_counter(); delta = ((uint64_t)(NSEC_PER_SEC / HZ)) * evt->mult; delta >>= evt->shift; now = hpet_readl(HPET_COUNTER); cmp = now + (unsigned int)delta; cfg = hpet_readl(HPET_Tn_CFG(channel)); cfg |= HPET_TN_ENABLE | HPET_TN_PERIODIC | HPET_TN_SETVAL | HPET_TN_32BIT; hpet_writel(cfg, HPET_Tn_CFG(channel)); hpet_writel(cmp, HPET_Tn_CMP(channel)); udelay(1); /* * HPET on AMD 81xx needs a second write (with HPET_TN_SETVAL * cleared) to T0_CMP to set the period. The HPET_TN_SETVAL * bit is automatically cleared after the first write. * (See AMD-8111 HyperTransport I/O Hub Data Sheet, * Publication # 24674) */ hpet_writel((unsigned int)delta, HPET_Tn_CMP(channel)); hpet_start_counter(); hpet_print_config(); return 0; } static int hpet_clkevt_set_state_oneshot(struct clock_event_device *evt) { unsigned int channel = clockevent_to_channel(evt)->num; unsigned int cfg; cfg = hpet_readl(HPET_Tn_CFG(channel)); cfg &= ~HPET_TN_PERIODIC; cfg |= HPET_TN_ENABLE | HPET_TN_32BIT; hpet_writel(cfg, HPET_Tn_CFG(channel)); return 0; } static int hpet_clkevt_set_state_shutdown(struct clock_event_device *evt) { unsigned int channel = clockevent_to_channel(evt)->num; unsigned int cfg; cfg = hpet_readl(HPET_Tn_CFG(channel)); cfg &= ~HPET_TN_ENABLE; hpet_writel(cfg, HPET_Tn_CFG(channel)); return 0; } static int hpet_clkevt_legacy_resume(struct clock_event_device *evt) { hpet_enable_legacy_int(); hpet_print_config(); return 0; } static int hpet_clkevt_set_next_event(unsigned long delta, struct clock_event_device *evt) { unsigned int channel = clockevent_to_channel(evt)->num; u32 cnt; s32 res; cnt = hpet_readl(HPET_COUNTER); cnt += (u32) delta; hpet_writel(cnt, HPET_Tn_CMP(channel)); /* * HPETs are a complete disaster. The compare register is * based on a equal comparison and neither provides a less * than or equal functionality (which would require to take * the wraparound into account) nor a simple count down event * mode. Further the write to the comparator register is * delayed internally up to two HPET clock cycles in certain * chipsets (ATI, ICH9,10). Some newer AMD chipsets have even * longer delays. We worked around that by reading back the * compare register, but that required another workaround for * ICH9,10 chips where the first readout after write can * return the old stale value. We already had a minimum * programming delta of 5us enforced, but a NMI or SMI hitting * between the counter readout and the comparator write can * move us behind that point easily. Now instead of reading * the compare register back several times, we make the ETIME * decision based on the following: Return ETIME if the * counter value after the write is less than HPET_MIN_CYCLES * away from the event or if the counter is already ahead of * the event. The minimum programming delta for the generic * clockevents code is set to 1.5 * HPET_MIN_CYCLES. */ res = (s32)(cnt - hpet_readl(HPET_COUNTER)); return res < HPET_MIN_CYCLES ? -ETIME : 0; } static void hpet_init_clockevent(struct hpet_channel *hc, unsigned int rating) { struct clock_event_device *evt = &hc->evt; evt->rating = rating; evt->irq = hc->irq; evt->name = hc->name; evt->cpumask = cpumask_of(hc->cpu); evt->set_state_oneshot = hpet_clkevt_set_state_oneshot; evt->set_next_event = hpet_clkevt_set_next_event; evt->set_state_shutdown = hpet_clkevt_set_state_shutdown; evt->features = CLOCK_EVT_FEAT_ONESHOT; if (hc->boot_cfg & HPET_TN_PERIODIC) { evt->features |= CLOCK_EVT_FEAT_PERIODIC; evt->set_state_periodic = hpet_clkevt_set_state_periodic; } } static void __init hpet_legacy_clockevent_register(struct hpet_channel *hc) { /* * Start HPET with the boot CPU's cpumask and make it global after * the IO_APIC has been initialized. */ hc->cpu = boot_cpu_data.cpu_index; strscpy(hc->name, "hpet", sizeof(hc->name)); hpet_init_clockevent(hc, 50); hc->evt.tick_resume = hpet_clkevt_legacy_resume; /* * Legacy horrors and sins from the past. HPET used periodic mode * unconditionally forever on the legacy channel 0. Removing the * below hack and using the conditional in hpet_init_clockevent() * makes at least Qemu and one hardware machine fail to boot. * There are two issues which cause the boot failure: * * #1 After the timer delivery test in IOAPIC and the IOAPIC setup * the next interrupt is not delivered despite the HPET channel * being programmed correctly. Reprogramming the HPET after * switching to IOAPIC makes it work again. After fixing this, * the next issue surfaces: * * #2 Due to the unconditional periodic mode availability the Local * APIC timer calibration can hijack the global clockevents * event handler without causing damage. Using oneshot at this * stage makes if hang because the HPET does not get * reprogrammed due to the handler hijacking. Duh, stupid me! * * Both issues require major surgery and especially the kick HPET * again after enabling IOAPIC results in really nasty hackery. * This 'assume periodic works' magic has survived since HPET * support got added, so it's questionable whether this should be * fixed. Both Qemu and the failing hardware machine support * periodic mode despite the fact that both don't advertise it in * the configuration register and both need that extra kick after * switching to IOAPIC. Seems to be a feature... */ hc->evt.features |= CLOCK_EVT_FEAT_PERIODIC; hc->evt.set_state_periodic = hpet_clkevt_set_state_periodic; /* Start HPET legacy interrupts */ hpet_enable_legacy_int(); clockevents_config_and_register(&hc->evt, hpet_freq, HPET_MIN_PROG_DELTA, 0x7FFFFFFF); global_clock_event = &hc->evt; pr_debug("Clockevent registered\n"); } /* * HPET MSI Support */ #ifdef CONFIG_GENERIC_MSI_IRQ static void hpet_msi_unmask(struct irq_data *data) { struct hpet_channel *hc = irq_data_get_irq_handler_data(data); unsigned int cfg; cfg = hpet_readl(HPET_Tn_CFG(hc->num)); cfg |= HPET_TN_ENABLE | HPET_TN_FSB; hpet_writel(cfg, HPET_Tn_CFG(hc->num)); } static void hpet_msi_mask(struct irq_data *data) { struct hpet_channel *hc = irq_data_get_irq_handler_data(data); unsigned int cfg; cfg = hpet_readl(HPET_Tn_CFG(hc->num)); cfg &= ~(HPET_TN_ENABLE | HPET_TN_FSB); hpet_writel(cfg, HPET_Tn_CFG(hc->num)); } static void hpet_msi_write(struct hpet_channel *hc, struct msi_msg *msg) { hpet_writel(msg->data, HPET_Tn_ROUTE(hc->num)); hpet_writel(msg->address_lo, HPET_Tn_ROUTE(hc->num) + 4); } static void hpet_msi_write_msg(struct irq_data *data, struct msi_msg *msg) { hpet_msi_write(irq_data_get_irq_handler_data(data), msg); } static struct irq_chip hpet_msi_controller __ro_after_init = { .name = "HPET-MSI", .irq_unmask = hpet_msi_unmask, .irq_mask = hpet_msi_mask, .irq_ack = irq_chip_ack_parent, .irq_set_affinity = msi_domain_set_affinity, .irq_retrigger = irq_chip_retrigger_hierarchy, .irq_write_msi_msg = hpet_msi_write_msg, .flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_AFFINITY_PRE_STARTUP, }; static int hpet_msi_init(struct irq_domain *domain, struct msi_domain_info *info, unsigned int virq, irq_hw_number_t hwirq, msi_alloc_info_t *arg) { irq_set_status_flags(virq, IRQ_MOVE_PCNTXT); irq_domain_set_info(domain, virq, arg->hwirq, info->chip, NULL, handle_edge_irq, arg->data, "edge"); return 0; } static void hpet_msi_free(struct irq_domain *domain, struct msi_domain_info *info, unsigned int virq) { irq_clear_status_flags(virq, IRQ_MOVE_PCNTXT); } static struct msi_domain_ops hpet_msi_domain_ops = { .msi_init = hpet_msi_init, .msi_free = hpet_msi_free, }; static struct msi_domain_info hpet_msi_domain_info = { .ops = &hpet_msi_domain_ops, .chip = &hpet_msi_controller, .flags = MSI_FLAG_USE_DEF_DOM_OPS, }; static struct irq_domain *hpet_create_irq_domain(int hpet_id) { struct msi_domain_info *domain_info; struct irq_domain *parent, *d; struct fwnode_handle *fn; struct irq_fwspec fwspec; if (x86_vector_domain == NULL) return NULL; domain_info = kzalloc(sizeof(*domain_info), GFP_KERNEL); if (!domain_info) return NULL; *domain_info = hpet_msi_domain_info; domain_info->data = (void *)(long)hpet_id; fn = irq_domain_alloc_named_id_fwnode(hpet_msi_controller.name, hpet_id); if (!fn) { kfree(domain_info); return NULL; } fwspec.fwnode = fn; fwspec.param_count = 1; fwspec.param[0] = hpet_id; parent = irq_find_matching_fwspec(&fwspec, DOMAIN_BUS_ANY); if (!parent) { irq_domain_free_fwnode(fn); kfree(domain_info); return NULL; } if (parent != x86_vector_domain) hpet_msi_controller.name = "IR-HPET-MSI"; d = msi_create_irq_domain(fn, domain_info, parent); if (!d) { irq_domain_free_fwnode(fn); kfree(domain_info); } return d; } static inline int hpet_dev_id(struct irq_domain *domain) { struct msi_domain_info *info = msi_get_domain_info(domain); return (int)(long)info->data; } static int hpet_assign_irq(struct irq_domain *domain, struct hpet_channel *hc, int dev_num) { struct irq_alloc_info info; init_irq_alloc_info(&info, NULL); info.type = X86_IRQ_ALLOC_TYPE_HPET; info.data = hc; info.devid = hpet_dev_id(domain); info.hwirq = dev_num; return irq_domain_alloc_irqs(domain, 1, NUMA_NO_NODE, &info); } static int hpet_clkevt_msi_resume(struct clock_event_device *evt) { struct hpet_channel *hc = clockevent_to_channel(evt); struct irq_data *data = irq_get_irq_data(hc->irq); struct msi_msg msg; /* Restore the MSI msg and unmask the interrupt */ irq_chip_compose_msi_msg(data, &msg); hpet_msi_write(hc, &msg); hpet_msi_unmask(data); return 0; } static irqreturn_t hpet_msi_interrupt_handler(int irq, void *data) { struct hpet_channel *hc = data; struct clock_event_device *evt = &hc->evt; if (!evt->event_handler) { pr_info("Spurious interrupt HPET channel %d\n", hc->num); return IRQ_HANDLED; } evt->event_handler(evt); return IRQ_HANDLED; } static int hpet_setup_msi_irq(struct hpet_channel *hc) { if (request_irq(hc->irq, hpet_msi_interrupt_handler, IRQF_TIMER | IRQF_NOBALANCING, hc->name, hc)) return -1; disable_irq(hc->irq); irq_set_affinity(hc->irq, cpumask_of(hc->cpu)); enable_irq(hc->irq); pr_debug("%s irq %u for MSI\n", hc->name, hc->irq); return 0; } /* Invoked from the hotplug callback on @cpu */ static void init_one_hpet_msi_clockevent(struct hpet_channel *hc, int cpu) { struct clock_event_device *evt = &hc->evt; hc->cpu = cpu; per_cpu(cpu_hpet_channel, cpu) = hc; hpet_setup_msi_irq(hc); hpet_init_clockevent(hc, 110); evt->tick_resume = hpet_clkevt_msi_resume; clockevents_config_and_register(evt, hpet_freq, HPET_MIN_PROG_DELTA, 0x7FFFFFFF); } static struct hpet_channel *hpet_get_unused_clockevent(void) { int i; for (i = 0; i < hpet_base.nr_channels; i++) { struct hpet_channel *hc = hpet_base.channels + i; if (hc->mode != HPET_MODE_CLOCKEVT || hc->in_use) continue; hc->in_use = 1; return hc; } return NULL; } static int hpet_cpuhp_online(unsigned int cpu) { struct hpet_channel *hc = hpet_get_unused_clockevent(); if (hc) init_one_hpet_msi_clockevent(hc, cpu); return 0; } static int hpet_cpuhp_dead(unsigned int cpu) { struct hpet_channel *hc = per_cpu(cpu_hpet_channel, cpu); if (!hc) return 0; free_irq(hc->irq, hc); hc->in_use = 0; per_cpu(cpu_hpet_channel, cpu) = NULL; return 0; } static void __init hpet_select_clockevents(void) { unsigned int i; hpet_base.nr_clockevents = 0; /* No point if MSI is disabled or CPU has an Always Runing APIC Timer */ if (hpet_msi_disable || boot_cpu_has(X86_FEATURE_ARAT)) return; hpet_print_config(); hpet_domain = hpet_create_irq_domain(hpet_blockid); if (!hpet_domain) return; for (i = 0; i < hpet_base.nr_channels; i++) { struct hpet_channel *hc = hpet_base.channels + i; int irq; if (hc->mode != HPET_MODE_UNUSED) continue; /* Only consider HPET channel with MSI support */ if (!(hc->boot_cfg & HPET_TN_FSB_CAP)) continue; sprintf(hc->name, "hpet%d", i); irq = hpet_assign_irq(hpet_domain, hc, hc->num); if (irq <= 0) continue; hc->irq = irq; hc->mode = HPET_MODE_CLOCKEVT; if (++hpet_base.nr_clockevents == num_possible_cpus()) break; } pr_info("%d channels of %d reserved for per-cpu timers\n", hpet_base.nr_channels, hpet_base.nr_clockevents); } #else static inline void hpet_select_clockevents(void) { } #define hpet_cpuhp_online NULL #define hpet_cpuhp_dead NULL #endif /* * Clock source related code */ #if defined(CONFIG_SMP) && defined(CONFIG_64BIT) /* * Reading the HPET counter is a very slow operation. If a large number of * CPUs are trying to access the HPET counter simultaneously, it can cause * massive delays and slow down system performance dramatically. This may * happen when HPET is the default clock source instead of TSC. For a * really large system with hundreds of CPUs, the slowdown may be so * severe, that it can actually crash the system because of a NMI watchdog * soft lockup, for example. * * If multiple CPUs are trying to access the HPET counter at the same time, * we don't actually need to read the counter multiple times. Instead, the * other CPUs can use the counter value read by the first CPU in the group. * * This special feature is only enabled on x86-64 systems. It is unlikely * that 32-bit x86 systems will have enough CPUs to require this feature * with its associated locking overhead. We also need 64-bit atomic read. * * The lock and the HPET value are stored together and can be read in a * single atomic 64-bit read. It is explicitly assumed that arch_spinlock_t * is 32 bits in size. */ union hpet_lock { struct { arch_spinlock_t lock; u32 value; }; u64 lockval; }; static union hpet_lock hpet __cacheline_aligned = { { .lock = __ARCH_SPIN_LOCK_UNLOCKED, }, }; static u64 read_hpet(struct clocksource *cs) { unsigned long flags; union hpet_lock old, new; BUILD_BUG_ON(sizeof(union hpet_lock) != 8); /* * Read HPET directly if in NMI. */ if (in_nmi()) return (u64)hpet_readl(HPET_COUNTER); /* * Read the current state of the lock and HPET value atomically. */ old.lockval = READ_ONCE(hpet.lockval); if (arch_spin_is_locked(&old.lock)) goto contended; local_irq_save(flags); if (arch_spin_trylock(&hpet.lock)) { new.value = hpet_readl(HPET_COUNTER); /* * Use WRITE_ONCE() to prevent store tearing. */ WRITE_ONCE(hpet.value, new.value); arch_spin_unlock(&hpet.lock); local_irq_restore(flags); return (u64)new.value; } local_irq_restore(flags); contended: /* * Contended case * -------------- * Wait until the HPET value change or the lock is free to indicate * its value is up-to-date. * * It is possible that old.value has already contained the latest * HPET value while the lock holder was in the process of releasing * the lock. Checking for lock state change will enable us to return * the value immediately instead of waiting for the next HPET reader * to come along. */ do { cpu_relax(); new.lockval = READ_ONCE(hpet.lockval); } while ((new.value == old.value) && arch_spin_is_locked(&new.lock)); return (u64)new.value; } #else /* * For UP or 32-bit. */ static u64 read_hpet(struct clocksource *cs) { return (u64)hpet_readl(HPET_COUNTER); } #endif static struct clocksource clocksource_hpet = { .name = "hpet", .rating = 250, .read = read_hpet, .mask = HPET_MASK, .flags = CLOCK_SOURCE_IS_CONTINUOUS, .resume = hpet_resume_counter, }; /* * AMD SB700 based systems with spread spectrum enabled use a SMM based * HPET emulation to provide proper frequency setting. * * On such systems the SMM code is initialized with the first HPET register * access and takes some time to complete. During this time the config * register reads 0xffffffff. We check for max 1000 loops whether the * config register reads a non-0xffffffff value to make sure that the * HPET is up and running before we proceed any further. * * A counting loop is safe, as the HPET access takes thousands of CPU cycles. * * On non-SB700 based machines this check is only done once and has no * side effects. */ static bool __init hpet_cfg_working(void) { int i; for (i = 0; i < 1000; i++) { if (hpet_readl(HPET_CFG) != 0xFFFFFFFF) return true; } pr_warn("Config register invalid. Disabling HPET\n"); return false; } static bool __init hpet_counting(void) { u64 start, now, t1; hpet_restart_counter(); t1 = hpet_readl(HPET_COUNTER); start = rdtsc(); /* * We don't know the TSC frequency yet, but waiting for * 200000 TSC cycles is safe: * 4 GHz == 50us * 1 GHz == 200us */ do { if (t1 != hpet_readl(HPET_COUNTER)) return true; now = rdtsc(); } while ((now - start) < 200000UL); pr_warn("Counter not counting. HPET disabled\n"); return false; } static bool __init mwait_pc10_supported(void) { unsigned int eax, ebx, ecx, mwait_substates; if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) return false; if (!cpu_feature_enabled(X86_FEATURE_MWAIT)) return false; if (boot_cpu_data.cpuid_level < CPUID_MWAIT_LEAF) return false; cpuid(CPUID_MWAIT_LEAF, &eax, &ebx, &ecx, &mwait_substates); return (ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED) && (ecx & CPUID5_ECX_INTERRUPT_BREAK) && (mwait_substates & (0xF << 28)); } /* * Check whether the system supports PC10. If so force disable HPET as that * stops counting in PC10. This check is overbroad as it does not take any * of the following into account: * * - ACPI tables * - Enablement of intel_idle * - Command line arguments which limit intel_idle C-state support * * That's perfectly fine. HPET is a piece of hardware designed by committee * and the only reasons why it is still in use on modern systems is the * fact that it is impossible to reliably query TSC and CPU frequency via * CPUID or firmware. * * If HPET is functional it is useful for calibrating TSC, but this can be * done via PMTIMER as well which seems to be the last remaining timer on * X86/INTEL platforms that has not been completely wreckaged by feature * creep. * * In theory HPET support should be removed altogether, but there are older * systems out there which depend on it because TSC and APIC timer are * dysfunctional in deeper C-states. * * It's only 20 years now that hardware people have been asked to provide * reliable and discoverable facilities which can be used for timekeeping * and per CPU timer interrupts. * * The probability that this problem is going to be solved in the * forseeable future is close to zero, so the kernel has to be cluttered * with heuristics to keep up with the ever growing amount of hardware and * firmware trainwrecks. Hopefully some day hardware people will understand * that the approach of "This can be fixed in software" is not sustainable. * Hope dies last... */ static bool __init hpet_is_pc10_damaged(void) { unsigned long long pcfg; /* Check whether PC10 substates are supported */ if (!mwait_pc10_supported()) return false; /* Check whether PC10 is enabled in PKG C-state limit */ rdmsrl(MSR_PKG_CST_CONFIG_CONTROL, pcfg); if ((pcfg & 0xF) < 8) return false; if (hpet_force_user) { pr_warn("HPET force enabled via command line, but dysfunctional in PC10.\n"); return false; } pr_info("HPET dysfunctional in PC10. Force disabled.\n"); boot_hpet_disable = true; return true; } /** * hpet_enable - Try to setup the HPET timer. Returns 1 on success. */ int __init hpet_enable(void) { u32 hpet_period, cfg, id, irq; unsigned int i, channels; struct hpet_channel *hc; u64 freq; if (!is_hpet_capable()) return 0; if (hpet_is_pc10_damaged()) return 0; hpet_set_mapping(); if (!hpet_virt_address) return 0; /* Validate that the config register is working */ if (!hpet_cfg_working()) goto out_nohpet; /* * Read the period and check for a sane value: */ hpet_period = hpet_readl(HPET_PERIOD); if (hpet_period < HPET_MIN_PERIOD || hpet_period > HPET_MAX_PERIOD) goto out_nohpet; /* The period is a femtoseconds value. Convert it to a frequency. */ freq = FSEC_PER_SEC; do_div(freq, hpet_period); hpet_freq = freq; /* * Read the HPET ID register to retrieve the IRQ routing * information and the number of channels */ id = hpet_readl(HPET_ID); hpet_print_config(); /* This is the HPET channel number which is zero based */ channels = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1; /* * The legacy routing mode needs at least two channels, tick timer * and the rtc emulation channel. */ if (IS_ENABLED(CONFIG_HPET_EMULATE_RTC) && channels < 2) goto out_nohpet; hc = kcalloc(channels, sizeof(*hc), GFP_KERNEL); if (!hc) { pr_warn("Disabling HPET.\n"); goto out_nohpet; } hpet_base.channels = hc; hpet_base.nr_channels = channels; /* Read, store and sanitize the global configuration */ cfg = hpet_readl(HPET_CFG); hpet_base.boot_cfg = cfg; cfg &= ~(HPET_CFG_ENABLE | HPET_CFG_LEGACY); hpet_writel(cfg, HPET_CFG); if (cfg) pr_warn("Global config: Unknown bits %#x\n", cfg); /* Read, store and sanitize the per channel configuration */ for (i = 0; i < channels; i++, hc++) { hc->num = i; cfg = hpet_readl(HPET_Tn_CFG(i)); hc->boot_cfg = cfg; irq = (cfg & Tn_INT_ROUTE_CNF_MASK) >> Tn_INT_ROUTE_CNF_SHIFT; hc->irq = irq; cfg &= ~(HPET_TN_ENABLE | HPET_TN_LEVEL | HPET_TN_FSB); hpet_writel(cfg, HPET_Tn_CFG(i)); cfg &= ~(HPET_TN_PERIODIC | HPET_TN_PERIODIC_CAP | HPET_TN_64BIT_CAP | HPET_TN_32BIT | HPET_TN_ROUTE | HPET_TN_FSB | HPET_TN_FSB_CAP); if (cfg) pr_warn("Channel #%u config: Unknown bits %#x\n", i, cfg); } hpet_print_config(); /* * Validate that the counter is counting. This needs to be done * after sanitizing the config registers to properly deal with * force enabled HPETs. */ if (!hpet_counting()) goto out_nohpet; if (tsc_clocksource_watchdog_disabled()) clocksource_hpet.flags |= CLOCK_SOURCE_MUST_VERIFY; clocksource_register_hz(&clocksource_hpet, (u32)hpet_freq); if (id & HPET_ID_LEGSUP) { hpet_legacy_clockevent_register(&hpet_base.channels[0]); hpet_base.channels[0].mode = HPET_MODE_LEGACY; if (IS_ENABLED(CONFIG_HPET_EMULATE_RTC)) hpet_base.channels[1].mode = HPET_MODE_LEGACY; return 1; } return 0; out_nohpet: kfree(hpet_base.channels); hpet_base.channels = NULL; hpet_base.nr_channels = 0; hpet_clear_mapping(); hpet_address = 0; return 0; } /* * The late initialization runs after the PCI quirks have been invoked * which might have detected a system on which the HPET can be enforced. * * Also, the MSI machinery is not working yet when the HPET is initialized * early. * * If the HPET is enabled, then: * * 1) Reserve one channel for /dev/hpet if CONFIG_HPET=y * 2) Reserve up to num_possible_cpus() channels as per CPU clockevents * 3) Setup /dev/hpet if CONFIG_HPET=y * 4) Register hotplug callbacks when clockevents are available */ static __init int hpet_late_init(void) { int ret; if (!hpet_address) { if (!force_hpet_address) return -ENODEV; hpet_address = force_hpet_address; hpet_enable(); } if (!hpet_virt_address) return -ENODEV; hpet_select_device_channel(); hpet_select_clockevents(); hpet_reserve_platform_timers(); hpet_print_config(); if (!hpet_base.nr_clockevents) return 0; ret = cpuhp_setup_state(CPUHP_AP_X86_HPET_ONLINE, "x86/hpet:online", hpet_cpuhp_online, NULL); if (ret) return ret; ret = cpuhp_setup_state(CPUHP_X86_HPET_DEAD, "x86/hpet:dead", NULL, hpet_cpuhp_dead); if (ret) goto err_cpuhp; return 0; err_cpuhp: cpuhp_remove_state(CPUHP_AP_X86_HPET_ONLINE); return ret; } fs_initcall(hpet_late_init); void hpet_disable(void) { unsigned int i; u32 cfg; if (!is_hpet_capable() || !hpet_virt_address) return; /* Restore boot configuration with the enable bit cleared */ cfg = hpet_base.boot_cfg; cfg &= ~HPET_CFG_ENABLE; hpet_writel(cfg, HPET_CFG); /* Restore the channel boot configuration */ for (i = 0; i < hpet_base.nr_channels; i++) hpet_writel(hpet_base.channels[i].boot_cfg, HPET_Tn_CFG(i)); /* If the HPET was enabled at boot time, reenable it */ if (hpet_base.boot_cfg & HPET_CFG_ENABLE) hpet_writel(hpet_base.boot_cfg, HPET_CFG); } #ifdef CONFIG_HPET_EMULATE_RTC /* * HPET in LegacyReplacement mode eats up the RTC interrupt line. When HPET * is enabled, we support RTC interrupt functionality in software. * * RTC has 3 kinds of interrupts: * * 1) Update Interrupt - generate an interrupt, every second, when the * RTC clock is updated * 2) Alarm Interrupt - generate an interrupt at a specific time of day * 3) Periodic Interrupt - generate periodic interrupt, with frequencies * 2Hz-8192Hz (2Hz-64Hz for non-root user) (all frequencies in powers of 2) * * (1) and (2) above are implemented using polling at a frequency of 64 Hz: * DEFAULT_RTC_INT_FREQ. * * The exact frequency is a tradeoff between accuracy and interrupt overhead. * * For (3), we use interrupts at 64 Hz, or the user specified periodic frequency, * if it's higher. */ #include <linux/mc146818rtc.h> #include <linux/rtc.h> #define DEFAULT_RTC_INT_FREQ 64 #define DEFAULT_RTC_SHIFT 6 #define RTC_NUM_INTS 1 static unsigned long hpet_rtc_flags; static int hpet_prev_update_sec; static struct rtc_time hpet_alarm_time; static unsigned long hpet_pie_count; static u32 hpet_t1_cmp; static u32 hpet_default_delta; static u32 hpet_pie_delta; static unsigned long hpet_pie_limit; static rtc_irq_handler irq_handler; /* * Check that the HPET counter c1 is ahead of c2 */ static inline int hpet_cnt_ahead(u32 c1, u32 c2) { return (s32)(c2 - c1) < 0; } /* * Registers a IRQ handler. */ int hpet_register_irq_handler(rtc_irq_handler handler) { if (!is_hpet_enabled()) return -ENODEV; if (irq_handler) return -EBUSY; irq_handler = handler; return 0; } EXPORT_SYMBOL_GPL(hpet_register_irq_handler); /* * Deregisters the IRQ handler registered with hpet_register_irq_handler() * and does cleanup. */ void hpet_unregister_irq_handler(rtc_irq_handler handler) { if (!is_hpet_enabled()) return; irq_handler = NULL; hpet_rtc_flags = 0; } EXPORT_SYMBOL_GPL(hpet_unregister_irq_handler); /* * Channel 1 for RTC emulation. We use one shot mode, as periodic mode * is not supported by all HPET implementations for channel 1. * * hpet_rtc_timer_init() is called when the rtc is initialized. */ int hpet_rtc_timer_init(void) { unsigned int cfg, cnt, delta; unsigned long flags; if (!is_hpet_enabled()) return 0; if (!hpet_default_delta) { struct clock_event_device *evt = &hpet_base.channels[0].evt; uint64_t clc; clc = (uint64_t) evt->mult * NSEC_PER_SEC; clc >>= evt->shift + DEFAULT_RTC_SHIFT; hpet_default_delta = clc; } if (!(hpet_rtc_flags & RTC_PIE) || hpet_pie_limit) delta = hpet_default_delta; else delta = hpet_pie_delta; local_irq_save(flags); cnt = delta + hpet_readl(HPET_COUNTER); hpet_writel(cnt, HPET_T1_CMP); hpet_t1_cmp = cnt; cfg = hpet_readl(HPET_T1_CFG); cfg &= ~HPET_TN_PERIODIC; cfg |= HPET_TN_ENABLE | HPET_TN_32BIT; hpet_writel(cfg, HPET_T1_CFG); local_irq_restore(flags); return 1; } EXPORT_SYMBOL_GPL(hpet_rtc_timer_init); static void hpet_disable_rtc_channel(void) { u32 cfg = hpet_readl(HPET_T1_CFG); cfg &= ~HPET_TN_ENABLE; hpet_writel(cfg, HPET_T1_CFG); } /* * The functions below are called from rtc driver. * Return 0 if HPET is not being used. * Otherwise do the necessary changes and return 1. */ int hpet_mask_rtc_irq_bit(unsigned long bit_mask) { if (!is_hpet_enabled()) return 0; hpet_rtc_flags &= ~bit_mask; if (unlikely(!hpet_rtc_flags)) hpet_disable_rtc_channel(); return 1; } EXPORT_SYMBOL_GPL(hpet_mask_rtc_irq_bit); int hpet_set_rtc_irq_bit(unsigned long bit_mask) { unsigned long oldbits = hpet_rtc_flags; if (!is_hpet_enabled()) return 0; hpet_rtc_flags |= bit_mask; if ((bit_mask & RTC_UIE) && !(oldbits & RTC_UIE)) hpet_prev_update_sec = -1; if (!oldbits) hpet_rtc_timer_init(); return 1; } EXPORT_SYMBOL_GPL(hpet_set_rtc_irq_bit); int hpet_set_alarm_time(unsigned char hrs, unsigned char min, unsigned char sec) { if (!is_hpet_enabled()) return 0; hpet_alarm_time.tm_hour = hrs; hpet_alarm_time.tm_min = min; hpet_alarm_time.tm_sec = sec; return 1; } EXPORT_SYMBOL_GPL(hpet_set_alarm_time); int hpet_set_periodic_freq(unsigned long freq) { uint64_t clc; if (!is_hpet_enabled()) return 0; if (freq <= DEFAULT_RTC_INT_FREQ) { hpet_pie_limit = DEFAULT_RTC_INT_FREQ / freq; } else { struct clock_event_device *evt = &hpet_base.channels[0].evt; clc = (uint64_t) evt->mult * NSEC_PER_SEC; do_div(clc, freq); clc >>= evt->shift; hpet_pie_delta = clc; hpet_pie_limit = 0; } return 1; } EXPORT_SYMBOL_GPL(hpet_set_periodic_freq); int hpet_rtc_dropped_irq(void) { return is_hpet_enabled(); } EXPORT_SYMBOL_GPL(hpet_rtc_dropped_irq); static void hpet_rtc_timer_reinit(void) { unsigned int delta; int lost_ints = -1; if (unlikely(!hpet_rtc_flags)) hpet_disable_rtc_channel(); if (!(hpet_rtc_flags & RTC_PIE) || hpet_pie_limit) delta = hpet_default_delta; else delta = hpet_pie_delta; /* * Increment the comparator value until we are ahead of the * current count. */ do { hpet_t1_cmp += delta; hpet_writel(hpet_t1_cmp, HPET_T1_CMP); lost_ints++; } while (!hpet_cnt_ahead(hpet_t1_cmp, hpet_readl(HPET_COUNTER))); if (lost_ints) { if (hpet_rtc_flags & RTC_PIE) hpet_pie_count += lost_ints; if (printk_ratelimit()) pr_warn("Lost %d RTC interrupts\n", lost_ints); } } irqreturn_t hpet_rtc_interrupt(int irq, void *dev_id) { struct rtc_time curr_time; unsigned long rtc_int_flag = 0; hpet_rtc_timer_reinit(); memset(&curr_time, 0, sizeof(struct rtc_time)); if (hpet_rtc_flags & (RTC_UIE | RTC_AIE)) { if (unlikely(mc146818_get_time(&curr_time) < 0)) { pr_err_ratelimited("unable to read current time from RTC\n"); return IRQ_HANDLED; } } if (hpet_rtc_flags & RTC_UIE && curr_time.tm_sec != hpet_prev_update_sec) { if (hpet_prev_update_sec >= 0) rtc_int_flag = RTC_UF; hpet_prev_update_sec = curr_time.tm_sec; } if (hpet_rtc_flags & RTC_PIE && ++hpet_pie_count >= hpet_pie_limit) { rtc_int_flag |= RTC_PF; hpet_pie_count = 0; } if (hpet_rtc_flags & RTC_AIE && (curr_time.tm_sec == hpet_alarm_time.tm_sec) && (curr_time.tm_min == hpet_alarm_time.tm_min) && (curr_time.tm_hour == hpet_alarm_time.tm_hour)) rtc_int_flag |= RTC_AF; if (rtc_int_flag) { rtc_int_flag |= (RTC_IRQF | (RTC_NUM_INTS << 8)); if (irq_handler) irq_handler(rtc_int_flag, dev_id); } return IRQ_HANDLED; } EXPORT_SYMBOL_GPL(hpet_rtc_interrupt); #endif
linux-master
arch/x86/kernel/hpet.c
// SPDX-License-Identifier: GPL-2.0-only /* By Ross Biro 1/23/92 */ /* * Pentium III FXSR, SSE support * Gareth Hughes <[email protected]>, May 2000 */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/sched/task_stack.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/ptrace.h> #include <linux/user.h> #include <linux/elf.h> #include <linux/security.h> #include <linux/audit.h> #include <linux/seccomp.h> #include <linux/signal.h> #include <linux/perf_event.h> #include <linux/hw_breakpoint.h> #include <linux/rcupdate.h> #include <linux/export.h> #include <linux/context_tracking.h> #include <linux/nospec.h> #include <linux/uaccess.h> #include <asm/processor.h> #include <asm/fpu/signal.h> #include <asm/fpu/regset.h> #include <asm/fpu/xstate.h> #include <asm/debugreg.h> #include <asm/ldt.h> #include <asm/desc.h> #include <asm/prctl.h> #include <asm/proto.h> #include <asm/hw_breakpoint.h> #include <asm/traps.h> #include <asm/syscall.h> #include <asm/fsgsbase.h> #include <asm/io_bitmap.h> #include "tls.h" enum x86_regset_32 { REGSET32_GENERAL, REGSET32_FP, REGSET32_XFP, REGSET32_XSTATE, REGSET32_TLS, REGSET32_IOPERM, }; enum x86_regset_64 { REGSET64_GENERAL, REGSET64_FP, REGSET64_IOPERM, REGSET64_XSTATE, REGSET64_SSP, }; #define REGSET_GENERAL \ ({ \ BUILD_BUG_ON((int)REGSET32_GENERAL != (int)REGSET64_GENERAL); \ REGSET32_GENERAL; \ }) #define REGSET_FP \ ({ \ BUILD_BUG_ON((int)REGSET32_FP != (int)REGSET64_FP); \ REGSET32_FP; \ }) struct pt_regs_offset { const char *name; int offset; }; #define REG_OFFSET_NAME(r) {.name = #r, .offset = offsetof(struct pt_regs, r)} #define REG_OFFSET_END {.name = NULL, .offset = 0} static const struct pt_regs_offset regoffset_table[] = { #ifdef CONFIG_X86_64 REG_OFFSET_NAME(r15), REG_OFFSET_NAME(r14), REG_OFFSET_NAME(r13), REG_OFFSET_NAME(r12), REG_OFFSET_NAME(r11), REG_OFFSET_NAME(r10), REG_OFFSET_NAME(r9), REG_OFFSET_NAME(r8), #endif REG_OFFSET_NAME(bx), REG_OFFSET_NAME(cx), REG_OFFSET_NAME(dx), REG_OFFSET_NAME(si), REG_OFFSET_NAME(di), REG_OFFSET_NAME(bp), REG_OFFSET_NAME(ax), #ifdef CONFIG_X86_32 REG_OFFSET_NAME(ds), REG_OFFSET_NAME(es), REG_OFFSET_NAME(fs), REG_OFFSET_NAME(gs), #endif REG_OFFSET_NAME(orig_ax), REG_OFFSET_NAME(ip), REG_OFFSET_NAME(cs), REG_OFFSET_NAME(flags), REG_OFFSET_NAME(sp), REG_OFFSET_NAME(ss), REG_OFFSET_END, }; /** * regs_query_register_offset() - query register offset from its name * @name: the name of a register * * regs_query_register_offset() returns the offset of a register in struct * pt_regs from its name. If the name is invalid, this returns -EINVAL; */ int regs_query_register_offset(const char *name) { const struct pt_regs_offset *roff; for (roff = regoffset_table; roff->name != NULL; roff++) if (!strcmp(roff->name, name)) return roff->offset; return -EINVAL; } /** * regs_query_register_name() - query register name from its offset * @offset: the offset of a register in struct pt_regs. * * regs_query_register_name() returns the name of a register from its * offset in struct pt_regs. If the @offset is invalid, this returns NULL; */ const char *regs_query_register_name(unsigned int offset) { const struct pt_regs_offset *roff; for (roff = regoffset_table; roff->name != NULL; roff++) if (roff->offset == offset) return roff->name; return NULL; } /* * does not yet catch signals sent when the child dies. * in exit.c or in signal.c. */ /* * Determines which flags the user has access to [1 = access, 0 = no access]. */ #define FLAG_MASK_32 ((unsigned long) \ (X86_EFLAGS_CF | X86_EFLAGS_PF | \ X86_EFLAGS_AF | X86_EFLAGS_ZF | \ X86_EFLAGS_SF | X86_EFLAGS_TF | \ X86_EFLAGS_DF | X86_EFLAGS_OF | \ X86_EFLAGS_RF | X86_EFLAGS_AC)) /* * Determines whether a value may be installed in a segment register. */ static inline bool invalid_selector(u16 value) { return unlikely(value != 0 && (value & SEGMENT_RPL_MASK) != USER_RPL); } #ifdef CONFIG_X86_32 #define FLAG_MASK FLAG_MASK_32 static unsigned long *pt_regs_access(struct pt_regs *regs, unsigned long regno) { BUILD_BUG_ON(offsetof(struct pt_regs, bx) != 0); return &regs->bx + (regno >> 2); } static u16 get_segment_reg(struct task_struct *task, unsigned long offset) { /* * Returning the value truncates it to 16 bits. */ unsigned int retval; if (offset != offsetof(struct user_regs_struct, gs)) retval = *pt_regs_access(task_pt_regs(task), offset); else { if (task == current) savesegment(gs, retval); else retval = task->thread.gs; } return retval; } static int set_segment_reg(struct task_struct *task, unsigned long offset, u16 value) { if (WARN_ON_ONCE(task == current)) return -EIO; /* * The value argument was already truncated to 16 bits. */ if (invalid_selector(value)) return -EIO; /* * For %cs and %ss we cannot permit a null selector. * We can permit a bogus selector as long as it has USER_RPL. * Null selectors are fine for other segment registers, but * we will never get back to user mode with invalid %cs or %ss * and will take the trap in iret instead. Much code relies * on user_mode() to distinguish a user trap frame (which can * safely use invalid selectors) from a kernel trap frame. */ switch (offset) { case offsetof(struct user_regs_struct, cs): case offsetof(struct user_regs_struct, ss): if (unlikely(value == 0)) return -EIO; fallthrough; default: *pt_regs_access(task_pt_regs(task), offset) = value; break; case offsetof(struct user_regs_struct, gs): task->thread.gs = value; } return 0; } #else /* CONFIG_X86_64 */ #define FLAG_MASK (FLAG_MASK_32 | X86_EFLAGS_NT) static unsigned long *pt_regs_access(struct pt_regs *regs, unsigned long offset) { BUILD_BUG_ON(offsetof(struct pt_regs, r15) != 0); return &regs->r15 + (offset / sizeof(regs->r15)); } static u16 get_segment_reg(struct task_struct *task, unsigned long offset) { /* * Returning the value truncates it to 16 bits. */ unsigned int seg; switch (offset) { case offsetof(struct user_regs_struct, fs): if (task == current) { /* Older gas can't assemble movq %?s,%r?? */ asm("movl %%fs,%0" : "=r" (seg)); return seg; } return task->thread.fsindex; case offsetof(struct user_regs_struct, gs): if (task == current) { asm("movl %%gs,%0" : "=r" (seg)); return seg; } return task->thread.gsindex; case offsetof(struct user_regs_struct, ds): if (task == current) { asm("movl %%ds,%0" : "=r" (seg)); return seg; } return task->thread.ds; case offsetof(struct user_regs_struct, es): if (task == current) { asm("movl %%es,%0" : "=r" (seg)); return seg; } return task->thread.es; case offsetof(struct user_regs_struct, cs): case offsetof(struct user_regs_struct, ss): break; } return *pt_regs_access(task_pt_regs(task), offset); } static int set_segment_reg(struct task_struct *task, unsigned long offset, u16 value) { if (WARN_ON_ONCE(task == current)) return -EIO; /* * The value argument was already truncated to 16 bits. */ if (invalid_selector(value)) return -EIO; /* * Writes to FS and GS will change the stored selector. Whether * this changes the segment base as well depends on whether * FSGSBASE is enabled. */ switch (offset) { case offsetof(struct user_regs_struct,fs): task->thread.fsindex = value; break; case offsetof(struct user_regs_struct,gs): task->thread.gsindex = value; break; case offsetof(struct user_regs_struct,ds): task->thread.ds = value; break; case offsetof(struct user_regs_struct,es): task->thread.es = value; break; /* * Can't actually change these in 64-bit mode. */ case offsetof(struct user_regs_struct,cs): if (unlikely(value == 0)) return -EIO; task_pt_regs(task)->cs = value; break; case offsetof(struct user_regs_struct,ss): if (unlikely(value == 0)) return -EIO; task_pt_regs(task)->ss = value; break; } return 0; } #endif /* CONFIG_X86_32 */ static unsigned long get_flags(struct task_struct *task) { unsigned long retval = task_pt_regs(task)->flags; /* * If the debugger set TF, hide it from the readout. */ if (test_tsk_thread_flag(task, TIF_FORCED_TF)) retval &= ~X86_EFLAGS_TF; return retval; } static int set_flags(struct task_struct *task, unsigned long value) { struct pt_regs *regs = task_pt_regs(task); /* * If the user value contains TF, mark that * it was not "us" (the debugger) that set it. * If not, make sure it stays set if we had. */ if (value & X86_EFLAGS_TF) clear_tsk_thread_flag(task, TIF_FORCED_TF); else if (test_tsk_thread_flag(task, TIF_FORCED_TF)) value |= X86_EFLAGS_TF; regs->flags = (regs->flags & ~FLAG_MASK) | (value & FLAG_MASK); return 0; } static int putreg(struct task_struct *child, unsigned long offset, unsigned long value) { switch (offset) { case offsetof(struct user_regs_struct, cs): case offsetof(struct user_regs_struct, ds): case offsetof(struct user_regs_struct, es): case offsetof(struct user_regs_struct, fs): case offsetof(struct user_regs_struct, gs): case offsetof(struct user_regs_struct, ss): return set_segment_reg(child, offset, value); case offsetof(struct user_regs_struct, flags): return set_flags(child, value); #ifdef CONFIG_X86_64 case offsetof(struct user_regs_struct,fs_base): if (value >= TASK_SIZE_MAX) return -EIO; x86_fsbase_write_task(child, value); return 0; case offsetof(struct user_regs_struct,gs_base): if (value >= TASK_SIZE_MAX) return -EIO; x86_gsbase_write_task(child, value); return 0; #endif } *pt_regs_access(task_pt_regs(child), offset) = value; return 0; } static unsigned long getreg(struct task_struct *task, unsigned long offset) { switch (offset) { case offsetof(struct user_regs_struct, cs): case offsetof(struct user_regs_struct, ds): case offsetof(struct user_regs_struct, es): case offsetof(struct user_regs_struct, fs): case offsetof(struct user_regs_struct, gs): case offsetof(struct user_regs_struct, ss): return get_segment_reg(task, offset); case offsetof(struct user_regs_struct, flags): return get_flags(task); #ifdef CONFIG_X86_64 case offsetof(struct user_regs_struct, fs_base): return x86_fsbase_read_task(task); case offsetof(struct user_regs_struct, gs_base): return x86_gsbase_read_task(task); #endif } return *pt_regs_access(task_pt_regs(task), offset); } static int genregs_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { int reg; for (reg = 0; to.left; reg++) membuf_store(&to, getreg(target, reg * sizeof(unsigned long))); return 0; } static int genregs_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { int ret = 0; if (kbuf) { const unsigned long *k = kbuf; while (count >= sizeof(*k) && !ret) { ret = putreg(target, pos, *k++); count -= sizeof(*k); pos += sizeof(*k); } } else { const unsigned long __user *u = ubuf; while (count >= sizeof(*u) && !ret) { unsigned long word; ret = __get_user(word, u++); if (ret) break; ret = putreg(target, pos, word); count -= sizeof(*u); pos += sizeof(*u); } } return ret; } static void ptrace_triggered(struct perf_event *bp, struct perf_sample_data *data, struct pt_regs *regs) { int i; struct thread_struct *thread = &(current->thread); /* * Store in the virtual DR6 register the fact that the breakpoint * was hit so the thread's debugger will see it. */ for (i = 0; i < HBP_NUM; i++) { if (thread->ptrace_bps[i] == bp) break; } thread->virtual_dr6 |= (DR_TRAP0 << i); } /* * Walk through every ptrace breakpoints for this thread and * build the dr7 value on top of their attributes. * */ static unsigned long ptrace_get_dr7(struct perf_event *bp[]) { int i; int dr7 = 0; struct arch_hw_breakpoint *info; for (i = 0; i < HBP_NUM; i++) { if (bp[i] && !bp[i]->attr.disabled) { info = counter_arch_bp(bp[i]); dr7 |= encode_dr7(i, info->len, info->type); } } return dr7; } static int ptrace_fill_bp_fields(struct perf_event_attr *attr, int len, int type, bool disabled) { int err, bp_len, bp_type; err = arch_bp_generic_fields(len, type, &bp_len, &bp_type); if (!err) { attr->bp_len = bp_len; attr->bp_type = bp_type; attr->disabled = disabled; } return err; } static struct perf_event * ptrace_register_breakpoint(struct task_struct *tsk, int len, int type, unsigned long addr, bool disabled) { struct perf_event_attr attr; int err; ptrace_breakpoint_init(&attr); attr.bp_addr = addr; err = ptrace_fill_bp_fields(&attr, len, type, disabled); if (err) return ERR_PTR(err); return register_user_hw_breakpoint(&attr, ptrace_triggered, NULL, tsk); } static int ptrace_modify_breakpoint(struct perf_event *bp, int len, int type, int disabled) { struct perf_event_attr attr = bp->attr; int err; err = ptrace_fill_bp_fields(&attr, len, type, disabled); if (err) return err; return modify_user_hw_breakpoint(bp, &attr); } /* * Handle ptrace writes to debug register 7. */ static int ptrace_write_dr7(struct task_struct *tsk, unsigned long data) { struct thread_struct *thread = &tsk->thread; unsigned long old_dr7; bool second_pass = false; int i, rc, ret = 0; data &= ~DR_CONTROL_RESERVED; old_dr7 = ptrace_get_dr7(thread->ptrace_bps); restore: rc = 0; for (i = 0; i < HBP_NUM; i++) { unsigned len, type; bool disabled = !decode_dr7(data, i, &len, &type); struct perf_event *bp = thread->ptrace_bps[i]; if (!bp) { if (disabled) continue; bp = ptrace_register_breakpoint(tsk, len, type, 0, disabled); if (IS_ERR(bp)) { rc = PTR_ERR(bp); break; } thread->ptrace_bps[i] = bp; continue; } rc = ptrace_modify_breakpoint(bp, len, type, disabled); if (rc) break; } /* Restore if the first pass failed, second_pass shouldn't fail. */ if (rc && !WARN_ON(second_pass)) { ret = rc; data = old_dr7; second_pass = true; goto restore; } return ret; } /* * Handle PTRACE_PEEKUSR calls for the debug register area. */ static unsigned long ptrace_get_debugreg(struct task_struct *tsk, int n) { struct thread_struct *thread = &tsk->thread; unsigned long val = 0; if (n < HBP_NUM) { int index = array_index_nospec(n, HBP_NUM); struct perf_event *bp = thread->ptrace_bps[index]; if (bp) val = bp->hw.info.address; } else if (n == 6) { val = thread->virtual_dr6 ^ DR6_RESERVED; /* Flip back to arch polarity */ } else if (n == 7) { val = thread->ptrace_dr7; } return val; } static int ptrace_set_breakpoint_addr(struct task_struct *tsk, int nr, unsigned long addr) { struct thread_struct *t = &tsk->thread; struct perf_event *bp = t->ptrace_bps[nr]; int err = 0; if (!bp) { /* * Put stub len and type to create an inactive but correct bp. * * CHECKME: the previous code returned -EIO if the addr wasn't * a valid task virtual addr. The new one will return -EINVAL in * this case. * -EINVAL may be what we want for in-kernel breakpoints users, * but -EIO looks better for ptrace, since we refuse a register * writing for the user. And anyway this is the previous * behaviour. */ bp = ptrace_register_breakpoint(tsk, X86_BREAKPOINT_LEN_1, X86_BREAKPOINT_WRITE, addr, true); if (IS_ERR(bp)) err = PTR_ERR(bp); else t->ptrace_bps[nr] = bp; } else { struct perf_event_attr attr = bp->attr; attr.bp_addr = addr; err = modify_user_hw_breakpoint(bp, &attr); } return err; } /* * Handle PTRACE_POKEUSR calls for the debug register area. */ static int ptrace_set_debugreg(struct task_struct *tsk, int n, unsigned long val) { struct thread_struct *thread = &tsk->thread; /* There are no DR4 or DR5 registers */ int rc = -EIO; if (n < HBP_NUM) { rc = ptrace_set_breakpoint_addr(tsk, n, val); } else if (n == 6) { thread->virtual_dr6 = val ^ DR6_RESERVED; /* Flip to positive polarity */ rc = 0; } else if (n == 7) { rc = ptrace_write_dr7(tsk, val); if (!rc) thread->ptrace_dr7 = val; } return rc; } /* * These access the current or another (stopped) task's io permission * bitmap for debugging or core dump. */ static int ioperm_active(struct task_struct *target, const struct user_regset *regset) { struct io_bitmap *iobm = target->thread.io_bitmap; return iobm ? DIV_ROUND_UP(iobm->max, regset->size) : 0; } static int ioperm_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { struct io_bitmap *iobm = target->thread.io_bitmap; if (!iobm) return -ENXIO; return membuf_write(&to, iobm->bitmap, IO_BITMAP_BYTES); } /* * Called by kernel/ptrace.c when detaching.. * * Make sure the single step bit is not set. */ void ptrace_disable(struct task_struct *child) { user_disable_single_step(child); } #if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION static const struct user_regset_view user_x86_32_view; /* Initialized below. */ #endif #ifdef CONFIG_X86_64 static const struct user_regset_view user_x86_64_view; /* Initialized below. */ #endif long arch_ptrace(struct task_struct *child, long request, unsigned long addr, unsigned long data) { int ret; unsigned long __user *datap = (unsigned long __user *)data; #ifdef CONFIG_X86_64 /* This is native 64-bit ptrace() */ const struct user_regset_view *regset_view = &user_x86_64_view; #else /* This is native 32-bit ptrace() */ const struct user_regset_view *regset_view = &user_x86_32_view; #endif switch (request) { /* read the word at location addr in the USER area. */ case PTRACE_PEEKUSR: { unsigned long tmp; ret = -EIO; if ((addr & (sizeof(data) - 1)) || addr >= sizeof(struct user)) break; tmp = 0; /* Default return condition */ if (addr < sizeof(struct user_regs_struct)) tmp = getreg(child, addr); else if (addr >= offsetof(struct user, u_debugreg[0]) && addr <= offsetof(struct user, u_debugreg[7])) { addr -= offsetof(struct user, u_debugreg[0]); tmp = ptrace_get_debugreg(child, addr / sizeof(data)); } ret = put_user(tmp, datap); break; } case PTRACE_POKEUSR: /* write the word at location addr in the USER area */ ret = -EIO; if ((addr & (sizeof(data) - 1)) || addr >= sizeof(struct user)) break; if (addr < sizeof(struct user_regs_struct)) ret = putreg(child, addr, data); else if (addr >= offsetof(struct user, u_debugreg[0]) && addr <= offsetof(struct user, u_debugreg[7])) { addr -= offsetof(struct user, u_debugreg[0]); ret = ptrace_set_debugreg(child, addr / sizeof(data), data); } break; case PTRACE_GETREGS: /* Get all gp regs from the child. */ return copy_regset_to_user(child, regset_view, REGSET_GENERAL, 0, sizeof(struct user_regs_struct), datap); case PTRACE_SETREGS: /* Set all gp regs in the child. */ return copy_regset_from_user(child, regset_view, REGSET_GENERAL, 0, sizeof(struct user_regs_struct), datap); case PTRACE_GETFPREGS: /* Get the child FPU state. */ return copy_regset_to_user(child, regset_view, REGSET_FP, 0, sizeof(struct user_i387_struct), datap); case PTRACE_SETFPREGS: /* Set the child FPU state. */ return copy_regset_from_user(child, regset_view, REGSET_FP, 0, sizeof(struct user_i387_struct), datap); #ifdef CONFIG_X86_32 case PTRACE_GETFPXREGS: /* Get the child extended FPU state. */ return copy_regset_to_user(child, &user_x86_32_view, REGSET32_XFP, 0, sizeof(struct user_fxsr_struct), datap) ? -EIO : 0; case PTRACE_SETFPXREGS: /* Set the child extended FPU state. */ return copy_regset_from_user(child, &user_x86_32_view, REGSET32_XFP, 0, sizeof(struct user_fxsr_struct), datap) ? -EIO : 0; #endif #if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION case PTRACE_GET_THREAD_AREA: if ((int) addr < 0) return -EIO; ret = do_get_thread_area(child, addr, (struct user_desc __user *)data); break; case PTRACE_SET_THREAD_AREA: if ((int) addr < 0) return -EIO; ret = do_set_thread_area(child, addr, (struct user_desc __user *)data, 0); break; #endif #ifdef CONFIG_X86_64 /* normal 64bit interface to access TLS data. Works just like arch_prctl, except that the arguments are reversed. */ case PTRACE_ARCH_PRCTL: ret = do_arch_prctl_64(child, data, addr); break; #endif default: ret = ptrace_request(child, request, addr, data); break; } return ret; } #ifdef CONFIG_IA32_EMULATION #include <linux/compat.h> #include <linux/syscalls.h> #include <asm/ia32.h> #include <asm/user32.h> #define R32(l,q) \ case offsetof(struct user32, regs.l): \ regs->q = value; break #define SEG32(rs) \ case offsetof(struct user32, regs.rs): \ return set_segment_reg(child, \ offsetof(struct user_regs_struct, rs), \ value); \ break static int putreg32(struct task_struct *child, unsigned regno, u32 value) { struct pt_regs *regs = task_pt_regs(child); int ret; switch (regno) { SEG32(cs); SEG32(ds); SEG32(es); /* * A 32-bit ptracer on a 64-bit kernel expects that writing * FS or GS will also update the base. This is needed for * operations like PTRACE_SETREGS to fully restore a saved * CPU state. */ case offsetof(struct user32, regs.fs): ret = set_segment_reg(child, offsetof(struct user_regs_struct, fs), value); if (ret == 0) child->thread.fsbase = x86_fsgsbase_read_task(child, value); return ret; case offsetof(struct user32, regs.gs): ret = set_segment_reg(child, offsetof(struct user_regs_struct, gs), value); if (ret == 0) child->thread.gsbase = x86_fsgsbase_read_task(child, value); return ret; SEG32(ss); R32(ebx, bx); R32(ecx, cx); R32(edx, dx); R32(edi, di); R32(esi, si); R32(ebp, bp); R32(eax, ax); R32(eip, ip); R32(esp, sp); case offsetof(struct user32, regs.orig_eax): /* * Warning: bizarre corner case fixup here. A 32-bit * debugger setting orig_eax to -1 wants to disable * syscall restart. Make sure that the syscall * restart code sign-extends orig_ax. Also make sure * we interpret the -ERESTART* codes correctly if * loaded into regs->ax in case the task is not * actually still sitting at the exit from a 32-bit * syscall with TS_COMPAT still set. */ regs->orig_ax = value; if (syscall_get_nr(child, regs) != -1) child->thread_info.status |= TS_I386_REGS_POKED; break; case offsetof(struct user32, regs.eflags): return set_flags(child, value); case offsetof(struct user32, u_debugreg[0]) ... offsetof(struct user32, u_debugreg[7]): regno -= offsetof(struct user32, u_debugreg[0]); return ptrace_set_debugreg(child, regno / 4, value); default: if (regno > sizeof(struct user32) || (regno & 3)) return -EIO; /* * Other dummy fields in the virtual user structure * are ignored */ break; } return 0; } #undef R32 #undef SEG32 #define R32(l,q) \ case offsetof(struct user32, regs.l): \ *val = regs->q; break #define SEG32(rs) \ case offsetof(struct user32, regs.rs): \ *val = get_segment_reg(child, \ offsetof(struct user_regs_struct, rs)); \ break static int getreg32(struct task_struct *child, unsigned regno, u32 *val) { struct pt_regs *regs = task_pt_regs(child); switch (regno) { SEG32(ds); SEG32(es); SEG32(fs); SEG32(gs); R32(cs, cs); R32(ss, ss); R32(ebx, bx); R32(ecx, cx); R32(edx, dx); R32(edi, di); R32(esi, si); R32(ebp, bp); R32(eax, ax); R32(orig_eax, orig_ax); R32(eip, ip); R32(esp, sp); case offsetof(struct user32, regs.eflags): *val = get_flags(child); break; case offsetof(struct user32, u_debugreg[0]) ... offsetof(struct user32, u_debugreg[7]): regno -= offsetof(struct user32, u_debugreg[0]); *val = ptrace_get_debugreg(child, regno / 4); break; default: if (regno > sizeof(struct user32) || (regno & 3)) return -EIO; /* * Other dummy fields in the virtual user structure * are ignored */ *val = 0; break; } return 0; } #undef R32 #undef SEG32 static int genregs32_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { int reg; for (reg = 0; to.left; reg++) { u32 val; getreg32(target, reg * 4, &val); membuf_store(&to, val); } return 0; } static int genregs32_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { int ret = 0; if (kbuf) { const compat_ulong_t *k = kbuf; while (count >= sizeof(*k) && !ret) { ret = putreg32(target, pos, *k++); count -= sizeof(*k); pos += sizeof(*k); } } else { const compat_ulong_t __user *u = ubuf; while (count >= sizeof(*u) && !ret) { compat_ulong_t word; ret = __get_user(word, u++); if (ret) break; ret = putreg32(target, pos, word); count -= sizeof(*u); pos += sizeof(*u); } } return ret; } static long ia32_arch_ptrace(struct task_struct *child, compat_long_t request, compat_ulong_t caddr, compat_ulong_t cdata) { unsigned long addr = caddr; unsigned long data = cdata; void __user *datap = compat_ptr(data); int ret; __u32 val; switch (request) { case PTRACE_PEEKUSR: ret = getreg32(child, addr, &val); if (ret == 0) ret = put_user(val, (__u32 __user *)datap); break; case PTRACE_POKEUSR: ret = putreg32(child, addr, data); break; case PTRACE_GETREGS: /* Get all gp regs from the child. */ return copy_regset_to_user(child, &user_x86_32_view, REGSET_GENERAL, 0, sizeof(struct user_regs_struct32), datap); case PTRACE_SETREGS: /* Set all gp regs in the child. */ return copy_regset_from_user(child, &user_x86_32_view, REGSET_GENERAL, 0, sizeof(struct user_regs_struct32), datap); case PTRACE_GETFPREGS: /* Get the child FPU state. */ return copy_regset_to_user(child, &user_x86_32_view, REGSET_FP, 0, sizeof(struct user_i387_ia32_struct), datap); case PTRACE_SETFPREGS: /* Set the child FPU state. */ return copy_regset_from_user( child, &user_x86_32_view, REGSET_FP, 0, sizeof(struct user_i387_ia32_struct), datap); case PTRACE_GETFPXREGS: /* Get the child extended FPU state. */ return copy_regset_to_user(child, &user_x86_32_view, REGSET32_XFP, 0, sizeof(struct user32_fxsr_struct), datap); case PTRACE_SETFPXREGS: /* Set the child extended FPU state. */ return copy_regset_from_user(child, &user_x86_32_view, REGSET32_XFP, 0, sizeof(struct user32_fxsr_struct), datap); case PTRACE_GET_THREAD_AREA: case PTRACE_SET_THREAD_AREA: return arch_ptrace(child, request, addr, data); default: return compat_ptrace_request(child, request, addr, data); } return ret; } #endif /* CONFIG_IA32_EMULATION */ #ifdef CONFIG_X86_X32_ABI static long x32_arch_ptrace(struct task_struct *child, compat_long_t request, compat_ulong_t caddr, compat_ulong_t cdata) { unsigned long addr = caddr; unsigned long data = cdata; void __user *datap = compat_ptr(data); int ret; switch (request) { /* Read 32bits at location addr in the USER area. Only allow to return the lower 32bits of segment and debug registers. */ case PTRACE_PEEKUSR: { u32 tmp; ret = -EIO; if ((addr & (sizeof(data) - 1)) || addr >= sizeof(struct user) || addr < offsetof(struct user_regs_struct, cs)) break; tmp = 0; /* Default return condition */ if (addr < sizeof(struct user_regs_struct)) tmp = getreg(child, addr); else if (addr >= offsetof(struct user, u_debugreg[0]) && addr <= offsetof(struct user, u_debugreg[7])) { addr -= offsetof(struct user, u_debugreg[0]); tmp = ptrace_get_debugreg(child, addr / sizeof(data)); } ret = put_user(tmp, (__u32 __user *)datap); break; } /* Write the word at location addr in the USER area. Only allow to update segment and debug registers with the upper 32bits zero-extended. */ case PTRACE_POKEUSR: ret = -EIO; if ((addr & (sizeof(data) - 1)) || addr >= sizeof(struct user) || addr < offsetof(struct user_regs_struct, cs)) break; if (addr < sizeof(struct user_regs_struct)) ret = putreg(child, addr, data); else if (addr >= offsetof(struct user, u_debugreg[0]) && addr <= offsetof(struct user, u_debugreg[7])) { addr -= offsetof(struct user, u_debugreg[0]); ret = ptrace_set_debugreg(child, addr / sizeof(data), data); } break; case PTRACE_GETREGS: /* Get all gp regs from the child. */ return copy_regset_to_user(child, &user_x86_64_view, REGSET_GENERAL, 0, sizeof(struct user_regs_struct), datap); case PTRACE_SETREGS: /* Set all gp regs in the child. */ return copy_regset_from_user(child, &user_x86_64_view, REGSET_GENERAL, 0, sizeof(struct user_regs_struct), datap); case PTRACE_GETFPREGS: /* Get the child FPU state. */ return copy_regset_to_user(child, &user_x86_64_view, REGSET_FP, 0, sizeof(struct user_i387_struct), datap); case PTRACE_SETFPREGS: /* Set the child FPU state. */ return copy_regset_from_user(child, &user_x86_64_view, REGSET_FP, 0, sizeof(struct user_i387_struct), datap); default: return compat_ptrace_request(child, request, addr, data); } return ret; } #endif #ifdef CONFIG_COMPAT long compat_arch_ptrace(struct task_struct *child, compat_long_t request, compat_ulong_t caddr, compat_ulong_t cdata) { #ifdef CONFIG_X86_X32_ABI if (!in_ia32_syscall()) return x32_arch_ptrace(child, request, caddr, cdata); #endif #ifdef CONFIG_IA32_EMULATION return ia32_arch_ptrace(child, request, caddr, cdata); #else return 0; #endif } #endif /* CONFIG_COMPAT */ #ifdef CONFIG_X86_64 static struct user_regset x86_64_regsets[] __ro_after_init = { [REGSET64_GENERAL] = { .core_note_type = NT_PRSTATUS, .n = sizeof(struct user_regs_struct) / sizeof(long), .size = sizeof(long), .align = sizeof(long), .regset_get = genregs_get, .set = genregs_set }, [REGSET64_FP] = { .core_note_type = NT_PRFPREG, .n = sizeof(struct fxregs_state) / sizeof(long), .size = sizeof(long), .align = sizeof(long), .active = regset_xregset_fpregs_active, .regset_get = xfpregs_get, .set = xfpregs_set }, [REGSET64_XSTATE] = { .core_note_type = NT_X86_XSTATE, .size = sizeof(u64), .align = sizeof(u64), .active = xstateregs_active, .regset_get = xstateregs_get, .set = xstateregs_set }, [REGSET64_IOPERM] = { .core_note_type = NT_386_IOPERM, .n = IO_BITMAP_LONGS, .size = sizeof(long), .align = sizeof(long), .active = ioperm_active, .regset_get = ioperm_get }, #ifdef CONFIG_X86_USER_SHADOW_STACK [REGSET64_SSP] = { .core_note_type = NT_X86_SHSTK, .n = 1, .size = sizeof(u64), .align = sizeof(u64), .active = ssp_active, .regset_get = ssp_get, .set = ssp_set }, #endif }; static const struct user_regset_view user_x86_64_view = { .name = "x86_64", .e_machine = EM_X86_64, .regsets = x86_64_regsets, .n = ARRAY_SIZE(x86_64_regsets) }; #else /* CONFIG_X86_32 */ #define user_regs_struct32 user_regs_struct #define genregs32_get genregs_get #define genregs32_set genregs_set #endif /* CONFIG_X86_64 */ #if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION static struct user_regset x86_32_regsets[] __ro_after_init = { [REGSET32_GENERAL] = { .core_note_type = NT_PRSTATUS, .n = sizeof(struct user_regs_struct32) / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .regset_get = genregs32_get, .set = genregs32_set }, [REGSET32_FP] = { .core_note_type = NT_PRFPREG, .n = sizeof(struct user_i387_ia32_struct) / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .active = regset_fpregs_active, .regset_get = fpregs_get, .set = fpregs_set }, [REGSET32_XFP] = { .core_note_type = NT_PRXFPREG, .n = sizeof(struct fxregs_state) / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .active = regset_xregset_fpregs_active, .regset_get = xfpregs_get, .set = xfpregs_set }, [REGSET32_XSTATE] = { .core_note_type = NT_X86_XSTATE, .size = sizeof(u64), .align = sizeof(u64), .active = xstateregs_active, .regset_get = xstateregs_get, .set = xstateregs_set }, [REGSET32_TLS] = { .core_note_type = NT_386_TLS, .n = GDT_ENTRY_TLS_ENTRIES, .bias = GDT_ENTRY_TLS_MIN, .size = sizeof(struct user_desc), .align = sizeof(struct user_desc), .active = regset_tls_active, .regset_get = regset_tls_get, .set = regset_tls_set }, [REGSET32_IOPERM] = { .core_note_type = NT_386_IOPERM, .n = IO_BITMAP_BYTES / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .active = ioperm_active, .regset_get = ioperm_get }, }; static const struct user_regset_view user_x86_32_view = { .name = "i386", .e_machine = EM_386, .regsets = x86_32_regsets, .n = ARRAY_SIZE(x86_32_regsets) }; #endif /* * This represents bytes 464..511 in the memory layout exported through * the REGSET_XSTATE interface. */ u64 xstate_fx_sw_bytes[USER_XSTATE_FX_SW_WORDS]; void __init update_regset_xstate_info(unsigned int size, u64 xstate_mask) { #ifdef CONFIG_X86_64 x86_64_regsets[REGSET64_XSTATE].n = size / sizeof(u64); #endif #if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION x86_32_regsets[REGSET32_XSTATE].n = size / sizeof(u64); #endif xstate_fx_sw_bytes[USER_XSTATE_XCR0_WORD] = xstate_mask; } /* * This is used by the core dump code to decide which regset to dump. The * core dump code writes out the resulting .e_machine and the corresponding * regsets. This is suboptimal if the task is messing around with its CS.L * field, but at worst the core dump will end up missing some information. * * Unfortunately, it is also used by the broken PTRACE_GETREGSET and * PTRACE_SETREGSET APIs. These APIs look at the .regsets field but have * no way to make sure that the e_machine they use matches the caller's * expectations. The result is that the data format returned by * PTRACE_GETREGSET depends on the returned CS field (and even the offset * of the returned CS field depends on its value!) and the data format * accepted by PTRACE_SETREGSET is determined by the old CS value. The * upshot is that it is basically impossible to use these APIs correctly. * * The best way to fix it in the long run would probably be to add new * improved ptrace() APIs to read and write registers reliably, possibly by * allowing userspace to select the ELF e_machine variant that they expect. */ const struct user_regset_view *task_user_regset_view(struct task_struct *task) { #ifdef CONFIG_IA32_EMULATION if (!user_64bit_mode(task_pt_regs(task))) #endif #if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION return &user_x86_32_view; #endif #ifdef CONFIG_X86_64 return &user_x86_64_view; #endif } void send_sigtrap(struct pt_regs *regs, int error_code, int si_code) { struct task_struct *tsk = current; tsk->thread.trap_nr = X86_TRAP_DB; tsk->thread.error_code = error_code; /* Send us the fake SIGTRAP */ force_sig_fault(SIGTRAP, si_code, user_mode(regs) ? (void __user *)regs->ip : NULL); } void user_single_step_report(struct pt_regs *regs) { send_sigtrap(regs, 0, TRAP_BRKPT); }
linux-master
arch/x86/kernel/ptrace.c
// SPDX-License-Identifier: GPL-2.0-only /* * Dynamic DMA mapping support for AMD Hammer. * * Use the integrated AGP GART in the Hammer northbridge as an IOMMU for PCI. * This allows to use PCI devices that only support 32bit addresses on systems * with more than 4GB. * * See Documentation/core-api/dma-api-howto.rst for the interface specification. * * Copyright 2002 Andi Kleen, SuSE Labs. */ #include <linux/types.h> #include <linux/ctype.h> #include <linux/agp_backend.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/sched/debug.h> #include <linux/string.h> #include <linux/spinlock.h> #include <linux/pci.h> #include <linux/topology.h> #include <linux/interrupt.h> #include <linux/bitmap.h> #include <linux/kdebug.h> #include <linux/scatterlist.h> #include <linux/iommu-helper.h> #include <linux/syscore_ops.h> #include <linux/io.h> #include <linux/gfp.h> #include <linux/atomic.h> #include <linux/dma-direct.h> #include <linux/dma-map-ops.h> #include <asm/mtrr.h> #include <asm/proto.h> #include <asm/iommu.h> #include <asm/gart.h> #include <asm/set_memory.h> #include <asm/dma.h> #include <asm/amd_nb.h> #include <asm/x86_init.h> static unsigned long iommu_bus_base; /* GART remapping area (physical) */ static unsigned long iommu_size; /* size of remapping area bytes */ static unsigned long iommu_pages; /* .. and in pages */ static u32 *iommu_gatt_base; /* Remapping table */ /* * If this is disabled the IOMMU will use an optimized flushing strategy * of only flushing when an mapping is reused. With it true the GART is * flushed for every mapping. Problem is that doing the lazy flush seems * to trigger bugs with some popular PCI cards, in particular 3ware (but * has been also seen with Qlogic at least). */ static int iommu_fullflush = 1; /* Allocation bitmap for the remapping area: */ static DEFINE_SPINLOCK(iommu_bitmap_lock); /* Guarded by iommu_bitmap_lock: */ static unsigned long *iommu_gart_bitmap; static u32 gart_unmapped_entry; #define GPTE_VALID 1 #define GPTE_COHERENT 2 #define GPTE_ENCODE(x) \ (((x) & 0xfffff000) | (((x) >> 32) << 4) | GPTE_VALID | GPTE_COHERENT) #define GPTE_DECODE(x) (((x) & 0xfffff000) | (((u64)(x) & 0xff0) << 28)) #ifdef CONFIG_AGP #define AGPEXTERN extern #else #define AGPEXTERN #endif /* GART can only remap to physical addresses < 1TB */ #define GART_MAX_PHYS_ADDR (1ULL << 40) /* backdoor interface to AGP driver */ AGPEXTERN int agp_memory_reserved; AGPEXTERN __u32 *agp_gatt_table; static unsigned long next_bit; /* protected by iommu_bitmap_lock */ static bool need_flush; /* global flush state. set for each gart wrap */ static unsigned long alloc_iommu(struct device *dev, int size, unsigned long align_mask) { unsigned long offset, flags; unsigned long boundary_size; unsigned long base_index; base_index = ALIGN(iommu_bus_base & dma_get_seg_boundary(dev), PAGE_SIZE) >> PAGE_SHIFT; boundary_size = dma_get_seg_boundary_nr_pages(dev, PAGE_SHIFT); spin_lock_irqsave(&iommu_bitmap_lock, flags); offset = iommu_area_alloc(iommu_gart_bitmap, iommu_pages, next_bit, size, base_index, boundary_size, align_mask); if (offset == -1) { need_flush = true; offset = iommu_area_alloc(iommu_gart_bitmap, iommu_pages, 0, size, base_index, boundary_size, align_mask); } if (offset != -1) { next_bit = offset+size; if (next_bit >= iommu_pages) { next_bit = 0; need_flush = true; } } if (iommu_fullflush) need_flush = true; spin_unlock_irqrestore(&iommu_bitmap_lock, flags); return offset; } static void free_iommu(unsigned long offset, int size) { unsigned long flags; spin_lock_irqsave(&iommu_bitmap_lock, flags); bitmap_clear(iommu_gart_bitmap, offset, size); if (offset >= next_bit) next_bit = offset + size; spin_unlock_irqrestore(&iommu_bitmap_lock, flags); } /* * Use global flush state to avoid races with multiple flushers. */ static void flush_gart(void) { unsigned long flags; spin_lock_irqsave(&iommu_bitmap_lock, flags); if (need_flush) { amd_flush_garts(); need_flush = false; } spin_unlock_irqrestore(&iommu_bitmap_lock, flags); } #ifdef CONFIG_IOMMU_LEAK /* Debugging aid for drivers that don't free their IOMMU tables */ static void dump_leak(void) { static int dump; if (dump) return; dump = 1; show_stack(NULL, NULL, KERN_ERR); debug_dma_dump_mappings(NULL); } #endif static void iommu_full(struct device *dev, size_t size, int dir) { /* * Ran out of IOMMU space for this operation. This is very bad. * Unfortunately the drivers cannot handle this operation properly. * Return some non mapped prereserved space in the aperture and * let the Northbridge deal with it. This will result in garbage * in the IO operation. When the size exceeds the prereserved space * memory corruption will occur or random memory will be DMAed * out. Hopefully no network devices use single mappings that big. */ dev_err(dev, "PCI-DMA: Out of IOMMU space for %lu bytes\n", size); #ifdef CONFIG_IOMMU_LEAK dump_leak(); #endif } static inline int need_iommu(struct device *dev, unsigned long addr, size_t size) { return force_iommu || !dma_capable(dev, addr, size, true); } static inline int nonforced_iommu(struct device *dev, unsigned long addr, size_t size) { return !dma_capable(dev, addr, size, true); } /* Map a single continuous physical area into the IOMMU. * Caller needs to check if the iommu is needed and flush. */ static dma_addr_t dma_map_area(struct device *dev, dma_addr_t phys_mem, size_t size, int dir, unsigned long align_mask) { unsigned long npages = iommu_num_pages(phys_mem, size, PAGE_SIZE); unsigned long iommu_page; int i; if (unlikely(phys_mem + size > GART_MAX_PHYS_ADDR)) return DMA_MAPPING_ERROR; iommu_page = alloc_iommu(dev, npages, align_mask); if (iommu_page == -1) { if (!nonforced_iommu(dev, phys_mem, size)) return phys_mem; if (panic_on_overflow) panic("dma_map_area overflow %lu bytes\n", size); iommu_full(dev, size, dir); return DMA_MAPPING_ERROR; } for (i = 0; i < npages; i++) { iommu_gatt_base[iommu_page + i] = GPTE_ENCODE(phys_mem); phys_mem += PAGE_SIZE; } return iommu_bus_base + iommu_page*PAGE_SIZE + (phys_mem & ~PAGE_MASK); } /* Map a single area into the IOMMU */ static dma_addr_t gart_map_page(struct device *dev, struct page *page, unsigned long offset, size_t size, enum dma_data_direction dir, unsigned long attrs) { unsigned long bus; phys_addr_t paddr = page_to_phys(page) + offset; if (!need_iommu(dev, paddr, size)) return paddr; bus = dma_map_area(dev, paddr, size, dir, 0); flush_gart(); return bus; } /* * Free a DMA mapping. */ static void gart_unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size, enum dma_data_direction dir, unsigned long attrs) { unsigned long iommu_page; int npages; int i; if (WARN_ON_ONCE(dma_addr == DMA_MAPPING_ERROR)) return; /* * This driver will not always use a GART mapping, but might have * created a direct mapping instead. If that is the case there is * nothing to unmap here. */ if (dma_addr < iommu_bus_base || dma_addr >= iommu_bus_base + iommu_size) return; iommu_page = (dma_addr - iommu_bus_base)>>PAGE_SHIFT; npages = iommu_num_pages(dma_addr, size, PAGE_SIZE); for (i = 0; i < npages; i++) { iommu_gatt_base[iommu_page + i] = gart_unmapped_entry; } free_iommu(iommu_page, npages); } /* * Wrapper for pci_unmap_single working with scatterlists. */ static void gart_unmap_sg(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir, unsigned long attrs) { struct scatterlist *s; int i; for_each_sg(sg, s, nents, i) { if (!s->dma_length || !s->length) break; gart_unmap_page(dev, s->dma_address, s->dma_length, dir, 0); } } /* Fallback for dma_map_sg in case of overflow */ static int dma_map_sg_nonforce(struct device *dev, struct scatterlist *sg, int nents, int dir) { struct scatterlist *s; int i; #ifdef CONFIG_IOMMU_DEBUG pr_debug("dma_map_sg overflow\n"); #endif for_each_sg(sg, s, nents, i) { unsigned long addr = sg_phys(s); if (nonforced_iommu(dev, addr, s->length)) { addr = dma_map_area(dev, addr, s->length, dir, 0); if (addr == DMA_MAPPING_ERROR) { if (i > 0) gart_unmap_sg(dev, sg, i, dir, 0); nents = 0; sg[0].dma_length = 0; break; } } s->dma_address = addr; s->dma_length = s->length; } flush_gart(); return nents; } /* Map multiple scatterlist entries continuous into the first. */ static int __dma_map_cont(struct device *dev, struct scatterlist *start, int nelems, struct scatterlist *sout, unsigned long pages) { unsigned long iommu_start = alloc_iommu(dev, pages, 0); unsigned long iommu_page = iommu_start; struct scatterlist *s; int i; if (iommu_start == -1) return -ENOMEM; for_each_sg(start, s, nelems, i) { unsigned long pages, addr; unsigned long phys_addr = s->dma_address; BUG_ON(s != start && s->offset); if (s == start) { sout->dma_address = iommu_bus_base; sout->dma_address += iommu_page*PAGE_SIZE + s->offset; sout->dma_length = s->length; } else { sout->dma_length += s->length; } addr = phys_addr; pages = iommu_num_pages(s->offset, s->length, PAGE_SIZE); while (pages--) { iommu_gatt_base[iommu_page] = GPTE_ENCODE(addr); addr += PAGE_SIZE; iommu_page++; } } BUG_ON(iommu_page - iommu_start != pages); return 0; } static inline int dma_map_cont(struct device *dev, struct scatterlist *start, int nelems, struct scatterlist *sout, unsigned long pages, int need) { if (!need) { BUG_ON(nelems != 1); sout->dma_address = start->dma_address; sout->dma_length = start->length; return 0; } return __dma_map_cont(dev, start, nelems, sout, pages); } /* * DMA map all entries in a scatterlist. * Merge chunks that have page aligned sizes into a continuous mapping. */ static int gart_map_sg(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir, unsigned long attrs) { struct scatterlist *s, *ps, *start_sg, *sgmap; int need = 0, nextneed, i, out, start, ret; unsigned long pages = 0; unsigned int seg_size; unsigned int max_seg_size; if (nents == 0) return -EINVAL; out = 0; start = 0; start_sg = sg; sgmap = sg; seg_size = 0; max_seg_size = dma_get_max_seg_size(dev); ps = NULL; /* shut up gcc */ for_each_sg(sg, s, nents, i) { dma_addr_t addr = sg_phys(s); s->dma_address = addr; BUG_ON(s->length == 0); nextneed = need_iommu(dev, addr, s->length); /* Handle the previous not yet processed entries */ if (i > start) { /* * Can only merge when the last chunk ends on a * page boundary and the new one doesn't have an * offset. */ if (!iommu_merge || !nextneed || !need || s->offset || (s->length + seg_size > max_seg_size) || (ps->offset + ps->length) % PAGE_SIZE) { ret = dma_map_cont(dev, start_sg, i - start, sgmap, pages, need); if (ret < 0) goto error; out++; seg_size = 0; sgmap = sg_next(sgmap); pages = 0; start = i; start_sg = s; } } seg_size += s->length; need = nextneed; pages += iommu_num_pages(s->offset, s->length, PAGE_SIZE); ps = s; } ret = dma_map_cont(dev, start_sg, i - start, sgmap, pages, need); if (ret < 0) goto error; out++; flush_gart(); if (out < nents) { sgmap = sg_next(sgmap); sgmap->dma_length = 0; } return out; error: flush_gart(); gart_unmap_sg(dev, sg, out, dir, 0); /* When it was forced or merged try again in a dumb way */ if (force_iommu || iommu_merge) { out = dma_map_sg_nonforce(dev, sg, nents, dir); if (out > 0) return out; } if (panic_on_overflow) panic("dma_map_sg: overflow on %lu pages\n", pages); iommu_full(dev, pages << PAGE_SHIFT, dir); return ret; } /* allocate and map a coherent mapping */ static void * gart_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_addr, gfp_t flag, unsigned long attrs) { void *vaddr; vaddr = dma_direct_alloc(dev, size, dma_addr, flag, attrs); if (!vaddr || !force_iommu || dev->coherent_dma_mask <= DMA_BIT_MASK(24)) return vaddr; *dma_addr = dma_map_area(dev, virt_to_phys(vaddr), size, DMA_BIDIRECTIONAL, (1UL << get_order(size)) - 1); flush_gart(); if (unlikely(*dma_addr == DMA_MAPPING_ERROR)) goto out_free; return vaddr; out_free: dma_direct_free(dev, size, vaddr, *dma_addr, attrs); return NULL; } /* free a coherent mapping */ static void gart_free_coherent(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_addr, unsigned long attrs) { gart_unmap_page(dev, dma_addr, size, DMA_BIDIRECTIONAL, 0); dma_direct_free(dev, size, vaddr, dma_addr, attrs); } static int no_agp; static __init unsigned long check_iommu_size(unsigned long aper, u64 aper_size) { unsigned long a; if (!iommu_size) { iommu_size = aper_size; if (!no_agp) iommu_size /= 2; } a = aper + iommu_size; iommu_size -= round_up(a, PMD_SIZE) - a; if (iommu_size < 64*1024*1024) { pr_warn("PCI-DMA: Warning: Small IOMMU %luMB." " Consider increasing the AGP aperture in BIOS\n", iommu_size >> 20); } return iommu_size; } static __init unsigned read_aperture(struct pci_dev *dev, u32 *size) { unsigned aper_size = 0, aper_base_32, aper_order; u64 aper_base; pci_read_config_dword(dev, AMD64_GARTAPERTUREBASE, &aper_base_32); pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &aper_order); aper_order = (aper_order >> 1) & 7; aper_base = aper_base_32 & 0x7fff; aper_base <<= 25; aper_size = (32 * 1024 * 1024) << aper_order; if (aper_base + aper_size > 0x100000000UL || !aper_size) aper_base = 0; *size = aper_size; return aper_base; } static void enable_gart_translations(void) { int i; if (!amd_nb_has_feature(AMD_NB_GART)) return; for (i = 0; i < amd_nb_num(); i++) { struct pci_dev *dev = node_to_amd_nb(i)->misc; enable_gart_translation(dev, __pa(agp_gatt_table)); } /* Flush the GART-TLB to remove stale entries */ amd_flush_garts(); } /* * If fix_up_north_bridges is set, the north bridges have to be fixed up on * resume in the same way as they are handled in gart_iommu_hole_init(). */ static bool fix_up_north_bridges; static u32 aperture_order; static u32 aperture_alloc; void set_up_gart_resume(u32 aper_order, u32 aper_alloc) { fix_up_north_bridges = true; aperture_order = aper_order; aperture_alloc = aper_alloc; } static void gart_fixup_northbridges(void) { int i; if (!fix_up_north_bridges) return; if (!amd_nb_has_feature(AMD_NB_GART)) return; pr_info("PCI-DMA: Restoring GART aperture settings\n"); for (i = 0; i < amd_nb_num(); i++) { struct pci_dev *dev = node_to_amd_nb(i)->misc; /* * Don't enable translations just yet. That is the next * step. Restore the pre-suspend aperture settings. */ gart_set_size_and_enable(dev, aperture_order); pci_write_config_dword(dev, AMD64_GARTAPERTUREBASE, aperture_alloc >> 25); } } static void gart_resume(void) { pr_info("PCI-DMA: Resuming GART IOMMU\n"); gart_fixup_northbridges(); enable_gart_translations(); } static struct syscore_ops gart_syscore_ops = { .resume = gart_resume, }; /* * Private Northbridge GATT initialization in case we cannot use the * AGP driver for some reason. */ static __init int init_amd_gatt(struct agp_kern_info *info) { unsigned aper_size, gatt_size, new_aper_size; unsigned aper_base, new_aper_base; struct pci_dev *dev; void *gatt; int i; pr_info("PCI-DMA: Disabling AGP.\n"); aper_size = aper_base = info->aper_size = 0; dev = NULL; for (i = 0; i < amd_nb_num(); i++) { dev = node_to_amd_nb(i)->misc; new_aper_base = read_aperture(dev, &new_aper_size); if (!new_aper_base) goto nommu; if (!aper_base) { aper_size = new_aper_size; aper_base = new_aper_base; } if (aper_size != new_aper_size || aper_base != new_aper_base) goto nommu; } if (!aper_base) goto nommu; info->aper_base = aper_base; info->aper_size = aper_size >> 20; gatt_size = (aper_size >> PAGE_SHIFT) * sizeof(u32); gatt = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, get_order(gatt_size)); if (!gatt) panic("Cannot allocate GATT table"); if (set_memory_uc((unsigned long)gatt, gatt_size >> PAGE_SHIFT)) panic("Could not set GART PTEs to uncacheable pages"); agp_gatt_table = gatt; register_syscore_ops(&gart_syscore_ops); flush_gart(); pr_info("PCI-DMA: aperture base @ %x size %u KB\n", aper_base, aper_size>>10); return 0; nommu: /* Should not happen anymore */ pr_warn("PCI-DMA: More than 4GB of RAM and no IOMMU - falling back to iommu=soft.\n"); return -1; } static const struct dma_map_ops gart_dma_ops = { .map_sg = gart_map_sg, .unmap_sg = gart_unmap_sg, .map_page = gart_map_page, .unmap_page = gart_unmap_page, .alloc = gart_alloc_coherent, .free = gart_free_coherent, .mmap = dma_common_mmap, .get_sgtable = dma_common_get_sgtable, .dma_supported = dma_direct_supported, .get_required_mask = dma_direct_get_required_mask, .alloc_pages = dma_direct_alloc_pages, .free_pages = dma_direct_free_pages, }; static void gart_iommu_shutdown(void) { struct pci_dev *dev; int i; /* don't shutdown it if there is AGP installed */ if (!no_agp) return; if (!amd_nb_has_feature(AMD_NB_GART)) return; for (i = 0; i < amd_nb_num(); i++) { u32 ctl; dev = node_to_amd_nb(i)->misc; pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &ctl); ctl &= ~GARTEN; pci_write_config_dword(dev, AMD64_GARTAPERTURECTL, ctl); } } int __init gart_iommu_init(void) { struct agp_kern_info info; unsigned long iommu_start; unsigned long aper_base, aper_size; unsigned long start_pfn, end_pfn; unsigned long scratch; if (!amd_nb_has_feature(AMD_NB_GART)) return 0; #ifndef CONFIG_AGP_AMD64 no_agp = 1; #else /* Makefile puts PCI initialization via subsys_initcall first. */ /* Add other AMD AGP bridge drivers here */ no_agp = no_agp || (agp_amd64_init() < 0) || (agp_copy_info(agp_bridge, &info) < 0); #endif if (no_iommu || (!force_iommu && max_pfn <= MAX_DMA32_PFN) || !gart_iommu_aperture || (no_agp && init_amd_gatt(&info) < 0)) { if (max_pfn > MAX_DMA32_PFN) { pr_warn("More than 4GB of memory but GART IOMMU not available.\n"); pr_warn("falling back to iommu=soft.\n"); } return 0; } /* need to map that range */ aper_size = info.aper_size << 20; aper_base = info.aper_base; end_pfn = (aper_base>>PAGE_SHIFT) + (aper_size>>PAGE_SHIFT); start_pfn = PFN_DOWN(aper_base); if (!pfn_range_is_mapped(start_pfn, end_pfn)) init_memory_mapping(start_pfn<<PAGE_SHIFT, end_pfn<<PAGE_SHIFT, PAGE_KERNEL); pr_info("PCI-DMA: using GART IOMMU.\n"); iommu_size = check_iommu_size(info.aper_base, aper_size); iommu_pages = iommu_size >> PAGE_SHIFT; iommu_gart_bitmap = (void *) __get_free_pages(GFP_KERNEL | __GFP_ZERO, get_order(iommu_pages/8)); if (!iommu_gart_bitmap) panic("Cannot allocate iommu bitmap\n"); pr_info("PCI-DMA: Reserving %luMB of IOMMU area in the AGP aperture\n", iommu_size >> 20); agp_memory_reserved = iommu_size; iommu_start = aper_size - iommu_size; iommu_bus_base = info.aper_base + iommu_start; iommu_gatt_base = agp_gatt_table + (iommu_start>>PAGE_SHIFT); /* * Unmap the IOMMU part of the GART. The alias of the page is * always mapped with cache enabled and there is no full cache * coherency across the GART remapping. The unmapping avoids * automatic prefetches from the CPU allocating cache lines in * there. All CPU accesses are done via the direct mapping to * the backing memory. The GART address is only used by PCI * devices. */ set_memory_np((unsigned long)__va(iommu_bus_base), iommu_size >> PAGE_SHIFT); /* * Tricky. The GART table remaps the physical memory range, * so the CPU wont notice potential aliases and if the memory * is remapped to UC later on, we might surprise the PCI devices * with a stray writeout of a cacheline. So play it sure and * do an explicit, full-scale wbinvd() _after_ having marked all * the pages as Not-Present: */ wbinvd(); /* * Now all caches are flushed and we can safely enable * GART hardware. Doing it early leaves the possibility * of stale cache entries that can lead to GART PTE * errors. */ enable_gart_translations(); /* * Try to workaround a bug (thanks to BenH): * Set unmapped entries to a scratch page instead of 0. * Any prefetches that hit unmapped entries won't get an bus abort * then. (P2P bridge may be prefetching on DMA reads). */ scratch = get_zeroed_page(GFP_KERNEL); if (!scratch) panic("Cannot allocate iommu scratch page"); gart_unmapped_entry = GPTE_ENCODE(__pa(scratch)); flush_gart(); dma_ops = &gart_dma_ops; x86_platform.iommu_shutdown = gart_iommu_shutdown; x86_swiotlb_enable = false; return 0; } void __init gart_parse_options(char *p) { int arg; if (isdigit(*p) && get_option(&p, &arg)) iommu_size = arg; if (!strncmp(p, "fullflush", 9)) iommu_fullflush = 1; if (!strncmp(p, "nofullflush", 11)) iommu_fullflush = 0; if (!strncmp(p, "noagp", 5)) no_agp = 1; if (!strncmp(p, "noaperture", 10)) fix_aperture = 0; /* duplicated from pci-dma.c */ if (!strncmp(p, "force", 5)) gart_iommu_aperture_allowed = 1; if (!strncmp(p, "allowed", 7)) gart_iommu_aperture_allowed = 1; if (!strncmp(p, "memaper", 7)) { fallback_aper_force = 1; p += 7; if (*p == '=') { ++p; if (get_option(&p, &arg)) fallback_aper_order = arg; } } }
linux-master
arch/x86/kernel/amd_gart_64.c
// SPDX-License-Identifier: GPL-2.0 /* * This contains the io-permission bitmap code - written by obz, with changes * by Linus. 32/64 bits code unification by Miguel Botón. */ #include <linux/capability.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/bitmap.h> #include <linux/ioport.h> #include <linux/sched.h> #include <linux/slab.h> #include <asm/io_bitmap.h> #include <asm/desc.h> #include <asm/syscalls.h> #ifdef CONFIG_X86_IOPL_IOPERM static atomic64_t io_bitmap_sequence; void io_bitmap_share(struct task_struct *tsk) { /* Can be NULL when current->thread.iopl_emul == 3 */ if (current->thread.io_bitmap) { /* * Take a refcount on current's bitmap. It can be used by * both tasks as long as none of them changes the bitmap. */ refcount_inc(&current->thread.io_bitmap->refcnt); tsk->thread.io_bitmap = current->thread.io_bitmap; } set_tsk_thread_flag(tsk, TIF_IO_BITMAP); } static void task_update_io_bitmap(struct task_struct *tsk) { struct thread_struct *t = &tsk->thread; if (t->iopl_emul == 3 || t->io_bitmap) { /* TSS update is handled on exit to user space */ set_tsk_thread_flag(tsk, TIF_IO_BITMAP); } else { clear_tsk_thread_flag(tsk, TIF_IO_BITMAP); /* Invalidate TSS */ preempt_disable(); tss_update_io_bitmap(); preempt_enable(); } } void io_bitmap_exit(struct task_struct *tsk) { struct io_bitmap *iobm = tsk->thread.io_bitmap; tsk->thread.io_bitmap = NULL; task_update_io_bitmap(tsk); if (iobm && refcount_dec_and_test(&iobm->refcnt)) kfree(iobm); } /* * This changes the io permissions bitmap in the current task. */ long ksys_ioperm(unsigned long from, unsigned long num, int turn_on) { struct thread_struct *t = &current->thread; unsigned int i, max_long; struct io_bitmap *iobm; if ((from + num <= from) || (from + num > IO_BITMAP_BITS)) return -EINVAL; if (turn_on && (!capable(CAP_SYS_RAWIO) || security_locked_down(LOCKDOWN_IOPORT))) return -EPERM; /* * If it's the first ioperm() call in this thread's lifetime, set the * IO bitmap up. ioperm() is much less timing critical than clone(), * this is why we delay this operation until now: */ iobm = t->io_bitmap; if (!iobm) { /* No point to allocate a bitmap just to clear permissions */ if (!turn_on) return 0; iobm = kmalloc(sizeof(*iobm), GFP_KERNEL); if (!iobm) return -ENOMEM; memset(iobm->bitmap, 0xff, sizeof(iobm->bitmap)); refcount_set(&iobm->refcnt, 1); } /* * If the bitmap is not shared, then nothing can take a refcount as * current can obviously not fork at the same time. If it's shared * duplicate it and drop the refcount on the original one. */ if (refcount_read(&iobm->refcnt) > 1) { iobm = kmemdup(iobm, sizeof(*iobm), GFP_KERNEL); if (!iobm) return -ENOMEM; refcount_set(&iobm->refcnt, 1); io_bitmap_exit(current); } /* * Store the bitmap pointer (might be the same if the task already * head one). Must be done here so freeing the bitmap when all * permissions are dropped has the pointer set up. */ t->io_bitmap = iobm; /* Mark it active for context switching and exit to user mode */ set_thread_flag(TIF_IO_BITMAP); /* * Update the tasks bitmap. The update of the TSS bitmap happens on * exit to user mode. So this needs no protection. */ if (turn_on) bitmap_clear(iobm->bitmap, from, num); else bitmap_set(iobm->bitmap, from, num); /* * Search for a (possibly new) maximum. This is simple and stupid, * to keep it obviously correct: */ max_long = UINT_MAX; for (i = 0; i < IO_BITMAP_LONGS; i++) { if (iobm->bitmap[i] != ~0UL) max_long = i; } /* All permissions dropped? */ if (max_long == UINT_MAX) { io_bitmap_exit(current); return 0; } iobm->max = (max_long + 1) * sizeof(unsigned long); /* * Update the sequence number to force a TSS update on return to * user mode. */ iobm->sequence = atomic64_add_return(1, &io_bitmap_sequence); return 0; } SYSCALL_DEFINE3(ioperm, unsigned long, from, unsigned long, num, int, turn_on) { return ksys_ioperm(from, num, turn_on); } /* * The sys_iopl functionality depends on the level argument, which if * granted for the task is used to enable access to all 65536 I/O ports. * * This does not use the IOPL mechanism provided by the CPU as that would * also allow the user space task to use the CLI/STI instructions. * * Disabling interrupts in a user space task is dangerous as it might lock * up the machine and the semantics vs. syscalls and exceptions is * undefined. * * Setting IOPL to level 0-2 is disabling I/O permissions. Level 3 * 3 enables them. * * IOPL is strictly per thread and inherited on fork. */ SYSCALL_DEFINE1(iopl, unsigned int, level) { struct thread_struct *t = &current->thread; unsigned int old; if (level > 3) return -EINVAL; old = t->iopl_emul; /* No point in going further if nothing changes */ if (level == old) return 0; /* Trying to gain more privileges? */ if (level > old) { if (!capable(CAP_SYS_RAWIO) || security_locked_down(LOCKDOWN_IOPORT)) return -EPERM; } t->iopl_emul = level; task_update_io_bitmap(current); return 0; } #else /* CONFIG_X86_IOPL_IOPERM */ long ksys_ioperm(unsigned long from, unsigned long num, int turn_on) { return -ENOSYS; } SYSCALL_DEFINE3(ioperm, unsigned long, from, unsigned long, num, int, turn_on) { return -ENOSYS; } SYSCALL_DEFINE1(iopl, unsigned int, level) { return -ENOSYS; } #endif
linux-master
arch/x86/kernel/ioport.c
// SPDX-License-Identifier: GPL-2.0 /* * AMD Family 10h mmconfig enablement */ #include <linux/types.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/pci.h> #include <linux/dmi.h> #include <linux/range.h> #include <asm/pci-direct.h> #include <linux/sort.h> #include <asm/io.h> #include <asm/msr.h> #include <asm/acpi.h> #include <asm/mmconfig.h> #include <asm/pci_x86.h> struct pci_hostbridge_probe { u32 bus; u32 slot; u32 vendor; u32 device; }; static u64 fam10h_pci_mmconf_base; static struct pci_hostbridge_probe pci_probes[] = { { 0, 0x18, PCI_VENDOR_ID_AMD, 0x1200 }, { 0xff, 0, PCI_VENDOR_ID_AMD, 0x1200 }, }; static int cmp_range(const void *x1, const void *x2) { const struct range *r1 = x1; const struct range *r2 = x2; int start1, start2; start1 = r1->start >> 32; start2 = r2->start >> 32; return start1 - start2; } #define MMCONF_UNIT (1ULL << FAM10H_MMIO_CONF_BASE_SHIFT) #define MMCONF_MASK (~(MMCONF_UNIT - 1)) #define MMCONF_SIZE (MMCONF_UNIT << 8) /* need to avoid (0xfd<<32), (0xfe<<32), and (0xff<<32), ht used space */ #define FAM10H_PCI_MMCONF_BASE (0xfcULL<<32) #define BASE_VALID(b) ((b) + MMCONF_SIZE <= (0xfdULL<<32) || (b) >= (1ULL<<40)) static void get_fam10h_pci_mmconf_base(void) { int i; unsigned bus; unsigned slot; int found; u64 val; u32 address; u64 tom2; u64 base = FAM10H_PCI_MMCONF_BASE; int hi_mmio_num; struct range range[8]; /* only try to get setting from BSP */ if (fam10h_pci_mmconf_base) return; if (!early_pci_allowed()) return; found = 0; for (i = 0; i < ARRAY_SIZE(pci_probes); i++) { u32 id; u16 device; u16 vendor; bus = pci_probes[i].bus; slot = pci_probes[i].slot; id = read_pci_config(bus, slot, 0, PCI_VENDOR_ID); vendor = id & 0xffff; device = (id>>16) & 0xffff; if (pci_probes[i].vendor == vendor && pci_probes[i].device == device) { found = 1; break; } } if (!found) return; /* SYS_CFG */ address = MSR_AMD64_SYSCFG; rdmsrl(address, val); /* TOP_MEM2 is not enabled? */ if (!(val & (1<<21))) { tom2 = 1ULL << 32; } else { /* TOP_MEM2 */ address = MSR_K8_TOP_MEM2; rdmsrl(address, val); tom2 = max(val & 0xffffff800000ULL, 1ULL << 32); } if (base <= tom2) base = (tom2 + 2 * MMCONF_UNIT - 1) & MMCONF_MASK; /* * need to check if the range is in the high mmio range that is * above 4G */ hi_mmio_num = 0; for (i = 0; i < 8; i++) { u32 reg; u64 start; u64 end; reg = read_pci_config(bus, slot, 1, 0x80 + (i << 3)); if (!(reg & 3)) continue; start = (u64)(reg & 0xffffff00) << 8; /* 39:16 on 31:8*/ reg = read_pci_config(bus, slot, 1, 0x84 + (i << 3)); end = ((u64)(reg & 0xffffff00) << 8) | 0xffff; /* 39:16 on 31:8*/ if (end < tom2) continue; range[hi_mmio_num].start = start; range[hi_mmio_num].end = end; hi_mmio_num++; } if (!hi_mmio_num) goto out; /* sort the range */ sort(range, hi_mmio_num, sizeof(struct range), cmp_range, NULL); if (range[hi_mmio_num - 1].end < base) goto out; if (range[0].start > base + MMCONF_SIZE) goto out; /* need to find one window */ base = (range[0].start & MMCONF_MASK) - MMCONF_UNIT; if ((base > tom2) && BASE_VALID(base)) goto out; base = (range[hi_mmio_num - 1].end + MMCONF_UNIT) & MMCONF_MASK; if (BASE_VALID(base)) goto out; /* need to find window between ranges */ for (i = 1; i < hi_mmio_num; i++) { base = (range[i - 1].end + MMCONF_UNIT) & MMCONF_MASK; val = range[i].start & MMCONF_MASK; if (val >= base + MMCONF_SIZE && BASE_VALID(base)) goto out; } return; out: fam10h_pci_mmconf_base = base; } void fam10h_check_enable_mmcfg(void) { u64 val; u32 address; if (!(pci_probe & PCI_CHECK_ENABLE_AMD_MMCONF)) return; address = MSR_FAM10H_MMIO_CONF_BASE; rdmsrl(address, val); /* try to make sure that AP's setting is identical to BSP setting */ if (val & FAM10H_MMIO_CONF_ENABLE) { unsigned busnbits; busnbits = (val >> FAM10H_MMIO_CONF_BUSRANGE_SHIFT) & FAM10H_MMIO_CONF_BUSRANGE_MASK; /* only trust the one handle 256 buses, if acpi=off */ if (!acpi_pci_disabled || busnbits >= 8) { u64 base = val & MMCONF_MASK; if (!fam10h_pci_mmconf_base) { fam10h_pci_mmconf_base = base; return; } else if (fam10h_pci_mmconf_base == base) return; } } /* * if it is not enabled, try to enable it and assume only one segment * with 256 buses */ get_fam10h_pci_mmconf_base(); if (!fam10h_pci_mmconf_base) { pci_probe &= ~PCI_CHECK_ENABLE_AMD_MMCONF; return; } printk(KERN_INFO "Enable MMCONFIG on AMD Family 10h\n"); val &= ~((FAM10H_MMIO_CONF_BASE_MASK<<FAM10H_MMIO_CONF_BASE_SHIFT) | (FAM10H_MMIO_CONF_BUSRANGE_MASK<<FAM10H_MMIO_CONF_BUSRANGE_SHIFT)); val |= fam10h_pci_mmconf_base | (8 << FAM10H_MMIO_CONF_BUSRANGE_SHIFT) | FAM10H_MMIO_CONF_ENABLE; wrmsrl(address, val); } static int __init set_check_enable_amd_mmconf(const struct dmi_system_id *d) { pci_probe |= PCI_CHECK_ENABLE_AMD_MMCONF; return 0; } static const struct dmi_system_id __initconst mmconf_dmi_table[] = { { .callback = set_check_enable_amd_mmconf, .ident = "Sun Microsystems Machine", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Sun Microsystems"), }, }, {} }; /* Called from a non __init function, but only on the BSP. */ void __ref check_enable_amd_mmconf_dmi(void) { dmi_check_system(mmconf_dmi_table); }
linux-master
arch/x86/kernel/mmconf-fam10h_64.c
/* * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs * * Pentium III FXSR, SSE support * Gareth Hughes <[email protected]>, May 2000 */ /* * Handle hardware traps and faults. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/context_tracking.h> #include <linux/interrupt.h> #include <linux/kallsyms.h> #include <linux/kmsan.h> #include <linux/spinlock.h> #include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/kdebug.h> #include <linux/kgdb.h> #include <linux/kernel.h> #include <linux/export.h> #include <linux/ptrace.h> #include <linux/uprobes.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/kexec.h> #include <linux/sched.h> #include <linux/sched/task_stack.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/bug.h> #include <linux/nmi.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/io.h> #include <linux/hardirq.h> #include <linux/atomic.h> #include <linux/iommu.h> #include <asm/stacktrace.h> #include <asm/processor.h> #include <asm/debugreg.h> #include <asm/realmode.h> #include <asm/text-patching.h> #include <asm/ftrace.h> #include <asm/traps.h> #include <asm/desc.h> #include <asm/fpu/api.h> #include <asm/cpu.h> #include <asm/cpu_entry_area.h> #include <asm/mce.h> #include <asm/fixmap.h> #include <asm/mach_traps.h> #include <asm/alternative.h> #include <asm/fpu/xstate.h> #include <asm/vm86.h> #include <asm/umip.h> #include <asm/insn.h> #include <asm/insn-eval.h> #include <asm/vdso.h> #include <asm/tdx.h> #include <asm/cfi.h> #ifdef CONFIG_X86_64 #include <asm/x86_init.h> #else #include <asm/processor-flags.h> #include <asm/setup.h> #endif #include <asm/proto.h> DECLARE_BITMAP(system_vectors, NR_VECTORS); __always_inline int is_valid_bugaddr(unsigned long addr) { if (addr < TASK_SIZE_MAX) return 0; /* * We got #UD, if the text isn't readable we'd have gotten * a different exception. */ return *(unsigned short *)addr == INSN_UD2; } static nokprobe_inline int do_trap_no_signal(struct task_struct *tsk, int trapnr, const char *str, struct pt_regs *regs, long error_code) { if (v8086_mode(regs)) { /* * Traps 0, 1, 3, 4, and 5 should be forwarded to vm86. * On nmi (interrupt 2), do_trap should not be called. */ if (trapnr < X86_TRAP_UD) { if (!handle_vm86_trap((struct kernel_vm86_regs *) regs, error_code, trapnr)) return 0; } } else if (!user_mode(regs)) { if (fixup_exception(regs, trapnr, error_code, 0)) return 0; tsk->thread.error_code = error_code; tsk->thread.trap_nr = trapnr; die(str, regs, error_code); } else { if (fixup_vdso_exception(regs, trapnr, error_code, 0)) return 0; } /* * We want error_code and trap_nr set for userspace faults and * kernelspace faults which result in die(), but not * kernelspace faults which are fixed up. die() gives the * process no chance to handle the signal and notice the * kernel fault information, so that won't result in polluting * the information about previously queued, but not yet * delivered, faults. See also exc_general_protection below. */ tsk->thread.error_code = error_code; tsk->thread.trap_nr = trapnr; return -1; } static void show_signal(struct task_struct *tsk, int signr, const char *type, const char *desc, struct pt_regs *regs, long error_code) { if (show_unhandled_signals && unhandled_signal(tsk, signr) && printk_ratelimit()) { pr_info("%s[%d] %s%s ip:%lx sp:%lx error:%lx", tsk->comm, task_pid_nr(tsk), type, desc, regs->ip, regs->sp, error_code); print_vma_addr(KERN_CONT " in ", regs->ip); pr_cont("\n"); } } static void do_trap(int trapnr, int signr, char *str, struct pt_regs *regs, long error_code, int sicode, void __user *addr) { struct task_struct *tsk = current; if (!do_trap_no_signal(tsk, trapnr, str, regs, error_code)) return; show_signal(tsk, signr, "trap ", str, regs, error_code); if (!sicode) force_sig(signr); else force_sig_fault(signr, sicode, addr); } NOKPROBE_SYMBOL(do_trap); static void do_error_trap(struct pt_regs *regs, long error_code, char *str, unsigned long trapnr, int signr, int sicode, void __user *addr) { RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU"); if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, signr) != NOTIFY_STOP) { cond_local_irq_enable(regs); do_trap(trapnr, signr, str, regs, error_code, sicode, addr); cond_local_irq_disable(regs); } } /* * Posix requires to provide the address of the faulting instruction for * SIGILL (#UD) and SIGFPE (#DE) in the si_addr member of siginfo_t. * * This address is usually regs->ip, but when an uprobe moved the code out * of line then regs->ip points to the XOL code which would confuse * anything which analyzes the fault address vs. the unmodified binary. If * a trap happened in XOL code then uprobe maps regs->ip back to the * original instruction address. */ static __always_inline void __user *error_get_trap_addr(struct pt_regs *regs) { return (void __user *)uprobe_get_trap_addr(regs); } DEFINE_IDTENTRY(exc_divide_error) { do_error_trap(regs, 0, "divide error", X86_TRAP_DE, SIGFPE, FPE_INTDIV, error_get_trap_addr(regs)); } DEFINE_IDTENTRY(exc_overflow) { do_error_trap(regs, 0, "overflow", X86_TRAP_OF, SIGSEGV, 0, NULL); } #ifdef CONFIG_X86_F00F_BUG void handle_invalid_op(struct pt_regs *regs) #else static inline void handle_invalid_op(struct pt_regs *regs) #endif { do_error_trap(regs, 0, "invalid opcode", X86_TRAP_UD, SIGILL, ILL_ILLOPN, error_get_trap_addr(regs)); } static noinstr bool handle_bug(struct pt_regs *regs) { bool handled = false; /* * Normally @regs are unpoisoned by irqentry_enter(), but handle_bug() * is a rare case that uses @regs without passing them to * irqentry_enter(). */ kmsan_unpoison_entry_regs(regs); if (!is_valid_bugaddr(regs->ip)) return handled; /* * All lies, just get the WARN/BUG out. */ instrumentation_begin(); /* * Since we're emulating a CALL with exceptions, restore the interrupt * state to what it was at the exception site. */ if (regs->flags & X86_EFLAGS_IF) raw_local_irq_enable(); if (report_bug(regs->ip, regs) == BUG_TRAP_TYPE_WARN || handle_cfi_failure(regs) == BUG_TRAP_TYPE_WARN) { regs->ip += LEN_UD2; handled = true; } if (regs->flags & X86_EFLAGS_IF) raw_local_irq_disable(); instrumentation_end(); return handled; } DEFINE_IDTENTRY_RAW(exc_invalid_op) { irqentry_state_t state; /* * We use UD2 as a short encoding for 'CALL __WARN', as such * handle it before exception entry to avoid recursive WARN * in case exception entry is the one triggering WARNs. */ if (!user_mode(regs) && handle_bug(regs)) return; state = irqentry_enter(regs); instrumentation_begin(); handle_invalid_op(regs); instrumentation_end(); irqentry_exit(regs, state); } DEFINE_IDTENTRY(exc_coproc_segment_overrun) { do_error_trap(regs, 0, "coprocessor segment overrun", X86_TRAP_OLD_MF, SIGFPE, 0, NULL); } DEFINE_IDTENTRY_ERRORCODE(exc_invalid_tss) { do_error_trap(regs, error_code, "invalid TSS", X86_TRAP_TS, SIGSEGV, 0, NULL); } DEFINE_IDTENTRY_ERRORCODE(exc_segment_not_present) { do_error_trap(regs, error_code, "segment not present", X86_TRAP_NP, SIGBUS, 0, NULL); } DEFINE_IDTENTRY_ERRORCODE(exc_stack_segment) { do_error_trap(regs, error_code, "stack segment", X86_TRAP_SS, SIGBUS, 0, NULL); } DEFINE_IDTENTRY_ERRORCODE(exc_alignment_check) { char *str = "alignment check"; if (notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_AC, SIGBUS) == NOTIFY_STOP) return; if (!user_mode(regs)) die("Split lock detected\n", regs, error_code); local_irq_enable(); if (handle_user_split_lock(regs, error_code)) goto out; do_trap(X86_TRAP_AC, SIGBUS, "alignment check", regs, error_code, BUS_ADRALN, NULL); out: local_irq_disable(); } #ifdef CONFIG_VMAP_STACK __visible void __noreturn handle_stack_overflow(struct pt_regs *regs, unsigned long fault_address, struct stack_info *info) { const char *name = stack_type_name(info->type); printk(KERN_EMERG "BUG: %s stack guard page was hit at %p (stack is %p..%p)\n", name, (void *)fault_address, info->begin, info->end); die("stack guard page", regs, 0); /* Be absolutely certain we don't return. */ panic("%s stack guard hit", name); } #endif /* * Runs on an IST stack for x86_64 and on a special task stack for x86_32. * * On x86_64, this is more or less a normal kernel entry. Notwithstanding the * SDM's warnings about double faults being unrecoverable, returning works as * expected. Presumably what the SDM actually means is that the CPU may get * the register state wrong on entry, so returning could be a bad idea. * * Various CPU engineers have promised that double faults due to an IRET fault * while the stack is read-only are, in fact, recoverable. * * On x86_32, this is entered through a task gate, and regs are synthesized * from the TSS. Returning is, in principle, okay, but changes to regs will * be lost. If, for some reason, we need to return to a context with modified * regs, the shim code could be adjusted to synchronize the registers. * * The 32bit #DF shim provides CR2 already as an argument. On 64bit it needs * to be read before doing anything else. */ DEFINE_IDTENTRY_DF(exc_double_fault) { static const char str[] = "double fault"; struct task_struct *tsk = current; #ifdef CONFIG_VMAP_STACK unsigned long address = read_cr2(); struct stack_info info; #endif #ifdef CONFIG_X86_ESPFIX64 extern unsigned char native_irq_return_iret[]; /* * If IRET takes a non-IST fault on the espfix64 stack, then we * end up promoting it to a doublefault. In that case, take * advantage of the fact that we're not using the normal (TSS.sp0) * stack right now. We can write a fake #GP(0) frame at TSS.sp0 * and then modify our own IRET frame so that, when we return, * we land directly at the #GP(0) vector with the stack already * set up according to its expectations. * * The net result is that our #GP handler will think that we * entered from usermode with the bad user context. * * No need for nmi_enter() here because we don't use RCU. */ if (((long)regs->sp >> P4D_SHIFT) == ESPFIX_PGD_ENTRY && regs->cs == __KERNEL_CS && regs->ip == (unsigned long)native_irq_return_iret) { struct pt_regs *gpregs = (struct pt_regs *)this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1; unsigned long *p = (unsigned long *)regs->sp; /* * regs->sp points to the failing IRET frame on the * ESPFIX64 stack. Copy it to the entry stack. This fills * in gpregs->ss through gpregs->ip. * */ gpregs->ip = p[0]; gpregs->cs = p[1]; gpregs->flags = p[2]; gpregs->sp = p[3]; gpregs->ss = p[4]; gpregs->orig_ax = 0; /* Missing (lost) #GP error code */ /* * Adjust our frame so that we return straight to the #GP * vector with the expected RSP value. This is safe because * we won't enable interrupts or schedule before we invoke * general_protection, so nothing will clobber the stack * frame we just set up. * * We will enter general_protection with kernel GSBASE, * which is what the stub expects, given that the faulting * RIP will be the IRET instruction. */ regs->ip = (unsigned long)asm_exc_general_protection; regs->sp = (unsigned long)&gpregs->orig_ax; return; } #endif irqentry_nmi_enter(regs); instrumentation_begin(); notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_DF, SIGSEGV); tsk->thread.error_code = error_code; tsk->thread.trap_nr = X86_TRAP_DF; #ifdef CONFIG_VMAP_STACK /* * If we overflow the stack into a guard page, the CPU will fail * to deliver #PF and will send #DF instead. Similarly, if we * take any non-IST exception while too close to the bottom of * the stack, the processor will get a page fault while * delivering the exception and will generate a double fault. * * According to the SDM (footnote in 6.15 under "Interrupt 14 - * Page-Fault Exception (#PF): * * Processors update CR2 whenever a page fault is detected. If a * second page fault occurs while an earlier page fault is being * delivered, the faulting linear address of the second fault will * overwrite the contents of CR2 (replacing the previous * address). These updates to CR2 occur even if the page fault * results in a double fault or occurs during the delivery of a * double fault. * * The logic below has a small possibility of incorrectly diagnosing * some errors as stack overflows. For example, if the IDT or GDT * gets corrupted such that #GP delivery fails due to a bad descriptor * causing #GP and we hit this condition while CR2 coincidentally * points to the stack guard page, we'll think we overflowed the * stack. Given that we're going to panic one way or another * if this happens, this isn't necessarily worth fixing. * * If necessary, we could improve the test by only diagnosing * a stack overflow if the saved RSP points within 47 bytes of * the bottom of the stack: if RSP == tsk_stack + 48 and we * take an exception, the stack is already aligned and there * will be enough room SS, RSP, RFLAGS, CS, RIP, and a * possible error code, so a stack overflow would *not* double * fault. With any less space left, exception delivery could * fail, and, as a practical matter, we've overflowed the * stack even if the actual trigger for the double fault was * something else. */ if (get_stack_guard_info((void *)address, &info)) handle_stack_overflow(regs, address, &info); #endif pr_emerg("PANIC: double fault, error_code: 0x%lx\n", error_code); die("double fault", regs, error_code); panic("Machine halted."); instrumentation_end(); } DEFINE_IDTENTRY(exc_bounds) { if (notify_die(DIE_TRAP, "bounds", regs, 0, X86_TRAP_BR, SIGSEGV) == NOTIFY_STOP) return; cond_local_irq_enable(regs); if (!user_mode(regs)) die("bounds", regs, 0); do_trap(X86_TRAP_BR, SIGSEGV, "bounds", regs, 0, 0, NULL); cond_local_irq_disable(regs); } enum kernel_gp_hint { GP_NO_HINT, GP_NON_CANONICAL, GP_CANONICAL }; /* * When an uncaught #GP occurs, try to determine the memory address accessed by * the instruction and return that address to the caller. Also, try to figure * out whether any part of the access to that address was non-canonical. */ static enum kernel_gp_hint get_kernel_gp_address(struct pt_regs *regs, unsigned long *addr) { u8 insn_buf[MAX_INSN_SIZE]; struct insn insn; int ret; if (copy_from_kernel_nofault(insn_buf, (void *)regs->ip, MAX_INSN_SIZE)) return GP_NO_HINT; ret = insn_decode_kernel(&insn, insn_buf); if (ret < 0) return GP_NO_HINT; *addr = (unsigned long)insn_get_addr_ref(&insn, regs); if (*addr == -1UL) return GP_NO_HINT; #ifdef CONFIG_X86_64 /* * Check that: * - the operand is not in the kernel half * - the last byte of the operand is not in the user canonical half */ if (*addr < ~__VIRTUAL_MASK && *addr + insn.opnd_bytes - 1 > __VIRTUAL_MASK) return GP_NON_CANONICAL; #endif return GP_CANONICAL; } #define GPFSTR "general protection fault" static bool fixup_iopl_exception(struct pt_regs *regs) { struct thread_struct *t = &current->thread; unsigned char byte; unsigned long ip; if (!IS_ENABLED(CONFIG_X86_IOPL_IOPERM) || t->iopl_emul != 3) return false; if (insn_get_effective_ip(regs, &ip)) return false; if (get_user(byte, (const char __user *)ip)) return false; if (byte != 0xfa && byte != 0xfb) return false; if (!t->iopl_warn && printk_ratelimit()) { pr_err("%s[%d] attempts to use CLI/STI, pretending it's a NOP, ip:%lx", current->comm, task_pid_nr(current), ip); print_vma_addr(KERN_CONT " in ", ip); pr_cont("\n"); t->iopl_warn = 1; } regs->ip += 1; return true; } /* * The unprivileged ENQCMD instruction generates #GPs if the * IA32_PASID MSR has not been populated. If possible, populate * the MSR from a PASID previously allocated to the mm. */ static bool try_fixup_enqcmd_gp(void) { #ifdef CONFIG_IOMMU_SVA u32 pasid; /* * MSR_IA32_PASID is managed using XSAVE. Directly * writing to the MSR is only possible when fpregs * are valid and the fpstate is not. This is * guaranteed when handling a userspace exception * in *before* interrupts are re-enabled. */ lockdep_assert_irqs_disabled(); /* * Hardware without ENQCMD will not generate * #GPs that can be fixed up here. */ if (!cpu_feature_enabled(X86_FEATURE_ENQCMD)) return false; /* * If the mm has not been allocated a * PASID, the #GP can not be fixed up. */ if (!mm_valid_pasid(current->mm)) return false; pasid = current->mm->pasid; /* * Did this thread already have its PASID activated? * If so, the #GP must be from something else. */ if (current->pasid_activated) return false; wrmsrl(MSR_IA32_PASID, pasid | MSR_IA32_PASID_VALID); current->pasid_activated = 1; return true; #else return false; #endif } static bool gp_try_fixup_and_notify(struct pt_regs *regs, int trapnr, unsigned long error_code, const char *str, unsigned long address) { if (fixup_exception(regs, trapnr, error_code, address)) return true; current->thread.error_code = error_code; current->thread.trap_nr = trapnr; /* * To be potentially processing a kprobe fault and to trust the result * from kprobe_running(), we have to be non-preemptible. */ if (!preemptible() && kprobe_running() && kprobe_fault_handler(regs, trapnr)) return true; return notify_die(DIE_GPF, str, regs, error_code, trapnr, SIGSEGV) == NOTIFY_STOP; } static void gp_user_force_sig_segv(struct pt_regs *regs, int trapnr, unsigned long error_code, const char *str) { current->thread.error_code = error_code; current->thread.trap_nr = trapnr; show_signal(current, SIGSEGV, "", str, regs, error_code); force_sig(SIGSEGV); } DEFINE_IDTENTRY_ERRORCODE(exc_general_protection) { char desc[sizeof(GPFSTR) + 50 + 2*sizeof(unsigned long) + 1] = GPFSTR; enum kernel_gp_hint hint = GP_NO_HINT; unsigned long gp_addr; if (user_mode(regs) && try_fixup_enqcmd_gp()) return; cond_local_irq_enable(regs); if (static_cpu_has(X86_FEATURE_UMIP)) { if (user_mode(regs) && fixup_umip_exception(regs)) goto exit; } if (v8086_mode(regs)) { local_irq_enable(); handle_vm86_fault((struct kernel_vm86_regs *) regs, error_code); local_irq_disable(); return; } if (user_mode(regs)) { if (fixup_iopl_exception(regs)) goto exit; if (fixup_vdso_exception(regs, X86_TRAP_GP, error_code, 0)) goto exit; gp_user_force_sig_segv(regs, X86_TRAP_GP, error_code, desc); goto exit; } if (gp_try_fixup_and_notify(regs, X86_TRAP_GP, error_code, desc, 0)) goto exit; if (error_code) snprintf(desc, sizeof(desc), "segment-related " GPFSTR); else hint = get_kernel_gp_address(regs, &gp_addr); if (hint != GP_NO_HINT) snprintf(desc, sizeof(desc), GPFSTR ", %s 0x%lx", (hint == GP_NON_CANONICAL) ? "probably for non-canonical address" : "maybe for address", gp_addr); /* * KASAN is interested only in the non-canonical case, clear it * otherwise. */ if (hint != GP_NON_CANONICAL) gp_addr = 0; die_addr(desc, regs, error_code, gp_addr); exit: cond_local_irq_disable(regs); } static bool do_int3(struct pt_regs *regs) { int res; #ifdef CONFIG_KGDB_LOW_LEVEL_TRAP if (kgdb_ll_trap(DIE_INT3, "int3", regs, 0, X86_TRAP_BP, SIGTRAP) == NOTIFY_STOP) return true; #endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */ #ifdef CONFIG_KPROBES if (kprobe_int3_handler(regs)) return true; #endif res = notify_die(DIE_INT3, "int3", regs, 0, X86_TRAP_BP, SIGTRAP); return res == NOTIFY_STOP; } NOKPROBE_SYMBOL(do_int3); static void do_int3_user(struct pt_regs *regs) { if (do_int3(regs)) return; cond_local_irq_enable(regs); do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, 0, 0, NULL); cond_local_irq_disable(regs); } DEFINE_IDTENTRY_RAW(exc_int3) { /* * poke_int3_handler() is completely self contained code; it does (and * must) *NOT* call out to anything, lest it hits upon yet another * INT3. */ if (poke_int3_handler(regs)) return; /* * irqentry_enter_from_user_mode() uses static_branch_{,un}likely() * and therefore can trigger INT3, hence poke_int3_handler() must * be done before. If the entry came from kernel mode, then use * nmi_enter() because the INT3 could have been hit in any context * including NMI. */ if (user_mode(regs)) { irqentry_enter_from_user_mode(regs); instrumentation_begin(); do_int3_user(regs); instrumentation_end(); irqentry_exit_to_user_mode(regs); } else { irqentry_state_t irq_state = irqentry_nmi_enter(regs); instrumentation_begin(); if (!do_int3(regs)) die("int3", regs, 0); instrumentation_end(); irqentry_nmi_exit(regs, irq_state); } } #ifdef CONFIG_X86_64 /* * Help handler running on a per-cpu (IST or entry trampoline) stack * to switch to the normal thread stack if the interrupted code was in * user mode. The actual stack switch is done in entry_64.S */ asmlinkage __visible noinstr struct pt_regs *sync_regs(struct pt_regs *eregs) { struct pt_regs *regs = (struct pt_regs *)this_cpu_read(pcpu_hot.top_of_stack) - 1; if (regs != eregs) *regs = *eregs; return regs; } #ifdef CONFIG_AMD_MEM_ENCRYPT asmlinkage __visible noinstr struct pt_regs *vc_switch_off_ist(struct pt_regs *regs) { unsigned long sp, *stack; struct stack_info info; struct pt_regs *regs_ret; /* * In the SYSCALL entry path the RSP value comes from user-space - don't * trust it and switch to the current kernel stack */ if (ip_within_syscall_gap(regs)) { sp = this_cpu_read(pcpu_hot.top_of_stack); goto sync; } /* * From here on the RSP value is trusted. Now check whether entry * happened from a safe stack. Not safe are the entry or unknown stacks, * use the fall-back stack instead in this case. */ sp = regs->sp; stack = (unsigned long *)sp; if (!get_stack_info_noinstr(stack, current, &info) || info.type == STACK_TYPE_ENTRY || info.type > STACK_TYPE_EXCEPTION_LAST) sp = __this_cpu_ist_top_va(VC2); sync: /* * Found a safe stack - switch to it as if the entry didn't happen via * IST stack. The code below only copies pt_regs, the real switch happens * in assembly code. */ sp = ALIGN_DOWN(sp, 8) - sizeof(*regs_ret); regs_ret = (struct pt_regs *)sp; *regs_ret = *regs; return regs_ret; } #endif asmlinkage __visible noinstr struct pt_regs *fixup_bad_iret(struct pt_regs *bad_regs) { struct pt_regs tmp, *new_stack; /* * This is called from entry_64.S early in handling a fault * caused by a bad iret to user mode. To handle the fault * correctly, we want to move our stack frame to where it would * be had we entered directly on the entry stack (rather than * just below the IRET frame) and we want to pretend that the * exception came from the IRET target. */ new_stack = (struct pt_regs *)__this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1; /* Copy the IRET target to the temporary storage. */ __memcpy(&tmp.ip, (void *)bad_regs->sp, 5*8); /* Copy the remainder of the stack from the current stack. */ __memcpy(&tmp, bad_regs, offsetof(struct pt_regs, ip)); /* Update the entry stack */ __memcpy(new_stack, &tmp, sizeof(tmp)); BUG_ON(!user_mode(new_stack)); return new_stack; } #endif static bool is_sysenter_singlestep(struct pt_regs *regs) { /* * We don't try for precision here. If we're anywhere in the region of * code that can be single-stepped in the SYSENTER entry path, then * assume that this is a useless single-step trap due to SYSENTER * being invoked with TF set. (We don't know in advance exactly * which instructions will be hit because BTF could plausibly * be set.) */ #ifdef CONFIG_X86_32 return (regs->ip - (unsigned long)__begin_SYSENTER_singlestep_region) < (unsigned long)__end_SYSENTER_singlestep_region - (unsigned long)__begin_SYSENTER_singlestep_region; #elif defined(CONFIG_IA32_EMULATION) return (regs->ip - (unsigned long)entry_SYSENTER_compat) < (unsigned long)__end_entry_SYSENTER_compat - (unsigned long)entry_SYSENTER_compat; #else return false; #endif } static __always_inline unsigned long debug_read_clear_dr6(void) { unsigned long dr6; /* * The Intel SDM says: * * Certain debug exceptions may clear bits 0-3. The remaining * contents of the DR6 register are never cleared by the * processor. To avoid confusion in identifying debug * exceptions, debug handlers should clear the register before * returning to the interrupted task. * * Keep it simple: clear DR6 immediately. */ get_debugreg(dr6, 6); set_debugreg(DR6_RESERVED, 6); dr6 ^= DR6_RESERVED; /* Flip to positive polarity */ return dr6; } /* * Our handling of the processor debug registers is non-trivial. * We do not clear them on entry and exit from the kernel. Therefore * it is possible to get a watchpoint trap here from inside the kernel. * However, the code in ./ptrace.c has ensured that the user can * only set watchpoints on userspace addresses. Therefore the in-kernel * watchpoint trap can only occur in code which is reading/writing * from user space. Such code must not hold kernel locks (since it * can equally take a page fault), therefore it is safe to call * force_sig_info even though that claims and releases locks. * * Code in ./signal.c ensures that the debug control register * is restored before we deliver any signal, and therefore that * user code runs with the correct debug control register even though * we clear it here. * * Being careful here means that we don't have to be as careful in a * lot of more complicated places (task switching can be a bit lazy * about restoring all the debug state, and ptrace doesn't have to * find every occurrence of the TF bit that could be saved away even * by user code) * * May run on IST stack. */ static bool notify_debug(struct pt_regs *regs, unsigned long *dr6) { /* * Notifiers will clear bits in @dr6 to indicate the event has been * consumed - hw_breakpoint_handler(), single_stop_cont(). * * Notifiers will set bits in @virtual_dr6 to indicate the desire * for signals - ptrace_triggered(), kgdb_hw_overflow_handler(). */ if (notify_die(DIE_DEBUG, "debug", regs, (long)dr6, 0, SIGTRAP) == NOTIFY_STOP) return true; return false; } static __always_inline void exc_debug_kernel(struct pt_regs *regs, unsigned long dr6) { /* * Disable breakpoints during exception handling; recursive exceptions * are exceedingly 'fun'. * * Since this function is NOKPROBE, and that also applies to * HW_BREAKPOINT_X, we can't hit a breakpoint before this (XXX except a * HW_BREAKPOINT_W on our stack) * * Entry text is excluded for HW_BP_X and cpu_entry_area, which * includes the entry stack is excluded for everything. */ unsigned long dr7 = local_db_save(); irqentry_state_t irq_state = irqentry_nmi_enter(regs); instrumentation_begin(); /* * If something gets miswired and we end up here for a user mode * #DB, we will malfunction. */ WARN_ON_ONCE(user_mode(regs)); if (test_thread_flag(TIF_BLOCKSTEP)) { /* * The SDM says "The processor clears the BTF flag when it * generates a debug exception." but PTRACE_BLOCKSTEP requested * it for userspace, but we just took a kernel #DB, so re-set * BTF. */ unsigned long debugctl; rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); debugctl |= DEBUGCTLMSR_BTF; wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); } /* * Catch SYSENTER with TF set and clear DR_STEP. If this hit a * watchpoint at the same time then that will still be handled. */ if ((dr6 & DR_STEP) && is_sysenter_singlestep(regs)) dr6 &= ~DR_STEP; /* * The kernel doesn't use INT1 */ if (!dr6) goto out; if (notify_debug(regs, &dr6)) goto out; /* * The kernel doesn't use TF single-step outside of: * * - Kprobes, consumed through kprobe_debug_handler() * - KGDB, consumed through notify_debug() * * So if we get here with DR_STEP set, something is wonky. * * A known way to trigger this is through QEMU's GDB stub, * which leaks #DB into the guest and causes IST recursion. */ if (WARN_ON_ONCE(dr6 & DR_STEP)) regs->flags &= ~X86_EFLAGS_TF; out: instrumentation_end(); irqentry_nmi_exit(regs, irq_state); local_db_restore(dr7); } static __always_inline void exc_debug_user(struct pt_regs *regs, unsigned long dr6) { bool icebp; /* * If something gets miswired and we end up here for a kernel mode * #DB, we will malfunction. */ WARN_ON_ONCE(!user_mode(regs)); /* * NB: We can't easily clear DR7 here because * irqentry_exit_to_usermode() can invoke ptrace, schedule, access * user memory, etc. This means that a recursive #DB is possible. If * this happens, that #DB will hit exc_debug_kernel() and clear DR7. * Since we're not on the IST stack right now, everything will be * fine. */ irqentry_enter_from_user_mode(regs); instrumentation_begin(); /* * Start the virtual/ptrace DR6 value with just the DR_STEP mask * of the real DR6. ptrace_triggered() will set the DR_TRAPn bits. * * Userspace expects DR_STEP to be visible in ptrace_get_debugreg(6) * even if it is not the result of PTRACE_SINGLESTEP. */ current->thread.virtual_dr6 = (dr6 & DR_STEP); /* * The SDM says "The processor clears the BTF flag when it * generates a debug exception." Clear TIF_BLOCKSTEP to keep * TIF_BLOCKSTEP in sync with the hardware BTF flag. */ clear_thread_flag(TIF_BLOCKSTEP); /* * If dr6 has no reason to give us about the origin of this trap, * then it's very likely the result of an icebp/int01 trap. * User wants a sigtrap for that. */ icebp = !dr6; if (notify_debug(regs, &dr6)) goto out; /* It's safe to allow irq's after DR6 has been saved */ local_irq_enable(); if (v8086_mode(regs)) { handle_vm86_trap((struct kernel_vm86_regs *)regs, 0, X86_TRAP_DB); goto out_irq; } /* #DB for bus lock can only be triggered from userspace. */ if (dr6 & DR_BUS_LOCK) handle_bus_lock(regs); /* Add the virtual_dr6 bits for signals. */ dr6 |= current->thread.virtual_dr6; if (dr6 & (DR_STEP | DR_TRAP_BITS) || icebp) send_sigtrap(regs, 0, get_si_code(dr6)); out_irq: local_irq_disable(); out: instrumentation_end(); irqentry_exit_to_user_mode(regs); } #ifdef CONFIG_X86_64 /* IST stack entry */ DEFINE_IDTENTRY_DEBUG(exc_debug) { exc_debug_kernel(regs, debug_read_clear_dr6()); } /* User entry, runs on regular task stack */ DEFINE_IDTENTRY_DEBUG_USER(exc_debug) { exc_debug_user(regs, debug_read_clear_dr6()); } #else /* 32 bit does not have separate entry points. */ DEFINE_IDTENTRY_RAW(exc_debug) { unsigned long dr6 = debug_read_clear_dr6(); if (user_mode(regs)) exc_debug_user(regs, dr6); else exc_debug_kernel(regs, dr6); } #endif /* * Note that we play around with the 'TS' bit in an attempt to get * the correct behaviour even in the presence of the asynchronous * IRQ13 behaviour */ static void math_error(struct pt_regs *regs, int trapnr) { struct task_struct *task = current; struct fpu *fpu = &task->thread.fpu; int si_code; char *str = (trapnr == X86_TRAP_MF) ? "fpu exception" : "simd exception"; cond_local_irq_enable(regs); if (!user_mode(regs)) { if (fixup_exception(regs, trapnr, 0, 0)) goto exit; task->thread.error_code = 0; task->thread.trap_nr = trapnr; if (notify_die(DIE_TRAP, str, regs, 0, trapnr, SIGFPE) != NOTIFY_STOP) die(str, regs, 0); goto exit; } /* * Synchronize the FPU register state to the memory register state * if necessary. This allows the exception handler to inspect it. */ fpu_sync_fpstate(fpu); task->thread.trap_nr = trapnr; task->thread.error_code = 0; si_code = fpu__exception_code(fpu, trapnr); /* Retry when we get spurious exceptions: */ if (!si_code) goto exit; if (fixup_vdso_exception(regs, trapnr, 0, 0)) goto exit; force_sig_fault(SIGFPE, si_code, (void __user *)uprobe_get_trap_addr(regs)); exit: cond_local_irq_disable(regs); } DEFINE_IDTENTRY(exc_coprocessor_error) { math_error(regs, X86_TRAP_MF); } DEFINE_IDTENTRY(exc_simd_coprocessor_error) { if (IS_ENABLED(CONFIG_X86_INVD_BUG)) { /* AMD 486 bug: INVD in CPL 0 raises #XF instead of #GP */ if (!static_cpu_has(X86_FEATURE_XMM)) { __exc_general_protection(regs, 0); return; } } math_error(regs, X86_TRAP_XF); } DEFINE_IDTENTRY(exc_spurious_interrupt_bug) { /* * This addresses a Pentium Pro Erratum: * * PROBLEM: If the APIC subsystem is configured in mixed mode with * Virtual Wire mode implemented through the local APIC, an * interrupt vector of 0Fh (Intel reserved encoding) may be * generated by the local APIC (Int 15). This vector may be * generated upon receipt of a spurious interrupt (an interrupt * which is removed before the system receives the INTA sequence) * instead of the programmed 8259 spurious interrupt vector. * * IMPLICATION: The spurious interrupt vector programmed in the * 8259 is normally handled by an operating system's spurious * interrupt handler. However, a vector of 0Fh is unknown to some * operating systems, which would crash if this erratum occurred. * * In theory this could be limited to 32bit, but the handler is not * hurting and who knows which other CPUs suffer from this. */ } static bool handle_xfd_event(struct pt_regs *regs) { u64 xfd_err; int err; if (!IS_ENABLED(CONFIG_X86_64) || !cpu_feature_enabled(X86_FEATURE_XFD)) return false; rdmsrl(MSR_IA32_XFD_ERR, xfd_err); if (!xfd_err) return false; wrmsrl(MSR_IA32_XFD_ERR, 0); /* Die if that happens in kernel space */ if (WARN_ON(!user_mode(regs))) return false; local_irq_enable(); err = xfd_enable_feature(xfd_err); switch (err) { case -EPERM: force_sig_fault(SIGILL, ILL_ILLOPC, error_get_trap_addr(regs)); break; case -EFAULT: force_sig(SIGSEGV); break; } local_irq_disable(); return true; } DEFINE_IDTENTRY(exc_device_not_available) { unsigned long cr0 = read_cr0(); if (handle_xfd_event(regs)) return; #ifdef CONFIG_MATH_EMULATION if (!boot_cpu_has(X86_FEATURE_FPU) && (cr0 & X86_CR0_EM)) { struct math_emu_info info = { }; cond_local_irq_enable(regs); info.regs = regs; math_emulate(&info); cond_local_irq_disable(regs); return; } #endif /* This should not happen. */ if (WARN(cr0 & X86_CR0_TS, "CR0.TS was set")) { /* Try to fix it up and carry on. */ write_cr0(cr0 & ~X86_CR0_TS); } else { /* * Something terrible happened, and we're better off trying * to kill the task than getting stuck in a never-ending * loop of #NM faults. */ die("unexpected #NM exception", regs, 0); } } #ifdef CONFIG_INTEL_TDX_GUEST #define VE_FAULT_STR "VE fault" static void ve_raise_fault(struct pt_regs *regs, long error_code, unsigned long address) { if (user_mode(regs)) { gp_user_force_sig_segv(regs, X86_TRAP_VE, error_code, VE_FAULT_STR); return; } if (gp_try_fixup_and_notify(regs, X86_TRAP_VE, error_code, VE_FAULT_STR, address)) { return; } die_addr(VE_FAULT_STR, regs, error_code, address); } /* * Virtualization Exceptions (#VE) are delivered to TDX guests due to * specific guest actions which may happen in either user space or the * kernel: * * * Specific instructions (WBINVD, for example) * * Specific MSR accesses * * Specific CPUID leaf accesses * * Access to specific guest physical addresses * * In the settings that Linux will run in, virtualization exceptions are * never generated on accesses to normal, TD-private memory that has been * accepted (by BIOS or with tdx_enc_status_changed()). * * Syscall entry code has a critical window where the kernel stack is not * yet set up. Any exception in this window leads to hard to debug issues * and can be exploited for privilege escalation. Exceptions in the NMI * entry code also cause issues. Returning from the exception handler with * IRET will re-enable NMIs and nested NMI will corrupt the NMI stack. * * For these reasons, the kernel avoids #VEs during the syscall gap and * the NMI entry code. Entry code paths do not access TD-shared memory, * MMIO regions, use #VE triggering MSRs, instructions, or CPUID leaves * that might generate #VE. VMM can remove memory from TD at any point, * but access to unaccepted (or missing) private memory leads to VM * termination, not to #VE. * * Similarly to page faults and breakpoints, #VEs are allowed in NMI * handlers once the kernel is ready to deal with nested NMIs. * * During #VE delivery, all interrupts, including NMIs, are blocked until * TDGETVEINFO is called. It prevents #VE nesting until the kernel reads * the VE info. * * If a guest kernel action which would normally cause a #VE occurs in * the interrupt-disabled region before TDGETVEINFO, a #DF (fault * exception) is delivered to the guest which will result in an oops. * * The entry code has been audited carefully for following these expectations. * Changes in the entry code have to be audited for correctness vs. this * aspect. Similarly to #PF, #VE in these places will expose kernel to * privilege escalation or may lead to random crashes. */ DEFINE_IDTENTRY(exc_virtualization_exception) { struct ve_info ve; /* * NMIs/Machine-checks/Interrupts will be in a disabled state * till TDGETVEINFO TDCALL is executed. This ensures that VE * info cannot be overwritten by a nested #VE. */ tdx_get_ve_info(&ve); cond_local_irq_enable(regs); /* * If tdx_handle_virt_exception() could not process * it successfully, treat it as #GP(0) and handle it. */ if (!tdx_handle_virt_exception(regs, &ve)) ve_raise_fault(regs, 0, ve.gla); cond_local_irq_disable(regs); } #endif #ifdef CONFIG_X86_32 DEFINE_IDTENTRY_SW(iret_error) { local_irq_enable(); if (notify_die(DIE_TRAP, "iret exception", regs, 0, X86_TRAP_IRET, SIGILL) != NOTIFY_STOP) { do_trap(X86_TRAP_IRET, SIGILL, "iret exception", regs, 0, ILL_BADSTK, (void __user *)NULL); } local_irq_disable(); } #endif void __init trap_init(void) { /* Init cpu_entry_area before IST entries are set up */ setup_cpu_entry_areas(); /* Init GHCB memory pages when running as an SEV-ES guest */ sev_es_init_vc_handling(); /* Initialize TSS before setting up traps so ISTs work */ cpu_init_exception_handling(); /* Setup traps as cpu_init() might #GP */ idt_setup_traps(); cpu_init(); }
linux-master
arch/x86/kernel/traps.c
// SPDX-License-Identifier: GPL-2.0 /* * Generate definitions needed by assembly language modules. * This code generates raw asm output which is post-processed to extract * and format the required data. */ #define COMPILE_OFFSETS #include <linux/crypto.h> #include <crypto/aria.h> #include <linux/sched.h> #include <linux/stddef.h> #include <linux/hardirq.h> #include <linux/suspend.h> #include <linux/kbuild.h> #include <asm/processor.h> #include <asm/thread_info.h> #include <asm/sigframe.h> #include <asm/bootparam.h> #include <asm/suspend.h> #include <asm/tlbflush.h> #include <asm/tdx.h> #ifdef CONFIG_XEN #include <xen/interface/xen.h> #endif #ifdef CONFIG_X86_32 # include "asm-offsets_32.c" #else # include "asm-offsets_64.c" #endif static void __used common(void) { BLANK(); OFFSET(TASK_threadsp, task_struct, thread.sp); #ifdef CONFIG_STACKPROTECTOR OFFSET(TASK_stack_canary, task_struct, stack_canary); #endif BLANK(); OFFSET(pbe_address, pbe, address); OFFSET(pbe_orig_address, pbe, orig_address); OFFSET(pbe_next, pbe, next); #if defined(CONFIG_X86_32) || defined(CONFIG_IA32_EMULATION) BLANK(); OFFSET(IA32_SIGCONTEXT_ax, sigcontext_32, ax); OFFSET(IA32_SIGCONTEXT_bx, sigcontext_32, bx); OFFSET(IA32_SIGCONTEXT_cx, sigcontext_32, cx); OFFSET(IA32_SIGCONTEXT_dx, sigcontext_32, dx); OFFSET(IA32_SIGCONTEXT_si, sigcontext_32, si); OFFSET(IA32_SIGCONTEXT_di, sigcontext_32, di); OFFSET(IA32_SIGCONTEXT_bp, sigcontext_32, bp); OFFSET(IA32_SIGCONTEXT_sp, sigcontext_32, sp); OFFSET(IA32_SIGCONTEXT_ip, sigcontext_32, ip); BLANK(); OFFSET(IA32_RT_SIGFRAME_sigcontext, rt_sigframe_ia32, uc.uc_mcontext); #endif #ifdef CONFIG_XEN BLANK(); OFFSET(XEN_vcpu_info_mask, vcpu_info, evtchn_upcall_mask); OFFSET(XEN_vcpu_info_pending, vcpu_info, evtchn_upcall_pending); OFFSET(XEN_vcpu_info_arch_cr2, vcpu_info, arch.cr2); #endif BLANK(); OFFSET(TDX_MODULE_rcx, tdx_module_output, rcx); OFFSET(TDX_MODULE_rdx, tdx_module_output, rdx); OFFSET(TDX_MODULE_r8, tdx_module_output, r8); OFFSET(TDX_MODULE_r9, tdx_module_output, r9); OFFSET(TDX_MODULE_r10, tdx_module_output, r10); OFFSET(TDX_MODULE_r11, tdx_module_output, r11); BLANK(); OFFSET(TDX_HYPERCALL_r8, tdx_hypercall_args, r8); OFFSET(TDX_HYPERCALL_r9, tdx_hypercall_args, r9); OFFSET(TDX_HYPERCALL_r10, tdx_hypercall_args, r10); OFFSET(TDX_HYPERCALL_r11, tdx_hypercall_args, r11); OFFSET(TDX_HYPERCALL_r12, tdx_hypercall_args, r12); OFFSET(TDX_HYPERCALL_r13, tdx_hypercall_args, r13); OFFSET(TDX_HYPERCALL_r14, tdx_hypercall_args, r14); OFFSET(TDX_HYPERCALL_r15, tdx_hypercall_args, r15); OFFSET(TDX_HYPERCALL_rdi, tdx_hypercall_args, rdi); OFFSET(TDX_HYPERCALL_rsi, tdx_hypercall_args, rsi); OFFSET(TDX_HYPERCALL_rbx, tdx_hypercall_args, rbx); OFFSET(TDX_HYPERCALL_rdx, tdx_hypercall_args, rdx); BLANK(); OFFSET(BP_scratch, boot_params, scratch); OFFSET(BP_secure_boot, boot_params, secure_boot); OFFSET(BP_loadflags, boot_params, hdr.loadflags); OFFSET(BP_hardware_subarch, boot_params, hdr.hardware_subarch); OFFSET(BP_version, boot_params, hdr.version); OFFSET(BP_kernel_alignment, boot_params, hdr.kernel_alignment); OFFSET(BP_init_size, boot_params, hdr.init_size); OFFSET(BP_pref_address, boot_params, hdr.pref_address); BLANK(); DEFINE(PTREGS_SIZE, sizeof(struct pt_regs)); /* TLB state for the entry code */ OFFSET(TLB_STATE_user_pcid_flush_mask, tlb_state, user_pcid_flush_mask); /* Layout info for cpu_entry_area */ OFFSET(CPU_ENTRY_AREA_entry_stack, cpu_entry_area, entry_stack_page); DEFINE(SIZEOF_entry_stack, sizeof(struct entry_stack)); DEFINE(MASK_entry_stack, (~(sizeof(struct entry_stack) - 1))); /* Offset for fields in tss_struct */ OFFSET(TSS_sp0, tss_struct, x86_tss.sp0); OFFSET(TSS_sp1, tss_struct, x86_tss.sp1); OFFSET(TSS_sp2, tss_struct, x86_tss.sp2); OFFSET(X86_top_of_stack, pcpu_hot, top_of_stack); OFFSET(X86_current_task, pcpu_hot, current_task); #ifdef CONFIG_CALL_DEPTH_TRACKING OFFSET(X86_call_depth, pcpu_hot, call_depth); #endif #if IS_ENABLED(CONFIG_CRYPTO_ARIA_AESNI_AVX_X86_64) /* Offset for fields in aria_ctx */ BLANK(); OFFSET(ARIA_CTX_enc_key, aria_ctx, enc_key); OFFSET(ARIA_CTX_dec_key, aria_ctx, dec_key); OFFSET(ARIA_CTX_rounds, aria_ctx, rounds); #endif }
linux-master
arch/x86/kernel/asm-offsets.c
// SPDX-License-Identifier: GPL-2.0 /* * check TSC synchronization. * * Copyright (C) 2006, Red Hat, Inc., Ingo Molnar * * We check whether all boot CPUs have their TSC's synchronized, * print a warning if not and turn off the TSC clock-source. * * The warp-check is point-to-point between two CPUs, the CPU * initiating the bootup is the 'source CPU', the freshly booting * CPU is the 'target CPU'. * * Only two CPUs may participate - they can enter in any order. * ( The serial nature of the boot logic and the CPU hotplug lock * protects against more than 2 CPUs entering this code. ) */ #include <linux/topology.h> #include <linux/spinlock.h> #include <linux/kernel.h> #include <linux/smp.h> #include <linux/nmi.h> #include <asm/tsc.h> struct tsc_adjust { s64 bootval; s64 adjusted; unsigned long nextcheck; bool warned; }; static DEFINE_PER_CPU(struct tsc_adjust, tsc_adjust); static struct timer_list tsc_sync_check_timer; /* * TSC's on different sockets may be reset asynchronously. * This may cause the TSC ADJUST value on socket 0 to be NOT 0. */ bool __read_mostly tsc_async_resets; void mark_tsc_async_resets(char *reason) { if (tsc_async_resets) return; tsc_async_resets = true; pr_info("tsc: Marking TSC async resets true due to %s\n", reason); } void tsc_verify_tsc_adjust(bool resume) { struct tsc_adjust *adj = this_cpu_ptr(&tsc_adjust); s64 curval; if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST)) return; /* Skip unnecessary error messages if TSC already unstable */ if (check_tsc_unstable()) return; /* Rate limit the MSR check */ if (!resume && time_before(jiffies, adj->nextcheck)) return; adj->nextcheck = jiffies + HZ; rdmsrl(MSR_IA32_TSC_ADJUST, curval); if (adj->adjusted == curval) return; /* Restore the original value */ wrmsrl(MSR_IA32_TSC_ADJUST, adj->adjusted); if (!adj->warned || resume) { pr_warn(FW_BUG "TSC ADJUST differs: CPU%u %lld --> %lld. Restoring\n", smp_processor_id(), adj->adjusted, curval); adj->warned = true; } } /* * Normally the tsc_sync will be checked every time system enters idle * state, but there is still caveat that a system won't enter idle, * either because it's too busy or configured purposely to not enter * idle. * * So setup a periodic timer (every 10 minutes) to make sure the check * is always on. */ #define SYNC_CHECK_INTERVAL (HZ * 600) static void tsc_sync_check_timer_fn(struct timer_list *unused) { int next_cpu; tsc_verify_tsc_adjust(false); /* Run the check for all onlined CPUs in turn */ next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask); if (next_cpu >= nr_cpu_ids) next_cpu = cpumask_first(cpu_online_mask); tsc_sync_check_timer.expires += SYNC_CHECK_INTERVAL; add_timer_on(&tsc_sync_check_timer, next_cpu); } static int __init start_sync_check_timer(void) { if (!cpu_feature_enabled(X86_FEATURE_TSC_ADJUST) || tsc_clocksource_reliable) return 0; timer_setup(&tsc_sync_check_timer, tsc_sync_check_timer_fn, 0); tsc_sync_check_timer.expires = jiffies + SYNC_CHECK_INTERVAL; add_timer(&tsc_sync_check_timer); return 0; } late_initcall(start_sync_check_timer); static void tsc_sanitize_first_cpu(struct tsc_adjust *cur, s64 bootval, unsigned int cpu, bool bootcpu) { /* * First online CPU in a package stores the boot value in the * adjustment value. This value might change later via the sync * mechanism. If that fails we still can yell about boot values not * being consistent. * * On the boot cpu we just force set the ADJUST value to 0 if it's * non zero. We don't do that on non boot cpus because physical * hotplug should have set the ADJUST register to a value > 0 so * the TSC is in sync with the already running cpus. * * Also don't force the ADJUST value to zero if that is a valid value * for socket 0 as determined by the system arch. This is required * when multiple sockets are reset asynchronously with each other * and socket 0 may not have an TSC ADJUST value of 0. */ if (bootcpu && bootval != 0) { if (likely(!tsc_async_resets)) { pr_warn(FW_BUG "TSC ADJUST: CPU%u: %lld force to 0\n", cpu, bootval); wrmsrl(MSR_IA32_TSC_ADJUST, 0); bootval = 0; } else { pr_info("TSC ADJUST: CPU%u: %lld NOT forced to 0\n", cpu, bootval); } } cur->adjusted = bootval; } #ifndef CONFIG_SMP bool __init tsc_store_and_check_tsc_adjust(bool bootcpu) { struct tsc_adjust *cur = this_cpu_ptr(&tsc_adjust); s64 bootval; if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST)) return false; /* Skip unnecessary error messages if TSC already unstable */ if (check_tsc_unstable()) return false; rdmsrl(MSR_IA32_TSC_ADJUST, bootval); cur->bootval = bootval; cur->nextcheck = jiffies + HZ; tsc_sanitize_first_cpu(cur, bootval, smp_processor_id(), bootcpu); return false; } #else /* !CONFIG_SMP */ /* * Store and check the TSC ADJUST MSR if available */ bool tsc_store_and_check_tsc_adjust(bool bootcpu) { struct tsc_adjust *ref, *cur = this_cpu_ptr(&tsc_adjust); unsigned int refcpu, cpu = smp_processor_id(); struct cpumask *mask; s64 bootval; if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST)) return false; rdmsrl(MSR_IA32_TSC_ADJUST, bootval); cur->bootval = bootval; cur->nextcheck = jiffies + HZ; cur->warned = false; /* * If a non-zero TSC value for socket 0 may be valid then the default * adjusted value cannot assumed to be zero either. */ if (tsc_async_resets) cur->adjusted = bootval; /* * Check whether this CPU is the first in a package to come up. In * this case do not check the boot value against another package * because the new package might have been physically hotplugged, * where TSC_ADJUST is expected to be different. When called on the * boot CPU topology_core_cpumask() might not be available yet. */ mask = topology_core_cpumask(cpu); refcpu = mask ? cpumask_any_but(mask, cpu) : nr_cpu_ids; if (refcpu >= nr_cpu_ids) { tsc_sanitize_first_cpu(cur, bootval, smp_processor_id(), bootcpu); return false; } ref = per_cpu_ptr(&tsc_adjust, refcpu); /* * Compare the boot value and complain if it differs in the * package. */ if (bootval != ref->bootval) printk_once(FW_BUG "TSC ADJUST differs within socket(s), fixing all errors\n"); /* * The TSC_ADJUST values in a package must be the same. If the boot * value on this newly upcoming CPU differs from the adjustment * value of the already online CPU in this package, set it to that * adjusted value. */ if (bootval != ref->adjusted) { cur->adjusted = ref->adjusted; wrmsrl(MSR_IA32_TSC_ADJUST, ref->adjusted); } /* * We have the TSCs forced to be in sync on this package. Skip sync * test: */ return true; } /* * Entry/exit counters that make sure that both CPUs * run the measurement code at once: */ static atomic_t start_count; static atomic_t stop_count; static atomic_t test_runs; /* * We use a raw spinlock in this exceptional case, because * we want to have the fastest, inlined, non-debug version * of a critical section, to be able to prove TSC time-warps: */ static arch_spinlock_t sync_lock = __ARCH_SPIN_LOCK_UNLOCKED; static cycles_t last_tsc; static cycles_t max_warp; static int nr_warps; static int random_warps; /* * TSC-warp measurement loop running on both CPUs. This is not called * if there is no TSC. */ static cycles_t check_tsc_warp(unsigned int timeout) { cycles_t start, now, prev, end, cur_max_warp = 0; int i, cur_warps = 0; start = rdtsc_ordered(); /* * The measurement runs for 'timeout' msecs: */ end = start + (cycles_t) tsc_khz * timeout; for (i = 0; ; i++) { /* * We take the global lock, measure TSC, save the * previous TSC that was measured (possibly on * another CPU) and update the previous TSC timestamp. */ arch_spin_lock(&sync_lock); prev = last_tsc; now = rdtsc_ordered(); last_tsc = now; arch_spin_unlock(&sync_lock); /* * Be nice every now and then (and also check whether * measurement is done [we also insert a 10 million * loops safety exit, so we dont lock up in case the * TSC readout is totally broken]): */ if (unlikely(!(i & 7))) { if (now > end || i > 10000000) break; cpu_relax(); touch_nmi_watchdog(); } /* * Outside the critical section we can now see whether * we saw a time-warp of the TSC going backwards: */ if (unlikely(prev > now)) { arch_spin_lock(&sync_lock); max_warp = max(max_warp, prev - now); cur_max_warp = max_warp; /* * Check whether this bounces back and forth. Only * one CPU should observe time going backwards. */ if (cur_warps != nr_warps) random_warps++; nr_warps++; cur_warps = nr_warps; arch_spin_unlock(&sync_lock); } } WARN(!(now-start), "Warning: zero tsc calibration delta: %Ld [max: %Ld]\n", now-start, end-start); return cur_max_warp; } /* * If the target CPU coming online doesn't have any of its core-siblings * online, a timeout of 20msec will be used for the TSC-warp measurement * loop. Otherwise a smaller timeout of 2msec will be used, as we have some * information about this socket already (and this information grows as we * have more and more logical-siblings in that socket). * * Ideally we should be able to skip the TSC sync check on the other * core-siblings, if the first logical CPU in a socket passed the sync test. * But as the TSC is per-logical CPU and can potentially be modified wrongly * by the bios, TSC sync test for smaller duration should be able * to catch such errors. Also this will catch the condition where all the * cores in the socket don't get reset at the same time. */ static inline unsigned int loop_timeout(int cpu) { return (cpumask_weight(topology_core_cpumask(cpu)) > 1) ? 2 : 20; } /* * The freshly booted CPU initiates this via an async SMP function call. */ static void check_tsc_sync_source(void *__cpu) { unsigned int cpu = (unsigned long)__cpu; int cpus = 2; /* * Set the maximum number of test runs to * 1 if the CPU does not provide the TSC_ADJUST MSR * 3 if the MSR is available, so the target can try to adjust */ if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST)) atomic_set(&test_runs, 1); else atomic_set(&test_runs, 3); retry: /* Wait for the target to start. */ while (atomic_read(&start_count) != cpus - 1) cpu_relax(); /* * Trigger the target to continue into the measurement too: */ atomic_inc(&start_count); check_tsc_warp(loop_timeout(cpu)); while (atomic_read(&stop_count) != cpus-1) cpu_relax(); /* * If the test was successful set the number of runs to zero and * stop. If not, decrement the number of runs an check if we can * retry. In case of random warps no retry is attempted. */ if (!nr_warps) { atomic_set(&test_runs, 0); pr_debug("TSC synchronization [CPU#%d -> CPU#%u]: passed\n", smp_processor_id(), cpu); } else if (atomic_dec_and_test(&test_runs) || random_warps) { /* Force it to 0 if random warps brought us here */ atomic_set(&test_runs, 0); pr_warn("TSC synchronization [CPU#%d -> CPU#%u]:\n", smp_processor_id(), cpu); pr_warn("Measured %Ld cycles TSC warp between CPUs, " "turning off TSC clock.\n", max_warp); if (random_warps) pr_warn("TSC warped randomly between CPUs\n"); mark_tsc_unstable("check_tsc_sync_source failed"); } /* * Reset it - just in case we boot another CPU later: */ atomic_set(&start_count, 0); random_warps = 0; nr_warps = 0; max_warp = 0; last_tsc = 0; /* * Let the target continue with the bootup: */ atomic_inc(&stop_count); /* * Retry, if there is a chance to do so. */ if (atomic_read(&test_runs) > 0) goto retry; } /* * Freshly booted CPUs call into this: */ void check_tsc_sync_target(void) { struct tsc_adjust *cur = this_cpu_ptr(&tsc_adjust); unsigned int cpu = smp_processor_id(); cycles_t cur_max_warp, gbl_max_warp; int cpus = 2; /* Also aborts if there is no TSC. */ if (unsynchronized_tsc()) return; /* * Store, verify and sanitize the TSC adjust register. If * successful skip the test. * * The test is also skipped when the TSC is marked reliable. This * is true for SoCs which have no fallback clocksource. On these * SoCs the TSC is frequency synchronized, but still the TSC ADJUST * register might have been wreckaged by the BIOS.. */ if (tsc_store_and_check_tsc_adjust(false) || tsc_clocksource_reliable) return; /* Kick the control CPU into the TSC synchronization function */ smp_call_function_single(cpumask_first(cpu_online_mask), check_tsc_sync_source, (unsigned long *)(unsigned long)cpu, 0); retry: /* * Register this CPU's participation and wait for the * source CPU to start the measurement: */ atomic_inc(&start_count); while (atomic_read(&start_count) != cpus) cpu_relax(); cur_max_warp = check_tsc_warp(loop_timeout(cpu)); /* * Store the maximum observed warp value for a potential retry: */ gbl_max_warp = max_warp; /* * Ok, we are done: */ atomic_inc(&stop_count); /* * Wait for the source CPU to print stuff: */ while (atomic_read(&stop_count) != cpus) cpu_relax(); /* * Reset it for the next sync test: */ atomic_set(&stop_count, 0); /* * Check the number of remaining test runs. If not zero, the test * failed and a retry with adjusted TSC is possible. If zero the * test was either successful or failed terminally. */ if (!atomic_read(&test_runs)) return; /* * If the warp value of this CPU is 0, then the other CPU * observed time going backwards so this TSC was ahead and * needs to move backwards. */ if (!cur_max_warp) cur_max_warp = -gbl_max_warp; /* * Add the result to the previous adjustment value. * * The adjustment value is slightly off by the overhead of the * sync mechanism (observed values are ~200 TSC cycles), but this * really depends on CPU, node distance and frequency. So * compensating for this is hard to get right. Experiments show * that the warp is not longer detectable when the observed warp * value is used. In the worst case the adjustment needs to go * through a 3rd run for fine tuning. */ cur->adjusted += cur_max_warp; pr_warn("TSC ADJUST compensate: CPU%u observed %lld warp. Adjust: %lld\n", cpu, cur_max_warp, cur->adjusted); wrmsrl(MSR_IA32_TSC_ADJUST, cur->adjusted); goto retry; } #endif /* CONFIG_SMP */
linux-master
arch/x86/kernel/tsc_sync.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/objtool.h> #include <linux/module.h> #include <linux/sort.h> #include <asm/ptrace.h> #include <asm/stacktrace.h> #include <asm/unwind.h> #include <asm/orc_types.h> #include <asm/orc_lookup.h> #include <asm/orc_header.h> ORC_HEADER; #define orc_warn(fmt, ...) \ printk_deferred_once(KERN_WARNING "WARNING: " fmt, ##__VA_ARGS__) #define orc_warn_current(args...) \ ({ \ static bool dumped_before; \ if (state->task == current && !state->error) { \ orc_warn(args); \ if (unwind_debug && !dumped_before) { \ dumped_before = true; \ unwind_dump(state); \ } \ } \ }) extern int __start_orc_unwind_ip[]; extern int __stop_orc_unwind_ip[]; extern struct orc_entry __start_orc_unwind[]; extern struct orc_entry __stop_orc_unwind[]; static bool orc_init __ro_after_init; static bool unwind_debug __ro_after_init; static unsigned int lookup_num_blocks __ro_after_init; static int __init unwind_debug_cmdline(char *str) { unwind_debug = true; return 0; } early_param("unwind_debug", unwind_debug_cmdline); static void unwind_dump(struct unwind_state *state) { static bool dumped_before; unsigned long word, *sp; struct stack_info stack_info = {0}; unsigned long visit_mask = 0; if (dumped_before) return; dumped_before = true; printk_deferred("unwind stack type:%d next_sp:%p mask:0x%lx graph_idx:%d\n", state->stack_info.type, state->stack_info.next_sp, state->stack_mask, state->graph_idx); for (sp = __builtin_frame_address(0); sp; sp = PTR_ALIGN(stack_info.next_sp, sizeof(long))) { if (get_stack_info(sp, state->task, &stack_info, &visit_mask)) break; for (; sp < stack_info.end; sp++) { word = READ_ONCE_NOCHECK(*sp); printk_deferred("%0*lx: %0*lx (%pB)\n", BITS_PER_LONG/4, (unsigned long)sp, BITS_PER_LONG/4, word, (void *)word); } } } static inline unsigned long orc_ip(const int *ip) { return (unsigned long)ip + *ip; } static struct orc_entry *__orc_find(int *ip_table, struct orc_entry *u_table, unsigned int num_entries, unsigned long ip) { int *first = ip_table; int *last = ip_table + num_entries - 1; int *mid = first, *found = first; if (!num_entries) return NULL; /* * Do a binary range search to find the rightmost duplicate of a given * starting address. Some entries are section terminators which are * "weak" entries for ensuring there are no gaps. They should be * ignored when they conflict with a real entry. */ while (first <= last) { mid = first + ((last - first) / 2); if (orc_ip(mid) <= ip) { found = mid; first = mid + 1; } else last = mid - 1; } return u_table + (found - ip_table); } #ifdef CONFIG_MODULES static struct orc_entry *orc_module_find(unsigned long ip) { struct module *mod; mod = __module_address(ip); if (!mod || !mod->arch.orc_unwind || !mod->arch.orc_unwind_ip) return NULL; return __orc_find(mod->arch.orc_unwind_ip, mod->arch.orc_unwind, mod->arch.num_orcs, ip); } #else static struct orc_entry *orc_module_find(unsigned long ip) { return NULL; } #endif #ifdef CONFIG_DYNAMIC_FTRACE static struct orc_entry *orc_find(unsigned long ip); /* * Ftrace dynamic trampolines do not have orc entries of their own. * But they are copies of the ftrace entries that are static and * defined in ftrace_*.S, which do have orc entries. * * If the unwinder comes across a ftrace trampoline, then find the * ftrace function that was used to create it, and use that ftrace * function's orc entry, as the placement of the return code in * the stack will be identical. */ static struct orc_entry *orc_ftrace_find(unsigned long ip) { struct ftrace_ops *ops; unsigned long tramp_addr, offset; ops = ftrace_ops_trampoline(ip); if (!ops) return NULL; /* Set tramp_addr to the start of the code copied by the trampoline */ if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) tramp_addr = (unsigned long)ftrace_regs_caller; else tramp_addr = (unsigned long)ftrace_caller; /* Now place tramp_addr to the location within the trampoline ip is at */ offset = ip - ops->trampoline; tramp_addr += offset; /* Prevent unlikely recursion */ if (ip == tramp_addr) return NULL; return orc_find(tramp_addr); } #else static struct orc_entry *orc_ftrace_find(unsigned long ip) { return NULL; } #endif /* * If we crash with IP==0, the last successfully executed instruction * was probably an indirect function call with a NULL function pointer, * and we don't have unwind information for NULL. * This hardcoded ORC entry for IP==0 allows us to unwind from a NULL function * pointer into its parent and then continue normally from there. */ static struct orc_entry null_orc_entry = { .sp_offset = sizeof(long), .sp_reg = ORC_REG_SP, .bp_reg = ORC_REG_UNDEFINED, .type = ORC_TYPE_CALL }; /* Fake frame pointer entry -- used as a fallback for generated code */ static struct orc_entry orc_fp_entry = { .type = ORC_TYPE_CALL, .sp_reg = ORC_REG_BP, .sp_offset = 16, .bp_reg = ORC_REG_PREV_SP, .bp_offset = -16, }; static struct orc_entry *orc_find(unsigned long ip) { static struct orc_entry *orc; if (ip == 0) return &null_orc_entry; /* For non-init vmlinux addresses, use the fast lookup table: */ if (ip >= LOOKUP_START_IP && ip < LOOKUP_STOP_IP) { unsigned int idx, start, stop; idx = (ip - LOOKUP_START_IP) / LOOKUP_BLOCK_SIZE; if (unlikely((idx >= lookup_num_blocks-1))) { orc_warn("WARNING: bad lookup idx: idx=%u num=%u ip=%pB\n", idx, lookup_num_blocks, (void *)ip); return NULL; } start = orc_lookup[idx]; stop = orc_lookup[idx + 1] + 1; if (unlikely((__start_orc_unwind + start >= __stop_orc_unwind) || (__start_orc_unwind + stop > __stop_orc_unwind))) { orc_warn("WARNING: bad lookup value: idx=%u num=%u start=%u stop=%u ip=%pB\n", idx, lookup_num_blocks, start, stop, (void *)ip); return NULL; } return __orc_find(__start_orc_unwind_ip + start, __start_orc_unwind + start, stop - start, ip); } /* vmlinux .init slow lookup: */ if (is_kernel_inittext(ip)) return __orc_find(__start_orc_unwind_ip, __start_orc_unwind, __stop_orc_unwind_ip - __start_orc_unwind_ip, ip); /* Module lookup: */ orc = orc_module_find(ip); if (orc) return orc; return orc_ftrace_find(ip); } #ifdef CONFIG_MODULES static DEFINE_MUTEX(sort_mutex); static int *cur_orc_ip_table = __start_orc_unwind_ip; static struct orc_entry *cur_orc_table = __start_orc_unwind; static void orc_sort_swap(void *_a, void *_b, int size) { struct orc_entry *orc_a, *orc_b; int *a = _a, *b = _b, tmp; int delta = _b - _a; /* Swap the .orc_unwind_ip entries: */ tmp = *a; *a = *b + delta; *b = tmp - delta; /* Swap the corresponding .orc_unwind entries: */ orc_a = cur_orc_table + (a - cur_orc_ip_table); orc_b = cur_orc_table + (b - cur_orc_ip_table); swap(*orc_a, *orc_b); } static int orc_sort_cmp(const void *_a, const void *_b) { struct orc_entry *orc_a; const int *a = _a, *b = _b; unsigned long a_val = orc_ip(a); unsigned long b_val = orc_ip(b); if (a_val > b_val) return 1; if (a_val < b_val) return -1; /* * The "weak" section terminator entries need to always be first * to ensure the lookup code skips them in favor of real entries. * These terminator entries exist to handle any gaps created by * whitelisted .o files which didn't get objtool generation. */ orc_a = cur_orc_table + (a - cur_orc_ip_table); return orc_a->type == ORC_TYPE_UNDEFINED ? -1 : 1; } void unwind_module_init(struct module *mod, void *_orc_ip, size_t orc_ip_size, void *_orc, size_t orc_size) { int *orc_ip = _orc_ip; struct orc_entry *orc = _orc; unsigned int num_entries = orc_ip_size / sizeof(int); WARN_ON_ONCE(orc_ip_size % sizeof(int) != 0 || orc_size % sizeof(*orc) != 0 || num_entries != orc_size / sizeof(*orc)); /* * The 'cur_orc_*' globals allow the orc_sort_swap() callback to * associate an .orc_unwind_ip table entry with its corresponding * .orc_unwind entry so they can both be swapped. */ mutex_lock(&sort_mutex); cur_orc_ip_table = orc_ip; cur_orc_table = orc; sort(orc_ip, num_entries, sizeof(int), orc_sort_cmp, orc_sort_swap); mutex_unlock(&sort_mutex); mod->arch.orc_unwind_ip = orc_ip; mod->arch.orc_unwind = orc; mod->arch.num_orcs = num_entries; } #endif void __init unwind_init(void) { size_t orc_ip_size = (void *)__stop_orc_unwind_ip - (void *)__start_orc_unwind_ip; size_t orc_size = (void *)__stop_orc_unwind - (void *)__start_orc_unwind; size_t num_entries = orc_ip_size / sizeof(int); struct orc_entry *orc; int i; if (!num_entries || orc_ip_size % sizeof(int) != 0 || orc_size % sizeof(struct orc_entry) != 0 || num_entries != orc_size / sizeof(struct orc_entry)) { orc_warn("WARNING: Bad or missing .orc_unwind table. Disabling unwinder.\n"); return; } /* * Note, the orc_unwind and orc_unwind_ip tables were already * sorted at build time via the 'sorttable' tool. * It's ready for binary search straight away, no need to sort it. */ /* Initialize the fast lookup table: */ lookup_num_blocks = orc_lookup_end - orc_lookup; for (i = 0; i < lookup_num_blocks-1; i++) { orc = __orc_find(__start_orc_unwind_ip, __start_orc_unwind, num_entries, LOOKUP_START_IP + (LOOKUP_BLOCK_SIZE * i)); if (!orc) { orc_warn("WARNING: Corrupt .orc_unwind table. Disabling unwinder.\n"); return; } orc_lookup[i] = orc - __start_orc_unwind; } /* Initialize the ending block: */ orc = __orc_find(__start_orc_unwind_ip, __start_orc_unwind, num_entries, LOOKUP_STOP_IP); if (!orc) { orc_warn("WARNING: Corrupt .orc_unwind table. Disabling unwinder.\n"); return; } orc_lookup[lookup_num_blocks-1] = orc - __start_orc_unwind; orc_init = true; } unsigned long unwind_get_return_address(struct unwind_state *state) { if (unwind_done(state)) return 0; return __kernel_text_address(state->ip) ? state->ip : 0; } EXPORT_SYMBOL_GPL(unwind_get_return_address); unsigned long *unwind_get_return_address_ptr(struct unwind_state *state) { if (unwind_done(state)) return NULL; if (state->regs) return &state->regs->ip; if (state->sp) return (unsigned long *)state->sp - 1; return NULL; } static bool stack_access_ok(struct unwind_state *state, unsigned long _addr, size_t len) { struct stack_info *info = &state->stack_info; void *addr = (void *)_addr; if (on_stack(info, addr, len)) return true; return !get_stack_info(addr, state->task, info, &state->stack_mask) && on_stack(info, addr, len); } static bool deref_stack_reg(struct unwind_state *state, unsigned long addr, unsigned long *val) { if (!stack_access_ok(state, addr, sizeof(long))) return false; *val = READ_ONCE_NOCHECK(*(unsigned long *)addr); return true; } static bool deref_stack_regs(struct unwind_state *state, unsigned long addr, unsigned long *ip, unsigned long *sp) { struct pt_regs *regs = (struct pt_regs *)addr; /* x86-32 support will be more complicated due to the &regs->sp hack */ BUILD_BUG_ON(IS_ENABLED(CONFIG_X86_32)); if (!stack_access_ok(state, addr, sizeof(struct pt_regs))) return false; *ip = READ_ONCE_NOCHECK(regs->ip); *sp = READ_ONCE_NOCHECK(regs->sp); return true; } static bool deref_stack_iret_regs(struct unwind_state *state, unsigned long addr, unsigned long *ip, unsigned long *sp) { struct pt_regs *regs = (void *)addr - IRET_FRAME_OFFSET; if (!stack_access_ok(state, addr, IRET_FRAME_SIZE)) return false; *ip = READ_ONCE_NOCHECK(regs->ip); *sp = READ_ONCE_NOCHECK(regs->sp); return true; } /* * If state->regs is non-NULL, and points to a full pt_regs, just get the reg * value from state->regs. * * Otherwise, if state->regs just points to IRET regs, and the previous frame * had full regs, it's safe to get the value from the previous regs. This can * happen when early/late IRQ entry code gets interrupted by an NMI. */ static bool get_reg(struct unwind_state *state, unsigned int reg_off, unsigned long *val) { unsigned int reg = reg_off/8; if (!state->regs) return false; if (state->full_regs) { *val = READ_ONCE_NOCHECK(((unsigned long *)state->regs)[reg]); return true; } if (state->prev_regs) { *val = READ_ONCE_NOCHECK(((unsigned long *)state->prev_regs)[reg]); return true; } return false; } bool unwind_next_frame(struct unwind_state *state) { unsigned long ip_p, sp, tmp, orig_ip = state->ip, prev_sp = state->sp; enum stack_type prev_type = state->stack_info.type; struct orc_entry *orc; bool indirect = false; if (unwind_done(state)) return false; /* Don't let modules unload while we're reading their ORC data. */ preempt_disable(); /* End-of-stack check for user tasks: */ if (state->regs && user_mode(state->regs)) goto the_end; /* * Find the orc_entry associated with the text address. * * For a call frame (as opposed to a signal frame), state->ip points to * the instruction after the call. That instruction's stack layout * could be different from the call instruction's layout, for example * if the call was to a noreturn function. So get the ORC data for the * call instruction itself. */ orc = orc_find(state->signal ? state->ip : state->ip - 1); if (!orc) { /* * As a fallback, try to assume this code uses a frame pointer. * This is useful for generated code, like BPF, which ORC * doesn't know about. This is just a guess, so the rest of * the unwind is no longer considered reliable. */ orc = &orc_fp_entry; state->error = true; } else { if (orc->type == ORC_TYPE_UNDEFINED) goto err; if (orc->type == ORC_TYPE_END_OF_STACK) goto the_end; } state->signal = orc->signal; /* Find the previous frame's stack: */ switch (orc->sp_reg) { case ORC_REG_SP: sp = state->sp + orc->sp_offset; break; case ORC_REG_BP: sp = state->bp + orc->sp_offset; break; case ORC_REG_SP_INDIRECT: sp = state->sp; indirect = true; break; case ORC_REG_BP_INDIRECT: sp = state->bp + orc->sp_offset; indirect = true; break; case ORC_REG_R10: if (!get_reg(state, offsetof(struct pt_regs, r10), &sp)) { orc_warn_current("missing R10 value at %pB\n", (void *)state->ip); goto err; } break; case ORC_REG_R13: if (!get_reg(state, offsetof(struct pt_regs, r13), &sp)) { orc_warn_current("missing R13 value at %pB\n", (void *)state->ip); goto err; } break; case ORC_REG_DI: if (!get_reg(state, offsetof(struct pt_regs, di), &sp)) { orc_warn_current("missing RDI value at %pB\n", (void *)state->ip); goto err; } break; case ORC_REG_DX: if (!get_reg(state, offsetof(struct pt_regs, dx), &sp)) { orc_warn_current("missing DX value at %pB\n", (void *)state->ip); goto err; } break; default: orc_warn("unknown SP base reg %d at %pB\n", orc->sp_reg, (void *)state->ip); goto err; } if (indirect) { if (!deref_stack_reg(state, sp, &sp)) goto err; if (orc->sp_reg == ORC_REG_SP_INDIRECT) sp += orc->sp_offset; } /* Find IP, SP and possibly regs: */ switch (orc->type) { case ORC_TYPE_CALL: ip_p = sp - sizeof(long); if (!deref_stack_reg(state, ip_p, &state->ip)) goto err; state->ip = unwind_recover_ret_addr(state, state->ip, (unsigned long *)ip_p); state->sp = sp; state->regs = NULL; state->prev_regs = NULL; break; case ORC_TYPE_REGS: if (!deref_stack_regs(state, sp, &state->ip, &state->sp)) { orc_warn_current("can't access registers at %pB\n", (void *)orig_ip); goto err; } /* * There is a small chance to interrupt at the entry of * arch_rethook_trampoline() where the ORC info doesn't exist. * That point is right after the RET to arch_rethook_trampoline() * which was modified return address. * At that point, the @addr_p of the unwind_recover_rethook() * (this has to point the address of the stack entry storing * the modified return address) must be "SP - (a stack entry)" * because SP is incremented by the RET. */ state->ip = unwind_recover_rethook(state, state->ip, (unsigned long *)(state->sp - sizeof(long))); state->regs = (struct pt_regs *)sp; state->prev_regs = NULL; state->full_regs = true; break; case ORC_TYPE_REGS_PARTIAL: if (!deref_stack_iret_regs(state, sp, &state->ip, &state->sp)) { orc_warn_current("can't access iret registers at %pB\n", (void *)orig_ip); goto err; } /* See ORC_TYPE_REGS case comment. */ state->ip = unwind_recover_rethook(state, state->ip, (unsigned long *)(state->sp - sizeof(long))); if (state->full_regs) state->prev_regs = state->regs; state->regs = (void *)sp - IRET_FRAME_OFFSET; state->full_regs = false; break; default: orc_warn("unknown .orc_unwind entry type %d at %pB\n", orc->type, (void *)orig_ip); goto err; } /* Find BP: */ switch (orc->bp_reg) { case ORC_REG_UNDEFINED: if (get_reg(state, offsetof(struct pt_regs, bp), &tmp)) state->bp = tmp; break; case ORC_REG_PREV_SP: if (!deref_stack_reg(state, sp + orc->bp_offset, &state->bp)) goto err; break; case ORC_REG_BP: if (!deref_stack_reg(state, state->bp + orc->bp_offset, &state->bp)) goto err; break; default: orc_warn("unknown BP base reg %d for ip %pB\n", orc->bp_reg, (void *)orig_ip); goto err; } /* Prevent a recursive loop due to bad ORC data: */ if (state->stack_info.type == prev_type && on_stack(&state->stack_info, (void *)state->sp, sizeof(long)) && state->sp <= prev_sp) { orc_warn_current("stack going in the wrong direction? at %pB\n", (void *)orig_ip); goto err; } preempt_enable(); return true; err: state->error = true; the_end: preempt_enable(); state->stack_info.type = STACK_TYPE_UNKNOWN; return false; } EXPORT_SYMBOL_GPL(unwind_next_frame); void __unwind_start(struct unwind_state *state, struct task_struct *task, struct pt_regs *regs, unsigned long *first_frame) { memset(state, 0, sizeof(*state)); state->task = task; if (!orc_init) goto err; /* * Refuse to unwind the stack of a task while it's executing on another * CPU. This check is racy, but that's ok: the unwinder has other * checks to prevent it from going off the rails. */ if (task_on_another_cpu(task)) goto err; if (regs) { if (user_mode(regs)) goto the_end; state->ip = regs->ip; state->sp = regs->sp; state->bp = regs->bp; state->regs = regs; state->full_regs = true; state->signal = true; } else if (task == current) { asm volatile("lea (%%rip), %0\n\t" "mov %%rsp, %1\n\t" "mov %%rbp, %2\n\t" : "=r" (state->ip), "=r" (state->sp), "=r" (state->bp)); } else { struct inactive_task_frame *frame = (void *)task->thread.sp; state->sp = task->thread.sp + sizeof(*frame); state->bp = READ_ONCE_NOCHECK(frame->bp); state->ip = READ_ONCE_NOCHECK(frame->ret_addr); state->signal = (void *)state->ip == ret_from_fork; } if (get_stack_info((unsigned long *)state->sp, state->task, &state->stack_info, &state->stack_mask)) { /* * We weren't on a valid stack. It's possible that * we overflowed a valid stack into a guard page. * See if the next page up is valid so that we can * generate some kind of backtrace if this happens. */ void *next_page = (void *)PAGE_ALIGN((unsigned long)state->sp); state->error = true; if (get_stack_info(next_page, state->task, &state->stack_info, &state->stack_mask)) return; } /* * The caller can provide the address of the first frame directly * (first_frame) or indirectly (regs->sp) to indicate which stack frame * to start unwinding at. Skip ahead until we reach it. */ /* When starting from regs, skip the regs frame: */ if (regs) { unwind_next_frame(state); return; } /* Otherwise, skip ahead to the user-specified starting frame: */ while (!unwind_done(state) && (!on_stack(&state->stack_info, first_frame, sizeof(long)) || state->sp <= (unsigned long)first_frame)) unwind_next_frame(state); return; err: state->error = true; the_end: state->stack_info.type = STACK_TYPE_UNKNOWN; } EXPORT_SYMBOL_GPL(__unwind_start);
linux-master
arch/x86/kernel/unwind_orc.c
/* * Populate sysfs with topology information * * Written by: Matthew Dobson, IBM Corporation * Original Code: Paul Dorwin, IBM Corporation, Patrick Mochel, OSDL * * Copyright (C) 2002, IBM Corp. * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Send feedback to <[email protected]> */ #include <linux/interrupt.h> #include <linux/nodemask.h> #include <linux/export.h> #include <linux/mmzone.h> #include <linux/init.h> #include <linux/smp.h> #include <linux/irq.h> #include <asm/io_apic.h> #include <asm/cpu.h> static DEFINE_PER_CPU(struct x86_cpu, cpu_devices); #ifdef CONFIG_HOTPLUG_CPU int arch_register_cpu(int cpu) { struct x86_cpu *xc = per_cpu_ptr(&cpu_devices, cpu); xc->cpu.hotpluggable = cpu > 0; return register_cpu(&xc->cpu, cpu); } EXPORT_SYMBOL(arch_register_cpu); void arch_unregister_cpu(int num) { unregister_cpu(&per_cpu(cpu_devices, num).cpu); } EXPORT_SYMBOL(arch_unregister_cpu); #else /* CONFIG_HOTPLUG_CPU */ static int __init arch_register_cpu(int num) { return register_cpu(&per_cpu(cpu_devices, num).cpu, num); } #endif /* CONFIG_HOTPLUG_CPU */ static int __init topology_init(void) { int i; for_each_present_cpu(i) arch_register_cpu(i); return 0; } subsys_initcall(topology_init);
linux-master
arch/x86/kernel/topology.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/platform_device.h> #include <linux/err.h> #include <linux/init.h> static __init int add_pcspkr(void) { struct platform_device *pd; pd = platform_device_register_simple("pcspkr", -1, NULL, 0); return PTR_ERR_OR_ZERO(pd); } device_initcall(add_pcspkr);
linux-master
arch/x86/kernel/pcspeaker.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/ptrace.h> #include <asm/bugs.h> #include <asm/traps.h> enum cp_error_code { CP_EC = (1 << 15) - 1, CP_RET = 1, CP_IRET = 2, CP_ENDBR = 3, CP_RSTRORSSP = 4, CP_SETSSBSY = 5, CP_ENCL = 1 << 15, }; static const char cp_err[][10] = { [0] = "unknown", [1] = "near ret", [2] = "far/iret", [3] = "endbranch", [4] = "rstorssp", [5] = "setssbsy", }; static const char *cp_err_string(unsigned long error_code) { unsigned int cpec = error_code & CP_EC; if (cpec >= ARRAY_SIZE(cp_err)) cpec = 0; return cp_err[cpec]; } static void do_unexpected_cp(struct pt_regs *regs, unsigned long error_code) { WARN_ONCE(1, "Unexpected %s #CP, error_code: %s\n", user_mode(regs) ? "user mode" : "kernel mode", cp_err_string(error_code)); } static DEFINE_RATELIMIT_STATE(cpf_rate, DEFAULT_RATELIMIT_INTERVAL, DEFAULT_RATELIMIT_BURST); static void do_user_cp_fault(struct pt_regs *regs, unsigned long error_code) { struct task_struct *tsk; unsigned long ssp; /* * An exception was just taken from userspace. Since interrupts are disabled * here, no scheduling should have messed with the registers yet and they * will be whatever is live in userspace. So read the SSP before enabling * interrupts so locking the fpregs to do it later is not required. */ rdmsrl(MSR_IA32_PL3_SSP, ssp); cond_local_irq_enable(regs); tsk = current; tsk->thread.error_code = error_code; tsk->thread.trap_nr = X86_TRAP_CP; /* Ratelimit to prevent log spamming. */ if (show_unhandled_signals && unhandled_signal(tsk, SIGSEGV) && __ratelimit(&cpf_rate)) { pr_emerg("%s[%d] control protection ip:%lx sp:%lx ssp:%lx error:%lx(%s)%s", tsk->comm, task_pid_nr(tsk), regs->ip, regs->sp, ssp, error_code, cp_err_string(error_code), error_code & CP_ENCL ? " in enclave" : ""); print_vma_addr(KERN_CONT " in ", regs->ip); pr_cont("\n"); } force_sig_fault(SIGSEGV, SEGV_CPERR, (void __user *)0); cond_local_irq_disable(regs); } static __ro_after_init bool ibt_fatal = true; static void do_kernel_cp_fault(struct pt_regs *regs, unsigned long error_code) { if ((error_code & CP_EC) != CP_ENDBR) { do_unexpected_cp(regs, error_code); return; } if (unlikely(regs->ip == (unsigned long)&ibt_selftest_noendbr)) { regs->ax = 0; return; } pr_err("Missing ENDBR: %pS\n", (void *)instruction_pointer(regs)); if (!ibt_fatal) { printk(KERN_DEFAULT CUT_HERE); __warn(__FILE__, __LINE__, (void *)regs->ip, TAINT_WARN, regs, NULL); return; } BUG(); } static int __init ibt_setup(char *str) { if (!strcmp(str, "off")) setup_clear_cpu_cap(X86_FEATURE_IBT); if (!strcmp(str, "warn")) ibt_fatal = false; return 1; } __setup("ibt=", ibt_setup); DEFINE_IDTENTRY_ERRORCODE(exc_control_protection) { if (user_mode(regs)) { if (cpu_feature_enabled(X86_FEATURE_USER_SHSTK)) do_user_cp_fault(regs, error_code); else do_unexpected_cp(regs, error_code); } else { if (cpu_feature_enabled(X86_FEATURE_IBT)) do_kernel_cp_fault(regs, error_code); else do_unexpected_cp(regs, error_code); } }
linux-master
arch/x86/kernel/cet.c
// SPDX-License-Identifier: GPL-2.0-or-later /* Kernel module help for x86. Copyright (C) 2001 Rusty Russell. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/moduleloader.h> #include <linux/elf.h> #include <linux/vmalloc.h> #include <linux/fs.h> #include <linux/string.h> #include <linux/kernel.h> #include <linux/kasan.h> #include <linux/bug.h> #include <linux/mm.h> #include <linux/gfp.h> #include <linux/jump_label.h> #include <linux/random.h> #include <linux/memory.h> #include <asm/text-patching.h> #include <asm/page.h> #include <asm/setup.h> #include <asm/unwind.h> #if 0 #define DEBUGP(fmt, ...) \ printk(KERN_DEBUG fmt, ##__VA_ARGS__) #else #define DEBUGP(fmt, ...) \ do { \ if (0) \ printk(KERN_DEBUG fmt, ##__VA_ARGS__); \ } while (0) #endif #ifdef CONFIG_RANDOMIZE_BASE static unsigned long module_load_offset; /* Mutex protects the module_load_offset. */ static DEFINE_MUTEX(module_kaslr_mutex); static unsigned long int get_module_load_offset(void) { if (kaslr_enabled()) { mutex_lock(&module_kaslr_mutex); /* * Calculate the module_load_offset the first time this * code is called. Once calculated it stays the same until * reboot. */ if (module_load_offset == 0) module_load_offset = get_random_u32_inclusive(1, 1024) * PAGE_SIZE; mutex_unlock(&module_kaslr_mutex); } return module_load_offset; } #else static unsigned long int get_module_load_offset(void) { return 0; } #endif void *module_alloc(unsigned long size) { gfp_t gfp_mask = GFP_KERNEL; void *p; if (PAGE_ALIGN(size) > MODULES_LEN) return NULL; p = __vmalloc_node_range(size, MODULE_ALIGN, MODULES_VADDR + get_module_load_offset(), MODULES_END, gfp_mask, PAGE_KERNEL, VM_FLUSH_RESET_PERMS | VM_DEFER_KMEMLEAK, NUMA_NO_NODE, __builtin_return_address(0)); if (p && (kasan_alloc_module_shadow(p, size, gfp_mask) < 0)) { vfree(p); return NULL; } return p; } #ifdef CONFIG_X86_32 int apply_relocate(Elf32_Shdr *sechdrs, const char *strtab, unsigned int symindex, unsigned int relsec, struct module *me) { unsigned int i; Elf32_Rel *rel = (void *)sechdrs[relsec].sh_addr; Elf32_Sym *sym; uint32_t *location; DEBUGP("Applying relocate section %u to %u\n", relsec, sechdrs[relsec].sh_info); for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) { /* This is where to make the change */ location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr + rel[i].r_offset; /* This is the symbol it is referring to. Note that all undefined symbols have been resolved. */ sym = (Elf32_Sym *)sechdrs[symindex].sh_addr + ELF32_R_SYM(rel[i].r_info); switch (ELF32_R_TYPE(rel[i].r_info)) { case R_386_32: /* We add the value into the location given */ *location += sym->st_value; break; case R_386_PC32: case R_386_PLT32: /* Add the value, subtract its position */ *location += sym->st_value - (uint32_t)location; break; default: pr_err("%s: Unknown relocation: %u\n", me->name, ELF32_R_TYPE(rel[i].r_info)); return -ENOEXEC; } } return 0; } #else /*X86_64*/ static int __write_relocate_add(Elf64_Shdr *sechdrs, const char *strtab, unsigned int symindex, unsigned int relsec, struct module *me, void *(*write)(void *dest, const void *src, size_t len), bool apply) { unsigned int i; Elf64_Rela *rel = (void *)sechdrs[relsec].sh_addr; Elf64_Sym *sym; void *loc; u64 val; u64 zero = 0ULL; DEBUGP("%s relocate section %u to %u\n", apply ? "Applying" : "Clearing", relsec, sechdrs[relsec].sh_info); for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) { size_t size; /* This is where to make the change */ loc = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr + rel[i].r_offset; /* This is the symbol it is referring to. Note that all undefined symbols have been resolved. */ sym = (Elf64_Sym *)sechdrs[symindex].sh_addr + ELF64_R_SYM(rel[i].r_info); DEBUGP("type %d st_value %Lx r_addend %Lx loc %Lx\n", (int)ELF64_R_TYPE(rel[i].r_info), sym->st_value, rel[i].r_addend, (u64)loc); val = sym->st_value + rel[i].r_addend; switch (ELF64_R_TYPE(rel[i].r_info)) { case R_X86_64_NONE: continue; /* nothing to write */ case R_X86_64_64: size = 8; break; case R_X86_64_32: if (val != *(u32 *)&val) goto overflow; size = 4; break; case R_X86_64_32S: if ((s64)val != *(s32 *)&val) goto overflow; size = 4; break; case R_X86_64_PC32: case R_X86_64_PLT32: val -= (u64)loc; size = 4; break; case R_X86_64_PC64: val -= (u64)loc; size = 8; break; default: pr_err("%s: Unknown rela relocation: %llu\n", me->name, ELF64_R_TYPE(rel[i].r_info)); return -ENOEXEC; } if (apply) { if (memcmp(loc, &zero, size)) { pr_err("x86/modules: Invalid relocation target, existing value is nonzero for type %d, loc %p, val %Lx\n", (int)ELF64_R_TYPE(rel[i].r_info), loc, val); return -ENOEXEC; } write(loc, &val, size); } else { if (memcmp(loc, &val, size)) { pr_warn("x86/modules: Invalid relocation target, existing value does not match expected value for type %d, loc %p, val %Lx\n", (int)ELF64_R_TYPE(rel[i].r_info), loc, val); return -ENOEXEC; } write(loc, &zero, size); } } return 0; overflow: pr_err("overflow in relocation type %d val %Lx\n", (int)ELF64_R_TYPE(rel[i].r_info), val); pr_err("`%s' likely not compiled with -mcmodel=kernel\n", me->name); return -ENOEXEC; } static int write_relocate_add(Elf64_Shdr *sechdrs, const char *strtab, unsigned int symindex, unsigned int relsec, struct module *me, bool apply) { int ret; bool early = me->state == MODULE_STATE_UNFORMED; void *(*write)(void *, const void *, size_t) = memcpy; if (!early) { write = text_poke; mutex_lock(&text_mutex); } ret = __write_relocate_add(sechdrs, strtab, symindex, relsec, me, write, apply); if (!early) { text_poke_sync(); mutex_unlock(&text_mutex); } return ret; } int apply_relocate_add(Elf64_Shdr *sechdrs, const char *strtab, unsigned int symindex, unsigned int relsec, struct module *me) { return write_relocate_add(sechdrs, strtab, symindex, relsec, me, true); } #ifdef CONFIG_LIVEPATCH void clear_relocate_add(Elf64_Shdr *sechdrs, const char *strtab, unsigned int symindex, unsigned int relsec, struct module *me) { write_relocate_add(sechdrs, strtab, symindex, relsec, me, false); } #endif #endif int module_finalize(const Elf_Ehdr *hdr, const Elf_Shdr *sechdrs, struct module *me) { const Elf_Shdr *s, *alt = NULL, *locks = NULL, *para = NULL, *orc = NULL, *orc_ip = NULL, *retpolines = NULL, *returns = NULL, *ibt_endbr = NULL, *calls = NULL, *cfi = NULL; char *secstrings = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset; for (s = sechdrs; s < sechdrs + hdr->e_shnum; s++) { if (!strcmp(".altinstructions", secstrings + s->sh_name)) alt = s; if (!strcmp(".smp_locks", secstrings + s->sh_name)) locks = s; if (!strcmp(".parainstructions", secstrings + s->sh_name)) para = s; if (!strcmp(".orc_unwind", secstrings + s->sh_name)) orc = s; if (!strcmp(".orc_unwind_ip", secstrings + s->sh_name)) orc_ip = s; if (!strcmp(".retpoline_sites", secstrings + s->sh_name)) retpolines = s; if (!strcmp(".return_sites", secstrings + s->sh_name)) returns = s; if (!strcmp(".call_sites", secstrings + s->sh_name)) calls = s; if (!strcmp(".cfi_sites", secstrings + s->sh_name)) cfi = s; if (!strcmp(".ibt_endbr_seal", secstrings + s->sh_name)) ibt_endbr = s; } /* * See alternative_instructions() for the ordering rules between the * various patching types. */ if (para) { void *pseg = (void *)para->sh_addr; apply_paravirt(pseg, pseg + para->sh_size); } if (retpolines || cfi) { void *rseg = NULL, *cseg = NULL; unsigned int rsize = 0, csize = 0; if (retpolines) { rseg = (void *)retpolines->sh_addr; rsize = retpolines->sh_size; } if (cfi) { cseg = (void *)cfi->sh_addr; csize = cfi->sh_size; } apply_fineibt(rseg, rseg + rsize, cseg, cseg + csize); } if (retpolines) { void *rseg = (void *)retpolines->sh_addr; apply_retpolines(rseg, rseg + retpolines->sh_size); } if (returns) { void *rseg = (void *)returns->sh_addr; apply_returns(rseg, rseg + returns->sh_size); } if (alt) { /* patch .altinstructions */ void *aseg = (void *)alt->sh_addr; apply_alternatives(aseg, aseg + alt->sh_size); } if (calls || para) { struct callthunk_sites cs = {}; if (calls) { cs.call_start = (void *)calls->sh_addr; cs.call_end = (void *)calls->sh_addr + calls->sh_size; } if (para) { cs.pv_start = (void *)para->sh_addr; cs.pv_end = (void *)para->sh_addr + para->sh_size; } callthunks_patch_module_calls(&cs, me); } if (ibt_endbr) { void *iseg = (void *)ibt_endbr->sh_addr; apply_seal_endbr(iseg, iseg + ibt_endbr->sh_size); } if (locks) { void *lseg = (void *)locks->sh_addr; void *text = me->mem[MOD_TEXT].base; void *text_end = text + me->mem[MOD_TEXT].size; alternatives_smp_module_add(me, me->name, lseg, lseg + locks->sh_size, text, text_end); } if (orc && orc_ip) unwind_module_init(me, (void *)orc_ip->sh_addr, orc_ip->sh_size, (void *)orc->sh_addr, orc->sh_size); return 0; } void module_arch_cleanup(struct module *mod) { alternatives_smp_module_del(mod); }
linux-master
arch/x86/kernel/module.c
// SPDX-License-Identifier: GPL-2.0-only /* * handle transition of Linux booting another kernel * Copyright (C) 2002-2005 Eric Biederman <[email protected]> */ #include <linux/mm.h> #include <linux/kexec.h> #include <linux/delay.h> #include <linux/numa.h> #include <linux/ftrace.h> #include <linux/suspend.h> #include <linux/gfp.h> #include <linux/io.h> #include <asm/pgalloc.h> #include <asm/tlbflush.h> #include <asm/mmu_context.h> #include <asm/apic.h> #include <asm/io_apic.h> #include <asm/cpufeature.h> #include <asm/desc.h> #include <asm/set_memory.h> #include <asm/debugreg.h> static void load_segments(void) { #define __STR(X) #X #define STR(X) __STR(X) __asm__ __volatile__ ( "\tljmp $"STR(__KERNEL_CS)",$1f\n" "\t1:\n" "\tmovl $"STR(__KERNEL_DS)",%%eax\n" "\tmovl %%eax,%%ds\n" "\tmovl %%eax,%%es\n" "\tmovl %%eax,%%ss\n" : : : "eax", "memory"); #undef STR #undef __STR } static void machine_kexec_free_page_tables(struct kimage *image) { free_pages((unsigned long)image->arch.pgd, PGD_ALLOCATION_ORDER); image->arch.pgd = NULL; #ifdef CONFIG_X86_PAE free_page((unsigned long)image->arch.pmd0); image->arch.pmd0 = NULL; free_page((unsigned long)image->arch.pmd1); image->arch.pmd1 = NULL; #endif free_page((unsigned long)image->arch.pte0); image->arch.pte0 = NULL; free_page((unsigned long)image->arch.pte1); image->arch.pte1 = NULL; } static int machine_kexec_alloc_page_tables(struct kimage *image) { image->arch.pgd = (pgd_t *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, PGD_ALLOCATION_ORDER); #ifdef CONFIG_X86_PAE image->arch.pmd0 = (pmd_t *)get_zeroed_page(GFP_KERNEL); image->arch.pmd1 = (pmd_t *)get_zeroed_page(GFP_KERNEL); #endif image->arch.pte0 = (pte_t *)get_zeroed_page(GFP_KERNEL); image->arch.pte1 = (pte_t *)get_zeroed_page(GFP_KERNEL); if (!image->arch.pgd || #ifdef CONFIG_X86_PAE !image->arch.pmd0 || !image->arch.pmd1 || #endif !image->arch.pte0 || !image->arch.pte1) { return -ENOMEM; } return 0; } static void machine_kexec_page_table_set_one( pgd_t *pgd, pmd_t *pmd, pte_t *pte, unsigned long vaddr, unsigned long paddr) { p4d_t *p4d; pud_t *pud; pgd += pgd_index(vaddr); #ifdef CONFIG_X86_PAE if (!(pgd_val(*pgd) & _PAGE_PRESENT)) set_pgd(pgd, __pgd(__pa(pmd) | _PAGE_PRESENT)); #endif p4d = p4d_offset(pgd, vaddr); pud = pud_offset(p4d, vaddr); pmd = pmd_offset(pud, vaddr); if (!(pmd_val(*pmd) & _PAGE_PRESENT)) set_pmd(pmd, __pmd(__pa(pte) | _PAGE_TABLE)); pte = pte_offset_kernel(pmd, vaddr); set_pte(pte, pfn_pte(paddr >> PAGE_SHIFT, PAGE_KERNEL_EXEC)); } static void machine_kexec_prepare_page_tables(struct kimage *image) { void *control_page; pmd_t *pmd = NULL; control_page = page_address(image->control_code_page); #ifdef CONFIG_X86_PAE pmd = image->arch.pmd0; #endif machine_kexec_page_table_set_one( image->arch.pgd, pmd, image->arch.pte0, (unsigned long)control_page, __pa(control_page)); #ifdef CONFIG_X86_PAE pmd = image->arch.pmd1; #endif machine_kexec_page_table_set_one( image->arch.pgd, pmd, image->arch.pte1, __pa(control_page), __pa(control_page)); } /* * A architecture hook called to validate the * proposed image and prepare the control pages * as needed. The pages for KEXEC_CONTROL_PAGE_SIZE * have been allocated, but the segments have yet * been copied into the kernel. * * Do what every setup is needed on image and the * reboot code buffer to allow us to avoid allocations * later. * * - Make control page executable. * - Allocate page tables * - Setup page tables */ int machine_kexec_prepare(struct kimage *image) { int error; set_memory_x((unsigned long)page_address(image->control_code_page), 1); error = machine_kexec_alloc_page_tables(image); if (error) return error; machine_kexec_prepare_page_tables(image); return 0; } /* * Undo anything leftover by machine_kexec_prepare * when an image is freed. */ void machine_kexec_cleanup(struct kimage *image) { set_memory_nx((unsigned long)page_address(image->control_code_page), 1); machine_kexec_free_page_tables(image); } /* * Do not allocate memory (or fail in any way) in machine_kexec(). * We are past the point of no return, committed to rebooting now. */ void machine_kexec(struct kimage *image) { unsigned long page_list[PAGES_NR]; void *control_page; int save_ftrace_enabled; asmlinkage unsigned long (*relocate_kernel_ptr)(unsigned long indirection_page, unsigned long control_page, unsigned long start_address, unsigned int has_pae, unsigned int preserve_context); #ifdef CONFIG_KEXEC_JUMP if (image->preserve_context) save_processor_state(); #endif save_ftrace_enabled = __ftrace_enabled_save(); /* Interrupts aren't acceptable while we reboot */ local_irq_disable(); hw_breakpoint_disable(); if (image->preserve_context) { #ifdef CONFIG_X86_IO_APIC /* * We need to put APICs in legacy mode so that we can * get timer interrupts in second kernel. kexec/kdump * paths already have calls to restore_boot_irq_mode() * in one form or other. kexec jump path also need one. */ clear_IO_APIC(); restore_boot_irq_mode(); #endif } control_page = page_address(image->control_code_page); memcpy(control_page, relocate_kernel, KEXEC_CONTROL_CODE_MAX_SIZE); relocate_kernel_ptr = control_page; page_list[PA_CONTROL_PAGE] = __pa(control_page); page_list[VA_CONTROL_PAGE] = (unsigned long)control_page; page_list[PA_PGD] = __pa(image->arch.pgd); if (image->type == KEXEC_TYPE_DEFAULT) page_list[PA_SWAP_PAGE] = (page_to_pfn(image->swap_page) << PAGE_SHIFT); /* * The segment registers are funny things, they have both a * visible and an invisible part. Whenever the visible part is * set to a specific selector, the invisible part is loaded * with from a table in memory. At no other time is the * descriptor table in memory accessed. * * I take advantage of this here by force loading the * segments, before I zap the gdt with an invalid value. */ load_segments(); /* * The gdt & idt are now invalid. * If you want to load them you must set up your own idt & gdt. */ native_idt_invalidate(); native_gdt_invalidate(); /* now call it */ image->start = relocate_kernel_ptr((unsigned long)image->head, (unsigned long)page_list, image->start, boot_cpu_has(X86_FEATURE_PAE), image->preserve_context); #ifdef CONFIG_KEXEC_JUMP if (image->preserve_context) restore_processor_state(); #endif __ftrace_enabled_restore(save_ftrace_enabled); }
linux-master
arch/x86/kernel/machine_kexec_32.c
// SPDX-License-Identifier: GPL-2.0 /* * Architecture specific OF callbacks. */ #include <linux/export.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/list.h> #include <linux/of.h> #include <linux/of_fdt.h> #include <linux/of_address.h> #include <linux/of_platform.h> #include <linux/of_irq.h> #include <linux/libfdt.h> #include <linux/slab.h> #include <linux/pci.h> #include <linux/of_pci.h> #include <linux/initrd.h> #include <asm/irqdomain.h> #include <asm/hpet.h> #include <asm/apic.h> #include <asm/io_apic.h> #include <asm/pci_x86.h> #include <asm/setup.h> #include <asm/i8259.h> #include <asm/prom.h> __initdata u64 initial_dtb; char __initdata cmd_line[COMMAND_LINE_SIZE]; int __initdata of_ioapic; void __init add_dtb(u64 data) { initial_dtb = data + offsetof(struct setup_data, data); } /* * CE4100 ids. Will be moved to machine_device_initcall() once we have it. */ static struct of_device_id __initdata ce4100_ids[] = { { .compatible = "intel,ce4100-cp", }, { .compatible = "isa", }, { .compatible = "pci", }, {}, }; static int __init add_bus_probe(void) { if (!of_have_populated_dt()) return 0; return of_platform_bus_probe(NULL, ce4100_ids, NULL); } device_initcall(add_bus_probe); #ifdef CONFIG_PCI struct device_node *pcibios_get_phb_of_node(struct pci_bus *bus) { struct device_node *np; for_each_node_by_type(np, "pci") { const void *prop; unsigned int bus_min; prop = of_get_property(np, "bus-range", NULL); if (!prop) continue; bus_min = be32_to_cpup(prop); if (bus->number == bus_min) return np; } return NULL; } static int x86_of_pci_irq_enable(struct pci_dev *dev) { u32 virq; int ret; u8 pin; ret = pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin); if (ret) return ret; if (!pin) return 0; virq = of_irq_parse_and_map_pci(dev, 0, 0); if (virq == 0) return -EINVAL; dev->irq = virq; return 0; } static void x86_of_pci_irq_disable(struct pci_dev *dev) { } void x86_of_pci_init(void) { pcibios_enable_irq = x86_of_pci_irq_enable; pcibios_disable_irq = x86_of_pci_irq_disable; } #endif static void __init dtb_setup_hpet(void) { #ifdef CONFIG_HPET_TIMER struct device_node *dn; struct resource r; int ret; dn = of_find_compatible_node(NULL, NULL, "intel,ce4100-hpet"); if (!dn) return; ret = of_address_to_resource(dn, 0, &r); if (ret) { WARN_ON(1); return; } hpet_address = r.start; #endif } #ifdef CONFIG_X86_LOCAL_APIC static void __init dtb_cpu_setup(void) { struct device_node *dn; u32 apic_id; for_each_of_cpu_node(dn) { apic_id = of_get_cpu_hwid(dn, 0); if (apic_id == ~0U) { pr_warn("%pOF: missing local APIC ID\n", dn); continue; } generic_processor_info(apic_id); } } static void __init dtb_lapic_setup(void) { struct device_node *dn; struct resource r; unsigned long lapic_addr = APIC_DEFAULT_PHYS_BASE; int ret; dn = of_find_compatible_node(NULL, NULL, "intel,ce4100-lapic"); if (dn) { ret = of_address_to_resource(dn, 0, &r); if (WARN_ON(ret)) return; lapic_addr = r.start; } /* Did the boot loader setup the local APIC ? */ if (!boot_cpu_has(X86_FEATURE_APIC)) { /* Try force enabling, which registers the APIC address */ if (!apic_force_enable(lapic_addr)) return; } else { register_lapic_address(lapic_addr); } smp_found_config = 1; pic_mode = !of_property_read_bool(dn, "intel,virtual-wire-mode"); pr_info("%s compatibility mode.\n", pic_mode ? "IMCR and PIC" : "Virtual Wire"); } #endif /* CONFIG_X86_LOCAL_APIC */ #ifdef CONFIG_X86_IO_APIC static unsigned int ioapic_id; struct of_ioapic_type { u32 out_type; u32 is_level; u32 active_low; }; static struct of_ioapic_type of_ioapic_type[] = { { .out_type = IRQ_TYPE_EDGE_FALLING, .is_level = 0, .active_low = 1, }, { .out_type = IRQ_TYPE_LEVEL_HIGH, .is_level = 1, .active_low = 0, }, { .out_type = IRQ_TYPE_LEVEL_LOW, .is_level = 1, .active_low = 1, }, { .out_type = IRQ_TYPE_EDGE_RISING, .is_level = 0, .active_low = 0, }, }; static int dt_irqdomain_alloc(struct irq_domain *domain, unsigned int virq, unsigned int nr_irqs, void *arg) { struct irq_fwspec *fwspec = (struct irq_fwspec *)arg; struct of_ioapic_type *it; struct irq_alloc_info tmp; int type_index; if (WARN_ON(fwspec->param_count < 2)) return -EINVAL; type_index = fwspec->param[1]; if (type_index >= ARRAY_SIZE(of_ioapic_type)) return -EINVAL; it = &of_ioapic_type[type_index]; ioapic_set_alloc_attr(&tmp, NUMA_NO_NODE, it->is_level, it->active_low); tmp.devid = mpc_ioapic_id(mp_irqdomain_ioapic_idx(domain)); tmp.ioapic.pin = fwspec->param[0]; return mp_irqdomain_alloc(domain, virq, nr_irqs, &tmp); } static const struct irq_domain_ops ioapic_irq_domain_ops = { .alloc = dt_irqdomain_alloc, .free = mp_irqdomain_free, .activate = mp_irqdomain_activate, .deactivate = mp_irqdomain_deactivate, }; static void __init dtb_add_ioapic(struct device_node *dn) { struct resource r; int ret; struct ioapic_domain_cfg cfg = { .type = IOAPIC_DOMAIN_DYNAMIC, .ops = &ioapic_irq_domain_ops, .dev = dn, }; ret = of_address_to_resource(dn, 0, &r); if (ret) { pr_err("Can't obtain address from device node %pOF.\n", dn); return; } mp_register_ioapic(++ioapic_id, r.start, gsi_top, &cfg); } static void __init dtb_ioapic_setup(void) { struct device_node *dn; for_each_compatible_node(dn, NULL, "intel,ce4100-ioapic") dtb_add_ioapic(dn); if (nr_ioapics) { of_ioapic = 1; return; } pr_err("Error: No information about IO-APIC in OF.\n"); } #else static void __init dtb_ioapic_setup(void) {} #endif static void __init dtb_apic_setup(void) { #ifdef CONFIG_X86_LOCAL_APIC dtb_lapic_setup(); dtb_cpu_setup(); #endif dtb_ioapic_setup(); } #ifdef CONFIG_OF_EARLY_FLATTREE static void __init x86_flattree_get_config(void) { u32 size, map_len; void *dt; if (!initial_dtb) return; map_len = max(PAGE_SIZE - (initial_dtb & ~PAGE_MASK), (u64)128); dt = early_memremap(initial_dtb, map_len); size = fdt_totalsize(dt); if (map_len < size) { early_memunmap(dt, map_len); dt = early_memremap(initial_dtb, size); map_len = size; } early_init_dt_verify(dt); unflatten_and_copy_device_tree(); early_memunmap(dt, map_len); } #else static inline void x86_flattree_get_config(void) { } #endif void __init x86_dtb_init(void) { x86_flattree_get_config(); if (!of_have_populated_dt()) return; dtb_setup_hpet(); dtb_apic_setup(); }
linux-master
arch/x86/kernel/devicetree.c
// SPDX-License-Identifier: GPL-2.0 /* * Clang Control Flow Integrity (CFI) support. * * Copyright (C) 2022 Google LLC */ #include <asm/cfi.h> #include <asm/insn.h> #include <asm/insn-eval.h> #include <linux/string.h> /* * Returns the target address and the expected type when regs->ip points * to a compiler-generated CFI trap. */ static bool decode_cfi_insn(struct pt_regs *regs, unsigned long *target, u32 *type) { char buffer[MAX_INSN_SIZE]; struct insn insn; int offset = 0; *target = *type = 0; /* * The compiler generates the following instruction sequence * for indirect call checks: * *   movl -<id>, %r10d ; 6 bytes * addl -4(%reg), %r10d ; 4 bytes * je .Ltmp1 ; 2 bytes * ud2 ; <- regs->ip * .Ltmp1: * * We can decode the expected type and the target address from the * movl/addl instructions. */ if (copy_from_kernel_nofault(buffer, (void *)regs->ip - 12, MAX_INSN_SIZE)) return false; if (insn_decode_kernel(&insn, &buffer[offset])) return false; if (insn.opcode.value != 0xBA) return false; *type = -(u32)insn.immediate.value; if (copy_from_kernel_nofault(buffer, (void *)regs->ip - 6, MAX_INSN_SIZE)) return false; if (insn_decode_kernel(&insn, &buffer[offset])) return false; if (insn.opcode.value != 0x3) return false; /* Read the target address from the register. */ offset = insn_get_modrm_rm_off(&insn, regs); if (offset < 0) return false; *target = *(unsigned long *)((void *)regs + offset); return true; } /* * Checks if a ud2 trap is because of a CFI failure, and handles the trap * if needed. Returns a bug_trap_type value similarly to report_bug. */ enum bug_trap_type handle_cfi_failure(struct pt_regs *regs) { unsigned long target; u32 type; if (!is_cfi_trap(regs->ip)) return BUG_TRAP_TYPE_NONE; if (!decode_cfi_insn(regs, &target, &type)) return report_cfi_failure_noaddr(regs, regs->ip); return report_cfi_failure(regs, regs->ip, &target, type); } /* * Ensure that __kcfi_typeid_ symbols are emitted for functions that may * not be indirectly called with all configurations. */ __ADDRESSABLE(__memcpy)
linux-master
arch/x86/kernel/cfi.c
// SPDX-License-Identifier: GPL-2.0-only /* * Low level x86 E820 memory map handling functions. * * The firmware and bootloader passes us the "E820 table", which is the primary * physical memory layout description available about x86 systems. * * The kernel takes the E820 memory layout and optionally modifies it with * quirks and other tweaks, and feeds that into the generic Linux memory * allocation code routines via a platform independent interface (memblock, etc.). */ #include <linux/crash_dump.h> #include <linux/memblock.h> #include <linux/suspend.h> #include <linux/acpi.h> #include <linux/firmware-map.h> #include <linux/sort.h> #include <linux/memory_hotplug.h> #include <asm/e820/api.h> #include <asm/setup.h> /* * We organize the E820 table into three main data structures: * * - 'e820_table_firmware': the original firmware version passed to us by the * bootloader - not modified by the kernel. It is composed of two parts: * the first 128 E820 memory entries in boot_params.e820_table and the remaining * (if any) entries of the SETUP_E820_EXT nodes. We use this to: * * - inform the user about the firmware's notion of memory layout * via /sys/firmware/memmap * * - the hibernation code uses it to generate a kernel-independent CRC32 * checksum of the physical memory layout of a system. * * - 'e820_table_kexec': a slightly modified (by the kernel) firmware version * passed to us by the bootloader - the major difference between * e820_table_firmware[] and this one is that, the latter marks the setup_data * list created by the EFI boot stub as reserved, so that kexec can reuse the * setup_data information in the second kernel. Besides, e820_table_kexec[] * might also be modified by the kexec itself to fake a mptable. * We use this to: * * - kexec, which is a bootloader in disguise, uses the original E820 * layout to pass to the kexec-ed kernel. This way the original kernel * can have a restricted E820 map while the kexec()-ed kexec-kernel * can have access to full memory - etc. * * - 'e820_table': this is the main E820 table that is massaged by the * low level x86 platform code, or modified by boot parameters, before * passed on to higher level MM layers. * * Once the E820 map has been converted to the standard Linux memory layout * information its role stops - modifying it has no effect and does not get * re-propagated. So its main role is a temporary bootstrap storage of firmware * specific memory layout data during early bootup. */ static struct e820_table e820_table_init __initdata; static struct e820_table e820_table_kexec_init __initdata; static struct e820_table e820_table_firmware_init __initdata; struct e820_table *e820_table __refdata = &e820_table_init; struct e820_table *e820_table_kexec __refdata = &e820_table_kexec_init; struct e820_table *e820_table_firmware __refdata = &e820_table_firmware_init; /* For PCI or other memory-mapped resources */ unsigned long pci_mem_start = 0xaeedbabe; #ifdef CONFIG_PCI EXPORT_SYMBOL(pci_mem_start); #endif /* * This function checks if any part of the range <start,end> is mapped * with type. */ static bool _e820__mapped_any(struct e820_table *table, u64 start, u64 end, enum e820_type type) { int i; for (i = 0; i < table->nr_entries; i++) { struct e820_entry *entry = &table->entries[i]; if (type && entry->type != type) continue; if (entry->addr >= end || entry->addr + entry->size <= start) continue; return true; } return false; } bool e820__mapped_raw_any(u64 start, u64 end, enum e820_type type) { return _e820__mapped_any(e820_table_firmware, start, end, type); } EXPORT_SYMBOL_GPL(e820__mapped_raw_any); bool e820__mapped_any(u64 start, u64 end, enum e820_type type) { return _e820__mapped_any(e820_table, start, end, type); } EXPORT_SYMBOL_GPL(e820__mapped_any); /* * This function checks if the entire <start,end> range is mapped with 'type'. * * Note: this function only works correctly once the E820 table is sorted and * not-overlapping (at least for the range specified), which is the case normally. */ static struct e820_entry *__e820__mapped_all(u64 start, u64 end, enum e820_type type) { int i; for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; if (type && entry->type != type) continue; /* Is the region (part) in overlap with the current region? */ if (entry->addr >= end || entry->addr + entry->size <= start) continue; /* * If the region is at the beginning of <start,end> we move * 'start' to the end of the region since it's ok until there */ if (entry->addr <= start) start = entry->addr + entry->size; /* * If 'start' is now at or beyond 'end', we're done, full * coverage of the desired range exists: */ if (start >= end) return entry; } return NULL; } /* * This function checks if the entire range <start,end> is mapped with type. */ bool __init e820__mapped_all(u64 start, u64 end, enum e820_type type) { return __e820__mapped_all(start, end, type); } /* * This function returns the type associated with the range <start,end>. */ int e820__get_entry_type(u64 start, u64 end) { struct e820_entry *entry = __e820__mapped_all(start, end, 0); return entry ? entry->type : -EINVAL; } /* * Add a memory region to the kernel E820 map. */ static void __init __e820__range_add(struct e820_table *table, u64 start, u64 size, enum e820_type type) { int x = table->nr_entries; if (x >= ARRAY_SIZE(table->entries)) { pr_err("too many entries; ignoring [mem %#010llx-%#010llx]\n", start, start + size - 1); return; } table->entries[x].addr = start; table->entries[x].size = size; table->entries[x].type = type; table->nr_entries++; } void __init e820__range_add(u64 start, u64 size, enum e820_type type) { __e820__range_add(e820_table, start, size, type); } static void __init e820_print_type(enum e820_type type) { switch (type) { case E820_TYPE_RAM: /* Fall through: */ case E820_TYPE_RESERVED_KERN: pr_cont("usable"); break; case E820_TYPE_RESERVED: pr_cont("reserved"); break; case E820_TYPE_SOFT_RESERVED: pr_cont("soft reserved"); break; case E820_TYPE_ACPI: pr_cont("ACPI data"); break; case E820_TYPE_NVS: pr_cont("ACPI NVS"); break; case E820_TYPE_UNUSABLE: pr_cont("unusable"); break; case E820_TYPE_PMEM: /* Fall through: */ case E820_TYPE_PRAM: pr_cont("persistent (type %u)", type); break; default: pr_cont("type %u", type); break; } } void __init e820__print_table(char *who) { int i; for (i = 0; i < e820_table->nr_entries; i++) { pr_info("%s: [mem %#018Lx-%#018Lx] ", who, e820_table->entries[i].addr, e820_table->entries[i].addr + e820_table->entries[i].size - 1); e820_print_type(e820_table->entries[i].type); pr_cont("\n"); } } /* * Sanitize an E820 map. * * Some E820 layouts include overlapping entries. The following * replaces the original E820 map with a new one, removing overlaps, * and resolving conflicting memory types in favor of highest * numbered type. * * The input parameter 'entries' points to an array of 'struct * e820_entry' which on entry has elements in the range [0, *nr_entries) * valid, and which has space for up to max_nr_entries entries. * On return, the resulting sanitized E820 map entries will be in * overwritten in the same location, starting at 'entries'. * * The integer pointed to by nr_entries must be valid on entry (the * current number of valid entries located at 'entries'). If the * sanitizing succeeds the *nr_entries will be updated with the new * number of valid entries (something no more than max_nr_entries). * * The return value from e820__update_table() is zero if it * successfully 'sanitized' the map entries passed in, and is -1 * if it did nothing, which can happen if either of (1) it was * only passed one map entry, or (2) any of the input map entries * were invalid (start + size < start, meaning that the size was * so big the described memory range wrapped around through zero.) * * Visually we're performing the following * (1,2,3,4 = memory types)... * * Sample memory map (w/overlaps): * ____22__________________ * ______________________4_ * ____1111________________ * _44_____________________ * 11111111________________ * ____________________33__ * ___________44___________ * __________33333_________ * ______________22________ * ___________________2222_ * _________111111111______ * _____________________11_ * _________________4______ * * Sanitized equivalent (no overlap): * 1_______________________ * _44_____________________ * ___1____________________ * ____22__________________ * ______11________________ * _________1______________ * __________3_____________ * ___________44___________ * _____________33_________ * _______________2________ * ________________1_______ * _________________4______ * ___________________2____ * ____________________33__ * ______________________4_ */ struct change_member { /* Pointer to the original entry: */ struct e820_entry *entry; /* Address for this change point: */ unsigned long long addr; }; static struct change_member change_point_list[2*E820_MAX_ENTRIES] __initdata; static struct change_member *change_point[2*E820_MAX_ENTRIES] __initdata; static struct e820_entry *overlap_list[E820_MAX_ENTRIES] __initdata; static struct e820_entry new_entries[E820_MAX_ENTRIES] __initdata; static int __init cpcompare(const void *a, const void *b) { struct change_member * const *app = a, * const *bpp = b; const struct change_member *ap = *app, *bp = *bpp; /* * Inputs are pointers to two elements of change_point[]. If their * addresses are not equal, their difference dominates. If the addresses * are equal, then consider one that represents the end of its region * to be greater than one that does not. */ if (ap->addr != bp->addr) return ap->addr > bp->addr ? 1 : -1; return (ap->addr != ap->entry->addr) - (bp->addr != bp->entry->addr); } static bool e820_nomerge(enum e820_type type) { /* * These types may indicate distinct platform ranges aligned to * numa node, protection domain, performance domain, or other * boundaries. Do not merge them. */ if (type == E820_TYPE_PRAM) return true; if (type == E820_TYPE_SOFT_RESERVED) return true; return false; } int __init e820__update_table(struct e820_table *table) { struct e820_entry *entries = table->entries; u32 max_nr_entries = ARRAY_SIZE(table->entries); enum e820_type current_type, last_type; unsigned long long last_addr; u32 new_nr_entries, overlap_entries; u32 i, chg_idx, chg_nr; /* If there's only one memory region, don't bother: */ if (table->nr_entries < 2) return -1; BUG_ON(table->nr_entries > max_nr_entries); /* Bail out if we find any unreasonable addresses in the map: */ for (i = 0; i < table->nr_entries; i++) { if (entries[i].addr + entries[i].size < entries[i].addr) return -1; } /* Create pointers for initial change-point information (for sorting): */ for (i = 0; i < 2 * table->nr_entries; i++) change_point[i] = &change_point_list[i]; /* * Record all known change-points (starting and ending addresses), * omitting empty memory regions: */ chg_idx = 0; for (i = 0; i < table->nr_entries; i++) { if (entries[i].size != 0) { change_point[chg_idx]->addr = entries[i].addr; change_point[chg_idx++]->entry = &entries[i]; change_point[chg_idx]->addr = entries[i].addr + entries[i].size; change_point[chg_idx++]->entry = &entries[i]; } } chg_nr = chg_idx; /* Sort change-point list by memory addresses (low -> high): */ sort(change_point, chg_nr, sizeof(*change_point), cpcompare, NULL); /* Create a new memory map, removing overlaps: */ overlap_entries = 0; /* Number of entries in the overlap table */ new_nr_entries = 0; /* Index for creating new map entries */ last_type = 0; /* Start with undefined memory type */ last_addr = 0; /* Start with 0 as last starting address */ /* Loop through change-points, determining effect on the new map: */ for (chg_idx = 0; chg_idx < chg_nr; chg_idx++) { /* Keep track of all overlapping entries */ if (change_point[chg_idx]->addr == change_point[chg_idx]->entry->addr) { /* Add map entry to overlap list (> 1 entry implies an overlap) */ overlap_list[overlap_entries++] = change_point[chg_idx]->entry; } else { /* Remove entry from list (order independent, so swap with last): */ for (i = 0; i < overlap_entries; i++) { if (overlap_list[i] == change_point[chg_idx]->entry) overlap_list[i] = overlap_list[overlap_entries-1]; } overlap_entries--; } /* * If there are overlapping entries, decide which * "type" to use (larger value takes precedence -- * 1=usable, 2,3,4,4+=unusable) */ current_type = 0; for (i = 0; i < overlap_entries; i++) { if (overlap_list[i]->type > current_type) current_type = overlap_list[i]->type; } /* Continue building up new map based on this information: */ if (current_type != last_type || e820_nomerge(current_type)) { if (last_type) { new_entries[new_nr_entries].size = change_point[chg_idx]->addr - last_addr; /* Move forward only if the new size was non-zero: */ if (new_entries[new_nr_entries].size != 0) /* No more space left for new entries? */ if (++new_nr_entries >= max_nr_entries) break; } if (current_type) { new_entries[new_nr_entries].addr = change_point[chg_idx]->addr; new_entries[new_nr_entries].type = current_type; last_addr = change_point[chg_idx]->addr; } last_type = current_type; } } /* Copy the new entries into the original location: */ memcpy(entries, new_entries, new_nr_entries*sizeof(*entries)); table->nr_entries = new_nr_entries; return 0; } static int __init __append_e820_table(struct boot_e820_entry *entries, u32 nr_entries) { struct boot_e820_entry *entry = entries; while (nr_entries) { u64 start = entry->addr; u64 size = entry->size; u64 end = start + size - 1; u32 type = entry->type; /* Ignore the entry on 64-bit overflow: */ if (start > end && likely(size)) return -1; e820__range_add(start, size, type); entry++; nr_entries--; } return 0; } /* * Copy the BIOS E820 map into a safe place. * * Sanity-check it while we're at it.. * * If we're lucky and live on a modern system, the setup code * will have given us a memory map that we can use to properly * set up memory. If we aren't, we'll fake a memory map. */ static int __init append_e820_table(struct boot_e820_entry *entries, u32 nr_entries) { /* Only one memory region (or negative)? Ignore it */ if (nr_entries < 2) return -1; return __append_e820_table(entries, nr_entries); } static u64 __init __e820__range_update(struct e820_table *table, u64 start, u64 size, enum e820_type old_type, enum e820_type new_type) { u64 end; unsigned int i; u64 real_updated_size = 0; BUG_ON(old_type == new_type); if (size > (ULLONG_MAX - start)) size = ULLONG_MAX - start; end = start + size; printk(KERN_DEBUG "e820: update [mem %#010Lx-%#010Lx] ", start, end - 1); e820_print_type(old_type); pr_cont(" ==> "); e820_print_type(new_type); pr_cont("\n"); for (i = 0; i < table->nr_entries; i++) { struct e820_entry *entry = &table->entries[i]; u64 final_start, final_end; u64 entry_end; if (entry->type != old_type) continue; entry_end = entry->addr + entry->size; /* Completely covered by new range? */ if (entry->addr >= start && entry_end <= end) { entry->type = new_type; real_updated_size += entry->size; continue; } /* New range is completely covered? */ if (entry->addr < start && entry_end > end) { __e820__range_add(table, start, size, new_type); __e820__range_add(table, end, entry_end - end, entry->type); entry->size = start - entry->addr; real_updated_size += size; continue; } /* Partially covered: */ final_start = max(start, entry->addr); final_end = min(end, entry_end); if (final_start >= final_end) continue; __e820__range_add(table, final_start, final_end - final_start, new_type); real_updated_size += final_end - final_start; /* * Left range could be head or tail, so need to update * its size first: */ entry->size -= final_end - final_start; if (entry->addr < final_start) continue; entry->addr = final_end; } return real_updated_size; } u64 __init e820__range_update(u64 start, u64 size, enum e820_type old_type, enum e820_type new_type) { return __e820__range_update(e820_table, start, size, old_type, new_type); } static u64 __init e820__range_update_kexec(u64 start, u64 size, enum e820_type old_type, enum e820_type new_type) { return __e820__range_update(e820_table_kexec, start, size, old_type, new_type); } /* Remove a range of memory from the E820 table: */ u64 __init e820__range_remove(u64 start, u64 size, enum e820_type old_type, bool check_type) { int i; u64 end; u64 real_removed_size = 0; if (size > (ULLONG_MAX - start)) size = ULLONG_MAX - start; end = start + size; printk(KERN_DEBUG "e820: remove [mem %#010Lx-%#010Lx] ", start, end - 1); if (check_type) e820_print_type(old_type); pr_cont("\n"); for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; u64 final_start, final_end; u64 entry_end; if (check_type && entry->type != old_type) continue; entry_end = entry->addr + entry->size; /* Completely covered? */ if (entry->addr >= start && entry_end <= end) { real_removed_size += entry->size; memset(entry, 0, sizeof(*entry)); continue; } /* Is the new range completely covered? */ if (entry->addr < start && entry_end > end) { e820__range_add(end, entry_end - end, entry->type); entry->size = start - entry->addr; real_removed_size += size; continue; } /* Partially covered: */ final_start = max(start, entry->addr); final_end = min(end, entry_end); if (final_start >= final_end) continue; real_removed_size += final_end - final_start; /* * Left range could be head or tail, so need to update * the size first: */ entry->size -= final_end - final_start; if (entry->addr < final_start) continue; entry->addr = final_end; } return real_removed_size; } void __init e820__update_table_print(void) { if (e820__update_table(e820_table)) return; pr_info("modified physical RAM map:\n"); e820__print_table("modified"); } static void __init e820__update_table_kexec(void) { e820__update_table(e820_table_kexec); } #define MAX_GAP_END 0x100000000ull /* * Search for a gap in the E820 memory space from 0 to MAX_GAP_END (4GB). */ static int __init e820_search_gap(unsigned long *gapstart, unsigned long *gapsize) { unsigned long long last = MAX_GAP_END; int i = e820_table->nr_entries; int found = 0; while (--i >= 0) { unsigned long long start = e820_table->entries[i].addr; unsigned long long end = start + e820_table->entries[i].size; /* * Since "last" is at most 4GB, we know we'll * fit in 32 bits if this condition is true: */ if (last > end) { unsigned long gap = last - end; if (gap >= *gapsize) { *gapsize = gap; *gapstart = end; found = 1; } } if (start < last) last = start; } return found; } /* * Search for the biggest gap in the low 32 bits of the E820 * memory space. We pass this space to the PCI subsystem, so * that it can assign MMIO resources for hotplug or * unconfigured devices in. * * Hopefully the BIOS let enough space left. */ __init void e820__setup_pci_gap(void) { unsigned long gapstart, gapsize; int found; gapsize = 0x400000; found = e820_search_gap(&gapstart, &gapsize); if (!found) { #ifdef CONFIG_X86_64 gapstart = (max_pfn << PAGE_SHIFT) + 1024*1024; pr_err("Cannot find an available gap in the 32-bit address range\n"); pr_err("PCI devices with unassigned 32-bit BARs may not work!\n"); #else gapstart = 0x10000000; #endif } /* * e820__reserve_resources_late() protects stolen RAM already: */ pci_mem_start = gapstart; pr_info("[mem %#010lx-%#010lx] available for PCI devices\n", gapstart, gapstart + gapsize - 1); } /* * Called late during init, in free_initmem(). * * Initial e820_table and e820_table_kexec are largish __initdata arrays. * * Copy them to a (usually much smaller) dynamically allocated area that is * sized precisely after the number of e820 entries. * * This is done after we've performed all the fixes and tweaks to the tables. * All functions which modify them are __init functions, which won't exist * after free_initmem(). */ __init void e820__reallocate_tables(void) { struct e820_table *n; int size; size = offsetof(struct e820_table, entries) + sizeof(struct e820_entry)*e820_table->nr_entries; n = kmemdup(e820_table, size, GFP_KERNEL); BUG_ON(!n); e820_table = n; size = offsetof(struct e820_table, entries) + sizeof(struct e820_entry)*e820_table_kexec->nr_entries; n = kmemdup(e820_table_kexec, size, GFP_KERNEL); BUG_ON(!n); e820_table_kexec = n; size = offsetof(struct e820_table, entries) + sizeof(struct e820_entry)*e820_table_firmware->nr_entries; n = kmemdup(e820_table_firmware, size, GFP_KERNEL); BUG_ON(!n); e820_table_firmware = n; } /* * Because of the small fixed size of struct boot_params, only the first * 128 E820 memory entries are passed to the kernel via boot_params.e820_table, * the remaining (if any) entries are passed via the SETUP_E820_EXT node of * struct setup_data, which is parsed here. */ void __init e820__memory_setup_extended(u64 phys_addr, u32 data_len) { int entries; struct boot_e820_entry *extmap; struct setup_data *sdata; sdata = early_memremap(phys_addr, data_len); entries = sdata->len / sizeof(*extmap); extmap = (struct boot_e820_entry *)(sdata->data); __append_e820_table(extmap, entries); e820__update_table(e820_table); memcpy(e820_table_kexec, e820_table, sizeof(*e820_table_kexec)); memcpy(e820_table_firmware, e820_table, sizeof(*e820_table_firmware)); early_memunmap(sdata, data_len); pr_info("extended physical RAM map:\n"); e820__print_table("extended"); } /* * Find the ranges of physical addresses that do not correspond to * E820 RAM areas and register the corresponding pages as 'nosave' for * hibernation (32-bit) or software suspend and suspend to RAM (64-bit). * * This function requires the E820 map to be sorted and without any * overlapping entries. */ void __init e820__register_nosave_regions(unsigned long limit_pfn) { int i; unsigned long pfn = 0; for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; if (pfn < PFN_UP(entry->addr)) register_nosave_region(pfn, PFN_UP(entry->addr)); pfn = PFN_DOWN(entry->addr + entry->size); if (entry->type != E820_TYPE_RAM && entry->type != E820_TYPE_RESERVED_KERN) register_nosave_region(PFN_UP(entry->addr), pfn); if (pfn >= limit_pfn) break; } } #ifdef CONFIG_ACPI /* * Register ACPI NVS memory regions, so that we can save/restore them during * hibernation and the subsequent resume: */ static int __init e820__register_nvs_regions(void) { int i; for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; if (entry->type == E820_TYPE_NVS) acpi_nvs_register(entry->addr, entry->size); } return 0; } core_initcall(e820__register_nvs_regions); #endif /* * Allocate the requested number of bytes with the requested alignment * and return (the physical address) to the caller. Also register this * range in the 'kexec' E820 table as a reserved range. * * This allows kexec to fake a new mptable, as if it came from the real * system. */ u64 __init e820__memblock_alloc_reserved(u64 size, u64 align) { u64 addr; addr = memblock_phys_alloc(size, align); if (addr) { e820__range_update_kexec(addr, size, E820_TYPE_RAM, E820_TYPE_RESERVED); pr_info("update e820_table_kexec for e820__memblock_alloc_reserved()\n"); e820__update_table_kexec(); } return addr; } #ifdef CONFIG_X86_32 # ifdef CONFIG_X86_PAE # define MAX_ARCH_PFN (1ULL<<(36-PAGE_SHIFT)) # else # define MAX_ARCH_PFN (1ULL<<(32-PAGE_SHIFT)) # endif #else /* CONFIG_X86_32 */ # define MAX_ARCH_PFN MAXMEM>>PAGE_SHIFT #endif /* * Find the highest page frame number we have available */ static unsigned long __init e820_end_pfn(unsigned long limit_pfn, enum e820_type type) { int i; unsigned long last_pfn = 0; unsigned long max_arch_pfn = MAX_ARCH_PFN; for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; unsigned long start_pfn; unsigned long end_pfn; if (entry->type != type) continue; start_pfn = entry->addr >> PAGE_SHIFT; end_pfn = (entry->addr + entry->size) >> PAGE_SHIFT; if (start_pfn >= limit_pfn) continue; if (end_pfn > limit_pfn) { last_pfn = limit_pfn; break; } if (end_pfn > last_pfn) last_pfn = end_pfn; } if (last_pfn > max_arch_pfn) last_pfn = max_arch_pfn; pr_info("last_pfn = %#lx max_arch_pfn = %#lx\n", last_pfn, max_arch_pfn); return last_pfn; } unsigned long __init e820__end_of_ram_pfn(void) { return e820_end_pfn(MAX_ARCH_PFN, E820_TYPE_RAM); } unsigned long __init e820__end_of_low_ram_pfn(void) { return e820_end_pfn(1UL << (32 - PAGE_SHIFT), E820_TYPE_RAM); } static void __init early_panic(char *msg) { early_printk(msg); panic(msg); } static int userdef __initdata; /* The "mem=nopentium" boot option disables 4MB page tables on 32-bit kernels: */ static int __init parse_memopt(char *p) { u64 mem_size; if (!p) return -EINVAL; if (!strcmp(p, "nopentium")) { #ifdef CONFIG_X86_32 setup_clear_cpu_cap(X86_FEATURE_PSE); return 0; #else pr_warn("mem=nopentium ignored! (only supported on x86_32)\n"); return -EINVAL; #endif } userdef = 1; mem_size = memparse(p, &p); /* Don't remove all memory when getting "mem={invalid}" parameter: */ if (mem_size == 0) return -EINVAL; e820__range_remove(mem_size, ULLONG_MAX - mem_size, E820_TYPE_RAM, 1); #ifdef CONFIG_MEMORY_HOTPLUG max_mem_size = mem_size; #endif return 0; } early_param("mem", parse_memopt); static int __init parse_memmap_one(char *p) { char *oldp; u64 start_at, mem_size; if (!p) return -EINVAL; if (!strncmp(p, "exactmap", 8)) { e820_table->nr_entries = 0; userdef = 1; return 0; } oldp = p; mem_size = memparse(p, &p); if (p == oldp) return -EINVAL; userdef = 1; if (*p == '@') { start_at = memparse(p+1, &p); e820__range_add(start_at, mem_size, E820_TYPE_RAM); } else if (*p == '#') { start_at = memparse(p+1, &p); e820__range_add(start_at, mem_size, E820_TYPE_ACPI); } else if (*p == '$') { start_at = memparse(p+1, &p); e820__range_add(start_at, mem_size, E820_TYPE_RESERVED); } else if (*p == '!') { start_at = memparse(p+1, &p); e820__range_add(start_at, mem_size, E820_TYPE_PRAM); } else if (*p == '%') { enum e820_type from = 0, to = 0; start_at = memparse(p + 1, &p); if (*p == '-') from = simple_strtoull(p + 1, &p, 0); if (*p == '+') to = simple_strtoull(p + 1, &p, 0); if (*p != '\0') return -EINVAL; if (from && to) e820__range_update(start_at, mem_size, from, to); else if (to) e820__range_add(start_at, mem_size, to); else if (from) e820__range_remove(start_at, mem_size, from, 1); else e820__range_remove(start_at, mem_size, 0, 0); } else { e820__range_remove(mem_size, ULLONG_MAX - mem_size, E820_TYPE_RAM, 1); } return *p == '\0' ? 0 : -EINVAL; } static int __init parse_memmap_opt(char *str) { while (str) { char *k = strchr(str, ','); if (k) *k++ = 0; parse_memmap_one(str); str = k; } return 0; } early_param("memmap", parse_memmap_opt); /* * Reserve all entries from the bootloader's extensible data nodes list, * because if present we are going to use it later on to fetch e820 * entries from it: */ void __init e820__reserve_setup_data(void) { struct setup_indirect *indirect; struct setup_data *data; u64 pa_data, pa_next; u32 len; pa_data = boot_params.hdr.setup_data; if (!pa_data) return; while (pa_data) { data = early_memremap(pa_data, sizeof(*data)); if (!data) { pr_warn("e820: failed to memremap setup_data entry\n"); return; } len = sizeof(*data); pa_next = data->next; e820__range_update(pa_data, sizeof(*data)+data->len, E820_TYPE_RAM, E820_TYPE_RESERVED_KERN); /* * SETUP_EFI and SETUP_IMA are supplied by kexec and do not need * to be reserved. */ if (data->type != SETUP_EFI && data->type != SETUP_IMA) e820__range_update_kexec(pa_data, sizeof(*data) + data->len, E820_TYPE_RAM, E820_TYPE_RESERVED_KERN); if (data->type == SETUP_INDIRECT) { len += data->len; early_memunmap(data, sizeof(*data)); data = early_memremap(pa_data, len); if (!data) { pr_warn("e820: failed to memremap indirect setup_data\n"); return; } indirect = (struct setup_indirect *)data->data; if (indirect->type != SETUP_INDIRECT) { e820__range_update(indirect->addr, indirect->len, E820_TYPE_RAM, E820_TYPE_RESERVED_KERN); e820__range_update_kexec(indirect->addr, indirect->len, E820_TYPE_RAM, E820_TYPE_RESERVED_KERN); } } pa_data = pa_next; early_memunmap(data, len); } e820__update_table(e820_table); e820__update_table(e820_table_kexec); pr_info("extended physical RAM map:\n"); e820__print_table("reserve setup_data"); } /* * Called after parse_early_param(), after early parameters (such as mem=) * have been processed, in which case we already have an E820 table filled in * via the parameter callback function(s), but it's not sorted and printed yet: */ void __init e820__finish_early_params(void) { if (userdef) { if (e820__update_table(e820_table) < 0) early_panic("Invalid user supplied memory map"); pr_info("user-defined physical RAM map:\n"); e820__print_table("user"); } } static const char *__init e820_type_to_string(struct e820_entry *entry) { switch (entry->type) { case E820_TYPE_RESERVED_KERN: /* Fall-through: */ case E820_TYPE_RAM: return "System RAM"; case E820_TYPE_ACPI: return "ACPI Tables"; case E820_TYPE_NVS: return "ACPI Non-volatile Storage"; case E820_TYPE_UNUSABLE: return "Unusable memory"; case E820_TYPE_PRAM: return "Persistent Memory (legacy)"; case E820_TYPE_PMEM: return "Persistent Memory"; case E820_TYPE_RESERVED: return "Reserved"; case E820_TYPE_SOFT_RESERVED: return "Soft Reserved"; default: return "Unknown E820 type"; } } static unsigned long __init e820_type_to_iomem_type(struct e820_entry *entry) { switch (entry->type) { case E820_TYPE_RESERVED_KERN: /* Fall-through: */ case E820_TYPE_RAM: return IORESOURCE_SYSTEM_RAM; case E820_TYPE_ACPI: /* Fall-through: */ case E820_TYPE_NVS: /* Fall-through: */ case E820_TYPE_UNUSABLE: /* Fall-through: */ case E820_TYPE_PRAM: /* Fall-through: */ case E820_TYPE_PMEM: /* Fall-through: */ case E820_TYPE_RESERVED: /* Fall-through: */ case E820_TYPE_SOFT_RESERVED: /* Fall-through: */ default: return IORESOURCE_MEM; } } static unsigned long __init e820_type_to_iores_desc(struct e820_entry *entry) { switch (entry->type) { case E820_TYPE_ACPI: return IORES_DESC_ACPI_TABLES; case E820_TYPE_NVS: return IORES_DESC_ACPI_NV_STORAGE; case E820_TYPE_PMEM: return IORES_DESC_PERSISTENT_MEMORY; case E820_TYPE_PRAM: return IORES_DESC_PERSISTENT_MEMORY_LEGACY; case E820_TYPE_RESERVED: return IORES_DESC_RESERVED; case E820_TYPE_SOFT_RESERVED: return IORES_DESC_SOFT_RESERVED; case E820_TYPE_RESERVED_KERN: /* Fall-through: */ case E820_TYPE_RAM: /* Fall-through: */ case E820_TYPE_UNUSABLE: /* Fall-through: */ default: return IORES_DESC_NONE; } } static bool __init do_mark_busy(enum e820_type type, struct resource *res) { /* this is the legacy bios/dos rom-shadow + mmio region */ if (res->start < (1ULL<<20)) return true; /* * Treat persistent memory and other special memory ranges like * device memory, i.e. reserve it for exclusive use of a driver */ switch (type) { case E820_TYPE_RESERVED: case E820_TYPE_SOFT_RESERVED: case E820_TYPE_PRAM: case E820_TYPE_PMEM: return false; case E820_TYPE_RESERVED_KERN: case E820_TYPE_RAM: case E820_TYPE_ACPI: case E820_TYPE_NVS: case E820_TYPE_UNUSABLE: default: return true; } } /* * Mark E820 reserved areas as busy for the resource manager: */ static struct resource __initdata *e820_res; void __init e820__reserve_resources(void) { int i; struct resource *res; u64 end; res = memblock_alloc(sizeof(*res) * e820_table->nr_entries, SMP_CACHE_BYTES); if (!res) panic("%s: Failed to allocate %zu bytes\n", __func__, sizeof(*res) * e820_table->nr_entries); e820_res = res; for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = e820_table->entries + i; end = entry->addr + entry->size - 1; if (end != (resource_size_t)end) { res++; continue; } res->start = entry->addr; res->end = end; res->name = e820_type_to_string(entry); res->flags = e820_type_to_iomem_type(entry); res->desc = e820_type_to_iores_desc(entry); /* * Don't register the region that could be conflicted with * PCI device BAR resources and insert them later in * pcibios_resource_survey(): */ if (do_mark_busy(entry->type, res)) { res->flags |= IORESOURCE_BUSY; insert_resource(&iomem_resource, res); } res++; } /* Expose the bootloader-provided memory layout to the sysfs. */ for (i = 0; i < e820_table_firmware->nr_entries; i++) { struct e820_entry *entry = e820_table_firmware->entries + i; firmware_map_add_early(entry->addr, entry->addr + entry->size, e820_type_to_string(entry)); } } /* * How much should we pad the end of RAM, depending on where it is? */ static unsigned long __init ram_alignment(resource_size_t pos) { unsigned long mb = pos >> 20; /* To 64kB in the first megabyte */ if (!mb) return 64*1024; /* To 1MB in the first 16MB */ if (mb < 16) return 1024*1024; /* To 64MB for anything above that */ return 64*1024*1024; } #define MAX_RESOURCE_SIZE ((resource_size_t)-1) void __init e820__reserve_resources_late(void) { int i; struct resource *res; res = e820_res; for (i = 0; i < e820_table->nr_entries; i++) { if (!res->parent && res->end) insert_resource_expand_to_fit(&iomem_resource, res); res++; } /* * Try to bump up RAM regions to reasonable boundaries, to * avoid stolen RAM: */ for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; u64 start, end; if (entry->type != E820_TYPE_RAM) continue; start = entry->addr + entry->size; end = round_up(start, ram_alignment(start)) - 1; if (end > MAX_RESOURCE_SIZE) end = MAX_RESOURCE_SIZE; if (start >= end) continue; printk(KERN_DEBUG "e820: reserve RAM buffer [mem %#010llx-%#010llx]\n", start, end); reserve_region_with_split(&iomem_resource, start, end, "RAM buffer"); } } /* * Pass the firmware (bootloader) E820 map to the kernel and process it: */ char *__init e820__memory_setup_default(void) { char *who = "BIOS-e820"; /* * Try to copy the BIOS-supplied E820-map. * * Otherwise fake a memory map; one section from 0k->640k, * the next section from 1mb->appropriate_mem_k */ if (append_e820_table(boot_params.e820_table, boot_params.e820_entries) < 0) { u64 mem_size; /* Compare results from other methods and take the one that gives more RAM: */ if (boot_params.alt_mem_k < boot_params.screen_info.ext_mem_k) { mem_size = boot_params.screen_info.ext_mem_k; who = "BIOS-88"; } else { mem_size = boot_params.alt_mem_k; who = "BIOS-e801"; } e820_table->nr_entries = 0; e820__range_add(0, LOWMEMSIZE(), E820_TYPE_RAM); e820__range_add(HIGH_MEMORY, mem_size << 10, E820_TYPE_RAM); } /* We just appended a lot of ranges, sanitize the table: */ e820__update_table(e820_table); return who; } /* * Calls e820__memory_setup_default() in essence to pick up the firmware/bootloader * E820 map - with an optional platform quirk available for virtual platforms * to override this method of boot environment processing: */ void __init e820__memory_setup(void) { char *who; /* This is a firmware interface ABI - make sure we don't break it: */ BUILD_BUG_ON(sizeof(struct boot_e820_entry) != 20); who = x86_init.resources.memory_setup(); memcpy(e820_table_kexec, e820_table, sizeof(*e820_table_kexec)); memcpy(e820_table_firmware, e820_table, sizeof(*e820_table_firmware)); pr_info("BIOS-provided physical RAM map:\n"); e820__print_table(who); } void __init e820__memblock_setup(void) { int i; u64 end; /* * The bootstrap memblock region count maximum is 128 entries * (INIT_MEMBLOCK_REGIONS), but EFI might pass us more E820 entries * than that - so allow memblock resizing. * * This is safe, because this call happens pretty late during x86 setup, * so we know about reserved memory regions already. (This is important * so that memblock resizing does no stomp over reserved areas.) */ memblock_allow_resize(); for (i = 0; i < e820_table->nr_entries; i++) { struct e820_entry *entry = &e820_table->entries[i]; end = entry->addr + entry->size; if (end != (resource_size_t)end) continue; if (entry->type == E820_TYPE_SOFT_RESERVED) memblock_reserve(entry->addr, entry->size); if (entry->type != E820_TYPE_RAM && entry->type != E820_TYPE_RESERVED_KERN) continue; memblock_add(entry->addr, entry->size); } /* Throw away partial pages: */ memblock_trim_memory(PAGE_SIZE); memblock_dump_all(); }
linux-master
arch/x86/kernel/e820.c
// SPDX-License-Identifier: GPL-2.0-only /* * Shared support code for AMD K8 northbridges and derivatives. * Copyright 2006 Andi Kleen, SUSE Labs. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/types.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/export.h> #include <linux/spinlock.h> #include <linux/pci_ids.h> #include <asm/amd_nb.h> #define PCI_DEVICE_ID_AMD_17H_ROOT 0x1450 #define PCI_DEVICE_ID_AMD_17H_M10H_ROOT 0x15d0 #define PCI_DEVICE_ID_AMD_17H_M30H_ROOT 0x1480 #define PCI_DEVICE_ID_AMD_17H_M60H_ROOT 0x1630 #define PCI_DEVICE_ID_AMD_17H_MA0H_ROOT 0x14b5 #define PCI_DEVICE_ID_AMD_19H_M10H_ROOT 0x14a4 #define PCI_DEVICE_ID_AMD_19H_M40H_ROOT 0x14b5 #define PCI_DEVICE_ID_AMD_19H_M60H_ROOT 0x14d8 #define PCI_DEVICE_ID_AMD_19H_M70H_ROOT 0x14e8 #define PCI_DEVICE_ID_AMD_1AH_M00H_ROOT 0x153a #define PCI_DEVICE_ID_AMD_1AH_M20H_ROOT 0x1507 #define PCI_DEVICE_ID_AMD_MI200_ROOT 0x14bb #define PCI_DEVICE_ID_AMD_17H_DF_F4 0x1464 #define PCI_DEVICE_ID_AMD_17H_M10H_DF_F4 0x15ec #define PCI_DEVICE_ID_AMD_17H_M30H_DF_F4 0x1494 #define PCI_DEVICE_ID_AMD_17H_M60H_DF_F4 0x144c #define PCI_DEVICE_ID_AMD_17H_M70H_DF_F4 0x1444 #define PCI_DEVICE_ID_AMD_17H_MA0H_DF_F4 0x1728 #define PCI_DEVICE_ID_AMD_19H_DF_F4 0x1654 #define PCI_DEVICE_ID_AMD_19H_M10H_DF_F4 0x14b1 #define PCI_DEVICE_ID_AMD_19H_M40H_DF_F4 0x167d #define PCI_DEVICE_ID_AMD_19H_M50H_DF_F4 0x166e #define PCI_DEVICE_ID_AMD_19H_M60H_DF_F4 0x14e4 #define PCI_DEVICE_ID_AMD_19H_M70H_DF_F4 0x14f4 #define PCI_DEVICE_ID_AMD_19H_M78H_DF_F4 0x12fc #define PCI_DEVICE_ID_AMD_1AH_M00H_DF_F4 0x12c4 #define PCI_DEVICE_ID_AMD_MI200_DF_F4 0x14d4 /* Protect the PCI config register pairs used for SMN. */ static DEFINE_MUTEX(smn_mutex); static u32 *flush_words; static const struct pci_device_id amd_root_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M10H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M30H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M60H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_MA0H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M10H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M40H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M60H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M70H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_1AH_M00H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_1AH_M20H_ROOT) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_MI200_ROOT) }, {} }; #define PCI_DEVICE_ID_AMD_CNB17H_F4 0x1704 static const struct pci_device_id amd_nb_misc_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_K8_NB_MISC) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_10H_NB_MISC) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_15H_NB_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_15H_M10H_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_15H_M30H_NB_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_15H_M60H_NB_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_16H_NB_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_16H_M30H_NB_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M10H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M30H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M60H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_MA0H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CNB17H_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M70H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M10H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M40H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M50H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M60H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M70H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M78H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_1AH_M00H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_1AH_M20H_DF_F3) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_MI200_DF_F3) }, {} }; static const struct pci_device_id amd_nb_link_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_15H_NB_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_15H_M30H_NB_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_15H_M60H_NB_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_16H_NB_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_16H_M30H_NB_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M10H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M30H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M60H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_M70H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_17H_MA0H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M10H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M40H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_19H_M50H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CNB17H_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_1AH_M00H_DF_F4) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_MI200_DF_F4) }, {} }; static const struct pci_device_id hygon_root_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_HYGON, PCI_DEVICE_ID_AMD_17H_ROOT) }, {} }; static const struct pci_device_id hygon_nb_misc_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_HYGON, PCI_DEVICE_ID_AMD_17H_DF_F3) }, {} }; static const struct pci_device_id hygon_nb_link_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_HYGON, PCI_DEVICE_ID_AMD_17H_DF_F4) }, {} }; const struct amd_nb_bus_dev_range amd_nb_bus_dev_ranges[] __initconst = { { 0x00, 0x18, 0x20 }, { 0xff, 0x00, 0x20 }, { 0xfe, 0x00, 0x20 }, { } }; static struct amd_northbridge_info amd_northbridges; u16 amd_nb_num(void) { return amd_northbridges.num; } EXPORT_SYMBOL_GPL(amd_nb_num); bool amd_nb_has_feature(unsigned int feature) { return ((amd_northbridges.flags & feature) == feature); } EXPORT_SYMBOL_GPL(amd_nb_has_feature); struct amd_northbridge *node_to_amd_nb(int node) { return (node < amd_northbridges.num) ? &amd_northbridges.nb[node] : NULL; } EXPORT_SYMBOL_GPL(node_to_amd_nb); static struct pci_dev *next_northbridge(struct pci_dev *dev, const struct pci_device_id *ids) { do { dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, dev); if (!dev) break; } while (!pci_match_id(ids, dev)); return dev; } static int __amd_smn_rw(u16 node, u32 address, u32 *value, bool write) { struct pci_dev *root; int err = -ENODEV; if (node >= amd_northbridges.num) goto out; root = node_to_amd_nb(node)->root; if (!root) goto out; mutex_lock(&smn_mutex); err = pci_write_config_dword(root, 0x60, address); if (err) { pr_warn("Error programming SMN address 0x%x.\n", address); goto out_unlock; } err = (write ? pci_write_config_dword(root, 0x64, *value) : pci_read_config_dword(root, 0x64, value)); if (err) pr_warn("Error %s SMN address 0x%x.\n", (write ? "writing to" : "reading from"), address); out_unlock: mutex_unlock(&smn_mutex); out: return err; } int amd_smn_read(u16 node, u32 address, u32 *value) { return __amd_smn_rw(node, address, value, false); } EXPORT_SYMBOL_GPL(amd_smn_read); int amd_smn_write(u16 node, u32 address, u32 value) { return __amd_smn_rw(node, address, &value, true); } EXPORT_SYMBOL_GPL(amd_smn_write); static int amd_cache_northbridges(void) { const struct pci_device_id *misc_ids = amd_nb_misc_ids; const struct pci_device_id *link_ids = amd_nb_link_ids; const struct pci_device_id *root_ids = amd_root_ids; struct pci_dev *root, *misc, *link; struct amd_northbridge *nb; u16 roots_per_misc = 0; u16 misc_count = 0; u16 root_count = 0; u16 i, j; if (amd_northbridges.num) return 0; if (boot_cpu_data.x86_vendor == X86_VENDOR_HYGON) { root_ids = hygon_root_ids; misc_ids = hygon_nb_misc_ids; link_ids = hygon_nb_link_ids; } misc = NULL; while ((misc = next_northbridge(misc, misc_ids))) misc_count++; if (!misc_count) return -ENODEV; root = NULL; while ((root = next_northbridge(root, root_ids))) root_count++; if (root_count) { roots_per_misc = root_count / misc_count; /* * There should be _exactly_ N roots for each DF/SMN * interface. */ if (!roots_per_misc || (root_count % roots_per_misc)) { pr_info("Unsupported AMD DF/PCI configuration found\n"); return -ENODEV; } } nb = kcalloc(misc_count, sizeof(struct amd_northbridge), GFP_KERNEL); if (!nb) return -ENOMEM; amd_northbridges.nb = nb; amd_northbridges.num = misc_count; link = misc = root = NULL; for (i = 0; i < amd_northbridges.num; i++) { node_to_amd_nb(i)->root = root = next_northbridge(root, root_ids); node_to_amd_nb(i)->misc = misc = next_northbridge(misc, misc_ids); node_to_amd_nb(i)->link = link = next_northbridge(link, link_ids); /* * If there are more PCI root devices than data fabric/ * system management network interfaces, then the (N) * PCI roots per DF/SMN interface are functionally the * same (for DF/SMN access) and N-1 are redundant. N-1 * PCI roots should be skipped per DF/SMN interface so * the following DF/SMN interfaces get mapped to * correct PCI roots. */ for (j = 1; j < roots_per_misc; j++) root = next_northbridge(root, root_ids); } if (amd_gart_present()) amd_northbridges.flags |= AMD_NB_GART; /* * Check for L3 cache presence. */ if (!cpuid_edx(0x80000006)) return 0; /* * Some CPU families support L3 Cache Index Disable. There are some * limitations because of E382 and E388 on family 0x10. */ if (boot_cpu_data.x86 == 0x10 && boot_cpu_data.x86_model >= 0x8 && (boot_cpu_data.x86_model > 0x9 || boot_cpu_data.x86_stepping >= 0x1)) amd_northbridges.flags |= AMD_NB_L3_INDEX_DISABLE; if (boot_cpu_data.x86 == 0x15) amd_northbridges.flags |= AMD_NB_L3_INDEX_DISABLE; /* L3 cache partitioning is supported on family 0x15 */ if (boot_cpu_data.x86 == 0x15) amd_northbridges.flags |= AMD_NB_L3_PARTITIONING; return 0; } /* * Ignores subdevice/subvendor but as far as I can figure out * they're useless anyways */ bool __init early_is_amd_nb(u32 device) { const struct pci_device_id *misc_ids = amd_nb_misc_ids; const struct pci_device_id *id; u32 vendor = device & 0xffff; if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD && boot_cpu_data.x86_vendor != X86_VENDOR_HYGON) return false; if (boot_cpu_data.x86_vendor == X86_VENDOR_HYGON) misc_ids = hygon_nb_misc_ids; device >>= 16; for (id = misc_ids; id->vendor; id++) if (vendor == id->vendor && device == id->device) return true; return false; } struct resource *amd_get_mmconfig_range(struct resource *res) { u32 address; u64 base, msr; unsigned int segn_busn_bits; if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD && boot_cpu_data.x86_vendor != X86_VENDOR_HYGON) return NULL; /* assume all cpus from fam10h have mmconfig */ if (boot_cpu_data.x86 < 0x10) return NULL; address = MSR_FAM10H_MMIO_CONF_BASE; rdmsrl(address, msr); /* mmconfig is not enabled */ if (!(msr & FAM10H_MMIO_CONF_ENABLE)) return NULL; base = msr & (FAM10H_MMIO_CONF_BASE_MASK<<FAM10H_MMIO_CONF_BASE_SHIFT); segn_busn_bits = (msr >> FAM10H_MMIO_CONF_BUSRANGE_SHIFT) & FAM10H_MMIO_CONF_BUSRANGE_MASK; res->flags = IORESOURCE_MEM; res->start = base; res->end = base + (1ULL<<(segn_busn_bits + 20)) - 1; return res; } int amd_get_subcaches(int cpu) { struct pci_dev *link = node_to_amd_nb(topology_die_id(cpu))->link; unsigned int mask; if (!amd_nb_has_feature(AMD_NB_L3_PARTITIONING)) return 0; pci_read_config_dword(link, 0x1d4, &mask); return (mask >> (4 * cpu_data(cpu).cpu_core_id)) & 0xf; } int amd_set_subcaches(int cpu, unsigned long mask) { static unsigned int reset, ban; struct amd_northbridge *nb = node_to_amd_nb(topology_die_id(cpu)); unsigned int reg; int cuid; if (!amd_nb_has_feature(AMD_NB_L3_PARTITIONING) || mask > 0xf) return -EINVAL; /* if necessary, collect reset state of L3 partitioning and BAN mode */ if (reset == 0) { pci_read_config_dword(nb->link, 0x1d4, &reset); pci_read_config_dword(nb->misc, 0x1b8, &ban); ban &= 0x180000; } /* deactivate BAN mode if any subcaches are to be disabled */ if (mask != 0xf) { pci_read_config_dword(nb->misc, 0x1b8, &reg); pci_write_config_dword(nb->misc, 0x1b8, reg & ~0x180000); } cuid = cpu_data(cpu).cpu_core_id; mask <<= 4 * cuid; mask |= (0xf ^ (1 << cuid)) << 26; pci_write_config_dword(nb->link, 0x1d4, mask); /* reset BAN mode if L3 partitioning returned to reset state */ pci_read_config_dword(nb->link, 0x1d4, &reg); if (reg == reset) { pci_read_config_dword(nb->misc, 0x1b8, &reg); reg &= ~0x180000; pci_write_config_dword(nb->misc, 0x1b8, reg | ban); } return 0; } static void amd_cache_gart(void) { u16 i; if (!amd_nb_has_feature(AMD_NB_GART)) return; flush_words = kmalloc_array(amd_northbridges.num, sizeof(u32), GFP_KERNEL); if (!flush_words) { amd_northbridges.flags &= ~AMD_NB_GART; pr_notice("Cannot initialize GART flush words, GART support disabled\n"); return; } for (i = 0; i != amd_northbridges.num; i++) pci_read_config_dword(node_to_amd_nb(i)->misc, 0x9c, &flush_words[i]); } void amd_flush_garts(void) { int flushed, i; unsigned long flags; static DEFINE_SPINLOCK(gart_lock); if (!amd_nb_has_feature(AMD_NB_GART)) return; /* * Avoid races between AGP and IOMMU. In theory it's not needed * but I'm not sure if the hardware won't lose flush requests * when another is pending. This whole thing is so expensive anyways * that it doesn't matter to serialize more. -AK */ spin_lock_irqsave(&gart_lock, flags); flushed = 0; for (i = 0; i < amd_northbridges.num; i++) { pci_write_config_dword(node_to_amd_nb(i)->misc, 0x9c, flush_words[i] | 1); flushed++; } for (i = 0; i < amd_northbridges.num; i++) { u32 w; /* Make sure the hardware actually executed the flush*/ for (;;) { pci_read_config_dword(node_to_amd_nb(i)->misc, 0x9c, &w); if (!(w & 1)) break; cpu_relax(); } } spin_unlock_irqrestore(&gart_lock, flags); if (!flushed) pr_notice("nothing to flush?\n"); } EXPORT_SYMBOL_GPL(amd_flush_garts); static void __fix_erratum_688(void *info) { #define MSR_AMD64_IC_CFG 0xC0011021 msr_set_bit(MSR_AMD64_IC_CFG, 3); msr_set_bit(MSR_AMD64_IC_CFG, 14); } /* Apply erratum 688 fix so machines without a BIOS fix work. */ static __init void fix_erratum_688(void) { struct pci_dev *F4; u32 val; if (boot_cpu_data.x86 != 0x14) return; if (!amd_northbridges.num) return; F4 = node_to_amd_nb(0)->link; if (!F4) return; if (pci_read_config_dword(F4, 0x164, &val)) return; if (val & BIT(2)) return; on_each_cpu(__fix_erratum_688, NULL, 0); pr_info("x86/cpu/AMD: CPU erratum 688 worked around\n"); } static __init int init_amd_nbs(void) { amd_cache_northbridges(); amd_cache_gart(); fix_erratum_688(); return 0; } /* This has to go after the PCI subsystem */ fs_initcall(init_amd_nbs);
linux-master
arch/x86/kernel/amd_nb.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/mm.h> #include <linux/sched.h> #include <linux/sched/debug.h> #include <linux/init_task.h> #include <linux/fs.h> #include <linux/uaccess.h> #include <asm/processor.h> #include <asm/desc.h> #include <asm/traps.h> #include <asm/doublefault.h> #define ptr_ok(x) ((x) > PAGE_OFFSET && (x) < PAGE_OFFSET + MAXMEM) #define TSS(x) this_cpu_read(cpu_tss_rw.x86_tss.x) static void set_df_gdt_entry(unsigned int cpu); /* * Called by double_fault with CR0.TS and EFLAGS.NT cleared. The CPU thinks * we're running the doublefault task. Cannot return. */ asmlinkage noinstr void __noreturn doublefault_shim(void) { unsigned long cr2; struct pt_regs regs; BUILD_BUG_ON(sizeof(struct doublefault_stack) != PAGE_SIZE); cr2 = native_read_cr2(); /* Reset back to the normal kernel task. */ force_reload_TR(); set_df_gdt_entry(smp_processor_id()); trace_hardirqs_off(); /* * Fill in pt_regs. A downside of doing this in C is that the unwinder * won't see it (no ENCODE_FRAME_POINTER), so a nested stack dump * won't successfully unwind to the source of the double fault. * The main dump from exc_double_fault() is fine, though, since it * uses these regs directly. * * If anyone ever cares, this could be moved to asm. */ regs.ss = TSS(ss); regs.__ssh = 0; regs.sp = TSS(sp); regs.flags = TSS(flags); regs.cs = TSS(cs); /* We won't go through the entry asm, so we can leave __csh as 0. */ regs.__csh = 0; regs.ip = TSS(ip); regs.orig_ax = 0; regs.gs = TSS(gs); regs.__gsh = 0; regs.fs = TSS(fs); regs.__fsh = 0; regs.es = TSS(es); regs.__esh = 0; regs.ds = TSS(ds); regs.__dsh = 0; regs.ax = TSS(ax); regs.bp = TSS(bp); regs.di = TSS(di); regs.si = TSS(si); regs.dx = TSS(dx); regs.cx = TSS(cx); regs.bx = TSS(bx); exc_double_fault(&regs, 0, cr2); /* * x86_32 does not save the original CR3 anywhere on a task switch. * This means that, even if we wanted to return, we would need to find * some way to reconstruct CR3. We could make a credible guess based * on cpu_tlbstate, but that would be racy and would not account for * PTI. */ panic("cannot return from double fault\n"); } DEFINE_PER_CPU_PAGE_ALIGNED(struct doublefault_stack, doublefault_stack) = { .tss = { /* * No sp0 or ss0 -- we never run CPL != 0 with this TSS * active. sp is filled in later. */ .ldt = 0, .io_bitmap_base = IO_BITMAP_OFFSET_INVALID, .ip = (unsigned long) asm_exc_double_fault, .flags = X86_EFLAGS_FIXED, .es = __USER_DS, .cs = __KERNEL_CS, .ss = __KERNEL_DS, .ds = __USER_DS, .fs = __KERNEL_PERCPU, .gs = 0, .__cr3 = __pa_nodebug(swapper_pg_dir), }, }; static void set_df_gdt_entry(unsigned int cpu) { /* Set up doublefault TSS pointer in the GDT */ __set_tss_desc(cpu, GDT_ENTRY_DOUBLEFAULT_TSS, &get_cpu_entry_area(cpu)->doublefault_stack.tss); } void doublefault_init_cpu_tss(void) { unsigned int cpu = smp_processor_id(); struct cpu_entry_area *cea = get_cpu_entry_area(cpu); /* * The linker isn't smart enough to initialize percpu variables that * point to other places in percpu space. */ this_cpu_write(doublefault_stack.tss.sp, (unsigned long)&cea->doublefault_stack.stack + sizeof(doublefault_stack.stack)); set_df_gdt_entry(cpu); }
linux-master
arch/x86/kernel/doublefault_32.c
// SPDX-License-Identifier: GPL-2.0-only /* ----------------------------------------------------------------------- * * * Copyright 2014 Intel Corporation; author: H. Peter Anvin * * ----------------------------------------------------------------------- */ /* * The IRET instruction, when returning to a 16-bit segment, only * restores the bottom 16 bits of the user space stack pointer. This * causes some 16-bit software to break, but it also leaks kernel state * to user space. * * This works around this by creating percpu "ministacks", each of which * is mapped 2^16 times 64K apart. When we detect that the return SS is * on the LDT, we copy the IRET frame to the ministack and use the * relevant alias to return to userspace. The ministacks are mapped * readonly, so if the IRET fault we promote #GP to #DF which is an IST * vector and thus has its own stack; we then do the fixup in the #DF * handler. * * This file sets up the ministacks and the related page tables. The * actual ministack invocation is in entry_64.S. */ #include <linux/init.h> #include <linux/init_task.h> #include <linux/kernel.h> #include <linux/percpu.h> #include <linux/gfp.h> #include <linux/random.h> #include <linux/pgtable.h> #include <asm/pgalloc.h> #include <asm/setup.h> #include <asm/espfix.h> /* * Note: we only need 6*8 = 48 bytes for the espfix stack, but round * it up to a cache line to avoid unnecessary sharing. */ #define ESPFIX_STACK_SIZE (8*8UL) #define ESPFIX_STACKS_PER_PAGE (PAGE_SIZE/ESPFIX_STACK_SIZE) /* There is address space for how many espfix pages? */ #define ESPFIX_PAGE_SPACE (1UL << (P4D_SHIFT-PAGE_SHIFT-16)) #define ESPFIX_MAX_CPUS (ESPFIX_STACKS_PER_PAGE * ESPFIX_PAGE_SPACE) #if CONFIG_NR_CPUS > ESPFIX_MAX_CPUS # error "Need more virtual address space for the ESPFIX hack" #endif #define PGALLOC_GFP (GFP_KERNEL | __GFP_ZERO) /* This contains the *bottom* address of the espfix stack */ DEFINE_PER_CPU_READ_MOSTLY(unsigned long, espfix_stack); DEFINE_PER_CPU_READ_MOSTLY(unsigned long, espfix_waddr); /* Initialization mutex - should this be a spinlock? */ static DEFINE_MUTEX(espfix_init_mutex); /* Page allocation bitmap - each page serves ESPFIX_STACKS_PER_PAGE CPUs */ #define ESPFIX_MAX_PAGES DIV_ROUND_UP(CONFIG_NR_CPUS, ESPFIX_STACKS_PER_PAGE) static void *espfix_pages[ESPFIX_MAX_PAGES]; static __page_aligned_bss pud_t espfix_pud_page[PTRS_PER_PUD] __aligned(PAGE_SIZE); static unsigned int page_random, slot_random; /* * This returns the bottom address of the espfix stack for a specific CPU. * The math allows for a non-power-of-two ESPFIX_STACK_SIZE, in which case * we have to account for some amount of padding at the end of each page. */ static inline unsigned long espfix_base_addr(unsigned int cpu) { unsigned long page, slot; unsigned long addr; page = (cpu / ESPFIX_STACKS_PER_PAGE) ^ page_random; slot = (cpu + slot_random) % ESPFIX_STACKS_PER_PAGE; addr = (page << PAGE_SHIFT) + (slot * ESPFIX_STACK_SIZE); addr = (addr & 0xffffUL) | ((addr & ~0xffffUL) << 16); addr += ESPFIX_BASE_ADDR; return addr; } #define PTE_STRIDE (65536/PAGE_SIZE) #define ESPFIX_PTE_CLONES (PTRS_PER_PTE/PTE_STRIDE) #define ESPFIX_PMD_CLONES PTRS_PER_PMD #define ESPFIX_PUD_CLONES (65536/(ESPFIX_PTE_CLONES*ESPFIX_PMD_CLONES)) #define PGTABLE_PROT ((_KERNPG_TABLE & ~_PAGE_RW) | _PAGE_NX) static void init_espfix_random(void) { unsigned long rand = get_random_long(); slot_random = rand % ESPFIX_STACKS_PER_PAGE; page_random = (rand / ESPFIX_STACKS_PER_PAGE) & (ESPFIX_PAGE_SPACE - 1); } void __init init_espfix_bsp(void) { pgd_t *pgd; p4d_t *p4d; /* Install the espfix pud into the kernel page directory */ pgd = &init_top_pgt[pgd_index(ESPFIX_BASE_ADDR)]; p4d = p4d_alloc(&init_mm, pgd, ESPFIX_BASE_ADDR); p4d_populate(&init_mm, p4d, espfix_pud_page); /* Randomize the locations */ init_espfix_random(); /* The rest is the same as for any other processor */ init_espfix_ap(0); } void init_espfix_ap(int cpu) { unsigned int page; unsigned long addr; pud_t pud, *pud_p; pmd_t pmd, *pmd_p; pte_t pte, *pte_p; int n, node; void *stack_page; pteval_t ptemask; /* We only have to do this once... */ if (likely(per_cpu(espfix_stack, cpu))) return; /* Already initialized */ addr = espfix_base_addr(cpu); page = cpu/ESPFIX_STACKS_PER_PAGE; /* Did another CPU already set this up? */ stack_page = READ_ONCE(espfix_pages[page]); if (likely(stack_page)) goto done; mutex_lock(&espfix_init_mutex); /* Did we race on the lock? */ stack_page = READ_ONCE(espfix_pages[page]); if (stack_page) goto unlock_done; node = cpu_to_node(cpu); ptemask = __supported_pte_mask; pud_p = &espfix_pud_page[pud_index(addr)]; pud = *pud_p; if (!pud_present(pud)) { struct page *page = alloc_pages_node(node, PGALLOC_GFP, 0); pmd_p = (pmd_t *)page_address(page); pud = __pud(__pa(pmd_p) | (PGTABLE_PROT & ptemask)); paravirt_alloc_pmd(&init_mm, __pa(pmd_p) >> PAGE_SHIFT); for (n = 0; n < ESPFIX_PUD_CLONES; n++) set_pud(&pud_p[n], pud); } pmd_p = pmd_offset(&pud, addr); pmd = *pmd_p; if (!pmd_present(pmd)) { struct page *page = alloc_pages_node(node, PGALLOC_GFP, 0); pte_p = (pte_t *)page_address(page); pmd = __pmd(__pa(pte_p) | (PGTABLE_PROT & ptemask)); paravirt_alloc_pte(&init_mm, __pa(pte_p) >> PAGE_SHIFT); for (n = 0; n < ESPFIX_PMD_CLONES; n++) set_pmd(&pmd_p[n], pmd); } pte_p = pte_offset_kernel(&pmd, addr); stack_page = page_address(alloc_pages_node(node, GFP_KERNEL, 0)); /* * __PAGE_KERNEL_* includes _PAGE_GLOBAL, which we want since * this is mapped to userspace. */ pte = __pte(__pa(stack_page) | ((__PAGE_KERNEL_RO | _PAGE_ENC) & ptemask)); for (n = 0; n < ESPFIX_PTE_CLONES; n++) set_pte(&pte_p[n*PTE_STRIDE], pte); /* Job is done for this CPU and any CPU which shares this page */ WRITE_ONCE(espfix_pages[page], stack_page); unlock_done: mutex_unlock(&espfix_init_mutex); done: per_cpu(espfix_stack, cpu) = addr; per_cpu(espfix_waddr, cpu) = (unsigned long)stack_page + (addr & ~PAGE_MASK); }
linux-master
arch/x86/kernel/espfix_64.c
// SPDX-License-Identifier: GPL-2.0-or-later /* ----------------------------------------------------------------------- * * * Copyright 2000-2008 H. Peter Anvin - All Rights Reserved * Copyright 2009 Intel Corporation; author: H. Peter Anvin * * ----------------------------------------------------------------------- */ /* * x86 MSR access device * * This device is accessed by lseek() to the appropriate register number * and then read/write in chunks of 8 bytes. A larger size means multiple * reads or writes of the same register. * * This driver uses /dev/cpu/%d/msr where %d is the minor number, and on * an SMP box will direct the access to CPU %d. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/smp.h> #include <linux/major.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/cpu.h> #include <linux/notifier.h> #include <linux/uaccess.h> #include <linux/gfp.h> #include <linux/security.h> #include <asm/cpufeature.h> #include <asm/msr.h> static enum cpuhp_state cpuhp_msr_state; enum allow_write_msrs { MSR_WRITES_ON, MSR_WRITES_OFF, MSR_WRITES_DEFAULT, }; static enum allow_write_msrs allow_writes = MSR_WRITES_DEFAULT; static ssize_t msr_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { u32 __user *tmp = (u32 __user *) buf; u32 data[2]; u32 reg = *ppos; int cpu = iminor(file_inode(file)); int err = 0; ssize_t bytes = 0; if (count % 8) return -EINVAL; /* Invalid chunk size */ for (; count; count -= 8) { err = rdmsr_safe_on_cpu(cpu, reg, &data[0], &data[1]); if (err) break; if (copy_to_user(tmp, &data, 8)) { err = -EFAULT; break; } tmp += 2; bytes += 8; } return bytes ? bytes : err; } static int filter_write(u32 reg) { /* * MSRs writes usually happen all at once, and can easily saturate kmsg. * Only allow one message every 30 seconds. * * It's possible to be smarter here and do it (for example) per-MSR, but * it would certainly be more complex, and this is enough at least to * avoid saturating the ring buffer. */ static DEFINE_RATELIMIT_STATE(fw_rs, 30 * HZ, 1); switch (allow_writes) { case MSR_WRITES_ON: return 0; case MSR_WRITES_OFF: return -EPERM; default: break; } if (!__ratelimit(&fw_rs)) return 0; pr_warn("Write to unrecognized MSR 0x%x by %s (pid: %d).\n", reg, current->comm, current->pid); pr_warn("See https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/about for details.\n"); return 0; } static ssize_t msr_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { const u32 __user *tmp = (const u32 __user *)buf; u32 data[2]; u32 reg = *ppos; int cpu = iminor(file_inode(file)); int err = 0; ssize_t bytes = 0; err = security_locked_down(LOCKDOWN_MSR); if (err) return err; err = filter_write(reg); if (err) return err; if (count % 8) return -EINVAL; /* Invalid chunk size */ for (; count; count -= 8) { if (copy_from_user(&data, tmp, 8)) { err = -EFAULT; break; } add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK); err = wrmsr_safe_on_cpu(cpu, reg, data[0], data[1]); if (err) break; tmp += 2; bytes += 8; } return bytes ? bytes : err; } static long msr_ioctl(struct file *file, unsigned int ioc, unsigned long arg) { u32 __user *uregs = (u32 __user *)arg; u32 regs[8]; int cpu = iminor(file_inode(file)); int err; switch (ioc) { case X86_IOC_RDMSR_REGS: if (!(file->f_mode & FMODE_READ)) { err = -EBADF; break; } if (copy_from_user(&regs, uregs, sizeof(regs))) { err = -EFAULT; break; } err = rdmsr_safe_regs_on_cpu(cpu, regs); if (err) break; if (copy_to_user(uregs, &regs, sizeof(regs))) err = -EFAULT; break; case X86_IOC_WRMSR_REGS: if (!(file->f_mode & FMODE_WRITE)) { err = -EBADF; break; } if (copy_from_user(&regs, uregs, sizeof(regs))) { err = -EFAULT; break; } err = security_locked_down(LOCKDOWN_MSR); if (err) break; err = filter_write(regs[1]); if (err) return err; add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK); err = wrmsr_safe_regs_on_cpu(cpu, regs); if (err) break; if (copy_to_user(uregs, &regs, sizeof(regs))) err = -EFAULT; break; default: err = -ENOTTY; break; } return err; } static int msr_open(struct inode *inode, struct file *file) { unsigned int cpu = iminor(file_inode(file)); struct cpuinfo_x86 *c; if (!capable(CAP_SYS_RAWIO)) return -EPERM; if (cpu >= nr_cpu_ids || !cpu_online(cpu)) return -ENXIO; /* No such CPU */ c = &cpu_data(cpu); if (!cpu_has(c, X86_FEATURE_MSR)) return -EIO; /* MSR not supported */ return 0; } /* * File operations we support */ static const struct file_operations msr_fops = { .owner = THIS_MODULE, .llseek = no_seek_end_llseek, .read = msr_read, .write = msr_write, .open = msr_open, .unlocked_ioctl = msr_ioctl, .compat_ioctl = msr_ioctl, }; static char *msr_devnode(const struct device *dev, umode_t *mode) { return kasprintf(GFP_KERNEL, "cpu/%u/msr", MINOR(dev->devt)); } static const struct class msr_class = { .name = "msr", .devnode = msr_devnode, }; static int msr_device_create(unsigned int cpu) { struct device *dev; dev = device_create(&msr_class, NULL, MKDEV(MSR_MAJOR, cpu), NULL, "msr%d", cpu); return PTR_ERR_OR_ZERO(dev); } static int msr_device_destroy(unsigned int cpu) { device_destroy(&msr_class, MKDEV(MSR_MAJOR, cpu)); return 0; } static int __init msr_init(void) { int err; if (__register_chrdev(MSR_MAJOR, 0, NR_CPUS, "cpu/msr", &msr_fops)) { pr_err("unable to get major %d for msr\n", MSR_MAJOR); return -EBUSY; } err = class_register(&msr_class); if (err) goto out_chrdev; err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/msr:online", msr_device_create, msr_device_destroy); if (err < 0) goto out_class; cpuhp_msr_state = err; return 0; out_class: class_unregister(&msr_class); out_chrdev: __unregister_chrdev(MSR_MAJOR, 0, NR_CPUS, "cpu/msr"); return err; } module_init(msr_init); static void __exit msr_exit(void) { cpuhp_remove_state(cpuhp_msr_state); class_unregister(&msr_class); __unregister_chrdev(MSR_MAJOR, 0, NR_CPUS, "cpu/msr"); } module_exit(msr_exit) static int set_allow_writes(const char *val, const struct kernel_param *cp) { /* val is NUL-terminated, see kernfs_fop_write() */ char *s = strstrip((char *)val); if (!strcmp(s, "on")) allow_writes = MSR_WRITES_ON; else if (!strcmp(s, "off")) allow_writes = MSR_WRITES_OFF; else allow_writes = MSR_WRITES_DEFAULT; return 0; } static int get_allow_writes(char *buf, const struct kernel_param *kp) { const char *res; switch (allow_writes) { case MSR_WRITES_ON: res = "on"; break; case MSR_WRITES_OFF: res = "off"; break; default: res = "default"; break; } return sprintf(buf, "%s\n", res); } static const struct kernel_param_ops allow_writes_ops = { .set = set_allow_writes, .get = get_allow_writes }; module_param_cb(allow_writes, &allow_writes_ops, NULL, 0600); MODULE_AUTHOR("H. Peter Anvin <[email protected]>"); MODULE_DESCRIPTION("x86 generic MSR driver"); MODULE_LICENSE("GPL");
linux-master
arch/x86/kernel/msr.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/sched.h> #include <linux/ftrace.h> #include <asm/ptrace.h> #include <asm/bitops.h> #include <asm/stacktrace.h> #include <asm/unwind.h> unsigned long unwind_get_return_address(struct unwind_state *state) { unsigned long addr; if (unwind_done(state)) return 0; addr = READ_ONCE_NOCHECK(*state->sp); return unwind_recover_ret_addr(state, addr, state->sp); } EXPORT_SYMBOL_GPL(unwind_get_return_address); unsigned long *unwind_get_return_address_ptr(struct unwind_state *state) { return NULL; } bool unwind_next_frame(struct unwind_state *state) { struct stack_info *info = &state->stack_info; if (unwind_done(state)) return false; do { for (state->sp++; state->sp < info->end; state->sp++) { unsigned long addr = READ_ONCE_NOCHECK(*state->sp); if (__kernel_text_address(addr)) return true; } state->sp = PTR_ALIGN(info->next_sp, sizeof(long)); } while (!get_stack_info(state->sp, state->task, info, &state->stack_mask)); return false; } EXPORT_SYMBOL_GPL(unwind_next_frame); void __unwind_start(struct unwind_state *state, struct task_struct *task, struct pt_regs *regs, unsigned long *first_frame) { memset(state, 0, sizeof(*state)); state->task = task; state->sp = PTR_ALIGN(first_frame, sizeof(long)); get_stack_info(first_frame, state->task, &state->stack_info, &state->stack_mask); /* * The caller can provide the address of the first frame directly * (first_frame) or indirectly (regs->sp) to indicate which stack frame * to start unwinding at. Skip ahead until we reach it. */ if (!unwind_done(state) && (!on_stack(&state->stack_info, first_frame, sizeof(long)) || !__kernel_text_address(*first_frame))) unwind_next_frame(state); } EXPORT_SYMBOL_GPL(__unwind_start);
linux-master
arch/x86/kernel/unwind_guess.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/kernel.h> #include <linux/init.h> #include <linux/memblock.h> #include <asm/setup.h> #include <asm/bios_ebda.h> /* * This function reserves all conventional PC system BIOS related * firmware memory areas (some of which are data, some of which * are code), that must not be used by the kernel as available * RAM. * * The BIOS places the EBDA/XBDA at the top of conventional * memory, and usually decreases the reported amount of * conventional memory (int 0x12) too. * * This means that as a first approximation on most systems we can * guess the reserved BIOS area by looking at the low BIOS RAM size * value and assume that everything above that value (up to 1MB) is * reserved. * * But life in firmware country is not that simple: * * - This code also contains a quirk for Dell systems that neglect * to reserve the EBDA area in the 'RAM size' value ... * * - The same quirk also avoids a problem with the AMD768MPX * chipset: reserve a page before VGA to prevent PCI prefetch * into it (errata #56). (Usually the page is reserved anyways, * unless you have no PS/2 mouse plugged in.) * * - Plus paravirt systems don't have a reliable value in the * 'BIOS RAM size' pointer we can rely on, so we must quirk * them too. * * Due to those various problems this function is deliberately * very conservative and tries to err on the side of reserving * too much, to not risk reserving too little. * * Losing a small amount of memory in the bottom megabyte is * rarely a problem, as long as we have enough memory to install * the SMP bootup trampoline which *must* be in this area. * * Using memory that is in use by the BIOS or by some DMA device * the BIOS didn't shut down *is* a big problem to the kernel, * obviously. */ #define BIOS_RAM_SIZE_KB_PTR 0x413 #define BIOS_START_MIN 0x20000U /* 128K, less than this is insane */ #define BIOS_START_MAX 0x9f000U /* 640K, absolute maximum */ void __init reserve_bios_regions(void) { unsigned int bios_start, ebda_start; /* * NOTE: In a paravirtual environment the BIOS reserved * area is absent. We'll just have to assume that the * paravirt case can handle memory setup correctly, * without our help. */ if (!x86_platform.legacy.reserve_bios_regions) return; /* * BIOS RAM size is encoded in kilobytes, convert it * to bytes to get a first guess at where the BIOS * firmware area starts: */ bios_start = *(unsigned short *)__va(BIOS_RAM_SIZE_KB_PTR); bios_start <<= 10; /* * If bios_start is less than 128K, assume it is bogus * and bump it up to 640K. Similarly, if bios_start is above 640K, * don't trust it. */ if (bios_start < BIOS_START_MIN || bios_start > BIOS_START_MAX) bios_start = BIOS_START_MAX; /* Get the start address of the EBDA page: */ ebda_start = get_bios_ebda(); /* * If the EBDA start address is sane and is below the BIOS region, * then also reserve everything from the EBDA start address up to * the BIOS region. */ if (ebda_start >= BIOS_START_MIN && ebda_start < bios_start) bios_start = ebda_start; /* Reserve all memory between bios_start and the 1MB mark: */ memblock_reserve(bios_start, 0x100000 - bios_start); }
linux-master
arch/x86/kernel/ebda.c
// SPDX-License-Identifier: GPL-2.0-only #define pr_fmt(fmt) "SMP alternatives: " fmt #include <linux/module.h> #include <linux/sched.h> #include <linux/perf_event.h> #include <linux/mutex.h> #include <linux/list.h> #include <linux/stringify.h> #include <linux/highmem.h> #include <linux/mm.h> #include <linux/vmalloc.h> #include <linux/memory.h> #include <linux/stop_machine.h> #include <linux/slab.h> #include <linux/kdebug.h> #include <linux/kprobes.h> #include <linux/mmu_context.h> #include <linux/bsearch.h> #include <linux/sync_core.h> #include <asm/text-patching.h> #include <asm/alternative.h> #include <asm/sections.h> #include <asm/mce.h> #include <asm/nmi.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> #include <asm/insn.h> #include <asm/io.h> #include <asm/fixmap.h> #include <asm/paravirt.h> #include <asm/asm-prototypes.h> int __read_mostly alternatives_patched; EXPORT_SYMBOL_GPL(alternatives_patched); #define MAX_PATCH_LEN (255-1) #define DA_ALL (~0) #define DA_ALT 0x01 #define DA_RET 0x02 #define DA_RETPOLINE 0x04 #define DA_ENDBR 0x08 #define DA_SMP 0x10 static unsigned int __initdata_or_module debug_alternative; static int __init debug_alt(char *str) { if (str && *str == '=') str++; if (!str || kstrtouint(str, 0, &debug_alternative)) debug_alternative = DA_ALL; return 1; } __setup("debug-alternative", debug_alt); static int noreplace_smp; static int __init setup_noreplace_smp(char *str) { noreplace_smp = 1; return 1; } __setup("noreplace-smp", setup_noreplace_smp); #define DPRINTK(type, fmt, args...) \ do { \ if (debug_alternative & DA_##type) \ printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \ } while (0) #define DUMP_BYTES(type, buf, len, fmt, args...) \ do { \ if (unlikely(debug_alternative & DA_##type)) { \ int j; \ \ if (!(len)) \ break; \ \ printk(KERN_DEBUG pr_fmt(fmt), ##args); \ for (j = 0; j < (len) - 1; j++) \ printk(KERN_CONT "%02hhx ", buf[j]); \ printk(KERN_CONT "%02hhx\n", buf[j]); \ } \ } while (0) static const unsigned char x86nops[] = { BYTES_NOP1, BYTES_NOP2, BYTES_NOP3, BYTES_NOP4, BYTES_NOP5, BYTES_NOP6, BYTES_NOP7, BYTES_NOP8, #ifdef CONFIG_64BIT BYTES_NOP9, BYTES_NOP10, BYTES_NOP11, #endif }; const unsigned char * const x86_nops[ASM_NOP_MAX+1] = { NULL, x86nops, x86nops + 1, x86nops + 1 + 2, x86nops + 1 + 2 + 3, x86nops + 1 + 2 + 3 + 4, x86nops + 1 + 2 + 3 + 4 + 5, x86nops + 1 + 2 + 3 + 4 + 5 + 6, x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7, #ifdef CONFIG_64BIT x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, #endif }; /* * Fill the buffer with a single effective instruction of size @len. * * In order not to issue an ORC stack depth tracking CFI entry (Call Frame Info) * for every single-byte NOP, try to generate the maximally available NOP of * size <= ASM_NOP_MAX such that only a single CFI entry is generated (vs one for * each single-byte NOPs). If @len to fill out is > ASM_NOP_MAX, pad with INT3 and * *jump* over instead of executing long and daft NOPs. */ static void __init_or_module add_nop(u8 *instr, unsigned int len) { u8 *target = instr + len; if (!len) return; if (len <= ASM_NOP_MAX) { memcpy(instr, x86_nops[len], len); return; } if (len < 128) { __text_gen_insn(instr, JMP8_INSN_OPCODE, instr, target, JMP8_INSN_SIZE); instr += JMP8_INSN_SIZE; } else { __text_gen_insn(instr, JMP32_INSN_OPCODE, instr, target, JMP32_INSN_SIZE); instr += JMP32_INSN_SIZE; } for (;instr < target; instr++) *instr = INT3_INSN_OPCODE; } extern s32 __retpoline_sites[], __retpoline_sites_end[]; extern s32 __return_sites[], __return_sites_end[]; extern s32 __cfi_sites[], __cfi_sites_end[]; extern s32 __ibt_endbr_seal[], __ibt_endbr_seal_end[]; extern struct alt_instr __alt_instructions[], __alt_instructions_end[]; extern s32 __smp_locks[], __smp_locks_end[]; void text_poke_early(void *addr, const void *opcode, size_t len); /* * Matches NOP and NOPL, not any of the other possible NOPs. */ static bool insn_is_nop(struct insn *insn) { /* Anything NOP, but no REP NOP */ if (insn->opcode.bytes[0] == 0x90 && (!insn->prefixes.nbytes || insn->prefixes.bytes[0] != 0xF3)) return true; /* NOPL */ if (insn->opcode.bytes[0] == 0x0F && insn->opcode.bytes[1] == 0x1F) return true; /* TODO: more nops */ return false; } /* * Find the offset of the first non-NOP instruction starting at @offset * but no further than @len. */ static int skip_nops(u8 *instr, int offset, int len) { struct insn insn; for (; offset < len; offset += insn.length) { if (insn_decode_kernel(&insn, &instr[offset])) break; if (!insn_is_nop(&insn)) break; } return offset; } /* * Optimize a sequence of NOPs, possibly preceded by an unconditional jump * to the end of the NOP sequence into a single NOP. */ static bool __init_or_module __optimize_nops(u8 *instr, size_t len, struct insn *insn, int *next, int *prev, int *target) { int i = *next - insn->length; switch (insn->opcode.bytes[0]) { case JMP8_INSN_OPCODE: case JMP32_INSN_OPCODE: *prev = i; *target = *next + insn->immediate.value; return false; } if (insn_is_nop(insn)) { int nop = i; *next = skip_nops(instr, *next, len); if (*target && *next == *target) nop = *prev; add_nop(instr + nop, *next - nop); DUMP_BYTES(ALT, instr, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, *next); return true; } *target = 0; return false; } /* * "noinline" to cause control flow change and thus invalidate I$ and * cause refetch after modification. */ static void __init_or_module noinline optimize_nops(u8 *instr, size_t len) { int prev, target = 0; for (int next, i = 0; i < len; i = next) { struct insn insn; if (insn_decode_kernel(&insn, &instr[i])) return; next = i + insn.length; __optimize_nops(instr, len, &insn, &next, &prev, &target); } } /* * In this context, "source" is where the instructions are placed in the * section .altinstr_replacement, for example during kernel build by the * toolchain. * "Destination" is where the instructions are being patched in by this * machinery. * * The source offset is: * * src_imm = target - src_next_ip (1) * * and the target offset is: * * dst_imm = target - dst_next_ip (2) * * so rework (1) as an expression for target like: * * target = src_imm + src_next_ip (1a) * * and substitute in (2) to get: * * dst_imm = (src_imm + src_next_ip) - dst_next_ip (3) * * Now, since the instruction stream is 'identical' at src and dst (it * is being copied after all) it can be stated that: * * src_next_ip = src + ip_offset * dst_next_ip = dst + ip_offset (4) * * Substitute (4) in (3) and observe ip_offset being cancelled out to * obtain: * * dst_imm = src_imm + (src + ip_offset) - (dst + ip_offset) * = src_imm + src - dst + ip_offset - ip_offset * = src_imm + src - dst (5) * * IOW, only the relative displacement of the code block matters. */ #define apply_reloc_n(n_, p_, d_) \ do { \ s32 v = *(s##n_ *)(p_); \ v += (d_); \ BUG_ON((v >> 31) != (v >> (n_-1))); \ *(s##n_ *)(p_) = (s##n_)v; \ } while (0) static __always_inline void apply_reloc(int n, void *ptr, uintptr_t diff) { switch (n) { case 1: apply_reloc_n(8, ptr, diff); break; case 2: apply_reloc_n(16, ptr, diff); break; case 4: apply_reloc_n(32, ptr, diff); break; default: BUG(); } } static __always_inline bool need_reloc(unsigned long offset, u8 *src, size_t src_len) { u8 *target = src + offset; /* * If the target is inside the patched block, it's relative to the * block itself and does not need relocation. */ return (target < src || target > src + src_len); } static void __init_or_module noinline apply_relocation(u8 *buf, size_t len, u8 *dest, u8 *src, size_t src_len) { int prev, target = 0; for (int next, i = 0; i < len; i = next) { struct insn insn; if (WARN_ON_ONCE(insn_decode_kernel(&insn, &buf[i]))) return; next = i + insn.length; if (__optimize_nops(buf, len, &insn, &next, &prev, &target)) continue; switch (insn.opcode.bytes[0]) { case 0x0f: if (insn.opcode.bytes[1] < 0x80 || insn.opcode.bytes[1] > 0x8f) break; fallthrough; /* Jcc.d32 */ case 0x70 ... 0x7f: /* Jcc.d8 */ case JMP8_INSN_OPCODE: case JMP32_INSN_OPCODE: case CALL_INSN_OPCODE: if (need_reloc(next + insn.immediate.value, src, src_len)) { apply_reloc(insn.immediate.nbytes, buf + i + insn_offset_immediate(&insn), src - dest); } /* * Where possible, convert JMP.d32 into JMP.d8. */ if (insn.opcode.bytes[0] == JMP32_INSN_OPCODE) { s32 imm = insn.immediate.value; imm += src - dest; imm += JMP32_INSN_SIZE - JMP8_INSN_SIZE; if ((imm >> 31) == (imm >> 7)) { buf[i+0] = JMP8_INSN_OPCODE; buf[i+1] = (s8)imm; memset(&buf[i+2], INT3_INSN_OPCODE, insn.length - 2); } } break; } if (insn_rip_relative(&insn)) { if (need_reloc(next + insn.displacement.value, src, src_len)) { apply_reloc(insn.displacement.nbytes, buf + i + insn_offset_displacement(&insn), src - dest); } } } } /* * Replace instructions with better alternatives for this CPU type. This runs * before SMP is initialized to avoid SMP problems with self modifying code. * This implies that asymmetric systems where APs have less capabilities than * the boot processor are not handled. Tough. Make sure you disable such * features by hand. * * Marked "noinline" to cause control flow change and thus insn cache * to refetch changed I$ lines. */ void __init_or_module noinline apply_alternatives(struct alt_instr *start, struct alt_instr *end) { struct alt_instr *a; u8 *instr, *replacement; u8 insn_buff[MAX_PATCH_LEN]; DPRINTK(ALT, "alt table %px, -> %px", start, end); /* * The scan order should be from start to end. A later scanned * alternative code can overwrite previously scanned alternative code. * Some kernel functions (e.g. memcpy, memset, etc) use this order to * patch code. * * So be careful if you want to change the scan order to any other * order. */ for (a = start; a < end; a++) { int insn_buff_sz = 0; instr = (u8 *)&a->instr_offset + a->instr_offset; replacement = (u8 *)&a->repl_offset + a->repl_offset; BUG_ON(a->instrlen > sizeof(insn_buff)); BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32); /* * Patch if either: * - feature is present * - feature not present but ALT_FLAG_NOT is set to mean, * patch if feature is *NOT* present. */ if (!boot_cpu_has(a->cpuid) == !(a->flags & ALT_FLAG_NOT)) { optimize_nops(instr, a->instrlen); continue; } DPRINTK(ALT, "feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)", (a->flags & ALT_FLAG_NOT) ? "!" : "", a->cpuid >> 5, a->cpuid & 0x1f, instr, instr, a->instrlen, replacement, a->replacementlen); memcpy(insn_buff, replacement, a->replacementlen); insn_buff_sz = a->replacementlen; for (; insn_buff_sz < a->instrlen; insn_buff_sz++) insn_buff[insn_buff_sz] = 0x90; apply_relocation(insn_buff, a->instrlen, instr, replacement, a->replacementlen); DUMP_BYTES(ALT, instr, a->instrlen, "%px: old_insn: ", instr); DUMP_BYTES(ALT, replacement, a->replacementlen, "%px: rpl_insn: ", replacement); DUMP_BYTES(ALT, insn_buff, insn_buff_sz, "%px: final_insn: ", instr); text_poke_early(instr, insn_buff, insn_buff_sz); } } static inline bool is_jcc32(struct insn *insn) { /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */ return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80; } #if defined(CONFIG_RETPOLINE) && defined(CONFIG_OBJTOOL) /* * CALL/JMP *%\reg */ static int emit_indirect(int op, int reg, u8 *bytes) { int i = 0; u8 modrm; switch (op) { case CALL_INSN_OPCODE: modrm = 0x10; /* Reg = 2; CALL r/m */ break; case JMP32_INSN_OPCODE: modrm = 0x20; /* Reg = 4; JMP r/m */ break; default: WARN_ON_ONCE(1); return -1; } if (reg >= 8) { bytes[i++] = 0x41; /* REX.B prefix */ reg -= 8; } modrm |= 0xc0; /* Mod = 3 */ modrm += reg; bytes[i++] = 0xff; /* opcode */ bytes[i++] = modrm; return i; } static int emit_call_track_retpoline(void *addr, struct insn *insn, int reg, u8 *bytes) { u8 op = insn->opcode.bytes[0]; int i = 0; /* * Clang does 'weird' Jcc __x86_indirect_thunk_r11 conditional * tail-calls. Deal with them. */ if (is_jcc32(insn)) { bytes[i++] = op; op = insn->opcode.bytes[1]; goto clang_jcc; } if (insn->length == 6) bytes[i++] = 0x2e; /* CS-prefix */ switch (op) { case CALL_INSN_OPCODE: __text_gen_insn(bytes+i, op, addr+i, __x86_indirect_call_thunk_array[reg], CALL_INSN_SIZE); i += CALL_INSN_SIZE; break; case JMP32_INSN_OPCODE: clang_jcc: __text_gen_insn(bytes+i, op, addr+i, __x86_indirect_jump_thunk_array[reg], JMP32_INSN_SIZE); i += JMP32_INSN_SIZE; break; default: WARN(1, "%pS %px %*ph\n", addr, addr, 6, addr); return -1; } WARN_ON_ONCE(i != insn->length); return i; } /* * Rewrite the compiler generated retpoline thunk calls. * * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate * indirect instructions, avoiding the extra indirection. * * For example, convert: * * CALL __x86_indirect_thunk_\reg * * into: * * CALL *%\reg * * It also tries to inline spectre_v2=retpoline,lfence when size permits. */ static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes) { retpoline_thunk_t *target; int reg, ret, i = 0; u8 op, cc; target = addr + insn->length + insn->immediate.value; reg = target - __x86_indirect_thunk_array; if (WARN_ON_ONCE(reg & ~0xf)) return -1; /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */ BUG_ON(reg == 4); if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) && !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) { if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH)) return emit_call_track_retpoline(addr, insn, reg, bytes); return -1; } op = insn->opcode.bytes[0]; /* * Convert: * * Jcc.d32 __x86_indirect_thunk_\reg * * into: * * Jncc.d8 1f * [ LFENCE ] * JMP *%\reg * [ NOP ] * 1: */ if (is_jcc32(insn)) { cc = insn->opcode.bytes[1] & 0xf; cc ^= 1; /* invert condition */ bytes[i++] = 0x70 + cc; /* Jcc.d8 */ bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */ /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */ op = JMP32_INSN_OPCODE; } /* * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE. */ if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) { bytes[i++] = 0x0f; bytes[i++] = 0xae; bytes[i++] = 0xe8; /* LFENCE */ } ret = emit_indirect(op, reg, bytes + i); if (ret < 0) return ret; i += ret; /* * The compiler is supposed to EMIT an INT3 after every unconditional * JMP instruction due to AMD BTC. However, if the compiler is too old * or SLS isn't enabled, we still need an INT3 after indirect JMPs * even on Intel. */ if (op == JMP32_INSN_OPCODE && i < insn->length) bytes[i++] = INT3_INSN_OPCODE; for (; i < insn->length;) bytes[i++] = BYTES_NOP1; return i; } /* * Generated by 'objtool --retpoline'. */ void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; struct insn insn; int len, ret; u8 bytes[16]; u8 op1, op2; ret = insn_decode_kernel(&insn, addr); if (WARN_ON_ONCE(ret < 0)) continue; op1 = insn.opcode.bytes[0]; op2 = insn.opcode.bytes[1]; switch (op1) { case CALL_INSN_OPCODE: case JMP32_INSN_OPCODE: break; case 0x0f: /* escape */ if (op2 >= 0x80 && op2 <= 0x8f) break; fallthrough; default: WARN_ON_ONCE(1); continue; } DPRINTK(RETPOLINE, "retpoline at: %pS (%px) len: %d to: %pS", addr, addr, insn.length, addr + insn.length + insn.immediate.value); len = patch_retpoline(addr, &insn, bytes); if (len == insn.length) { optimize_nops(bytes, len); DUMP_BYTES(RETPOLINE, ((u8*)addr), len, "%px: orig: ", addr); DUMP_BYTES(RETPOLINE, ((u8*)bytes), len, "%px: repl: ", addr); text_poke_early(addr, bytes, len); } } } #ifdef CONFIG_RETHUNK /* * Rewrite the compiler generated return thunk tail-calls. * * For example, convert: * * JMP __x86_return_thunk * * into: * * RET */ static int patch_return(void *addr, struct insn *insn, u8 *bytes) { int i = 0; /* Patch the custom return thunks... */ if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) { i = JMP32_INSN_SIZE; __text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i); } else { /* ... or patch them out if not needed. */ bytes[i++] = RET_INSN_OPCODE; } for (; i < insn->length;) bytes[i++] = INT3_INSN_OPCODE; return i; } void __init_or_module noinline apply_returns(s32 *start, s32 *end) { s32 *s; if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) static_call_force_reinit(); for (s = start; s < end; s++) { void *dest = NULL, *addr = (void *)s + *s; struct insn insn; int len, ret; u8 bytes[16]; u8 op; ret = insn_decode_kernel(&insn, addr); if (WARN_ON_ONCE(ret < 0)) continue; op = insn.opcode.bytes[0]; if (op == JMP32_INSN_OPCODE) dest = addr + insn.length + insn.immediate.value; if (__static_call_fixup(addr, op, dest) || WARN_ONCE(dest != &__x86_return_thunk, "missing return thunk: %pS-%pS: %*ph", addr, dest, 5, addr)) continue; DPRINTK(RET, "return thunk at: %pS (%px) len: %d to: %pS", addr, addr, insn.length, addr + insn.length + insn.immediate.value); len = patch_return(addr, &insn, bytes); if (len == insn.length) { DUMP_BYTES(RET, ((u8*)addr), len, "%px: orig: ", addr); DUMP_BYTES(RET, ((u8*)bytes), len, "%px: repl: ", addr); text_poke_early(addr, bytes, len); } } } #else void __init_or_module noinline apply_returns(s32 *start, s32 *end) { } #endif /* CONFIG_RETHUNK */ #else /* !CONFIG_RETPOLINE || !CONFIG_OBJTOOL */ void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { } void __init_or_module noinline apply_returns(s32 *start, s32 *end) { } #endif /* CONFIG_RETPOLINE && CONFIG_OBJTOOL */ #ifdef CONFIG_X86_KERNEL_IBT static void poison_cfi(void *addr); static void __init_or_module poison_endbr(void *addr, bool warn) { u32 endbr, poison = gen_endbr_poison(); if (WARN_ON_ONCE(get_kernel_nofault(endbr, addr))) return; if (!is_endbr(endbr)) { WARN_ON_ONCE(warn); return; } DPRINTK(ENDBR, "ENDBR at: %pS (%px)", addr, addr); /* * When we have IBT, the lack of ENDBR will trigger #CP */ DUMP_BYTES(ENDBR, ((u8*)addr), 4, "%px: orig: ", addr); DUMP_BYTES(ENDBR, ((u8*)&poison), 4, "%px: repl: ", addr); text_poke_early(addr, &poison, 4); } /* * Generated by: objtool --ibt * * Seal the functions for indirect calls by clobbering the ENDBR instructions * and the kCFI hash value. */ void __init_or_module noinline apply_seal_endbr(s32 *start, s32 *end) { s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; poison_endbr(addr, true); if (IS_ENABLED(CONFIG_FINEIBT)) poison_cfi(addr - 16); } } #else void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { } #endif /* CONFIG_X86_KERNEL_IBT */ #ifdef CONFIG_FINEIBT enum cfi_mode { CFI_DEFAULT, CFI_OFF, CFI_KCFI, CFI_FINEIBT, }; static enum cfi_mode cfi_mode __ro_after_init = CFI_DEFAULT; static bool cfi_rand __ro_after_init = true; static u32 cfi_seed __ro_after_init; /* * Re-hash the CFI hash with a boot-time seed while making sure the result is * not a valid ENDBR instruction. */ static u32 cfi_rehash(u32 hash) { hash ^= cfi_seed; while (unlikely(is_endbr(hash) || is_endbr(-hash))) { bool lsb = hash & 1; hash >>= 1; if (lsb) hash ^= 0x80200003; } return hash; } static __init int cfi_parse_cmdline(char *str) { if (!str) return -EINVAL; while (str) { char *next = strchr(str, ','); if (next) { *next = 0; next++; } if (!strcmp(str, "auto")) { cfi_mode = CFI_DEFAULT; } else if (!strcmp(str, "off")) { cfi_mode = CFI_OFF; cfi_rand = false; } else if (!strcmp(str, "kcfi")) { cfi_mode = CFI_KCFI; } else if (!strcmp(str, "fineibt")) { cfi_mode = CFI_FINEIBT; } else if (!strcmp(str, "norand")) { cfi_rand = false; } else { pr_err("Ignoring unknown cfi option (%s).", str); } str = next; } return 0; } early_param("cfi", cfi_parse_cmdline); /* * kCFI FineIBT * * __cfi_\func: __cfi_\func: * movl $0x12345678,%eax // 5 endbr64 // 4 * nop subl $0x12345678,%r10d // 7 * nop jz 1f // 2 * nop ud2 // 2 * nop 1: nop // 1 * nop * nop * nop * nop * nop * nop * nop * * * caller: caller: * movl $(-0x12345678),%r10d // 6 movl $0x12345678,%r10d // 6 * addl $-15(%r11),%r10d // 4 sub $16,%r11 // 4 * je 1f // 2 nop4 // 4 * ud2 // 2 * 1: call __x86_indirect_thunk_r11 // 5 call *%r11; nop2; // 5 * */ asm( ".pushsection .rodata \n" "fineibt_preamble_start: \n" " endbr64 \n" " subl $0x12345678, %r10d \n" " je fineibt_preamble_end \n" " ud2 \n" " nop \n" "fineibt_preamble_end: \n" ".popsection\n" ); extern u8 fineibt_preamble_start[]; extern u8 fineibt_preamble_end[]; #define fineibt_preamble_size (fineibt_preamble_end - fineibt_preamble_start) #define fineibt_preamble_hash 7 asm( ".pushsection .rodata \n" "fineibt_caller_start: \n" " movl $0x12345678, %r10d \n" " sub $16, %r11 \n" ASM_NOP4 "fineibt_caller_end: \n" ".popsection \n" ); extern u8 fineibt_caller_start[]; extern u8 fineibt_caller_end[]; #define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start) #define fineibt_caller_hash 2 #define fineibt_caller_jmp (fineibt_caller_size - 2) static u32 decode_preamble_hash(void *addr) { u8 *p = addr; /* b8 78 56 34 12 mov $0x12345678,%eax */ if (p[0] == 0xb8) return *(u32 *)(addr + 1); return 0; /* invalid hash value */ } static u32 decode_caller_hash(void *addr) { u8 *p = addr; /* 41 ba 78 56 34 12 mov $0x12345678,%r10d */ if (p[0] == 0x41 && p[1] == 0xba) return -*(u32 *)(addr + 2); /* e8 0c 78 56 34 12 jmp.d8 +12 */ if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp) return -*(u32 *)(addr + 2); return 0; /* invalid hash value */ } /* .retpoline_sites */ static int cfi_disable_callers(s32 *start, s32 *end) { /* * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate * in tact for later usage. Also see decode_caller_hash() and * cfi_rewrite_callers(). */ const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp }; s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; u32 hash; addr -= fineibt_caller_size; hash = decode_caller_hash(addr); if (!hash) /* nocfi callers */ continue; text_poke_early(addr, jmp, 2); } return 0; } static int cfi_enable_callers(s32 *start, s32 *end) { /* * Re-enable kCFI, undo what cfi_disable_callers() did. */ const u8 mov[] = { 0x41, 0xba }; s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; u32 hash; addr -= fineibt_caller_size; hash = decode_caller_hash(addr); if (!hash) /* nocfi callers */ continue; text_poke_early(addr, mov, 2); } return 0; } /* .cfi_sites */ static int cfi_rand_preamble(s32 *start, s32 *end) { s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; u32 hash; hash = decode_preamble_hash(addr); if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n", addr, addr, 5, addr)) return -EINVAL; hash = cfi_rehash(hash); text_poke_early(addr + 1, &hash, 4); } return 0; } static int cfi_rewrite_preamble(s32 *start, s32 *end) { s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; u32 hash; hash = decode_preamble_hash(addr); if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n", addr, addr, 5, addr)) return -EINVAL; text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size); WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678); text_poke_early(addr + fineibt_preamble_hash, &hash, 4); } return 0; } static void cfi_rewrite_endbr(s32 *start, s32 *end) { s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; poison_endbr(addr+16, false); } } /* .retpoline_sites */ static int cfi_rand_callers(s32 *start, s32 *end) { s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; u32 hash; addr -= fineibt_caller_size; hash = decode_caller_hash(addr); if (hash) { hash = -cfi_rehash(hash); text_poke_early(addr + 2, &hash, 4); } } return 0; } static int cfi_rewrite_callers(s32 *start, s32 *end) { s32 *s; for (s = start; s < end; s++) { void *addr = (void *)s + *s; u32 hash; addr -= fineibt_caller_size; hash = decode_caller_hash(addr); if (hash) { text_poke_early(addr, fineibt_caller_start, fineibt_caller_size); WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678); text_poke_early(addr + fineibt_caller_hash, &hash, 4); } /* rely on apply_retpolines() */ } return 0; } static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline, s32 *start_cfi, s32 *end_cfi, bool builtin) { int ret; if (WARN_ONCE(fineibt_preamble_size != 16, "FineIBT preamble wrong size: %ld", fineibt_preamble_size)) return; if (cfi_mode == CFI_DEFAULT) { cfi_mode = CFI_KCFI; if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT)) cfi_mode = CFI_FINEIBT; } /* * Rewrite the callers to not use the __cfi_ stubs, such that we might * rewrite them. This disables all CFI. If this succeeds but any of the * later stages fails, we're without CFI. */ ret = cfi_disable_callers(start_retpoline, end_retpoline); if (ret) goto err; if (cfi_rand) { if (builtin) cfi_seed = get_random_u32(); ret = cfi_rand_preamble(start_cfi, end_cfi); if (ret) goto err; ret = cfi_rand_callers(start_retpoline, end_retpoline); if (ret) goto err; } switch (cfi_mode) { case CFI_OFF: if (builtin) pr_info("Disabling CFI\n"); return; case CFI_KCFI: ret = cfi_enable_callers(start_retpoline, end_retpoline); if (ret) goto err; if (builtin) pr_info("Using kCFI\n"); return; case CFI_FINEIBT: /* place the FineIBT preamble at func()-16 */ ret = cfi_rewrite_preamble(start_cfi, end_cfi); if (ret) goto err; /* rewrite the callers to target func()-16 */ ret = cfi_rewrite_callers(start_retpoline, end_retpoline); if (ret) goto err; /* now that nobody targets func()+0, remove ENDBR there */ cfi_rewrite_endbr(start_cfi, end_cfi); if (builtin) pr_info("Using FineIBT CFI\n"); return; default: break; } err: pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n"); } static inline void poison_hash(void *addr) { *(u32 *)addr = 0; } static void poison_cfi(void *addr) { switch (cfi_mode) { case CFI_FINEIBT: /* * __cfi_\func: * osp nopl (%rax) * subl $0, %r10d * jz 1f * ud2 * 1: nop */ poison_endbr(addr, false); poison_hash(addr + fineibt_preamble_hash); break; case CFI_KCFI: /* * __cfi_\func: * movl $0, %eax * .skip 11, 0x90 */ poison_hash(addr + 1); break; default: break; } } #else static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline, s32 *start_cfi, s32 *end_cfi, bool builtin) { } #ifdef CONFIG_X86_KERNEL_IBT static void poison_cfi(void *addr) { } #endif #endif void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline, s32 *start_cfi, s32 *end_cfi) { return __apply_fineibt(start_retpoline, end_retpoline, start_cfi, end_cfi, /* .builtin = */ false); } #ifdef CONFIG_SMP static void alternatives_smp_lock(const s32 *start, const s32 *end, u8 *text, u8 *text_end) { const s32 *poff; for (poff = start; poff < end; poff++) { u8 *ptr = (u8 *)poff + *poff; if (!*poff || ptr < text || ptr >= text_end) continue; /* turn DS segment override prefix into lock prefix */ if (*ptr == 0x3e) text_poke(ptr, ((unsigned char []){0xf0}), 1); } } static void alternatives_smp_unlock(const s32 *start, const s32 *end, u8 *text, u8 *text_end) { const s32 *poff; for (poff = start; poff < end; poff++) { u8 *ptr = (u8 *)poff + *poff; if (!*poff || ptr < text || ptr >= text_end) continue; /* turn lock prefix into DS segment override prefix */ if (*ptr == 0xf0) text_poke(ptr, ((unsigned char []){0x3E}), 1); } } struct smp_alt_module { /* what is this ??? */ struct module *mod; char *name; /* ptrs to lock prefixes */ const s32 *locks; const s32 *locks_end; /* .text segment, needed to avoid patching init code ;) */ u8 *text; u8 *text_end; struct list_head next; }; static LIST_HEAD(smp_alt_modules); static bool uniproc_patched = false; /* protected by text_mutex */ void __init_or_module alternatives_smp_module_add(struct module *mod, char *name, void *locks, void *locks_end, void *text, void *text_end) { struct smp_alt_module *smp; mutex_lock(&text_mutex); if (!uniproc_patched) goto unlock; if (num_possible_cpus() == 1) /* Don't bother remembering, we'll never have to undo it. */ goto smp_unlock; smp = kzalloc(sizeof(*smp), GFP_KERNEL); if (NULL == smp) /* we'll run the (safe but slow) SMP code then ... */ goto unlock; smp->mod = mod; smp->name = name; smp->locks = locks; smp->locks_end = locks_end; smp->text = text; smp->text_end = text_end; DPRINTK(SMP, "locks %p -> %p, text %p -> %p, name %s\n", smp->locks, smp->locks_end, smp->text, smp->text_end, smp->name); list_add_tail(&smp->next, &smp_alt_modules); smp_unlock: alternatives_smp_unlock(locks, locks_end, text, text_end); unlock: mutex_unlock(&text_mutex); } void __init_or_module alternatives_smp_module_del(struct module *mod) { struct smp_alt_module *item; mutex_lock(&text_mutex); list_for_each_entry(item, &smp_alt_modules, next) { if (mod != item->mod) continue; list_del(&item->next); kfree(item); break; } mutex_unlock(&text_mutex); } void alternatives_enable_smp(void) { struct smp_alt_module *mod; /* Why bother if there are no other CPUs? */ BUG_ON(num_possible_cpus() == 1); mutex_lock(&text_mutex); if (uniproc_patched) { pr_info("switching to SMP code\n"); BUG_ON(num_online_cpus() != 1); clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP); clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP); list_for_each_entry(mod, &smp_alt_modules, next) alternatives_smp_lock(mod->locks, mod->locks_end, mod->text, mod->text_end); uniproc_patched = false; } mutex_unlock(&text_mutex); } /* * Return 1 if the address range is reserved for SMP-alternatives. * Must hold text_mutex. */ int alternatives_text_reserved(void *start, void *end) { struct smp_alt_module *mod; const s32 *poff; u8 *text_start = start; u8 *text_end = end; lockdep_assert_held(&text_mutex); list_for_each_entry(mod, &smp_alt_modules, next) { if (mod->text > text_end || mod->text_end < text_start) continue; for (poff = mod->locks; poff < mod->locks_end; poff++) { const u8 *ptr = (const u8 *)poff + *poff; if (text_start <= ptr && text_end > ptr) return 1; } } return 0; } #endif /* CONFIG_SMP */ #ifdef CONFIG_PARAVIRT /* Use this to add nops to a buffer, then text_poke the whole buffer. */ static void __init_or_module add_nops(void *insns, unsigned int len) { while (len > 0) { unsigned int noplen = len; if (noplen > ASM_NOP_MAX) noplen = ASM_NOP_MAX; memcpy(insns, x86_nops[noplen], noplen); insns += noplen; len -= noplen; } } void __init_or_module apply_paravirt(struct paravirt_patch_site *start, struct paravirt_patch_site *end) { struct paravirt_patch_site *p; char insn_buff[MAX_PATCH_LEN]; for (p = start; p < end; p++) { unsigned int used; BUG_ON(p->len > MAX_PATCH_LEN); /* prep the buffer with the original instructions */ memcpy(insn_buff, p->instr, p->len); used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len); BUG_ON(used > p->len); /* Pad the rest with nops */ add_nops(insn_buff + used, p->len - used); text_poke_early(p->instr, insn_buff, p->len); } } extern struct paravirt_patch_site __start_parainstructions[], __stop_parainstructions[]; #endif /* CONFIG_PARAVIRT */ /* * Self-test for the INT3 based CALL emulation code. * * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up * properly and that there is a stack gap between the INT3 frame and the * previous context. Without this gap doing a virtual PUSH on the interrupted * stack would corrupt the INT3 IRET frame. * * See entry_{32,64}.S for more details. */ /* * We define the int3_magic() function in assembly to control the calling * convention such that we can 'call' it from assembly. */ extern void int3_magic(unsigned int *ptr); /* defined in asm */ asm ( " .pushsection .init.text, \"ax\", @progbits\n" " .type int3_magic, @function\n" "int3_magic:\n" ANNOTATE_NOENDBR " movl $1, (%" _ASM_ARG1 ")\n" ASM_RET " .size int3_magic, .-int3_magic\n" " .popsection\n" ); extern void int3_selftest_ip(void); /* defined in asm below */ static int __init int3_exception_notify(struct notifier_block *self, unsigned long val, void *data) { unsigned long selftest = (unsigned long)&int3_selftest_ip; struct die_args *args = data; struct pt_regs *regs = args->regs; OPTIMIZER_HIDE_VAR(selftest); if (!regs || user_mode(regs)) return NOTIFY_DONE; if (val != DIE_INT3) return NOTIFY_DONE; if (regs->ip - INT3_INSN_SIZE != selftest) return NOTIFY_DONE; int3_emulate_call(regs, (unsigned long)&int3_magic); return NOTIFY_STOP; } /* Must be noinline to ensure uniqueness of int3_selftest_ip. */ static noinline void __init int3_selftest(void) { static __initdata struct notifier_block int3_exception_nb = { .notifier_call = int3_exception_notify, .priority = INT_MAX-1, /* last */ }; unsigned int val = 0; BUG_ON(register_die_notifier(&int3_exception_nb)); /* * Basically: int3_magic(&val); but really complicated :-) * * INT3 padded with NOP to CALL_INSN_SIZE. The int3_exception_nb * notifier above will emulate CALL for us. */ asm volatile ("int3_selftest_ip:\n\t" ANNOTATE_NOENDBR " int3; nop; nop; nop; nop\n\t" : ASM_CALL_CONSTRAINT : __ASM_SEL_RAW(a, D) (&val) : "memory"); BUG_ON(val != 1); unregister_die_notifier(&int3_exception_nb); } static __initdata int __alt_reloc_selftest_addr; extern void __init __alt_reloc_selftest(void *arg); __visible noinline void __init __alt_reloc_selftest(void *arg) { WARN_ON(arg != &__alt_reloc_selftest_addr); } static noinline void __init alt_reloc_selftest(void) { /* * Tests apply_relocation(). * * This has a relative immediate (CALL) in a place other than the first * instruction and additionally on x86_64 we get a RIP-relative LEA: * * lea 0x0(%rip),%rdi # 5d0: R_X86_64_PC32 .init.data+0x5566c * call +0 # 5d5: R_X86_64_PLT32 __alt_reloc_selftest-0x4 * * Getting this wrong will either crash and burn or tickle the WARN * above. */ asm_inline volatile ( ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS) : /* output */ : [mem] "m" (__alt_reloc_selftest_addr) : _ASM_ARG1 ); } void __init alternative_instructions(void) { int3_selftest(); /* * The patching is not fully atomic, so try to avoid local * interruptions that might execute the to be patched code. * Other CPUs are not running. */ stop_nmi(); /* * Don't stop machine check exceptions while patching. * MCEs only happen when something got corrupted and in this * case we must do something about the corruption. * Ignoring it is worse than an unlikely patching race. * Also machine checks tend to be broadcast and if one CPU * goes into machine check the others follow quickly, so we don't * expect a machine check to cause undue problems during to code * patching. */ /* * Paravirt patching and alternative patching can be combined to * replace a function call with a short direct code sequence (e.g. * by setting a constant return value instead of doing that in an * external function). * In order to make this work the following sequence is required: * 1. set (artificial) features depending on used paravirt * functions which can later influence alternative patching * 2. apply paravirt patching (generally replacing an indirect * function call with a direct one) * 3. apply alternative patching (e.g. replacing a direct function * call with a custom code sequence) * Doing paravirt patching after alternative patching would clobber * the optimization of the custom code with a function call again. */ paravirt_set_cap(); /* * First patch paravirt functions, such that we overwrite the indirect * call with the direct call. */ apply_paravirt(__parainstructions, __parainstructions_end); __apply_fineibt(__retpoline_sites, __retpoline_sites_end, __cfi_sites, __cfi_sites_end, true); /* * Rewrite the retpolines, must be done before alternatives since * those can rewrite the retpoline thunks. */ apply_retpolines(__retpoline_sites, __retpoline_sites_end); apply_returns(__return_sites, __return_sites_end); /* * Then patch alternatives, such that those paravirt calls that are in * alternatives can be overwritten by their immediate fragments. */ apply_alternatives(__alt_instructions, __alt_instructions_end); /* * Now all calls are established. Apply the call thunks if * required. */ callthunks_patch_builtin_calls(); /* * Seal all functions that do not have their address taken. */ apply_seal_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end); #ifdef CONFIG_SMP /* Patch to UP if other cpus not imminent. */ if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) { uniproc_patched = true; alternatives_smp_module_add(NULL, "core kernel", __smp_locks, __smp_locks_end, _text, _etext); } if (!uniproc_patched || num_possible_cpus() == 1) { free_init_pages("SMP alternatives", (unsigned long)__smp_locks, (unsigned long)__smp_locks_end); } #endif restart_nmi(); alternatives_patched = 1; alt_reloc_selftest(); } /** * text_poke_early - Update instructions on a live kernel at boot time * @addr: address to modify * @opcode: source of the copy * @len: length to copy * * When you use this code to patch more than one byte of an instruction * you need to make sure that other CPUs cannot execute this code in parallel. * Also no thread must be currently preempted in the middle of these * instructions. And on the local CPU you need to be protected against NMI or * MCE handlers seeing an inconsistent instruction while you patch. */ void __init_or_module text_poke_early(void *addr, const void *opcode, size_t len) { unsigned long flags; if (boot_cpu_has(X86_FEATURE_NX) && is_module_text_address((unsigned long)addr)) { /* * Modules text is marked initially as non-executable, so the * code cannot be running and speculative code-fetches are * prevented. Just change the code. */ memcpy(addr, opcode, len); } else { local_irq_save(flags); memcpy(addr, opcode, len); local_irq_restore(flags); sync_core(); /* * Could also do a CLFLUSH here to speed up CPU recovery; but * that causes hangs on some VIA CPUs. */ } } typedef struct { struct mm_struct *mm; } temp_mm_state_t; /* * Using a temporary mm allows to set temporary mappings that are not accessible * by other CPUs. Such mappings are needed to perform sensitive memory writes * that override the kernel memory protections (e.g., W^X), without exposing the * temporary page-table mappings that are required for these write operations to * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the * mapping is torn down. * * Context: The temporary mm needs to be used exclusively by a single core. To * harden security IRQs must be disabled while the temporary mm is * loaded, thereby preventing interrupt handler bugs from overriding * the kernel memory protection. */ static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm) { temp_mm_state_t temp_state; lockdep_assert_irqs_disabled(); /* * Make sure not to be in TLB lazy mode, as otherwise we'll end up * with a stale address space WITHOUT being in lazy mode after * restoring the previous mm. */ if (this_cpu_read(cpu_tlbstate_shared.is_lazy)) leave_mm(smp_processor_id()); temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm); switch_mm_irqs_off(NULL, mm, current); /* * If breakpoints are enabled, disable them while the temporary mm is * used. Userspace might set up watchpoints on addresses that are used * in the temporary mm, which would lead to wrong signals being sent or * crashes. * * Note that breakpoints are not disabled selectively, which also causes * kernel breakpoints (e.g., perf's) to be disabled. This might be * undesirable, but still seems reasonable as the code that runs in the * temporary mm should be short. */ if (hw_breakpoint_active()) hw_breakpoint_disable(); return temp_state; } static inline void unuse_temporary_mm(temp_mm_state_t prev_state) { lockdep_assert_irqs_disabled(); switch_mm_irqs_off(NULL, prev_state.mm, current); /* * Restore the breakpoints if they were disabled before the temporary mm * was loaded. */ if (hw_breakpoint_active()) hw_breakpoint_restore(); } __ro_after_init struct mm_struct *poking_mm; __ro_after_init unsigned long poking_addr; static void text_poke_memcpy(void *dst, const void *src, size_t len) { memcpy(dst, src, len); } static void text_poke_memset(void *dst, const void *src, size_t len) { int c = *(const int *)src; memset(dst, c, len); } typedef void text_poke_f(void *dst, const void *src, size_t len); static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len) { bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE; struct page *pages[2] = {NULL}; temp_mm_state_t prev; unsigned long flags; pte_t pte, *ptep; spinlock_t *ptl; pgprot_t pgprot; /* * While boot memory allocator is running we cannot use struct pages as * they are not yet initialized. There is no way to recover. */ BUG_ON(!after_bootmem); if (!core_kernel_text((unsigned long)addr)) { pages[0] = vmalloc_to_page(addr); if (cross_page_boundary) pages[1] = vmalloc_to_page(addr + PAGE_SIZE); } else { pages[0] = virt_to_page(addr); WARN_ON(!PageReserved(pages[0])); if (cross_page_boundary) pages[1] = virt_to_page(addr + PAGE_SIZE); } /* * If something went wrong, crash and burn since recovery paths are not * implemented. */ BUG_ON(!pages[0] || (cross_page_boundary && !pages[1])); /* * Map the page without the global bit, as TLB flushing is done with * flush_tlb_mm_range(), which is intended for non-global PTEs. */ pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL); /* * The lock is not really needed, but this allows to avoid open-coding. */ ptep = get_locked_pte(poking_mm, poking_addr, &ptl); /* * This must not fail; preallocated in poking_init(). */ VM_BUG_ON(!ptep); local_irq_save(flags); pte = mk_pte(pages[0], pgprot); set_pte_at(poking_mm, poking_addr, ptep, pte); if (cross_page_boundary) { pte = mk_pte(pages[1], pgprot); set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte); } /* * Loading the temporary mm behaves as a compiler barrier, which * guarantees that the PTE will be set at the time memcpy() is done. */ prev = use_temporary_mm(poking_mm); kasan_disable_current(); func((u8 *)poking_addr + offset_in_page(addr), src, len); kasan_enable_current(); /* * Ensure that the PTE is only cleared after the instructions of memcpy * were issued by using a compiler barrier. */ barrier(); pte_clear(poking_mm, poking_addr, ptep); if (cross_page_boundary) pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1); /* * Loading the previous page-table hierarchy requires a serializing * instruction that already allows the core to see the updated version. * Xen-PV is assumed to serialize execution in a similar manner. */ unuse_temporary_mm(prev); /* * Flushing the TLB might involve IPIs, which would require enabled * IRQs, but not if the mm is not used, as it is in this point. */ flush_tlb_mm_range(poking_mm, poking_addr, poking_addr + (cross_page_boundary ? 2 : 1) * PAGE_SIZE, PAGE_SHIFT, false); if (func == text_poke_memcpy) { /* * If the text does not match what we just wrote then something is * fundamentally screwy; there's nothing we can really do about that. */ BUG_ON(memcmp(addr, src, len)); } local_irq_restore(flags); pte_unmap_unlock(ptep, ptl); return addr; } /** * text_poke - Update instructions on a live kernel * @addr: address to modify * @opcode: source of the copy * @len: length to copy * * Only atomic text poke/set should be allowed when not doing early patching. * It means the size must be writable atomically and the address must be aligned * in a way that permits an atomic write. It also makes sure we fit on a single * page. * * Note that the caller must ensure that if the modified code is part of a * module, the module would not be removed during poking. This can be achieved * by registering a module notifier, and ordering module removal and patching * trough a mutex. */ void *text_poke(void *addr, const void *opcode, size_t len) { lockdep_assert_held(&text_mutex); return __text_poke(text_poke_memcpy, addr, opcode, len); } /** * text_poke_kgdb - Update instructions on a live kernel by kgdb * @addr: address to modify * @opcode: source of the copy * @len: length to copy * * Only atomic text poke/set should be allowed when not doing early patching. * It means the size must be writable atomically and the address must be aligned * in a way that permits an atomic write. It also makes sure we fit on a single * page. * * Context: should only be used by kgdb, which ensures no other core is running, * despite the fact it does not hold the text_mutex. */ void *text_poke_kgdb(void *addr, const void *opcode, size_t len) { return __text_poke(text_poke_memcpy, addr, opcode, len); } void *text_poke_copy_locked(void *addr, const void *opcode, size_t len, bool core_ok) { unsigned long start = (unsigned long)addr; size_t patched = 0; if (WARN_ON_ONCE(!core_ok && core_kernel_text(start))) return NULL; while (patched < len) { unsigned long ptr = start + patched; size_t s; s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched); __text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s); patched += s; } return addr; } /** * text_poke_copy - Copy instructions into (an unused part of) RX memory * @addr: address to modify * @opcode: source of the copy * @len: length to copy, could be more than 2x PAGE_SIZE * * Not safe against concurrent execution; useful for JITs to dump * new code blocks into unused regions of RX memory. Can be used in * conjunction with synchronize_rcu_tasks() to wait for existing * execution to quiesce after having made sure no existing functions * pointers are live. */ void *text_poke_copy(void *addr, const void *opcode, size_t len) { mutex_lock(&text_mutex); addr = text_poke_copy_locked(addr, opcode, len, false); mutex_unlock(&text_mutex); return addr; } /** * text_poke_set - memset into (an unused part of) RX memory * @addr: address to modify * @c: the byte to fill the area with * @len: length to copy, could be more than 2x PAGE_SIZE * * This is useful to overwrite unused regions of RX memory with illegal * instructions. */ void *text_poke_set(void *addr, int c, size_t len) { unsigned long start = (unsigned long)addr; size_t patched = 0; if (WARN_ON_ONCE(core_kernel_text(start))) return NULL; mutex_lock(&text_mutex); while (patched < len) { unsigned long ptr = start + patched; size_t s; s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched); __text_poke(text_poke_memset, (void *)ptr, (void *)&c, s); patched += s; } mutex_unlock(&text_mutex); return addr; } static void do_sync_core(void *info) { sync_core(); } void text_poke_sync(void) { on_each_cpu(do_sync_core, NULL, 1); } /* * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of * this thing. When len == 6 everything is prefixed with 0x0f and we map * opcode to Jcc.d8, using len to distinguish. */ struct text_poke_loc { /* addr := _stext + rel_addr */ s32 rel_addr; s32 disp; u8 len; u8 opcode; const u8 text[POKE_MAX_OPCODE_SIZE]; /* see text_poke_bp_batch() */ u8 old; }; struct bp_patching_desc { struct text_poke_loc *vec; int nr_entries; atomic_t refs; }; static struct bp_patching_desc bp_desc; static __always_inline struct bp_patching_desc *try_get_desc(void) { struct bp_patching_desc *desc = &bp_desc; if (!raw_atomic_inc_not_zero(&desc->refs)) return NULL; return desc; } static __always_inline void put_desc(void) { struct bp_patching_desc *desc = &bp_desc; smp_mb__before_atomic(); raw_atomic_dec(&desc->refs); } static __always_inline void *text_poke_addr(struct text_poke_loc *tp) { return _stext + tp->rel_addr; } static __always_inline int patch_cmp(const void *key, const void *elt) { struct text_poke_loc *tp = (struct text_poke_loc *) elt; if (key < text_poke_addr(tp)) return -1; if (key > text_poke_addr(tp)) return 1; return 0; } noinstr int poke_int3_handler(struct pt_regs *regs) { struct bp_patching_desc *desc; struct text_poke_loc *tp; int ret = 0; void *ip; if (user_mode(regs)) return 0; /* * Having observed our INT3 instruction, we now must observe * bp_desc with non-zero refcount: * * bp_desc.refs = 1 INT3 * WMB RMB * write INT3 if (bp_desc.refs != 0) */ smp_rmb(); desc = try_get_desc(); if (!desc) return 0; /* * Discount the INT3. See text_poke_bp_batch(). */ ip = (void *) regs->ip - INT3_INSN_SIZE; /* * Skip the binary search if there is a single member in the vector. */ if (unlikely(desc->nr_entries > 1)) { tp = __inline_bsearch(ip, desc->vec, desc->nr_entries, sizeof(struct text_poke_loc), patch_cmp); if (!tp) goto out_put; } else { tp = desc->vec; if (text_poke_addr(tp) != ip) goto out_put; } ip += tp->len; switch (tp->opcode) { case INT3_INSN_OPCODE: /* * Someone poked an explicit INT3, they'll want to handle it, * do not consume. */ goto out_put; case RET_INSN_OPCODE: int3_emulate_ret(regs); break; case CALL_INSN_OPCODE: int3_emulate_call(regs, (long)ip + tp->disp); break; case JMP32_INSN_OPCODE: case JMP8_INSN_OPCODE: int3_emulate_jmp(regs, (long)ip + tp->disp); break; case 0x70 ... 0x7f: /* Jcc */ int3_emulate_jcc(regs, tp->opcode & 0xf, (long)ip, tp->disp); break; default: BUG(); } ret = 1; out_put: put_desc(); return ret; } #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc)) static struct text_poke_loc tp_vec[TP_VEC_MAX]; static int tp_vec_nr; /** * text_poke_bp_batch() -- update instructions on live kernel on SMP * @tp: vector of instructions to patch * @nr_entries: number of entries in the vector * * Modify multi-byte instruction by using int3 breakpoint on SMP. * We completely avoid stop_machine() here, and achieve the * synchronization using int3 breakpoint. * * The way it is done: * - For each entry in the vector: * - add a int3 trap to the address that will be patched * - sync cores * - For each entry in the vector: * - update all but the first byte of the patched range * - sync cores * - For each entry in the vector: * - replace the first byte (int3) by the first byte of * replacing opcode * - sync cores */ static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries) { unsigned char int3 = INT3_INSN_OPCODE; unsigned int i; int do_sync; lockdep_assert_held(&text_mutex); bp_desc.vec = tp; bp_desc.nr_entries = nr_entries; /* * Corresponds to the implicit memory barrier in try_get_desc() to * ensure reading a non-zero refcount provides up to date bp_desc data. */ atomic_set_release(&bp_desc.refs, 1); /* * Function tracing can enable thousands of places that need to be * updated. This can take quite some time, and with full kernel debugging * enabled, this could cause the softlockup watchdog to trigger. * This function gets called every 256 entries added to be patched. * Call cond_resched() here to make sure that other tasks can get scheduled * while processing all the functions being patched. */ cond_resched(); /* * Corresponding read barrier in int3 notifier for making sure the * nr_entries and handler are correctly ordered wrt. patching. */ smp_wmb(); /* * First step: add a int3 trap to the address that will be patched. */ for (i = 0; i < nr_entries; i++) { tp[i].old = *(u8 *)text_poke_addr(&tp[i]); text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE); } text_poke_sync(); /* * Second step: update all but the first byte of the patched range. */ for (do_sync = 0, i = 0; i < nr_entries; i++) { u8 old[POKE_MAX_OPCODE_SIZE+1] = { tp[i].old, }; u8 _new[POKE_MAX_OPCODE_SIZE+1]; const u8 *new = tp[i].text; int len = tp[i].len; if (len - INT3_INSN_SIZE > 0) { memcpy(old + INT3_INSN_SIZE, text_poke_addr(&tp[i]) + INT3_INSN_SIZE, len - INT3_INSN_SIZE); if (len == 6) { _new[0] = 0x0f; memcpy(_new + 1, new, 5); new = _new; } text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE, new + INT3_INSN_SIZE, len - INT3_INSN_SIZE); do_sync++; } /* * Emit a perf event to record the text poke, primarily to * support Intel PT decoding which must walk the executable code * to reconstruct the trace. The flow up to here is: * - write INT3 byte * - IPI-SYNC * - write instruction tail * At this point the actual control flow will be through the * INT3 and handler and not hit the old or new instruction. * Intel PT outputs FUP/TIP packets for the INT3, so the flow * can still be decoded. Subsequently: * - emit RECORD_TEXT_POKE with the new instruction * - IPI-SYNC * - write first byte * - IPI-SYNC * So before the text poke event timestamp, the decoder will see * either the old instruction flow or FUP/TIP of INT3. After the * text poke event timestamp, the decoder will see either the * new instruction flow or FUP/TIP of INT3. Thus decoders can * use the timestamp as the point at which to modify the * executable code. * The old instruction is recorded so that the event can be * processed forwards or backwards. */ perf_event_text_poke(text_poke_addr(&tp[i]), old, len, new, len); } if (do_sync) { /* * According to Intel, this core syncing is very likely * not necessary and we'd be safe even without it. But * better safe than sorry (plus there's not only Intel). */ text_poke_sync(); } /* * Third step: replace the first byte (int3) by the first byte of * replacing opcode. */ for (do_sync = 0, i = 0; i < nr_entries; i++) { u8 byte = tp[i].text[0]; if (tp[i].len == 6) byte = 0x0f; if (byte == INT3_INSN_OPCODE) continue; text_poke(text_poke_addr(&tp[i]), &byte, INT3_INSN_SIZE); do_sync++; } if (do_sync) text_poke_sync(); /* * Remove and wait for refs to be zero. */ if (!atomic_dec_and_test(&bp_desc.refs)) atomic_cond_read_acquire(&bp_desc.refs, !VAL); } static void text_poke_loc_init(struct text_poke_loc *tp, void *addr, const void *opcode, size_t len, const void *emulate) { struct insn insn; int ret, i = 0; if (len == 6) i = 1; memcpy((void *)tp->text, opcode+i, len-i); if (!emulate) emulate = opcode; ret = insn_decode_kernel(&insn, emulate); BUG_ON(ret < 0); tp->rel_addr = addr - (void *)_stext; tp->len = len; tp->opcode = insn.opcode.bytes[0]; if (is_jcc32(&insn)) { /* * Map Jcc.d32 onto Jcc.d8 and use len to distinguish. */ tp->opcode = insn.opcode.bytes[1] - 0x10; } switch (tp->opcode) { case RET_INSN_OPCODE: case JMP32_INSN_OPCODE: case JMP8_INSN_OPCODE: /* * Control flow instructions without implied execution of the * next instruction can be padded with INT3. */ for (i = insn.length; i < len; i++) BUG_ON(tp->text[i] != INT3_INSN_OPCODE); break; default: BUG_ON(len != insn.length); } switch (tp->opcode) { case INT3_INSN_OPCODE: case RET_INSN_OPCODE: break; case CALL_INSN_OPCODE: case JMP32_INSN_OPCODE: case JMP8_INSN_OPCODE: case 0x70 ... 0x7f: /* Jcc */ tp->disp = insn.immediate.value; break; default: /* assume NOP */ switch (len) { case 2: /* NOP2 -- emulate as JMP8+0 */ BUG_ON(memcmp(emulate, x86_nops[len], len)); tp->opcode = JMP8_INSN_OPCODE; tp->disp = 0; break; case 5: /* NOP5 -- emulate as JMP32+0 */ BUG_ON(memcmp(emulate, x86_nops[len], len)); tp->opcode = JMP32_INSN_OPCODE; tp->disp = 0; break; default: /* unknown instruction */ BUG(); } break; } } /* * We hard rely on the tp_vec being ordered; ensure this is so by flushing * early if needed. */ static bool tp_order_fail(void *addr) { struct text_poke_loc *tp; if (!tp_vec_nr) return false; if (!addr) /* force */ return true; tp = &tp_vec[tp_vec_nr - 1]; if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr) return true; return false; } static void text_poke_flush(void *addr) { if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) { text_poke_bp_batch(tp_vec, tp_vec_nr); tp_vec_nr = 0; } } void text_poke_finish(void) { text_poke_flush(NULL); } void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate) { struct text_poke_loc *tp; text_poke_flush(addr); tp = &tp_vec[tp_vec_nr++]; text_poke_loc_init(tp, addr, opcode, len, emulate); } /** * text_poke_bp() -- update instructions on live kernel on SMP * @addr: address to patch * @opcode: opcode of new instruction * @len: length to copy * @emulate: instruction to be emulated * * Update a single instruction with the vector in the stack, avoiding * dynamically allocated memory. This function should be used when it is * not possible to allocate memory. */ void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate) { struct text_poke_loc tp; text_poke_loc_init(&tp, addr, opcode, len, emulate); text_poke_bp_batch(&tp, 1); }
linux-master
arch/x86/kernel/alternative.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2013 Seiji Aguchi <[email protected]> */ #include <linux/jump_label.h> #include <linux/atomic.h> #include <asm/trace/exceptions.h> DEFINE_STATIC_KEY_FALSE(trace_pagefault_key); int trace_pagefault_reg(void) { static_branch_inc(&trace_pagefault_key); return 0; } void trace_pagefault_unreg(void) { static_branch_dec(&trace_pagefault_key); }
linux-master
arch/x86/kernel/tracepoint.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 1995 Linus Torvalds * * Pentium III FXSR, SSE support * Gareth Hughes <[email protected]>, May 2000 * * X86-64 port * Andi Kleen. * * CPU hotplug support - [email protected] */ /* * This file handles the architecture-dependent parts of process handling.. */ #include <linux/cpu.h> #include <linux/errno.h> #include <linux/sched.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/elfcore.h> #include <linux/smp.h> #include <linux/slab.h> #include <linux/user.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/export.h> #include <linux/ptrace.h> #include <linux/notifier.h> #include <linux/kprobes.h> #include <linux/kdebug.h> #include <linux/prctl.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/ftrace.h> #include <linux/syscalls.h> #include <linux/iommu.h> #include <asm/processor.h> #include <asm/pkru.h> #include <asm/fpu/sched.h> #include <asm/mmu_context.h> #include <asm/prctl.h> #include <asm/desc.h> #include <asm/proto.h> #include <asm/ia32.h> #include <asm/debugreg.h> #include <asm/switch_to.h> #include <asm/xen/hypervisor.h> #include <asm/vdso.h> #include <asm/resctrl.h> #include <asm/unistd.h> #include <asm/fsgsbase.h> #ifdef CONFIG_IA32_EMULATION /* Not included via unistd.h */ #include <asm/unistd_32_ia32.h> #endif #include "process.h" /* Prints also some state that isn't saved in the pt_regs */ void __show_regs(struct pt_regs *regs, enum show_regs_mode mode, const char *log_lvl) { unsigned long cr0 = 0L, cr2 = 0L, cr3 = 0L, cr4 = 0L, fs, gs, shadowgs; unsigned long d0, d1, d2, d3, d6, d7; unsigned int fsindex, gsindex; unsigned int ds, es; show_iret_regs(regs, log_lvl); if (regs->orig_ax != -1) pr_cont(" ORIG_RAX: %016lx\n", regs->orig_ax); else pr_cont("\n"); printk("%sRAX: %016lx RBX: %016lx RCX: %016lx\n", log_lvl, regs->ax, regs->bx, regs->cx); printk("%sRDX: %016lx RSI: %016lx RDI: %016lx\n", log_lvl, regs->dx, regs->si, regs->di); printk("%sRBP: %016lx R08: %016lx R09: %016lx\n", log_lvl, regs->bp, regs->r8, regs->r9); printk("%sR10: %016lx R11: %016lx R12: %016lx\n", log_lvl, regs->r10, regs->r11, regs->r12); printk("%sR13: %016lx R14: %016lx R15: %016lx\n", log_lvl, regs->r13, regs->r14, regs->r15); if (mode == SHOW_REGS_SHORT) return; if (mode == SHOW_REGS_USER) { rdmsrl(MSR_FS_BASE, fs); rdmsrl(MSR_KERNEL_GS_BASE, shadowgs); printk("%sFS: %016lx GS: %016lx\n", log_lvl, fs, shadowgs); return; } asm("movl %%ds,%0" : "=r" (ds)); asm("movl %%es,%0" : "=r" (es)); asm("movl %%fs,%0" : "=r" (fsindex)); asm("movl %%gs,%0" : "=r" (gsindex)); rdmsrl(MSR_FS_BASE, fs); rdmsrl(MSR_GS_BASE, gs); rdmsrl(MSR_KERNEL_GS_BASE, shadowgs); cr0 = read_cr0(); cr2 = read_cr2(); cr3 = __read_cr3(); cr4 = __read_cr4(); printk("%sFS: %016lx(%04x) GS:%016lx(%04x) knlGS:%016lx\n", log_lvl, fs, fsindex, gs, gsindex, shadowgs); printk("%sCS: %04lx DS: %04x ES: %04x CR0: %016lx\n", log_lvl, regs->cs, ds, es, cr0); printk("%sCR2: %016lx CR3: %016lx CR4: %016lx\n", log_lvl, cr2, cr3, cr4); get_debugreg(d0, 0); get_debugreg(d1, 1); get_debugreg(d2, 2); get_debugreg(d3, 3); get_debugreg(d6, 6); get_debugreg(d7, 7); /* Only print out debug registers if they are in their non-default state. */ if (!((d0 == 0) && (d1 == 0) && (d2 == 0) && (d3 == 0) && (d6 == DR6_RESERVED) && (d7 == 0x400))) { printk("%sDR0: %016lx DR1: %016lx DR2: %016lx\n", log_lvl, d0, d1, d2); printk("%sDR3: %016lx DR6: %016lx DR7: %016lx\n", log_lvl, d3, d6, d7); } if (cpu_feature_enabled(X86_FEATURE_OSPKE)) printk("%sPKRU: %08x\n", log_lvl, read_pkru()); } void release_thread(struct task_struct *dead_task) { WARN_ON(dead_task->mm); } enum which_selector { FS, GS }; /* * Out of line to be protected from kprobes and tracing. If this would be * traced or probed than any access to a per CPU variable happens with * the wrong GS. * * It is not used on Xen paravirt. When paravirt support is needed, it * needs to be renamed with native_ prefix. */ static noinstr unsigned long __rdgsbase_inactive(void) { unsigned long gsbase; lockdep_assert_irqs_disabled(); if (!cpu_feature_enabled(X86_FEATURE_XENPV)) { native_swapgs(); gsbase = rdgsbase(); native_swapgs(); } else { instrumentation_begin(); rdmsrl(MSR_KERNEL_GS_BASE, gsbase); instrumentation_end(); } return gsbase; } /* * Out of line to be protected from kprobes and tracing. If this would be * traced or probed than any access to a per CPU variable happens with * the wrong GS. * * It is not used on Xen paravirt. When paravirt support is needed, it * needs to be renamed with native_ prefix. */ static noinstr void __wrgsbase_inactive(unsigned long gsbase) { lockdep_assert_irqs_disabled(); if (!cpu_feature_enabled(X86_FEATURE_XENPV)) { native_swapgs(); wrgsbase(gsbase); native_swapgs(); } else { instrumentation_begin(); wrmsrl(MSR_KERNEL_GS_BASE, gsbase); instrumentation_end(); } } /* * Saves the FS or GS base for an outgoing thread if FSGSBASE extensions are * not available. The goal is to be reasonably fast on non-FSGSBASE systems. * It's forcibly inlined because it'll generate better code and this function * is hot. */ static __always_inline void save_base_legacy(struct task_struct *prev_p, unsigned short selector, enum which_selector which) { if (likely(selector == 0)) { /* * On Intel (without X86_BUG_NULL_SEG), the segment base could * be the pre-existing saved base or it could be zero. On AMD * (with X86_BUG_NULL_SEG), the segment base could be almost * anything. * * This branch is very hot (it's hit twice on almost every * context switch between 64-bit programs), and avoiding * the RDMSR helps a lot, so we just assume that whatever * value is already saved is correct. This matches historical * Linux behavior, so it won't break existing applications. * * To avoid leaking state, on non-X86_BUG_NULL_SEG CPUs, if we * report that the base is zero, it needs to actually be zero: * see the corresponding logic in load_seg_legacy. */ } else { /* * If the selector is 1, 2, or 3, then the base is zero on * !X86_BUG_NULL_SEG CPUs and could be anything on * X86_BUG_NULL_SEG CPUs. In the latter case, Linux * has never attempted to preserve the base across context * switches. * * If selector > 3, then it refers to a real segment, and * saving the base isn't necessary. */ if (which == FS) prev_p->thread.fsbase = 0; else prev_p->thread.gsbase = 0; } } static __always_inline void save_fsgs(struct task_struct *task) { savesegment(fs, task->thread.fsindex); savesegment(gs, task->thread.gsindex); if (static_cpu_has(X86_FEATURE_FSGSBASE)) { /* * If FSGSBASE is enabled, we can't make any useful guesses * about the base, and user code expects us to save the current * value. Fortunately, reading the base directly is efficient. */ task->thread.fsbase = rdfsbase(); task->thread.gsbase = __rdgsbase_inactive(); } else { save_base_legacy(task, task->thread.fsindex, FS); save_base_legacy(task, task->thread.gsindex, GS); } } /* * While a process is running,current->thread.fsbase and current->thread.gsbase * may not match the corresponding CPU registers (see save_base_legacy()). */ void current_save_fsgs(void) { unsigned long flags; /* Interrupts need to be off for FSGSBASE */ local_irq_save(flags); save_fsgs(current); local_irq_restore(flags); } #if IS_ENABLED(CONFIG_KVM) EXPORT_SYMBOL_GPL(current_save_fsgs); #endif static __always_inline void loadseg(enum which_selector which, unsigned short sel) { if (which == FS) loadsegment(fs, sel); else load_gs_index(sel); } static __always_inline void load_seg_legacy(unsigned short prev_index, unsigned long prev_base, unsigned short next_index, unsigned long next_base, enum which_selector which) { if (likely(next_index <= 3)) { /* * The next task is using 64-bit TLS, is not using this * segment at all, or is having fun with arcane CPU features. */ if (next_base == 0) { /* * Nasty case: on AMD CPUs, we need to forcibly zero * the base. */ if (static_cpu_has_bug(X86_BUG_NULL_SEG)) { loadseg(which, __USER_DS); loadseg(which, next_index); } else { /* * We could try to exhaustively detect cases * under which we can skip the segment load, * but there's really only one case that matters * for performance: if both the previous and * next states are fully zeroed, we can skip * the load. * * (This assumes that prev_base == 0 has no * false positives. This is the case on * Intel-style CPUs.) */ if (likely(prev_index | next_index | prev_base)) loadseg(which, next_index); } } else { if (prev_index != next_index) loadseg(which, next_index); wrmsrl(which == FS ? MSR_FS_BASE : MSR_KERNEL_GS_BASE, next_base); } } else { /* * The next task is using a real segment. Loading the selector * is sufficient. */ loadseg(which, next_index); } } /* * Store prev's PKRU value and load next's PKRU value if they differ. PKRU * is not XSTATE managed on context switch because that would require a * lookup in the task's FPU xsave buffer and require to keep that updated * in various places. */ static __always_inline void x86_pkru_load(struct thread_struct *prev, struct thread_struct *next) { if (!cpu_feature_enabled(X86_FEATURE_OSPKE)) return; /* Stash the prev task's value: */ prev->pkru = rdpkru(); /* * PKRU writes are slightly expensive. Avoid them when not * strictly necessary: */ if (prev->pkru != next->pkru) wrpkru(next->pkru); } static __always_inline void x86_fsgsbase_load(struct thread_struct *prev, struct thread_struct *next) { if (static_cpu_has(X86_FEATURE_FSGSBASE)) { /* Update the FS and GS selectors if they could have changed. */ if (unlikely(prev->fsindex || next->fsindex)) loadseg(FS, next->fsindex); if (unlikely(prev->gsindex || next->gsindex)) loadseg(GS, next->gsindex); /* Update the bases. */ wrfsbase(next->fsbase); __wrgsbase_inactive(next->gsbase); } else { load_seg_legacy(prev->fsindex, prev->fsbase, next->fsindex, next->fsbase, FS); load_seg_legacy(prev->gsindex, prev->gsbase, next->gsindex, next->gsbase, GS); } } unsigned long x86_fsgsbase_read_task(struct task_struct *task, unsigned short selector) { unsigned short idx = selector >> 3; unsigned long base; if (likely((selector & SEGMENT_TI_MASK) == 0)) { if (unlikely(idx >= GDT_ENTRIES)) return 0; /* * There are no user segments in the GDT with nonzero bases * other than the TLS segments. */ if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX) return 0; idx -= GDT_ENTRY_TLS_MIN; base = get_desc_base(&task->thread.tls_array[idx]); } else { #ifdef CONFIG_MODIFY_LDT_SYSCALL struct ldt_struct *ldt; /* * If performance here mattered, we could protect the LDT * with RCU. This is a slow path, though, so we can just * take the mutex. */ mutex_lock(&task->mm->context.lock); ldt = task->mm->context.ldt; if (unlikely(!ldt || idx >= ldt->nr_entries)) base = 0; else base = get_desc_base(ldt->entries + idx); mutex_unlock(&task->mm->context.lock); #else base = 0; #endif } return base; } unsigned long x86_gsbase_read_cpu_inactive(void) { unsigned long gsbase; if (boot_cpu_has(X86_FEATURE_FSGSBASE)) { unsigned long flags; local_irq_save(flags); gsbase = __rdgsbase_inactive(); local_irq_restore(flags); } else { rdmsrl(MSR_KERNEL_GS_BASE, gsbase); } return gsbase; } void x86_gsbase_write_cpu_inactive(unsigned long gsbase) { if (boot_cpu_has(X86_FEATURE_FSGSBASE)) { unsigned long flags; local_irq_save(flags); __wrgsbase_inactive(gsbase); local_irq_restore(flags); } else { wrmsrl(MSR_KERNEL_GS_BASE, gsbase); } } unsigned long x86_fsbase_read_task(struct task_struct *task) { unsigned long fsbase; if (task == current) fsbase = x86_fsbase_read_cpu(); else if (boot_cpu_has(X86_FEATURE_FSGSBASE) || (task->thread.fsindex == 0)) fsbase = task->thread.fsbase; else fsbase = x86_fsgsbase_read_task(task, task->thread.fsindex); return fsbase; } unsigned long x86_gsbase_read_task(struct task_struct *task) { unsigned long gsbase; if (task == current) gsbase = x86_gsbase_read_cpu_inactive(); else if (boot_cpu_has(X86_FEATURE_FSGSBASE) || (task->thread.gsindex == 0)) gsbase = task->thread.gsbase; else gsbase = x86_fsgsbase_read_task(task, task->thread.gsindex); return gsbase; } void x86_fsbase_write_task(struct task_struct *task, unsigned long fsbase) { WARN_ON_ONCE(task == current); task->thread.fsbase = fsbase; } void x86_gsbase_write_task(struct task_struct *task, unsigned long gsbase) { WARN_ON_ONCE(task == current); task->thread.gsbase = gsbase; } static void start_thread_common(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp, unsigned int _cs, unsigned int _ss, unsigned int _ds) { WARN_ON_ONCE(regs != current_pt_regs()); if (static_cpu_has(X86_BUG_NULL_SEG)) { /* Loading zero below won't clear the base. */ loadsegment(fs, __USER_DS); load_gs_index(__USER_DS); } reset_thread_features(); loadsegment(fs, 0); loadsegment(es, _ds); loadsegment(ds, _ds); load_gs_index(0); regs->ip = new_ip; regs->sp = new_sp; regs->cs = _cs; regs->ss = _ss; regs->flags = X86_EFLAGS_IF; } void start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp) { start_thread_common(regs, new_ip, new_sp, __USER_CS, __USER_DS, 0); } EXPORT_SYMBOL_GPL(start_thread); #ifdef CONFIG_COMPAT void compat_start_thread(struct pt_regs *regs, u32 new_ip, u32 new_sp, bool x32) { start_thread_common(regs, new_ip, new_sp, x32 ? __USER_CS : __USER32_CS, __USER_DS, __USER_DS); } #endif /* * switch_to(x,y) should switch tasks from x to y. * * This could still be optimized: * - fold all the options into a flag word and test it with a single test. * - could test fs/gs bitsliced * * Kprobes not supported here. Set the probe on schedule instead. * Function graph tracer not supported too. */ __no_kmsan_checks __visible __notrace_funcgraph struct task_struct * __switch_to(struct task_struct *prev_p, struct task_struct *next_p) { struct thread_struct *prev = &prev_p->thread; struct thread_struct *next = &next_p->thread; struct fpu *prev_fpu = &prev->fpu; int cpu = smp_processor_id(); WARN_ON_ONCE(IS_ENABLED(CONFIG_DEBUG_ENTRY) && this_cpu_read(pcpu_hot.hardirq_stack_inuse)); if (!test_thread_flag(TIF_NEED_FPU_LOAD)) switch_fpu_prepare(prev_fpu, cpu); /* We must save %fs and %gs before load_TLS() because * %fs and %gs may be cleared by load_TLS(). * * (e.g. xen_load_tls()) */ save_fsgs(prev_p); /* * Load TLS before restoring any segments so that segment loads * reference the correct GDT entries. */ load_TLS(next, cpu); /* * Leave lazy mode, flushing any hypercalls made here. This * must be done after loading TLS entries in the GDT but before * loading segments that might reference them. */ arch_end_context_switch(next_p); /* Switch DS and ES. * * Reading them only returns the selectors, but writing them (if * nonzero) loads the full descriptor from the GDT or LDT. The * LDT for next is loaded in switch_mm, and the GDT is loaded * above. * * We therefore need to write new values to the segment * registers on every context switch unless both the new and old * values are zero. * * Note that we don't need to do anything for CS and SS, as * those are saved and restored as part of pt_regs. */ savesegment(es, prev->es); if (unlikely(next->es | prev->es)) loadsegment(es, next->es); savesegment(ds, prev->ds); if (unlikely(next->ds | prev->ds)) loadsegment(ds, next->ds); x86_fsgsbase_load(prev, next); x86_pkru_load(prev, next); /* * Switch the PDA and FPU contexts. */ raw_cpu_write(pcpu_hot.current_task, next_p); raw_cpu_write(pcpu_hot.top_of_stack, task_top_of_stack(next_p)); switch_fpu_finish(); /* Reload sp0. */ update_task_stack(next_p); switch_to_extra(prev_p, next_p); if (static_cpu_has_bug(X86_BUG_SYSRET_SS_ATTRS)) { /* * AMD CPUs have a misfeature: SYSRET sets the SS selector but * does not update the cached descriptor. As a result, if we * do SYSRET while SS is NULL, we'll end up in user mode with * SS apparently equal to __USER_DS but actually unusable. * * The straightforward workaround would be to fix it up just * before SYSRET, but that would slow down the system call * fast paths. Instead, we ensure that SS is never NULL in * system call context. We do this by replacing NULL SS * selectors at every context switch. SYSCALL sets up a valid * SS, so the only way to get NULL is to re-enter the kernel * from CPL 3 through an interrupt. Since that can't happen * in the same task as a running syscall, we are guaranteed to * context switch between every interrupt vector entry and a * subsequent SYSRET. * * We read SS first because SS reads are much faster than * writes. Out of caution, we force SS to __KERNEL_DS even if * it previously had a different non-NULL value. */ unsigned short ss_sel; savesegment(ss, ss_sel); if (ss_sel != __KERNEL_DS) loadsegment(ss, __KERNEL_DS); } /* Load the Intel cache allocation PQR MSR. */ resctrl_sched_in(next_p); return prev_p; } void set_personality_64bit(void) { /* inherit personality from parent */ /* Make sure to be in 64bit mode */ clear_thread_flag(TIF_ADDR32); /* Pretend that this comes from a 64bit execve */ task_pt_regs(current)->orig_ax = __NR_execve; current_thread_info()->status &= ~TS_COMPAT; if (current->mm) __set_bit(MM_CONTEXT_HAS_VSYSCALL, &current->mm->context.flags); /* TBD: overwrites user setup. Should have two bits. But 64bit processes have always behaved this way, so it's not too bad. The main problem is just that 32bit children are affected again. */ current->personality &= ~READ_IMPLIES_EXEC; } static void __set_personality_x32(void) { #ifdef CONFIG_X86_X32_ABI if (current->mm) current->mm->context.flags = 0; current->personality &= ~READ_IMPLIES_EXEC; /* * in_32bit_syscall() uses the presence of the x32 syscall bit * flag to determine compat status. The x86 mmap() code relies on * the syscall bitness so set x32 syscall bit right here to make * in_32bit_syscall() work during exec(). * * Pretend to come from a x32 execve. */ task_pt_regs(current)->orig_ax = __NR_x32_execve | __X32_SYSCALL_BIT; current_thread_info()->status &= ~TS_COMPAT; #endif } static void __set_personality_ia32(void) { #ifdef CONFIG_IA32_EMULATION if (current->mm) { /* * uprobes applied to this MM need to know this and * cannot use user_64bit_mode() at that time. */ __set_bit(MM_CONTEXT_UPROBE_IA32, &current->mm->context.flags); } current->personality |= force_personality32; /* Prepare the first "return" to user space */ task_pt_regs(current)->orig_ax = __NR_ia32_execve; current_thread_info()->status |= TS_COMPAT; #endif } void set_personality_ia32(bool x32) { /* Make sure to be in 32bit mode */ set_thread_flag(TIF_ADDR32); if (x32) __set_personality_x32(); else __set_personality_ia32(); } EXPORT_SYMBOL_GPL(set_personality_ia32); #ifdef CONFIG_CHECKPOINT_RESTORE static long prctl_map_vdso(const struct vdso_image *image, unsigned long addr) { int ret; ret = map_vdso_once(image, addr); if (ret) return ret; return (long)image->size; } #endif #ifdef CONFIG_ADDRESS_MASKING #define LAM_U57_BITS 6 static int prctl_enable_tagged_addr(struct mm_struct *mm, unsigned long nr_bits) { if (!cpu_feature_enabled(X86_FEATURE_LAM)) return -ENODEV; /* PTRACE_ARCH_PRCTL */ if (current->mm != mm) return -EINVAL; if (mm_valid_pasid(mm) && !test_bit(MM_CONTEXT_FORCE_TAGGED_SVA, &mm->context.flags)) return -EINVAL; if (mmap_write_lock_killable(mm)) return -EINTR; if (test_bit(MM_CONTEXT_LOCK_LAM, &mm->context.flags)) { mmap_write_unlock(mm); return -EBUSY; } if (!nr_bits) { mmap_write_unlock(mm); return -EINVAL; } else if (nr_bits <= LAM_U57_BITS) { mm->context.lam_cr3_mask = X86_CR3_LAM_U57; mm->context.untag_mask = ~GENMASK(62, 57); } else { mmap_write_unlock(mm); return -EINVAL; } write_cr3(__read_cr3() | mm->context.lam_cr3_mask); set_tlbstate_lam_mode(mm); set_bit(MM_CONTEXT_LOCK_LAM, &mm->context.flags); mmap_write_unlock(mm); return 0; } #endif long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2) { int ret = 0; switch (option) { case ARCH_SET_GS: { if (unlikely(arg2 >= TASK_SIZE_MAX)) return -EPERM; preempt_disable(); /* * ARCH_SET_GS has always overwritten the index * and the base. Zero is the most sensible value * to put in the index, and is the only value that * makes any sense if FSGSBASE is unavailable. */ if (task == current) { loadseg(GS, 0); x86_gsbase_write_cpu_inactive(arg2); /* * On non-FSGSBASE systems, save_base_legacy() expects * that we also fill in thread.gsbase. */ task->thread.gsbase = arg2; } else { task->thread.gsindex = 0; x86_gsbase_write_task(task, arg2); } preempt_enable(); break; } case ARCH_SET_FS: { /* * Not strictly needed for %fs, but do it for symmetry * with %gs */ if (unlikely(arg2 >= TASK_SIZE_MAX)) return -EPERM; preempt_disable(); /* * Set the selector to 0 for the same reason * as %gs above. */ if (task == current) { loadseg(FS, 0); x86_fsbase_write_cpu(arg2); /* * On non-FSGSBASE systems, save_base_legacy() expects * that we also fill in thread.fsbase. */ task->thread.fsbase = arg2; } else { task->thread.fsindex = 0; x86_fsbase_write_task(task, arg2); } preempt_enable(); break; } case ARCH_GET_FS: { unsigned long base = x86_fsbase_read_task(task); ret = put_user(base, (unsigned long __user *)arg2); break; } case ARCH_GET_GS: { unsigned long base = x86_gsbase_read_task(task); ret = put_user(base, (unsigned long __user *)arg2); break; } #ifdef CONFIG_CHECKPOINT_RESTORE # ifdef CONFIG_X86_X32_ABI case ARCH_MAP_VDSO_X32: return prctl_map_vdso(&vdso_image_x32, arg2); # endif # if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION case ARCH_MAP_VDSO_32: return prctl_map_vdso(&vdso_image_32, arg2); # endif case ARCH_MAP_VDSO_64: return prctl_map_vdso(&vdso_image_64, arg2); #endif #ifdef CONFIG_ADDRESS_MASKING case ARCH_GET_UNTAG_MASK: return put_user(task->mm->context.untag_mask, (unsigned long __user *)arg2); case ARCH_ENABLE_TAGGED_ADDR: return prctl_enable_tagged_addr(task->mm, arg2); case ARCH_FORCE_TAGGED_SVA: if (current != task) return -EINVAL; set_bit(MM_CONTEXT_FORCE_TAGGED_SVA, &task->mm->context.flags); return 0; case ARCH_GET_MAX_TAG_BITS: if (!cpu_feature_enabled(X86_FEATURE_LAM)) return put_user(0, (unsigned long __user *)arg2); else return put_user(LAM_U57_BITS, (unsigned long __user *)arg2); #endif case ARCH_SHSTK_ENABLE: case ARCH_SHSTK_DISABLE: case ARCH_SHSTK_LOCK: case ARCH_SHSTK_UNLOCK: case ARCH_SHSTK_STATUS: return shstk_prctl(task, option, arg2); default: ret = -EINVAL; break; } return ret; } SYSCALL_DEFINE2(arch_prctl, int, option, unsigned long, arg2) { long ret; ret = do_arch_prctl_64(current, option, arg2); if (ret == -EINVAL) ret = do_arch_prctl_common(option, arg2); return ret; } #ifdef CONFIG_IA32_EMULATION COMPAT_SYSCALL_DEFINE2(arch_prctl, int, option, unsigned long, arg2) { return do_arch_prctl_common(option, arg2); } #endif unsigned long KSTK_ESP(struct task_struct *task) { return task_pt_regs(task)->sp; }
linux-master
arch/x86/kernel/process_64.c
// SPDX-License-Identifier: GPL-2.0 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/export.h> #include <linux/reboot.h> #include <linux/init.h> #include <linux/pm.h> #include <linux/efi.h> #include <linux/dmi.h> #include <linux/sched.h> #include <linux/tboot.h> #include <linux/delay.h> #include <linux/objtool.h> #include <linux/pgtable.h> #include <acpi/reboot.h> #include <asm/io.h> #include <asm/apic.h> #include <asm/io_apic.h> #include <asm/desc.h> #include <asm/hpet.h> #include <asm/proto.h> #include <asm/reboot_fixups.h> #include <asm/reboot.h> #include <asm/pci_x86.h> #include <asm/cpu.h> #include <asm/nmi.h> #include <asm/smp.h> #include <linux/ctype.h> #include <linux/mc146818rtc.h> #include <asm/realmode.h> #include <asm/x86_init.h> #include <asm/efi.h> /* * Power off function, if any */ void (*pm_power_off)(void); EXPORT_SYMBOL(pm_power_off); /* * This is set if we need to go through the 'emergency' path. * When machine_emergency_restart() is called, we may be on * an inconsistent state and won't be able to do a clean cleanup */ static int reboot_emergency; /* This is set by the PCI code if either type 1 or type 2 PCI is detected */ bool port_cf9_safe = false; /* * Reboot options and system auto-detection code provided by * Dell Inc. so their systems "just work". :-) */ /* * Some machines require the "reboot=a" commandline options */ static int __init set_acpi_reboot(const struct dmi_system_id *d) { if (reboot_type != BOOT_ACPI) { reboot_type = BOOT_ACPI; pr_info("%s series board detected. Selecting %s-method for reboots.\n", d->ident, "ACPI"); } return 0; } /* * Some machines require the "reboot=b" or "reboot=k" commandline options, * this quirk makes that automatic. */ static int __init set_bios_reboot(const struct dmi_system_id *d) { if (reboot_type != BOOT_BIOS) { reboot_type = BOOT_BIOS; pr_info("%s series board detected. Selecting %s-method for reboots.\n", d->ident, "BIOS"); } return 0; } /* * Some machines don't handle the default ACPI reboot method and * require the EFI reboot method: */ static int __init set_efi_reboot(const struct dmi_system_id *d) { if (reboot_type != BOOT_EFI && !efi_runtime_disabled()) { reboot_type = BOOT_EFI; pr_info("%s series board detected. Selecting EFI-method for reboot.\n", d->ident); } return 0; } void __noreturn machine_real_restart(unsigned int type) { local_irq_disable(); /* * Write zero to CMOS register number 0x0f, which the BIOS POST * routine will recognize as telling it to do a proper reboot. (Well * that's what this book in front of me says -- it may only apply to * the Phoenix BIOS though, it's not clear). At the same time, * disable NMIs by setting the top bit in the CMOS address register, * as we're about to do peculiar things to the CPU. I'm not sure if * `outb_p' is needed instead of just `outb'. Use it to be on the * safe side. (Yes, CMOS_WRITE does outb_p's. - Paul G.) */ spin_lock(&rtc_lock); CMOS_WRITE(0x00, 0x8f); spin_unlock(&rtc_lock); /* * Switch to the trampoline page table. */ load_trampoline_pgtable(); /* Jump to the identity-mapped low memory code */ #ifdef CONFIG_X86_32 asm volatile("jmpl *%0" : : "rm" (real_mode_header->machine_real_restart_asm), "a" (type)); #else asm volatile("ljmpl *%0" : : "m" (real_mode_header->machine_real_restart_asm), "D" (type)); #endif unreachable(); } #ifdef CONFIG_APM_MODULE EXPORT_SYMBOL(machine_real_restart); #endif STACK_FRAME_NON_STANDARD(machine_real_restart); /* * Some Apple MacBook and MacBookPro's needs reboot=p to be able to reboot */ static int __init set_pci_reboot(const struct dmi_system_id *d) { if (reboot_type != BOOT_CF9_FORCE) { reboot_type = BOOT_CF9_FORCE; pr_info("%s series board detected. Selecting %s-method for reboots.\n", d->ident, "PCI"); } return 0; } static int __init set_kbd_reboot(const struct dmi_system_id *d) { if (reboot_type != BOOT_KBD) { reboot_type = BOOT_KBD; pr_info("%s series board detected. Selecting %s-method for reboot.\n", d->ident, "KBD"); } return 0; } /* * This is a single dmi_table handling all reboot quirks. */ static const struct dmi_system_id reboot_dmi_table[] __initconst = { /* Acer */ { /* Handle reboot issue on Acer Aspire one */ .callback = set_kbd_reboot, .ident = "Acer Aspire One A110", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "AOA110"), }, }, { /* Handle reboot issue on Acer TravelMate X514-51T */ .callback = set_efi_reboot, .ident = "Acer TravelMate X514-51T", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate X514-51T"), }, }, /* Apple */ { /* Handle problems with rebooting on Apple MacBook5 */ .callback = set_pci_reboot, .ident = "Apple MacBook5", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Apple Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "MacBook5"), }, }, { /* Handle problems with rebooting on Apple MacBook6,1 */ .callback = set_pci_reboot, .ident = "Apple MacBook6,1", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Apple Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "MacBook6,1"), }, }, { /* Handle problems with rebooting on Apple MacBookPro5 */ .callback = set_pci_reboot, .ident = "Apple MacBookPro5", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Apple Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "MacBookPro5"), }, }, { /* Handle problems with rebooting on Apple Macmini3,1 */ .callback = set_pci_reboot, .ident = "Apple Macmini3,1", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Apple Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Macmini3,1"), }, }, { /* Handle problems with rebooting on the iMac9,1. */ .callback = set_pci_reboot, .ident = "Apple iMac9,1", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Apple Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "iMac9,1"), }, }, { /* Handle problems with rebooting on the iMac10,1. */ .callback = set_pci_reboot, .ident = "Apple iMac10,1", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Apple Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "iMac10,1"), }, }, /* ASRock */ { /* Handle problems with rebooting on ASRock Q1900DC-ITX */ .callback = set_pci_reboot, .ident = "ASRock Q1900DC-ITX", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "ASRock"), DMI_MATCH(DMI_BOARD_NAME, "Q1900DC-ITX"), }, }, /* ASUS */ { /* Handle problems with rebooting on ASUS P4S800 */ .callback = set_bios_reboot, .ident = "ASUS P4S800", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."), DMI_MATCH(DMI_BOARD_NAME, "P4S800"), }, }, { /* Handle problems with rebooting on ASUS EeeBook X205TA */ .callback = set_acpi_reboot, .ident = "ASUS EeeBook X205TA", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK COMPUTER INC."), DMI_MATCH(DMI_PRODUCT_NAME, "X205TA"), }, }, { /* Handle problems with rebooting on ASUS EeeBook X205TAW */ .callback = set_acpi_reboot, .ident = "ASUS EeeBook X205TAW", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK COMPUTER INC."), DMI_MATCH(DMI_PRODUCT_NAME, "X205TAW"), }, }, /* Certec */ { /* Handle problems with rebooting on Certec BPC600 */ .callback = set_pci_reboot, .ident = "Certec BPC600", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Certec"), DMI_MATCH(DMI_PRODUCT_NAME, "BPC600"), }, }, /* Dell */ { /* Handle problems with rebooting on Dell DXP061 */ .callback = set_bios_reboot, .ident = "Dell DXP061", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Dell DXP061"), }, }, { /* Handle problems with rebooting on Dell E520's */ .callback = set_bios_reboot, .ident = "Dell E520", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Dell DM061"), }, }, { /* Handle problems with rebooting on the Latitude E5410. */ .callback = set_pci_reboot, .ident = "Dell Latitude E5410", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Latitude E5410"), }, }, { /* Handle problems with rebooting on the Latitude E5420. */ .callback = set_pci_reboot, .ident = "Dell Latitude E5420", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Latitude E5420"), }, }, { /* Handle problems with rebooting on the Latitude E6320. */ .callback = set_pci_reboot, .ident = "Dell Latitude E6320", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Latitude E6320"), }, }, { /* Handle problems with rebooting on the Latitude E6420. */ .callback = set_pci_reboot, .ident = "Dell Latitude E6420", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Latitude E6420"), }, }, { /* Handle problems with rebooting on Dell Optiplex 330 with 0KP561 */ .callback = set_bios_reboot, .ident = "Dell OptiPlex 330", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 330"), DMI_MATCH(DMI_BOARD_NAME, "0KP561"), }, }, { /* Handle problems with rebooting on Dell Optiplex 360 with 0T656F */ .callback = set_bios_reboot, .ident = "Dell OptiPlex 360", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 360"), DMI_MATCH(DMI_BOARD_NAME, "0T656F"), }, }, { /* Handle problems with rebooting on Dell Optiplex 745's SFF */ .callback = set_bios_reboot, .ident = "Dell OptiPlex 745", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 745"), }, }, { /* Handle problems with rebooting on Dell Optiplex 745's DFF */ .callback = set_bios_reboot, .ident = "Dell OptiPlex 745", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 745"), DMI_MATCH(DMI_BOARD_NAME, "0MM599"), }, }, { /* Handle problems with rebooting on Dell Optiplex 745 with 0KW626 */ .callback = set_bios_reboot, .ident = "Dell OptiPlex 745", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 745"), DMI_MATCH(DMI_BOARD_NAME, "0KW626"), }, }, { /* Handle problems with rebooting on Dell OptiPlex 760 with 0G919G */ .callback = set_bios_reboot, .ident = "Dell OptiPlex 760", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 760"), DMI_MATCH(DMI_BOARD_NAME, "0G919G"), }, }, { /* Handle problems with rebooting on the OptiPlex 990. */ .callback = set_pci_reboot, .ident = "Dell OptiPlex 990 BIOS A0x", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 990"), DMI_MATCH(DMI_BIOS_VERSION, "A0"), }, }, { /* Handle problems with rebooting on Dell 300's */ .callback = set_bios_reboot, .ident = "Dell PowerEdge 300", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Computer Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "PowerEdge 300/"), }, }, { /* Handle problems with rebooting on Dell 1300's */ .callback = set_bios_reboot, .ident = "Dell PowerEdge 1300", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Computer Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "PowerEdge 1300/"), }, }, { /* Handle problems with rebooting on Dell 2400's */ .callback = set_bios_reboot, .ident = "Dell PowerEdge 2400", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Computer Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "PowerEdge 2400"), }, }, { /* Handle problems with rebooting on the Dell PowerEdge C6100. */ .callback = set_pci_reboot, .ident = "Dell PowerEdge C6100", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell"), DMI_MATCH(DMI_PRODUCT_NAME, "C6100"), }, }, { /* Handle problems with rebooting on the Precision M6600. */ .callback = set_pci_reboot, .ident = "Dell Precision M6600", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Precision M6600"), }, }, { /* Handle problems with rebooting on Dell T5400's */ .callback = set_bios_reboot, .ident = "Dell Precision T5400", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Precision WorkStation T5400"), }, }, { /* Handle problems with rebooting on Dell T7400's */ .callback = set_bios_reboot, .ident = "Dell Precision T7400", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Precision WorkStation T7400"), }, }, { /* Handle problems with rebooting on Dell XPS710 */ .callback = set_bios_reboot, .ident = "Dell XPS710", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "Dell XPS710"), }, }, { /* Handle problems with rebooting on Dell Optiplex 7450 AIO */ .callback = set_acpi_reboot, .ident = "Dell OptiPlex 7450 AIO", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 7450 AIO"), }, }, /* Hewlett-Packard */ { /* Handle problems with rebooting on HP laptops */ .callback = set_bios_reboot, .ident = "HP Compaq Laptop", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq"), }, }, { /* PCIe Wifi card isn't detected after reboot otherwise */ .callback = set_pci_reboot, .ident = "Zotac ZBOX CI327 nano", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "NA"), DMI_MATCH(DMI_PRODUCT_NAME, "ZBOX-CI327NANO-GS-01"), }, }, /* Sony */ { /* Handle problems with rebooting on Sony VGN-Z540N */ .callback = set_bios_reboot, .ident = "Sony VGN-Z540N", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "VGN-Z540N"), }, }, { } }; static int __init reboot_init(void) { int rv; /* * Only do the DMI check if reboot_type hasn't been overridden * on the command line */ if (!reboot_default) return 0; /* * The DMI quirks table takes precedence. If no quirks entry * matches and the ACPI Hardware Reduced bit is set and EFI * runtime services are enabled, force EFI reboot. */ rv = dmi_check_system(reboot_dmi_table); if (!rv && efi_reboot_required() && !efi_runtime_disabled()) reboot_type = BOOT_EFI; return 0; } core_initcall(reboot_init); static inline void kb_wait(void) { int i; for (i = 0; i < 0x10000; i++) { if ((inb(0x64) & 0x02) == 0) break; udelay(2); } } static inline void nmi_shootdown_cpus_on_restart(void); #if IS_ENABLED(CONFIG_KVM_INTEL) || IS_ENABLED(CONFIG_KVM_AMD) /* RCU-protected callback to disable virtualization prior to reboot. */ static cpu_emergency_virt_cb __rcu *cpu_emergency_virt_callback; void cpu_emergency_register_virt_callback(cpu_emergency_virt_cb *callback) { if (WARN_ON_ONCE(rcu_access_pointer(cpu_emergency_virt_callback))) return; rcu_assign_pointer(cpu_emergency_virt_callback, callback); } EXPORT_SYMBOL_GPL(cpu_emergency_register_virt_callback); void cpu_emergency_unregister_virt_callback(cpu_emergency_virt_cb *callback) { if (WARN_ON_ONCE(rcu_access_pointer(cpu_emergency_virt_callback) != callback)) return; rcu_assign_pointer(cpu_emergency_virt_callback, NULL); synchronize_rcu(); } EXPORT_SYMBOL_GPL(cpu_emergency_unregister_virt_callback); /* * Disable virtualization, i.e. VMX or SVM, to ensure INIT is recognized during * reboot. VMX blocks INIT if the CPU is post-VMXON, and SVM blocks INIT if * GIF=0, i.e. if the crash occurred between CLGI and STGI. */ void cpu_emergency_disable_virtualization(void) { cpu_emergency_virt_cb *callback; /* * IRQs must be disabled as KVM enables virtualization in hardware via * function call IPIs, i.e. IRQs need to be disabled to guarantee * virtualization stays disabled. */ lockdep_assert_irqs_disabled(); rcu_read_lock(); callback = rcu_dereference(cpu_emergency_virt_callback); if (callback) callback(); rcu_read_unlock(); } static void emergency_reboot_disable_virtualization(void) { local_irq_disable(); /* * Disable virtualization on all CPUs before rebooting to avoid hanging * the system, as VMX and SVM block INIT when running in the host. * * We can't take any locks and we may be on an inconsistent state, so * use NMIs as IPIs to tell the other CPUs to disable VMX/SVM and halt. * * Do the NMI shootdown even if virtualization is off on _this_ CPU, as * other CPUs may have virtualization enabled. */ if (rcu_access_pointer(cpu_emergency_virt_callback)) { /* Safely force _this_ CPU out of VMX/SVM operation. */ cpu_emergency_disable_virtualization(); /* Disable VMX/SVM and halt on other CPUs. */ nmi_shootdown_cpus_on_restart(); } } #else static void emergency_reboot_disable_virtualization(void) { } #endif /* CONFIG_KVM_INTEL || CONFIG_KVM_AMD */ void __attribute__((weak)) mach_reboot_fixups(void) { } /* * To the best of our knowledge Windows compatible x86 hardware expects * the following on reboot: * * 1) If the FADT has the ACPI reboot register flag set, try it * 2) If still alive, write to the keyboard controller * 3) If still alive, write to the ACPI reboot register again * 4) If still alive, write to the keyboard controller again * 5) If still alive, call the EFI runtime service to reboot * 6) If no EFI runtime service, call the BIOS to do a reboot * * We default to following the same pattern. We also have * two other reboot methods: 'triple fault' and 'PCI', which * can be triggered via the reboot= kernel boot option or * via quirks. * * This means that this function can never return, it can misbehave * by not rebooting properly and hanging. */ static void native_machine_emergency_restart(void) { int i; int attempt = 0; int orig_reboot_type = reboot_type; unsigned short mode; if (reboot_emergency) emergency_reboot_disable_virtualization(); tboot_shutdown(TB_SHUTDOWN_REBOOT); /* Tell the BIOS if we want cold or warm reboot */ mode = reboot_mode == REBOOT_WARM ? 0x1234 : 0; *((unsigned short *)__va(0x472)) = mode; /* * If an EFI capsule has been registered with the firmware then * override the reboot= parameter. */ if (efi_capsule_pending(NULL)) { pr_info("EFI capsule is pending, forcing EFI reboot.\n"); reboot_type = BOOT_EFI; } for (;;) { /* Could also try the reset bit in the Hammer NB */ switch (reboot_type) { case BOOT_ACPI: acpi_reboot(); reboot_type = BOOT_KBD; break; case BOOT_KBD: mach_reboot_fixups(); /* For board specific fixups */ for (i = 0; i < 10; i++) { kb_wait(); udelay(50); outb(0xfe, 0x64); /* Pulse reset low */ udelay(50); } if (attempt == 0 && orig_reboot_type == BOOT_ACPI) { attempt = 1; reboot_type = BOOT_ACPI; } else { reboot_type = BOOT_EFI; } break; case BOOT_EFI: efi_reboot(reboot_mode, NULL); reboot_type = BOOT_BIOS; break; case BOOT_BIOS: machine_real_restart(MRR_BIOS); /* We're probably dead after this, but... */ reboot_type = BOOT_CF9_SAFE; break; case BOOT_CF9_FORCE: port_cf9_safe = true; fallthrough; case BOOT_CF9_SAFE: if (port_cf9_safe) { u8 reboot_code = reboot_mode == REBOOT_WARM ? 0x06 : 0x0E; u8 cf9 = inb(0xcf9) & ~reboot_code; outb(cf9|2, 0xcf9); /* Request hard reset */ udelay(50); /* Actually do the reset */ outb(cf9|reboot_code, 0xcf9); udelay(50); } reboot_type = BOOT_TRIPLE; break; case BOOT_TRIPLE: idt_invalidate(); __asm__ __volatile__("int3"); /* We're probably dead after this, but... */ reboot_type = BOOT_KBD; break; } } } void native_machine_shutdown(void) { /* Stop the cpus and apics */ #ifdef CONFIG_X86_IO_APIC /* * Disabling IO APIC before local APIC is a workaround for * erratum AVR31 in "Intel Atom Processor C2000 Product Family * Specification Update". In this situation, interrupts that target * a Logical Processor whose Local APIC is either in the process of * being hardware disabled or software disabled are neither delivered * nor discarded. When this erratum occurs, the processor may hang. * * Even without the erratum, it still makes sense to quiet IO APIC * before disabling Local APIC. */ clear_IO_APIC(); #endif #ifdef CONFIG_SMP /* * Stop all of the others. Also disable the local irq to * not receive the per-cpu timer interrupt which may trigger * scheduler's load balance. */ local_irq_disable(); stop_other_cpus(); #endif lapic_shutdown(); restore_boot_irq_mode(); #ifdef CONFIG_HPET_TIMER hpet_disable(); #endif #ifdef CONFIG_X86_64 x86_platform.iommu_shutdown(); #endif } static void __machine_emergency_restart(int emergency) { reboot_emergency = emergency; machine_ops.emergency_restart(); } static void native_machine_restart(char *__unused) { pr_notice("machine restart\n"); if (!reboot_force) machine_shutdown(); __machine_emergency_restart(0); } static void native_machine_halt(void) { /* Stop other cpus and apics */ machine_shutdown(); tboot_shutdown(TB_SHUTDOWN_HALT); stop_this_cpu(NULL); } static void native_machine_power_off(void) { if (kernel_can_power_off()) { if (!reboot_force) machine_shutdown(); do_kernel_power_off(); } /* A fallback in case there is no PM info available */ tboot_shutdown(TB_SHUTDOWN_HALT); } struct machine_ops machine_ops __ro_after_init = { .power_off = native_machine_power_off, .shutdown = native_machine_shutdown, .emergency_restart = native_machine_emergency_restart, .restart = native_machine_restart, .halt = native_machine_halt, #ifdef CONFIG_KEXEC_CORE .crash_shutdown = native_machine_crash_shutdown, #endif }; void machine_power_off(void) { machine_ops.power_off(); } void machine_shutdown(void) { machine_ops.shutdown(); } void machine_emergency_restart(void) { __machine_emergency_restart(1); } void machine_restart(char *cmd) { machine_ops.restart(cmd); } void machine_halt(void) { machine_ops.halt(); } #ifdef CONFIG_KEXEC_CORE void machine_crash_shutdown(struct pt_regs *regs) { machine_ops.crash_shutdown(regs); } #endif /* This is the CPU performing the emergency shutdown work. */ int crashing_cpu = -1; #if defined(CONFIG_SMP) static nmi_shootdown_cb shootdown_callback; static atomic_t waiting_for_crash_ipi; static int crash_ipi_issued; static int crash_nmi_callback(unsigned int val, struct pt_regs *regs) { int cpu; cpu = raw_smp_processor_id(); /* * Don't do anything if this handler is invoked on crashing cpu. * Otherwise, system will completely hang. Crashing cpu can get * an NMI if system was initially booted with nmi_watchdog parameter. */ if (cpu == crashing_cpu) return NMI_HANDLED; local_irq_disable(); if (shootdown_callback) shootdown_callback(cpu, regs); /* * Prepare the CPU for reboot _after_ invoking the callback so that the * callback can safely use virtualization instructions, e.g. VMCLEAR. */ cpu_emergency_disable_virtualization(); atomic_dec(&waiting_for_crash_ipi); /* Assume hlt works */ halt(); for (;;) cpu_relax(); return NMI_HANDLED; } /** * nmi_shootdown_cpus - Stop other CPUs via NMI * @callback: Optional callback to be invoked from the NMI handler * * The NMI handler on the remote CPUs invokes @callback, if not * NULL, first and then disables virtualization to ensure that * INIT is recognized during reboot. * * nmi_shootdown_cpus() can only be invoked once. After the first * invocation all other CPUs are stuck in crash_nmi_callback() and * cannot respond to a second NMI. */ void nmi_shootdown_cpus(nmi_shootdown_cb callback) { unsigned long msecs; local_irq_disable(); /* * Avoid certain doom if a shootdown already occurred; re-registering * the NMI handler will cause list corruption, modifying the callback * will do who knows what, etc... */ if (WARN_ON_ONCE(crash_ipi_issued)) return; /* Make a note of crashing cpu. Will be used in NMI callback. */ crashing_cpu = safe_smp_processor_id(); shootdown_callback = callback; atomic_set(&waiting_for_crash_ipi, num_online_cpus() - 1); /* Would it be better to replace the trap vector here? */ if (register_nmi_handler(NMI_LOCAL, crash_nmi_callback, NMI_FLAG_FIRST, "crash")) return; /* Return what? */ /* * Ensure the new callback function is set before sending * out the NMI */ wmb(); apic_send_IPI_allbutself(NMI_VECTOR); /* Kick CPUs looping in NMI context. */ WRITE_ONCE(crash_ipi_issued, 1); msecs = 1000; /* Wait at most a second for the other cpus to stop */ while ((atomic_read(&waiting_for_crash_ipi) > 0) && msecs) { mdelay(1); msecs--; } /* * Leave the nmi callback set, shootdown is a one-time thing. Clearing * the callback could result in a NULL pointer dereference if a CPU * (finally) responds after the timeout expires. */ } static inline void nmi_shootdown_cpus_on_restart(void) { if (!crash_ipi_issued) nmi_shootdown_cpus(NULL); } /* * Check if the crash dumping IPI got issued and if so, call its callback * directly. This function is used when we have already been in NMI handler. * It doesn't return. */ void run_crash_ipi_callback(struct pt_regs *regs) { if (crash_ipi_issued) crash_nmi_callback(0, regs); } /* Override the weak function in kernel/panic.c */ void __noreturn nmi_panic_self_stop(struct pt_regs *regs) { while (1) { /* If no CPU is preparing crash dump, we simply loop here. */ run_crash_ipi_callback(regs); cpu_relax(); } } #else /* !CONFIG_SMP */ void nmi_shootdown_cpus(nmi_shootdown_cb callback) { /* No other CPUs to shoot down */ } static inline void nmi_shootdown_cpus_on_restart(void) { } void run_crash_ipi_callback(struct pt_regs *regs) { } #endif
linux-master
arch/x86/kernel/reboot.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 1992, 1998 Linus Torvalds, Ingo Molnar * * This file contains the lowest level x86-specific interrupt * entry, irq-stacks and irq statistics code. All the remaining * irq logic is done by the generic kernel/irq/ code and * by the x86-specific irq controller code. (e.g. i8259.c and * io_apic.c.) */ #include <linux/seq_file.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/kernel_stat.h> #include <linux/notifier.h> #include <linux/cpu.h> #include <linux/delay.h> #include <linux/uaccess.h> #include <linux/percpu.h> #include <linux/mm.h> #include <asm/apic.h> #include <asm/nospec-branch.h> #include <asm/softirq_stack.h> #ifdef CONFIG_DEBUG_STACKOVERFLOW int sysctl_panic_on_stackoverflow __read_mostly; /* Debugging check for stack overflow: is there less than 1KB free? */ static int check_stack_overflow(void) { long sp; __asm__ __volatile__("andl %%esp,%0" : "=r" (sp) : "0" (THREAD_SIZE - 1)); return sp < (sizeof(struct thread_info) + STACK_WARN); } static void print_stack_overflow(void) { printk(KERN_WARNING "low stack detected by irq handler\n"); dump_stack(); if (sysctl_panic_on_stackoverflow) panic("low stack detected by irq handler - check messages\n"); } #else static inline int check_stack_overflow(void) { return 0; } static inline void print_stack_overflow(void) { } #endif static void call_on_stack(void *func, void *stack) { asm volatile("xchgl %%ebx,%%esp \n" CALL_NOSPEC "movl %%ebx,%%esp \n" : "=b" (stack) : "0" (stack), [thunk_target] "D"(func) : "memory", "cc", "edx", "ecx", "eax"); } static inline void *current_stack(void) { return (void *)(current_stack_pointer & ~(THREAD_SIZE - 1)); } static inline int execute_on_irq_stack(int overflow, struct irq_desc *desc) { struct irq_stack *curstk, *irqstk; u32 *isp, *prev_esp, arg1; curstk = (struct irq_stack *) current_stack(); irqstk = __this_cpu_read(pcpu_hot.hardirq_stack_ptr); /* * this is where we switch to the IRQ stack. However, if we are * already using the IRQ stack (because we interrupted a hardirq * handler) we can't do that and just have to keep using the * current stack (which is the irq stack already after all) */ if (unlikely(curstk == irqstk)) return 0; isp = (u32 *) ((char *)irqstk + sizeof(*irqstk)); /* Save the next esp at the bottom of the stack */ prev_esp = (u32 *)irqstk; *prev_esp = current_stack_pointer; if (unlikely(overflow)) call_on_stack(print_stack_overflow, isp); asm volatile("xchgl %%ebx,%%esp \n" CALL_NOSPEC "movl %%ebx,%%esp \n" : "=a" (arg1), "=b" (isp) : "0" (desc), "1" (isp), [thunk_target] "D" (desc->handle_irq) : "memory", "cc", "ecx"); return 1; } /* * Allocate per-cpu stacks for hardirq and softirq processing */ int irq_init_percpu_irqstack(unsigned int cpu) { int node = cpu_to_node(cpu); struct page *ph, *ps; if (per_cpu(pcpu_hot.hardirq_stack_ptr, cpu)) return 0; ph = alloc_pages_node(node, THREADINFO_GFP, THREAD_SIZE_ORDER); if (!ph) return -ENOMEM; ps = alloc_pages_node(node, THREADINFO_GFP, THREAD_SIZE_ORDER); if (!ps) { __free_pages(ph, THREAD_SIZE_ORDER); return -ENOMEM; } per_cpu(pcpu_hot.hardirq_stack_ptr, cpu) = page_address(ph); per_cpu(pcpu_hot.softirq_stack_ptr, cpu) = page_address(ps); return 0; } #ifdef CONFIG_SOFTIRQ_ON_OWN_STACK void do_softirq_own_stack(void) { struct irq_stack *irqstk; u32 *isp, *prev_esp; irqstk = __this_cpu_read(pcpu_hot.softirq_stack_ptr); /* build the stack frame on the softirq stack */ isp = (u32 *) ((char *)irqstk + sizeof(*irqstk)); /* Push the previous esp onto the stack */ prev_esp = (u32 *)irqstk; *prev_esp = current_stack_pointer; call_on_stack(__do_softirq, isp); } #endif void __handle_irq(struct irq_desc *desc, struct pt_regs *regs) { int overflow = check_stack_overflow(); if (user_mode(regs) || !execute_on_irq_stack(overflow, desc)) { if (unlikely(overflow)) print_stack_overflow(); generic_handle_irq_desc(desc); } }
linux-master
arch/x86/kernel/irq_32.c
// SPDX-License-Identifier: GPL-2.0 /* Various workarounds for chipset bugs. This code runs very early and can't use the regular PCI subsystem The entries are keyed to PCI bridges which usually identify chipsets uniquely. This is only for whole classes of chipsets with specific problems which need early invasive action (e.g. before the timers are initialized). Most PCI device specific workarounds can be done later and should be in standard PCI quirks Mainboard specific bugs should be handled by DMI entries. CPU specific bugs in setup.c */ #include <linux/pci.h> #include <linux/acpi.h> #include <linux/delay.h> #include <linux/pci_ids.h> #include <linux/bcma/bcma.h> #include <linux/bcma/bcma_regs.h> #include <linux/platform_data/x86/apple.h> #include <drm/i915_drm.h> #include <drm/i915_pciids.h> #include <asm/pci-direct.h> #include <asm/dma.h> #include <asm/io_apic.h> #include <asm/apic.h> #include <asm/hpet.h> #include <asm/iommu.h> #include <asm/gart.h> #include <asm/irq_remapping.h> #include <asm/early_ioremap.h> static void __init fix_hypertransport_config(int num, int slot, int func) { u32 htcfg; /* * we found a hypertransport bus * make sure that we are broadcasting * interrupts to all cpus on the ht bus * if we're using extended apic ids */ htcfg = read_pci_config(num, slot, func, 0x68); if (htcfg & (1 << 18)) { printk(KERN_INFO "Detected use of extended apic ids " "on hypertransport bus\n"); if ((htcfg & (1 << 17)) == 0) { printk(KERN_INFO "Enabling hypertransport extended " "apic interrupt broadcast\n"); printk(KERN_INFO "Note this is a bios bug, " "please contact your hw vendor\n"); htcfg |= (1 << 17); write_pci_config(num, slot, func, 0x68, htcfg); } } } static void __init via_bugs(int num, int slot, int func) { #ifdef CONFIG_GART_IOMMU if ((max_pfn > MAX_DMA32_PFN || force_iommu) && !gart_iommu_aperture_allowed) { printk(KERN_INFO "Looks like a VIA chipset. Disabling IOMMU." " Override with iommu=allowed\n"); gart_iommu_aperture_disabled = 1; } #endif } #ifdef CONFIG_ACPI #ifdef CONFIG_X86_IO_APIC static int __init nvidia_hpet_check(struct acpi_table_header *header) { return 0; } #endif /* CONFIG_X86_IO_APIC */ #endif /* CONFIG_ACPI */ static void __init nvidia_bugs(int num, int slot, int func) { #ifdef CONFIG_ACPI #ifdef CONFIG_X86_IO_APIC /* * Only applies to Nvidia root ports (bus 0) and not to * Nvidia graphics cards with PCI ports on secondary buses. */ if (num) return; /* * All timer overrides on Nvidia are * wrong unless HPET is enabled. * Unfortunately that's not true on many Asus boards. * We don't know yet how to detect this automatically, but * at least allow a command line override. */ if (acpi_use_timer_override) return; if (acpi_table_parse(ACPI_SIG_HPET, nvidia_hpet_check)) { acpi_skip_timer_override = 1; printk(KERN_INFO "Nvidia board " "detected. Ignoring ACPI " "timer override.\n"); printk(KERN_INFO "If you got timer trouble " "try acpi_use_timer_override\n"); } #endif #endif /* RED-PEN skip them on mptables too? */ } #if defined(CONFIG_ACPI) && defined(CONFIG_X86_IO_APIC) static u32 __init ati_ixp4x0_rev(int num, int slot, int func) { u32 d; u8 b; b = read_pci_config_byte(num, slot, func, 0xac); b &= ~(1<<5); write_pci_config_byte(num, slot, func, 0xac, b); d = read_pci_config(num, slot, func, 0x70); d |= 1<<8; write_pci_config(num, slot, func, 0x70, d); d = read_pci_config(num, slot, func, 0x8); d &= 0xff; return d; } static void __init ati_bugs(int num, int slot, int func) { u32 d; u8 b; if (acpi_use_timer_override) return; d = ati_ixp4x0_rev(num, slot, func); if (d < 0x82) acpi_skip_timer_override = 1; else { /* check for IRQ0 interrupt swap */ outb(0x72, 0xcd6); b = inb(0xcd7); if (!(b & 0x2)) acpi_skip_timer_override = 1; } if (acpi_skip_timer_override) { printk(KERN_INFO "SB4X0 revision 0x%x\n", d); printk(KERN_INFO "Ignoring ACPI timer override.\n"); printk(KERN_INFO "If you got timer trouble " "try acpi_use_timer_override\n"); } } static u32 __init ati_sbx00_rev(int num, int slot, int func) { u32 d; d = read_pci_config(num, slot, func, 0x8); d &= 0xff; return d; } static void __init ati_bugs_contd(int num, int slot, int func) { u32 d, rev; rev = ati_sbx00_rev(num, slot, func); if (rev >= 0x40) acpi_fix_pin2_polarity = 1; /* * SB600: revisions 0x11, 0x12, 0x13, 0x14, ... * SB700: revisions 0x39, 0x3a, ... * SB800: revisions 0x40, 0x41, ... */ if (rev >= 0x39) return; if (acpi_use_timer_override) return; /* check for IRQ0 interrupt swap */ d = read_pci_config(num, slot, func, 0x64); if (!(d & (1<<14))) acpi_skip_timer_override = 1; if (acpi_skip_timer_override) { printk(KERN_INFO "SB600 revision 0x%x\n", rev); printk(KERN_INFO "Ignoring ACPI timer override.\n"); printk(KERN_INFO "If you got timer trouble " "try acpi_use_timer_override\n"); } } #else static void __init ati_bugs(int num, int slot, int func) { } static void __init ati_bugs_contd(int num, int slot, int func) { } #endif static void __init intel_remapping_check(int num, int slot, int func) { u8 revision; u16 device; device = read_pci_config_16(num, slot, func, PCI_DEVICE_ID); revision = read_pci_config_byte(num, slot, func, PCI_REVISION_ID); /* * Revision <= 13 of all triggering devices id in this quirk * have a problem draining interrupts when irq remapping is * enabled, and should be flagged as broken. Additionally * revision 0x22 of device id 0x3405 has this problem. */ if (revision <= 0x13) set_irq_remapping_broken(); else if (device == 0x3405 && revision == 0x22) set_irq_remapping_broken(); } /* * Systems with Intel graphics controllers set aside memory exclusively * for gfx driver use. This memory is not marked in the E820 as reserved * or as RAM, and so is subject to overlap from E820 manipulation later * in the boot process. On some systems, MMIO space is allocated on top, * despite the efforts of the "RAM buffer" approach, which simply rounds * memory boundaries up to 64M to try to catch space that may decode * as RAM and so is not suitable for MMIO. */ #define KB(x) ((x) * 1024UL) #define MB(x) (KB (KB (x))) static resource_size_t __init i830_tseg_size(void) { u8 esmramc = read_pci_config_byte(0, 0, 0, I830_ESMRAMC); if (!(esmramc & TSEG_ENABLE)) return 0; if (esmramc & I830_TSEG_SIZE_1M) return MB(1); else return KB(512); } static resource_size_t __init i845_tseg_size(void) { u8 esmramc = read_pci_config_byte(0, 0, 0, I845_ESMRAMC); u8 tseg_size = esmramc & I845_TSEG_SIZE_MASK; if (!(esmramc & TSEG_ENABLE)) return 0; switch (tseg_size) { case I845_TSEG_SIZE_512K: return KB(512); case I845_TSEG_SIZE_1M: return MB(1); default: WARN(1, "Unknown ESMRAMC value: %x!\n", esmramc); } return 0; } static resource_size_t __init i85x_tseg_size(void) { u8 esmramc = read_pci_config_byte(0, 0, 0, I85X_ESMRAMC); if (!(esmramc & TSEG_ENABLE)) return 0; return MB(1); } static resource_size_t __init i830_mem_size(void) { return read_pci_config_byte(0, 0, 0, I830_DRB3) * MB(32); } static resource_size_t __init i85x_mem_size(void) { return read_pci_config_byte(0, 0, 1, I85X_DRB3) * MB(32); } /* * On 830/845/85x the stolen memory base isn't available in any * register. We need to calculate it as TOM-TSEG_SIZE-stolen_size. */ static resource_size_t __init i830_stolen_base(int num, int slot, int func, resource_size_t stolen_size) { return i830_mem_size() - i830_tseg_size() - stolen_size; } static resource_size_t __init i845_stolen_base(int num, int slot, int func, resource_size_t stolen_size) { return i830_mem_size() - i845_tseg_size() - stolen_size; } static resource_size_t __init i85x_stolen_base(int num, int slot, int func, resource_size_t stolen_size) { return i85x_mem_size() - i85x_tseg_size() - stolen_size; } static resource_size_t __init i865_stolen_base(int num, int slot, int func, resource_size_t stolen_size) { u16 toud = 0; toud = read_pci_config_16(0, 0, 0, I865_TOUD); return toud * KB(64) + i845_tseg_size(); } static resource_size_t __init gen3_stolen_base(int num, int slot, int func, resource_size_t stolen_size) { u32 bsm; /* Almost universally we can find the Graphics Base of Stolen Memory * at register BSM (0x5c) in the igfx configuration space. On a few * (desktop) machines this is also mirrored in the bridge device at * different locations, or in the MCHBAR. */ bsm = read_pci_config(num, slot, func, INTEL_BSM); return bsm & INTEL_BSM_MASK; } static resource_size_t __init gen11_stolen_base(int num, int slot, int func, resource_size_t stolen_size) { u64 bsm; bsm = read_pci_config(num, slot, func, INTEL_GEN11_BSM_DW0); bsm &= INTEL_BSM_MASK; bsm |= (u64)read_pci_config(num, slot, func, INTEL_GEN11_BSM_DW1) << 32; return bsm; } static resource_size_t __init i830_stolen_size(int num, int slot, int func) { u16 gmch_ctrl; u16 gms; gmch_ctrl = read_pci_config_16(0, 0, 0, I830_GMCH_CTRL); gms = gmch_ctrl & I830_GMCH_GMS_MASK; switch (gms) { case I830_GMCH_GMS_STOLEN_512: return KB(512); case I830_GMCH_GMS_STOLEN_1024: return MB(1); case I830_GMCH_GMS_STOLEN_8192: return MB(8); /* local memory isn't part of the normal address space */ case I830_GMCH_GMS_LOCAL: return 0; default: WARN(1, "Unknown GMCH_CTRL value: %x!\n", gmch_ctrl); } return 0; } static resource_size_t __init gen3_stolen_size(int num, int slot, int func) { u16 gmch_ctrl; u16 gms; gmch_ctrl = read_pci_config_16(0, 0, 0, I830_GMCH_CTRL); gms = gmch_ctrl & I855_GMCH_GMS_MASK; switch (gms) { case I855_GMCH_GMS_STOLEN_1M: return MB(1); case I855_GMCH_GMS_STOLEN_4M: return MB(4); case I855_GMCH_GMS_STOLEN_8M: return MB(8); case I855_GMCH_GMS_STOLEN_16M: return MB(16); case I855_GMCH_GMS_STOLEN_32M: return MB(32); case I915_GMCH_GMS_STOLEN_48M: return MB(48); case I915_GMCH_GMS_STOLEN_64M: return MB(64); case G33_GMCH_GMS_STOLEN_128M: return MB(128); case G33_GMCH_GMS_STOLEN_256M: return MB(256); case INTEL_GMCH_GMS_STOLEN_96M: return MB(96); case INTEL_GMCH_GMS_STOLEN_160M:return MB(160); case INTEL_GMCH_GMS_STOLEN_224M:return MB(224); case INTEL_GMCH_GMS_STOLEN_352M:return MB(352); default: WARN(1, "Unknown GMCH_CTRL value: %x!\n", gmch_ctrl); } return 0; } static resource_size_t __init gen6_stolen_size(int num, int slot, int func) { u16 gmch_ctrl; u16 gms; gmch_ctrl = read_pci_config_16(num, slot, func, SNB_GMCH_CTRL); gms = (gmch_ctrl >> SNB_GMCH_GMS_SHIFT) & SNB_GMCH_GMS_MASK; return gms * MB(32); } static resource_size_t __init gen8_stolen_size(int num, int slot, int func) { u16 gmch_ctrl; u16 gms; gmch_ctrl = read_pci_config_16(num, slot, func, SNB_GMCH_CTRL); gms = (gmch_ctrl >> BDW_GMCH_GMS_SHIFT) & BDW_GMCH_GMS_MASK; return gms * MB(32); } static resource_size_t __init chv_stolen_size(int num, int slot, int func) { u16 gmch_ctrl; u16 gms; gmch_ctrl = read_pci_config_16(num, slot, func, SNB_GMCH_CTRL); gms = (gmch_ctrl >> SNB_GMCH_GMS_SHIFT) & SNB_GMCH_GMS_MASK; /* * 0x0 to 0x10: 32MB increments starting at 0MB * 0x11 to 0x16: 4MB increments starting at 8MB * 0x17 to 0x1d: 4MB increments start at 36MB */ if (gms < 0x11) return gms * MB(32); else if (gms < 0x17) return (gms - 0x11) * MB(4) + MB(8); else return (gms - 0x17) * MB(4) + MB(36); } static resource_size_t __init gen9_stolen_size(int num, int slot, int func) { u16 gmch_ctrl; u16 gms; gmch_ctrl = read_pci_config_16(num, slot, func, SNB_GMCH_CTRL); gms = (gmch_ctrl >> BDW_GMCH_GMS_SHIFT) & BDW_GMCH_GMS_MASK; /* 0x0 to 0xef: 32MB increments starting at 0MB */ /* 0xf0 to 0xfe: 4MB increments starting at 4MB */ if (gms < 0xf0) return gms * MB(32); else return (gms - 0xf0) * MB(4) + MB(4); } struct intel_early_ops { resource_size_t (*stolen_size)(int num, int slot, int func); resource_size_t (*stolen_base)(int num, int slot, int func, resource_size_t size); }; static const struct intel_early_ops i830_early_ops __initconst = { .stolen_base = i830_stolen_base, .stolen_size = i830_stolen_size, }; static const struct intel_early_ops i845_early_ops __initconst = { .stolen_base = i845_stolen_base, .stolen_size = i830_stolen_size, }; static const struct intel_early_ops i85x_early_ops __initconst = { .stolen_base = i85x_stolen_base, .stolen_size = gen3_stolen_size, }; static const struct intel_early_ops i865_early_ops __initconst = { .stolen_base = i865_stolen_base, .stolen_size = gen3_stolen_size, }; static const struct intel_early_ops gen3_early_ops __initconst = { .stolen_base = gen3_stolen_base, .stolen_size = gen3_stolen_size, }; static const struct intel_early_ops gen6_early_ops __initconst = { .stolen_base = gen3_stolen_base, .stolen_size = gen6_stolen_size, }; static const struct intel_early_ops gen8_early_ops __initconst = { .stolen_base = gen3_stolen_base, .stolen_size = gen8_stolen_size, }; static const struct intel_early_ops gen9_early_ops __initconst = { .stolen_base = gen3_stolen_base, .stolen_size = gen9_stolen_size, }; static const struct intel_early_ops chv_early_ops __initconst = { .stolen_base = gen3_stolen_base, .stolen_size = chv_stolen_size, }; static const struct intel_early_ops gen11_early_ops __initconst = { .stolen_base = gen11_stolen_base, .stolen_size = gen9_stolen_size, }; /* Intel integrated GPUs for which we need to reserve "stolen memory" */ static const struct pci_device_id intel_early_ids[] __initconst = { INTEL_I830_IDS(&i830_early_ops), INTEL_I845G_IDS(&i845_early_ops), INTEL_I85X_IDS(&i85x_early_ops), INTEL_I865G_IDS(&i865_early_ops), INTEL_I915G_IDS(&gen3_early_ops), INTEL_I915GM_IDS(&gen3_early_ops), INTEL_I945G_IDS(&gen3_early_ops), INTEL_I945GM_IDS(&gen3_early_ops), INTEL_VLV_IDS(&gen6_early_ops), INTEL_PINEVIEW_G_IDS(&gen3_early_ops), INTEL_PINEVIEW_M_IDS(&gen3_early_ops), INTEL_I965G_IDS(&gen3_early_ops), INTEL_G33_IDS(&gen3_early_ops), INTEL_I965GM_IDS(&gen3_early_ops), INTEL_GM45_IDS(&gen3_early_ops), INTEL_G45_IDS(&gen3_early_ops), INTEL_IRONLAKE_D_IDS(&gen3_early_ops), INTEL_IRONLAKE_M_IDS(&gen3_early_ops), INTEL_SNB_D_IDS(&gen6_early_ops), INTEL_SNB_M_IDS(&gen6_early_ops), INTEL_IVB_M_IDS(&gen6_early_ops), INTEL_IVB_D_IDS(&gen6_early_ops), INTEL_HSW_IDS(&gen6_early_ops), INTEL_BDW_IDS(&gen8_early_ops), INTEL_CHV_IDS(&chv_early_ops), INTEL_SKL_IDS(&gen9_early_ops), INTEL_BXT_IDS(&gen9_early_ops), INTEL_KBL_IDS(&gen9_early_ops), INTEL_CFL_IDS(&gen9_early_ops), INTEL_GLK_IDS(&gen9_early_ops), INTEL_CNL_IDS(&gen9_early_ops), INTEL_ICL_11_IDS(&gen11_early_ops), INTEL_EHL_IDS(&gen11_early_ops), INTEL_JSL_IDS(&gen11_early_ops), INTEL_TGL_12_IDS(&gen11_early_ops), INTEL_RKL_IDS(&gen11_early_ops), INTEL_ADLS_IDS(&gen11_early_ops), INTEL_ADLP_IDS(&gen11_early_ops), INTEL_ADLN_IDS(&gen11_early_ops), INTEL_RPLS_IDS(&gen11_early_ops), INTEL_RPLP_IDS(&gen11_early_ops), }; struct resource intel_graphics_stolen_res __ro_after_init = DEFINE_RES_MEM(0, 0); EXPORT_SYMBOL(intel_graphics_stolen_res); static void __init intel_graphics_stolen(int num, int slot, int func, const struct intel_early_ops *early_ops) { resource_size_t base, size; resource_size_t end; size = early_ops->stolen_size(num, slot, func); base = early_ops->stolen_base(num, slot, func, size); if (!size || !base) return; end = base + size - 1; intel_graphics_stolen_res.start = base; intel_graphics_stolen_res.end = end; printk(KERN_INFO "Reserving Intel graphics memory at %pR\n", &intel_graphics_stolen_res); /* Mark this space as reserved */ e820__range_add(base, size, E820_TYPE_RESERVED); e820__update_table(e820_table); } static void __init intel_graphics_quirks(int num, int slot, int func) { const struct intel_early_ops *early_ops; u16 device; int i; /* * Reserve "stolen memory" for an integrated GPU. If we've already * found one, there's nothing to do for other (discrete) GPUs. */ if (resource_size(&intel_graphics_stolen_res)) return; device = read_pci_config_16(num, slot, func, PCI_DEVICE_ID); for (i = 0; i < ARRAY_SIZE(intel_early_ids); i++) { kernel_ulong_t driver_data = intel_early_ids[i].driver_data; if (intel_early_ids[i].device != device) continue; early_ops = (typeof(early_ops))driver_data; intel_graphics_stolen(num, slot, func, early_ops); return; } } static void __init force_disable_hpet(int num, int slot, int func) { #ifdef CONFIG_HPET_TIMER boot_hpet_disable = true; pr_info("x86/hpet: Will disable the HPET for this platform because it's not reliable\n"); #endif } #define BCM4331_MMIO_SIZE 16384 #define BCM4331_PM_CAP 0x40 #define bcma_aread32(reg) ioread32(mmio + 1 * BCMA_CORE_SIZE + reg) #define bcma_awrite32(reg, val) iowrite32(val, mmio + 1 * BCMA_CORE_SIZE + reg) static void __init apple_airport_reset(int bus, int slot, int func) { void __iomem *mmio; u16 pmcsr; u64 addr; int i; if (!x86_apple_machine) return; /* Card may have been put into PCI_D3hot by grub quirk */ pmcsr = read_pci_config_16(bus, slot, func, BCM4331_PM_CAP + PCI_PM_CTRL); if ((pmcsr & PCI_PM_CTRL_STATE_MASK) != PCI_D0) { pmcsr &= ~PCI_PM_CTRL_STATE_MASK; write_pci_config_16(bus, slot, func, BCM4331_PM_CAP + PCI_PM_CTRL, pmcsr); mdelay(10); pmcsr = read_pci_config_16(bus, slot, func, BCM4331_PM_CAP + PCI_PM_CTRL); if ((pmcsr & PCI_PM_CTRL_STATE_MASK) != PCI_D0) { pr_err("pci 0000:%02x:%02x.%d: Cannot power up Apple AirPort card\n", bus, slot, func); return; } } addr = read_pci_config(bus, slot, func, PCI_BASE_ADDRESS_0); addr |= (u64)read_pci_config(bus, slot, func, PCI_BASE_ADDRESS_1) << 32; addr &= PCI_BASE_ADDRESS_MEM_MASK; mmio = early_ioremap(addr, BCM4331_MMIO_SIZE); if (!mmio) { pr_err("pci 0000:%02x:%02x.%d: Cannot iomap Apple AirPort card\n", bus, slot, func); return; } pr_info("Resetting Apple AirPort card (left enabled by EFI)\n"); for (i = 0; bcma_aread32(BCMA_RESET_ST) && i < 30; i++) udelay(10); bcma_awrite32(BCMA_RESET_CTL, BCMA_RESET_CTL_RESET); bcma_aread32(BCMA_RESET_CTL); udelay(1); bcma_awrite32(BCMA_RESET_CTL, 0); bcma_aread32(BCMA_RESET_CTL); udelay(10); early_iounmap(mmio, BCM4331_MMIO_SIZE); } #define QFLAG_APPLY_ONCE 0x1 #define QFLAG_APPLIED 0x2 #define QFLAG_DONE (QFLAG_APPLY_ONCE|QFLAG_APPLIED) struct chipset { u32 vendor; u32 device; u32 class; u32 class_mask; u32 flags; void (*f)(int num, int slot, int func); }; static struct chipset early_qrk[] __initdata = { { PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID, PCI_CLASS_BRIDGE_PCI, PCI_ANY_ID, QFLAG_APPLY_ONCE, nvidia_bugs }, { PCI_VENDOR_ID_VIA, PCI_ANY_ID, PCI_CLASS_BRIDGE_PCI, PCI_ANY_ID, QFLAG_APPLY_ONCE, via_bugs }, { PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_K8_NB, PCI_CLASS_BRIDGE_HOST, PCI_ANY_ID, 0, fix_hypertransport_config }, { PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP400_SMBUS, PCI_CLASS_SERIAL_SMBUS, PCI_ANY_ID, 0, ati_bugs }, { PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_SBX00_SMBUS, PCI_CLASS_SERIAL_SMBUS, PCI_ANY_ID, 0, ati_bugs_contd }, { PCI_VENDOR_ID_INTEL, 0x3403, PCI_CLASS_BRIDGE_HOST, PCI_BASE_CLASS_BRIDGE, 0, intel_remapping_check }, { PCI_VENDOR_ID_INTEL, 0x3405, PCI_CLASS_BRIDGE_HOST, PCI_BASE_CLASS_BRIDGE, 0, intel_remapping_check }, { PCI_VENDOR_ID_INTEL, 0x3406, PCI_CLASS_BRIDGE_HOST, PCI_BASE_CLASS_BRIDGE, 0, intel_remapping_check }, { PCI_VENDOR_ID_INTEL, PCI_ANY_ID, PCI_CLASS_DISPLAY_VGA, PCI_ANY_ID, 0, intel_graphics_quirks }, /* * HPET on the current version of the Baytrail platform has accuracy * problems: it will halt in deep idle state - so we disable it. * * More details can be found in section 18.10.1.3 of the datasheet: * * http://www.intel.com/content/dam/www/public/us/en/documents/datasheets/atom-z8000-datasheet-vol-1.pdf */ { PCI_VENDOR_ID_INTEL, 0x0f00, PCI_CLASS_BRIDGE_HOST, PCI_ANY_ID, 0, force_disable_hpet}, { PCI_VENDOR_ID_BROADCOM, 0x4331, PCI_CLASS_NETWORK_OTHER, PCI_ANY_ID, 0, apple_airport_reset}, {} }; static void __init early_pci_scan_bus(int bus); /** * check_dev_quirk - apply early quirks to a given PCI device * @num: bus number * @slot: slot number * @func: PCI function * * Check the vendor & device ID against the early quirks table. * * If the device is single function, let early_pci_scan_bus() know so we don't * poke at this device again. */ static int __init check_dev_quirk(int num, int slot, int func) { u16 class; u16 vendor; u16 device; u8 type; u8 sec; int i; class = read_pci_config_16(num, slot, func, PCI_CLASS_DEVICE); if (class == 0xffff) return -1; /* no class, treat as single function */ vendor = read_pci_config_16(num, slot, func, PCI_VENDOR_ID); device = read_pci_config_16(num, slot, func, PCI_DEVICE_ID); for (i = 0; early_qrk[i].f != NULL; i++) { if (((early_qrk[i].vendor == PCI_ANY_ID) || (early_qrk[i].vendor == vendor)) && ((early_qrk[i].device == PCI_ANY_ID) || (early_qrk[i].device == device)) && (!((early_qrk[i].class ^ class) & early_qrk[i].class_mask))) { if ((early_qrk[i].flags & QFLAG_DONE) != QFLAG_DONE) early_qrk[i].f(num, slot, func); early_qrk[i].flags |= QFLAG_APPLIED; } } type = read_pci_config_byte(num, slot, func, PCI_HEADER_TYPE); if ((type & 0x7f) == PCI_HEADER_TYPE_BRIDGE) { sec = read_pci_config_byte(num, slot, func, PCI_SECONDARY_BUS); if (sec > num) early_pci_scan_bus(sec); } if (!(type & 0x80)) return -1; return 0; } static void __init early_pci_scan_bus(int bus) { int slot, func; /* Poor man's PCI discovery */ for (slot = 0; slot < 32; slot++) for (func = 0; func < 8; func++) { /* Only probe function 0 on single fn devices */ if (check_dev_quirk(bus, slot, func)) break; } } void __init early_quirks(void) { if (!early_pci_allowed()) return; early_pci_scan_bus(0); }
linux-master
arch/x86/kernel/early-quirks.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * x86 implementation of rethook. Mostly copied from arch/x86/kernel/kprobes/core.c. */ #include <linux/bug.h> #include <linux/rethook.h> #include <linux/kprobes.h> #include <linux/objtool.h> #include "kprobes/common.h" __visible void arch_rethook_trampoline_callback(struct pt_regs *regs); #ifndef ANNOTATE_NOENDBR #define ANNOTATE_NOENDBR #endif /* * When a target function returns, this code saves registers and calls * arch_rethook_trampoline_callback(), which calls the rethook handler. */ asm( ".text\n" ".global arch_rethook_trampoline\n" ".type arch_rethook_trampoline, @function\n" "arch_rethook_trampoline:\n" #ifdef CONFIG_X86_64 ANNOTATE_NOENDBR /* This is only jumped from ret instruction */ /* Push a fake return address to tell the unwinder it's a rethook. */ " pushq $arch_rethook_trampoline\n" UNWIND_HINT_FUNC " pushq $" __stringify(__KERNEL_DS) "\n" /* Save the 'sp - 16', this will be fixed later. */ " pushq %rsp\n" " pushfq\n" SAVE_REGS_STRING " movq %rsp, %rdi\n" " call arch_rethook_trampoline_callback\n" RESTORE_REGS_STRING /* In the callback function, 'regs->flags' is copied to 'regs->ss'. */ " addq $16, %rsp\n" " popfq\n" #else /* Push a fake return address to tell the unwinder it's a rethook. */ " pushl $arch_rethook_trampoline\n" UNWIND_HINT_FUNC " pushl %ss\n" /* Save the 'sp - 8', this will be fixed later. */ " pushl %esp\n" " pushfl\n" SAVE_REGS_STRING " movl %esp, %eax\n" " call arch_rethook_trampoline_callback\n" RESTORE_REGS_STRING /* In the callback function, 'regs->flags' is copied to 'regs->ss'. */ " addl $8, %esp\n" " popfl\n" #endif ASM_RET ".size arch_rethook_trampoline, .-arch_rethook_trampoline\n" ); NOKPROBE_SYMBOL(arch_rethook_trampoline); /* * Called from arch_rethook_trampoline */ __used __visible void arch_rethook_trampoline_callback(struct pt_regs *regs) { unsigned long *frame_pointer; /* fixup registers */ regs->cs = __KERNEL_CS; #ifdef CONFIG_X86_32 regs->gs = 0; #endif regs->ip = (unsigned long)&arch_rethook_trampoline; regs->orig_ax = ~0UL; regs->sp += 2*sizeof(long); frame_pointer = (long *)(regs + 1); /* * The return address at 'frame_pointer' is recovered by the * arch_rethook_fixup_return() which called from this * rethook_trampoline_handler(). */ rethook_trampoline_handler(regs, (unsigned long)frame_pointer); /* * Copy FLAGS to 'pt_regs::ss' so that arch_rethook_trapmoline() * can do RET right after POPF. */ *(unsigned long *)&regs->ss = regs->flags; } NOKPROBE_SYMBOL(arch_rethook_trampoline_callback); /* * arch_rethook_trampoline() skips updating frame pointer. The frame pointer * saved in arch_rethook_trampoline_callback() points to the real caller * function's frame pointer. Thus the arch_rethook_trampoline() doesn't have * a standard stack frame with CONFIG_FRAME_POINTER=y. * Let's mark it non-standard function. Anyway, FP unwinder can correctly * unwind without the hint. */ STACK_FRAME_NON_STANDARD_FP(arch_rethook_trampoline); /* This is called from rethook_trampoline_handler(). */ void arch_rethook_fixup_return(struct pt_regs *regs, unsigned long correct_ret_addr) { unsigned long *frame_pointer = (void *)(regs + 1); /* Replace fake return address with real one. */ *frame_pointer = correct_ret_addr; } NOKPROBE_SYMBOL(arch_rethook_fixup_return); void arch_rethook_prepare(struct rethook_node *rh, struct pt_regs *regs, bool mcount) { unsigned long *stack = (unsigned long *)regs->sp; rh->ret_addr = stack[0]; rh->frame = regs->sp; /* Replace the return addr with trampoline addr */ stack[0] = (unsigned long) arch_rethook_trampoline; } NOKPROBE_SYMBOL(arch_rethook_prepare);
linux-master
arch/x86/kernel/rethook.c
// SPDX-License-Identifier: GPL-2.0-only /* * vSMPowered(tm) systems specific initialization * Copyright (C) 2005 ScaleMP Inc. * * Ravikiran Thirumalai <[email protected]>, * Shai Fultheim <[email protected]> * Paravirt ops integration: Glauber de Oliveira Costa <[email protected]>, * Ravikiran Thirumalai <[email protected]> */ #include <linux/init.h> #include <linux/pci_ids.h> #include <linux/pci_regs.h> #include <linux/smp.h> #include <linux/irq.h> #include <asm/apic.h> #include <asm/pci-direct.h> #include <asm/io.h> #include <asm/paravirt.h> #include <asm/setup.h> #define TOPOLOGY_REGISTER_OFFSET 0x10 #ifdef CONFIG_PCI static void __init set_vsmp_ctl(void) { void __iomem *address; unsigned int cap, ctl, cfg; /* set vSMP magic bits to indicate vSMP capable kernel */ cfg = read_pci_config(0, 0x1f, 0, PCI_BASE_ADDRESS_0); address = early_ioremap(cfg, 8); cap = readl(address); ctl = readl(address + 4); printk(KERN_INFO "vSMP CTL: capabilities:0x%08x control:0x%08x\n", cap, ctl); /* If possible, let the vSMP foundation route the interrupt optimally */ #ifdef CONFIG_SMP if (cap & ctl & BIT(8)) { ctl &= ~BIT(8); #ifdef CONFIG_PROC_FS /* Don't let users change irq affinity via procfs */ no_irq_affinity = 1; #endif } #endif writel(ctl, address + 4); ctl = readl(address + 4); pr_info("vSMP CTL: control set to:0x%08x\n", ctl); early_iounmap(address, 8); } static int is_vsmp = -1; static void __init detect_vsmp_box(void) { is_vsmp = 0; if (!early_pci_allowed()) return; /* Check if we are running on a ScaleMP vSMPowered box */ if (read_pci_config(0, 0x1f, 0, PCI_VENDOR_ID) == (PCI_VENDOR_ID_SCALEMP | (PCI_DEVICE_ID_SCALEMP_VSMP_CTL << 16))) is_vsmp = 1; } static int is_vsmp_box(void) { if (is_vsmp != -1) return is_vsmp; else { WARN_ON_ONCE(1); return 0; } } #else static void __init detect_vsmp_box(void) { } static int is_vsmp_box(void) { return 0; } static void __init set_vsmp_ctl(void) { } #endif static void __init vsmp_cap_cpus(void) { #if !defined(CONFIG_X86_VSMP) && defined(CONFIG_SMP) && defined(CONFIG_PCI) void __iomem *address; unsigned int cfg, topology, node_shift, maxcpus; /* * CONFIG_X86_VSMP is not configured, so limit the number CPUs to the * ones present in the first board, unless explicitly overridden by * setup_max_cpus */ if (setup_max_cpus != NR_CPUS) return; /* Read the vSMP Foundation topology register */ cfg = read_pci_config(0, 0x1f, 0, PCI_BASE_ADDRESS_0); address = early_ioremap(cfg + TOPOLOGY_REGISTER_OFFSET, 4); if (WARN_ON(!address)) return; topology = readl(address); node_shift = (topology >> 16) & 0x7; if (!node_shift) /* The value 0 should be decoded as 8 */ node_shift = 8; maxcpus = (topology & ((1 << node_shift) - 1)) + 1; pr_info("vSMP CTL: Capping CPUs to %d (CONFIG_X86_VSMP is unset)\n", maxcpus); setup_max_cpus = maxcpus; early_iounmap(address, 4); #endif } static int apicid_phys_pkg_id(int initial_apic_id, int index_msb) { return read_apic_id() >> index_msb; } static void vsmp_apic_post_init(void) { /* need to update phys_pkg_id */ apic->phys_pkg_id = apicid_phys_pkg_id; } void __init vsmp_init(void) { detect_vsmp_box(); if (!is_vsmp_box()) return; x86_platform.apic_post_init = vsmp_apic_post_init; vsmp_cap_cpus(); set_vsmp_ctl(); return; }
linux-master
arch/x86/kernel/vsmp_64.c
// SPDX-License-Identifier: GPL-2.0 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/export.h> #include <linux/init.h> #include <linux/memblock.h> #include <linux/percpu.h> #include <linux/kexec.h> #include <linux/crash_dump.h> #include <linux/smp.h> #include <linux/topology.h> #include <linux/pfn.h> #include <linux/stackprotector.h> #include <asm/sections.h> #include <asm/processor.h> #include <asm/desc.h> #include <asm/setup.h> #include <asm/mpspec.h> #include <asm/apicdef.h> #include <asm/highmem.h> #include <asm/proto.h> #include <asm/cpumask.h> #include <asm/cpu.h> #ifdef CONFIG_X86_64 #define BOOT_PERCPU_OFFSET ((unsigned long)__per_cpu_load) #else #define BOOT_PERCPU_OFFSET 0 #endif DEFINE_PER_CPU_READ_MOSTLY(unsigned long, this_cpu_off) = BOOT_PERCPU_OFFSET; EXPORT_PER_CPU_SYMBOL(this_cpu_off); unsigned long __per_cpu_offset[NR_CPUS] __ro_after_init = { [0 ... NR_CPUS-1] = BOOT_PERCPU_OFFSET, }; EXPORT_SYMBOL(__per_cpu_offset); /* * On x86_64 symbols referenced from code should be reachable using * 32bit relocations. Reserve space for static percpu variables in * modules so that they are always served from the first chunk which * is located at the percpu segment base. On x86_32, anything can * address anywhere. No need to reserve space in the first chunk. */ #ifdef CONFIG_X86_64 #define PERCPU_FIRST_CHUNK_RESERVE PERCPU_MODULE_RESERVE #else #define PERCPU_FIRST_CHUNK_RESERVE 0 #endif #ifdef CONFIG_X86_32 /** * pcpu_need_numa - determine percpu allocation needs to consider NUMA * * If NUMA is not configured or there is only one NUMA node available, * there is no reason to consider NUMA. This function determines * whether percpu allocation should consider NUMA or not. * * RETURNS: * true if NUMA should be considered; otherwise, false. */ static bool __init pcpu_need_numa(void) { #ifdef CONFIG_NUMA pg_data_t *last = NULL; unsigned int cpu; for_each_possible_cpu(cpu) { int node = early_cpu_to_node(cpu); if (node_online(node) && NODE_DATA(node) && last && last != NODE_DATA(node)) return true; last = NODE_DATA(node); } #endif return false; } #endif static int __init pcpu_cpu_distance(unsigned int from, unsigned int to) { #ifdef CONFIG_NUMA if (early_cpu_to_node(from) == early_cpu_to_node(to)) return LOCAL_DISTANCE; else return REMOTE_DISTANCE; #else return LOCAL_DISTANCE; #endif } static int __init pcpu_cpu_to_node(int cpu) { return early_cpu_to_node(cpu); } void __init pcpu_populate_pte(unsigned long addr) { populate_extra_pte(addr); } static inline void setup_percpu_segment(int cpu) { #ifdef CONFIG_X86_32 struct desc_struct d = GDT_ENTRY_INIT(0x8092, per_cpu_offset(cpu), 0xFFFFF); write_gdt_entry(get_cpu_gdt_rw(cpu), GDT_ENTRY_PERCPU, &d, DESCTYPE_S); #endif } void __init setup_per_cpu_areas(void) { unsigned int cpu; unsigned long delta; int rc; pr_info("NR_CPUS:%d nr_cpumask_bits:%d nr_cpu_ids:%u nr_node_ids:%u\n", NR_CPUS, nr_cpumask_bits, nr_cpu_ids, nr_node_ids); /* * Allocate percpu area. Embedding allocator is our favorite; * however, on NUMA configurations, it can result in very * sparse unit mapping and vmalloc area isn't spacious enough * on 32bit. Use page in that case. */ #ifdef CONFIG_X86_32 if (pcpu_chosen_fc == PCPU_FC_AUTO && pcpu_need_numa()) pcpu_chosen_fc = PCPU_FC_PAGE; #endif rc = -EINVAL; if (pcpu_chosen_fc != PCPU_FC_PAGE) { const size_t dyn_size = PERCPU_MODULE_RESERVE + PERCPU_DYNAMIC_RESERVE - PERCPU_FIRST_CHUNK_RESERVE; size_t atom_size; /* * On 64bit, use PMD_SIZE for atom_size so that embedded * percpu areas are aligned to PMD. This, in the future, * can also allow using PMD mappings in vmalloc area. Use * PAGE_SIZE on 32bit as vmalloc space is highly contended * and large vmalloc area allocs can easily fail. */ #ifdef CONFIG_X86_64 atom_size = PMD_SIZE; #else atom_size = PAGE_SIZE; #endif rc = pcpu_embed_first_chunk(PERCPU_FIRST_CHUNK_RESERVE, dyn_size, atom_size, pcpu_cpu_distance, pcpu_cpu_to_node); if (rc < 0) pr_warn("%s allocator failed (%d), falling back to page size\n", pcpu_fc_names[pcpu_chosen_fc], rc); } if (rc < 0) rc = pcpu_page_first_chunk(PERCPU_FIRST_CHUNK_RESERVE, pcpu_cpu_to_node); if (rc < 0) panic("cannot initialize percpu area (err=%d)", rc); /* alrighty, percpu areas up and running */ delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start; for_each_possible_cpu(cpu) { per_cpu_offset(cpu) = delta + pcpu_unit_offsets[cpu]; per_cpu(this_cpu_off, cpu) = per_cpu_offset(cpu); per_cpu(pcpu_hot.cpu_number, cpu) = cpu; setup_percpu_segment(cpu); /* * Copy data used in early init routines from the * initial arrays to the per cpu data areas. These * arrays then become expendable and the *_early_ptr's * are zeroed indicating that the static arrays are * gone. */ #ifdef CONFIG_X86_LOCAL_APIC per_cpu(x86_cpu_to_apicid, cpu) = early_per_cpu_map(x86_cpu_to_apicid, cpu); per_cpu(x86_cpu_to_acpiid, cpu) = early_per_cpu_map(x86_cpu_to_acpiid, cpu); #endif #ifdef CONFIG_NUMA per_cpu(x86_cpu_to_node_map, cpu) = early_per_cpu_map(x86_cpu_to_node_map, cpu); /* * Ensure that the boot cpu numa_node is correct when the boot * cpu is on a node that doesn't have memory installed. * Also cpu_up() will call cpu_to_node() for APs when * MEMORY_HOTPLUG is defined, before per_cpu(numa_node) is set * up later with c_init aka intel_init/amd_init. * So set them all (boot cpu and all APs). */ set_cpu_numa_node(cpu, early_cpu_to_node(cpu)); #endif /* * Up to this point, the boot CPU has been using .init.data * area. Reload any changed state for the boot CPU. */ if (!cpu) switch_gdt_and_percpu_base(cpu); } /* indicate the early static arrays will soon be gone */ #ifdef CONFIG_X86_LOCAL_APIC early_per_cpu_ptr(x86_cpu_to_apicid) = NULL; early_per_cpu_ptr(x86_cpu_to_acpiid) = NULL; #endif #ifdef CONFIG_NUMA early_per_cpu_ptr(x86_cpu_to_node_map) = NULL; #endif /* Setup node to cpumask map */ setup_node_to_cpumask_map(); /* Setup cpu initialized, callin, callout masks */ setup_cpu_local_masks(); /* * Sync back kernel address range again. We already did this in * setup_arch(), but percpu data also needs to be available in * the smpboot asm and arch_sync_kernel_mappings() doesn't sync to * swapper_pg_dir on 32-bit. The per-cpu mappings need to be available * there too. * * FIXME: Can the later sync in setup_cpu_entry_areas() replace * this call? */ sync_initial_page_table(); }
linux-master
arch/x86/kernel/setup_percpu.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 1995 Linus Torvalds * * This file contains the setup_arch() code, which handles the architecture-dependent * parts of early kernel initialization. */ #include <linux/acpi.h> #include <linux/console.h> #include <linux/crash_dump.h> #include <linux/dma-map-ops.h> #include <linux/dmi.h> #include <linux/efi.h> #include <linux/ima.h> #include <linux/init_ohci1394_dma.h> #include <linux/initrd.h> #include <linux/iscsi_ibft.h> #include <linux/memblock.h> #include <linux/panic_notifier.h> #include <linux/pci.h> #include <linux/root_dev.h> #include <linux/hugetlb.h> #include <linux/tboot.h> #include <linux/usb/xhci-dbgp.h> #include <linux/static_call.h> #include <linux/swiotlb.h> #include <linux/random.h> #include <uapi/linux/mount.h> #include <xen/xen.h> #include <asm/apic.h> #include <asm/efi.h> #include <asm/numa.h> #include <asm/bios_ebda.h> #include <asm/bugs.h> #include <asm/cacheinfo.h> #include <asm/cpu.h> #include <asm/efi.h> #include <asm/gart.h> #include <asm/hypervisor.h> #include <asm/io_apic.h> #include <asm/kasan.h> #include <asm/kaslr.h> #include <asm/mce.h> #include <asm/memtype.h> #include <asm/mtrr.h> #include <asm/realmode.h> #include <asm/olpc_ofw.h> #include <asm/pci-direct.h> #include <asm/prom.h> #include <asm/proto.h> #include <asm/thermal.h> #include <asm/unwind.h> #include <asm/vsyscall.h> #include <linux/vmalloc.h> /* * max_low_pfn_mapped: highest directly mapped pfn < 4 GB * max_pfn_mapped: highest directly mapped pfn > 4 GB * * The direct mapping only covers E820_TYPE_RAM regions, so the ranges and gaps are * represented by pfn_mapped[]. */ unsigned long max_low_pfn_mapped; unsigned long max_pfn_mapped; #ifdef CONFIG_DMI RESERVE_BRK(dmi_alloc, 65536); #endif unsigned long _brk_start = (unsigned long)__brk_base; unsigned long _brk_end = (unsigned long)__brk_base; struct boot_params boot_params; /* * These are the four main kernel memory regions, we put them into * the resource tree so that kdump tools and other debugging tools * recover it: */ static struct resource rodata_resource = { .name = "Kernel rodata", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM }; static struct resource data_resource = { .name = "Kernel data", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM }; static struct resource code_resource = { .name = "Kernel code", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM }; static struct resource bss_resource = { .name = "Kernel bss", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM }; #ifdef CONFIG_X86_32 /* CPU data as detected by the assembly code in head_32.S */ struct cpuinfo_x86 new_cpu_data; struct apm_info apm_info; EXPORT_SYMBOL(apm_info); #if defined(CONFIG_X86_SPEEDSTEP_SMI) || \ defined(CONFIG_X86_SPEEDSTEP_SMI_MODULE) struct ist_info ist_info; EXPORT_SYMBOL(ist_info); #else struct ist_info ist_info; #endif #endif struct cpuinfo_x86 boot_cpu_data __read_mostly; EXPORT_SYMBOL(boot_cpu_data); #if !defined(CONFIG_X86_PAE) || defined(CONFIG_X86_64) __visible unsigned long mmu_cr4_features __ro_after_init; #else __visible unsigned long mmu_cr4_features __ro_after_init = X86_CR4_PAE; #endif #ifdef CONFIG_IMA static phys_addr_t ima_kexec_buffer_phys; static size_t ima_kexec_buffer_size; #endif /* Boot loader ID and version as integers, for the benefit of proc_dointvec */ int bootloader_type, bootloader_version; /* * Setup options */ struct screen_info screen_info; EXPORT_SYMBOL(screen_info); struct edid_info edid_info; EXPORT_SYMBOL_GPL(edid_info); extern int root_mountflags; unsigned long saved_video_mode; #define RAMDISK_IMAGE_START_MASK 0x07FF #define RAMDISK_PROMPT_FLAG 0x8000 #define RAMDISK_LOAD_FLAG 0x4000 static char __initdata command_line[COMMAND_LINE_SIZE]; #ifdef CONFIG_CMDLINE_BOOL static char __initdata builtin_cmdline[COMMAND_LINE_SIZE] = CONFIG_CMDLINE; #endif #if defined(CONFIG_EDD) || defined(CONFIG_EDD_MODULE) struct edd edd; #ifdef CONFIG_EDD_MODULE EXPORT_SYMBOL(edd); #endif /** * copy_edd() - Copy the BIOS EDD information * from boot_params into a safe place. * */ static inline void __init copy_edd(void) { memcpy(edd.mbr_signature, boot_params.edd_mbr_sig_buffer, sizeof(edd.mbr_signature)); memcpy(edd.edd_info, boot_params.eddbuf, sizeof(edd.edd_info)); edd.mbr_signature_nr = boot_params.edd_mbr_sig_buf_entries; edd.edd_info_nr = boot_params.eddbuf_entries; } #else static inline void __init copy_edd(void) { } #endif void * __init extend_brk(size_t size, size_t align) { size_t mask = align - 1; void *ret; BUG_ON(_brk_start == 0); BUG_ON(align & mask); _brk_end = (_brk_end + mask) & ~mask; BUG_ON((char *)(_brk_end + size) > __brk_limit); ret = (void *)_brk_end; _brk_end += size; memset(ret, 0, size); return ret; } #ifdef CONFIG_X86_32 static void __init cleanup_highmap(void) { } #endif static void __init reserve_brk(void) { if (_brk_end > _brk_start) memblock_reserve(__pa_symbol(_brk_start), _brk_end - _brk_start); /* Mark brk area as locked down and no longer taking any new allocations */ _brk_start = 0; } u64 relocated_ramdisk; #ifdef CONFIG_BLK_DEV_INITRD static u64 __init get_ramdisk_image(void) { u64 ramdisk_image = boot_params.hdr.ramdisk_image; ramdisk_image |= (u64)boot_params.ext_ramdisk_image << 32; if (ramdisk_image == 0) ramdisk_image = phys_initrd_start; return ramdisk_image; } static u64 __init get_ramdisk_size(void) { u64 ramdisk_size = boot_params.hdr.ramdisk_size; ramdisk_size |= (u64)boot_params.ext_ramdisk_size << 32; if (ramdisk_size == 0) ramdisk_size = phys_initrd_size; return ramdisk_size; } static void __init relocate_initrd(void) { /* Assume only end is not page aligned */ u64 ramdisk_image = get_ramdisk_image(); u64 ramdisk_size = get_ramdisk_size(); u64 area_size = PAGE_ALIGN(ramdisk_size); /* We need to move the initrd down into directly mapped mem */ relocated_ramdisk = memblock_phys_alloc_range(area_size, PAGE_SIZE, 0, PFN_PHYS(max_pfn_mapped)); if (!relocated_ramdisk) panic("Cannot find place for new RAMDISK of size %lld\n", ramdisk_size); initrd_start = relocated_ramdisk + PAGE_OFFSET; initrd_end = initrd_start + ramdisk_size; printk(KERN_INFO "Allocated new RAMDISK: [mem %#010llx-%#010llx]\n", relocated_ramdisk, relocated_ramdisk + ramdisk_size - 1); copy_from_early_mem((void *)initrd_start, ramdisk_image, ramdisk_size); printk(KERN_INFO "Move RAMDISK from [mem %#010llx-%#010llx] to" " [mem %#010llx-%#010llx]\n", ramdisk_image, ramdisk_image + ramdisk_size - 1, relocated_ramdisk, relocated_ramdisk + ramdisk_size - 1); } static void __init early_reserve_initrd(void) { /* Assume only end is not page aligned */ u64 ramdisk_image = get_ramdisk_image(); u64 ramdisk_size = get_ramdisk_size(); u64 ramdisk_end = PAGE_ALIGN(ramdisk_image + ramdisk_size); if (!boot_params.hdr.type_of_loader || !ramdisk_image || !ramdisk_size) return; /* No initrd provided by bootloader */ memblock_reserve(ramdisk_image, ramdisk_end - ramdisk_image); } static void __init reserve_initrd(void) { /* Assume only end is not page aligned */ u64 ramdisk_image = get_ramdisk_image(); u64 ramdisk_size = get_ramdisk_size(); u64 ramdisk_end = PAGE_ALIGN(ramdisk_image + ramdisk_size); if (!boot_params.hdr.type_of_loader || !ramdisk_image || !ramdisk_size) return; /* No initrd provided by bootloader */ initrd_start = 0; printk(KERN_INFO "RAMDISK: [mem %#010llx-%#010llx]\n", ramdisk_image, ramdisk_end - 1); if (pfn_range_is_mapped(PFN_DOWN(ramdisk_image), PFN_DOWN(ramdisk_end))) { /* All are mapped, easy case */ initrd_start = ramdisk_image + PAGE_OFFSET; initrd_end = initrd_start + ramdisk_size; return; } relocate_initrd(); memblock_phys_free(ramdisk_image, ramdisk_end - ramdisk_image); } #else static void __init early_reserve_initrd(void) { } static void __init reserve_initrd(void) { } #endif /* CONFIG_BLK_DEV_INITRD */ static void __init add_early_ima_buffer(u64 phys_addr) { #ifdef CONFIG_IMA struct ima_setup_data *data; data = early_memremap(phys_addr + sizeof(struct setup_data), sizeof(*data)); if (!data) { pr_warn("setup: failed to memremap ima_setup_data entry\n"); return; } if (data->size) { memblock_reserve(data->addr, data->size); ima_kexec_buffer_phys = data->addr; ima_kexec_buffer_size = data->size; } early_memunmap(data, sizeof(*data)); #else pr_warn("Passed IMA kexec data, but CONFIG_IMA not set. Ignoring.\n"); #endif } #if defined(CONFIG_HAVE_IMA_KEXEC) && !defined(CONFIG_OF_FLATTREE) int __init ima_free_kexec_buffer(void) { if (!ima_kexec_buffer_size) return -ENOENT; memblock_free_late(ima_kexec_buffer_phys, ima_kexec_buffer_size); ima_kexec_buffer_phys = 0; ima_kexec_buffer_size = 0; return 0; } int __init ima_get_kexec_buffer(void **addr, size_t *size) { if (!ima_kexec_buffer_size) return -ENOENT; *addr = __va(ima_kexec_buffer_phys); *size = ima_kexec_buffer_size; return 0; } #endif static void __init parse_setup_data(void) { struct setup_data *data; u64 pa_data, pa_next; pa_data = boot_params.hdr.setup_data; while (pa_data) { u32 data_len, data_type; data = early_memremap(pa_data, sizeof(*data)); data_len = data->len + sizeof(struct setup_data); data_type = data->type; pa_next = data->next; early_memunmap(data, sizeof(*data)); switch (data_type) { case SETUP_E820_EXT: e820__memory_setup_extended(pa_data, data_len); break; case SETUP_DTB: add_dtb(pa_data); break; case SETUP_EFI: parse_efi_setup(pa_data, data_len); break; case SETUP_IMA: add_early_ima_buffer(pa_data); break; case SETUP_RNG_SEED: data = early_memremap(pa_data, data_len); add_bootloader_randomness(data->data, data->len); /* Zero seed for forward secrecy. */ memzero_explicit(data->data, data->len); /* Zero length in case we find ourselves back here by accident. */ memzero_explicit(&data->len, sizeof(data->len)); early_memunmap(data, data_len); break; default: break; } pa_data = pa_next; } } static void __init memblock_x86_reserve_range_setup_data(void) { struct setup_indirect *indirect; struct setup_data *data; u64 pa_data, pa_next; u32 len; pa_data = boot_params.hdr.setup_data; while (pa_data) { data = early_memremap(pa_data, sizeof(*data)); if (!data) { pr_warn("setup: failed to memremap setup_data entry\n"); return; } len = sizeof(*data); pa_next = data->next; memblock_reserve(pa_data, sizeof(*data) + data->len); if (data->type == SETUP_INDIRECT) { len += data->len; early_memunmap(data, sizeof(*data)); data = early_memremap(pa_data, len); if (!data) { pr_warn("setup: failed to memremap indirect setup_data\n"); return; } indirect = (struct setup_indirect *)data->data; if (indirect->type != SETUP_INDIRECT) memblock_reserve(indirect->addr, indirect->len); } pa_data = pa_next; early_memunmap(data, len); } } /* * --------- Crashkernel reservation ------------------------------ */ /* 16M alignment for crash kernel regions */ #define CRASH_ALIGN SZ_16M /* * Keep the crash kernel below this limit. * * Earlier 32-bits kernels would limit the kernel to the low 512 MB range * due to mapping restrictions. * * 64-bit kdump kernels need to be restricted to be under 64 TB, which is * the upper limit of system RAM in 4-level paging mode. Since the kdump * jump could be from 5-level paging to 4-level paging, the jump will fail if * the kernel is put above 64 TB, and during the 1st kernel bootup there's * no good way to detect the paging mode of the target kernel which will be * loaded for dumping. */ #ifdef CONFIG_X86_32 # define CRASH_ADDR_LOW_MAX SZ_512M # define CRASH_ADDR_HIGH_MAX SZ_512M #else # define CRASH_ADDR_LOW_MAX SZ_4G # define CRASH_ADDR_HIGH_MAX SZ_64T #endif static int __init reserve_crashkernel_low(void) { #ifdef CONFIG_X86_64 unsigned long long base, low_base = 0, low_size = 0; unsigned long low_mem_limit; int ret; low_mem_limit = min(memblock_phys_mem_size(), CRASH_ADDR_LOW_MAX); /* crashkernel=Y,low */ ret = parse_crashkernel_low(boot_command_line, low_mem_limit, &low_size, &base); if (ret) { /* * two parts from kernel/dma/swiotlb.c: * -swiotlb size: user-specified with swiotlb= or default. * * -swiotlb overflow buffer: now hardcoded to 32k. We round it * to 8M for other buffers that may need to stay low too. Also * make sure we allocate enough extra low memory so that we * don't run out of DMA buffers for 32-bit devices. */ low_size = max(swiotlb_size_or_default() + (8UL << 20), 256UL << 20); } else { /* passed with crashkernel=0,low ? */ if (!low_size) return 0; } low_base = memblock_phys_alloc_range(low_size, CRASH_ALIGN, 0, CRASH_ADDR_LOW_MAX); if (!low_base) { pr_err("Cannot reserve %ldMB crashkernel low memory, please try smaller size.\n", (unsigned long)(low_size >> 20)); return -ENOMEM; } pr_info("Reserving %ldMB of low memory at %ldMB for crashkernel (low RAM limit: %ldMB)\n", (unsigned long)(low_size >> 20), (unsigned long)(low_base >> 20), (unsigned long)(low_mem_limit >> 20)); crashk_low_res.start = low_base; crashk_low_res.end = low_base + low_size - 1; insert_resource(&iomem_resource, &crashk_low_res); #endif return 0; } static void __init reserve_crashkernel(void) { unsigned long long crash_size, crash_base, total_mem; bool high = false; int ret; if (!IS_ENABLED(CONFIG_KEXEC_CORE)) return; total_mem = memblock_phys_mem_size(); /* crashkernel=XM */ ret = parse_crashkernel(boot_command_line, total_mem, &crash_size, &crash_base); if (ret != 0 || crash_size <= 0) { /* crashkernel=X,high */ ret = parse_crashkernel_high(boot_command_line, total_mem, &crash_size, &crash_base); if (ret != 0 || crash_size <= 0) return; high = true; } if (xen_pv_domain()) { pr_info("Ignoring crashkernel for a Xen PV domain\n"); return; } /* 0 means: find the address automatically */ if (!crash_base) { /* * Set CRASH_ADDR_LOW_MAX upper bound for crash memory, * crashkernel=x,high reserves memory over 4G, also allocates * 256M extra low memory for DMA buffers and swiotlb. * But the extra memory is not required for all machines. * So try low memory first and fall back to high memory * unless "crashkernel=size[KMG],high" is specified. */ if (!high) crash_base = memblock_phys_alloc_range(crash_size, CRASH_ALIGN, CRASH_ALIGN, CRASH_ADDR_LOW_MAX); if (!crash_base) crash_base = memblock_phys_alloc_range(crash_size, CRASH_ALIGN, CRASH_ALIGN, CRASH_ADDR_HIGH_MAX); if (!crash_base) { pr_info("crashkernel reservation failed - No suitable area found.\n"); return; } } else { unsigned long long start; start = memblock_phys_alloc_range(crash_size, SZ_1M, crash_base, crash_base + crash_size); if (start != crash_base) { pr_info("crashkernel reservation failed - memory is in use.\n"); return; } } if (crash_base >= (1ULL << 32) && reserve_crashkernel_low()) { memblock_phys_free(crash_base, crash_size); return; } pr_info("Reserving %ldMB of memory at %ldMB for crashkernel (System RAM: %ldMB)\n", (unsigned long)(crash_size >> 20), (unsigned long)(crash_base >> 20), (unsigned long)(total_mem >> 20)); crashk_res.start = crash_base; crashk_res.end = crash_base + crash_size - 1; insert_resource(&iomem_resource, &crashk_res); } static struct resource standard_io_resources[] = { { .name = "dma1", .start = 0x00, .end = 0x1f, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "pic1", .start = 0x20, .end = 0x21, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "timer0", .start = 0x40, .end = 0x43, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "timer1", .start = 0x50, .end = 0x53, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "keyboard", .start = 0x60, .end = 0x60, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "keyboard", .start = 0x64, .end = 0x64, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "dma page reg", .start = 0x80, .end = 0x8f, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "pic2", .start = 0xa0, .end = 0xa1, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "dma2", .start = 0xc0, .end = 0xdf, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "fpu", .start = 0xf0, .end = 0xff, .flags = IORESOURCE_BUSY | IORESOURCE_IO } }; void __init reserve_standard_io_resources(void) { int i; /* request I/O space for devices used on all i[345]86 PCs */ for (i = 0; i < ARRAY_SIZE(standard_io_resources); i++) request_resource(&ioport_resource, &standard_io_resources[i]); } static bool __init snb_gfx_workaround_needed(void) { #ifdef CONFIG_PCI int i; u16 vendor, devid; static const __initconst u16 snb_ids[] = { 0x0102, 0x0112, 0x0122, 0x0106, 0x0116, 0x0126, 0x010a, }; /* Assume no if something weird is going on with PCI */ if (!early_pci_allowed()) return false; vendor = read_pci_config_16(0, 2, 0, PCI_VENDOR_ID); if (vendor != 0x8086) return false; devid = read_pci_config_16(0, 2, 0, PCI_DEVICE_ID); for (i = 0; i < ARRAY_SIZE(snb_ids); i++) if (devid == snb_ids[i]) return true; #endif return false; } /* * Sandy Bridge graphics has trouble with certain ranges, exclude * them from allocation. */ static void __init trim_snb_memory(void) { static const __initconst unsigned long bad_pages[] = { 0x20050000, 0x20110000, 0x20130000, 0x20138000, 0x40004000, }; int i; if (!snb_gfx_workaround_needed()) return; printk(KERN_DEBUG "reserving inaccessible SNB gfx pages\n"); /* * SandyBridge integrated graphics devices have a bug that prevents * them from accessing certain memory ranges, namely anything below * 1M and in the pages listed in bad_pages[] above. * * To avoid these pages being ever accessed by SNB gfx devices reserve * bad_pages that have not already been reserved at boot time. * All memory below the 1 MB mark is anyway reserved later during * setup_arch(), so there is no need to reserve it here. */ for (i = 0; i < ARRAY_SIZE(bad_pages); i++) { if (memblock_reserve(bad_pages[i], PAGE_SIZE)) printk(KERN_WARNING "failed to reserve 0x%08lx\n", bad_pages[i]); } } static void __init trim_bios_range(void) { /* * A special case is the first 4Kb of memory; * This is a BIOS owned area, not kernel ram, but generally * not listed as such in the E820 table. * * This typically reserves additional memory (64KiB by default) * since some BIOSes are known to corrupt low memory. See the * Kconfig help text for X86_RESERVE_LOW. */ e820__range_update(0, PAGE_SIZE, E820_TYPE_RAM, E820_TYPE_RESERVED); /* * special case: Some BIOSes report the PC BIOS * area (640Kb -> 1Mb) as RAM even though it is not. * take them out. */ e820__range_remove(BIOS_BEGIN, BIOS_END - BIOS_BEGIN, E820_TYPE_RAM, 1); e820__update_table(e820_table); } /* called before trim_bios_range() to spare extra sanitize */ static void __init e820_add_kernel_range(void) { u64 start = __pa_symbol(_text); u64 size = __pa_symbol(_end) - start; /* * Complain if .text .data and .bss are not marked as E820_TYPE_RAM and * attempt to fix it by adding the range. We may have a confused BIOS, * or the user may have used memmap=exactmap or memmap=xxM$yyM to * exclude kernel range. If we really are running on top non-RAM, * we will crash later anyways. */ if (e820__mapped_all(start, start + size, E820_TYPE_RAM)) return; pr_warn(".text .data .bss are not marked as E820_TYPE_RAM!\n"); e820__range_remove(start, size, E820_TYPE_RAM, 0); e820__range_add(start, size, E820_TYPE_RAM); } static void __init early_reserve_memory(void) { /* * Reserve the memory occupied by the kernel between _text and * __end_of_kernel_reserve symbols. Any kernel sections after the * __end_of_kernel_reserve symbol must be explicitly reserved with a * separate memblock_reserve() or they will be discarded. */ memblock_reserve(__pa_symbol(_text), (unsigned long)__end_of_kernel_reserve - (unsigned long)_text); /* * The first 4Kb of memory is a BIOS owned area, but generally it is * not listed as such in the E820 table. * * Reserve the first 64K of memory since some BIOSes are known to * corrupt low memory. After the real mode trampoline is allocated the * rest of the memory below 640k is reserved. * * In addition, make sure page 0 is always reserved because on * systems with L1TF its contents can be leaked to user processes. */ memblock_reserve(0, SZ_64K); early_reserve_initrd(); memblock_x86_reserve_range_setup_data(); reserve_bios_regions(); trim_snb_memory(); } /* * Dump out kernel offset information on panic. */ static int dump_kernel_offset(struct notifier_block *self, unsigned long v, void *p) { if (kaslr_enabled()) { pr_emerg("Kernel Offset: 0x%lx from 0x%lx (relocation range: 0x%lx-0x%lx)\n", kaslr_offset(), __START_KERNEL, __START_KERNEL_map, MODULES_VADDR-1); } else { pr_emerg("Kernel Offset: disabled\n"); } return 0; } void x86_configure_nx(void) { if (boot_cpu_has(X86_FEATURE_NX)) __supported_pte_mask |= _PAGE_NX; else __supported_pte_mask &= ~_PAGE_NX; } static void __init x86_report_nx(void) { if (!boot_cpu_has(X86_FEATURE_NX)) { printk(KERN_NOTICE "Notice: NX (Execute Disable) protection " "missing in CPU!\n"); } else { #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE) printk(KERN_INFO "NX (Execute Disable) protection: active\n"); #else /* 32bit non-PAE kernel, NX cannot be used */ printk(KERN_NOTICE "Notice: NX (Execute Disable) protection " "cannot be enabled: non-PAE kernel!\n"); #endif } } /* * Determine if we were loaded by an EFI loader. If so, then we have also been * passed the efi memmap, systab, etc., so we should use these data structures * for initialization. Note, the efi init code path is determined by the * global efi_enabled. This allows the same kernel image to be used on existing * systems (with a traditional BIOS) as well as on EFI systems. */ /* * setup_arch - architecture-specific boot-time initializations * * Note: On x86_64, fixmaps are ready for use even before this is called. */ void __init setup_arch(char **cmdline_p) { #ifdef CONFIG_X86_32 memcpy(&boot_cpu_data, &new_cpu_data, sizeof(new_cpu_data)); /* * copy kernel address range established so far and switch * to the proper swapper page table */ clone_pgd_range(swapper_pg_dir + KERNEL_PGD_BOUNDARY, initial_page_table + KERNEL_PGD_BOUNDARY, KERNEL_PGD_PTRS); load_cr3(swapper_pg_dir); /* * Note: Quark X1000 CPUs advertise PGE incorrectly and require * a cr3 based tlb flush, so the following __flush_tlb_all() * will not flush anything because the CPU quirk which clears * X86_FEATURE_PGE has not been invoked yet. Though due to the * load_cr3() above the TLB has been flushed already. The * quirk is invoked before subsequent calls to __flush_tlb_all() * so proper operation is guaranteed. */ __flush_tlb_all(); #else printk(KERN_INFO "Command line: %s\n", boot_command_line); boot_cpu_data.x86_phys_bits = MAX_PHYSMEM_BITS; #endif /* * If we have OLPC OFW, we might end up relocating the fixmap due to * reserve_top(), so do this before touching the ioremap area. */ olpc_ofw_detect(); idt_setup_early_traps(); early_cpu_init(); jump_label_init(); static_call_init(); early_ioremap_init(); setup_olpc_ofw_pgd(); ROOT_DEV = old_decode_dev(boot_params.hdr.root_dev); screen_info = boot_params.screen_info; edid_info = boot_params.edid_info; #ifdef CONFIG_X86_32 apm_info.bios = boot_params.apm_bios_info; ist_info = boot_params.ist_info; #endif saved_video_mode = boot_params.hdr.vid_mode; bootloader_type = boot_params.hdr.type_of_loader; if ((bootloader_type >> 4) == 0xe) { bootloader_type &= 0xf; bootloader_type |= (boot_params.hdr.ext_loader_type+0x10) << 4; } bootloader_version = bootloader_type & 0xf; bootloader_version |= boot_params.hdr.ext_loader_ver << 4; #ifdef CONFIG_BLK_DEV_RAM rd_image_start = boot_params.hdr.ram_size & RAMDISK_IMAGE_START_MASK; #endif #ifdef CONFIG_EFI if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI32_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); } else if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI64_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); set_bit(EFI_64BIT, &efi.flags); } #endif x86_init.oem.arch_setup(); /* * Do some memory reservations *before* memory is added to memblock, so * memblock allocations won't overwrite it. * * After this point, everything still needed from the boot loader or * firmware or kernel text should be early reserved or marked not RAM in * e820. All other memory is free game. * * This call needs to happen before e820__memory_setup() which calls the * xen_memory_setup() on Xen dom0 which relies on the fact that those * early reservations have happened already. */ early_reserve_memory(); iomem_resource.end = (1ULL << boot_cpu_data.x86_phys_bits) - 1; e820__memory_setup(); parse_setup_data(); copy_edd(); if (!boot_params.hdr.root_flags) root_mountflags &= ~MS_RDONLY; setup_initial_init_mm(_text, _etext, _edata, (void *)_brk_end); code_resource.start = __pa_symbol(_text); code_resource.end = __pa_symbol(_etext)-1; rodata_resource.start = __pa_symbol(__start_rodata); rodata_resource.end = __pa_symbol(__end_rodata)-1; data_resource.start = __pa_symbol(_sdata); data_resource.end = __pa_symbol(_edata)-1; bss_resource.start = __pa_symbol(__bss_start); bss_resource.end = __pa_symbol(__bss_stop)-1; #ifdef CONFIG_CMDLINE_BOOL #ifdef CONFIG_CMDLINE_OVERRIDE strscpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); #else if (builtin_cmdline[0]) { /* append boot loader cmdline to builtin */ strlcat(builtin_cmdline, " ", COMMAND_LINE_SIZE); strlcat(builtin_cmdline, boot_command_line, COMMAND_LINE_SIZE); strscpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); } #endif #endif strscpy(command_line, boot_command_line, COMMAND_LINE_SIZE); *cmdline_p = command_line; /* * x86_configure_nx() is called before parse_early_param() to detect * whether hardware doesn't support NX (so that the early EHCI debug * console setup can safely call set_fixmap()). */ x86_configure_nx(); parse_early_param(); if (efi_enabled(EFI_BOOT)) efi_memblock_x86_reserve_range(); #ifdef CONFIG_MEMORY_HOTPLUG /* * Memory used by the kernel cannot be hot-removed because Linux * cannot migrate the kernel pages. When memory hotplug is * enabled, we should prevent memblock from allocating memory * for the kernel. * * ACPI SRAT records all hotpluggable memory ranges. But before * SRAT is parsed, we don't know about it. * * The kernel image is loaded into memory at very early time. We * cannot prevent this anyway. So on NUMA system, we set any * node the kernel resides in as un-hotpluggable. * * Since on modern servers, one node could have double-digit * gigabytes memory, we can assume the memory around the kernel * image is also un-hotpluggable. So before SRAT is parsed, just * allocate memory near the kernel image to try the best to keep * the kernel away from hotpluggable memory. */ if (movable_node_is_enabled()) memblock_set_bottom_up(true); #endif x86_report_nx(); apic_setup_apic_calls(); if (acpi_mps_check()) { #ifdef CONFIG_X86_LOCAL_APIC apic_is_disabled = true; #endif setup_clear_cpu_cap(X86_FEATURE_APIC); } e820__reserve_setup_data(); e820__finish_early_params(); if (efi_enabled(EFI_BOOT)) efi_init(); reserve_ibft_region(); dmi_setup(); /* * VMware detection requires dmi to be available, so this * needs to be done after dmi_setup(), for the boot CPU. * For some guest types (Xen PV, SEV-SNP, TDX) it is required to be * called before cache_bp_init() for setting up MTRR state. */ init_hypervisor_platform(); tsc_early_init(); x86_init.resources.probe_roms(); /* after parse_early_param, so could debug it */ insert_resource(&iomem_resource, &code_resource); insert_resource(&iomem_resource, &rodata_resource); insert_resource(&iomem_resource, &data_resource); insert_resource(&iomem_resource, &bss_resource); e820_add_kernel_range(); trim_bios_range(); #ifdef CONFIG_X86_32 if (ppro_with_ram_bug()) { e820__range_update(0x70000000ULL, 0x40000ULL, E820_TYPE_RAM, E820_TYPE_RESERVED); e820__update_table(e820_table); printk(KERN_INFO "fixed physical RAM map:\n"); e820__print_table("bad_ppro"); } #else early_gart_iommu_check(); #endif /* * partially used pages are not usable - thus * we are rounding upwards: */ max_pfn = e820__end_of_ram_pfn(); /* update e820 for memory not covered by WB MTRRs */ cache_bp_init(); if (mtrr_trim_uncached_memory(max_pfn)) max_pfn = e820__end_of_ram_pfn(); max_possible_pfn = max_pfn; /* * Define random base addresses for memory sections after max_pfn is * defined and before each memory section base is used. */ kernel_randomize_memory(); #ifdef CONFIG_X86_32 /* max_low_pfn get updated here */ find_low_pfn_range(); #else check_x2apic(); /* How many end-of-memory variables you have, grandma! */ /* need this before calling reserve_initrd */ if (max_pfn > (1UL<<(32 - PAGE_SHIFT))) max_low_pfn = e820__end_of_low_ram_pfn(); else max_low_pfn = max_pfn; high_memory = (void *)__va(max_pfn * PAGE_SIZE - 1) + 1; #endif /* * Find and reserve possible boot-time SMP configuration: */ find_smp_config(); early_alloc_pgt_buf(); /* * Need to conclude brk, before e820__memblock_setup() * it could use memblock_find_in_range, could overlap with * brk area. */ reserve_brk(); cleanup_highmap(); memblock_set_current_limit(ISA_END_ADDRESS); e820__memblock_setup(); /* * Needs to run after memblock setup because it needs the physical * memory size. */ sev_setup_arch(); efi_fake_memmap(); efi_find_mirror(); efi_esrt_init(); efi_mokvar_table_init(); /* * The EFI specification says that boot service code won't be * called after ExitBootServices(). This is, in fact, a lie. */ efi_reserve_boot_services(); /* preallocate 4k for mptable mpc */ e820__memblock_alloc_reserved_mpc_new(); #ifdef CONFIG_X86_CHECK_BIOS_CORRUPTION setup_bios_corruption_check(); #endif #ifdef CONFIG_X86_32 printk(KERN_DEBUG "initial memory mapped: [mem 0x00000000-%#010lx]\n", (max_pfn_mapped<<PAGE_SHIFT) - 1); #endif /* * Find free memory for the real mode trampoline and place it there. If * there is not enough free memory under 1M, on EFI-enabled systems * there will be additional attempt to reclaim the memory for the real * mode trampoline at efi_free_boot_services(). * * Unconditionally reserve the entire first 1M of RAM because BIOSes * are known to corrupt low memory and several hundred kilobytes are not * worth complex detection what memory gets clobbered. Windows does the * same thing for very similar reasons. * * Moreover, on machines with SandyBridge graphics or in setups that use * crashkernel the entire 1M is reserved anyway. */ x86_platform.realmode_reserve(); init_mem_mapping(); idt_setup_early_pf(); /* * Update mmu_cr4_features (and, indirectly, trampoline_cr4_features) * with the current CR4 value. This may not be necessary, but * auditing all the early-boot CR4 manipulation would be needed to * rule it out. * * Mask off features that don't work outside long mode (just * PCIDE for now). */ mmu_cr4_features = __read_cr4() & ~X86_CR4_PCIDE; memblock_set_current_limit(get_max_mapped()); /* * NOTE: On x86-32, only from this point on, fixmaps are ready for use. */ #ifdef CONFIG_PROVIDE_OHCI1394_DMA_INIT if (init_ohci1394_dma_early) init_ohci1394_dma_on_all_controllers(); #endif /* Allocate bigger log buffer */ setup_log_buf(1); if (efi_enabled(EFI_BOOT)) { switch (boot_params.secure_boot) { case efi_secureboot_mode_disabled: pr_info("Secure boot disabled\n"); break; case efi_secureboot_mode_enabled: pr_info("Secure boot enabled\n"); break; default: pr_info("Secure boot could not be determined\n"); break; } } reserve_initrd(); acpi_table_upgrade(); /* Look for ACPI tables and reserve memory occupied by them. */ acpi_boot_table_init(); vsmp_init(); io_delay_init(); early_platform_quirks(); early_acpi_boot_init(); initmem_init(); dma_contiguous_reserve(max_pfn_mapped << PAGE_SHIFT); if (boot_cpu_has(X86_FEATURE_GBPAGES)) hugetlb_cma_reserve(PUD_SHIFT - PAGE_SHIFT); /* * Reserve memory for crash kernel after SRAT is parsed so that it * won't consume hotpluggable memory. */ reserve_crashkernel(); memblock_find_dma_reserve(); if (!early_xdbc_setup_hardware()) early_xdbc_register_console(); x86_init.paging.pagetable_init(); kasan_init(); /* * Sync back kernel address range. * * FIXME: Can the later sync in setup_cpu_entry_areas() replace * this call? */ sync_initial_page_table(); tboot_probe(); map_vsyscall(); x86_32_probe_apic(); early_quirks(); /* * Read APIC and some other early information from ACPI tables. */ acpi_boot_init(); x86_dtb_init(); /* * get boot-time SMP configuration: */ get_smp_config(); /* * Systems w/o ACPI and mptables might not have it mapped the local * APIC yet, but prefill_possible_map() might need to access it. */ init_apic_mappings(); prefill_possible_map(); init_cpu_to_node(); init_gi_nodes(); io_apic_init_mappings(); x86_init.hyper.guest_late_init(); e820__reserve_resources(); e820__register_nosave_regions(max_pfn); x86_init.resources.reserve_resources(); e820__setup_pci_gap(); #ifdef CONFIG_VT #if defined(CONFIG_VGA_CONSOLE) if (!efi_enabled(EFI_BOOT) || (efi_mem_type(0xa0000) != EFI_CONVENTIONAL_MEMORY)) conswitchp = &vga_con; #endif #endif x86_init.oem.banner(); x86_init.timers.wallclock_init(); /* * This needs to run before setup_local_APIC() which soft-disables the * local APIC temporarily and that masks the thermal LVT interrupt, * leading to softlockups on machines which have configured SMI * interrupt delivery. */ therm_lvt_init(); mcheck_init(); register_refined_jiffies(CLOCK_TICK_RATE); #ifdef CONFIG_EFI if (efi_enabled(EFI_BOOT)) efi_apply_memmap_quirks(); #endif unwind_init(); } #ifdef CONFIG_X86_32 static struct resource video_ram_resource = { .name = "Video RAM area", .start = 0xa0000, .end = 0xbffff, .flags = IORESOURCE_BUSY | IORESOURCE_MEM }; void __init i386_reserve_resources(void) { request_resource(&iomem_resource, &video_ram_resource); reserve_standard_io_resources(); } #endif /* CONFIG_X86_32 */ static struct notifier_block kernel_offset_notifier = { .notifier_call = dump_kernel_offset }; static int __init register_kernel_offset_dumper(void) { atomic_notifier_chain_register(&panic_notifier_list, &kernel_offset_notifier); return 0; } __initcall(register_kernel_offset_dumper);
linux-master
arch/x86/kernel/setup.c
/* * Copyright (C) 2009 Thomas Gleixner <[email protected]> * * For licencing details see kernel-base/COPYING */ #include <linux/init.h> #include <linux/ioport.h> #include <linux/export.h> #include <linux/pci.h> #include <asm/acpi.h> #include <asm/bios_ebda.h> #include <asm/paravirt.h> #include <asm/pci_x86.h> #include <asm/mpspec.h> #include <asm/setup.h> #include <asm/apic.h> #include <asm/e820/api.h> #include <asm/time.h> #include <asm/irq.h> #include <asm/io_apic.h> #include <asm/hpet.h> #include <asm/memtype.h> #include <asm/tsc.h> #include <asm/iommu.h> #include <asm/mach_traps.h> #include <asm/irqdomain.h> #include <asm/realmode.h> void x86_init_noop(void) { } void __init x86_init_uint_noop(unsigned int unused) { } static int __init iommu_init_noop(void) { return 0; } static void iommu_shutdown_noop(void) { } bool __init bool_x86_init_noop(void) { return false; } void x86_op_int_noop(int cpu) { } int set_rtc_noop(const struct timespec64 *now) { return -EINVAL; } void get_rtc_noop(struct timespec64 *now) { } static __initconst const struct of_device_id of_cmos_match[] = { { .compatible = "motorola,mc146818" }, {} }; /* * Allow devicetree configured systems to disable the RTC by setting the * corresponding DT node's status property to disabled. Code is optimized * out for CONFIG_OF=n builds. */ static __init void x86_wallclock_init(void) { struct device_node *node = of_find_matching_node(NULL, of_cmos_match); if (node && !of_device_is_available(node)) { x86_platform.get_wallclock = get_rtc_noop; x86_platform.set_wallclock = set_rtc_noop; } } /* * The platform setup functions are preset with the default functions * for standard PC hardware. */ struct x86_init_ops x86_init __initdata = { .resources = { .probe_roms = probe_roms, .reserve_resources = reserve_standard_io_resources, .memory_setup = e820__memory_setup_default, }, .mpparse = { .setup_ioapic_ids = x86_init_noop, .find_smp_config = default_find_smp_config, .get_smp_config = default_get_smp_config, }, .irqs = { .pre_vector_init = init_ISA_irqs, .intr_init = native_init_IRQ, .intr_mode_select = apic_intr_mode_select, .intr_mode_init = apic_intr_mode_init, .create_pci_msi_domain = native_create_pci_msi_domain, }, .oem = { .arch_setup = x86_init_noop, .banner = default_banner, }, .paging = { .pagetable_init = native_pagetable_init, }, .timers = { .setup_percpu_clockev = setup_boot_APIC_clock, .timer_init = hpet_time_init, .wallclock_init = x86_wallclock_init, }, .iommu = { .iommu_init = iommu_init_noop, }, .pci = { .init = x86_default_pci_init, .init_irq = x86_default_pci_init_irq, .fixup_irqs = x86_default_pci_fixup_irqs, }, .hyper = { .init_platform = x86_init_noop, .guest_late_init = x86_init_noop, .x2apic_available = bool_x86_init_noop, .msi_ext_dest_id = bool_x86_init_noop, .init_mem_mapping = x86_init_noop, .init_after_bootmem = x86_init_noop, }, .acpi = { .set_root_pointer = x86_default_set_root_pointer, .get_root_pointer = x86_default_get_root_pointer, .reduced_hw_early_init = acpi_generic_reduced_hw_init, }, }; struct x86_cpuinit_ops x86_cpuinit = { .early_percpu_clock_init = x86_init_noop, .setup_percpu_clockev = setup_secondary_APIC_clock, .parallel_bringup = true, }; static void default_nmi_init(void) { }; static bool enc_status_change_prepare_noop(unsigned long vaddr, int npages, bool enc) { return true; } static bool enc_status_change_finish_noop(unsigned long vaddr, int npages, bool enc) { return true; } static bool enc_tlb_flush_required_noop(bool enc) { return false; } static bool enc_cache_flush_required_noop(void) { return false; } static bool is_private_mmio_noop(u64 addr) {return false; } struct x86_platform_ops x86_platform __ro_after_init = { .calibrate_cpu = native_calibrate_cpu_early, .calibrate_tsc = native_calibrate_tsc, .get_wallclock = mach_get_cmos_time, .set_wallclock = mach_set_cmos_time, .iommu_shutdown = iommu_shutdown_noop, .is_untracked_pat_range = is_ISA_range, .nmi_init = default_nmi_init, .get_nmi_reason = default_get_nmi_reason, .save_sched_clock_state = tsc_save_sched_clock_state, .restore_sched_clock_state = tsc_restore_sched_clock_state, .realmode_reserve = reserve_real_mode, .realmode_init = init_real_mode, .hyper.pin_vcpu = x86_op_int_noop, .hyper.is_private_mmio = is_private_mmio_noop, .guest = { .enc_status_change_prepare = enc_status_change_prepare_noop, .enc_status_change_finish = enc_status_change_finish_noop, .enc_tlb_flush_required = enc_tlb_flush_required_noop, .enc_cache_flush_required = enc_cache_flush_required_noop, }, }; EXPORT_SYMBOL_GPL(x86_platform); struct x86_apic_ops x86_apic_ops __ro_after_init = { .io_apic_read = native_io_apic_read, .restore = native_restore_boot_irq_mode, };
linux-master
arch/x86/kernel/x86_init.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/sched.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/interrupt.h> #include <asm/sections.h> #include <asm/ptrace.h> #include <asm/bitops.h> #include <asm/stacktrace.h> #include <asm/unwind.h> #define FRAME_HEADER_SIZE (sizeof(long) * 2) unsigned long unwind_get_return_address(struct unwind_state *state) { if (unwind_done(state)) return 0; return __kernel_text_address(state->ip) ? state->ip : 0; } EXPORT_SYMBOL_GPL(unwind_get_return_address); unsigned long *unwind_get_return_address_ptr(struct unwind_state *state) { if (unwind_done(state)) return NULL; return state->regs ? &state->regs->ip : state->bp + 1; } static void unwind_dump(struct unwind_state *state) { static bool dumped_before = false; bool prev_zero, zero = false; unsigned long word, *sp; struct stack_info stack_info = {0}; unsigned long visit_mask = 0; if (dumped_before) return; dumped_before = true; printk_deferred("unwind stack type:%d next_sp:%p mask:0x%lx graph_idx:%d\n", state->stack_info.type, state->stack_info.next_sp, state->stack_mask, state->graph_idx); for (sp = PTR_ALIGN(state->orig_sp, sizeof(long)); sp; sp = PTR_ALIGN(stack_info.next_sp, sizeof(long))) { if (get_stack_info(sp, state->task, &stack_info, &visit_mask)) break; for (; sp < stack_info.end; sp++) { word = READ_ONCE_NOCHECK(*sp); prev_zero = zero; zero = word == 0; if (zero) { if (!prev_zero) printk_deferred("%p: %0*x ...\n", sp, BITS_PER_LONG/4, 0); continue; } printk_deferred("%p: %0*lx (%pB)\n", sp, BITS_PER_LONG/4, word, (void *)word); } } } static bool in_entry_code(unsigned long ip) { char *addr = (char *)ip; return addr >= __entry_text_start && addr < __entry_text_end; } static inline unsigned long *last_frame(struct unwind_state *state) { return (unsigned long *)task_pt_regs(state->task) - 2; } static bool is_last_frame(struct unwind_state *state) { return state->bp == last_frame(state); } #ifdef CONFIG_X86_32 #define GCC_REALIGN_WORDS 3 #else #define GCC_REALIGN_WORDS 1 #endif static inline unsigned long *last_aligned_frame(struct unwind_state *state) { return last_frame(state) - GCC_REALIGN_WORDS; } static bool is_last_aligned_frame(struct unwind_state *state) { unsigned long *last_bp = last_frame(state); unsigned long *aligned_bp = last_aligned_frame(state); /* * GCC can occasionally decide to realign the stack pointer and change * the offset of the stack frame in the prologue of a function called * by head/entry code. Examples: * * <start_secondary>: * push %edi * lea 0x8(%esp),%edi * and $0xfffffff8,%esp * pushl -0x4(%edi) * push %ebp * mov %esp,%ebp * * <x86_64_start_kernel>: * lea 0x8(%rsp),%r10 * and $0xfffffffffffffff0,%rsp * pushq -0x8(%r10) * push %rbp * mov %rsp,%rbp * * After aligning the stack, it pushes a duplicate copy of the return * address before pushing the frame pointer. */ return (state->bp == aligned_bp && *(aligned_bp + 1) == *(last_bp + 1)); } static bool is_last_ftrace_frame(struct unwind_state *state) { unsigned long *last_bp = last_frame(state); unsigned long *last_ftrace_bp = last_bp - 3; /* * When unwinding from an ftrace handler of a function called by entry * code, the stack layout of the last frame is: * * bp * parent ret addr * bp * function ret addr * parent ret addr * pt_regs * ----------------- */ return (state->bp == last_ftrace_bp && *state->bp == *(state->bp + 2) && *(state->bp + 1) == *(state->bp + 4)); } static bool is_last_task_frame(struct unwind_state *state) { return is_last_frame(state) || is_last_aligned_frame(state) || is_last_ftrace_frame(state); } /* * This determines if the frame pointer actually contains an encoded pointer to * pt_regs on the stack. See ENCODE_FRAME_POINTER. */ #ifdef CONFIG_X86_64 static struct pt_regs *decode_frame_pointer(unsigned long *bp) { unsigned long regs = (unsigned long)bp; if (!(regs & 0x1)) return NULL; return (struct pt_regs *)(regs & ~0x1); } #else static struct pt_regs *decode_frame_pointer(unsigned long *bp) { unsigned long regs = (unsigned long)bp; if (regs & 0x80000000) return NULL; return (struct pt_regs *)(regs | 0x80000000); } #endif /* * While walking the stack, KMSAN may stomp on stale locals from other * functions that were marked as uninitialized upon function exit, and * now hold the call frame information for the current function (e.g. the frame * pointer). Because KMSAN does not specifically mark call frames as * initialized, false positive reports are possible. To prevent such reports, * we mark the functions scanning the stack (here and below) with * __no_kmsan_checks. */ __no_kmsan_checks static bool update_stack_state(struct unwind_state *state, unsigned long *next_bp) { struct stack_info *info = &state->stack_info; enum stack_type prev_type = info->type; struct pt_regs *regs; unsigned long *frame, *prev_frame_end, *addr_p, addr; size_t len; if (state->regs) prev_frame_end = (void *)state->regs + sizeof(*state->regs); else prev_frame_end = (void *)state->bp + FRAME_HEADER_SIZE; /* Is the next frame pointer an encoded pointer to pt_regs? */ regs = decode_frame_pointer(next_bp); if (regs) { frame = (unsigned long *)regs; len = sizeof(*regs); state->got_irq = true; } else { frame = next_bp; len = FRAME_HEADER_SIZE; } /* * If the next bp isn't on the current stack, switch to the next one. * * We may have to traverse multiple stacks to deal with the possibility * that info->next_sp could point to an empty stack and the next bp * could be on a subsequent stack. */ while (!on_stack(info, frame, len)) if (get_stack_info(info->next_sp, state->task, info, &state->stack_mask)) return false; /* Make sure it only unwinds up and doesn't overlap the prev frame: */ if (state->orig_sp && state->stack_info.type == prev_type && frame < prev_frame_end) return false; /* Move state to the next frame: */ if (regs) { state->regs = regs; state->bp = NULL; } else { state->bp = next_bp; state->regs = NULL; } /* Save the return address: */ if (state->regs && user_mode(state->regs)) state->ip = 0; else { addr_p = unwind_get_return_address_ptr(state); addr = READ_ONCE_TASK_STACK(state->task, *addr_p); state->ip = unwind_recover_ret_addr(state, addr, addr_p); } /* Save the original stack pointer for unwind_dump(): */ if (!state->orig_sp) state->orig_sp = frame; return true; } __no_kmsan_checks bool unwind_next_frame(struct unwind_state *state) { struct pt_regs *regs; unsigned long *next_bp; if (unwind_done(state)) return false; /* Have we reached the end? */ if (state->regs && user_mode(state->regs)) goto the_end; if (is_last_task_frame(state)) { regs = task_pt_regs(state->task); /* * kthreads (other than the boot CPU's idle thread) have some * partial regs at the end of their stack which were placed * there by copy_thread(). But the regs don't have any * useful information, so we can skip them. * * This user_mode() check is slightly broader than a PF_KTHREAD * check because it also catches the awkward situation where a * newly forked kthread transitions into a user task by calling * kernel_execve(), which eventually clears PF_KTHREAD. */ if (!user_mode(regs)) goto the_end; /* * We're almost at the end, but not quite: there's still the * syscall regs frame. Entry code doesn't encode the regs * pointer for syscalls, so we have to set it manually. */ state->regs = regs; state->bp = NULL; state->ip = 0; return true; } /* Get the next frame pointer: */ if (state->next_bp) { next_bp = state->next_bp; state->next_bp = NULL; } else if (state->regs) { next_bp = (unsigned long *)state->regs->bp; } else { next_bp = (unsigned long *)READ_ONCE_TASK_STACK(state->task, *state->bp); } /* Move to the next frame if it's safe: */ if (!update_stack_state(state, next_bp)) goto bad_address; return true; bad_address: state->error = true; /* * When unwinding a non-current task, the task might actually be * running on another CPU, in which case it could be modifying its * stack while we're reading it. This is generally not a problem and * can be ignored as long as the caller understands that unwinding * another task will not always succeed. */ if (state->task != current) goto the_end; /* * Don't warn if the unwinder got lost due to an interrupt in entry * code or in the C handler before the first frame pointer got set up: */ if (state->got_irq && in_entry_code(state->ip)) goto the_end; if (state->regs && state->regs->sp >= (unsigned long)last_aligned_frame(state) && state->regs->sp < (unsigned long)task_pt_regs(state->task)) goto the_end; /* * There are some known frame pointer issues on 32-bit. Disable * unwinder warnings on 32-bit until it gets objtool support. */ if (IS_ENABLED(CONFIG_X86_32)) goto the_end; if (state->task != current) goto the_end; if (state->regs) { printk_deferred_once(KERN_WARNING "WARNING: kernel stack regs at %p in %s:%d has bad 'bp' value %p\n", state->regs, state->task->comm, state->task->pid, next_bp); unwind_dump(state); } else { printk_deferred_once(KERN_WARNING "WARNING: kernel stack frame pointer at %p in %s:%d has bad value %p\n", state->bp, state->task->comm, state->task->pid, next_bp); unwind_dump(state); } the_end: state->stack_info.type = STACK_TYPE_UNKNOWN; return false; } EXPORT_SYMBOL_GPL(unwind_next_frame); void __unwind_start(struct unwind_state *state, struct task_struct *task, struct pt_regs *regs, unsigned long *first_frame) { unsigned long *bp; memset(state, 0, sizeof(*state)); state->task = task; state->got_irq = (regs); /* Don't even attempt to start from user mode regs: */ if (regs && user_mode(regs)) { state->stack_info.type = STACK_TYPE_UNKNOWN; return; } bp = get_frame_pointer(task, regs); /* * If we crash with IP==0, the last successfully executed instruction * was probably an indirect function call with a NULL function pointer. * That means that SP points into the middle of an incomplete frame: * *SP is a return pointer, and *(SP-sizeof(unsigned long)) is where we * would have written a frame pointer if we hadn't crashed. * Pretend that the frame is complete and that BP points to it, but save * the real BP so that we can use it when looking for the next frame. */ if (regs && regs->ip == 0 && (unsigned long *)regs->sp >= first_frame) { state->next_bp = bp; bp = ((unsigned long *)regs->sp) - 1; } /* Initialize stack info and make sure the frame data is accessible: */ get_stack_info(bp, state->task, &state->stack_info, &state->stack_mask); update_stack_state(state, bp); /* * The caller can provide the address of the first frame directly * (first_frame) or indirectly (regs->sp) to indicate which stack frame * to start unwinding at. Skip ahead until we reach it. */ while (!unwind_done(state) && (!on_stack(&state->stack_info, first_frame, sizeof(long)) || (state->next_bp == NULL && state->bp < first_frame))) unwind_next_frame(state); } EXPORT_SYMBOL_GPL(__unwind_start);
linux-master
arch/x86/kernel/unwind_frame.c
// SPDX-License-Identifier: GPL-2.0 /* * Firmware replacement code. * * Work around broken BIOSes that don't set an aperture, only set the * aperture in the AGP bridge, or set too small aperture. * * If all fails map the aperture over some low memory. This is cheaper than * doing bounce buffering. The memory is lost. This is done at early boot * because only the bootmem allocator can allocate 32+MB. * * Copyright 2002 Andi Kleen, SuSE Labs. */ #define pr_fmt(fmt) "AGP: " fmt #include <linux/kernel.h> #include <linux/kcore.h> #include <linux/types.h> #include <linux/init.h> #include <linux/memblock.h> #include <linux/mmzone.h> #include <linux/pci_ids.h> #include <linux/pci.h> #include <linux/bitops.h> #include <linux/suspend.h> #include <asm/e820/api.h> #include <asm/io.h> #include <asm/iommu.h> #include <asm/gart.h> #include <asm/pci-direct.h> #include <asm/dma.h> #include <asm/amd_nb.h> #include <asm/x86_init.h> #include <linux/crash_dump.h> /* * Using 512M as goal, in case kexec will load kernel_big * that will do the on-position decompress, and could overlap with * the gart aperture that is used. * Sequence: * kernel_small * ==> kexec (with kdump trigger path or gart still enabled) * ==> kernel_small (gart area become e820_reserved) * ==> kexec (with kdump trigger path or gart still enabled) * ==> kerne_big (uncompressed size will be big than 64M or 128M) * So don't use 512M below as gart iommu, leave the space for kernel * code for safe. */ #define GART_MIN_ADDR (512ULL << 20) #define GART_MAX_ADDR (1ULL << 32) int gart_iommu_aperture; int gart_iommu_aperture_disabled __initdata; int gart_iommu_aperture_allowed __initdata; int fallback_aper_order __initdata = 1; /* 64MB */ int fallback_aper_force __initdata; int fix_aperture __initdata = 1; #if defined(CONFIG_PROC_VMCORE) || defined(CONFIG_PROC_KCORE) /* * If the first kernel maps the aperture over e820 RAM, the kdump kernel will * use the same range because it will remain configured in the northbridge. * Trying to dump this area via /proc/vmcore may crash the machine, so exclude * it from vmcore. */ static unsigned long aperture_pfn_start, aperture_page_count; static int gart_mem_pfn_is_ram(unsigned long pfn) { return likely((pfn < aperture_pfn_start) || (pfn >= aperture_pfn_start + aperture_page_count)); } #ifdef CONFIG_PROC_VMCORE static bool gart_oldmem_pfn_is_ram(struct vmcore_cb *cb, unsigned long pfn) { return !!gart_mem_pfn_is_ram(pfn); } static struct vmcore_cb gart_vmcore_cb = { .pfn_is_ram = gart_oldmem_pfn_is_ram, }; #endif static void __init exclude_from_core(u64 aper_base, u32 aper_order) { aperture_pfn_start = aper_base >> PAGE_SHIFT; aperture_page_count = (32 * 1024 * 1024) << aper_order >> PAGE_SHIFT; #ifdef CONFIG_PROC_VMCORE register_vmcore_cb(&gart_vmcore_cb); #endif #ifdef CONFIG_PROC_KCORE WARN_ON(register_mem_pfn_is_ram(&gart_mem_pfn_is_ram)); #endif } #else static void exclude_from_core(u64 aper_base, u32 aper_order) { } #endif /* This code runs before the PCI subsystem is initialized, so just access the northbridge directly. */ static u32 __init allocate_aperture(void) { u32 aper_size; unsigned long addr; /* aper_size should <= 1G */ if (fallback_aper_order > 5) fallback_aper_order = 5; aper_size = (32 * 1024 * 1024) << fallback_aper_order; /* * Aperture has to be naturally aligned. This means a 2GB aperture * won't have much chance of finding a place in the lower 4GB of * memory. Unfortunately we cannot move it up because that would * make the IOMMU useless. */ addr = memblock_phys_alloc_range(aper_size, aper_size, GART_MIN_ADDR, GART_MAX_ADDR); if (!addr) { pr_err("Cannot allocate aperture memory hole [mem %#010lx-%#010lx] (%uKB)\n", addr, addr + aper_size - 1, aper_size >> 10); return 0; } pr_info("Mapping aperture over RAM [mem %#010lx-%#010lx] (%uKB)\n", addr, addr + aper_size - 1, aper_size >> 10); register_nosave_region(addr >> PAGE_SHIFT, (addr+aper_size) >> PAGE_SHIFT); return (u32)addr; } /* Find a PCI capability */ static u32 __init find_cap(int bus, int slot, int func, int cap) { int bytes; u8 pos; if (!(read_pci_config_16(bus, slot, func, PCI_STATUS) & PCI_STATUS_CAP_LIST)) return 0; pos = read_pci_config_byte(bus, slot, func, PCI_CAPABILITY_LIST); for (bytes = 0; bytes < 48 && pos >= 0x40; bytes++) { u8 id; pos &= ~3; id = read_pci_config_byte(bus, slot, func, pos+PCI_CAP_LIST_ID); if (id == 0xff) break; if (id == cap) return pos; pos = read_pci_config_byte(bus, slot, func, pos+PCI_CAP_LIST_NEXT); } return 0; } /* Read a standard AGPv3 bridge header */ static u32 __init read_agp(int bus, int slot, int func, int cap, u32 *order) { u32 apsize; u32 apsizereg; int nbits; u32 aper_low, aper_hi; u64 aper; u32 old_order; pr_info("pci 0000:%02x:%02x:%02x: AGP bridge\n", bus, slot, func); apsizereg = read_pci_config_16(bus, slot, func, cap + 0x14); if (apsizereg == 0xffffffff) { pr_err("pci 0000:%02x:%02x.%d: APSIZE unreadable\n", bus, slot, func); return 0; } /* old_order could be the value from NB gart setting */ old_order = *order; apsize = apsizereg & 0xfff; /* Some BIOS use weird encodings not in the AGPv3 table. */ if (apsize & 0xff) apsize |= 0xf00; nbits = hweight16(apsize); *order = 7 - nbits; if ((int)*order < 0) /* < 32MB */ *order = 0; aper_low = read_pci_config(bus, slot, func, 0x10); aper_hi = read_pci_config(bus, slot, func, 0x14); aper = (aper_low & ~((1<<22)-1)) | ((u64)aper_hi << 32); /* * On some sick chips, APSIZE is 0. It means it wants 4G * so let double check that order, and lets trust AMD NB settings: */ pr_info("pci 0000:%02x:%02x.%d: AGP aperture [bus addr %#010Lx-%#010Lx] (old size %uMB)\n", bus, slot, func, aper, aper + (32ULL << (old_order + 20)) - 1, 32 << old_order); if (aper + (32ULL<<(20 + *order)) > 0x100000000ULL) { pr_info("pci 0000:%02x:%02x.%d: AGP aperture size %uMB (APSIZE %#x) is not right, using settings from NB\n", bus, slot, func, 32 << *order, apsizereg); *order = old_order; } pr_info("pci 0000:%02x:%02x.%d: AGP aperture [bus addr %#010Lx-%#010Lx] (%uMB, APSIZE %#x)\n", bus, slot, func, aper, aper + (32ULL << (*order + 20)) - 1, 32 << *order, apsizereg); if (!aperture_valid(aper, (32*1024*1024) << *order, 32<<20)) return 0; return (u32)aper; } /* * Look for an AGP bridge. Windows only expects the aperture in the * AGP bridge and some BIOS forget to initialize the Northbridge too. * Work around this here. * * Do an PCI bus scan by hand because we're running before the PCI * subsystem. * * All AMD AGP bridges are AGPv3 compliant, so we can do this scan * generically. It's probably overkill to always scan all slots because * the AGP bridges should be always an own bus on the HT hierarchy, * but do it here for future safety. */ static u32 __init search_agp_bridge(u32 *order, int *valid_agp) { int bus, slot, func; /* Poor man's PCI discovery */ for (bus = 0; bus < 256; bus++) { for (slot = 0; slot < 32; slot++) { for (func = 0; func < 8; func++) { u32 class, cap; u8 type; class = read_pci_config(bus, slot, func, PCI_CLASS_REVISION); if (class == 0xffffffff) break; switch (class >> 16) { case PCI_CLASS_BRIDGE_HOST: case PCI_CLASS_BRIDGE_OTHER: /* needed? */ /* AGP bridge? */ cap = find_cap(bus, slot, func, PCI_CAP_ID_AGP); if (!cap) break; *valid_agp = 1; return read_agp(bus, slot, func, cap, order); } /* No multi-function device? */ type = read_pci_config_byte(bus, slot, func, PCI_HEADER_TYPE); if (!(type & 0x80)) break; } } } pr_info("No AGP bridge found\n"); return 0; } static bool gart_fix_e820 __initdata = true; static int __init parse_gart_mem(char *p) { return kstrtobool(p, &gart_fix_e820); } early_param("gart_fix_e820", parse_gart_mem); /* * With kexec/kdump, if the first kernel doesn't shut down the GART and the * second kernel allocates a different GART region, there might be two * overlapping GART regions present: * * - the first still used by the GART initialized in the first kernel. * - (sub-)set of it used as normal RAM by the second kernel. * * which leads to memory corruptions and a kernel panic eventually. * * This can also happen if the BIOS has forgotten to mark the GART region * as reserved. * * Try to update the e820 map to mark that new region as reserved. */ void __init early_gart_iommu_check(void) { u32 agp_aper_order = 0; int i, fix, slot, valid_agp = 0; u32 ctl; u32 aper_size = 0, aper_order = 0, last_aper_order = 0; u64 aper_base = 0, last_aper_base = 0; int aper_enabled = 0, last_aper_enabled = 0, last_valid = 0; if (!amd_gart_present()) return; if (!early_pci_allowed()) return; /* This is mostly duplicate of iommu_hole_init */ search_agp_bridge(&agp_aper_order, &valid_agp); fix = 0; for (i = 0; amd_nb_bus_dev_ranges[i].dev_limit; i++) { int bus; int dev_base, dev_limit; bus = amd_nb_bus_dev_ranges[i].bus; dev_base = amd_nb_bus_dev_ranges[i].dev_base; dev_limit = amd_nb_bus_dev_ranges[i].dev_limit; for (slot = dev_base; slot < dev_limit; slot++) { if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00))) continue; ctl = read_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL); aper_enabled = ctl & GARTEN; aper_order = (ctl >> 1) & 7; aper_size = (32 * 1024 * 1024) << aper_order; aper_base = read_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE) & 0x7fff; aper_base <<= 25; if (last_valid) { if ((aper_order != last_aper_order) || (aper_base != last_aper_base) || (aper_enabled != last_aper_enabled)) { fix = 1; break; } } last_aper_order = aper_order; last_aper_base = aper_base; last_aper_enabled = aper_enabled; last_valid = 1; } } if (!fix && !aper_enabled) return; if (!aper_base || !aper_size || aper_base + aper_size > 0x100000000UL) fix = 1; if (gart_fix_e820 && !fix && aper_enabled) { if (e820__mapped_any(aper_base, aper_base + aper_size, E820_TYPE_RAM)) { /* reserve it, so we can reuse it in second kernel */ pr_info("e820: reserve [mem %#010Lx-%#010Lx] for GART\n", aper_base, aper_base + aper_size - 1); e820__range_add(aper_base, aper_size, E820_TYPE_RESERVED); e820__update_table_print(); } } if (valid_agp) return; /* disable them all at first */ for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) { int bus; int dev_base, dev_limit; bus = amd_nb_bus_dev_ranges[i].bus; dev_base = amd_nb_bus_dev_ranges[i].dev_base; dev_limit = amd_nb_bus_dev_ranges[i].dev_limit; for (slot = dev_base; slot < dev_limit; slot++) { if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00))) continue; ctl = read_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL); ctl &= ~GARTEN; write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl); } } } static int __initdata printed_gart_size_msg; void __init gart_iommu_hole_init(void) { u32 agp_aper_base = 0, agp_aper_order = 0; u32 aper_size, aper_alloc = 0, aper_order = 0, last_aper_order = 0; u64 aper_base, last_aper_base = 0; int fix, slot, valid_agp = 0; int i, node; if (!amd_gart_present()) return; if (gart_iommu_aperture_disabled || !fix_aperture || !early_pci_allowed()) return; pr_info("Checking aperture...\n"); if (!fallback_aper_force) agp_aper_base = search_agp_bridge(&agp_aper_order, &valid_agp); fix = 0; node = 0; for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) { int bus; int dev_base, dev_limit; u32 ctl; bus = amd_nb_bus_dev_ranges[i].bus; dev_base = amd_nb_bus_dev_ranges[i].dev_base; dev_limit = amd_nb_bus_dev_ranges[i].dev_limit; for (slot = dev_base; slot < dev_limit; slot++) { if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00))) continue; iommu_detected = 1; gart_iommu_aperture = 1; x86_init.iommu.iommu_init = gart_iommu_init; ctl = read_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL); /* * Before we do anything else disable the GART. It may * still be enabled if we boot into a crash-kernel here. * Reconfiguring the GART while it is enabled could have * unknown side-effects. */ ctl &= ~GARTEN; write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl); aper_order = (ctl >> 1) & 7; aper_size = (32 * 1024 * 1024) << aper_order; aper_base = read_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE) & 0x7fff; aper_base <<= 25; pr_info("Node %d: aperture [bus addr %#010Lx-%#010Lx] (%uMB)\n", node, aper_base, aper_base + aper_size - 1, aper_size >> 20); node++; if (!aperture_valid(aper_base, aper_size, 64<<20)) { if (valid_agp && agp_aper_base && agp_aper_base == aper_base && agp_aper_order == aper_order) { /* the same between two setting from NB and agp */ if (!no_iommu && max_pfn > MAX_DMA32_PFN && !printed_gart_size_msg) { pr_err("you are using iommu with agp, but GART size is less than 64MB\n"); pr_err("please increase GART size in your BIOS setup\n"); pr_err("if BIOS doesn't have that option, contact your HW vendor!\n"); printed_gart_size_msg = 1; } } else { fix = 1; goto out; } } if ((last_aper_order && aper_order != last_aper_order) || (last_aper_base && aper_base != last_aper_base)) { fix = 1; goto out; } last_aper_order = aper_order; last_aper_base = aper_base; } } out: if (!fix && !fallback_aper_force) { if (last_aper_base) { /* * If this is the kdump kernel, the first kernel * may have allocated the range over its e820 RAM * and fixed up the northbridge */ exclude_from_core(last_aper_base, last_aper_order); } return; } if (!fallback_aper_force) { aper_alloc = agp_aper_base; aper_order = agp_aper_order; } if (aper_alloc) { /* Got the aperture from the AGP bridge */ } else if ((!no_iommu && max_pfn > MAX_DMA32_PFN) || force_iommu || valid_agp || fallback_aper_force) { pr_info("Your BIOS doesn't leave an aperture memory hole\n"); pr_info("Please enable the IOMMU option in the BIOS setup\n"); pr_info("This costs you %dMB of RAM\n", 32 << fallback_aper_order); aper_order = fallback_aper_order; aper_alloc = allocate_aperture(); if (!aper_alloc) { /* * Could disable AGP and IOMMU here, but it's * probably not worth it. But the later users * cannot deal with bad apertures and turning * on the aperture over memory causes very * strange problems, so it's better to panic * early. */ panic("Not enough memory for aperture"); } } else { return; } /* * If this is the kdump kernel _and_ the first kernel did not * configure the aperture in the northbridge, this range may * overlap with the first kernel's memory. We can't access the * range through vmcore even though it should be part of the dump. */ exclude_from_core(aper_alloc, aper_order); /* Fix up the north bridges */ for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) { int bus, dev_base, dev_limit; /* * Don't enable translation yet but enable GART IO and CPU * accesses and set DISTLBWALKPRB since GART table memory is UC. */ u32 ctl = aper_order << 1; bus = amd_nb_bus_dev_ranges[i].bus; dev_base = amd_nb_bus_dev_ranges[i].dev_base; dev_limit = amd_nb_bus_dev_ranges[i].dev_limit; for (slot = dev_base; slot < dev_limit; slot++) { if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00))) continue; write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl); write_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE, aper_alloc >> 25); } } set_up_gart_resume(aper_order, aper_alloc); }
linux-master
arch/x86/kernel/aperture_64.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 1991,1992,1995 Linus Torvalds * Copyright (c) 1994 Alan Modra * Copyright (c) 1995 Markus Kuhn * Copyright (c) 1996 Ingo Molnar * Copyright (c) 1998 Andrea Arcangeli * Copyright (c) 2002,2006 Vojtech Pavlik * Copyright (c) 2003 Andi Kleen * */ #include <linux/clocksource.h> #include <linux/clockchips.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/i8253.h> #include <linux/time.h> #include <linux/export.h> #include <asm/vsyscall.h> #include <asm/x86_init.h> #include <asm/i8259.h> #include <asm/timer.h> #include <asm/hpet.h> #include <asm/time.h> unsigned long profile_pc(struct pt_regs *regs) { unsigned long pc = instruction_pointer(regs); if (!user_mode(regs) && in_lock_functions(pc)) { #ifdef CONFIG_FRAME_POINTER return *(unsigned long *)(regs->bp + sizeof(long)); #else unsigned long *sp = (unsigned long *)regs->sp; /* * Return address is either directly at stack pointer * or above a saved flags. Eflags has bits 22-31 zero, * kernel addresses don't. */ if (sp[0] >> 22) return sp[0]; if (sp[1] >> 22) return sp[1]; #endif } return pc; } EXPORT_SYMBOL(profile_pc); /* * Default timer interrupt handler for PIT/HPET */ static irqreturn_t timer_interrupt(int irq, void *dev_id) { global_clock_event->event_handler(global_clock_event); return IRQ_HANDLED; } static void __init setup_default_timer_irq(void) { unsigned long flags = IRQF_NOBALANCING | IRQF_IRQPOLL | IRQF_TIMER; /* * Unconditionally register the legacy timer interrupt; even * without legacy PIC/PIT we need this for the HPET0 in legacy * replacement mode. */ if (request_irq(0, timer_interrupt, flags, "timer", NULL)) pr_info("Failed to register legacy timer interrupt\n"); } /* Default timer init function */ void __init hpet_time_init(void) { if (!hpet_enable()) { if (!pit_timer_init()) return; } setup_default_timer_irq(); } static __init void x86_late_time_init(void) { /* * Before PIT/HPET init, select the interrupt mode. This is required * to make the decision whether PIT should be initialized correct. */ x86_init.irqs.intr_mode_select(); /* Setup the legacy timers */ x86_init.timers.timer_init(); /* * After PIT/HPET timers init, set up the final interrupt mode for * delivering IRQs. */ x86_init.irqs.intr_mode_init(); tsc_init(); if (static_cpu_has(X86_FEATURE_WAITPKG)) use_tpause_delay(); } /* * Initialize TSC and delay the periodic timer init to * late x86_late_time_init() so ioremap works. */ void __init time_init(void) { late_time_init = x86_late_time_init; } /* * Sanity check the vdso related archdata content. */ void clocksource_arch_init(struct clocksource *cs) { if (cs->vdso_clock_mode == VDSO_CLOCKMODE_NONE) return; if (cs->mask != CLOCKSOURCE_MASK(64)) { pr_warn("clocksource %s registered with invalid mask %016llx for VDSO. Disabling VDSO support.\n", cs->name, cs->mask); cs->vdso_clock_mode = VDSO_CLOCKMODE_NONE; } }
linux-master
arch/x86/kernel/time.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 1992 Krishna Balasubramanian and Linus Torvalds * Copyright (C) 1999 Ingo Molnar <[email protected]> * Copyright (C) 2002 Andi Kleen * * This handles calls from both 32bit and 64bit mode. * * Lock order: * contex.ldt_usr_sem * mmap_lock * context.lock */ #include <linux/errno.h> #include <linux/gfp.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/syscalls.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/uaccess.h> #include <asm/ldt.h> #include <asm/tlb.h> #include <asm/desc.h> #include <asm/mmu_context.h> #include <asm/pgtable_areas.h> #include <xen/xen.h> /* This is a multiple of PAGE_SIZE. */ #define LDT_SLOT_STRIDE (LDT_ENTRIES * LDT_ENTRY_SIZE) static inline void *ldt_slot_va(int slot) { return (void *)(LDT_BASE_ADDR + LDT_SLOT_STRIDE * slot); } void load_mm_ldt(struct mm_struct *mm) { struct ldt_struct *ldt; /* READ_ONCE synchronizes with smp_store_release */ ldt = READ_ONCE(mm->context.ldt); /* * Any change to mm->context.ldt is followed by an IPI to all * CPUs with the mm active. The LDT will not be freed until * after the IPI is handled by all such CPUs. This means that, * if the ldt_struct changes before we return, the values we see * will be safe, and the new values will be loaded before we run * any user code. * * NB: don't try to convert this to use RCU without extreme care. * We would still need IRQs off, because we don't want to change * the local LDT after an IPI loaded a newer value than the one * that we can see. */ if (unlikely(ldt)) { if (static_cpu_has(X86_FEATURE_PTI)) { if (WARN_ON_ONCE((unsigned long)ldt->slot > 1)) { /* * Whoops -- either the new LDT isn't mapped * (if slot == -1) or is mapped into a bogus * slot (if slot > 1). */ clear_LDT(); return; } /* * If page table isolation is enabled, ldt->entries * will not be mapped in the userspace pagetables. * Tell the CPU to access the LDT through the alias * at ldt_slot_va(ldt->slot). */ set_ldt(ldt_slot_va(ldt->slot), ldt->nr_entries); } else { set_ldt(ldt->entries, ldt->nr_entries); } } else { clear_LDT(); } } void switch_ldt(struct mm_struct *prev, struct mm_struct *next) { /* * Load the LDT if either the old or new mm had an LDT. * * An mm will never go from having an LDT to not having an LDT. Two * mms never share an LDT, so we don't gain anything by checking to * see whether the LDT changed. There's also no guarantee that * prev->context.ldt actually matches LDTR, but, if LDTR is non-NULL, * then prev->context.ldt will also be non-NULL. * * If we really cared, we could optimize the case where prev == next * and we're exiting lazy mode. Most of the time, if this happens, * we don't actually need to reload LDTR, but modify_ldt() is mostly * used by legacy code and emulators where we don't need this level of * performance. * * This uses | instead of || because it generates better code. */ if (unlikely((unsigned long)prev->context.ldt | (unsigned long)next->context.ldt)) load_mm_ldt(next); DEBUG_LOCKS_WARN_ON(preemptible()); } static void refresh_ldt_segments(void) { #ifdef CONFIG_X86_64 unsigned short sel; /* * Make sure that the cached DS and ES descriptors match the updated * LDT. */ savesegment(ds, sel); if ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) loadsegment(ds, sel); savesegment(es, sel); if ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) loadsegment(es, sel); #endif } /* context.lock is held by the task which issued the smp function call */ static void flush_ldt(void *__mm) { struct mm_struct *mm = __mm; if (this_cpu_read(cpu_tlbstate.loaded_mm) != mm) return; load_mm_ldt(mm); refresh_ldt_segments(); } /* The caller must call finalize_ldt_struct on the result. LDT starts zeroed. */ static struct ldt_struct *alloc_ldt_struct(unsigned int num_entries) { struct ldt_struct *new_ldt; unsigned int alloc_size; if (num_entries > LDT_ENTRIES) return NULL; new_ldt = kmalloc(sizeof(struct ldt_struct), GFP_KERNEL_ACCOUNT); if (!new_ldt) return NULL; BUILD_BUG_ON(LDT_ENTRY_SIZE != sizeof(struct desc_struct)); alloc_size = num_entries * LDT_ENTRY_SIZE; /* * Xen is very picky: it requires a page-aligned LDT that has no * trailing nonzero bytes in any page that contains LDT descriptors. * Keep it simple: zero the whole allocation and never allocate less * than PAGE_SIZE. */ if (alloc_size > PAGE_SIZE) new_ldt->entries = __vmalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_ZERO); else new_ldt->entries = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT); if (!new_ldt->entries) { kfree(new_ldt); return NULL; } /* The new LDT isn't aliased for PTI yet. */ new_ldt->slot = -1; new_ldt->nr_entries = num_entries; return new_ldt; } #ifdef CONFIG_PAGE_TABLE_ISOLATION static void do_sanity_check(struct mm_struct *mm, bool had_kernel_mapping, bool had_user_mapping) { if (mm->context.ldt) { /* * We already had an LDT. The top-level entry should already * have been allocated and synchronized with the usermode * tables. */ WARN_ON(!had_kernel_mapping); if (boot_cpu_has(X86_FEATURE_PTI)) WARN_ON(!had_user_mapping); } else { /* * This is the first time we're mapping an LDT for this process. * Sync the pgd to the usermode tables. */ WARN_ON(had_kernel_mapping); if (boot_cpu_has(X86_FEATURE_PTI)) WARN_ON(had_user_mapping); } } #ifdef CONFIG_X86_PAE static pmd_t *pgd_to_pmd_walk(pgd_t *pgd, unsigned long va) { p4d_t *p4d; pud_t *pud; if (pgd->pgd == 0) return NULL; p4d = p4d_offset(pgd, va); if (p4d_none(*p4d)) return NULL; pud = pud_offset(p4d, va); if (pud_none(*pud)) return NULL; return pmd_offset(pud, va); } static void map_ldt_struct_to_user(struct mm_struct *mm) { pgd_t *k_pgd = pgd_offset(mm, LDT_BASE_ADDR); pgd_t *u_pgd = kernel_to_user_pgdp(k_pgd); pmd_t *k_pmd, *u_pmd; k_pmd = pgd_to_pmd_walk(k_pgd, LDT_BASE_ADDR); u_pmd = pgd_to_pmd_walk(u_pgd, LDT_BASE_ADDR); if (boot_cpu_has(X86_FEATURE_PTI) && !mm->context.ldt) set_pmd(u_pmd, *k_pmd); } static void sanity_check_ldt_mapping(struct mm_struct *mm) { pgd_t *k_pgd = pgd_offset(mm, LDT_BASE_ADDR); pgd_t *u_pgd = kernel_to_user_pgdp(k_pgd); bool had_kernel, had_user; pmd_t *k_pmd, *u_pmd; k_pmd = pgd_to_pmd_walk(k_pgd, LDT_BASE_ADDR); u_pmd = pgd_to_pmd_walk(u_pgd, LDT_BASE_ADDR); had_kernel = (k_pmd->pmd != 0); had_user = (u_pmd->pmd != 0); do_sanity_check(mm, had_kernel, had_user); } #else /* !CONFIG_X86_PAE */ static void map_ldt_struct_to_user(struct mm_struct *mm) { pgd_t *pgd = pgd_offset(mm, LDT_BASE_ADDR); if (boot_cpu_has(X86_FEATURE_PTI) && !mm->context.ldt) set_pgd(kernel_to_user_pgdp(pgd), *pgd); } static void sanity_check_ldt_mapping(struct mm_struct *mm) { pgd_t *pgd = pgd_offset(mm, LDT_BASE_ADDR); bool had_kernel = (pgd->pgd != 0); bool had_user = (kernel_to_user_pgdp(pgd)->pgd != 0); do_sanity_check(mm, had_kernel, had_user); } #endif /* CONFIG_X86_PAE */ /* * If PTI is enabled, this maps the LDT into the kernelmode and * usermode tables for the given mm. */ static int map_ldt_struct(struct mm_struct *mm, struct ldt_struct *ldt, int slot) { unsigned long va; bool is_vmalloc; spinlock_t *ptl; int i, nr_pages; if (!boot_cpu_has(X86_FEATURE_PTI)) return 0; /* * Any given ldt_struct should have map_ldt_struct() called at most * once. */ WARN_ON(ldt->slot != -1); /* Check if the current mappings are sane */ sanity_check_ldt_mapping(mm); is_vmalloc = is_vmalloc_addr(ldt->entries); nr_pages = DIV_ROUND_UP(ldt->nr_entries * LDT_ENTRY_SIZE, PAGE_SIZE); for (i = 0; i < nr_pages; i++) { unsigned long offset = i << PAGE_SHIFT; const void *src = (char *)ldt->entries + offset; unsigned long pfn; pgprot_t pte_prot; pte_t pte, *ptep; va = (unsigned long)ldt_slot_va(slot) + offset; pfn = is_vmalloc ? vmalloc_to_pfn(src) : page_to_pfn(virt_to_page(src)); /* * Treat the PTI LDT range as a *userspace* range. * get_locked_pte() will allocate all needed pagetables * and account for them in this mm. */ ptep = get_locked_pte(mm, va, &ptl); if (!ptep) return -ENOMEM; /* * Map it RO so the easy to find address is not a primary * target via some kernel interface which misses a * permission check. */ pte_prot = __pgprot(__PAGE_KERNEL_RO & ~_PAGE_GLOBAL); /* Filter out unsuppored __PAGE_KERNEL* bits: */ pgprot_val(pte_prot) &= __supported_pte_mask; pte = pfn_pte(pfn, pte_prot); set_pte_at(mm, va, ptep, pte); pte_unmap_unlock(ptep, ptl); } /* Propagate LDT mapping to the user page-table */ map_ldt_struct_to_user(mm); ldt->slot = slot; return 0; } static void unmap_ldt_struct(struct mm_struct *mm, struct ldt_struct *ldt) { unsigned long va; int i, nr_pages; if (!ldt) return; /* LDT map/unmap is only required for PTI */ if (!boot_cpu_has(X86_FEATURE_PTI)) return; nr_pages = DIV_ROUND_UP(ldt->nr_entries * LDT_ENTRY_SIZE, PAGE_SIZE); for (i = 0; i < nr_pages; i++) { unsigned long offset = i << PAGE_SHIFT; spinlock_t *ptl; pte_t *ptep; va = (unsigned long)ldt_slot_va(ldt->slot) + offset; ptep = get_locked_pte(mm, va, &ptl); if (!WARN_ON_ONCE(!ptep)) { pte_clear(mm, va, ptep); pte_unmap_unlock(ptep, ptl); } } va = (unsigned long)ldt_slot_va(ldt->slot); flush_tlb_mm_range(mm, va, va + nr_pages * PAGE_SIZE, PAGE_SHIFT, false); } #else /* !CONFIG_PAGE_TABLE_ISOLATION */ static int map_ldt_struct(struct mm_struct *mm, struct ldt_struct *ldt, int slot) { return 0; } static void unmap_ldt_struct(struct mm_struct *mm, struct ldt_struct *ldt) { } #endif /* CONFIG_PAGE_TABLE_ISOLATION */ static void free_ldt_pgtables(struct mm_struct *mm) { #ifdef CONFIG_PAGE_TABLE_ISOLATION struct mmu_gather tlb; unsigned long start = LDT_BASE_ADDR; unsigned long end = LDT_END_ADDR; if (!boot_cpu_has(X86_FEATURE_PTI)) return; /* * Although free_pgd_range() is intended for freeing user * page-tables, it also works out for kernel mappings on x86. * We use tlb_gather_mmu_fullmm() to avoid confusing the * range-tracking logic in __tlb_adjust_range(). */ tlb_gather_mmu_fullmm(&tlb, mm); free_pgd_range(&tlb, start, end, start, end); tlb_finish_mmu(&tlb); #endif } /* After calling this, the LDT is immutable. */ static void finalize_ldt_struct(struct ldt_struct *ldt) { paravirt_alloc_ldt(ldt->entries, ldt->nr_entries); } static void install_ldt(struct mm_struct *mm, struct ldt_struct *ldt) { mutex_lock(&mm->context.lock); /* Synchronizes with READ_ONCE in load_mm_ldt. */ smp_store_release(&mm->context.ldt, ldt); /* Activate the LDT for all CPUs using currents mm. */ on_each_cpu_mask(mm_cpumask(mm), flush_ldt, mm, true); mutex_unlock(&mm->context.lock); } static void free_ldt_struct(struct ldt_struct *ldt) { if (likely(!ldt)) return; paravirt_free_ldt(ldt->entries, ldt->nr_entries); if (ldt->nr_entries * LDT_ENTRY_SIZE > PAGE_SIZE) vfree_atomic(ldt->entries); else free_page((unsigned long)ldt->entries); kfree(ldt); } /* * Called on fork from arch_dup_mmap(). Just copy the current LDT state, * the new task is not running, so nothing can be installed. */ int ldt_dup_context(struct mm_struct *old_mm, struct mm_struct *mm) { struct ldt_struct *new_ldt; int retval = 0; if (!old_mm) return 0; mutex_lock(&old_mm->context.lock); if (!old_mm->context.ldt) goto out_unlock; new_ldt = alloc_ldt_struct(old_mm->context.ldt->nr_entries); if (!new_ldt) { retval = -ENOMEM; goto out_unlock; } memcpy(new_ldt->entries, old_mm->context.ldt->entries, new_ldt->nr_entries * LDT_ENTRY_SIZE); finalize_ldt_struct(new_ldt); retval = map_ldt_struct(mm, new_ldt, 0); if (retval) { free_ldt_pgtables(mm); free_ldt_struct(new_ldt); goto out_unlock; } mm->context.ldt = new_ldt; out_unlock: mutex_unlock(&old_mm->context.lock); return retval; } /* * No need to lock the MM as we are the last user * * 64bit: Don't touch the LDT register - we're already in the next thread. */ void destroy_context_ldt(struct mm_struct *mm) { free_ldt_struct(mm->context.ldt); mm->context.ldt = NULL; } void ldt_arch_exit_mmap(struct mm_struct *mm) { free_ldt_pgtables(mm); } static int read_ldt(void __user *ptr, unsigned long bytecount) { struct mm_struct *mm = current->mm; unsigned long entries_size; int retval; down_read(&mm->context.ldt_usr_sem); if (!mm->context.ldt) { retval = 0; goto out_unlock; } if (bytecount > LDT_ENTRY_SIZE * LDT_ENTRIES) bytecount = LDT_ENTRY_SIZE * LDT_ENTRIES; entries_size = mm->context.ldt->nr_entries * LDT_ENTRY_SIZE; if (entries_size > bytecount) entries_size = bytecount; if (copy_to_user(ptr, mm->context.ldt->entries, entries_size)) { retval = -EFAULT; goto out_unlock; } if (entries_size != bytecount) { /* Zero-fill the rest and pretend we read bytecount bytes. */ if (clear_user(ptr + entries_size, bytecount - entries_size)) { retval = -EFAULT; goto out_unlock; } } retval = bytecount; out_unlock: up_read(&mm->context.ldt_usr_sem); return retval; } static int read_default_ldt(void __user *ptr, unsigned long bytecount) { /* CHECKME: Can we use _one_ random number ? */ #ifdef CONFIG_X86_32 unsigned long size = 5 * sizeof(struct desc_struct); #else unsigned long size = 128; #endif if (bytecount > size) bytecount = size; if (clear_user(ptr, bytecount)) return -EFAULT; return bytecount; } static bool allow_16bit_segments(void) { if (!IS_ENABLED(CONFIG_X86_16BIT)) return false; #ifdef CONFIG_XEN_PV /* * Xen PV does not implement ESPFIX64, which means that 16-bit * segments will not work correctly. Until either Xen PV implements * ESPFIX64 and can signal this fact to the guest or unless someone * provides compelling evidence that allowing broken 16-bit segments * is worthwhile, disallow 16-bit segments under Xen PV. */ if (xen_pv_domain()) { pr_info_once("Warning: 16-bit segments do not work correctly in a Xen PV guest\n"); return false; } #endif return true; } static int write_ldt(void __user *ptr, unsigned long bytecount, int oldmode) { struct mm_struct *mm = current->mm; struct ldt_struct *new_ldt, *old_ldt; unsigned int old_nr_entries, new_nr_entries; struct user_desc ldt_info; struct desc_struct ldt; int error; error = -EINVAL; if (bytecount != sizeof(ldt_info)) goto out; error = -EFAULT; if (copy_from_user(&ldt_info, ptr, sizeof(ldt_info))) goto out; error = -EINVAL; if (ldt_info.entry_number >= LDT_ENTRIES) goto out; if (ldt_info.contents == 3) { if (oldmode) goto out; if (ldt_info.seg_not_present == 0) goto out; } if ((oldmode && !ldt_info.base_addr && !ldt_info.limit) || LDT_empty(&ldt_info)) { /* The user wants to clear the entry. */ memset(&ldt, 0, sizeof(ldt)); } else { if (!ldt_info.seg_32bit && !allow_16bit_segments()) { error = -EINVAL; goto out; } fill_ldt(&ldt, &ldt_info); if (oldmode) ldt.avl = 0; } if (down_write_killable(&mm->context.ldt_usr_sem)) return -EINTR; old_ldt = mm->context.ldt; old_nr_entries = old_ldt ? old_ldt->nr_entries : 0; new_nr_entries = max(ldt_info.entry_number + 1, old_nr_entries); error = -ENOMEM; new_ldt = alloc_ldt_struct(new_nr_entries); if (!new_ldt) goto out_unlock; if (old_ldt) memcpy(new_ldt->entries, old_ldt->entries, old_nr_entries * LDT_ENTRY_SIZE); new_ldt->entries[ldt_info.entry_number] = ldt; finalize_ldt_struct(new_ldt); /* * If we are using PTI, map the new LDT into the userspace pagetables. * If there is already an LDT, use the other slot so that other CPUs * will continue to use the old LDT until install_ldt() switches * them over to the new LDT. */ error = map_ldt_struct(mm, new_ldt, old_ldt ? !old_ldt->slot : 0); if (error) { /* * This only can fail for the first LDT setup. If an LDT is * already installed then the PTE page is already * populated. Mop up a half populated page table. */ if (!WARN_ON_ONCE(old_ldt)) free_ldt_pgtables(mm); free_ldt_struct(new_ldt); goto out_unlock; } install_ldt(mm, new_ldt); unmap_ldt_struct(mm, old_ldt); free_ldt_struct(old_ldt); error = 0; out_unlock: up_write(&mm->context.ldt_usr_sem); out: return error; } SYSCALL_DEFINE3(modify_ldt, int , func , void __user * , ptr , unsigned long , bytecount) { int ret = -ENOSYS; switch (func) { case 0: ret = read_ldt(ptr, bytecount); break; case 1: ret = write_ldt(ptr, bytecount, 1); break; case 2: ret = read_default_ldt(ptr, bytecount); break; case 0x11: ret = write_ldt(ptr, bytecount, 0); break; } /* * The SYSCALL_DEFINE() macros give us an 'unsigned long' * return type, but tht ABI for sys_modify_ldt() expects * 'int'. This cast gives us an int-sized value in %rax * for the return code. The 'unsigned' is necessary so * the compiler does not try to sign-extend the negative * return codes into the high half of the register when * taking the value from int->long. */ return (unsigned int)ret; }
linux-master
arch/x86/kernel/ldt.c
// SPDX-License-Identifier: GPL-2.0 /* * Memory preserving reboot related code. * * Created by: Hariprasad Nellitheertha ([email protected]) * Copyright (C) IBM Corporation, 2004. All rights reserved */ #include <linux/errno.h> #include <linux/crash_dump.h> #include <linux/uio.h> #include <linux/io.h> #include <linux/cc_platform.h> static ssize_t __copy_oldmem_page(struct iov_iter *iter, unsigned long pfn, size_t csize, unsigned long offset, bool encrypted) { void *vaddr; if (!csize) return 0; if (encrypted) vaddr = (__force void *)ioremap_encrypted(pfn << PAGE_SHIFT, PAGE_SIZE); else vaddr = (__force void *)ioremap_cache(pfn << PAGE_SHIFT, PAGE_SIZE); if (!vaddr) return -ENOMEM; csize = copy_to_iter(vaddr + offset, csize, iter); iounmap((void __iomem *)vaddr); return csize; } ssize_t copy_oldmem_page(struct iov_iter *iter, unsigned long pfn, size_t csize, unsigned long offset) { return __copy_oldmem_page(iter, pfn, csize, offset, false); } /* * copy_oldmem_page_encrypted - same as copy_oldmem_page() above but ioremap the * memory with the encryption mask set to accommodate kdump on SME-enabled * machines. */ ssize_t copy_oldmem_page_encrypted(struct iov_iter *iter, unsigned long pfn, size_t csize, unsigned long offset) { return __copy_oldmem_page(iter, pfn, csize, offset, true); } ssize_t elfcorehdr_read(char *buf, size_t count, u64 *ppos) { struct kvec kvec = { .iov_base = buf, .iov_len = count }; struct iov_iter iter; iov_iter_kvec(&iter, ITER_DEST, &kvec, 1, count); return read_from_oldmem(&iter, count, ppos, cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)); }
linux-master
arch/x86/kernel/crash_dump_64.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/init.h> #include <linux/types.h> #include <linux/audit.h> #include <asm/unistd.h> #include <asm/audit.h> static unsigned dir_class[] = { #include <asm-generic/audit_dir_write.h> ~0U }; static unsigned read_class[] = { #include <asm-generic/audit_read.h> ~0U }; static unsigned write_class[] = { #include <asm-generic/audit_write.h> ~0U }; static unsigned chattr_class[] = { #include <asm-generic/audit_change_attr.h> ~0U }; static unsigned signal_class[] = { #include <asm-generic/audit_signal.h> ~0U }; int audit_classify_arch(int arch) { #ifdef CONFIG_IA32_EMULATION if (arch == AUDIT_ARCH_I386) return 1; #endif return 0; } int audit_classify_syscall(int abi, unsigned syscall) { #ifdef CONFIG_IA32_EMULATION if (abi == AUDIT_ARCH_I386) return ia32_classify_syscall(syscall); #endif switch(syscall) { case __NR_open: return AUDITSC_OPEN; case __NR_openat: return AUDITSC_OPENAT; case __NR_execve: case __NR_execveat: return AUDITSC_EXECVE; case __NR_openat2: return AUDITSC_OPENAT2; default: return AUDITSC_NATIVE; } } static int __init audit_classes_init(void) { #ifdef CONFIG_IA32_EMULATION audit_register_class(AUDIT_CLASS_WRITE_32, ia32_write_class); audit_register_class(AUDIT_CLASS_READ_32, ia32_read_class); audit_register_class(AUDIT_CLASS_DIR_WRITE_32, ia32_dir_class); audit_register_class(AUDIT_CLASS_CHATTR_32, ia32_chattr_class); audit_register_class(AUDIT_CLASS_SIGNAL_32, ia32_signal_class); #endif audit_register_class(AUDIT_CLASS_WRITE, write_class); audit_register_class(AUDIT_CLASS_READ, read_class); audit_register_class(AUDIT_CLASS_DIR_WRITE, dir_class); audit_register_class(AUDIT_CLASS_CHATTR, chattr_class); audit_register_class(AUDIT_CLASS_SIGNAL, signal_class); return 0; } __initcall(audit_classes_init);
linux-master
arch/x86/kernel/audit_64.c
// SPDX-License-Identifier: GPL-2.0 /* * prepare to run common code * * Copyright (C) 2000 Andrea Arcangeli <[email protected]> SuSE */ #define DISABLE_BRANCH_PROFILING /* cpu_feature_enabled() cannot be used this early */ #define USE_EARLY_PGTABLE_L5 #include <linux/init.h> #include <linux/linkage.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/percpu.h> #include <linux/start_kernel.h> #include <linux/io.h> #include <linux/memblock.h> #include <linux/cc_platform.h> #include <linux/pgtable.h> #include <asm/processor.h> #include <asm/proto.h> #include <asm/smp.h> #include <asm/setup.h> #include <asm/desc.h> #include <asm/tlbflush.h> #include <asm/sections.h> #include <asm/kdebug.h> #include <asm/e820/api.h> #include <asm/bios_ebda.h> #include <asm/bootparam_utils.h> #include <asm/microcode.h> #include <asm/kasan.h> #include <asm/fixmap.h> #include <asm/realmode.h> #include <asm/extable.h> #include <asm/trapnr.h> #include <asm/sev.h> #include <asm/tdx.h> /* * Manage page tables very early on. */ extern pmd_t early_dynamic_pgts[EARLY_DYNAMIC_PAGE_TABLES][PTRS_PER_PMD]; static unsigned int __initdata next_early_pgt; pmdval_t early_pmd_flags = __PAGE_KERNEL_LARGE & ~(_PAGE_GLOBAL | _PAGE_NX); #ifdef CONFIG_X86_5LEVEL unsigned int __pgtable_l5_enabled __ro_after_init; unsigned int pgdir_shift __ro_after_init = 39; EXPORT_SYMBOL(pgdir_shift); unsigned int ptrs_per_p4d __ro_after_init = 1; EXPORT_SYMBOL(ptrs_per_p4d); #endif #ifdef CONFIG_DYNAMIC_MEMORY_LAYOUT unsigned long page_offset_base __ro_after_init = __PAGE_OFFSET_BASE_L4; EXPORT_SYMBOL(page_offset_base); unsigned long vmalloc_base __ro_after_init = __VMALLOC_BASE_L4; EXPORT_SYMBOL(vmalloc_base); unsigned long vmemmap_base __ro_after_init = __VMEMMAP_BASE_L4; EXPORT_SYMBOL(vmemmap_base); #endif /* * GDT used on the boot CPU before switching to virtual addresses. */ static struct desc_struct startup_gdt[GDT_ENTRIES] = { [GDT_ENTRY_KERNEL32_CS] = GDT_ENTRY_INIT(0xc09b, 0, 0xfffff), [GDT_ENTRY_KERNEL_CS] = GDT_ENTRY_INIT(0xa09b, 0, 0xfffff), [GDT_ENTRY_KERNEL_DS] = GDT_ENTRY_INIT(0xc093, 0, 0xfffff), }; /* * Address needs to be set at runtime because it references the startup_gdt * while the kernel still uses a direct mapping. */ static struct desc_ptr startup_gdt_descr = { .size = sizeof(startup_gdt), .address = 0, }; #define __head __section(".head.text") static void __head *fixup_pointer(void *ptr, unsigned long physaddr) { return ptr - (void *)_text + (void *)physaddr; } static unsigned long __head *fixup_long(void *ptr, unsigned long physaddr) { return fixup_pointer(ptr, physaddr); } #ifdef CONFIG_X86_5LEVEL static unsigned int __head *fixup_int(void *ptr, unsigned long physaddr) { return fixup_pointer(ptr, physaddr); } static bool __head check_la57_support(unsigned long physaddr) { /* * 5-level paging is detected and enabled at kernel decompression * stage. Only check if it has been enabled there. */ if (!(native_read_cr4() & X86_CR4_LA57)) return false; *fixup_int(&__pgtable_l5_enabled, physaddr) = 1; *fixup_int(&pgdir_shift, physaddr) = 48; *fixup_int(&ptrs_per_p4d, physaddr) = 512; *fixup_long(&page_offset_base, physaddr) = __PAGE_OFFSET_BASE_L5; *fixup_long(&vmalloc_base, physaddr) = __VMALLOC_BASE_L5; *fixup_long(&vmemmap_base, physaddr) = __VMEMMAP_BASE_L5; return true; } #else static bool __head check_la57_support(unsigned long physaddr) { return false; } #endif static unsigned long __head sme_postprocess_startup(struct boot_params *bp, pmdval_t *pmd) { unsigned long vaddr, vaddr_end; int i; /* Encrypt the kernel and related (if SME is active) */ sme_encrypt_kernel(bp); /* * Clear the memory encryption mask from the .bss..decrypted section. * The bss section will be memset to zero later in the initialization so * there is no need to zero it after changing the memory encryption * attribute. */ if (sme_get_me_mask()) { vaddr = (unsigned long)__start_bss_decrypted; vaddr_end = (unsigned long)__end_bss_decrypted; for (; vaddr < vaddr_end; vaddr += PMD_SIZE) { /* * On SNP, transition the page to shared in the RMP table so that * it is consistent with the page table attribute change. * * __start_bss_decrypted has a virtual address in the high range * mapping (kernel .text). PVALIDATE, by way of * early_snp_set_memory_shared(), requires a valid virtual * address but the kernel is currently running off of the identity * mapping so use __pa() to get a *currently* valid virtual address. */ early_snp_set_memory_shared(__pa(vaddr), __pa(vaddr), PTRS_PER_PMD); i = pmd_index(vaddr); pmd[i] -= sme_get_me_mask(); } } /* * Return the SME encryption mask (if SME is active) to be used as a * modifier for the initial pgdir entry programmed into CR3. */ return sme_get_me_mask(); } /* Code in __startup_64() can be relocated during execution, but the compiler * doesn't have to generate PC-relative relocations when accessing globals from * that function. Clang actually does not generate them, which leads to * boot-time crashes. To work around this problem, every global pointer must * be adjusted using fixup_pointer(). */ unsigned long __head __startup_64(unsigned long physaddr, struct boot_params *bp) { unsigned long load_delta, *p; unsigned long pgtable_flags; pgdval_t *pgd; p4dval_t *p4d; pudval_t *pud; pmdval_t *pmd, pmd_entry; pteval_t *mask_ptr; bool la57; int i; unsigned int *next_pgt_ptr; la57 = check_la57_support(physaddr); /* Is the address too large? */ if (physaddr >> MAX_PHYSMEM_BITS) for (;;); /* * Compute the delta between the address I am compiled to run at * and the address I am actually running at. */ load_delta = physaddr - (unsigned long)(_text - __START_KERNEL_map); /* Is the address not 2M aligned? */ if (load_delta & ~PMD_MASK) for (;;); /* Include the SME encryption mask in the fixup value */ load_delta += sme_get_me_mask(); /* Fixup the physical addresses in the page table */ pgd = fixup_pointer(&early_top_pgt, physaddr); p = pgd + pgd_index(__START_KERNEL_map); if (la57) *p = (unsigned long)level4_kernel_pgt; else *p = (unsigned long)level3_kernel_pgt; *p += _PAGE_TABLE_NOENC - __START_KERNEL_map + load_delta; if (la57) { p4d = fixup_pointer(&level4_kernel_pgt, physaddr); p4d[511] += load_delta; } pud = fixup_pointer(&level3_kernel_pgt, physaddr); pud[510] += load_delta; pud[511] += load_delta; pmd = fixup_pointer(level2_fixmap_pgt, physaddr); for (i = FIXMAP_PMD_TOP; i > FIXMAP_PMD_TOP - FIXMAP_PMD_NUM; i--) pmd[i] += load_delta; /* * Set up the identity mapping for the switchover. These * entries should *NOT* have the global bit set! This also * creates a bunch of nonsense entries but that is fine -- * it avoids problems around wraparound. */ next_pgt_ptr = fixup_pointer(&next_early_pgt, physaddr); pud = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr); pmd = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr); pgtable_flags = _KERNPG_TABLE_NOENC + sme_get_me_mask(); if (la57) { p4d = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr); i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD; pgd[i + 0] = (pgdval_t)p4d + pgtable_flags; pgd[i + 1] = (pgdval_t)p4d + pgtable_flags; i = physaddr >> P4D_SHIFT; p4d[(i + 0) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags; p4d[(i + 1) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags; } else { i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD; pgd[i + 0] = (pgdval_t)pud + pgtable_flags; pgd[i + 1] = (pgdval_t)pud + pgtable_flags; } i = physaddr >> PUD_SHIFT; pud[(i + 0) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags; pud[(i + 1) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags; pmd_entry = __PAGE_KERNEL_LARGE_EXEC & ~_PAGE_GLOBAL; /* Filter out unsupported __PAGE_KERNEL_* bits: */ mask_ptr = fixup_pointer(&__supported_pte_mask, physaddr); pmd_entry &= *mask_ptr; pmd_entry += sme_get_me_mask(); pmd_entry += physaddr; for (i = 0; i < DIV_ROUND_UP(_end - _text, PMD_SIZE); i++) { int idx = i + (physaddr >> PMD_SHIFT); pmd[idx % PTRS_PER_PMD] = pmd_entry + i * PMD_SIZE; } /* * Fixup the kernel text+data virtual addresses. Note that * we might write invalid pmds, when the kernel is relocated * cleanup_highmap() fixes this up along with the mappings * beyond _end. * * Only the region occupied by the kernel image has so far * been checked against the table of usable memory regions * provided by the firmware, so invalidate pages outside that * region. A page table entry that maps to a reserved area of * memory would allow processor speculation into that area, * and on some hardware (particularly the UV platform) even * speculative access to some reserved areas is caught as an * error, causing the BIOS to halt the system. */ pmd = fixup_pointer(level2_kernel_pgt, physaddr); /* invalidate pages before the kernel image */ for (i = 0; i < pmd_index((unsigned long)_text); i++) pmd[i] &= ~_PAGE_PRESENT; /* fixup pages that are part of the kernel image */ for (; i <= pmd_index((unsigned long)_end); i++) if (pmd[i] & _PAGE_PRESENT) pmd[i] += load_delta; /* invalidate pages after the kernel image */ for (; i < PTRS_PER_PMD; i++) pmd[i] &= ~_PAGE_PRESENT; /* * Fixup phys_base - remove the memory encryption mask to obtain * the true physical address. */ *fixup_long(&phys_base, physaddr) += load_delta - sme_get_me_mask(); return sme_postprocess_startup(bp, pmd); } /* Wipe all early page tables except for the kernel symbol map */ static void __init reset_early_page_tables(void) { memset(early_top_pgt, 0, sizeof(pgd_t)*(PTRS_PER_PGD-1)); next_early_pgt = 0; write_cr3(__sme_pa_nodebug(early_top_pgt)); } /* Create a new PMD entry */ bool __init __early_make_pgtable(unsigned long address, pmdval_t pmd) { unsigned long physaddr = address - __PAGE_OFFSET; pgdval_t pgd, *pgd_p; p4dval_t p4d, *p4d_p; pudval_t pud, *pud_p; pmdval_t *pmd_p; /* Invalid address or early pgt is done ? */ if (physaddr >= MAXMEM || read_cr3_pa() != __pa_nodebug(early_top_pgt)) return false; again: pgd_p = &early_top_pgt[pgd_index(address)].pgd; pgd = *pgd_p; /* * The use of __START_KERNEL_map rather than __PAGE_OFFSET here is * critical -- __PAGE_OFFSET would point us back into the dynamic * range and we might end up looping forever... */ if (!pgtable_l5_enabled()) p4d_p = pgd_p; else if (pgd) p4d_p = (p4dval_t *)((pgd & PTE_PFN_MASK) + __START_KERNEL_map - phys_base); else { if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) { reset_early_page_tables(); goto again; } p4d_p = (p4dval_t *)early_dynamic_pgts[next_early_pgt++]; memset(p4d_p, 0, sizeof(*p4d_p) * PTRS_PER_P4D); *pgd_p = (pgdval_t)p4d_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE; } p4d_p += p4d_index(address); p4d = *p4d_p; if (p4d) pud_p = (pudval_t *)((p4d & PTE_PFN_MASK) + __START_KERNEL_map - phys_base); else { if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) { reset_early_page_tables(); goto again; } pud_p = (pudval_t *)early_dynamic_pgts[next_early_pgt++]; memset(pud_p, 0, sizeof(*pud_p) * PTRS_PER_PUD); *p4d_p = (p4dval_t)pud_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE; } pud_p += pud_index(address); pud = *pud_p; if (pud) pmd_p = (pmdval_t *)((pud & PTE_PFN_MASK) + __START_KERNEL_map - phys_base); else { if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) { reset_early_page_tables(); goto again; } pmd_p = (pmdval_t *)early_dynamic_pgts[next_early_pgt++]; memset(pmd_p, 0, sizeof(*pmd_p) * PTRS_PER_PMD); *pud_p = (pudval_t)pmd_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE; } pmd_p[pmd_index(address)] = pmd; return true; } static bool __init early_make_pgtable(unsigned long address) { unsigned long physaddr = address - __PAGE_OFFSET; pmdval_t pmd; pmd = (physaddr & PMD_MASK) + early_pmd_flags; return __early_make_pgtable(address, pmd); } void __init do_early_exception(struct pt_regs *regs, int trapnr) { if (trapnr == X86_TRAP_PF && early_make_pgtable(native_read_cr2())) return; if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT) && trapnr == X86_TRAP_VC && handle_vc_boot_ghcb(regs)) return; if (trapnr == X86_TRAP_VE && tdx_early_handle_ve(regs)) return; early_fixup_exception(regs, trapnr); } /* Don't add a printk in there. printk relies on the PDA which is not initialized yet. */ void __init clear_bss(void) { memset(__bss_start, 0, (unsigned long) __bss_stop - (unsigned long) __bss_start); memset(__brk_base, 0, (unsigned long) __brk_limit - (unsigned long) __brk_base); } static unsigned long get_cmd_line_ptr(void) { unsigned long cmd_line_ptr = boot_params.hdr.cmd_line_ptr; cmd_line_ptr |= (u64)boot_params.ext_cmd_line_ptr << 32; return cmd_line_ptr; } static void __init copy_bootdata(char *real_mode_data) { char * command_line; unsigned long cmd_line_ptr; /* * If SME is active, this will create decrypted mappings of the * boot data in advance of the copy operations. */ sme_map_bootdata(real_mode_data); memcpy(&boot_params, real_mode_data, sizeof(boot_params)); sanitize_boot_params(&boot_params); cmd_line_ptr = get_cmd_line_ptr(); if (cmd_line_ptr) { command_line = __va(cmd_line_ptr); memcpy(boot_command_line, command_line, COMMAND_LINE_SIZE); } /* * The old boot data is no longer needed and won't be reserved, * freeing up that memory for use by the system. If SME is active, * we need to remove the mappings that were created so that the * memory doesn't remain mapped as decrypted. */ sme_unmap_bootdata(real_mode_data); } asmlinkage __visible void __init __noreturn x86_64_start_kernel(char * real_mode_data) { /* * Build-time sanity checks on the kernel image and module * area mappings. (these are purely build-time and produce no code) */ BUILD_BUG_ON(MODULES_VADDR < __START_KERNEL_map); BUILD_BUG_ON(MODULES_VADDR - __START_KERNEL_map < KERNEL_IMAGE_SIZE); BUILD_BUG_ON(MODULES_LEN + KERNEL_IMAGE_SIZE > 2*PUD_SIZE); BUILD_BUG_ON((__START_KERNEL_map & ~PMD_MASK) != 0); BUILD_BUG_ON((MODULES_VADDR & ~PMD_MASK) != 0); BUILD_BUG_ON(!(MODULES_VADDR > __START_KERNEL)); MAYBE_BUILD_BUG_ON(!(((MODULES_END - 1) & PGDIR_MASK) == (__START_KERNEL & PGDIR_MASK))); BUILD_BUG_ON(__fix_to_virt(__end_of_fixed_addresses) <= MODULES_END); cr4_init_shadow(); /* Kill off the identity-map trampoline */ reset_early_page_tables(); clear_bss(); /* * This needs to happen *before* kasan_early_init() because latter maps stuff * into that page. */ clear_page(init_top_pgt); /* * SME support may update early_pmd_flags to include the memory * encryption mask, so it needs to be called before anything * that may generate a page fault. */ sme_early_init(); kasan_early_init(); /* * Flush global TLB entries which could be left over from the trampoline page * table. * * This needs to happen *after* kasan_early_init() as KASAN-enabled .configs * instrument native_write_cr4() so KASAN must be initialized for that * instrumentation to work. */ __native_tlb_flush_global(this_cpu_read(cpu_tlbstate.cr4)); idt_setup_early_handler(); /* Needed before cc_platform_has() can be used for TDX */ tdx_early_init(); copy_bootdata(__va(real_mode_data)); /* * Load microcode early on BSP. */ load_ucode_bsp(); /* set init_top_pgt kernel high mapping*/ init_top_pgt[511] = early_top_pgt[511]; x86_64_start_reservations(real_mode_data); } void __init __noreturn x86_64_start_reservations(char *real_mode_data) { /* version is always not zero if it is copied */ if (!boot_params.hdr.version) copy_bootdata(__va(real_mode_data)); x86_early_init_platform_quirks(); switch (boot_params.hdr.hardware_subarch) { case X86_SUBARCH_INTEL_MID: x86_intel_mid_early_setup(); break; default: break; } start_kernel(); } /* * Data structures and code used for IDT setup in head_64.S. The bringup-IDT is * used until the idt_table takes over. On the boot CPU this happens in * x86_64_start_kernel(), on secondary CPUs in start_secondary(). In both cases * this happens in the functions called from head_64.S. * * The idt_table can't be used that early because all the code modifying it is * in idt.c and can be instrumented by tracing or KASAN, which both don't work * during early CPU bringup. Also the idt_table has the runtime vectors * configured which require certain CPU state to be setup already (like TSS), * which also hasn't happened yet in early CPU bringup. */ static gate_desc bringup_idt_table[NUM_EXCEPTION_VECTORS] __page_aligned_data; static struct desc_ptr bringup_idt_descr = { .size = (NUM_EXCEPTION_VECTORS * sizeof(gate_desc)) - 1, .address = 0, /* Set at runtime */ }; static void set_bringup_idt_handler(gate_desc *idt, int n, void *handler) { #ifdef CONFIG_AMD_MEM_ENCRYPT struct idt_data data; gate_desc desc; init_idt_data(&data, n, handler); idt_init_desc(&desc, &data); native_write_idt_entry(idt, n, &desc); #endif } /* This runs while still in the direct mapping */ static void startup_64_load_idt(unsigned long physbase) { struct desc_ptr *desc = fixup_pointer(&bringup_idt_descr, physbase); gate_desc *idt = fixup_pointer(bringup_idt_table, physbase); if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) { void *handler; /* VMM Communication Exception */ handler = fixup_pointer(vc_no_ghcb, physbase); set_bringup_idt_handler(idt, X86_TRAP_VC, handler); } desc->address = (unsigned long)idt; native_load_idt(desc); } /* This is used when running on kernel addresses */ void early_setup_idt(void) { /* VMM Communication Exception */ if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) { setup_ghcb(); set_bringup_idt_handler(bringup_idt_table, X86_TRAP_VC, vc_boot_ghcb); } bringup_idt_descr.address = (unsigned long)bringup_idt_table; native_load_idt(&bringup_idt_descr); } /* * Setup boot CPU state needed before kernel switches to virtual addresses. */ void __head startup_64_setup_env(unsigned long physbase) { /* Load GDT */ startup_gdt_descr.address = (unsigned long)fixup_pointer(startup_gdt, physbase); native_load_gdt(&startup_gdt_descr); /* New GDT is live - reload data segment registers */ asm volatile("movl %%eax, %%ds\n" "movl %%eax, %%ss\n" "movl %%eax, %%es\n" : : "a"(__KERNEL_DS) : "memory"); startup_64_load_idt(physbase); }
linux-master
arch/x86/kernel/head64.c
// SPDX-License-Identifier: GPL-2.0 #ifndef __LINUX_KBUILD_H # error "Please do not build this file directly, build asm-offsets.c instead" #endif #include <asm/ia32.h> #if defined(CONFIG_KVM_GUEST) #include <asm/kvm_para.h> #endif int main(void) { #ifdef CONFIG_PARAVIRT #ifdef CONFIG_PARAVIRT_XXL #ifdef CONFIG_DEBUG_ENTRY OFFSET(PV_IRQ_save_fl, paravirt_patch_template, irq.save_fl); #endif #endif BLANK(); #endif #if defined(CONFIG_KVM_GUEST) OFFSET(KVM_STEAL_TIME_preempted, kvm_steal_time, preempted); BLANK(); #endif #define ENTRY(entry) OFFSET(pt_regs_ ## entry, pt_regs, entry) ENTRY(bx); ENTRY(cx); ENTRY(dx); ENTRY(sp); ENTRY(bp); ENTRY(si); ENTRY(di); ENTRY(r8); ENTRY(r9); ENTRY(r10); ENTRY(r11); ENTRY(r12); ENTRY(r13); ENTRY(r14); ENTRY(r15); ENTRY(flags); BLANK(); #undef ENTRY #define ENTRY(entry) OFFSET(saved_context_ ## entry, saved_context, entry) ENTRY(cr0); ENTRY(cr2); ENTRY(cr3); ENTRY(cr4); ENTRY(gdt_desc); BLANK(); #undef ENTRY BLANK(); #ifdef CONFIG_STACKPROTECTOR OFFSET(FIXED_stack_canary, fixed_percpu_data, stack_canary); BLANK(); #endif return 0; }
linux-master
arch/x86/kernel/asm-offsets_64.c
// SPDX-License-Identifier: GPL-2.0 /* * jump label x86 support * * Copyright (C) 2009 Jason Baron <[email protected]> * */ #include <linux/jump_label.h> #include <linux/memory.h> #include <linux/uaccess.h> #include <linux/module.h> #include <linux/list.h> #include <linux/jhash.h> #include <linux/cpu.h> #include <asm/kprobes.h> #include <asm/alternative.h> #include <asm/text-patching.h> #include <asm/insn.h> int arch_jump_entry_size(struct jump_entry *entry) { struct insn insn = {}; insn_decode_kernel(&insn, (void *)jump_entry_code(entry)); BUG_ON(insn.length != 2 && insn.length != 5); return insn.length; } struct jump_label_patch { const void *code; int size; }; static struct jump_label_patch __jump_label_patch(struct jump_entry *entry, enum jump_label_type type) { const void *expect, *code, *nop; const void *addr, *dest; int size; addr = (void *)jump_entry_code(entry); dest = (void *)jump_entry_target(entry); size = arch_jump_entry_size(entry); switch (size) { case JMP8_INSN_SIZE: code = text_gen_insn(JMP8_INSN_OPCODE, addr, dest); nop = x86_nops[size]; break; case JMP32_INSN_SIZE: code = text_gen_insn(JMP32_INSN_OPCODE, addr, dest); nop = x86_nops[size]; break; default: BUG(); } if (type == JUMP_LABEL_JMP) expect = nop; else expect = code; if (memcmp(addr, expect, size)) { /* * The location is not an op that we were expecting. * Something went wrong. Crash the box, as something could be * corrupting the kernel. */ pr_crit("jump_label: Fatal kernel bug, unexpected op at %pS [%p] (%5ph != %5ph)) size:%d type:%d\n", addr, addr, addr, expect, size, type); BUG(); } if (type == JUMP_LABEL_NOP) code = nop; return (struct jump_label_patch){.code = code, .size = size}; } static __always_inline void __jump_label_transform(struct jump_entry *entry, enum jump_label_type type, int init) { const struct jump_label_patch jlp = __jump_label_patch(entry, type); /* * As long as only a single processor is running and the code is still * not marked as RO, text_poke_early() can be used; Checking that * system_state is SYSTEM_BOOTING guarantees it. It will be set to * SYSTEM_SCHEDULING before other cores are awaken and before the * code is write-protected. * * At the time the change is being done, just ignore whether we * are doing nop -> jump or jump -> nop transition, and assume * always nop being the 'currently valid' instruction */ if (init || system_state == SYSTEM_BOOTING) { text_poke_early((void *)jump_entry_code(entry), jlp.code, jlp.size); return; } text_poke_bp((void *)jump_entry_code(entry), jlp.code, jlp.size, NULL); } static void __ref jump_label_transform(struct jump_entry *entry, enum jump_label_type type, int init) { mutex_lock(&text_mutex); __jump_label_transform(entry, type, init); mutex_unlock(&text_mutex); } void arch_jump_label_transform(struct jump_entry *entry, enum jump_label_type type) { jump_label_transform(entry, type, 0); } bool arch_jump_label_transform_queue(struct jump_entry *entry, enum jump_label_type type) { struct jump_label_patch jlp; if (system_state == SYSTEM_BOOTING) { /* * Fallback to the non-batching mode. */ arch_jump_label_transform(entry, type); return true; } mutex_lock(&text_mutex); jlp = __jump_label_patch(entry, type); text_poke_queue((void *)jump_entry_code(entry), jlp.code, jlp.size, NULL); mutex_unlock(&text_mutex); return true; } void arch_jump_label_transform_apply(void) { mutex_lock(&text_mutex); text_poke_finish(); mutex_unlock(&text_mutex); }
linux-master
arch/x86/kernel/jump_label.c
// SPDX-License-Identifier: GPL-2.0-or-later /* KVM paravirtual clock driver. A clocksource implementation Copyright (C) 2008 Glauber de Oliveira Costa, Red Hat Inc. */ #include <linux/clocksource.h> #include <linux/kvm_para.h> #include <asm/pvclock.h> #include <asm/msr.h> #include <asm/apic.h> #include <linux/percpu.h> #include <linux/hardirq.h> #include <linux/cpuhotplug.h> #include <linux/sched.h> #include <linux/sched/clock.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/set_memory.h> #include <linux/cc_platform.h> #include <asm/hypervisor.h> #include <asm/x86_init.h> #include <asm/kvmclock.h> static int kvmclock __initdata = 1; static int kvmclock_vsyscall __initdata = 1; static int msr_kvm_system_time __ro_after_init = MSR_KVM_SYSTEM_TIME; static int msr_kvm_wall_clock __ro_after_init = MSR_KVM_WALL_CLOCK; static u64 kvm_sched_clock_offset __ro_after_init; static int __init parse_no_kvmclock(char *arg) { kvmclock = 0; return 0; } early_param("no-kvmclock", parse_no_kvmclock); static int __init parse_no_kvmclock_vsyscall(char *arg) { kvmclock_vsyscall = 0; return 0; } early_param("no-kvmclock-vsyscall", parse_no_kvmclock_vsyscall); /* Aligned to page sizes to match whats mapped via vsyscalls to userspace */ #define HVC_BOOT_ARRAY_SIZE \ (PAGE_SIZE / sizeof(struct pvclock_vsyscall_time_info)) static struct pvclock_vsyscall_time_info hv_clock_boot[HVC_BOOT_ARRAY_SIZE] __bss_decrypted __aligned(PAGE_SIZE); static struct pvclock_wall_clock wall_clock __bss_decrypted; static struct pvclock_vsyscall_time_info *hvclock_mem; DEFINE_PER_CPU(struct pvclock_vsyscall_time_info *, hv_clock_per_cpu); EXPORT_PER_CPU_SYMBOL_GPL(hv_clock_per_cpu); /* * The wallclock is the time of day when we booted. Since then, some time may * have elapsed since the hypervisor wrote the data. So we try to account for * that with system time */ static void kvm_get_wallclock(struct timespec64 *now) { wrmsrl(msr_kvm_wall_clock, slow_virt_to_phys(&wall_clock)); preempt_disable(); pvclock_read_wallclock(&wall_clock, this_cpu_pvti(), now); preempt_enable(); } static int kvm_set_wallclock(const struct timespec64 *now) { return -ENODEV; } static u64 kvm_clock_read(void) { u64 ret; preempt_disable_notrace(); ret = pvclock_clocksource_read_nowd(this_cpu_pvti()); preempt_enable_notrace(); return ret; } static u64 kvm_clock_get_cycles(struct clocksource *cs) { return kvm_clock_read(); } static noinstr u64 kvm_sched_clock_read(void) { return pvclock_clocksource_read_nowd(this_cpu_pvti()) - kvm_sched_clock_offset; } static inline void kvm_sched_clock_init(bool stable) { if (!stable) clear_sched_clock_stable(); kvm_sched_clock_offset = kvm_clock_read(); paravirt_set_sched_clock(kvm_sched_clock_read); pr_info("kvm-clock: using sched offset of %llu cycles", kvm_sched_clock_offset); BUILD_BUG_ON(sizeof(kvm_sched_clock_offset) > sizeof(((struct pvclock_vcpu_time_info *)NULL)->system_time)); } /* * If we don't do that, there is the possibility that the guest * will calibrate under heavy load - thus, getting a lower lpj - * and execute the delays themselves without load. This is wrong, * because no delay loop can finish beforehand. * Any heuristics is subject to fail, because ultimately, a large * poll of guests can be running and trouble each other. So we preset * lpj here */ static unsigned long kvm_get_tsc_khz(void) { setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ); return pvclock_tsc_khz(this_cpu_pvti()); } static void __init kvm_get_preset_lpj(void) { unsigned long khz; u64 lpj; khz = kvm_get_tsc_khz(); lpj = ((u64)khz * 1000); do_div(lpj, HZ); preset_lpj = lpj; } bool kvm_check_and_clear_guest_paused(void) { struct pvclock_vsyscall_time_info *src = this_cpu_hvclock(); bool ret = false; if (!src) return ret; if ((src->pvti.flags & PVCLOCK_GUEST_STOPPED) != 0) { src->pvti.flags &= ~PVCLOCK_GUEST_STOPPED; pvclock_touch_watchdogs(); ret = true; } return ret; } static int kvm_cs_enable(struct clocksource *cs) { vclocks_set_used(VDSO_CLOCKMODE_PVCLOCK); return 0; } struct clocksource kvm_clock = { .name = "kvm-clock", .read = kvm_clock_get_cycles, .rating = 400, .mask = CLOCKSOURCE_MASK(64), .flags = CLOCK_SOURCE_IS_CONTINUOUS, .enable = kvm_cs_enable, }; EXPORT_SYMBOL_GPL(kvm_clock); static void kvm_register_clock(char *txt) { struct pvclock_vsyscall_time_info *src = this_cpu_hvclock(); u64 pa; if (!src) return; pa = slow_virt_to_phys(&src->pvti) | 0x01ULL; wrmsrl(msr_kvm_system_time, pa); pr_debug("kvm-clock: cpu %d, msr %llx, %s", smp_processor_id(), pa, txt); } static void kvm_save_sched_clock_state(void) { } static void kvm_restore_sched_clock_state(void) { kvm_register_clock("primary cpu clock, resume"); } #ifdef CONFIG_X86_LOCAL_APIC static void kvm_setup_secondary_clock(void) { kvm_register_clock("secondary cpu clock"); } #endif void kvmclock_disable(void) { native_write_msr(msr_kvm_system_time, 0, 0); } static void __init kvmclock_init_mem(void) { unsigned long ncpus; unsigned int order; struct page *p; int r; if (HVC_BOOT_ARRAY_SIZE >= num_possible_cpus()) return; ncpus = num_possible_cpus() - HVC_BOOT_ARRAY_SIZE; order = get_order(ncpus * sizeof(*hvclock_mem)); p = alloc_pages(GFP_KERNEL, order); if (!p) { pr_warn("%s: failed to alloc %d pages", __func__, (1U << order)); return; } hvclock_mem = page_address(p); /* * hvclock is shared between the guest and the hypervisor, must * be mapped decrypted. */ if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) { r = set_memory_decrypted((unsigned long) hvclock_mem, 1UL << order); if (r) { __free_pages(p, order); hvclock_mem = NULL; pr_warn("kvmclock: set_memory_decrypted() failed. Disabling\n"); return; } } memset(hvclock_mem, 0, PAGE_SIZE << order); } static int __init kvm_setup_vsyscall_timeinfo(void) { if (!kvm_para_available() || !kvmclock || nopv) return 0; kvmclock_init_mem(); #ifdef CONFIG_X86_64 if (per_cpu(hv_clock_per_cpu, 0) && kvmclock_vsyscall) { u8 flags; flags = pvclock_read_flags(&hv_clock_boot[0].pvti); if (!(flags & PVCLOCK_TSC_STABLE_BIT)) return 0; kvm_clock.vdso_clock_mode = VDSO_CLOCKMODE_PVCLOCK; } #endif return 0; } early_initcall(kvm_setup_vsyscall_timeinfo); static int kvmclock_setup_percpu(unsigned int cpu) { struct pvclock_vsyscall_time_info *p = per_cpu(hv_clock_per_cpu, cpu); /* * The per cpu area setup replicates CPU0 data to all cpu * pointers. So carefully check. CPU0 has been set up in init * already. */ if (!cpu || (p && p != per_cpu(hv_clock_per_cpu, 0))) return 0; /* Use the static page for the first CPUs, allocate otherwise */ if (cpu < HVC_BOOT_ARRAY_SIZE) p = &hv_clock_boot[cpu]; else if (hvclock_mem) p = hvclock_mem + cpu - HVC_BOOT_ARRAY_SIZE; else return -ENOMEM; per_cpu(hv_clock_per_cpu, cpu) = p; return p ? 0 : -ENOMEM; } void __init kvmclock_init(void) { u8 flags; if (!kvm_para_available() || !kvmclock) return; if (kvm_para_has_feature(KVM_FEATURE_CLOCKSOURCE2)) { msr_kvm_system_time = MSR_KVM_SYSTEM_TIME_NEW; msr_kvm_wall_clock = MSR_KVM_WALL_CLOCK_NEW; } else if (!kvm_para_has_feature(KVM_FEATURE_CLOCKSOURCE)) { return; } if (cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "kvmclock:setup_percpu", kvmclock_setup_percpu, NULL) < 0) { return; } pr_info("kvm-clock: Using msrs %x and %x", msr_kvm_system_time, msr_kvm_wall_clock); this_cpu_write(hv_clock_per_cpu, &hv_clock_boot[0]); kvm_register_clock("primary cpu clock"); pvclock_set_pvti_cpu0_va(hv_clock_boot); if (kvm_para_has_feature(KVM_FEATURE_CLOCKSOURCE_STABLE_BIT)) pvclock_set_flags(PVCLOCK_TSC_STABLE_BIT); flags = pvclock_read_flags(&hv_clock_boot[0].pvti); kvm_sched_clock_init(flags & PVCLOCK_TSC_STABLE_BIT); x86_platform.calibrate_tsc = kvm_get_tsc_khz; x86_platform.calibrate_cpu = kvm_get_tsc_khz; x86_platform.get_wallclock = kvm_get_wallclock; x86_platform.set_wallclock = kvm_set_wallclock; #ifdef CONFIG_X86_LOCAL_APIC x86_cpuinit.early_percpu_clock_init = kvm_setup_secondary_clock; #endif x86_platform.save_sched_clock_state = kvm_save_sched_clock_state; x86_platform.restore_sched_clock_state = kvm_restore_sched_clock_state; kvm_get_preset_lpj(); /* * X86_FEATURE_NONSTOP_TSC is TSC runs at constant rate * with P/T states and does not stop in deep C-states. * * Invariant TSC exposed by host means kvmclock is not necessary: * can use TSC as clocksource. * */ if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC) && boot_cpu_has(X86_FEATURE_NONSTOP_TSC) && !check_tsc_unstable()) kvm_clock.rating = 299; clocksource_register_hz(&kvm_clock, NSEC_PER_SEC); pv_info.name = "KVM"; }
linux-master
arch/x86/kernel/kvmclock.c
// SPDX-License-Identifier: GPL-2.0-only /* * itmt.c: Support Intel Turbo Boost Max Technology 3.0 * * (C) Copyright 2016 Intel Corporation * Author: Tim Chen <[email protected]> * * On platforms supporting Intel Turbo Boost Max Technology 3.0, (ITMT), * the maximum turbo frequencies of some cores in a CPU package may be * higher than for the other cores in the same package. In that case, * better performance can be achieved by making the scheduler prefer * to run tasks on the CPUs with higher max turbo frequencies. * * This file provides functions and data structures for enabling the * scheduler to favor scheduling on cores can be boosted to a higher * frequency under ITMT. */ #include <linux/sched.h> #include <linux/cpumask.h> #include <linux/cpuset.h> #include <linux/mutex.h> #include <linux/sysctl.h> #include <linux/nodemask.h> static DEFINE_MUTEX(itmt_update_mutex); DEFINE_PER_CPU_READ_MOSTLY(int, sched_core_priority); /* Boolean to track if system has ITMT capabilities */ static bool __read_mostly sched_itmt_capable; /* * Boolean to control whether we want to move processes to cpu capable * of higher turbo frequency for cpus supporting Intel Turbo Boost Max * Technology 3.0. * * It can be set via /proc/sys/kernel/sched_itmt_enabled */ unsigned int __read_mostly sysctl_sched_itmt_enabled; static int sched_itmt_update_handler(struct ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { unsigned int old_sysctl; int ret; mutex_lock(&itmt_update_mutex); if (!sched_itmt_capable) { mutex_unlock(&itmt_update_mutex); return -EINVAL; } old_sysctl = sysctl_sched_itmt_enabled; ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (!ret && write && old_sysctl != sysctl_sched_itmt_enabled) { x86_topology_update = true; rebuild_sched_domains(); } mutex_unlock(&itmt_update_mutex); return ret; } static struct ctl_table itmt_kern_table[] = { { .procname = "sched_itmt_enabled", .data = &sysctl_sched_itmt_enabled, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = sched_itmt_update_handler, .extra1 = SYSCTL_ZERO, .extra2 = SYSCTL_ONE, }, {} }; static struct ctl_table_header *itmt_sysctl_header; /** * sched_set_itmt_support() - Indicate platform supports ITMT * * This function is used by the OS to indicate to scheduler that the platform * is capable of supporting the ITMT feature. * * The current scheme has the pstate driver detects if the system * is ITMT capable and call sched_set_itmt_support. * * This must be done only after sched_set_itmt_core_prio * has been called to set the cpus' priorities. * It must not be called with cpu hot plug lock * held as we need to acquire the lock to rebuild sched domains * later. * * Return: 0 on success */ int sched_set_itmt_support(void) { mutex_lock(&itmt_update_mutex); if (sched_itmt_capable) { mutex_unlock(&itmt_update_mutex); return 0; } itmt_sysctl_header = register_sysctl("kernel", itmt_kern_table); if (!itmt_sysctl_header) { mutex_unlock(&itmt_update_mutex); return -ENOMEM; } sched_itmt_capable = true; sysctl_sched_itmt_enabled = 1; x86_topology_update = true; rebuild_sched_domains(); mutex_unlock(&itmt_update_mutex); return 0; } /** * sched_clear_itmt_support() - Revoke platform's support of ITMT * * This function is used by the OS to indicate that it has * revoked the platform's support of ITMT feature. * * It must not be called with cpu hot plug lock * held as we need to acquire the lock to rebuild sched domains * later. */ void sched_clear_itmt_support(void) { mutex_lock(&itmt_update_mutex); if (!sched_itmt_capable) { mutex_unlock(&itmt_update_mutex); return; } sched_itmt_capable = false; if (itmt_sysctl_header) { unregister_sysctl_table(itmt_sysctl_header); itmt_sysctl_header = NULL; } if (sysctl_sched_itmt_enabled) { /* disable sched_itmt if we are no longer ITMT capable */ sysctl_sched_itmt_enabled = 0; x86_topology_update = true; rebuild_sched_domains(); } mutex_unlock(&itmt_update_mutex); } int arch_asym_cpu_priority(int cpu) { return per_cpu(sched_core_priority, cpu); } /** * sched_set_itmt_core_prio() - Set CPU priority based on ITMT * @prio: Priority of @cpu * @cpu: The CPU number * * The pstate driver will find out the max boost frequency * and call this function to set a priority proportional * to the max boost frequency. CPUs with higher boost * frequency will receive higher priority. * * No need to rebuild sched domain after updating * the CPU priorities. The sched domains have no * dependency on CPU priorities. */ void sched_set_itmt_core_prio(int prio, int cpu) { per_cpu(sched_core_priority, cpu) = prio; }
linux-master
arch/x86/kernel/itmt.c
// SPDX-License-Identifier: GPL-2.0 /* * x86 specific code for irq_work * * Copyright (C) 2010 Red Hat, Inc., Peter Zijlstra */ #include <linux/kernel.h> #include <linux/irq_work.h> #include <linux/hardirq.h> #include <asm/apic.h> #include <asm/idtentry.h> #include <asm/trace/irq_vectors.h> #include <linux/interrupt.h> #ifdef CONFIG_X86_LOCAL_APIC DEFINE_IDTENTRY_SYSVEC(sysvec_irq_work) { apic_eoi(); trace_irq_work_entry(IRQ_WORK_VECTOR); inc_irq_stat(apic_irq_work_irqs); irq_work_run(); trace_irq_work_exit(IRQ_WORK_VECTOR); } void arch_irq_work_raise(void) { if (!arch_irq_work_has_interrupt()) return; __apic_send_IPI_self(IRQ_WORK_VECTOR); apic_wait_icr_idle(); } #endif
linux-master
arch/x86/kernel/irq_work.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/sched.h> #include <linux/mm.h> #include <linux/uaccess.h> #include <linux/mmzone.h> #include <linux/ioport.h> #include <linux/seq_file.h> #include <linux/console.h> #include <linux/init.h> #include <linux/edd.h> #include <linux/dmi.h> #include <linux/pfn.h> #include <linux/pci.h> #include <linux/export.h> #include <asm/probe_roms.h> #include <asm/pci-direct.h> #include <asm/e820/api.h> #include <asm/mmzone.h> #include <asm/setup.h> #include <asm/sections.h> #include <asm/io.h> #include <asm/setup_arch.h> #include <asm/sev.h> static struct resource system_rom_resource = { .name = "System ROM", .start = 0xf0000, .end = 0xfffff, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }; static struct resource extension_rom_resource = { .name = "Extension ROM", .start = 0xe0000, .end = 0xeffff, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }; static struct resource adapter_rom_resources[] = { { .name = "Adapter ROM", .start = 0xc8000, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM } }; static struct resource video_rom_resource = { .name = "Video ROM", .start = 0xc0000, .end = 0xc7fff, .flags = IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM }; /* does this oprom support the given pci device, or any of the devices * that the driver supports? */ static bool match_id(struct pci_dev *pdev, unsigned short vendor, unsigned short device) { struct pci_driver *drv = to_pci_driver(pdev->dev.driver); const struct pci_device_id *id; if (pdev->vendor == vendor && pdev->device == device) return true; for (id = drv ? drv->id_table : NULL; id && id->vendor; id++) if (id->vendor == vendor && id->device == device) break; return id && id->vendor; } static bool probe_list(struct pci_dev *pdev, unsigned short vendor, const void *rom_list) { unsigned short device; do { if (get_kernel_nofault(device, rom_list) != 0) device = 0; if (device && match_id(pdev, vendor, device)) break; rom_list += 2; } while (device); return !!device; } static struct resource *find_oprom(struct pci_dev *pdev) { struct resource *oprom = NULL; int i; for (i = 0; i < ARRAY_SIZE(adapter_rom_resources); i++) { struct resource *res = &adapter_rom_resources[i]; unsigned short offset, vendor, device, list, rev; const void *rom; if (res->end == 0) break; rom = isa_bus_to_virt(res->start); if (get_kernel_nofault(offset, rom + 0x18) != 0) continue; if (get_kernel_nofault(vendor, rom + offset + 0x4) != 0) continue; if (get_kernel_nofault(device, rom + offset + 0x6) != 0) continue; if (match_id(pdev, vendor, device)) { oprom = res; break; } if (get_kernel_nofault(list, rom + offset + 0x8) == 0 && get_kernel_nofault(rev, rom + offset + 0xc) == 0 && rev >= 3 && list && probe_list(pdev, vendor, rom + offset + list)) { oprom = res; break; } } return oprom; } void __iomem *pci_map_biosrom(struct pci_dev *pdev) { struct resource *oprom = find_oprom(pdev); if (!oprom) return NULL; return ioremap(oprom->start, resource_size(oprom)); } EXPORT_SYMBOL(pci_map_biosrom); void pci_unmap_biosrom(void __iomem *image) { iounmap(image); } EXPORT_SYMBOL(pci_unmap_biosrom); size_t pci_biosrom_size(struct pci_dev *pdev) { struct resource *oprom = find_oprom(pdev); return oprom ? resource_size(oprom) : 0; } EXPORT_SYMBOL(pci_biosrom_size); #define ROMSIGNATURE 0xaa55 static int __init romsignature(const unsigned char *rom) { const unsigned short * const ptr = (const unsigned short *)rom; unsigned short sig; return get_kernel_nofault(sig, ptr) == 0 && sig == ROMSIGNATURE; } static int __init romchecksum(const unsigned char *rom, unsigned long length) { unsigned char sum, c; for (sum = 0; length && get_kernel_nofault(c, rom++) == 0; length--) sum += c; return !length && !sum; } void __init probe_roms(void) { unsigned long start, length, upper; const unsigned char *rom; unsigned char c; int i; /* * The ROM memory range is not part of the e820 table and is therefore not * pre-validated by BIOS. The kernel page table maps the ROM region as encrypted * memory, and SNP requires encrypted memory to be validated before access. * Do that here. */ snp_prep_memory(video_rom_resource.start, ((system_rom_resource.end + 1) - video_rom_resource.start), SNP_PAGE_STATE_PRIVATE); /* video rom */ upper = adapter_rom_resources[0].start; for (start = video_rom_resource.start; start < upper; start += 2048) { rom = isa_bus_to_virt(start); if (!romsignature(rom)) continue; video_rom_resource.start = start; if (get_kernel_nofault(c, rom + 2) != 0) continue; /* 0 < length <= 0x7f * 512, historically */ length = c * 512; /* if checksum okay, trust length byte */ if (length && romchecksum(rom, length)) video_rom_resource.end = start + length - 1; request_resource(&iomem_resource, &video_rom_resource); break; } start = (video_rom_resource.end + 1 + 2047) & ~2047UL; if (start < upper) start = upper; /* system rom */ request_resource(&iomem_resource, &system_rom_resource); upper = system_rom_resource.start; /* check for extension rom (ignore length byte!) */ rom = isa_bus_to_virt(extension_rom_resource.start); if (romsignature(rom)) { length = resource_size(&extension_rom_resource); if (romchecksum(rom, length)) { request_resource(&iomem_resource, &extension_rom_resource); upper = extension_rom_resource.start; } } /* check for adapter roms on 2k boundaries */ for (i = 0; i < ARRAY_SIZE(adapter_rom_resources) && start < upper; start += 2048) { rom = isa_bus_to_virt(start); if (!romsignature(rom)) continue; if (get_kernel_nofault(c, rom + 2) != 0) continue; /* 0 < length <= 0x7f * 512, historically */ length = c * 512; /* but accept any length that fits if checksum okay */ if (!length || start + length > upper || !romchecksum(rom, length)) continue; adapter_rom_resources[i].start = start; adapter_rom_resources[i].end = start + length - 1; request_resource(&iomem_resource, &adapter_rom_resources[i]); start = adapter_rom_resources[i++].end & ~2047UL; } }
linux-master
arch/x86/kernel/probe_roms.c
// SPDX-License-Identifier: GPL-2.0-only /* * tboot.c: main implementation of helper functions used by kernel for * runtime support of Intel(R) Trusted Execution Technology * * Copyright (c) 2006-2009, Intel Corporation */ #include <linux/init_task.h> #include <linux/spinlock.h> #include <linux/export.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/init.h> #include <linux/dmar.h> #include <linux/cpu.h> #include <linux/pfn.h> #include <linux/mm.h> #include <linux/tboot.h> #include <linux/debugfs.h> #include <asm/realmode.h> #include <asm/processor.h> #include <asm/bootparam.h> #include <asm/pgalloc.h> #include <asm/fixmap.h> #include <asm/proto.h> #include <asm/setup.h> #include <asm/e820/api.h> #include <asm/io.h> #include "../realmode/rm/wakeup.h" /* Global pointer to shared data; NULL means no measured launch. */ static struct tboot *tboot __read_mostly; /* timeout for APs (in secs) to enter wait-for-SIPI state during shutdown */ #define AP_WAIT_TIMEOUT 1 #undef pr_fmt #define pr_fmt(fmt) "tboot: " fmt static u8 tboot_uuid[16] __initdata = TBOOT_UUID; bool tboot_enabled(void) { return tboot != NULL; } /* noinline to prevent gcc from warning about dereferencing constant fixaddr */ static noinline __init bool check_tboot_version(void) { if (memcmp(&tboot_uuid, &tboot->uuid, sizeof(tboot->uuid))) { pr_warn("tboot at 0x%llx is invalid\n", boot_params.tboot_addr); return false; } if (tboot->version < 5) { pr_warn("tboot version is invalid: %u\n", tboot->version); return false; } pr_info("found shared page at phys addr 0x%llx:\n", boot_params.tboot_addr); pr_debug("version: %d\n", tboot->version); pr_debug("log_addr: 0x%08x\n", tboot->log_addr); pr_debug("shutdown_entry: 0x%x\n", tboot->shutdown_entry); pr_debug("tboot_base: 0x%08x\n", tboot->tboot_base); pr_debug("tboot_size: 0x%x\n", tboot->tboot_size); return true; } void __init tboot_probe(void) { /* Look for valid page-aligned address for shared page. */ if (!boot_params.tboot_addr) return; /* * also verify that it is mapped as we expect it before calling * set_fixmap(), to reduce chance of garbage value causing crash */ if (!e820__mapped_any(boot_params.tboot_addr, boot_params.tboot_addr, E820_TYPE_RESERVED)) { pr_warn("non-0 tboot_addr but it is not of type E820_TYPE_RESERVED\n"); return; } /* Map and check for tboot UUID. */ set_fixmap(FIX_TBOOT_BASE, boot_params.tboot_addr); tboot = (void *)fix_to_virt(FIX_TBOOT_BASE); if (!check_tboot_version()) tboot = NULL; } static pgd_t *tboot_pg_dir; static struct mm_struct tboot_mm = { .mm_mt = MTREE_INIT_EXT(mm_mt, MM_MT_FLAGS, tboot_mm.mmap_lock), .pgd = swapper_pg_dir, .mm_users = ATOMIC_INIT(2), .mm_count = ATOMIC_INIT(1), .write_protect_seq = SEQCNT_ZERO(tboot_mm.write_protect_seq), MMAP_LOCK_INITIALIZER(init_mm) .page_table_lock = __SPIN_LOCK_UNLOCKED(init_mm.page_table_lock), .mmlist = LIST_HEAD_INIT(init_mm.mmlist), }; static inline void switch_to_tboot_pt(void) { write_cr3(virt_to_phys(tboot_pg_dir)); } static int map_tboot_page(unsigned long vaddr, unsigned long pfn, pgprot_t prot) { pgd_t *pgd; p4d_t *p4d; pud_t *pud; pmd_t *pmd; pte_t *pte; pgd = pgd_offset(&tboot_mm, vaddr); p4d = p4d_alloc(&tboot_mm, pgd, vaddr); if (!p4d) return -1; pud = pud_alloc(&tboot_mm, p4d, vaddr); if (!pud) return -1; pmd = pmd_alloc(&tboot_mm, pud, vaddr); if (!pmd) return -1; pte = pte_alloc_map(&tboot_mm, pmd, vaddr); if (!pte) return -1; set_pte_at(&tboot_mm, vaddr, pte, pfn_pte(pfn, prot)); pte_unmap(pte); /* * PTI poisons low addresses in the kernel page tables in the * name of making them unusable for userspace. To execute * code at such a low address, the poison must be cleared. * * Note: 'pgd' actually gets set in p4d_alloc() _or_ * pud_alloc() depending on 4/5-level paging. */ pgd->pgd &= ~_PAGE_NX; return 0; } static int map_tboot_pages(unsigned long vaddr, unsigned long start_pfn, unsigned long nr) { /* Reuse the original kernel mapping */ tboot_pg_dir = pgd_alloc(&tboot_mm); if (!tboot_pg_dir) return -1; for (; nr > 0; nr--, vaddr += PAGE_SIZE, start_pfn++) { if (map_tboot_page(vaddr, start_pfn, PAGE_KERNEL_EXEC)) return -1; } return 0; } static void tboot_create_trampoline(void) { u32 map_base, map_size; /* Create identity map for tboot shutdown code. */ map_base = PFN_DOWN(tboot->tboot_base); map_size = PFN_UP(tboot->tboot_size); if (map_tboot_pages(map_base << PAGE_SHIFT, map_base, map_size)) panic("tboot: Error mapping tboot pages (mfns) @ 0x%x, 0x%x\n", map_base, map_size); } #ifdef CONFIG_ACPI_SLEEP static void add_mac_region(phys_addr_t start, unsigned long size) { struct tboot_mac_region *mr; phys_addr_t end = start + size; if (tboot->num_mac_regions >= MAX_TB_MAC_REGIONS) panic("tboot: Too many MAC regions\n"); if (start && size) { mr = &tboot->mac_regions[tboot->num_mac_regions++]; mr->start = round_down(start, PAGE_SIZE); mr->size = round_up(end, PAGE_SIZE) - mr->start; } } static int tboot_setup_sleep(void) { int i; tboot->num_mac_regions = 0; for (i = 0; i < e820_table->nr_entries; i++) { if ((e820_table->entries[i].type != E820_TYPE_RAM) && (e820_table->entries[i].type != E820_TYPE_RESERVED_KERN)) continue; add_mac_region(e820_table->entries[i].addr, e820_table->entries[i].size); } tboot->acpi_sinfo.kernel_s3_resume_vector = real_mode_header->wakeup_start; return 0; } #else /* no CONFIG_ACPI_SLEEP */ static int tboot_setup_sleep(void) { /* S3 shutdown requested, but S3 not supported by the kernel... */ BUG(); return -1; } #endif void tboot_shutdown(u32 shutdown_type) { void (*shutdown)(void); if (!tboot_enabled()) return; /* * if we're being called before the 1:1 mapping is set up then just * return and let the normal shutdown happen; this should only be * due to very early panic() */ if (!tboot_pg_dir) return; /* if this is S3 then set regions to MAC */ if (shutdown_type == TB_SHUTDOWN_S3) if (tboot_setup_sleep()) return; tboot->shutdown_type = shutdown_type; switch_to_tboot_pt(); shutdown = (void(*)(void))(unsigned long)tboot->shutdown_entry; shutdown(); /* should not reach here */ while (1) halt(); } static void tboot_copy_fadt(const struct acpi_table_fadt *fadt) { #define TB_COPY_GAS(tbg, g) \ tbg.space_id = g.space_id; \ tbg.bit_width = g.bit_width; \ tbg.bit_offset = g.bit_offset; \ tbg.access_width = g.access_width; \ tbg.address = g.address; TB_COPY_GAS(tboot->acpi_sinfo.pm1a_cnt_blk, fadt->xpm1a_control_block); TB_COPY_GAS(tboot->acpi_sinfo.pm1b_cnt_blk, fadt->xpm1b_control_block); TB_COPY_GAS(tboot->acpi_sinfo.pm1a_evt_blk, fadt->xpm1a_event_block); TB_COPY_GAS(tboot->acpi_sinfo.pm1b_evt_blk, fadt->xpm1b_event_block); /* * We need phys addr of waking vector, but can't use virt_to_phys() on * &acpi_gbl_FACS because it is ioremap'ed, so calc from FACS phys * addr. */ tboot->acpi_sinfo.wakeup_vector = fadt->facs + offsetof(struct acpi_table_facs, firmware_waking_vector); } static int tboot_sleep(u8 sleep_state, u32 pm1a_control, u32 pm1b_control) { static u32 acpi_shutdown_map[ACPI_S_STATE_COUNT] = { /* S0,1,2: */ -1, -1, -1, /* S3: */ TB_SHUTDOWN_S3, /* S4: */ TB_SHUTDOWN_S4, /* S5: */ TB_SHUTDOWN_S5 }; if (!tboot_enabled()) return 0; tboot_copy_fadt(&acpi_gbl_FADT); tboot->acpi_sinfo.pm1a_cnt_val = pm1a_control; tboot->acpi_sinfo.pm1b_cnt_val = pm1b_control; /* we always use the 32b wakeup vector */ tboot->acpi_sinfo.vector_width = 32; if (sleep_state >= ACPI_S_STATE_COUNT || acpi_shutdown_map[sleep_state] == -1) { pr_warn("unsupported sleep state 0x%x\n", sleep_state); return -1; } tboot_shutdown(acpi_shutdown_map[sleep_state]); return 0; } static int tboot_extended_sleep(u8 sleep_state, u32 val_a, u32 val_b) { if (!tboot_enabled()) return 0; pr_warn("tboot is not able to suspend on platforms with reduced hardware sleep (ACPIv5)"); return -ENODEV; } static atomic_t ap_wfs_count; static int tboot_wait_for_aps(int num_aps) { unsigned long timeout; timeout = AP_WAIT_TIMEOUT*HZ; while (atomic_read((atomic_t *)&tboot->num_in_wfs) != num_aps && timeout) { mdelay(1); timeout--; } if (timeout) pr_warn("tboot wait for APs timeout\n"); return !(atomic_read((atomic_t *)&tboot->num_in_wfs) == num_aps); } static int tboot_dying_cpu(unsigned int cpu) { atomic_inc(&ap_wfs_count); if (num_online_cpus() == 1) { if (tboot_wait_for_aps(atomic_read(&ap_wfs_count))) return -EBUSY; } return 0; } #ifdef CONFIG_DEBUG_FS #define TBOOT_LOG_UUID { 0x26, 0x25, 0x19, 0xc0, 0x30, 0x6b, 0xb4, 0x4d, \ 0x4c, 0x84, 0xa3, 0xe9, 0x53, 0xb8, 0x81, 0x74 } #define TBOOT_SERIAL_LOG_ADDR 0x60000 #define TBOOT_SERIAL_LOG_SIZE 0x08000 #define LOG_MAX_SIZE_OFF 16 #define LOG_BUF_OFF 24 static uint8_t tboot_log_uuid[16] = TBOOT_LOG_UUID; static ssize_t tboot_log_read(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { void __iomem *log_base; u8 log_uuid[16]; u32 max_size; void *kbuf; int ret = -EFAULT; log_base = ioremap(TBOOT_SERIAL_LOG_ADDR, TBOOT_SERIAL_LOG_SIZE); if (!log_base) return ret; memcpy_fromio(log_uuid, log_base, sizeof(log_uuid)); if (memcmp(&tboot_log_uuid, log_uuid, sizeof(log_uuid))) goto err_iounmap; max_size = readl(log_base + LOG_MAX_SIZE_OFF); if (*ppos >= max_size) { ret = 0; goto err_iounmap; } if (*ppos + count > max_size) count = max_size - *ppos; kbuf = kmalloc(count, GFP_KERNEL); if (!kbuf) { ret = -ENOMEM; goto err_iounmap; } memcpy_fromio(kbuf, log_base + LOG_BUF_OFF + *ppos, count); if (copy_to_user(user_buf, kbuf, count)) goto err_kfree; *ppos += count; ret = count; err_kfree: kfree(kbuf); err_iounmap: iounmap(log_base); return ret; } static const struct file_operations tboot_log_fops = { .read = tboot_log_read, .llseek = default_llseek, }; #endif /* CONFIG_DEBUG_FS */ static __init int tboot_late_init(void) { if (!tboot_enabled()) return 0; tboot_create_trampoline(); atomic_set(&ap_wfs_count, 0); cpuhp_setup_state(CPUHP_AP_X86_TBOOT_DYING, "x86/tboot:dying", NULL, tboot_dying_cpu); #ifdef CONFIG_DEBUG_FS debugfs_create_file("tboot_log", S_IRUSR, arch_debugfs_dir, NULL, &tboot_log_fops); #endif acpi_os_set_prepare_sleep(&tboot_sleep); acpi_os_set_prepare_extended_sleep(&tboot_extended_sleep); return 0; } late_initcall(tboot_late_init); /* * TXT configuration registers (offsets from TXT_{PUB, PRIV}_CONFIG_REGS_BASE) */ #define TXT_PUB_CONFIG_REGS_BASE 0xfed30000 #define TXT_PRIV_CONFIG_REGS_BASE 0xfed20000 /* # pages for each config regs space - used by fixmap */ #define NR_TXT_CONFIG_PAGES ((TXT_PUB_CONFIG_REGS_BASE - \ TXT_PRIV_CONFIG_REGS_BASE) >> PAGE_SHIFT) /* offsets from pub/priv config space */ #define TXTCR_HEAP_BASE 0x0300 #define TXTCR_HEAP_SIZE 0x0308 #define SHA1_SIZE 20 struct sha1_hash { u8 hash[SHA1_SIZE]; }; struct sinit_mle_data { u32 version; /* currently 6 */ struct sha1_hash bios_acm_id; u32 edx_senter_flags; u64 mseg_valid; struct sha1_hash sinit_hash; struct sha1_hash mle_hash; struct sha1_hash stm_hash; struct sha1_hash lcp_policy_hash; u32 lcp_policy_control; u32 rlp_wakeup_addr; u32 reserved; u32 num_mdrs; u32 mdrs_off; u32 num_vtd_dmars; u32 vtd_dmars_off; } __packed; struct acpi_table_header *tboot_get_dmar_table(struct acpi_table_header *dmar_tbl) { void *heap_base, *heap_ptr, *config; if (!tboot_enabled()) return dmar_tbl; /* * ACPI tables may not be DMA protected by tboot, so use DMAR copy * SINIT saved in SinitMleData in TXT heap (which is DMA protected) */ /* map config space in order to get heap addr */ config = ioremap(TXT_PUB_CONFIG_REGS_BASE, NR_TXT_CONFIG_PAGES * PAGE_SIZE); if (!config) return NULL; /* now map TXT heap */ heap_base = ioremap(*(u64 *)(config + TXTCR_HEAP_BASE), *(u64 *)(config + TXTCR_HEAP_SIZE)); iounmap(config); if (!heap_base) return NULL; /* walk heap to SinitMleData */ /* skip BiosData */ heap_ptr = heap_base + *(u64 *)heap_base; /* skip OsMleData */ heap_ptr += *(u64 *)heap_ptr; /* skip OsSinitData */ heap_ptr += *(u64 *)heap_ptr; /* now points to SinitMleDataSize; set to SinitMleData */ heap_ptr += sizeof(u64); /* get addr of DMAR table */ dmar_tbl = (struct acpi_table_header *)(heap_ptr + ((struct sinit_mle_data *)heap_ptr)->vtd_dmars_off - sizeof(u64)); /* don't unmap heap because dmar.c needs access to this */ return dmar_tbl; }
linux-master
arch/x86/kernel/tboot.c
// SPDX-License-Identifier: GPL-2.0 /* * Jailhouse paravirt_ops implementation * * Copyright (c) Siemens AG, 2015-2017 * * Authors: * Jan Kiszka <[email protected]> */ #include <linux/acpi_pmtmr.h> #include <linux/kernel.h> #include <linux/reboot.h> #include <linux/serial_8250.h> #include <asm/apic.h> #include <asm/io_apic.h> #include <asm/acpi.h> #include <asm/cpu.h> #include <asm/hypervisor.h> #include <asm/i8259.h> #include <asm/irqdomain.h> #include <asm/pci_x86.h> #include <asm/reboot.h> #include <asm/setup.h> #include <asm/jailhouse_para.h> static struct jailhouse_setup_data setup_data; #define SETUP_DATA_V1_LEN (sizeof(setup_data.hdr) + sizeof(setup_data.v1)) #define SETUP_DATA_V2_LEN (SETUP_DATA_V1_LEN + sizeof(setup_data.v2)) static unsigned int precalibrated_tsc_khz; static void jailhouse_setup_irq(unsigned int irq) { struct mpc_intsrc mp_irq = { .type = MP_INTSRC, .irqtype = mp_INT, .irqflag = MP_IRQPOL_ACTIVE_HIGH | MP_IRQTRIG_EDGE, .srcbusirq = irq, .dstirq = irq, }; mp_save_irq(&mp_irq); } static uint32_t jailhouse_cpuid_base(void) { if (boot_cpu_data.cpuid_level < 0 || !boot_cpu_has(X86_FEATURE_HYPERVISOR)) return 0; return hypervisor_cpuid_base("Jailhouse\0\0\0", 0); } static uint32_t __init jailhouse_detect(void) { return jailhouse_cpuid_base(); } static void jailhouse_get_wallclock(struct timespec64 *now) { memset(now, 0, sizeof(*now)); } static void __init jailhouse_timer_init(void) { lapic_timer_period = setup_data.v1.apic_khz * (1000 / HZ); } static unsigned long jailhouse_get_tsc(void) { return precalibrated_tsc_khz; } static void __init jailhouse_x2apic_init(void) { #ifdef CONFIG_X86_X2APIC if (!x2apic_enabled()) return; /* * We do not have access to IR inside Jailhouse non-root cells. So * we have to run in physical mode. */ x2apic_phys = 1; /* * This will trigger the switch to apic_x2apic_phys. Empty OEM IDs * ensure that only this APIC driver picks up the call. */ default_acpi_madt_oem_check("", ""); #endif } static void __init jailhouse_get_smp_config(unsigned int early) { struct ioapic_domain_cfg ioapic_cfg = { .type = IOAPIC_DOMAIN_STRICT, .ops = &mp_ioapic_irqdomain_ops, }; unsigned int cpu; jailhouse_x2apic_init(); register_lapic_address(0xfee00000); for (cpu = 0; cpu < setup_data.v1.num_cpus; cpu++) generic_processor_info(setup_data.v1.cpu_ids[cpu]); smp_found_config = 1; if (setup_data.v1.standard_ioapic) { mp_register_ioapic(0, 0xfec00000, gsi_top, &ioapic_cfg); if (IS_ENABLED(CONFIG_SERIAL_8250) && setup_data.hdr.version < 2) { /* Register 1:1 mapping for legacy UART IRQs 3 and 4 */ jailhouse_setup_irq(3); jailhouse_setup_irq(4); } } } static void jailhouse_no_restart(void) { pr_notice("Jailhouse: Restart not supported, halting\n"); machine_halt(); } static int __init jailhouse_pci_arch_init(void) { pci_direct_init(1); /* * There are no bridges on the virtual PCI root bus under Jailhouse, * thus no other way to discover all devices than a full scan. * Respect any overrides via the command line, though. */ if (pcibios_last_bus < 0) pcibios_last_bus = 0xff; #ifdef CONFIG_PCI_MMCONFIG if (setup_data.v1.pci_mmconfig_base) { pci_mmconfig_add(0, 0, pcibios_last_bus, setup_data.v1.pci_mmconfig_base); pci_mmcfg_arch_init(); } #endif return 0; } #ifdef CONFIG_SERIAL_8250 static inline bool jailhouse_uart_enabled(unsigned int uart_nr) { return setup_data.v2.flags & BIT(uart_nr); } static void jailhouse_serial_fixup(int port, struct uart_port *up, u32 *capabilities) { static const u16 pcuart_base[] = {0x3f8, 0x2f8, 0x3e8, 0x2e8}; unsigned int n; for (n = 0; n < ARRAY_SIZE(pcuart_base); n++) { if (pcuart_base[n] != up->iobase) continue; if (jailhouse_uart_enabled(n)) { pr_info("Enabling UART%u (port 0x%lx)\n", n, up->iobase); jailhouse_setup_irq(up->irq); } else { /* Deactivate UART if access isn't allowed */ up->iobase = 0; } break; } } static void __init jailhouse_serial_workaround(void) { /* * There are flags inside setup_data that indicate availability of * platform UARTs since setup data version 2. * * In case of version 1, we don't know which UARTs belong Linux. In * this case, unconditionally register 1:1 mapping for legacy UART IRQs * 3 and 4. */ if (setup_data.hdr.version > 1) serial8250_set_isa_configurator(jailhouse_serial_fixup); } #else /* !CONFIG_SERIAL_8250 */ static inline void jailhouse_serial_workaround(void) { } #endif /* CONFIG_SERIAL_8250 */ static void __init jailhouse_init_platform(void) { u64 pa_data = boot_params.hdr.setup_data; unsigned long setup_data_len; struct setup_data header; void *mapping; x86_init.irqs.pre_vector_init = x86_init_noop; x86_init.timers.timer_init = jailhouse_timer_init; x86_init.mpparse.get_smp_config = jailhouse_get_smp_config; x86_init.pci.arch_init = jailhouse_pci_arch_init; x86_platform.calibrate_cpu = jailhouse_get_tsc; x86_platform.calibrate_tsc = jailhouse_get_tsc; x86_platform.get_wallclock = jailhouse_get_wallclock; x86_platform.legacy.rtc = 0; x86_platform.legacy.warm_reset = 0; x86_platform.legacy.i8042 = X86_LEGACY_I8042_PLATFORM_ABSENT; legacy_pic = &null_legacy_pic; machine_ops.emergency_restart = jailhouse_no_restart; while (pa_data) { mapping = early_memremap(pa_data, sizeof(header)); memcpy(&header, mapping, sizeof(header)); early_memunmap(mapping, sizeof(header)); if (header.type == SETUP_JAILHOUSE) break; pa_data = header.next; } if (!pa_data) panic("Jailhouse: No valid setup data found"); /* setup data must at least contain the header */ if (header.len < sizeof(setup_data.hdr)) goto unsupported; pa_data += offsetof(struct setup_data, data); setup_data_len = min_t(unsigned long, sizeof(setup_data), (unsigned long)header.len); mapping = early_memremap(pa_data, setup_data_len); memcpy(&setup_data, mapping, setup_data_len); early_memunmap(mapping, setup_data_len); if (setup_data.hdr.version == 0 || setup_data.hdr.compatible_version != JAILHOUSE_SETUP_REQUIRED_VERSION || (setup_data.hdr.version == 1 && header.len < SETUP_DATA_V1_LEN) || (setup_data.hdr.version >= 2 && header.len < SETUP_DATA_V2_LEN)) goto unsupported; pmtmr_ioport = setup_data.v1.pm_timer_address; pr_debug("Jailhouse: PM-Timer IO Port: %#x\n", pmtmr_ioport); precalibrated_tsc_khz = setup_data.v1.tsc_khz; setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ); pci_probe = 0; /* * Avoid that the kernel complains about missing ACPI tables - there * are none in a non-root cell. */ disable_acpi(); jailhouse_serial_workaround(); return; unsupported: panic("Jailhouse: Unsupported setup data structure"); } bool jailhouse_paravirt(void) { return jailhouse_cpuid_base() != 0; } static bool __init jailhouse_x2apic_available(void) { /* * The x2APIC is only available if the root cell enabled it. Jailhouse * does not support switching between xAPIC and x2APIC. */ return x2apic_enabled(); } const struct hypervisor_x86 x86_hyper_jailhouse __refconst = { .name = "Jailhouse", .detect = jailhouse_detect, .init.init_platform = jailhouse_init_platform, .init.x2apic_available = jailhouse_x2apic_available, .ignore_nopv = true, };
linux-master
arch/x86/kernel/jailhouse.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * User-space Probes (UProbes) for x86 * * Copyright (C) IBM Corporation, 2008-2011 * Authors: * Srikar Dronamraju * Jim Keniston */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/ptrace.h> #include <linux/uprobes.h> #include <linux/uaccess.h> #include <linux/kdebug.h> #include <asm/processor.h> #include <asm/insn.h> #include <asm/mmu_context.h> /* Post-execution fixups. */ /* Adjust IP back to vicinity of actual insn */ #define UPROBE_FIX_IP 0x01 /* Adjust the return address of a call insn */ #define UPROBE_FIX_CALL 0x02 /* Instruction will modify TF, don't change it */ #define UPROBE_FIX_SETF 0x04 #define UPROBE_FIX_RIP_SI 0x08 #define UPROBE_FIX_RIP_DI 0x10 #define UPROBE_FIX_RIP_BX 0x20 #define UPROBE_FIX_RIP_MASK \ (UPROBE_FIX_RIP_SI | UPROBE_FIX_RIP_DI | UPROBE_FIX_RIP_BX) #define UPROBE_TRAP_NR UINT_MAX /* Adaptations for mhiramat x86 decoder v14. */ #define OPCODE1(insn) ((insn)->opcode.bytes[0]) #define OPCODE2(insn) ((insn)->opcode.bytes[1]) #define OPCODE3(insn) ((insn)->opcode.bytes[2]) #define MODRM_REG(insn) X86_MODRM_REG((insn)->modrm.value) #define W(row, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf)\ (((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) | \ (b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) | \ (b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) | \ (bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf)) \ << (row % 32)) /* * Good-instruction tables for 32-bit apps. This is non-const and volatile * to keep gcc from statically optimizing it out, as variable_test_bit makes * some versions of gcc to think only *(unsigned long*) is used. * * Opcodes we'll probably never support: * 6c-6f - ins,outs. SEGVs if used in userspace * e4-e7 - in,out imm. SEGVs if used in userspace * ec-ef - in,out acc. SEGVs if used in userspace * cc - int3. SIGTRAP if used in userspace * ce - into. Not used in userspace - no kernel support to make it useful. SEGVs * (why we support bound (62) then? it's similar, and similarly unused...) * f1 - int1. SIGTRAP if used in userspace * f4 - hlt. SEGVs if used in userspace * fa - cli. SEGVs if used in userspace * fb - sti. SEGVs if used in userspace * * Opcodes which need some work to be supported: * 07,17,1f - pop es/ss/ds * Normally not used in userspace, but would execute if used. * Can cause GP or stack exception if tries to load wrong segment descriptor. * We hesitate to run them under single step since kernel's handling * of userspace single-stepping (TF flag) is fragile. * We can easily refuse to support push es/cs/ss/ds (06/0e/16/1e) * on the same grounds that they are never used. * cd - int N. * Used by userspace for "int 80" syscall entry. (Other "int N" * cause GP -> SEGV since their IDT gates don't allow calls from CPL 3). * Not supported since kernel's handling of userspace single-stepping * (TF flag) is fragile. * cf - iret. Normally not used in userspace. Doesn't SEGV unless arguments are bad */ #if defined(CONFIG_X86_32) || defined(CONFIG_IA32_EMULATION) static volatile u32 good_insns_32[256 / 32] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ /* ---------------------------------------------- */ W(0x00, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1) | /* 00 */ W(0x10, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0) , /* 10 */ W(0x20, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 20 */ W(0x30, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 30 */ W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 40 */ W(0x50, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 50 */ W(0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0) | /* 60 */ W(0x70, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 70 */ W(0x80, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 80 */ W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 90 */ W(0xa0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* a0 */ W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* b0 */ W(0xc0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0) | /* c0 */ W(0xd0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* d0 */ W(0xe0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0) | /* e0 */ W(0xf0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1) /* f0 */ /* ---------------------------------------------- */ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ }; #else #define good_insns_32 NULL #endif /* Good-instruction tables for 64-bit apps. * * Genuinely invalid opcodes: * 06,07 - formerly push/pop es * 0e - formerly push cs * 16,17 - formerly push/pop ss * 1e,1f - formerly push/pop ds * 27,2f,37,3f - formerly daa/das/aaa/aas * 60,61 - formerly pusha/popa * 62 - formerly bound. EVEX prefix for AVX512 (not yet supported) * 82 - formerly redundant encoding of Group1 * 9a - formerly call seg:ofs * ce - formerly into * d4,d5 - formerly aam/aad * d6 - formerly undocumented salc * ea - formerly jmp seg:ofs * * Opcodes we'll probably never support: * 6c-6f - ins,outs. SEGVs if used in userspace * e4-e7 - in,out imm. SEGVs if used in userspace * ec-ef - in,out acc. SEGVs if used in userspace * cc - int3. SIGTRAP if used in userspace * f1 - int1. SIGTRAP if used in userspace * f4 - hlt. SEGVs if used in userspace * fa - cli. SEGVs if used in userspace * fb - sti. SEGVs if used in userspace * * Opcodes which need some work to be supported: * cd - int N. * Used by userspace for "int 80" syscall entry. (Other "int N" * cause GP -> SEGV since their IDT gates don't allow calls from CPL 3). * Not supported since kernel's handling of userspace single-stepping * (TF flag) is fragile. * cf - iret. Normally not used in userspace. Doesn't SEGV unless arguments are bad */ #if defined(CONFIG_X86_64) static volatile u32 good_insns_64[256 / 32] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ /* ---------------------------------------------- */ W(0x00, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1) | /* 00 */ W(0x10, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0) , /* 10 */ W(0x20, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0) | /* 20 */ W(0x30, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0) , /* 30 */ W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 40 */ W(0x50, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 50 */ W(0x60, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0) | /* 60 */ W(0x70, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 70 */ W(0x80, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 80 */ W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1) , /* 90 */ W(0xa0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* a0 */ W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* b0 */ W(0xc0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0) | /* c0 */ W(0xd0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* d0 */ W(0xe0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0) | /* e0 */ W(0xf0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1) /* f0 */ /* ---------------------------------------------- */ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ }; #else #define good_insns_64 NULL #endif /* Using this for both 64-bit and 32-bit apps. * Opcodes we don't support: * 0f 00 - SLDT/STR/LLDT/LTR/VERR/VERW/-/- group. System insns * 0f 01 - SGDT/SIDT/LGDT/LIDT/SMSW/-/LMSW/INVLPG group. * Also encodes tons of other system insns if mod=11. * Some are in fact non-system: xend, xtest, rdtscp, maybe more * 0f 05 - syscall * 0f 06 - clts (CPL0 insn) * 0f 07 - sysret * 0f 08 - invd (CPL0 insn) * 0f 09 - wbinvd (CPL0 insn) * 0f 0b - ud2 * 0f 30 - wrmsr (CPL0 insn) (then why rdmsr is allowed, it's also CPL0 insn?) * 0f 34 - sysenter * 0f 35 - sysexit * 0f 37 - getsec * 0f 78 - vmread (Intel VMX. CPL0 insn) * 0f 79 - vmwrite (Intel VMX. CPL0 insn) * Note: with prefixes, these two opcodes are * extrq/insertq/AVX512 convert vector ops. * 0f ae - group15: [f]xsave,[f]xrstor,[v]{ld,st}mxcsr,clflush[opt], * {rd,wr}{fs,gs}base,{s,l,m}fence. * Why? They are all user-executable. */ static volatile u32 good_2byte_insns[256 / 32] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ /* ---------------------------------------------- */ W(0x00, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1) | /* 00 */ W(0x10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 10 */ W(0x20, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 20 */ W(0x30, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1) , /* 30 */ W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 40 */ W(0x50, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 50 */ W(0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 60 */ W(0x70, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1) , /* 70 */ W(0x80, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 80 */ W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 90 */ W(0xa0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1) | /* a0 */ W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* b0 */ W(0xc0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* c0 */ W(0xd0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* d0 */ W(0xe0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* e0 */ W(0xf0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) /* f0 */ /* ---------------------------------------------- */ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ }; #undef W /* * opcodes we may need to refine support for: * * 0f - 2-byte instructions: For many of these instructions, the validity * depends on the prefix and/or the reg field. On such instructions, we * just consider the opcode combination valid if it corresponds to any * valid instruction. * * 8f - Group 1 - only reg = 0 is OK * c6-c7 - Group 11 - only reg = 0 is OK * d9-df - fpu insns with some illegal encodings * f2, f3 - repnz, repz prefixes. These are also the first byte for * certain floating-point instructions, such as addsd. * * fe - Group 4 - only reg = 0 or 1 is OK * ff - Group 5 - only reg = 0-6 is OK * * others -- Do we need to support these? * * 0f - (floating-point?) prefetch instructions * 07, 17, 1f - pop es, pop ss, pop ds * 26, 2e, 36, 3e - es:, cs:, ss:, ds: segment prefixes -- * but 64 and 65 (fs: and gs:) seem to be used, so we support them * 67 - addr16 prefix * ce - into * f0 - lock prefix */ /* * TODO: * - Where necessary, examine the modrm byte and allow only valid instructions * in the different Groups and fpu instructions. */ static bool is_prefix_bad(struct insn *insn) { insn_byte_t p; int i; for_each_insn_prefix(insn, i, p) { insn_attr_t attr; attr = inat_get_opcode_attribute(p); switch (attr) { case INAT_MAKE_PREFIX(INAT_PFX_ES): case INAT_MAKE_PREFIX(INAT_PFX_CS): case INAT_MAKE_PREFIX(INAT_PFX_DS): case INAT_MAKE_PREFIX(INAT_PFX_SS): case INAT_MAKE_PREFIX(INAT_PFX_LOCK): return true; } } return false; } static int uprobe_init_insn(struct arch_uprobe *auprobe, struct insn *insn, bool x86_64) { enum insn_mode m = x86_64 ? INSN_MODE_64 : INSN_MODE_32; u32 volatile *good_insns; int ret; ret = insn_decode(insn, auprobe->insn, sizeof(auprobe->insn), m); if (ret < 0) return -ENOEXEC; if (is_prefix_bad(insn)) return -ENOTSUPP; /* We should not singlestep on the exception masking instructions */ if (insn_masking_exception(insn)) return -ENOTSUPP; if (x86_64) good_insns = good_insns_64; else good_insns = good_insns_32; if (test_bit(OPCODE1(insn), (unsigned long *)good_insns)) return 0; if (insn->opcode.nbytes == 2) { if (test_bit(OPCODE2(insn), (unsigned long *)good_2byte_insns)) return 0; } return -ENOTSUPP; } #ifdef CONFIG_X86_64 /* * If arch_uprobe->insn doesn't use rip-relative addressing, return * immediately. Otherwise, rewrite the instruction so that it accesses * its memory operand indirectly through a scratch register. Set * defparam->fixups accordingly. (The contents of the scratch register * will be saved before we single-step the modified instruction, * and restored afterward). * * We do this because a rip-relative instruction can access only a * relatively small area (+/- 2 GB from the instruction), and the XOL * area typically lies beyond that area. At least for instructions * that store to memory, we can't execute the original instruction * and "fix things up" later, because the misdirected store could be * disastrous. * * Some useful facts about rip-relative instructions: * * - There's always a modrm byte with bit layout "00 reg 101". * - There's never a SIB byte. * - The displacement is always 4 bytes. * - REX.B=1 bit in REX prefix, which normally extends r/m field, * has no effect on rip-relative mode. It doesn't make modrm byte * with r/m=101 refer to register 1101 = R13. */ static void riprel_analyze(struct arch_uprobe *auprobe, struct insn *insn) { u8 *cursor; u8 reg; u8 reg2; if (!insn_rip_relative(insn)) return; /* * insn_rip_relative() would have decoded rex_prefix, vex_prefix, modrm. * Clear REX.b bit (extension of MODRM.rm field): * we want to encode low numbered reg, not r8+. */ if (insn->rex_prefix.nbytes) { cursor = auprobe->insn + insn_offset_rex_prefix(insn); /* REX byte has 0100wrxb layout, clearing REX.b bit */ *cursor &= 0xfe; } /* * Similar treatment for VEX3/EVEX prefix. * TODO: add XOP treatment when insn decoder supports them */ if (insn->vex_prefix.nbytes >= 3) { /* * vex2: c5 rvvvvLpp (has no b bit) * vex3/xop: c4/8f rxbmmmmm wvvvvLpp * evex: 62 rxbR00mm wvvvv1pp zllBVaaa * Setting VEX3.b (setting because it has inverted meaning). * Setting EVEX.x since (in non-SIB encoding) EVEX.x * is the 4th bit of MODRM.rm, and needs the same treatment. * For VEX3-encoded insns, VEX3.x value has no effect in * non-SIB encoding, the change is superfluous but harmless. */ cursor = auprobe->insn + insn_offset_vex_prefix(insn) + 1; *cursor |= 0x60; } /* * Convert from rip-relative addressing to register-relative addressing * via a scratch register. * * This is tricky since there are insns with modrm byte * which also use registers not encoded in modrm byte: * [i]div/[i]mul: implicitly use dx:ax * shift ops: implicitly use cx * cmpxchg: implicitly uses ax * cmpxchg8/16b: implicitly uses dx:ax and bx:cx * Encoding: 0f c7/1 modrm * The code below thinks that reg=1 (cx), chooses si as scratch. * mulx: implicitly uses dx: mulx r/m,r1,r2 does r1:r2 = dx * r/m. * First appeared in Haswell (BMI2 insn). It is vex-encoded. * Example where none of bx,cx,dx can be used as scratch reg: * c4 e2 63 f6 0d disp32 mulx disp32(%rip),%ebx,%ecx * [v]pcmpistri: implicitly uses cx, xmm0 * [v]pcmpistrm: implicitly uses xmm0 * [v]pcmpestri: implicitly uses ax, dx, cx, xmm0 * [v]pcmpestrm: implicitly uses ax, dx, xmm0 * Evil SSE4.2 string comparison ops from hell. * maskmovq/[v]maskmovdqu: implicitly uses (ds:rdi) as destination. * Encoding: 0f f7 modrm, 66 0f f7 modrm, vex-encoded: c5 f9 f7 modrm. * Store op1, byte-masked by op2 msb's in each byte, to (ds:rdi). * AMD says it has no 3-operand form (vex.vvvv must be 1111) * and that it can have only register operands, not mem * (its modrm byte must have mode=11). * If these restrictions will ever be lifted, * we'll need code to prevent selection of di as scratch reg! * * Summary: I don't know any insns with modrm byte which * use SI register implicitly. DI register is used only * by one insn (maskmovq) and BX register is used * only by one too (cmpxchg8b). * BP is stack-segment based (may be a problem?). * AX, DX, CX are off-limits (many implicit users). * SP is unusable (it's stack pointer - think about "pop mem"; * also, rsp+disp32 needs sib encoding -> insn length change). */ reg = MODRM_REG(insn); /* Fetch modrm.reg */ reg2 = 0xff; /* Fetch vex.vvvv */ if (insn->vex_prefix.nbytes) reg2 = insn->vex_prefix.bytes[2]; /* * TODO: add XOP vvvv reading. * * vex.vvvv field is in bits 6-3, bits are inverted. * But in 32-bit mode, high-order bit may be ignored. * Therefore, let's consider only 3 low-order bits. */ reg2 = ((reg2 >> 3) & 0x7) ^ 0x7; /* * Register numbering is ax,cx,dx,bx, sp,bp,si,di, r8..r15. * * Choose scratch reg. Order is important: must not select bx * if we can use si (cmpxchg8b case!) */ if (reg != 6 && reg2 != 6) { reg2 = 6; auprobe->defparam.fixups |= UPROBE_FIX_RIP_SI; } else if (reg != 7 && reg2 != 7) { reg2 = 7; auprobe->defparam.fixups |= UPROBE_FIX_RIP_DI; /* TODO (paranoia): force maskmovq to not use di */ } else { reg2 = 3; auprobe->defparam.fixups |= UPROBE_FIX_RIP_BX; } /* * Point cursor at the modrm byte. The next 4 bytes are the * displacement. Beyond the displacement, for some instructions, * is the immediate operand. */ cursor = auprobe->insn + insn_offset_modrm(insn); /* * Change modrm from "00 reg 101" to "10 reg reg2". Example: * 89 05 disp32 mov %eax,disp32(%rip) becomes * 89 86 disp32 mov %eax,disp32(%rsi) */ *cursor = 0x80 | (reg << 3) | reg2; } static inline unsigned long * scratch_reg(struct arch_uprobe *auprobe, struct pt_regs *regs) { if (auprobe->defparam.fixups & UPROBE_FIX_RIP_SI) return &regs->si; if (auprobe->defparam.fixups & UPROBE_FIX_RIP_DI) return &regs->di; return &regs->bx; } /* * If we're emulating a rip-relative instruction, save the contents * of the scratch register and store the target address in that register. */ static void riprel_pre_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { if (auprobe->defparam.fixups & UPROBE_FIX_RIP_MASK) { struct uprobe_task *utask = current->utask; unsigned long *sr = scratch_reg(auprobe, regs); utask->autask.saved_scratch_register = *sr; *sr = utask->vaddr + auprobe->defparam.ilen; } } static void riprel_post_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { if (auprobe->defparam.fixups & UPROBE_FIX_RIP_MASK) { struct uprobe_task *utask = current->utask; unsigned long *sr = scratch_reg(auprobe, regs); *sr = utask->autask.saved_scratch_register; } } #else /* 32-bit: */ /* * No RIP-relative addressing on 32-bit */ static void riprel_analyze(struct arch_uprobe *auprobe, struct insn *insn) { } static void riprel_pre_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { } static void riprel_post_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { } #endif /* CONFIG_X86_64 */ struct uprobe_xol_ops { bool (*emulate)(struct arch_uprobe *, struct pt_regs *); int (*pre_xol)(struct arch_uprobe *, struct pt_regs *); int (*post_xol)(struct arch_uprobe *, struct pt_regs *); void (*abort)(struct arch_uprobe *, struct pt_regs *); }; static inline int sizeof_long(struct pt_regs *regs) { /* * Check registers for mode as in_xxx_syscall() does not apply here. */ return user_64bit_mode(regs) ? 8 : 4; } static int default_pre_xol_op(struct arch_uprobe *auprobe, struct pt_regs *regs) { riprel_pre_xol(auprobe, regs); return 0; } static int emulate_push_stack(struct pt_regs *regs, unsigned long val) { unsigned long new_sp = regs->sp - sizeof_long(regs); if (copy_to_user((void __user *)new_sp, &val, sizeof_long(regs))) return -EFAULT; regs->sp = new_sp; return 0; } /* * We have to fix things up as follows: * * Typically, the new ip is relative to the copied instruction. We need * to make it relative to the original instruction (FIX_IP). Exceptions * are return instructions and absolute or indirect jump or call instructions. * * If the single-stepped instruction was a call, the return address that * is atop the stack is the address following the copied instruction. We * need to make it the address following the original instruction (FIX_CALL). * * If the original instruction was a rip-relative instruction such as * "movl %edx,0xnnnn(%rip)", we have instead executed an equivalent * instruction using a scratch register -- e.g., "movl %edx,0xnnnn(%rsi)". * We need to restore the contents of the scratch register * (FIX_RIP_reg). */ static int default_post_xol_op(struct arch_uprobe *auprobe, struct pt_regs *regs) { struct uprobe_task *utask = current->utask; riprel_post_xol(auprobe, regs); if (auprobe->defparam.fixups & UPROBE_FIX_IP) { long correction = utask->vaddr - utask->xol_vaddr; regs->ip += correction; } else if (auprobe->defparam.fixups & UPROBE_FIX_CALL) { regs->sp += sizeof_long(regs); /* Pop incorrect return address */ if (emulate_push_stack(regs, utask->vaddr + auprobe->defparam.ilen)) return -ERESTART; } /* popf; tell the caller to not touch TF */ if (auprobe->defparam.fixups & UPROBE_FIX_SETF) utask->autask.saved_tf = true; return 0; } static void default_abort_op(struct arch_uprobe *auprobe, struct pt_regs *regs) { riprel_post_xol(auprobe, regs); } static const struct uprobe_xol_ops default_xol_ops = { .pre_xol = default_pre_xol_op, .post_xol = default_post_xol_op, .abort = default_abort_op, }; static bool branch_is_call(struct arch_uprobe *auprobe) { return auprobe->branch.opc1 == 0xe8; } #define CASE_COND \ COND(70, 71, XF(OF)) \ COND(72, 73, XF(CF)) \ COND(74, 75, XF(ZF)) \ COND(78, 79, XF(SF)) \ COND(7a, 7b, XF(PF)) \ COND(76, 77, XF(CF) || XF(ZF)) \ COND(7c, 7d, XF(SF) != XF(OF)) \ COND(7e, 7f, XF(ZF) || XF(SF) != XF(OF)) #define COND(op_y, op_n, expr) \ case 0x ## op_y: DO((expr) != 0) \ case 0x ## op_n: DO((expr) == 0) #define XF(xf) (!!(flags & X86_EFLAGS_ ## xf)) static bool is_cond_jmp_opcode(u8 opcode) { switch (opcode) { #define DO(expr) \ return true; CASE_COND #undef DO default: return false; } } static bool check_jmp_cond(struct arch_uprobe *auprobe, struct pt_regs *regs) { unsigned long flags = regs->flags; switch (auprobe->branch.opc1) { #define DO(expr) \ return expr; CASE_COND #undef DO default: /* not a conditional jmp */ return true; } } #undef XF #undef COND #undef CASE_COND static bool branch_emulate_op(struct arch_uprobe *auprobe, struct pt_regs *regs) { unsigned long new_ip = regs->ip += auprobe->branch.ilen; unsigned long offs = (long)auprobe->branch.offs; if (branch_is_call(auprobe)) { /* * If it fails we execute this (mangled, see the comment in * branch_clear_offset) insn out-of-line. In the likely case * this should trigger the trap, and the probed application * should die or restart the same insn after it handles the * signal, arch_uprobe_post_xol() won't be even called. * * But there is corner case, see the comment in ->post_xol(). */ if (emulate_push_stack(regs, new_ip)) return false; } else if (!check_jmp_cond(auprobe, regs)) { offs = 0; } regs->ip = new_ip + offs; return true; } static bool push_emulate_op(struct arch_uprobe *auprobe, struct pt_regs *regs) { unsigned long *src_ptr = (void *)regs + auprobe->push.reg_offset; if (emulate_push_stack(regs, *src_ptr)) return false; regs->ip += auprobe->push.ilen; return true; } static int branch_post_xol_op(struct arch_uprobe *auprobe, struct pt_regs *regs) { BUG_ON(!branch_is_call(auprobe)); /* * We can only get here if branch_emulate_op() failed to push the ret * address _and_ another thread expanded our stack before the (mangled) * "call" insn was executed out-of-line. Just restore ->sp and restart. * We could also restore ->ip and try to call branch_emulate_op() again. */ regs->sp += sizeof_long(regs); return -ERESTART; } static void branch_clear_offset(struct arch_uprobe *auprobe, struct insn *insn) { /* * Turn this insn into "call 1f; 1:", this is what we will execute * out-of-line if ->emulate() fails. We only need this to generate * a trap, so that the probed task receives the correct signal with * the properly filled siginfo. * * But see the comment in ->post_xol(), in the unlikely case it can * succeed. So we need to ensure that the new ->ip can not fall into * the non-canonical area and trigger #GP. * * We could turn it into (say) "pushf", but then we would need to * divorce ->insn[] and ->ixol[]. We need to preserve the 1st byte * of ->insn[] for set_orig_insn(). */ memset(auprobe->insn + insn_offset_immediate(insn), 0, insn->immediate.nbytes); } static const struct uprobe_xol_ops branch_xol_ops = { .emulate = branch_emulate_op, .post_xol = branch_post_xol_op, }; static const struct uprobe_xol_ops push_xol_ops = { .emulate = push_emulate_op, }; /* Returns -ENOSYS if branch_xol_ops doesn't handle this insn */ static int branch_setup_xol_ops(struct arch_uprobe *auprobe, struct insn *insn) { u8 opc1 = OPCODE1(insn); insn_byte_t p; int i; switch (opc1) { case 0xeb: /* jmp 8 */ case 0xe9: /* jmp 32 */ break; case 0x90: /* prefix* + nop; same as jmp with .offs = 0 */ goto setup; case 0xe8: /* call relative */ branch_clear_offset(auprobe, insn); break; case 0x0f: if (insn->opcode.nbytes != 2) return -ENOSYS; /* * If it is a "near" conditional jmp, OPCODE2() - 0x10 matches * OPCODE1() of the "short" jmp which checks the same condition. */ opc1 = OPCODE2(insn) - 0x10; fallthrough; default: if (!is_cond_jmp_opcode(opc1)) return -ENOSYS; } /* * 16-bit overrides such as CALLW (66 e8 nn nn) are not supported. * Intel and AMD behavior differ in 64-bit mode: Intel ignores 66 prefix. * No one uses these insns, reject any branch insns with such prefix. */ for_each_insn_prefix(insn, i, p) { if (p == 0x66) return -ENOTSUPP; } setup: auprobe->branch.opc1 = opc1; auprobe->branch.ilen = insn->length; auprobe->branch.offs = insn->immediate.value; auprobe->ops = &branch_xol_ops; return 0; } /* Returns -ENOSYS if push_xol_ops doesn't handle this insn */ static int push_setup_xol_ops(struct arch_uprobe *auprobe, struct insn *insn) { u8 opc1 = OPCODE1(insn), reg_offset = 0; if (opc1 < 0x50 || opc1 > 0x57) return -ENOSYS; if (insn->length > 2) return -ENOSYS; if (insn->length == 2) { /* only support rex_prefix 0x41 (x64 only) */ #ifdef CONFIG_X86_64 if (insn->rex_prefix.nbytes != 1 || insn->rex_prefix.bytes[0] != 0x41) return -ENOSYS; switch (opc1) { case 0x50: reg_offset = offsetof(struct pt_regs, r8); break; case 0x51: reg_offset = offsetof(struct pt_regs, r9); break; case 0x52: reg_offset = offsetof(struct pt_regs, r10); break; case 0x53: reg_offset = offsetof(struct pt_regs, r11); break; case 0x54: reg_offset = offsetof(struct pt_regs, r12); break; case 0x55: reg_offset = offsetof(struct pt_regs, r13); break; case 0x56: reg_offset = offsetof(struct pt_regs, r14); break; case 0x57: reg_offset = offsetof(struct pt_regs, r15); break; } #else return -ENOSYS; #endif } else { switch (opc1) { case 0x50: reg_offset = offsetof(struct pt_regs, ax); break; case 0x51: reg_offset = offsetof(struct pt_regs, cx); break; case 0x52: reg_offset = offsetof(struct pt_regs, dx); break; case 0x53: reg_offset = offsetof(struct pt_regs, bx); break; case 0x54: reg_offset = offsetof(struct pt_regs, sp); break; case 0x55: reg_offset = offsetof(struct pt_regs, bp); break; case 0x56: reg_offset = offsetof(struct pt_regs, si); break; case 0x57: reg_offset = offsetof(struct pt_regs, di); break; } } auprobe->push.reg_offset = reg_offset; auprobe->push.ilen = insn->length; auprobe->ops = &push_xol_ops; return 0; } /** * arch_uprobe_analyze_insn - instruction analysis including validity and fixups. * @auprobe: the probepoint information. * @mm: the probed address space. * @addr: virtual address at which to install the probepoint * Return 0 on success or a -ve number on error. */ int arch_uprobe_analyze_insn(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long addr) { struct insn insn; u8 fix_ip_or_call = UPROBE_FIX_IP; int ret; ret = uprobe_init_insn(auprobe, &insn, is_64bit_mm(mm)); if (ret) return ret; ret = branch_setup_xol_ops(auprobe, &insn); if (ret != -ENOSYS) return ret; ret = push_setup_xol_ops(auprobe, &insn); if (ret != -ENOSYS) return ret; /* * Figure out which fixups default_post_xol_op() will need to perform, * and annotate defparam->fixups accordingly. */ switch (OPCODE1(&insn)) { case 0x9d: /* popf */ auprobe->defparam.fixups |= UPROBE_FIX_SETF; break; case 0xc3: /* ret or lret -- ip is correct */ case 0xcb: case 0xc2: case 0xca: case 0xea: /* jmp absolute -- ip is correct */ fix_ip_or_call = 0; break; case 0x9a: /* call absolute - Fix return addr, not ip */ fix_ip_or_call = UPROBE_FIX_CALL; break; case 0xff: switch (MODRM_REG(&insn)) { case 2: case 3: /* call or lcall, indirect */ fix_ip_or_call = UPROBE_FIX_CALL; break; case 4: case 5: /* jmp or ljmp, indirect */ fix_ip_or_call = 0; break; } fallthrough; default: riprel_analyze(auprobe, &insn); } auprobe->defparam.ilen = insn.length; auprobe->defparam.fixups |= fix_ip_or_call; auprobe->ops = &default_xol_ops; return 0; } /* * arch_uprobe_pre_xol - prepare to execute out of line. * @auprobe: the probepoint information. * @regs: reflects the saved user state of current task. */ int arch_uprobe_pre_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { struct uprobe_task *utask = current->utask; if (auprobe->ops->pre_xol) { int err = auprobe->ops->pre_xol(auprobe, regs); if (err) return err; } regs->ip = utask->xol_vaddr; utask->autask.saved_trap_nr = current->thread.trap_nr; current->thread.trap_nr = UPROBE_TRAP_NR; utask->autask.saved_tf = !!(regs->flags & X86_EFLAGS_TF); regs->flags |= X86_EFLAGS_TF; if (test_tsk_thread_flag(current, TIF_BLOCKSTEP)) set_task_blockstep(current, false); return 0; } /* * If xol insn itself traps and generates a signal(Say, * SIGILL/SIGSEGV/etc), then detect the case where a singlestepped * instruction jumps back to its own address. It is assumed that anything * like do_page_fault/do_trap/etc sets thread.trap_nr != -1. * * arch_uprobe_pre_xol/arch_uprobe_post_xol save/restore thread.trap_nr, * arch_uprobe_xol_was_trapped() simply checks that ->trap_nr is not equal to * UPROBE_TRAP_NR == -1 set by arch_uprobe_pre_xol(). */ bool arch_uprobe_xol_was_trapped(struct task_struct *t) { if (t->thread.trap_nr != UPROBE_TRAP_NR) return true; return false; } /* * Called after single-stepping. To avoid the SMP problems that can * occur when we temporarily put back the original opcode to * single-step, we single-stepped a copy of the instruction. * * This function prepares to resume execution after the single-step. */ int arch_uprobe_post_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { struct uprobe_task *utask = current->utask; bool send_sigtrap = utask->autask.saved_tf; int err = 0; WARN_ON_ONCE(current->thread.trap_nr != UPROBE_TRAP_NR); current->thread.trap_nr = utask->autask.saved_trap_nr; if (auprobe->ops->post_xol) { err = auprobe->ops->post_xol(auprobe, regs); if (err) { /* * Restore ->ip for restart or post mortem analysis. * ->post_xol() must not return -ERESTART unless this * is really possible. */ regs->ip = utask->vaddr; if (err == -ERESTART) err = 0; send_sigtrap = false; } } /* * arch_uprobe_pre_xol() doesn't save the state of TIF_BLOCKSTEP * so we can get an extra SIGTRAP if we do not clear TF. We need * to examine the opcode to make it right. */ if (send_sigtrap) send_sig(SIGTRAP, current, 0); if (!utask->autask.saved_tf) regs->flags &= ~X86_EFLAGS_TF; return err; } /* callback routine for handling exceptions. */ int arch_uprobe_exception_notify(struct notifier_block *self, unsigned long val, void *data) { struct die_args *args = data; struct pt_regs *regs = args->regs; int ret = NOTIFY_DONE; /* We are only interested in userspace traps */ if (regs && !user_mode(regs)) return NOTIFY_DONE; switch (val) { case DIE_INT3: if (uprobe_pre_sstep_notifier(regs)) ret = NOTIFY_STOP; break; case DIE_DEBUG: if (uprobe_post_sstep_notifier(regs)) ret = NOTIFY_STOP; break; default: break; } return ret; } /* * This function gets called when XOL instruction either gets trapped or * the thread has a fatal signal. Reset the instruction pointer to its * probed address for the potential restart or for post mortem analysis. */ void arch_uprobe_abort_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { struct uprobe_task *utask = current->utask; if (auprobe->ops->abort) auprobe->ops->abort(auprobe, regs); current->thread.trap_nr = utask->autask.saved_trap_nr; regs->ip = utask->vaddr; /* clear TF if it was set by us in arch_uprobe_pre_xol() */ if (!utask->autask.saved_tf) regs->flags &= ~X86_EFLAGS_TF; } static bool __skip_sstep(struct arch_uprobe *auprobe, struct pt_regs *regs) { if (auprobe->ops->emulate) return auprobe->ops->emulate(auprobe, regs); return false; } bool arch_uprobe_skip_sstep(struct arch_uprobe *auprobe, struct pt_regs *regs) { bool ret = __skip_sstep(auprobe, regs); if (ret && (regs->flags & X86_EFLAGS_TF)) send_sig(SIGTRAP, current, 0); return ret; } unsigned long arch_uretprobe_hijack_return_addr(unsigned long trampoline_vaddr, struct pt_regs *regs) { int rasize = sizeof_long(regs), nleft; unsigned long orig_ret_vaddr = 0; /* clear high bits for 32-bit apps */ if (copy_from_user(&orig_ret_vaddr, (void __user *)regs->sp, rasize)) return -1; /* check whether address has been already hijacked */ if (orig_ret_vaddr == trampoline_vaddr) return orig_ret_vaddr; nleft = copy_to_user((void __user *)regs->sp, &trampoline_vaddr, rasize); if (likely(!nleft)) return orig_ret_vaddr; if (nleft != rasize) { pr_err("return address clobbered: pid=%d, %%sp=%#lx, %%ip=%#lx\n", current->pid, regs->sp, regs->ip); force_sig(SIGSEGV); } return -1; } bool arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, struct pt_regs *regs) { if (ctx == RP_CHECK_CALL) /* sp was just decremented by "call" insn */ return regs->sp < ret->stack; else return regs->sp <= ret->stack; }
linux-master
arch/x86/kernel/uprobes.c