All of lore.kernel.org
 help / color / mirror / Atom feed
From: Ian Rogers <irogers@google.com>
To: Peter Zijlstra <peterz@infradead.org>,
	Ingo Molnar <mingo@redhat.com>,
	 Arnaldo Carvalho de Melo <acme@kernel.org>,
	Namhyung Kim <namhyung@kernel.org>
Cc: Jiri Olsa <jolsa@kernel.org>,
	Adrian Hunter <adrian.hunter@intel.com>,
	 James Clark <james.clark@linaro.org>,
	linux-perf-users@vger.kernel.org,  linux-kernel@vger.kernel.org,
	Ian Rogers <irogers@google.com>
Subject: [PATCH 2/8] perf jevents: Support --gen-dir/--gen-manifest overlay and ignore backups
Date: Sat,  5 Dec 2026 18:11:41 -0800	[thread overview]
Message-ID: <20261206021147.3036701-3-irogers@google.com> (raw)
In-Reply-To: <20261206021147.3036701-1-irogers@google.com>

Previously jevents.py required all checked-in and generated JSON files
to live under a single starting_dir, forcing out-of-tree builds to copy
over a thousand checked-in JSON and CSV files into $(OUTPUT) before
generating pmu-events.c and pmu-events-string.c.

Refactor the repeated os.scandir()/ftw() passes and the stateful
is_leaf_dir_ignoring_sys() helper into a single in-memory map of
(arch, parents) -> {filename: path} populated by scan_arch_tree() and
emitted by process_model_files(). Grouping directly by parent directory
also avoids misfiling JSON files that sort alphabetically after a
sibling "sys" subdirectory.

Add optional --gen-dir, --gen-manifest, and repeatable --gen-file CLI
options so generated JSON files can be overlaid directly from a
separate output directory without copying checked-in sources. When
--gen-manifest or --gen-file is given, only listed files are read from
--gen-dir so stale files left over from earlier builds are ignored.
Standalone invocations without --gen-dir remain unchanged.

Harden directory and file discovery against backup and stray JSON files
that previously broke builds:
- Skip hidden entries (including Emacs ".#*.json" lockfiles) and
  directories containing dots (e.g. "skylake.bak/").
- Skip multi-dot backup JSONs (e.g. "cache.bak.json", "cache.orig.json")
  and git mergetool backups ("*_{BACKUP,BASE,LOCAL,REMOTE}_<pid>.json");
  no checked-in file under pmu-events/arch/ matches these patterns.
- Ignore leftover generated filenames (legacy-cache.json,
  extra-metrics.json, extra-metricgroups.json) in starting_dir when
  --gen-dir is supplied.
- Record JsonEvent.source_path so duplicate-event assertions report
  both conflicting file paths.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/pmu-events/jevents.py | 290 +++++++++++++++++++++----------
 1 file changed, 194 insertions(+), 96 deletions(-)

diff --git a/tools/perf/pmu-events/jevents.py b/tools/perf/pmu-events/jevents.py
index 50bfce7d07d4..f4c6edd30d08 100755
--- a/tools/perf/pmu-events/jevents.py
+++ b/tools/perf/pmu-events/jevents.py
@@ -8,6 +8,7 @@ import importlib
 import json
 import metric
 import os
+import re
 import sys
 from typing import (Callable, Dict, NamedTuple, Optional, Sequence, Set, TextIO,
                     Tuple)
@@ -91,6 +92,56 @@ _valid_keys: Set[str] = {
     'ThreadMask', 'UMask', 'Unit',
 }
 
+# Generated JSON filenames written into --gen-dir rather than starting_dir.
+# Ignored in starting_dir when --gen-dir is supplied so leftover files from
+# older in-tree builds cannot collide with freshly generated outputs.
+_GENERATED_JSON_NAMES = frozenset({
+    'legacy-cache.json',
+    'extra-metrics.json',
+    'extra-metricgroups.json',
+})
+
+# Backup files created by git mergetool end in .json and would otherwise look
+# like valid topic tables.
+_MERGETOOL_BACKUP_RE = re.compile(r'_(?:BACKUP|BASE|LOCAL|REMOTE)_\d+\.json$')
+
+
+def _is_valid_dir_name(name: str) -> bool:
+  """Return True if a directory under arch/ should be traversed."""
+  return not name.startswith('.') and '.' not in name
+
+
+def _is_valid_json_filename(name: str, skip_generated: bool = False) -> bool:
+  """Return True if filename looks like a PMU event/metric JSON table.
+
+  Skips hidden dotfiles (including Emacs '.#*' lockfiles), multi-dot backup
+  copies (e.g. 'cache.bak.json', 'cache.orig.json'), git mergetool backups,
+  and optionally generated filenames when scanning the source tree alongside
+  an explicit --gen-dir.
+  """
+  if name.startswith('.') or not name.endswith('.json'):
+    return False
+  if name.count('.') != 1:
+    return False
+  if _MERGETOOL_BACKUP_RE.search(name):
+    return False
+  if skip_generated and name in _GENERATED_JSON_NAMES:
+    return False
+  return True
+
+
+def _parents_match_model(parents: Sequence[str], model_arg: str) -> bool:
+  """Return True if directory components match the --model filter."""
+  if model_arg == 'all':
+    return True
+  models = model_arg.split(',')
+  check_depth = models[0].count('/')
+  if len(parents) <= check_depth:
+    return True
+  prefix = '/'.join(parents[:check_depth + 1])
+  return 'test' in prefix or 'common' in prefix or prefix in models
+
+
 def file_name_to_table_name(prefix: str, parents: Sequence[str],
                             dirname: str) -> str:
   """Generate a C table name from directory names."""
@@ -978,6 +1029,7 @@ class JsonEvent:
     legacy_cache_config = int(jd['LegacyCacheCode'], 0) if 'LegacyCacheCode' in jd else None
     self.name = jd['EventName'].lower() if 'EventName' in jd else None
     self.topic = ''
+    self.source_path = ''
     self.compat = jd.get('Compat')
     self.desc = fixdesc(jd.get('BriefDescription'))
     self.long_desc = fixdesc(jd.get('PublicDescription'))
@@ -1118,6 +1170,7 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]:
   metrics: list[Tuple[str, str, metric.Expression]] = []
   for event in events:
     event.topic = topic
+    event.source_path = path
     if event.metric_name and '-' not in event.metric_name:
       metrics.append((event.pmu, event.metric_name, event.metric_expr))
   updates = metric.RewriteMetricsInTermsOfOthers(metrics)
@@ -1134,24 +1187,22 @@ def read_json_events(path: str, topic: str) -> Sequence[JsonEvent]:
     _json_cache[key] = _read_json_events_impl(path, topic)
   return _json_cache[key]
 
-def preprocess_arch_std_files(archpath: str) -> None:
+def preprocess_arch_std_files(arch_std_files: Dict[str, str], arch: str) -> None:
   """Read in all architecture standard events."""
-  for item in os.scandir(archpath):
-    if not item.is_file() or not item.name.endswith('.json'):
-      continue
+  for filename, full_path in sorted(arch_std_files.items()):
     try:
-      for event in read_json_events(item.path, topic=''):
+      for event in read_json_events(full_path, topic=''):
         if event.name:
           _arch_std_events[event.name.lower()] = event
         if event.metric_name:
           _arch_std_events[event.metric_name.lower()] = event
     except Exception as e:
-        raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e
+      raise RuntimeError(f"Failure processing '{filename}' in arch '{arch}'") from e
 
 
-def add_events_table_entries(item: os.DirEntry, topic: str) -> None:
+def add_events_table_entries(path: str, topic: str) -> None:
   """Add contents of file to _pending_events table."""
-  for e in read_json_events(item.path, topic):
+  for e in read_json_events(path, topic):
     if e.name:
       _pending_events.append(e)
     if e.metric_name and not any(e.metric_name == x.metric_name and
@@ -1184,11 +1235,15 @@ def print_pending_events() -> None:
   first = True
   last_pmu = None
   last_name = None
+  last_path = None
   pmus: Set[Tuple[str, str]] = set()
   assert _args is not None
   for event in sorted(_pending_events, key=event_cmp_key):
     if last_pmu and last_pmu == event.pmu:
-      assert event.name != last_name, f"Duplicate event: {last_pmu}/{last_name}/ in {_pending_events_tblname}"
+      assert event.name != last_name, (
+          f"Duplicate event: {last_pmu}/{last_name}/ in {_pending_events_tblname} "
+          f"(from '{last_path}' and '{event.source_path}')"
+      )
     if event.pmu != last_pmu:
       if not first:
         _args.output_file.write('};\n')
@@ -1201,6 +1256,7 @@ def print_pending_events() -> None:
 
     _args.output_file.write(event.to_c_string(is_metric=False))
     last_name = event.name
+    last_path = event.source_path
   _pending_events = []
 
   _args.output_file.write(f"""
@@ -1279,24 +1335,12 @@ def get_topic(topic: str) -> str:
     return 'metrics'
   return topic.removesuffix('.json').replace('-', ' ')
 
-def preprocess_one_file(parents: Sequence[str], item: os.DirEntry) -> None:
-  if item.is_dir():
-    return
-
-  # base dir or too deep
-  level = len(parents)
-  if level == 0 or level > 4:
-    return
-
-  # Ignore other directories. If the file name does not have a .json
-  # extension, ignore it. It could be a readme.txt for instance.
-  if not item.is_file() or not item.name.endswith('.json'):
-    return
-
+def preprocess_one_file(parents: Sequence[str], filename: str, path: str) -> None:
+  """Add strings and metricgroup descriptions from a JSON file to BigCString."""
   assert _bcs is not None
-  if item.name.endswith('metricgroups.json'):
+  if filename.endswith('metricgroups.json'):
     metric_tblname = file_name_to_table_name('pmu_metrics_', parents[:-1], parents[-1])
-    with open(item.path, encoding='utf-8') as f:
+    with open(path, encoding='utf-8') as f:
       metricgroup_descriptions = json.load(f)
     for mgroup in metricgroup_descriptions:
       assert len(mgroup) > 1, parents
@@ -1307,49 +1351,30 @@ def preprocess_one_file(parents: Sequence[str], item: os.DirEntry) -> None:
       _metricgroups[metric_tblname][mgroup_bytes] = description
     return
 
-  topic = get_topic(item.name)
-  for event in read_json_events(item.path, topic):
+  topic = get_topic(filename)
+  for event in read_json_events(path, topic):
     if event.name:
       _bcs.add(event.build_bytes(is_metric=False), is_metric=False)
     if event.metric_name:
       _bcs.add(event.build_bytes(is_metric=True), is_metric=True)
 
-def process_one_file(parents: Sequence[str], item: os.DirEntry) -> None:
-  """Process a JSON file during the main walk."""
-  def is_leaf_dir_ignoring_sys(path: str) -> bool:
-    for item in os.scandir(path):
-      if item.is_dir() and item.name != 'sys':
-        return False
-    return True
 
-  # Model directories are leaves (ignoring possible sys
-  # directories). The FTW will walk into the directory next. Flush
-  # pending events and metrics and update the table names for the new
-  # model directory.
-  if item.is_dir() and is_leaf_dir_ignoring_sys(item.path):
-    print_pending_events()
-    print_pending_metrics()
-
-    global _pending_events_tblname
-    _pending_events_tblname = file_name_to_table_name('pmu_events_', parents, item.name)
-    global _pending_metrics_tblname
-    _pending_metrics_tblname = file_name_to_table_name('pmu_metrics_', parents, item.name)
-
-    if item.name == 'sys':
-      _sys_event_table_to_metric_table_mapping[_pending_events_tblname] = _pending_metrics_tblname
-    return
-
-  # base dir or too deep
-  level = len(parents)
-  if level == 0 or level > 4:
-    return
+def process_model_files(parents: Sequence[str], files: Dict[str, str]) -> None:
+  """Emit event and metric tables for one model (or sys) directory."""
+  global _pending_events_tblname
+  global _pending_metrics_tblname
+  _pending_events_tblname = file_name_to_table_name('pmu_events_', parents[:-1], parents[-1])
+  _pending_metrics_tblname = file_name_to_table_name('pmu_metrics_', parents[:-1], parents[-1])
+  if parents[-1] == 'sys':
+    _sys_event_table_to_metric_table_mapping[_pending_events_tblname] = _pending_metrics_tblname
 
-  # Ignore other directories. If the file name does not have a .json
-  # extension, ignore it. It could be a readme.txt for instance.
-  if not item.is_file() or not item.name.endswith('.json') or item.name.endswith('metricgroups.json'):
-    return
+  for filename, path in sorted(files.items()):
+    if filename.endswith('metricgroups.json'):
+      continue
+    add_events_table_entries(path, get_topic(filename))
 
-  add_events_table_entries(item, get_topic(item.name))
+  print_pending_events()
+  print_pending_metrics()
 
 
 def _metricgroup_table_fields(metric_tblname: str) -> Tuple[str, str]:
@@ -2188,25 +2213,6 @@ def main() -> None:
       return path
     raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
 
-  def ftw(path: str, parents: Sequence[str],
-          action: Callable[[Sequence[str], os.DirEntry], None]) -> None:
-    """Replicate the directory/file walking behavior of C's file tree walk."""
-    assert _args is not None
-    for item in sorted(os.scandir(path), key=lambda e: e.name):
-      if _args.model != 'all' and item.is_dir():
-        # Check if the model matches one in _args.model.
-        if len(parents) == _args.model.split(',')[0].count('/'):
-          # We're testing the correct directory.
-          item_path = '/'.join(parents) + ('/' if len(parents) > 0 else '') + item.name
-          if 'test' not in item_path and 'common' not in item_path and item_path not in _args.model.split(','):
-            continue
-      try:
-        action(parents, item)
-      except Exception as e:
-        raise RuntimeError(f'Action failure for \'{item.name}\' in {parents}') from e
-      if item.is_dir():
-        ftw(item.path, list(parents) + [item.name], action)
-
   ap = argparse.ArgumentParser()
   ap.add_argument(
       '--compress',
@@ -2218,6 +2224,34 @@ def main() -> None:
           'blocks indexed by (block_id << 16) | sub_offset (e.g. zlib,none)'
       ),
   )
+  ap.add_argument(
+      '--gen-dir',
+      type=dir_path,
+      default=None,
+      help=(
+          'Optional root directory of generated JSON files laid out in the '
+          'same <arch>/... hierarchy as starting_dir, overlaid without copying '
+          'checked-in source JSON files'
+      ),
+  )
+  ap.add_argument(
+      '--gen-manifest',
+      default=None,
+      help=(
+          'Optional file listing generated JSON paths relative to --gen-dir '
+          '(whitespace-separated); when given, only listed files are read '
+          'from --gen-dir so stale files are ignored'
+      ),
+  )
+  ap.add_argument(
+      '--gen-file',
+      action='append',
+      default=[],
+      help=(
+          'Generated JSON path relative to --gen-dir (may be repeated); '
+          'behaves like entries in --gen-manifest'
+      ),
+  )
   ap.add_argument('arch', help='Architecture name like x86')
   ap.add_argument('model', help='''Select a model such as skylake to
 reduce the code size.  Normally set to "all". For architectures like
@@ -2232,6 +2266,9 @@ such as "arm/cortex-a34".''',
   ap.add_argument('output_file', nargs='?', default=None)
   ap.add_argument('output_string_file', nargs='?', default=None)
   _args = ap.parse_args()
+  if (_args.gen_manifest or _args.gen_file) and not _args.gen_dir:
+    ap.error('--gen-manifest and --gen-file require --gen-dir')
+
   if _args.output_file:
     _args.output_file = open(_args.output_file, 'w', encoding='utf-8')
   else:
@@ -2271,7 +2308,7 @@ struct pmu_table_entry {
 """)
   archs = []
   for item in os.scandir(_args.starting_dir):
-    if not item.is_dir():
+    if not item.is_dir() or not _is_valid_dir_name(item.name):
       continue
     if item.name == _args.arch or _args.arch == 'all' or item.name == 'test' or item.name == 'common':
       archs.append(item.name)
@@ -2280,18 +2317,77 @@ struct pmu_table_entry {
     raise IOError(f'Missing architecture directory \'{_args.arch}\'')
 
   archs.sort()
-  import concurrent.futures
-  tasks = []
-  def collect_json(parents: Sequence[str], item: os.DirEntry) -> None:
-    if len(parents) == 0:
-      return
-    if item.is_file() and item.name.endswith('.json') and not item.name.endswith('metricgroups.json'):
-      tasks.append((item.path, get_topic(item.name)))
+  arch_std_files: Dict[str, Dict[str, str]] = {arch: {} for arch in archs}
+  arch_model_files: Dict[str, Dict[Tuple[str, ...], Dict[str, str]]] = {
+      arch: collections.defaultdict(dict) for arch in archs
+  }
+
+  def scan_arch_tree(arch: str, path: str, parents: Tuple[str, ...],
+                     skip_generated: bool) -> None:
+    """Populate arch_std_files and arch_model_files from a directory tree."""
+    assert _args is not None
+    for item in sorted(os.scandir(path), key=lambda e: e.name):
+      if item.is_dir():
+        if not _is_valid_dir_name(item.name):
+          continue
+        next_parents = parents + (item.name,)
+        if len(next_parents) > 4 or not _parents_match_model(next_parents, _args.model):
+          continue
+        scan_arch_tree(arch, item.path, next_parents, skip_generated)
+      elif item.is_file() and _is_valid_json_filename(item.name, skip_generated=skip_generated):
+        if len(parents) == 0:
+          arch_std_files[arch][item.name] = item.path
+        elif len(parents) <= 4:
+          arch_model_files[arch][parents][item.name] = item.path
+
+  skip_src_generated = bool(_args.gen_dir)
+  for arch in archs:
+    scan_arch_tree(arch, f'{_args.starting_dir}/{arch}', (), skip_src_generated)
+
+  if _args.gen_dir:
+    if _args.gen_manifest or _args.gen_file:
+      gen_rel_paths: list[str] = []
+      if _args.gen_manifest:
+        with open(_args.gen_manifest, encoding='utf-8') as f:
+          gen_rel_paths.extend(f.read().split())
+      gen_rel_paths.extend(_args.gen_file)
+      for raw_rel in gen_rel_paths:
+        rel_path = raw_rel.strip().replace('\\', '/')
+        if not rel_path:
+          continue
+        parts = rel_path.split('/')
+        if len(parts) < 2:
+          raise ValueError(f"Invalid generated JSON relative path '{rel_path}'")
+        arch = parts[0]
+        if arch not in arch_model_files:
+          continue
+        parents = tuple(parts[1:-1])
+        if any(not _is_valid_dir_name(p) for p in parents):
+          raise ValueError(f"Invalid generated JSON directory in '{rel_path}'")
+        filename = parts[-1]
+        if not _is_valid_json_filename(filename):
+          continue
+        full_path = os.path.join(_args.gen_dir, rel_path)
+        if not os.path.isfile(full_path):
+          raise FileNotFoundError(f"Missing generated JSON file '{full_path}'")
+        if len(parents) == 0:
+          arch_std_files[arch][filename] = full_path
+        elif len(parents) <= 4 and _parents_match_model(parents, _args.model):
+          arch_model_files[arch][parents][filename] = full_path
+    else:
+      for arch in archs:
+        gen_arch_path = f'{_args.gen_dir}/{arch}'
+        if os.path.isdir(gen_arch_path):
+          scan_arch_tree(arch, gen_arch_path, (), skip_generated=False)
 
+  import concurrent.futures
+  tasks: list[Tuple[str, str]] = []
   for arch in archs:
-    arch_path = f'{_args.starting_dir}/{arch}'
-    preprocess_arch_std_files(arch_path)
-    ftw(arch_path, [], collect_json)
+    preprocess_arch_std_files(arch_std_files[arch], arch)
+    for parents in sorted(arch_model_files[arch]):
+      for filename, full_path in sorted(arch_model_files[arch][parents].items()):
+        if not filename.endswith('metricgroups.json'):
+          tasks.append((full_path, get_topic(filename)))
 
   with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)),
                                               initializer=_init_worker,
@@ -2300,8 +2396,12 @@ struct pmu_table_entry {
       _json_cache[(path, topic)] = events
 
   for arch in archs:
-    arch_path = f'{_args.starting_dir}/{arch}'
-    ftw(arch_path, [], preprocess_one_file)
+    for parents in sorted(arch_model_files[arch]):
+      for filename, full_path in sorted(arch_model_files[arch][parents].items()):
+        try:
+          preprocess_one_file(parents, filename, full_path)
+        except Exception as e:
+          raise RuntimeError(f"Action failure for '{filename}' in {list(parents)}") from e
 
   assert _bcs is not None
   use_blocks = bool(_args.output_string_file) and _args.compress[0] != 'none'
@@ -2352,10 +2452,8 @@ struct pmu_table_entry {
 """)
     _args.output_file.write('const char *pmu_events__get_string(uint32_t offset);\n\n')
   for arch in archs:
-    arch_path = f'{_args.starting_dir}/{arch}'
-    ftw(arch_path, [], process_one_file)
-    print_pending_events()
-    print_pending_metrics()
+    for parents in sorted(arch_model_files[arch]):
+      process_model_files(parents, arch_model_files[arch][parents])
 
   print_metricgroup_tables()
   print_mapping_table(archs)
-- 
2.56.1.915.g69d5ec7298-goog


  parent reply	other threads:[~2026-12-06  2:11 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-06  2:11 [PATCH 0/8] perf build: Avoid pmu-events copies and improve build parallelism Ian Rogers
2026-12-06  2:11 ` [PATCH 1/8] perf pmu-events: Ignore backup and non-event JSON files in metric.py Ian Rogers
2026-12-06  2:22   ` sashiko-bot
2026-12-06  2:11 ` Ian Rogers [this message]
2026-12-06  2:23   ` [PATCH 2/8] perf jevents: Support --gen-dir/--gen-manifest overlay and ignore backups sashiko-bot
2026-12-06  2:11 ` [PATCH 3/8] perf build: Avoid copying pmu-events JSON files into OUTPUT Ian Rogers
2026-12-06  2:26   ` sashiko-bot
2026-12-06  2:11 ` [PATCH 4/8] perf pmu-events: Batch metric generation and scope via mapfile.csv Ian Rogers
2026-12-06  2:28   ` sashiko-bot
2026-12-06  2:11 ` [PATCH 5/8] perf build: Batch metric JSON generation in pmu-events/Build Ian Rogers
2026-12-06  2:26   ` sashiko-bot
2026-12-06  2:11 ` [PATCH 6/8] perf build: Run pmu-events tests in parallel with jevents.py Ian Rogers
2026-12-06  2:11 ` [PATCH 7/8] perf build: Depend on lib*-headers instead of archives in prepare Ian Rogers
2026-12-06  2:11 ` [PATCH 8/8] perf tests make: Only run shellcheck, mypy and pylint in pure builds Ian Rogers
2026-12-06  2:22   ` sashiko-bot
2026-12-06  2:28 ` [PATCH 0/8] perf build: Avoid pmu-events copies and improve build parallelism 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=20261206021147.3036701-3-irogers@google.com \
    --to=irogers@google.com \
    --cc=acme@kernel.org \
    --cc=adrian.hunter@intel.com \
    --cc=james.clark@linaro.org \
    --cc=jolsa@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-perf-users@vger.kernel.org \
    --cc=mingo@redhat.com \
    --cc=namhyung@kernel.org \
    --cc=peterz@infradead.org \
    /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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.