From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.70 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796523118; b=CIg0QCLEHPCfJtqGqKKirG8GEHLMPrOPITWrtScgVghuBUHXRF2LImn+9vb0csfbvUpK NzJ2XgNDLBV2sG78yDc7pn79WhEpA3oQfjHEeAc5aZ4zruCsADY66ujfbF+P3JqY/X4el 9WpFM0D1BHCU0nIkxNtr0f2JMqT3DGr61BGqq7pJqcmjh6/v+HG2hwjK81UfJLxTWermS DigG3O+gioimxSLZAUno/w4yWD5FdrYO0Ds9vjHiC0KIPcqeSICKTSAWsxv7H2xq/FSBv WqgeCTfIGPWOEx9kVjn+PaWLzm2hBat6OqDBIQwzN9zu0aJkazD20ecwzaNHjKAmdGQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796523118; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=seb906walUsCJhXMCtCzFBUiRA/C0DnetpIpwnjhuWw=; b=efqx0RbbIsbrCVl/H3LL0K1hkCxQ6VxtG2HrdGZSq59QZ3t5klRfQWQTPYn+kUocmlFu 0LLz3fmUJG1rXRdmF5uSS9tBO/qiOTuTDBKB2IlclxASwAElaMJzFfLXMZMLq3yUEqYHQ 9Pbh4P9f7RXLLc2c85dNsbSZvnPU4TuWgQgKDsUa0oD+s1O7O75JX/aWp+EUPCMd1NAmK Ryxr0WAAxAdhvm2u7Wg2GH9VF3qum/+hOTlVIvYXR7dHSS7xlytUYdgNaORqm/2ThNlNM PfkqEMl6ZW02QCtHAJggMh4KDAxwmrpuN6criwo+nVDnZt7jroswR3GJeMM1eYcl1Nw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Cq210Yhp; arc=none smtp.remote-ip=74.125.82.70 Received: from mail-dl1-f70.google.com (mail-dl1-f70.google.com [74.125.82.70]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CFBE2606A330 for ; Sun, 6 Dec 2026 02:11:57 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org CFBE2606A330 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Cq210Yhp Received: by mail-dl1-f70.google.com with SMTP id a92af1059eb24-139b62317d0so7221557c88.0 for ; Sat, 05 Dec 2026 18:11:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1796523117; x=1797127917; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=seb906walUsCJhXMCtCzFBUiRA/C0DnetpIpwnjhuWw=; b=Cq210YhpkQB6dDm/KTVOrs5UarQ1GcY3yr8GWeYXjGLu35UcRiZzR5LIMLSGAG3TEz uW6a6FC16DuQSEHxa0OnzTAMwwfzcjcFc7jW1LSCDRzWyNH51QPqrXfG4L0dRB3xQCIp nU+/ATBA2P+/KYErWq2e4FT+lfmLIZVG5GtKlMAqUPsenSBUvCCMYV3x2XxC+dhOrP95 +t42f779n7yW2zzHODwc5q9vRuGaxCgCtQI/j2SY8XJEn0MtvjZpDHYN5qGFKbIUOsa4 NRC77r9jYOXMdDnQjvYPMIgcQ7yoIoRw5g9xypliLqzVmoXAoMPxDXxESVlrqnihXcDE tJMw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796523117; x=1797127917; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=seb906walUsCJhXMCtCzFBUiRA/C0DnetpIpwnjhuWw=; b=IhIL3I6ER1h82HCjDH8trlzS7EAPw3RMwR/8lB9kUdZHtwPzwPej4zTyhDIzOXD4f/ m/+GJZstkJehaXaenpQPGnZcrxC4kFMo2AIH8zQAkBx+FI5Uv7vabowqscxGpOz3TJg8 dX0aR4rtFQ1EToK+M15gByM+CtPnHrdmxspWuq0pso8JFtdyzkRnbv+xzP4t8cs56eBa VsjrslmCFejSgWvKRu4G6Myl0tQUuxosmakr4B5SYmapcmsaBH+wFME5lquE9+xCXlJQ 500SdUKyQW0arBI4YOFbhTQylUjr9zkID3LFu8VrchHA6SqG/H6q8aDViUEEX/mPdxXg mBBQ== X-Forwarded-Encrypted: i=1; AL+hErEZlT2hsPi+gSwwEeDvmaKoQIFHkyVfJoJw/dyq+6aa9KxSrc42A+z4+PkAlzqpzMcJzajlyV8HSRul0lU=@vger.kernel.org X-Gm-Message-State: APuU4Z/e//JCV9bj41vggQt0c560/nAmkYLqvDfa8bIwftOlS2BpBzFU 8QLIUCsTdamyxQv8EhHbLBsPKaGFVnrZA1esq8RKnrJaFXMAfn/ESQkASTOppokEXRY9lO5qKaG 1J2N30FFytQ== X-Received: from dled8-n1.prod.google.com ([2002:a05:701b:42c8:10b0:1a0:8cef:34d5]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:b1d1:20b0:1b5:8a69:cc65 with SMTP id a92af1059eb24-1b5d705c400mr6254969c88.4.1796523116610; Sat, 05 Dec 2026 18:11:56 -0800 (PST) Date: Sat, 5 Dec 2026 18:11:41 -0800 In-Reply-To: <20261206021147.3036701-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261206021147.3036701-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.915.g69d5ec7298-goog Message-ID: <20261206021147.3036701-3-irogers@google.com> Subject: [PATCH 2/8] perf jevents: Support --gen-dir/--gen-manifest overlay and ignore backups From: Ian Rogers To: Peter Zijlstra , Ingo Molnar , Arnaldo Carvalho de Melo , Namhyung Kim Cc: Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org, Ian Rogers Content-Type: text/plain; charset="UTF-8" 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}_.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 --- 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 /... 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