Files
nvdriver/tools/summarize_original_dispatch.py
morebrackets 1ee1639002 Address CodeRabbit follow-up findings on #276
- tools/run_live_control.py (4778363104): fail closed when /sys/bus/pci/devices
  is unavailable instead of returning an empty inventory.
- tools/summarize_original_dispatch.py (4778363107): validate required string
  'stage' field when loading sites.json.
- tools/reconcile_native_fifo_live_bootstrap.py (4778363084, 4778363095):
  include index.json and _nv028064rm.rea.json in inputs_sha256 / existence
  checks and require len(groups) == 8 before reporting eight validated groups.
- tests/offline/test_live_control_and_summary_tools.py: add unit tests for
  missing PCI sysfs dir and malformed sites.json.
2026-12-02 17:05:52 -08:00

158 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""Decode original-driver hardware breakpoint dispatch observations without dereferencing objects."""
import argparse,bisect,collections,hashlib,json,re
from pathlib import Path
def _load_kallsyms(path: Path):
syms = {}
for line in path.read_text(encoding='utf-8').splitlines():
fields = line.split()
if len(fields) >= 3:
try:
address = int(fields[0], 16)
except ValueError:
continue
if address:
syms.setdefault(address, []).append(fields[2])
return syms, sorted(syms)
def main(argv=None):
p = argparse.ArgumentParser()
p.add_argument('registers', type=Path)
p.add_argument('--kallsyms', type=Path, required=True)
p.add_argument('--sites', type=Path, required=True)
p.add_argument('--output', type=Path, required=True)
a = p.parse_args(argv)
for path in (a.registers, a.kallsyms, a.sites):
if not path.is_file():
raise SystemExit(f"missing input file: {path}")
syms, addresses = _load_kallsyms(a.kallsyms)
def resolve(addr):
i = bisect.bisect_right(addresses, addr) - 1
if i < 0:
return {'name': None, 'offset': None}
base = addresses[i]
names = syms[base]
name = next((s for s in names if re.fullmatch(r'_nv\d+rm', s)), names[0])
return {'name': name, 'offset': hex(addr - base), 'aliases': names}
try:
sites_doc = json.loads(a.sites.read_text(encoding='utf-8'))
sites = {}
for s in sites_doc['sites']:
stage = s['stage']
if not isinstance(stage, str) or not stage:
raise ValueError(f"site missing valid string 'stage': {s!r}")
sites[int(s['runtime_ip'], 16)] = s
except (OSError, UnicodeDecodeError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
raise SystemExit(f"invalid sites file {a.sites}: {error}") from error
events = []
rejected = []
gpu_groups = {}
tids = set()
for n, line in enumerate(a.registers.read_text(encoding='utf-8').splitlines(), 1):
if not line.strip():
continue
m = re.search(r'\s(\d+)/(\d+)\s+(?:(\d+\.\d+):\s+)?mem:(0x[\da-f]+):x:\s+([\da-f]+) ABI:(\d+)', line)
regs = {k: int(v, 16) for k, v in re.findall(r'\b(AX|DI|SI|DX):(0x[\da-f]+)', line)}
if not m or len(regs) != 4:
rejected.append({'line': n, 'reason': 'unparsed sample'})
continue
pid, tid, t, event_ip, ip, abi = m.groups()
ip = int(ip, 16)
if ip not in sites or int(event_ip, 16) != ip or abi != '2':
rejected.append({'line': n, 'reason': 'unexpected site/event/ABI'})
continue
g = hex(regs['DI'])
group = gpu_groups.setdefault(g, [])
tids.add(int(tid))
e = {
'sample': len(events),
'source_line': n,
'pid': int(pid),
'tid': int(tid),
'perf_time_ns': int(t.replace('.', '')) if t else None,
'stage': sites[ip]['stage'],
'site': hex(ip),
'gpu_owner': g,
'gpu_ordinal': list(gpu_groups).index(g),
'engine_owner': hex(regs['SI']),
'callback_address': hex(regs['AX']),
'callback': resolve(regs['AX']),
'load_flags': regs['DX'] if sites[ip]['stage'] in ('PreLoad', 'Load') else None,
}
events.append(e)
group.append(e)
signatures = [[(e['stage'], e['callback_address'], e['load_flags']) for e in g] for g in gpu_groups.values()]
report = {
'schema': 1,
'sample_clock': 'Recorder default perf clock; no claim of equivalence to CLOCK_MONOTONIC or timestamps from another run.',
'claim': 'Observed attempted immediate method dispatches only. No callback return status or final downstream HAL body is established by these samples. Register values are not dereferenced. GPU object identity is not a PCI BDF mapping.',
'inputs': {str(x): hashlib.sha256(x.read_bytes()).hexdigest() for x in (a.registers, a.kallsyms, a.sites)},
'samples': len(events),
'rejected': rejected,
'tids': sorted(tids),
'gpu_count': len(gpu_groups),
'stage_counts': dict(collections.Counter(e['stage'] for e in events)),
'all_gpu_sequences_identical': bool(signatures) and all(s == signatures[0] for s in signatures),
'gpu_groups': [
{
'gpu_owner': g,
'samples': len(es),
'engine_owner_count': len(set(e['engine_owner'] for e in es)),
'stage_counts': dict(collections.Counter(e['stage'] for e in es)),
'timestamp_ordered': (
all(x['perf_time_ns'] <= y['perf_time_ns'] for x, y in zip(es, es[1:]))
if all(e['perf_time_ns'] is not None for e in es)
else None
),
}
for g, es in gpu_groups.items()
],
'events': events,
}
for g in report['gpu_groups']:
es = [e for e in events if e['gpu_owner'] == g['gpu_owner']]
owners = list(dict.fromkeys(e['engine_owner'] for e in es))
for e in es:
e['engine_ordinal'] = owners.index(e['engine_owner'])
orders = {stage: [e['engine_ordinal'] for e in es if e['stage'] == stage] for stage in ('InitUnlocked', 'InitLocked', 'PreLoad', 'Load')}
g['engine_orders'] = orders
# Missing stages or missing partners cannot establish an ordering.
stage_events = {stage: [e for e in es if e['stage'] == stage] for stage in orders}
locked, preload, load = (stage_events[stage] for stage in ('InitLocked', 'PreLoad', 'Load'))
g['same_engine_set_across_locked_preload_load'] = (
set(orders['InitLocked']) == set(orders['PreLoad']) == set(orders['Load'])
if locked and preload and load else None
)
g['all_preload_before_load'] = (
preload[-1]['sample'] < load[0]['sample'] if preload and load else None
)
first_locked = {}
for event in locked:
first_locked.setdefault(event['engine_ordinal'], event['sample'])
first_unlocked = {}
for event in stage_events['InitUnlocked']:
first_unlocked.setdefault(event['engine_ordinal'], event['sample'])
order_checks = [
sample < first_locked[owner] if owner in first_locked else None
for owner, sample in first_unlocked.items()
]
# InitUnlocked is optional, so no observations of it impose no ordering constraint.
if False in order_checks:
g['unlocked_before_matching_locked'] = False
elif None in order_checks:
g['unlocked_before_matching_locked'] = None
else:
g['unlocked_before_matching_locked'] = True
a.output.parent.mkdir(parents=True, exist_ok=True)
a.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print(json.dumps({k: report[k] for k in ('samples', 'gpu_count', 'stage_counts', 'all_gpu_sequences_identical', 'tids', 'rejected')}))
return 0
if __name__ == '__main__':
raise SystemExit(main())