mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 22:48:43 +00:00
228 lines
9.3 KiB
Python
228 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Own a PID-scoped tracefs instance and exact NVIDIA entry probes. No rebind/reset."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import time
|
|
|
|
# GPU argument is independently verified for these original routines. Raw args
|
|
# are retained as well; no unverified pointer chains or memory writes are used.
|
|
TRACE_ROOT = Path('/sys/kernel/tracing')
|
|
KALLSYMS_PATH = Path('/proc/kallsyms')
|
|
SYMBOLS = [
|
|
'nv_open_device', 'nv_close_device', 'rm_init_adapter', 'rm_shutdown_adapter',
|
|
'_nv000790rm', '_nv031364rm', '_nv030235rm', '_nv030241rm', '_nv033663rm',
|
|
'_nv033665rm', '_nv033300rm', '_nv033662rm', '_nv033231rm', '_nv033664rm',
|
|
'_nv033298rm', '_nv033685rm', '_nv055403rm', '_nv028309rm', '_nv028308rm',
|
|
'_nv043609rm', '_nv027753rm', '_nv027729rm', '_nv017686rm', '_nv017682rm',
|
|
'_nv016741rm', '_nv016753rm', '_nv016953rm', '_nv028470rm', '_nv043236rm',
|
|
'_nv043182rm', '_nv043215rm', '_nv027605rm', '_nv029864rm', '_nv028607rm',
|
|
]
|
|
GPU_SYMBOLS = set(SYMBOLS) - {
|
|
'nv_open_device', 'nv_close_device', 'rm_init_adapter',
|
|
'rm_shutdown_adapter', '_nv000790rm', '_nv031364rm',
|
|
}
|
|
SPECIFIC = {
|
|
'_nv016741rm': 'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8',
|
|
'_nv016753rm': 'acr385=+0x385(%si):u8 acr387=+0x387(%si):u8 acr392=+0x392(%si):u8 acr398=+0x398(%si):u8',
|
|
'_nv043236rm': 'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 image_bytes=+0x194(%si):u32 excluded=+0x198(%si):x32',
|
|
'_nv043182rm': 'lsfm190=+0x190(%si):u8 clients=+0x192(%si):u16 falcon_id=+0x608(%dx):u32 falcon_isa=+0x650(%dx):u32',
|
|
'_nv028470rm': 'falcon_isa=+0x650(%si):u32 falcon_3a7=+0x3a7(%si):u8',
|
|
'_nv027605rm': 'netlist_slot=+0x1c8(%si):u32',
|
|
'_nv029864rm': 'netlist_slot=+0x1f8(%si):u32',
|
|
'_nv055403rm': 'interval=+0x1e18(%di):u32',
|
|
}
|
|
|
|
|
|
def write(path, text):
|
|
with path.open('w') as f:
|
|
f.write(text)
|
|
|
|
|
|
def event_command(base, command):
|
|
fd = os.open(base / 'kprobe_events', os.O_WRONLY | os.O_APPEND)
|
|
try:
|
|
os.write(fd, (command + '\n').encode())
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def bindings():
|
|
r = {}
|
|
pci_root = Path('/sys/bus/pci/devices')
|
|
if not pci_root.is_dir():
|
|
return r
|
|
for d in pci_root.iterdir():
|
|
try:
|
|
if (d / 'vendor').read_text().strip() == '0x10de' and int((d / 'class').read_text(), 16) >> 16 == 3:
|
|
driver_link = d / 'driver'
|
|
r[d.name] = driver_link.resolve().name if driver_link.exists() else None
|
|
except (OSError, ValueError):
|
|
pass
|
|
return r
|
|
|
|
|
|
def live_identity(pid):
|
|
try:
|
|
s = Path(f'/proc/{pid}/stat').read_text()
|
|
rparen = s.rfind(')')
|
|
if rparen < 0:
|
|
return None
|
|
fields = s[rparen + 2:].split()
|
|
return fields[19] if len(fields) > 19 else None
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def main(argv=None):
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--pid', type=int, required=True)
|
|
p.add_argument('--output', type=Path, required=True)
|
|
p.add_argument('--timeout', type=float, default=90)
|
|
a = p.parse_args(argv)
|
|
if a.pid <= 0:
|
|
p.error('--pid must be positive')
|
|
if not math.isfinite(a.timeout) or a.timeout <= 0:
|
|
p.error('--timeout must be a finite positive number')
|
|
if os.geteuid() != 0:
|
|
raise SystemExit('run as root')
|
|
identity = live_identity(a.pid)
|
|
if identity is None:
|
|
raise SystemExit(f'selected target pid {a.pid} is gone')
|
|
|
|
out = a.output.resolve()
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
base = TRACE_ROOT
|
|
group = f'nv_rs_init_{os.getpid()}'
|
|
instance = base / 'instances' / group
|
|
added = []
|
|
errors = []
|
|
registered = []
|
|
created = False
|
|
trace_saved = False
|
|
|
|
version_path = Path('/proc/driver/nvidia/version')
|
|
try:
|
|
nvidia_version = version_path.read_text()
|
|
except OSError:
|
|
nvidia_version = None
|
|
|
|
report = {
|
|
'scope': (
|
|
'Only selected PID and inherited threads/children through event-fork. '
|
|
'Entry probes and declared read-only fields; no driver rebinding, GPU reset, '
|
|
'original memory writes, or service/persistence changes. Asynchronous kernel '
|
|
'workers not inheriting the selected PID are not covered.'
|
|
),
|
|
'pid': a.pid,
|
|
'pid_starttime': identity,
|
|
'probe_group': group,
|
|
'bindings_before': bindings(),
|
|
'clock_before': {'monotonic_ns': time.monotonic_ns(), 'realtime_ns': time.time_ns()},
|
|
'kernel': os.uname().release,
|
|
'nvidia_version': nvidia_version,
|
|
'errors': errors,
|
|
'registered': registered,
|
|
}
|
|
try:
|
|
instance.mkdir()
|
|
created = True
|
|
write(instance / 'tracing_on', '0')
|
|
write(instance / 'current_tracer', 'nop')
|
|
write(instance / 'buffer_size_kb', '8192')
|
|
write(instance / 'trace_clock', 'mono')
|
|
write(instance / 'set_event_pid', str(a.pid))
|
|
write(instance / 'options/event-fork', '1')
|
|
available = {
|
|
parts[2]
|
|
for line in KALLSYMS_PATH.read_text().splitlines()
|
|
if len(parts := line.split()) >= 4 and parts[3] == '[nvidia]'
|
|
}
|
|
for i, symbol in enumerate(SYMBOLS):
|
|
if symbol not in available:
|
|
errors.append({'symbol': symbol, 'error': 'not in current module symbol table'})
|
|
continue
|
|
name = f'e{i:02d}'
|
|
fetch = 'arg1=%di:x64 arg2=%si:x64 arg3=%dx:x64 arg4=%cx:x64 arg5=%r8:x64 arg6=%r9:x64'
|
|
if symbol in GPU_SYMBOLS:
|
|
fetch += ' gpu_id=+0xca8(%di):x32'
|
|
if symbol in SPECIFIC:
|
|
fetch += ' ' + SPECIFIC[symbol]
|
|
definition = f'p:{group}/{name} {symbol} {fetch}'
|
|
try:
|
|
event_command(base, definition)
|
|
added.append(name)
|
|
registered.append({'event': name, 'symbol': symbol, 'definition': definition})
|
|
except OSError as e:
|
|
errors.append({'symbol': symbol, 'error': str(e)})
|
|
continue
|
|
write(instance / 'events' / group / name / 'enable', '1')
|
|
if not added:
|
|
raise RuntimeError('no usable probes')
|
|
write(instance / 'tracing_on', '1')
|
|
report['ready_monotonic_ns'] = time.monotonic_ns()
|
|
(out / 'kernel-ready.json').write_text(json.dumps(report, indent=2) + '\n')
|
|
print('READY', a.pid, len(added), flush=True)
|
|
deadline = time.monotonic() + a.timeout
|
|
while live_identity(a.pid) == identity and time.monotonic() < deadline and not (out / 'stop-kernel-trace').exists():
|
|
time.sleep(0.05)
|
|
report['target_gone'] = live_identity(a.pid) != identity
|
|
report['timeout'] = time.monotonic() >= deadline
|
|
except BaseException as e:
|
|
report['failure'] = repr(e)
|
|
print('CAPTURE_ERROR', repr(e), flush=True)
|
|
finally:
|
|
if created:
|
|
try:
|
|
write(instance / 'tracing_on', '0')
|
|
except OSError as e:
|
|
errors.append({'cleanup': 'tracing_on', 'error': str(e)})
|
|
try:
|
|
trace = (instance / 'trace').read_bytes()
|
|
(out / 'kernel-trace.txt').write_bytes(trace)
|
|
report['trace_sha256'] = hashlib.sha256(trace).hexdigest()
|
|
report['trace_bytes'] = len(trace)
|
|
trace_saved = True
|
|
report['per_cpu_stats'] = {
|
|
p.parent.name: p.read_text()
|
|
for p in (instance / 'per_cpu').glob('cpu*/stats')
|
|
}
|
|
except OSError as e:
|
|
errors.append({'cleanup': 'read_trace', 'error': str(e)})
|
|
# Always disable every probe independently so kprobe removal never fails with EBUSY.
|
|
for name in added:
|
|
try:
|
|
write(instance / 'events' / group / name / 'enable', '0')
|
|
except OSError as e:
|
|
errors.append({'cleanup': f'disable:{name}', 'error': str(e)})
|
|
for name in added:
|
|
try:
|
|
event_command(base, f'-:{group}/{name}')
|
|
except OSError as e:
|
|
errors.append({'cleanup': name, 'error': str(e)})
|
|
if created:
|
|
try:
|
|
instance.rmdir()
|
|
except OSError as e:
|
|
errors.append({'cleanup': 'instance', 'error': str(e)})
|
|
try:
|
|
kprobes_text = (base / 'kprobe_events').read_text()
|
|
report['probes_removed'] = not any(group + '/' in line for line in kprobes_text.splitlines())
|
|
except OSError as e:
|
|
errors.append({'cleanup': 'verify_kprobe_events', 'error': str(e)})
|
|
report['probes_removed'] = False
|
|
report['trace_saved'] = trace_saved
|
|
report['instance_removed'] = not instance.exists()
|
|
report['bindings_after'] = bindings()
|
|
report['clock_after'] = {'monotonic_ns': time.monotonic_ns(), 'realtime_ns': time.time_ns()}
|
|
(out / 'kernel-capture.json').write_text(json.dumps(report, indent=2) + '\n')
|
|
print('CLOSED', report['probes_removed'], report['instance_removed'], flush=True)
|
|
return 0 if 'failure' not in report and report['trace_saved'] and report['probes_removed'] and report['instance_removed'] else 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|