Resguardo inicial

This commit is contained in:
lastdragon
2026-09-06 12:53:21 -06:00
parent 662efe3c2a
commit ad2088d178
94853 changed files with 43200404 additions and 0 deletions
@@ -0,0 +1,13 @@
perf-util-y += header.o
perf-util-y += tsc.o
perf-util-y += pmu.o
perf-util-y += topdown.o
perf-util-y += machine.o
perf-util-y += event.o
perf-util-y += evlist.o
perf-util-y += mem-events.o
perf-util-y += evsel.o
perf-util-y += iostat.o
perf-util-y += auxtrace.o
perf-util-y += intel-pt.o
perf-util-y += intel-bts.o
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* auxtrace.c: AUX area tracing support
* Copyright (c) 2013-2014, Intel Corporation.
*/
#include <errno.h>
#include <stdbool.h>
#include "../../../util/header.h"
#include "../../../util/debug.h"
#include "../../../util/pmu.h"
#include "../../../util/pmus.h"
#include "../../../util/auxtrace.h"
#include "../../../util/intel-pt.h"
#include "../../../util/intel-bts.h"
#include "../../../util/evlist.h"
static
struct auxtrace_record *auxtrace_record__init_intel(struct evlist *evlist,
int *err)
{
struct perf_pmu *intel_pt_pmu;
struct perf_pmu *intel_bts_pmu;
struct evsel *evsel;
bool found_pt = false;
bool found_bts = false;
intel_pt_pmu = perf_pmus__find(INTEL_PT_PMU_NAME);
intel_bts_pmu = perf_pmus__find(INTEL_BTS_PMU_NAME);
evlist__for_each_entry(evlist, evsel) {
if (intel_pt_pmu && evsel->core.attr.type == intel_pt_pmu->type)
found_pt = true;
if (intel_bts_pmu && evsel->core.attr.type == intel_bts_pmu->type)
found_bts = true;
}
if (found_pt && found_bts) {
pr_err("intel_pt and intel_bts may not be used together\n");
*err = -EINVAL;
return NULL;
}
if (found_pt)
return intel_pt_recording_init(err);
if (found_bts)
return intel_bts_recording_init(err);
return NULL;
}
struct auxtrace_record *auxtrace_record__init(struct evlist *evlist,
int *err)
{
char buffer[64];
struct perf_cpu cpu = perf_cpu_map__min(evlist->core.all_cpus);
int ret;
*err = 0;
ret = get_cpuid(buffer, sizeof(buffer), cpu);
if (ret) {
*err = ret;
return NULL;
}
if (!strncmp(buffer, "GenuineIntel,", 13))
return auxtrace_record__init_intel(evlist, err);
return NULL;
}
@@ -0,0 +1,34 @@
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef PERF_CPUID_H
#define PERF_CPUID_H 1
static inline void
cpuid(unsigned int op, unsigned int op2, unsigned int *a, unsigned int *b,
unsigned int *c, unsigned int *d)
{
/*
* Preserve %ebx/%rbx register by either placing it in %rdi or saving it
* on the stack - x86-64 needs to avoid the stack red zone. In PIC
* compilations %ebx contains the address of the global offset
* table. %rbx is occasionally used to address stack variables in
* presence of dynamic allocas.
*/
asm(
#if defined(__x86_64__)
"mov %%rbx, %%rdi\n"
"cpuid\n"
"xchg %%rdi, %%rbx\n"
#else
"pushl %%ebx\n"
"cpuid\n"
"movl %%ebx, %%edi\n"
"popl %%ebx\n"
#endif
: "=a"(*a), "=D"(*b), "=c"(*c), "=d"(*d)
: "a"(op), "2"(op2));
}
void get_cpuid_0(char *vendor, unsigned int *lvl);
#endif
@@ -0,0 +1,93 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/types.h>
#include <linux/string.h>
#include <linux/zalloc.h>
#include <stdlib.h>
#include "../../../util/event.h"
#include "../../../util/synthetic-events.h"
#include "../../../util/machine.h"
#include "../../../util/tool.h"
#include "../../../util/map.h"
#include "../../../util/debug.h"
#include "util/sample.h"
#if defined(__x86_64__)
struct perf_event__synthesize_extra_kmaps_cb_args {
const struct perf_tool *tool;
perf_event__handler_t process;
struct machine *machine;
union perf_event *event;
};
static int perf_event__synthesize_extra_kmaps_cb(struct map *map, void *data)
{
struct perf_event__synthesize_extra_kmaps_cb_args *args = data;
union perf_event *event = args->event;
struct kmap *kmap;
size_t size;
if (!__map__is_extra_kernel_map(map))
return 0;
kmap = map__kmap(map);
size = sizeof(event->mmap) - sizeof(event->mmap.filename) +
PERF_ALIGN(strlen(kmap->name) + 1, sizeof(u64)) +
args->machine->id_hdr_size;
memset(event, 0, size);
event->mmap.header.type = PERF_RECORD_MMAP;
/*
* kernel uses 0 for user space maps, see kernel/perf_event.c
* __perf_event_mmap
*/
if (machine__is_host(args->machine))
event->header.misc = PERF_RECORD_MISC_KERNEL;
else
event->header.misc = PERF_RECORD_MISC_GUEST_KERNEL;
event->mmap.header.size = size;
event->mmap.start = map__start(map);
event->mmap.len = map__size(map);
event->mmap.pgoff = map__pgoff(map);
event->mmap.pid = args->machine->pid;
strlcpy(event->mmap.filename, kmap->name, PATH_MAX);
if (perf_tool__process_synth_event(args->tool, event, args->machine, args->process) != 0)
return -1;
return 0;
}
int perf_event__synthesize_extra_kmaps(const struct perf_tool *tool,
perf_event__handler_t process,
struct machine *machine)
{
int rc;
struct maps *kmaps = machine__kernel_maps(machine);
struct perf_event__synthesize_extra_kmaps_cb_args args = {
.tool = tool,
.process = process,
.machine = machine,
.event = zalloc(sizeof(args.event->mmap) + machine->id_hdr_size),
};
if (!args.event) {
pr_debug("Not enough memory synthesizing mmap event "
"for extra kernel maps\n");
return -1;
}
rc = maps__for_each_map(kmaps, perf_event__synthesize_extra_kmaps_cb, &args);
free(args.event);
return rc;
}
#endif
@@ -0,0 +1,107 @@
// SPDX-License-Identifier: GPL-2.0
#include <string.h>
#include "../../../util/evlist.h"
#include "../../../util/evsel.h"
#include "topdown.h"
#include "evsel.h"
int arch_evlist__cmp(const struct evsel *lhs, const struct evsel *rhs)
{
/*
* Currently the following topdown events sequence are supported to
* move and regroup correctly.
*
* a. all events in a group
* perf stat -e "{instructions,topdown-retiring,slots}" -C0 sleep 1
* WARNING: events were regrouped to match PMUs
* Performance counter stats for 'CPU(s) 0':
* 15,066,240 slots
* 1,899,760 instructions
* 2,126,998 topdown-retiring
* b. all events not in a group
* perf stat -e "instructions,topdown-retiring,slots" -C0 sleep 1
* WARNING: events were regrouped to match PMUs
* Performance counter stats for 'CPU(s) 0':
* 2,045,561 instructions
* 17,108,370 slots
* 2,281,116 topdown-retiring
* c. slots event in a group but topdown metrics events outside the group
* perf stat -e "{instructions,slots},topdown-retiring" -C0 sleep 1
* WARNING: events were regrouped to match PMUs
* Performance counter stats for 'CPU(s) 0':
* 20,323,878 slots
* 2,634,884 instructions
* 3,028,656 topdown-retiring
* d. slots event and topdown metrics events in two groups
* perf stat -e "{instructions,slots},{topdown-retiring}" -C0 sleep 1
* WARNING: events were regrouped to match PMUs
* Performance counter stats for 'CPU(s) 0':
* 26,319,024 slots
* 2,427,791 instructions
* 2,683,508 topdown-retiring
* e. slots event and metrics event are not in a group and not adjacent
* perf stat -e "{instructions,slots},cycles,topdown-retiring" -C0 sleep 1
* WARNING: events were regrouped to match PMUs
* 68,433,522 slots
* 8,856,102 topdown-retiring
* 7,791,494 instructions
* 11,469,513 cycles
*/
if (topdown_sys_has_perf_metrics() &&
(arch_evsel__must_be_in_group(lhs) || arch_evsel__must_be_in_group(rhs))) {
/* Ensure the topdown slots comes first. */
if (arch_is_topdown_slots(lhs))
return -1;
if (arch_is_topdown_slots(rhs))
return 1;
/*
* Move topdown metrics events forward only when topdown metrics
* events are not in same group with previous slots event. If
* topdown metrics events are already in same group with slots
* event, do nothing.
*/
if (lhs->core.leader != rhs->core.leader) {
bool lhs_topdown = arch_is_topdown_metrics(lhs);
bool rhs_topdown = arch_is_topdown_metrics(rhs);
if (lhs_topdown && !rhs_topdown)
return -1;
if (!lhs_topdown && rhs_topdown)
return 1;
}
}
/* Retire latency event should not be group leader*/
if (lhs->retire_lat && !rhs->retire_lat)
return 1;
if (!lhs->retire_lat && rhs->retire_lat)
return -1;
/* Default ordering by insertion index. */
return lhs->core.idx - rhs->core.idx;
}
int arch_evlist__add_required_events(struct list_head *list)
{
struct evsel *pos, *metric_event = NULL;
int idx = 0;
if (!topdown_sys_has_perf_metrics())
return 0;
list_for_each_entry(pos, list, core.node) {
if (arch_is_topdown_slots(pos)) {
/* Slots event already present, nothing to do. */
return 0;
}
if (metric_event == NULL && arch_is_topdown_metrics(pos))
metric_event = pos;
idx++;
}
if (metric_event == NULL) {
/* No topdown metric events, nothing to do. */
return 0;
}
return topdown_insert_slots_event(list, idx + 1, metric_event);
}
@@ -0,0 +1,229 @@
// SPDX-License-Identifier: GPL-2.0
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "util/evlist.h"
#include "util/evsel.h"
#include "util/evsel_config.h"
#include "util/env.h"
#include "util/pmu.h"
#include "util/pmus.h"
#include "util/stat.h"
#include "util/strbuf.h"
#include "linux/string.h"
#include "topdown.h"
#include "evsel.h"
#include "util/debug.h"
#include "env.h"
#define IBS_FETCH_L3MISSONLY (1ULL << 59)
#define IBS_OP_L3MISSONLY (1ULL << 16)
void arch_evsel__set_sample_weight(struct evsel *evsel)
{
evsel__set_sample_bit(evsel, WEIGHT_STRUCT);
}
/* Check whether the evsel's PMU supports the perf metrics */
bool evsel__sys_has_perf_metrics(const struct evsel *evsel)
{
struct perf_pmu *pmu;
if (!topdown_sys_has_perf_metrics())
return false;
/*
* The PERF_TYPE_RAW type is the core PMU type, e.g., "cpu" PMU on a
* non-hybrid machine, "cpu_core" PMU on a hybrid machine. The
* topdown_sys_has_perf_metrics checks the slots event is only available
* for the core PMU, which supports the perf metrics feature. Checking
* both the PERF_TYPE_RAW type and the slots event should be good enough
* to detect the perf metrics feature.
*/
pmu = evsel__find_pmu(evsel);
return pmu && pmu->type == PERF_TYPE_RAW;
}
bool arch_evsel__must_be_in_group(const struct evsel *evsel)
{
if (!evsel__sys_has_perf_metrics(evsel))
return false;
return arch_is_topdown_metrics(evsel) || arch_is_topdown_slots(evsel);
}
int arch_evsel__hw_name(struct evsel *evsel, char *bf, size_t size)
{
u64 event = evsel->core.attr.config & PERF_HW_EVENT_MASK;
u64 pmu = evsel->core.attr.config >> PERF_PMU_TYPE_SHIFT;
const char *event_name;
if (event < PERF_COUNT_HW_MAX && evsel__hw_names[event])
event_name = evsel__hw_names[event];
else
event_name = "unknown-hardware";
/* The PMU type is not required for the non-hybrid platform. */
if (!pmu)
return scnprintf(bf, size, "%s", event_name);
return scnprintf(bf, size, "%s/%s/",
evsel->pmu ? evsel->pmu->name : "cpu",
event_name);
}
void arch_evsel__apply_ratio_to_prev(struct evsel *evsel,
struct perf_event_attr *attr)
{
struct perf_event_attr *prev_attr = NULL;
struct evsel *evsel_prev = NULL;
const char *name = "acr_mask";
int evsel_idx = 0;
__u64 ev_mask, pr_ev_mask;
if (!perf_pmu__has_format(evsel->pmu, name)) {
pr_err("'%s' does not have acr_mask format support\n", evsel->pmu->name);
return;
}
if (perf_pmu__format_type(evsel->pmu, name) !=
PERF_PMU_FORMAT_VALUE_CONFIG2) {
pr_err("'%s' does not have config2 format support\n", evsel->pmu->name);
return;
}
evsel_prev = evsel__prev(evsel);
if (!evsel_prev) {
pr_err("Previous event does not exist.\n");
return;
}
prev_attr = &evsel_prev->core.attr;
if (prev_attr->config2) {
pr_err("'%s' has set config2 (acr_mask?) already, configuration not supported\n", evsel_prev->name);
return;
}
/*
* acr_mask (config2) is calculated using the event's index in
* the event group. The first event will use the index of the
* second event as its mask (e.g., 0x2), indicating that the
* second event counter will be reset and a sample taken for
* the first event if its counter overflows. The second event
* will use the mask consisting of the first and second bits
* (e.g., 0x3), meaning both counters will be reset if the
* second event counter overflows.
*/
evsel_idx = evsel__group_idx(evsel);
ev_mask = 1ull << evsel_idx;
pr_ev_mask = 1ull << (evsel_idx - 1);
prev_attr->config2 = ev_mask;
attr->config2 = ev_mask | pr_ev_mask;
}
static void ibs_l3miss_warn(void)
{
pr_warning(
"WARNING: Hw internally resets sampling period when L3 Miss Filtering is enabled\n"
"and tagged operation does not cause L3 Miss. This causes sampling period skew.\n");
}
void arch__post_evsel_config(struct evsel *evsel, struct perf_event_attr *attr)
{
struct perf_pmu *evsel_pmu, *ibs_fetch_pmu, *ibs_op_pmu;
static int warned_once;
if (warned_once || !x86__is_amd_cpu())
return;
evsel_pmu = evsel__find_pmu(evsel);
if (!evsel_pmu)
return;
ibs_fetch_pmu = perf_pmus__find("ibs_fetch");
ibs_op_pmu = perf_pmus__find("ibs_op");
if (ibs_fetch_pmu && ibs_fetch_pmu->type == evsel_pmu->type) {
if (attr->config & IBS_FETCH_L3MISSONLY) {
ibs_l3miss_warn();
warned_once = 1;
}
} else if (ibs_op_pmu && ibs_op_pmu->type == evsel_pmu->type) {
if (attr->config & IBS_OP_L3MISSONLY) {
ibs_l3miss_warn();
warned_once = 1;
}
}
}
static int amd_evsel__open_strerror(struct evsel *evsel, char *msg, size_t size)
{
struct perf_pmu *pmu;
if (evsel->core.attr.precise_ip == 0)
return 0;
pmu = evsel__find_pmu(evsel);
if (!pmu || strncmp(pmu->name, "ibs", 3))
return 0;
/* More verbose IBS errors. */
if (evsel->core.attr.exclude_kernel || evsel->core.attr.exclude_user ||
evsel->core.attr.exclude_hv || evsel->core.attr.exclude_idle ||
evsel->core.attr.exclude_host || evsel->core.attr.exclude_guest) {
return scnprintf(msg, size, "AMD IBS doesn't support privilege filtering. Try "
"again without the privilege modifiers (like 'k') at the end.");
}
return 0;
}
static int intel_evsel__open_strerror(struct evsel *evsel, int err, char *msg, size_t size)
{
struct strbuf sb = STRBUF_INIT;
int ret;
if (err != EINVAL)
return 0;
if (!topdown_sys_has_perf_metrics())
return 0;
if (arch_is_topdown_slots(evsel)) {
if (!evsel__is_group_leader(evsel)) {
evlist__uniquify_evsel_names(evsel->evlist, &stat_config);
evlist__format_evsels(evsel->evlist, &sb, 2048);
ret = scnprintf(msg, size, "Topdown slots event can only be group leader "
"in '%s'.", sb.buf);
strbuf_release(&sb);
return ret;
}
} else if (arch_is_topdown_metrics(evsel)) {
struct evsel *pos;
evlist__for_each_entry(evsel->evlist, pos) {
if (pos == evsel || !arch_is_topdown_metrics(pos))
continue;
if (pos->core.attr.config != evsel->core.attr.config)
continue;
evlist__uniquify_evsel_names(evsel->evlist, &stat_config);
evlist__format_evsels(evsel->evlist, &sb, 2048);
ret = scnprintf(msg, size, "Perf metric event '%s' is duplicated "
"in the same group (only one event is allowed) in '%s'.",
evsel__name(evsel), sb.buf);
strbuf_release(&sb);
return ret;
}
}
return 0;
}
int arch_evsel__open_strerror(struct evsel *evsel, int err, char *msg, size_t size)
{
return x86__is_amd_cpu()
? amd_evsel__open_strerror(evsel, msg, size)
: intel_evsel__open_strerror(evsel, err, msg, size);
}
@@ -0,0 +1,7 @@
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _EVSEL_H
#define _EVSEL_H 1
bool evsel__sys_has_perf_metrics(const struct evsel *evsel);
#endif
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-2.0
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#include "../../../util/debug.h"
#include "../../../util/header.h"
#include "cpuid.h"
void get_cpuid_0(char *vendor, unsigned int *lvl)
{
unsigned int b, c, d;
cpuid(0, 0, lvl, &b, &c, &d);
strncpy(&vendor[0], (char *)(&b), 4);
strncpy(&vendor[4], (char *)(&d), 4);
strncpy(&vendor[8], (char *)(&c), 4);
vendor[12] = '\0';
}
static int
__get_cpuid(char *buffer, size_t sz, const char *fmt)
{
unsigned int a, b, c, d, lvl;
int family = -1, model = -1, step = -1;
int nb;
char vendor[16];
get_cpuid_0(vendor, &lvl);
if (lvl >= 1) {
cpuid(1, 0, &a, &b, &c, &d);
family = (a >> 8) & 0xf; /* bits 11 - 8 */
model = (a >> 4) & 0xf; /* Bits 7 - 4 */
step = a & 0xf;
/* extended family */
if (family == 0xf)
family += (a >> 20) & 0xff;
/* extended model */
if (family >= 0x6)
model += ((a >> 16) & 0xf) << 4;
}
nb = scnprintf(buffer, sz, fmt, vendor, family, model, step);
/* look for end marker to ensure the entire data fit */
if (strchr(buffer, '$')) {
buffer[nb-1] = '\0';
return 0;
}
return ENOBUFS;
}
int
get_cpuid(char *buffer, size_t sz, struct perf_cpu cpu __maybe_unused)
{
return __get_cpuid(buffer, sz, "%s,%u,%u,%u$");
}
char *get_cpuid_str(struct perf_cpu cpu __maybe_unused)
{
char *buf = malloc(128);
if (buf && __get_cpuid(buf, 128, "%s-%u-%X-%X$") < 0) {
free(buf);
return NULL;
}
return buf;
}
/* Full CPUID format for x86 is vendor-family-model-stepping */
static bool is_full_cpuid(const char *id)
{
const char *tmp = id;
int count = 0;
while ((tmp = strchr(tmp, '-')) != NULL) {
count++;
tmp++;
}
if (count == 3)
return true;
return false;
}
int strcmp_cpuid_str(const char *mapcpuid, const char *id)
{
regex_t re;
regmatch_t pmatch[1];
int match;
bool full_mapcpuid = is_full_cpuid(mapcpuid);
bool full_cpuid = is_full_cpuid(id);
/*
* Full CPUID format is required to identify a platform.
* Error out if the cpuid string is incomplete.
*/
if (full_mapcpuid && !full_cpuid) {
pr_info("Invalid CPUID %s. Full CPUID is required, "
"vendor-family-model-stepping\n", id);
return 1;
}
if (regcomp(&re, mapcpuid, REG_EXTENDED) != 0) {
/* Warn unable to generate match particular string. */
pr_info("Invalid regular expression %s\n", mapcpuid);
return 1;
}
match = !regexec(&re, id, 1, pmatch, 0);
regfree(&re);
if (match) {
size_t match_len = (pmatch[0].rm_eo - pmatch[0].rm_so);
size_t cpuid_len;
/* If the full CPUID format isn't required,
* ignoring the stepping.
*/
if (!full_mapcpuid && full_cpuid)
cpuid_len = strrchr(id, '-') - id;
else
cpuid_len = strlen(id);
/* Verify the entire string matched. */
if (match_len == cpuid_len)
return 0;
}
return 1;
}
@@ -0,0 +1,453 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* intel-bts.c: Intel Processor Trace support
* Copyright (c) 2013-2015, Intel Corporation.
*/
#include "../../../util/intel-bts.h"
#include <errno.h>
#include <linux/bitops.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include <linux/types.h>
#include <linux/zalloc.h>
#include <internal/lib.h> // page_size
#include "../../../util/auxtrace.h"
#include "../../../util/cpumap.h"
#include "../../../util/debug.h"
#include "../../../util/event.h"
#include "../../../util/evlist.h"
#include "../../../util/evsel.h"
#include "../../../util/mmap.h"
#include "../../../util/pmu.h"
#include "../../../util/pmus.h"
#include "../../../util/record.h"
#include "../../../util/session.h"
#include "../../../util/tsc.h"
#define KiB(x) ((x) * 1024)
#define MiB(x) ((x) * 1024 * 1024)
#define KiB_MASK(x) (KiB(x) - 1)
#define MiB_MASK(x) (MiB(x) - 1)
struct intel_bts_snapshot_ref {
void *ref_buf;
size_t ref_offset;
bool wrapped;
};
struct intel_bts_recording {
struct auxtrace_record itr;
struct perf_pmu *intel_bts_pmu;
struct evlist *evlist;
bool snapshot_mode;
size_t snapshot_size;
int snapshot_ref_cnt;
struct intel_bts_snapshot_ref *snapshot_refs;
};
struct branch {
u64 from;
u64 to;
u64 misc;
};
static size_t
intel_bts_info_priv_size(struct auxtrace_record *itr __maybe_unused,
struct evlist *evlist __maybe_unused)
{
return INTEL_BTS_AUXTRACE_PRIV_SIZE;
}
static int intel_bts_info_fill(struct auxtrace_record *itr,
struct perf_session *session,
struct perf_record_auxtrace_info *auxtrace_info,
size_t priv_size)
{
struct intel_bts_recording *btsr =
container_of(itr, struct intel_bts_recording, itr);
struct perf_pmu *intel_bts_pmu = btsr->intel_bts_pmu;
struct perf_event_mmap_page *pc;
struct perf_tsc_conversion tc = { .time_mult = 0, };
bool cap_user_time_zero = false;
int err;
if (priv_size != INTEL_BTS_AUXTRACE_PRIV_SIZE)
return -EINVAL;
if (!session->evlist->core.nr_mmaps)
return -EINVAL;
pc = session->evlist->mmap[0].core.base;
if (pc) {
err = perf_read_tsc_conversion(pc, &tc);
if (err) {
if (err != -EOPNOTSUPP)
return err;
} else {
cap_user_time_zero = tc.time_mult != 0;
}
if (!cap_user_time_zero)
ui__warning("Intel BTS: TSC not available\n");
}
auxtrace_info->type = PERF_AUXTRACE_INTEL_BTS;
auxtrace_info->priv[INTEL_BTS_PMU_TYPE] = intel_bts_pmu->type;
auxtrace_info->priv[INTEL_BTS_TIME_SHIFT] = tc.time_shift;
auxtrace_info->priv[INTEL_BTS_TIME_MULT] = tc.time_mult;
auxtrace_info->priv[INTEL_BTS_TIME_ZERO] = tc.time_zero;
auxtrace_info->priv[INTEL_BTS_CAP_USER_TIME_ZERO] = cap_user_time_zero;
auxtrace_info->priv[INTEL_BTS_SNAPSHOT_MODE] = btsr->snapshot_mode;
return 0;
}
static int intel_bts_recording_options(struct auxtrace_record *itr,
struct evlist *evlist,
struct record_opts *opts)
{
struct intel_bts_recording *btsr =
container_of(itr, struct intel_bts_recording, itr);
struct perf_pmu *intel_bts_pmu = btsr->intel_bts_pmu;
struct evsel *evsel, *intel_bts_evsel = NULL;
const struct perf_cpu_map *cpus = evlist->core.user_requested_cpus;
bool privileged = perf_event_paranoid_check(-1);
if (opts->auxtrace_sample_mode) {
pr_err("Intel BTS does not support AUX area sampling\n");
return -EINVAL;
}
btsr->evlist = evlist;
btsr->snapshot_mode = opts->auxtrace_snapshot_mode;
evlist__for_each_entry(evlist, evsel) {
if (evsel->core.attr.type == intel_bts_pmu->type) {
if (intel_bts_evsel) {
pr_err("There may be only one " INTEL_BTS_PMU_NAME " event\n");
return -EINVAL;
}
evsel->core.attr.freq = 0;
evsel->core.attr.sample_period = 1;
evsel->needs_auxtrace_mmap = true;
intel_bts_evsel = evsel;
opts->full_auxtrace = true;
}
}
if (opts->auxtrace_snapshot_mode && !opts->full_auxtrace) {
pr_err("Snapshot mode (-S option) requires " INTEL_BTS_PMU_NAME " PMU event (-e " INTEL_BTS_PMU_NAME ")\n");
return -EINVAL;
}
if (!opts->full_auxtrace)
return 0;
if (opts->full_auxtrace && !perf_cpu_map__is_any_cpu_or_is_empty(cpus)) {
pr_err(INTEL_BTS_PMU_NAME " does not support per-cpu recording\n");
return -EINVAL;
}
/* Set default sizes for snapshot mode */
if (opts->auxtrace_snapshot_mode) {
if (!opts->auxtrace_snapshot_size && !opts->auxtrace_mmap_pages) {
if (privileged) {
opts->auxtrace_mmap_pages = MiB(4) / page_size;
} else {
opts->auxtrace_mmap_pages = KiB(128) / page_size;
if (opts->mmap_pages == UINT_MAX)
opts->mmap_pages = KiB(256) / page_size;
}
} else if (!opts->auxtrace_mmap_pages && !privileged &&
opts->mmap_pages == UINT_MAX) {
opts->mmap_pages = KiB(256) / page_size;
}
if (!opts->auxtrace_snapshot_size)
opts->auxtrace_snapshot_size =
opts->auxtrace_mmap_pages * (size_t)page_size;
if (!opts->auxtrace_mmap_pages) {
size_t sz = opts->auxtrace_snapshot_size;
sz = round_up(sz, page_size) / page_size;
opts->auxtrace_mmap_pages = roundup_pow_of_two(sz);
}
if (opts->auxtrace_snapshot_size >
opts->auxtrace_mmap_pages * (size_t)page_size) {
pr_err("Snapshot size %zu must not be greater than AUX area tracing mmap size %zu\n",
opts->auxtrace_snapshot_size,
opts->auxtrace_mmap_pages * (size_t)page_size);
return -EINVAL;
}
if (!opts->auxtrace_snapshot_size || !opts->auxtrace_mmap_pages) {
pr_err("Failed to calculate default snapshot size and/or AUX area tracing mmap pages\n");
return -EINVAL;
}
pr_debug2("Intel BTS snapshot size: %zu\n",
opts->auxtrace_snapshot_size);
}
/* Set default sizes for full trace mode */
if (opts->full_auxtrace && !opts->auxtrace_mmap_pages) {
if (privileged) {
opts->auxtrace_mmap_pages = MiB(4) / page_size;
} else {
opts->auxtrace_mmap_pages = KiB(128) / page_size;
if (opts->mmap_pages == UINT_MAX)
opts->mmap_pages = KiB(256) / page_size;
}
}
/* Validate auxtrace_mmap_pages */
if (opts->auxtrace_mmap_pages) {
size_t sz = opts->auxtrace_mmap_pages * (size_t)page_size;
size_t min_sz;
if (opts->auxtrace_snapshot_mode)
min_sz = KiB(4);
else
min_sz = KiB(8);
if (sz < min_sz || !is_power_of_2(sz)) {
pr_err("Invalid mmap size for Intel BTS: must be at least %zuKiB and a power of 2\n",
min_sz / 1024);
return -EINVAL;
}
}
if (intel_bts_evsel) {
/*
* To obtain the auxtrace buffer file descriptor, the auxtrace event
* must come first.
*/
evlist__to_front(evlist, intel_bts_evsel);
/*
* In the case of per-cpu mmaps, we need the CPU on the
* AUX event.
*/
if (!perf_cpu_map__is_any_cpu_or_is_empty(cpus))
evsel__set_sample_bit(intel_bts_evsel, CPU);
}
/* Add dummy event to keep tracking */
if (opts->full_auxtrace) {
struct evsel *tracking_evsel;
int err;
err = parse_event(evlist, "dummy:u");
if (err)
return err;
tracking_evsel = evlist__last(evlist);
evlist__set_tracking_event(evlist, tracking_evsel);
tracking_evsel->core.attr.freq = 0;
tracking_evsel->core.attr.sample_period = 1;
}
return 0;
}
static int intel_bts_parse_snapshot_options(struct auxtrace_record *itr,
struct record_opts *opts,
const char *str)
{
struct intel_bts_recording *btsr =
container_of(itr, struct intel_bts_recording, itr);
unsigned long long snapshot_size = 0;
char *endptr;
if (str) {
snapshot_size = strtoull(str, &endptr, 0);
if (*endptr || snapshot_size > SIZE_MAX)
return -1;
}
opts->auxtrace_snapshot_mode = true;
opts->auxtrace_snapshot_size = snapshot_size;
btsr->snapshot_size = snapshot_size;
return 0;
}
static u64 intel_bts_reference(struct auxtrace_record *itr __maybe_unused)
{
return rdtsc();
}
static int intel_bts_alloc_snapshot_refs(struct intel_bts_recording *btsr,
int idx)
{
const size_t sz = sizeof(struct intel_bts_snapshot_ref);
int cnt = btsr->snapshot_ref_cnt, new_cnt = cnt * 2;
struct intel_bts_snapshot_ref *refs;
if (!new_cnt)
new_cnt = 16;
while (new_cnt <= idx)
new_cnt *= 2;
refs = calloc(new_cnt, sz);
if (!refs)
return -ENOMEM;
memcpy(refs, btsr->snapshot_refs, cnt * sz);
btsr->snapshot_refs = refs;
btsr->snapshot_ref_cnt = new_cnt;
return 0;
}
static void intel_bts_free_snapshot_refs(struct intel_bts_recording *btsr)
{
int i;
for (i = 0; i < btsr->snapshot_ref_cnt; i++)
zfree(&btsr->snapshot_refs[i].ref_buf);
zfree(&btsr->snapshot_refs);
}
static void intel_bts_recording_free(struct auxtrace_record *itr)
{
struct intel_bts_recording *btsr =
container_of(itr, struct intel_bts_recording, itr);
intel_bts_free_snapshot_refs(btsr);
free(btsr);
}
static int intel_bts_snapshot_start(struct auxtrace_record *itr)
{
struct intel_bts_recording *btsr =
container_of(itr, struct intel_bts_recording, itr);
struct evsel *evsel;
evlist__for_each_entry(btsr->evlist, evsel) {
if (evsel->core.attr.type == btsr->intel_bts_pmu->type)
return evsel__disable(evsel);
}
return -EINVAL;
}
static int intel_bts_snapshot_finish(struct auxtrace_record *itr)
{
struct intel_bts_recording *btsr =
container_of(itr, struct intel_bts_recording, itr);
struct evsel *evsel;
evlist__for_each_entry(btsr->evlist, evsel) {
if (evsel->core.attr.type == btsr->intel_bts_pmu->type)
return evsel__enable(evsel);
}
return -EINVAL;
}
static bool intel_bts_first_wrap(u64 *data, size_t buf_size)
{
int i, a, b;
b = buf_size >> 3;
a = b - 512;
if (a < 0)
a = 0;
for (i = a; i < b; i++) {
if (data[i])
return true;
}
return false;
}
static int intel_bts_find_snapshot(struct auxtrace_record *itr, int idx,
struct auxtrace_mmap *mm, unsigned char *data,
u64 *head, u64 *old)
{
struct intel_bts_recording *btsr =
container_of(itr, struct intel_bts_recording, itr);
bool wrapped;
int err;
pr_debug3("%s: mmap index %d old head %zu new head %zu\n",
__func__, idx, (size_t)*old, (size_t)*head);
if (idx >= btsr->snapshot_ref_cnt) {
err = intel_bts_alloc_snapshot_refs(btsr, idx);
if (err)
goto out_err;
}
wrapped = btsr->snapshot_refs[idx].wrapped;
if (!wrapped && intel_bts_first_wrap((u64 *)data, mm->len)) {
btsr->snapshot_refs[idx].wrapped = true;
wrapped = true;
}
/*
* In full trace mode 'head' continually increases. However in snapshot
* mode 'head' is an offset within the buffer. Here 'old' and 'head'
* are adjusted to match the full trace case which expects that 'old' is
* always less than 'head'.
*/
if (wrapped) {
*old = *head;
*head += mm->len;
} else {
if (mm->mask)
*old &= mm->mask;
else
*old %= mm->len;
if (*old > *head)
*head += mm->len;
}
pr_debug3("%s: wrap-around %sdetected, adjusted old head %zu adjusted new head %zu\n",
__func__, wrapped ? "" : "not ", (size_t)*old, (size_t)*head);
return 0;
out_err:
pr_err("%s: failed, error %d\n", __func__, err);
return err;
}
struct auxtrace_record *intel_bts_recording_init(int *err)
{
struct perf_pmu *intel_bts_pmu = perf_pmus__find(INTEL_BTS_PMU_NAME);
struct intel_bts_recording *btsr;
if (!intel_bts_pmu)
return NULL;
if (setenv("JITDUMP_USE_ARCH_TIMESTAMP", "1", 1)) {
*err = -errno;
return NULL;
}
btsr = zalloc(sizeof(struct intel_bts_recording));
if (!btsr) {
*err = -ENOMEM;
return NULL;
}
btsr->intel_bts_pmu = intel_bts_pmu;
btsr->itr.recording_options = intel_bts_recording_options;
btsr->itr.info_priv_size = intel_bts_info_priv_size;
btsr->itr.info_fill = intel_bts_info_fill;
btsr->itr.free = intel_bts_recording_free;
btsr->itr.snapshot_start = intel_bts_snapshot_start;
btsr->itr.snapshot_finish = intel_bts_snapshot_finish;
btsr->itr.find_snapshot = intel_bts_find_snapshot;
btsr->itr.parse_snapshot_options = intel_bts_parse_snapshot_options;
btsr->itr.reference = intel_bts_reference;
btsr->itr.read_finish = auxtrace_record__read_finish;
btsr->itr.alignment = sizeof(struct branch);
return &btsr->itr;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,475 @@
// SPDX-License-Identifier: GPL-2.0
/*
* perf iostat
*
* Copyright (C) 2020, Intel Corporation
*
* Authors: Alexander Antonov <alexander.antonov@linux.intel.com>
*/
#include <api/fs/fs.h>
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/zalloc.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <regex.h>
#include "util/cpumap.h"
#include "util/debug.h"
#include "util/iostat.h"
#include "util/counts.h"
#include "path.h"
#ifndef MAX_PATH
#define MAX_PATH 1024
#endif
#define UNCORE_IIO_PMU_PATH "bus/event_source/devices/uncore_iio_%d"
#define SYSFS_UNCORE_PMU_PATH "%s/"UNCORE_IIO_PMU_PATH
#define PLATFORM_MAPPING_PATH UNCORE_IIO_PMU_PATH"/die%d"
/*
* Each metric requiries one IIO event which increments at every 4B transfer
* in corresponding direction. The formulas to compute metrics are generic:
* #EventCount * 4B / (1024 * 1024)
*/
static const char * const iostat_metrics[] = {
"Inbound Read(MB)",
"Inbound Write(MB)",
"Outbound Read(MB)",
"Outbound Write(MB)",
};
static inline int iostat_metrics_count(void)
{
return sizeof(iostat_metrics) / sizeof(char *);
}
static const char *iostat_metric_by_idx(int idx)
{
return *(iostat_metrics + idx % iostat_metrics_count());
}
struct iio_root_port {
u32 domain;
u8 bus;
u8 die;
u8 pmu_idx;
int idx;
};
struct iio_root_ports_list {
struct iio_root_port **rps;
int nr_entries;
};
static struct iio_root_ports_list *root_ports;
static void iio_root_port_show(FILE *output,
const struct iio_root_port * const rp)
{
if (output && rp)
fprintf(output, "S%d-uncore_iio_%d<%04x:%02x>\n",
rp->die, rp->pmu_idx, rp->domain, rp->bus);
}
static struct iio_root_port *iio_root_port_new(u32 domain, u8 bus,
u8 die, u8 pmu_idx)
{
struct iio_root_port *p = calloc(1, sizeof(*p));
if (p) {
p->domain = domain;
p->bus = bus;
p->die = die;
p->pmu_idx = pmu_idx;
}
return p;
}
static void iio_root_ports_list_free(struct iio_root_ports_list *list)
{
int idx;
if (list) {
for (idx = 0; idx < list->nr_entries; idx++)
zfree(&list->rps[idx]);
zfree(&list->rps);
free(list);
}
}
static struct iio_root_port *iio_root_port_find_by_notation(
const struct iio_root_ports_list * const list, u32 domain, u8 bus)
{
int idx;
struct iio_root_port *rp;
if (list) {
for (idx = 0; idx < list->nr_entries; idx++) {
rp = list->rps[idx];
if (rp && rp->domain == domain && rp->bus == bus)
return rp;
}
}
return NULL;
}
static int iio_root_ports_list_insert(struct iio_root_ports_list *list,
struct iio_root_port * const rp)
{
struct iio_root_port **tmp_buf;
if (list && rp) {
rp->idx = list->nr_entries++;
tmp_buf = realloc(list->rps,
list->nr_entries * sizeof(*list->rps));
if (!tmp_buf) {
pr_err("Failed to realloc memory\n");
return -ENOMEM;
}
tmp_buf[rp->idx] = rp;
list->rps = tmp_buf;
}
return 0;
}
static int iio_mapping(u8 pmu_idx, struct iio_root_ports_list * const list)
{
char *buf;
char path[MAX_PATH];
u32 domain;
u8 bus;
struct iio_root_port *rp;
size_t size;
int ret;
for (int die = 0; die < cpu__max_node(); die++) {
scnprintf(path, MAX_PATH, PLATFORM_MAPPING_PATH, pmu_idx, die);
if (sysfs__read_str(path, &buf, &size) < 0) {
if (pmu_idx)
goto out;
pr_err("Mode iostat is not supported\n");
return -1;
}
ret = sscanf(buf, "%04x:%02hhx", &domain, &bus);
free(buf);
if (ret != 2) {
pr_err("Invalid mapping data: iio_%d; die%d\n",
pmu_idx, die);
return -1;
}
rp = iio_root_port_new(domain, bus, die, pmu_idx);
if (!rp || iio_root_ports_list_insert(list, rp)) {
free(rp);
return -ENOMEM;
}
}
out:
return 0;
}
static u8 iio_pmu_count(void)
{
u8 pmu_idx = 0;
char path[MAX_PATH];
const char *sysfs = sysfs__mountpoint();
if (sysfs) {
for (;; pmu_idx++) {
snprintf(path, sizeof(path), SYSFS_UNCORE_PMU_PATH,
sysfs, pmu_idx);
if (access(path, F_OK) != 0)
break;
}
}
return pmu_idx;
}
static int iio_root_ports_scan(struct iio_root_ports_list **list)
{
int ret = -ENOMEM;
struct iio_root_ports_list *tmp_list;
u8 pmu_count = iio_pmu_count();
if (!pmu_count) {
pr_err("Unsupported uncore pmu configuration\n");
return -1;
}
tmp_list = calloc(1, sizeof(*tmp_list));
if (!tmp_list)
goto err;
for (u8 pmu_idx = 0; pmu_idx < pmu_count; pmu_idx++) {
ret = iio_mapping(pmu_idx, tmp_list);
if (ret)
break;
}
err:
if (!ret)
*list = tmp_list;
else
iio_root_ports_list_free(tmp_list);
return ret;
}
static int iio_root_port_parse_str(u32 *domain, u8 *bus, char *str)
{
int ret;
regex_t regex;
/*
* Expected format domain:bus:
* Valid domain range [0:ffff]
* Valid bus range [0:ff]
* Example: 0000:af, 0:3d, 01:7
*/
regcomp(&regex, "^([a-f0-9A-F]{1,}):([a-f0-9A-F]{1,2})", REG_EXTENDED);
ret = regexec(&regex, str, 0, NULL, 0);
if (ret || sscanf(str, "%08x:%02hhx", domain, bus) != 2)
pr_warning("Unrecognized root port format: %s\n"
"Please use the following format:\n"
"\t [domain]:[bus]\n"
"\t for example: 0000:3d\n", str);
regfree(&regex);
return ret;
}
static int iio_root_ports_list_filter(struct iio_root_ports_list **list,
const char *filter)
{
char *tok, *tmp, *filter_copy = NULL;
struct iio_root_port *rp;
u32 domain;
u8 bus;
int ret = -ENOMEM;
struct iio_root_ports_list *tmp_list = calloc(1, sizeof(*tmp_list));
if (!tmp_list)
goto err;
filter_copy = strdup(filter);
if (!filter_copy)
goto err;
for (tok = strtok_r(filter_copy, ",", &tmp); tok;
tok = strtok_r(NULL, ",", &tmp)) {
if (!iio_root_port_parse_str(&domain, &bus, tok)) {
rp = iio_root_port_find_by_notation(*list, domain, bus);
if (rp) {
(*list)->rps[rp->idx] = NULL;
ret = iio_root_ports_list_insert(tmp_list, rp);
if (ret) {
free(rp);
goto err;
}
} else if (!iio_root_port_find_by_notation(tmp_list,
domain, bus))
pr_warning("Root port %04x:%02x were not found\n",
domain, bus);
}
}
if (tmp_list->nr_entries == 0) {
pr_err("Requested root ports were not found\n");
ret = -EINVAL;
}
err:
iio_root_ports_list_free(*list);
if (ret)
iio_root_ports_list_free(tmp_list);
else
*list = tmp_list;
free(filter_copy);
return ret;
}
static int iostat_event_group(struct evlist *evl,
struct iio_root_ports_list *list)
{
int ret;
int idx;
const char *iostat_cmd_template =
"{uncore_iio_%x/event=0x83,umask=0x04,ch_mask=0xF,fc_mask=0x07/,\
uncore_iio_%x/event=0x83,umask=0x01,ch_mask=0xF,fc_mask=0x07/,\
uncore_iio_%x/event=0xc0,umask=0x04,ch_mask=0xF,fc_mask=0x07/,\
uncore_iio_%x/event=0xc0,umask=0x01,ch_mask=0xF,fc_mask=0x07/}";
const int len_template = strlen(iostat_cmd_template) + 1;
struct evsel *evsel = NULL;
int metrics_count = iostat_metrics_count();
char *iostat_cmd = calloc(len_template, 1);
if (!iostat_cmd)
return -ENOMEM;
for (idx = 0; idx < list->nr_entries; idx++) {
sprintf(iostat_cmd, iostat_cmd_template,
list->rps[idx]->pmu_idx, list->rps[idx]->pmu_idx,
list->rps[idx]->pmu_idx, list->rps[idx]->pmu_idx);
ret = parse_event(evl, iostat_cmd);
if (ret)
goto err;
}
evlist__for_each_entry(evl, evsel) {
evsel->priv = list->rps[evsel->core.idx / metrics_count];
}
list->nr_entries = 0;
err:
iio_root_ports_list_free(list);
free(iostat_cmd);
return ret;
}
int iostat_prepare(struct evlist *evlist, struct perf_stat_config *config)
{
if (evlist->core.nr_entries > 0) {
pr_warning("The -e and -M options are not supported."
"All chosen events/metrics will be dropped\n");
evlist__delete(evlist);
evlist = evlist__new();
if (!evlist)
return -ENOMEM;
}
config->metric_only = true;
config->aggr_mode = AGGR_GLOBAL;
return iostat_event_group(evlist, root_ports);
}
int iostat_parse(const struct option *opt, const char *str,
int unset __maybe_unused)
{
int ret;
struct perf_stat_config *config = (struct perf_stat_config *)opt->data;
ret = iio_root_ports_scan(&root_ports);
if (!ret) {
config->iostat_run = true;
if (!str)
iostat_mode = IOSTAT_RUN;
else if (!strcmp(str, "list"))
iostat_mode = IOSTAT_LIST;
else {
iostat_mode = IOSTAT_RUN;
ret = iio_root_ports_list_filter(&root_ports, str);
}
}
return ret;
}
void iostat_list(struct evlist *evlist, struct perf_stat_config *config)
{
struct evsel *evsel;
struct iio_root_port *rp = NULL;
evlist__for_each_entry(evlist, evsel) {
if (rp != evsel->priv) {
rp = evsel->priv;
iio_root_port_show(config->output, rp);
}
}
}
void iostat_release(struct evlist *evlist)
{
struct evsel *evsel;
struct iio_root_port *rp = NULL;
evlist__for_each_entry(evlist, evsel) {
if (rp != evsel->priv) {
rp = evsel->priv;
zfree(&evsel->priv);
}
}
}
void iostat_prefix(struct evlist *evlist,
struct perf_stat_config *config,
char *prefix, struct timespec *ts)
{
struct iio_root_port *rp = evlist->selected->priv;
if (rp) {
/*
* TODO: This is the incorrect format in JSON mode.
* See prepare_timestamp()
*/
if (ts)
sprintf(prefix, "%6lu.%09lu%s%04x:%02x%s",
ts->tv_sec, ts->tv_nsec,
config->csv_sep, rp->domain, rp->bus,
config->csv_sep);
else
sprintf(prefix, "%04x:%02x%s", rp->domain, rp->bus,
config->csv_sep);
}
}
void iostat_print_header_prefix(struct perf_stat_config *config)
{
if (config->csv_output)
fputs("port,", config->output);
else if (config->interval)
fprintf(config->output, "# time port ");
else
fprintf(config->output, " port ");
}
void iostat_print_metric(struct perf_stat_config *config, struct evsel *evsel,
struct perf_stat_output_ctx *out)
{
double iostat_value = 0;
u64 prev_count_val = 0;
const char *iostat_metric = iostat_metric_by_idx(evsel->core.idx);
u8 die = ((struct iio_root_port *)evsel->priv)->die;
struct perf_counts_values *count = perf_counts(evsel->counts, die, 0);
if (count && count->run && count->ena) {
if (evsel->prev_raw_counts && !out->force_header) {
struct perf_counts_values *prev_count =
perf_counts(evsel->prev_raw_counts, die, 0);
prev_count_val = prev_count->val;
prev_count->val = count->val;
}
iostat_value = (count->val - prev_count_val) /
((double) count->run / count->ena);
}
out->print_metric(config, out->ctx, METRIC_THRESHOLD_UNKNOWN, "%8.0f", iostat_metric,
iostat_value / (256 * 1024));
}
void iostat_print_counters(struct evlist *evlist,
struct perf_stat_config *config, struct timespec *ts,
char *prefix, iostat_print_counter_t print_cnt_cb, void *arg)
{
void *perf_device = NULL;
struct evsel *counter = evlist__first(evlist);
evlist__set_selected(evlist, counter);
iostat_prefix(evlist, config, prefix, ts);
fprintf(config->output, "%s", prefix);
evlist__for_each_entry(evlist, counter) {
perf_device = evlist->selected->priv;
if (perf_device && perf_device != counter->priv) {
evlist__set_selected(evlist, counter);
iostat_prefix(evlist, config, prefix, ts);
fprintf(config->output, "\n%s", prefix);
}
print_cnt_cb(config, counter, arg);
}
fputc('\n', config->output);
}
@@ -0,0 +1,105 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/types.h>
#include <linux/string.h>
#include <limits.h>
#include <stdlib.h>
#include <internal/lib.h> // page_size
#include "../../../util/machine.h"
#include "../../../util/map.h"
#include "../../../util/symbol.h"
#include <linux/ctype.h>
#include <symbol/kallsyms.h>
#if defined(__x86_64__)
struct extra_kernel_map_info {
int cnt;
int max_cnt;
struct extra_kernel_map *maps;
bool get_entry_trampolines;
u64 entry_trampoline;
};
static int add_extra_kernel_map(struct extra_kernel_map_info *mi, u64 start,
u64 end, u64 pgoff, const char *name)
{
if (mi->cnt >= mi->max_cnt) {
void *buf;
size_t sz;
mi->max_cnt = mi->max_cnt ? mi->max_cnt * 2 : 32;
sz = sizeof(struct extra_kernel_map) * mi->max_cnt;
buf = realloc(mi->maps, sz);
if (!buf)
return -1;
mi->maps = buf;
}
mi->maps[mi->cnt].start = start;
mi->maps[mi->cnt].end = end;
mi->maps[mi->cnt].pgoff = pgoff;
strlcpy(mi->maps[mi->cnt].name, name, KMAP_NAME_LEN);
mi->cnt += 1;
return 0;
}
static int find_extra_kernel_maps(void *arg, const char *name, char type,
u64 start)
{
struct extra_kernel_map_info *mi = arg;
if (!mi->entry_trampoline && kallsyms2elf_binding(type) == STB_GLOBAL &&
!strcmp(name, "_entry_trampoline")) {
mi->entry_trampoline = start;
return 0;
}
if (is_entry_trampoline(name)) {
u64 end = start + page_size;
return add_extra_kernel_map(mi, start, end, 0, name);
}
return 0;
}
int machine__create_extra_kernel_maps(struct machine *machine,
struct dso *kernel)
{
struct extra_kernel_map_info mi = { .cnt = 0, };
char filename[PATH_MAX];
int ret;
int i;
machine__get_kallsyms_filename(machine, filename, PATH_MAX);
if (symbol__restricted_filename(filename, "/proc/kallsyms"))
return 0;
ret = kallsyms__parse(filename, &mi, find_extra_kernel_maps);
if (ret)
goto out_free;
if (!mi.entry_trampoline)
goto out_free;
for (i = 0; i < mi.cnt; i++) {
struct extra_kernel_map *xm = &mi.maps[i];
xm->pgoff = mi.entry_trampoline;
ret = machine__create_extra_kernel_map(machine, kernel, xm);
if (ret)
goto out_free;
}
machine->trampolines_mapped = mi.cnt;
out_free:
free(mi.maps);
return ret;
}
#endif
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: GPL-2.0
#include "linux/string.h"
#include "util/map_symbol.h"
#include "util/mem-events.h"
#include "mem-events.h"
#define MEM_LOADS_AUX 0x8203
#define E(t, n, s, l, a) { .tag = t, .name = n, .event_name = s, .ldlat = l, .aux_event = a }
struct perf_mem_event perf_mem_events_intel[PERF_MEM_EVENTS__MAX] = {
E("ldlat-loads", "%s/mem-loads,ldlat=%u/P", "mem-loads", true, 0),
E("ldlat-stores", "%s/mem-stores/P", "mem-stores", false, 0),
E(NULL, NULL, NULL, false, 0),
};
struct perf_mem_event perf_mem_events_intel_aux[PERF_MEM_EVENTS__MAX] = {
E("ldlat-loads", "{%s/mem-loads-aux/,%s/mem-loads,ldlat=%u/}:P", "mem-loads", true, MEM_LOADS_AUX),
E("ldlat-stores", "%s/mem-stores/P", "mem-stores", false, 0),
E(NULL, NULL, NULL, false, 0),
};
struct perf_mem_event perf_mem_events_amd[PERF_MEM_EVENTS__MAX] = {
E(NULL, NULL, NULL, false, 0),
E(NULL, NULL, NULL, false, 0),
E("mem-ldst", "%s//", NULL, false, 0),
};
struct perf_mem_event perf_mem_events_amd_ldlat[PERF_MEM_EVENTS__MAX] = {
E(NULL, NULL, NULL, false, 0),
E(NULL, NULL, NULL, false, 0),
E("mem-ldst", "%s/ldlat=%u/", NULL, true, 0),
};
@@ -0,0 +1,11 @@
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _X86_MEM_EVENTS_H
#define _X86_MEM_EVENTS_H
extern struct perf_mem_event perf_mem_events_intel[PERF_MEM_EVENTS__MAX];
extern struct perf_mem_event perf_mem_events_intel_aux[PERF_MEM_EVENTS__MAX];
extern struct perf_mem_event perf_mem_events_amd[PERF_MEM_EVENTS__MAX];
extern struct perf_mem_event perf_mem_events_amd_ldlat[PERF_MEM_EVENTS__MAX];
#endif /* _X86_MEM_EVENTS_H */
+310
View File
@@ -0,0 +1,310 @@
// SPDX-License-Identifier: GPL-2.0
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <linux/stddef.h>
#include <linux/string.h>
#include <linux/perf_event.h>
#include <api/fs/fs.h>
#include <api/io_dir.h>
#include <internal/cpumap.h>
#include <errno.h>
#include "../../../util/intel-pt.h"
#include "../../../util/intel-bts.h"
#include "../../../util/pmu.h"
#include "../../../util/fncache.h"
#include "../../../util/pmus.h"
#include "mem-events.h"
#include "util/debug.h"
#include "util/env.h"
#include "util/header.h"
static bool x86__is_intel_graniterapids(void)
{
static bool checked_if_graniterapids;
static bool is_graniterapids;
if (!checked_if_graniterapids) {
const char *graniterapids_cpuid = "GenuineIntel-6-A[DE]";
char *cpuid = get_cpuid_str((struct perf_cpu){0});
is_graniterapids = cpuid && strcmp_cpuid_str(graniterapids_cpuid, cpuid) == 0;
free(cpuid);
checked_if_graniterapids = true;
}
return is_graniterapids;
}
static struct perf_cpu_map *read_sysfs_cpu_map(const char *sysfs_path)
{
struct perf_cpu_map *cpus;
char *buf = NULL;
size_t buf_len;
if (sysfs__read_str(sysfs_path, &buf, &buf_len) < 0)
return NULL;
cpus = perf_cpu_map__new(buf);
free(buf);
return cpus;
}
static int snc_nodes_per_l3_cache(void)
{
static bool checked_snc;
static int snc_nodes;
if (!checked_snc) {
struct perf_cpu_map *node_cpus =
read_sysfs_cpu_map("devices/system/node/node0/cpulist");
struct perf_cpu_map *cache_cpus =
read_sysfs_cpu_map("devices/system/cpu/cpu0/cache/index3/shared_cpu_list");
snc_nodes = perf_cpu_map__nr(cache_cpus) / perf_cpu_map__nr(node_cpus);
perf_cpu_map__put(cache_cpus);
perf_cpu_map__put(node_cpus);
checked_snc = true;
}
return snc_nodes;
}
static int num_chas(void)
{
static bool checked_chas;
static int num_chas;
if (!checked_chas) {
int fd = perf_pmu__event_source_devices_fd();
struct io_dir dir;
struct io_dirent64 *dent;
if (fd < 0)
return -1;
io_dir__init(&dir, fd);
while ((dent = io_dir__readdir(&dir)) != NULL) {
/* Note, dent->d_type will be DT_LNK and so isn't a useful filter. */
if (strstarts(dent->d_name, "uncore_cha_"))
num_chas++;
}
close(fd);
checked_chas = true;
}
return num_chas;
}
#define MAX_SNCS 6
static int uncore_cha_snc(struct perf_pmu *pmu)
{
// CHA SNC numbers are ordered correspond to the CHAs number.
unsigned int cha_num;
int num_cha, chas_per_node, cha_snc;
int snc_nodes = snc_nodes_per_l3_cache();
if (snc_nodes <= 1)
return 0;
num_cha = num_chas();
if (num_cha <= 0) {
pr_warning("Unexpected: no CHAs found\n");
return 0;
}
/* Compute SNC for PMU. */
if (sscanf(pmu->name, "uncore_cha_%u", &cha_num) != 1) {
pr_warning("Unexpected: unable to compute CHA number '%s'\n", pmu->name);
return 0;
}
chas_per_node = num_cha / snc_nodes;
cha_snc = cha_num / chas_per_node;
/* Range check cha_snc. for unexpected out of bounds. */
return cha_snc >= MAX_SNCS ? 0 : cha_snc;
}
static int uncore_imc_snc(struct perf_pmu *pmu)
{
// Compute the IMC SNC using lookup tables.
unsigned int imc_num;
int snc_nodes = snc_nodes_per_l3_cache();
const u8 snc2_map[] = {1, 1, 0, 0, 1, 1, 0, 0};
const u8 snc3_map[] = {1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2, 2};
const u8 *snc_map;
size_t snc_map_len;
switch (snc_nodes) {
case 2:
snc_map = snc2_map;
snc_map_len = ARRAY_SIZE(snc2_map);
break;
case 3:
snc_map = snc3_map;
snc_map_len = ARRAY_SIZE(snc3_map);
break;
default:
/* Error or no lookup support for SNC with >3 nodes. */
return 0;
}
/* Compute SNC for PMU. */
if (sscanf(pmu->name, "uncore_imc_%u", &imc_num) != 1) {
pr_warning("Unexpected: unable to compute IMC number '%s'\n", pmu->name);
return 0;
}
if (imc_num >= snc_map_len) {
pr_warning("Unexpected IMC %d for SNC%d mapping\n", imc_num, snc_nodes);
return 0;
}
return snc_map[imc_num];
}
static int uncore_cha_imc_compute_cpu_adjust(int pmu_snc)
{
static bool checked_cpu_adjust[MAX_SNCS];
static int cpu_adjust[MAX_SNCS];
struct perf_cpu_map *node_cpus;
char node_path[] = "devices/system/node/node0/cpulist";
/* Was adjust already computed? */
if (checked_cpu_adjust[pmu_snc])
return cpu_adjust[pmu_snc];
/* SNC0 doesn't need an adjust. */
if (pmu_snc == 0) {
cpu_adjust[0] = 0;
checked_cpu_adjust[0] = true;
return 0;
}
/*
* Use NUMA topology to compute first CPU of the NUMA node, we want to
* adjust CPU 0 to be this and similarly for other CPUs if there is >1
* socket.
*/
assert(pmu_snc >= 0 && pmu_snc <= 9);
node_path[24] += pmu_snc; // Shift node0 to be node<pmu_snc>.
node_cpus = read_sysfs_cpu_map(node_path);
cpu_adjust[pmu_snc] = perf_cpu_map__cpu(node_cpus, 0).cpu;
if (cpu_adjust[pmu_snc] < 0) {
pr_debug("Failed to read valid CPU list from <sysfs>/%s\n", node_path);
cpu_adjust[pmu_snc] = 0;
} else {
checked_cpu_adjust[pmu_snc] = true;
}
perf_cpu_map__put(node_cpus);
return cpu_adjust[pmu_snc];
}
static void gnr_uncore_cha_imc_adjust_cpumask_for_snc(struct perf_pmu *pmu, bool cha)
{
// With sub-NUMA clustering (SNC) there is a NUMA node per SNC in the
// topology. For example, a two socket graniterapids machine may be set
// up with 3-way SNC meaning there are 6 NUMA nodes that should be
// displayed with --per-node. The cpumask of the CHA and IMC PMUs
// reflects per-socket information meaning, for example, uncore_cha_60
// on a two socket graniterapids machine with 120 cores per socket will
// have a cpumask of "0,120". This cpumask needs adjusting to "40,160"
// to reflect that uncore_cha_60 is used for the 2nd SNC of each
// socket. Without the adjustment events on uncore_cha_60 will appear in
// node 0 and node 3 (in our example 2 socket 3-way set up), but with
// the adjustment they will appear in node 1 and node 4. The number of
// CHAs is typically larger than the number of cores. The CHA numbers
// are assumed to split evenly and inorder wrt core numbers. There are
// fewer memory IMC PMUs than cores and mapping is handled using lookup
// tables.
static struct perf_cpu_map *cha_adjusted[MAX_SNCS];
static struct perf_cpu_map *imc_adjusted[MAX_SNCS];
struct perf_cpu_map **adjusted = cha ? cha_adjusted : imc_adjusted;
unsigned int idx;
int pmu_snc, cpu_adjust;
struct perf_cpu cpu;
bool alloc;
// Cpus from the kernel holds first CPU of each socket. e.g. 0,120.
if (perf_cpu_map__cpu(pmu->cpus, 0).cpu != 0) {
pr_debug("Ignoring cpumask adjust for %s as unexpected first CPU\n", pmu->name);
return;
}
pmu_snc = cha ? uncore_cha_snc(pmu) : uncore_imc_snc(pmu);
if (pmu_snc == 0) {
// No adjustment necessary for the first SNC.
return;
}
alloc = adjusted[pmu_snc] == NULL;
if (alloc) {
// Hold onto the perf_cpu_map globally to avoid recomputation.
cpu_adjust = uncore_cha_imc_compute_cpu_adjust(pmu_snc);
adjusted[pmu_snc] = perf_cpu_map__empty_new(perf_cpu_map__nr(pmu->cpus));
if (!adjusted[pmu_snc])
return;
}
perf_cpu_map__for_each_cpu(cpu, idx, pmu->cpus) {
// Compute the new cpu map values or if not allocating, assert
// that they match expectations. asserts will be removed to
// avoid overhead in NDEBUG builds.
if (alloc) {
RC_CHK_ACCESS(adjusted[pmu_snc])->map[idx].cpu = cpu.cpu + cpu_adjust;
} else if (idx == 0) {
cpu_adjust = perf_cpu_map__cpu(adjusted[pmu_snc], idx).cpu - cpu.cpu;
assert(uncore_cha_imc_compute_cpu_adjust(pmu_snc) == cpu_adjust);
} else {
assert(perf_cpu_map__cpu(adjusted[pmu_snc], idx).cpu ==
cpu.cpu + cpu_adjust);
}
}
perf_cpu_map__put(pmu->cpus);
pmu->cpus = perf_cpu_map__get(adjusted[pmu_snc]);
}
void perf_pmu__arch_init(struct perf_pmu *pmu)
{
struct perf_pmu_caps *ldlat_cap;
if (!strcmp(pmu->name, INTEL_PT_PMU_NAME)) {
pmu->auxtrace = true;
pmu->selectable = true;
pmu->perf_event_attr_init_default = intel_pt_pmu_default_config;
}
if (!strcmp(pmu->name, INTEL_BTS_PMU_NAME)) {
pmu->auxtrace = true;
pmu->selectable = true;
}
if (x86__is_amd_cpu()) {
if (strcmp(pmu->name, "ibs_op"))
return;
pmu->mem_events = perf_mem_events_amd;
if (!perf_pmu__caps_parse(pmu))
return;
ldlat_cap = perf_pmu__get_cap(pmu, "ldlat");
if (!ldlat_cap || strcmp(ldlat_cap->value, "1"))
return;
perf_mem_events__loads_ldlat = 0;
pmu->mem_events = perf_mem_events_amd_ldlat;
} else {
if (pmu->is_core) {
if (perf_pmu__have_event(pmu, "mem-loads-aux"))
pmu->mem_events = perf_mem_events_intel_aux;
else
pmu->mem_events = perf_mem_events_intel;
} else if (x86__is_intel_graniterapids()) {
if (strstarts(pmu->name, "uncore_cha_"))
gnr_uncore_cha_imc_adjust_cpumask_for_snc(pmu, /*cha=*/true);
else if (strstarts(pmu->name, "uncore_imc_"))
gnr_uncore_cha_imc_adjust_cpumask_for_snc(pmu, /*cha=*/false);
}
}
}
@@ -0,0 +1,108 @@
// SPDX-License-Identifier: GPL-2.0
#include <errno.h>
#include "util/evlist.h"
#include "util/pmu.h"
#include "util/pmus.h"
#include "util/topdown.h"
#include "topdown.h"
#include "evsel.h"
// cmask=0, inv=0, pc=0, edge=0, umask=4, event=0
#define TOPDOWN_SLOTS 0x0400
/* Check whether there is a PMU which supports the perf metrics. */
bool topdown_sys_has_perf_metrics(void)
{
static bool has_perf_metrics;
static bool cached;
struct perf_pmu *pmu;
if (cached)
return has_perf_metrics;
/*
* The perf metrics feature is a core PMU feature.
* The PERF_TYPE_RAW type is the type of a core PMU.
* The slots event is only available when the core PMU
* supports the perf metrics feature.
*/
pmu = perf_pmus__find_by_type(PERF_TYPE_RAW);
if (pmu && perf_pmu__have_event(pmu, "slots"))
has_perf_metrics = true;
cached = true;
return has_perf_metrics;
}
bool arch_is_topdown_slots(const struct evsel *evsel)
{
return evsel->core.attr.type == PERF_TYPE_RAW &&
evsel->core.attr.config == TOPDOWN_SLOTS &&
evsel->core.attr.config1 == 0;
}
bool arch_is_topdown_metrics(const struct evsel *evsel)
{
// cmask=0, inv=0, pc=0, edge=0, umask=0x80-0x87, event=0
return evsel->core.attr.type == PERF_TYPE_RAW &&
(evsel->core.attr.config & 0xFFFFF8FF) == 0x8000 &&
evsel->core.attr.config1 == 0;
}
/*
* Check whether a topdown group supports sample-read.
*
* Only Topdown metric supports sample-read. The slots
* event must be the leader of the topdown group.
*/
bool arch_topdown_sample_read(struct evsel *leader)
{
struct evsel *evsel;
if (!evsel__sys_has_perf_metrics(leader))
return false;
if (!arch_is_topdown_slots(leader))
return false;
/*
* If slots event as leader event but no topdown metric events
* in group, slots event should still sample as leader.
*/
evlist__for_each_entry(leader->evlist, evsel) {
if (evsel->core.leader != leader->core.leader)
continue;
if (evsel != leader && arch_is_topdown_metrics(evsel))
return true;
}
return false;
}
/*
* Make a copy of the topdown metric event metric_event with the given index but
* change its configuration to be a topdown slots event. Copying from
* metric_event ensures modifiers are the same.
*/
int topdown_insert_slots_event(struct list_head *list, int idx, struct evsel *metric_event)
{
struct evsel *evsel = evsel__new_idx(&metric_event->core.attr, idx);
if (!evsel)
return -ENOMEM;
evsel->core.attr.config = TOPDOWN_SLOTS;
evsel->core.cpus = perf_cpu_map__get(metric_event->core.cpus);
evsel->core.pmu_cpus = perf_cpu_map__get(metric_event->core.pmu_cpus);
evsel->core.is_pmu_core = true;
evsel->pmu = metric_event->pmu;
evsel->name = strdup("slots");
evsel->precise_max = metric_event->precise_max;
evsel->sample_read = metric_event->sample_read;
evsel->weak_group = metric_event->weak_group;
evsel->bpf_counter = metric_event->bpf_counter;
evsel->retire_lat = metric_event->retire_lat;
evsel__set_leader(evsel, evsel__leader(metric_event));
list_add_tail(&evsel->core.node, list);
return 0;
}
@@ -0,0 +1,15 @@
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _TOPDOWN_H
#define _TOPDOWN_H 1
#include <stdbool.h>
struct evsel;
struct list_head;
bool topdown_sys_has_perf_metrics(void);
bool arch_is_topdown_slots(const struct evsel *evsel);
bool arch_is_topdown_metrics(const struct evsel *evsel);
int topdown_insert_slots_event(struct list_head *list, int idx, struct evsel *metric_event);
#endif
@@ -0,0 +1,93 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/types.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "../../../util/debug.h"
#include "../../../util/tsc.h"
#include "cpuid.h"
u64 rdtsc(void)
{
unsigned int low, high;
asm volatile("rdtsc" : "=a" (low), "=d" (high));
return low | ((u64)high) << 32;
}
/*
* Derive the TSC frequency in Hz from the /proc/cpuinfo, for example:
* ...
* model name : Intel(R) Xeon(R) Gold 6154 CPU @ 3.00GHz
* ...
* will return 3000000000.
*/
static u64 cpuinfo_tsc_freq(void)
{
u64 result = 0;
FILE *cpuinfo;
char *line = NULL;
size_t len = 0;
cpuinfo = fopen("/proc/cpuinfo", "r");
if (!cpuinfo) {
pr_err("Failed to read /proc/cpuinfo for TSC frequency\n");
return 0;
}
while (getline(&line, &len, cpuinfo) > 0) {
if (!strncmp(line, "model name", 10)) {
char *pos = strstr(line + 11, " @ ");
double float_result;
if (pos && sscanf(pos, " @ %lfGHz", &float_result) == 1) {
float_result *= 1000000000;
result = (u64)float_result;
goto out;
}
}
}
out:
if (result == 0)
pr_err("Failed to find TSC frequency in /proc/cpuinfo\n");
free(line);
fclose(cpuinfo);
return result;
}
u64 arch_get_tsc_freq(void)
{
unsigned int a, b, c, d, lvl;
static bool cached;
static double tsc;
char vendor[16];
if (cached)
return tsc;
cached = true;
get_cpuid_0(vendor, &lvl);
if (!strstr(vendor, "Intel"))
return 0;
/*
* Don't support Time Stamp Counter and
* Nominal Core Crystal Clock Information Leaf.
*/
if (lvl < 0x15) {
tsc = cpuinfo_tsc_freq();
return tsc;
}
cpuid(0x15, 0, &a, &b, &c, &d);
/* TSC frequency is not enumerated */
if (!a || !b || !c) {
tsc = cpuinfo_tsc_freq();
return tsc;
}
tsc = (u64)c * (u64)b / (u64)a;
return tsc;
}