Linux Perf Users
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Ian Rogers" <irogers@google.com>
Cc: linux-perf-users@vger.kernel.org
Subject: Re: [PATCH v3 08/11] perf list, jevents: Add --export-dir and --output-dir sysfs-style exporters
Date: Fri, 04 Dec 2026 01:36:30 +0000	[thread overview]
Message-ID: <sashiko-outbox-248901@kernel.org> (raw)
In-Reply-To: <20261204011029.1946921-9-irogers@google.com>

Thank you for your contribution! Sashiko AI review found 9 potential
issues to consider:
- [Medium] perf jevents: broken RISC-V SiFive mimpid expansion in
  _expand_cpuid_pattern()
- [Medium] perf jevents: regex Compat skipped in _is_literal_compat(),
  breaking ARM CMN
- [Low] perf jevents: default starting_dir in main() omits
  build-generated JSON files
- [Low] perf list: missing explicit assert.h include for new assert()
  calls
- [Low] perf list: unchecked strlist__new() and strdup() in cmd_list()
  --export-dir
- [Low] perf pmu-layer: errno clobber and zero-write loop in
  export_write_str_at()
- [Low] perf pmu-layer: export_constraint_str() drops GROUP_EVENTS
  overrides
- [Low] perf list: O((E+M)*P) PMU rescans and missing DRM/HWMON early
  exit
- [Low] perf jevents: truthiness check in _export_event_files() drops 0
  latencies
--

commit b8344fa746e0c1d020b1e268db8e70477584fd3d
Author: Ian Rogers <irogers@google.com>

perf list, jevents: Add --export-dir and --output-dir sysfs-style exporters

This commit adds two sysfs-style directory exporters for pmu-events.dir
layering: perf list --export-dir to materialize active host PMU events,
metrics, and metricgroups on disk, and jevents.py --output-dir to export
architecture JSON trees with CPUID and sysfs compat symlinks.

> diff --git a/tools/perf/builtin-list.c b/tools/perf/builtin-list.c
> index 53e1834233c87..85de0bd73e324 100644
> --- a/tools/perf/builtin-list.c
> +++ b/tools/perf/builtin-list.c
> @@ -25,9 +26,11 @@
>  #include <linux/zalloc.h>
>  #include <ctype.h>
>  #include <errno.h>
> +#include <limits.h>
>  #include <stdarg.h>
>  #include <stdio.h>
>  #include <stdlib.h>
> +#include <string.h>

[Severity: Low]
Should <assert.h> be included explicitly here for the new assert() calls in
cmd_list()?  Relying on transitive inclusion can break builds across glibc
and musl if an indirect header stops pulling it in.

[ ... ]

> +		export_ps.visited_groups = strlist__new(NULL, NULL);
> +		assert(export_ps.visited_groups);
> +		ps->visited_metrics = strlist__new(NULL, NULL);
> +		assert(ps->visited_metrics);
> +		if (unit_name)
> +			ps->pmu_glob = strdup(unit_name);
> +		else if (cputype) {
> +			const struct perf_pmu *pmu = perf_pmus__pmu_for_pmu_filter(cputype);
> +
> +			if (!pmu) {
> +				pr_err("ERROR: cputype is not supported!\n");
> +				ret = -1;
> +				goto out;
> +			}
> +			ps->pmu_glob = strdup(pmu->name);
> +		}

[Severity: Low]
What happens if strlist__new() or strdup() fails here?  Under -DNDEBUG, the
assert() calls compile out and a NULL strlist reaches
export_dir_print_metric(), causing a NULL pointer dereference in
strlist__has_entry() or strlist__add().

Similarly, an unchecked strdup() leaves ps->pmu_glob NULL on allocation
failure, which silently disables the --unit or --cputype filter and exports
all PMUs instead of returning an error.

> diff --git a/tools/perf/pmu-events/jevents.py b/tools/perf/pmu-events/jevents.py
> index fdd984c420874..ed9b2f90535a1 100755
> --- a/tools/perf/pmu-events/jevents.py
> +++ b/tools/perf/pmu-events/jevents.py

[ ... ]

> +  if event.retirement_latency_mean:
> +    _write_text_file(base + '.retire-lat-mean', str(event.retirement_latency_mean))
> +  if event.retirement_latency_min:
> +    _write_text_file(base + '.retire-lat-min', str(event.retirement_latency_min))
> +  if event.retirement_latency_max:
> +    _write_text_file(base + '.retire-lat-max', str(event.retirement_latency_max))

[Severity: Low]
Can these truthiness checks drop valid zero retirement latency values?
JsonEvent.__init__() stores numeric JSON values directly, so a value of 0
(such as RetirementLatencyMin on 24 Intel Granite Rapids events) evaluates
as false and omits the .retire-lat-* file.

Unlike pmu_layer__export_event(), which writes the sidecar whenever
has_retire_lat_min is set, omitting the file leaves the attribute missing on
disk and lets a non-zero value from a lower pmu-events.dir layer leak
through.  Checking "is not None" would preserve explicit zeros.

[ ... ]

> +def _expand_cpuid_pattern(arch: str, pattern: str) -> Sequence[str]:
> +  """Expand a mapfile.csv CPUID pattern into literal directory names."""
> +  if arch == 's390':
> +    m = re.match(r'^\^IBM\.([^.*]+)\.\*.*$', pattern)
> +    if m:
> +      return ['IBM,' + x for x in _expand_regex_fragment(m.group(1))]
> +    return []
> +
> +  if arch == 'powerpc':
> +    return _expand_regex_fragment(pattern.replace('[[:xdigit:]]{4}', '0000'))
> +
> +  xdigit_cls = '[0-9A-F]' if arch == 'x86' else '[0-9a-f]'
> +  pat = pattern
> +  if pat.endswith('-[[:xdigit:]]+'):
> +    pat = pat[:-len('-[[:xdigit:]]+')]
> +  elif pat.endswith('-0x[[:xdigit:]]+'):
> +    pat = pat[:-len('-0x[[:xdigit:]]+')]
> +  elif pat.endswith('[[:xdigit:]]+'):
> +    pat = pat[:-len('[[:xdigit:]]+')] + f'({xdigit_cls}|)'
> +  pat = pat.replace('[[:xdigit:]]', xdigit_cls)
> +  return [c for c in _expand_regex_fragment(pat) if '/' not in c]

[Severity: Medium]
Does replacing a trailing [[:xdigit:]]+ with ({xdigit_cls}|) break RISC-V
SiFive CPUID resolution?  In tools/perf/pmu-events/arch/riscv/mapfile.csv,
entries like sifive/bullet-07 use patterns with a fixed leading nibble
followed by [[:xdigit:]]+ (such as
0x489-0x8000000000000[1-9a-e]07-0x[78ac][[:xdigit:]]+).

Because [[:xdigit:]]+ requires one or more hex digits, replacing it with
zero or one digit emits invalid 1-hex-digit mimpid symlinks (such as -0x7)
and only covers 1- and 2-digit mimpids.  Real SiFive cores report
multi-nibble 32-bit mimpid values, and build_cpuid_candidates() in
pmu-layer.c only probes the full mvendorid-marchid-mimpid string and the
mvendorid-marchid prefix, so none of those symlinks will match at runtime.

> +def _is_literal_compat(compat: str) -> bool:
> +  """Return True if compat is a plain PMU identifier without regex operators."""
> +  return bool(compat) and '/' not in compat and not any(
> +      ch in compat for ch in '*+?[]()|^$\\'
> +  )

[Severity: Medium]
Will skipping regex Compat strings make exported ARM CMN definitions
unreachable at runtime?  In
tools/perf/pmu-events/arch/arm64/arm/cmn/sys/cmn.json, Compat is
"(434|436|43c|43a).*", which _is_literal_compat() rejects, so no sys/
symlink is created for the exported arm_cmn files.

Since dir_for_each_scope() in pmu-layer.c only does a literal openat() under
sys/ for pmu->id, those exported ARM CMN events and metrics can never be
loaded.  This also contradicts the commit message example showing
sys/43401 -> ../models/arm64/arm/cmn (and for literal sys Compat entries,
target_root includes the trailing /sys component).

[ ... ]

> +  default_arch_dir = os.path.join(
> +      os.path.dirname(os.path.abspath(__file__)), 'arch'
> +  )

[Severity: Low]
Does defaulting starting_dir to the clean source arch/ directory silently
omit build-generated JSON definitions?  tools/perf/pmu-events/Build
generates legacy-cache.json and the Intel, AMD Zen, and ARM64
extra-metrics.json and extra-metricgroups.json files under
$(OUTPUT)pmu-events/arch/ rather than the source tree.

Running the documented command "jevents.py --output-dir /opt/pmu-events x86
all" without a pre-built starting_dir therefore produces an overlay tree
missing all Python-generated metrics, metricgroup descriptions, and legacy
cache events.

> diff --git a/tools/perf/util/pmu-layer.c b/tools/perf/util/pmu-layer.c
> index 7ab72c8adf9cc..5e28002b0bb49 100644
> --- a/tools/perf/util/pmu-layer.c
> +++ b/tools/perf/util/pmu-layer.c

[ ... ]

> +	while (off < len) {
> +		ssize_t n = write(fd, content + off, len - off);
> +
> +		if (n < 0) {
> +			if (errno == EINTR)
> +				continue;
> +			close(fd);
> +			return -errno;
> +		}
> +		off += (size_t)n;
> +	}
> +	for (;;) {
> +		ssize_t n = write(fd, "\n", 1);
> +
> +		if (n < 0 && errno == EINTR)
> +			continue;
> +		if (n != 1) {
> +			int err = errno ? -errno : -EIO;
> +
> +			close(fd);
> +			return err;
> +		}
> +		break;
> +	}

[Severity: Low]
Can close(fd) clobber errno before returning -errno on a failed write()?
Saving errno into a local variable before close(fd), as done in the loop
below, would preserve the original write() error.

Also, the first loop spins indefinitely if write() returns 0 while
off < len, and the trailing newline loop consults errno even when n == 0,
which can return a stale errno (such as EEXIST from pmu_layer__mkdir_p())
instead of -EIO.

[ ... ]

> +static struct perf_pmu_alias *export_find_pmu_and_alias(const char *pmu_name,
> +							const char *event_name,
> +							struct perf_pmu **out_pmu)
> +{
> +	struct perf_pmu *pmu = perf_pmus__find(pmu_name);
> +	struct perf_pmu *fallback_pmu = NULL;
> +	struct perf_pmu_alias *fallback_alias = NULL;
> +	struct perf_pmu_alias *alias;
> +
> +	if (pmu) {
> +		enum pmu_kind kind = perf_pmu__kind(pmu);
> +
> +		if (kind != PERF_PMU_KIND_DRM && kind != PERF_PMU_KIND_HWMON) {

[ ... ]

> +		}
> +		pmu = NULL;
> +	}
> +
> +	while ((pmu = perf_pmus__scan(pmu)) != NULL) {

[Severity: Low]
Can this cause O((E + M) * P) PMU rescans during perf list --export-dir on
servers with many uncore, hwmon, and DRM PMUs?  For JSON uncore events where
pmu_name is the generic unit name (e.g., uncore_cha), perf_pmus__find()
misses and falls through to a full perf_pmus__scan() on every event;
likewise, when perf_pmus__find() hits a DRM or HWMON PMU, it falls through
to perf_pmus__scan() instead of returning NULL.

export_find_pmu_metric() and export_pmu_glob_matches_metric() similarly scan
all PMUs per metric, and pmu_layer__export_event() and
pmu_layer__export_metric() repeat pmu_layer__mkdir_p() and open()/close() on
the same target directory for every individual event and metric.

[ ... ]

> +static const char *export_constraint_str(enum metric_event_groups grouping)
> +{
> +	switch (grouping) {
> +	case MetricNoGroupEvents:
> +		return "NO_GROUP_EVENTS";
> +	case MetricNoGroupEventsNmi:
> +		return "NO_GROUP_EVENTS_NMI";
> +	case MetricNoGroupEventsSmt:
> +		return "NO_GROUP_EVENTS_SMT";
> +	case MetricNoGroupEventsThresholdAndNmi:
> +		return "NO_THRESHOLD_AND_NMI";
> +	case MetricGroupEvents:
> +	default:
> +		return NULL;
> +	}
> +}

[Severity: Low]
Does returning NULL for MetricGroupEvents drop explicit GROUP_EVENTS
overrides on export?  parse_constraint_str() accepts GROUP_EVENTS (or 0) to
set has_event_grouping = true with MetricGroupEvents, and
pmu_layer__export_metric() only calls export_constraint_str() when
has_event_grouping is true.

Omitting the .constraint sidecar here means a lower layer's NO_GROUP_EVENTS*
constraint will take effect again when the exported directory is re-layered.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204011029.1946921-1-irogers@google.com?part=8

  reply	other threads:[~2026-12-04  1:36 UTC|newest]

Thread overview: 23+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-04  1:10 [PATCH v3 00/11] perf pmu: Layered sysfs-style PMU event and metric directories Ian Rogers
2026-12-04  1:10 ` [PATCH v3 01/11] perf pmu: Generalize pmu_alias_info_file() and lazy single-event sysfs loading Ian Rogers
2026-12-04  1:32   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 02/11] perf pmu: Add metric and metricgroup storage on struct perf_pmu Ian Rogers
2026-12-04  1:26   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 03/11] perf pmu-layer: Introduce stateless struct pmu_layer abstraction and builtin adapter Ian Rogers
2026-12-04  1:35   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 04/11] perf pmu-layer: Add openat-based directory layer with literal CPUID/symlink lookup Ian Rogers
2026-12-04  1:35   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 05/11] perf config: Add pmu-events.dir configuration option Ian Rogers
2026-12-04  1:27   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 06/11] perf pmu: Switch alias resolution and enumeration to layered PMU stack Ian Rogers
2026-12-04  1:38   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 07/11] perf metricgroup: Route metric and metricgroup lookups through struct perf_pmu Ian Rogers
2026-12-04  1:40   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 08/11] perf list, jevents: Add --export-dir and --output-dir sysfs-style exporters Ian Rogers
2026-12-04  1:36   ` sashiko-bot [this message]
2026-12-04  1:10 ` [PATCH v3 09/11] perf jevents: Add compiled-in model and sys table iterators Ian Rogers
2026-12-04  1:10 ` [PATCH v3 10/11] perf list: Add --export-cpuid to export compiled-in CPU models Ian Rogers
2026-12-04  1:44   ` sashiko-bot
2026-12-04  1:10 ` [PATCH v3 11/11] perf tests: Add round-trip export, CPUID symlink, and pmu-events.dir overlay tests Ian Rogers
2026-12-04  1:49   ` sashiko-bot
2026-12-04  1:49 ` [PATCH v3 00/11] perf pmu: Layered sysfs-style PMU event and metric directories sashiko-bot

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=sashiko-outbox-248901@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=irogers@google.com \
    --cc=linux-perf-users@vger.kernel.org \
    --cc=sashiko-reviews@lists.linux.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox