mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
Merge pull request #153 from Solarboaters/fix/first-open-runtime-verdict
tools: distinguish runtime and diagnostic first-open outcomes
This commit is contained in:
131
tests/first-open-verdict/test_runner.py
Normal file
131
tests/first-open-verdict/test_runner.py
Normal file
@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the real first-open script with all device/process I/O replaced by fixtures."""
|
||||
import contextlib
|
||||
import errno
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / 'tools/run_hardware_first_open.py'
|
||||
sys.path.insert(0, str(ROOT / 'tools'))
|
||||
|
||||
|
||||
class FirstOpenVerdict(unittest.TestCase):
|
||||
def exercise(self, runtime=False, bringup=0, open_errno=None, restore_error=False, inventory=True):
|
||||
# No real child process, device open, sysfs access or file write is allowed.
|
||||
state = {'loaded': False, 'logs': 0, 'calls': [], 'report': None}
|
||||
node = Path('/dev/nvidia-rs-0000:ee:00.0')
|
||||
link = Path('/sys/bus/pci/devices/0000:ee:00.0/driver')
|
||||
resolve = Path.resolve
|
||||
def fake_resolve(path, *args, **kwargs):
|
||||
if path == link:
|
||||
return Path('/fake/nvidia_rs' if state['loaded'] else '/fake/nvidia')
|
||||
return resolve(path, *args, **kwargs)
|
||||
def read_text(path, *args, **kwargs):
|
||||
if str(path) == '/proc/driver/nvidia/version':
|
||||
return 'fixture stock version'
|
||||
if str(path) == '/sys/module/nvidia_rs/parameters/runtime_engines':
|
||||
return 'Y\n' if runtime else 'N\n'
|
||||
if str(path) == '/sys/module/nvidia_rs/parameters/bringup':
|
||||
return f'{bringup}\n'
|
||||
raise AssertionError(f'unexpected read: {path}')
|
||||
def read_bytes(path):
|
||||
self.assertEqual(path, ROOT / 'kernel-open/nvidia_rs.ko')
|
||||
return b'fixture module'
|
||||
def write_text(path, text, *args, **kwargs):
|
||||
if path == Path('/dev/kmsg'):
|
||||
state['marker'] = text.strip()
|
||||
return len(text)
|
||||
self.assertEqual(path, ROOT / 'reports/hardware-first-open-fixture.json')
|
||||
state['report'] = json.loads(text)
|
||||
return len(text)
|
||||
def run(command, **kwargs):
|
||||
command = list(command)
|
||||
state['calls'].append(command)
|
||||
output = ''; rc = 0
|
||||
if command[0] == 'modinfo':
|
||||
output = 'runtime_engines:runtime (bool)\n'
|
||||
elif command[0] == 'dmesg':
|
||||
state['logs'] += 1
|
||||
marker = state.get('marker')
|
||||
if marker:
|
||||
output = marker + '\n'
|
||||
if inventory:
|
||||
output += 'nvidia_rs inventory 000a00 140000a1\n'
|
||||
elif state['logs'] > 1 and inventory:
|
||||
output = 'nvidia_rs inventory 000a00 140000a1\n'
|
||||
elif command[0] == 'insmod':
|
||||
state['loaded'] = True
|
||||
elif command == ['rmmod', 'nvidia_rs']:
|
||||
state['loaded'] = False
|
||||
elif command[:2] == ['/usr/bin/python3', str(ROOT / 'tools/gpu_binding.py')]:
|
||||
self.assertIn(command[2], ('release', 'restore'))
|
||||
rc = int(restore_error and command[2] == 'restore')
|
||||
output = '{}'
|
||||
else:
|
||||
raise AssertionError(f'unexpected command: {command}')
|
||||
return subprocess.CompletedProcess(command, rc, output, '')
|
||||
def open_device(path, flags):
|
||||
self.assertEqual(path, node)
|
||||
if open_errno is not None:
|
||||
raise OSError(open_errno, 'fixture error')
|
||||
return 12345
|
||||
argv = [str(SCRIPT), '--pci', '0000:ee:00.0', '--confirm', '0000:ee:00.0', '--label', 'fixture']
|
||||
if bringup:
|
||||
argv += ['--bringup', str(bringup)]
|
||||
if runtime:
|
||||
argv += ['--module-param', 'runtime_engines=1']
|
||||
with contextlib.ExitStack() as stack:
|
||||
for target, replacement in (
|
||||
('sys.argv', argv), ('os.geteuid', lambda: 0), ('subprocess.run', run),
|
||||
('os.open', open_device), ('os.close', lambda fd: self.assertEqual(fd, 12345)),
|
||||
('pathlib.Path.read_text', read_text), ('pathlib.Path.read_bytes', read_bytes),
|
||||
('pathlib.Path.write_text', write_text), ('pathlib.Path.write_bytes', lambda *a: self.fail('unexpected write')),
|
||||
('pathlib.Path.exists', lambda path: path in (node, link)), ('pathlib.Path.resolve', fake_resolve),
|
||||
):
|
||||
stack.enter_context(patch(target, replacement))
|
||||
stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
|
||||
stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
|
||||
with self.assertRaises(SystemExit) as result:
|
||||
runpy.run_path(str(SCRIPT), run_name='__main__')
|
||||
self.assertIsNotNone(state['report'])
|
||||
self.assertIn(['rmmod', 'nvidia_rs'], state['calls'])
|
||||
self.assertEqual(state['calls'][-2][2], 'restore')
|
||||
self.assertEqual(result.exception.code, 0 if state['report']['passed'] else 1)
|
||||
return state['report']
|
||||
|
||||
def test_runtime_success_is_not_a_failure(self):
|
||||
self.assertTrue(self.exercise(runtime=True)['passed'])
|
||||
|
||||
def test_runtime_refusal_is_not_success(self):
|
||||
self.assertFalse(self.exercise(runtime=True, open_errno=errno.EOPNOTSUPP)['passed'])
|
||||
|
||||
def test_diagnostic_mode_still_expects_refusal(self):
|
||||
self.assertTrue(self.exercise(open_errno=errno.EOPNOTSUPP)['passed'])
|
||||
self.assertFalse(self.exercise()['passed'])
|
||||
|
||||
def test_positive_bringup_overrides_runtime_engines_to_expect_refusal(self):
|
||||
ok_rep = self.exercise(runtime=True, bringup=1, open_errno=errno.EOPNOTSUPP)
|
||||
self.assertTrue(ok_rep['passed'])
|
||||
self.assertTrue(ok_rep['runtime_engines'])
|
||||
self.assertFalse(ok_rep['effective_runtime_engines'])
|
||||
self.assertFalse(self.exercise(runtime=True, bringup=1)['passed'])
|
||||
|
||||
def test_other_errors_restore_and_fail(self):
|
||||
for runtime in (False, True):
|
||||
self.assertFalse(self.exercise(runtime=runtime, open_errno=errno.EIO)['passed'])
|
||||
|
||||
def test_runtime_success_does_not_bypass_other_gates(self):
|
||||
self.assertFalse(self.exercise(runtime=True, restore_error=True)['passed'])
|
||||
self.assertFalse(self.exercise(runtime=True, inventory=False)['passed'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -184,6 +184,22 @@ try:
|
||||
report["driver_after_load"] = driver()
|
||||
if report["driver_after_load"] != "nvidia_rs":
|
||||
raise RuntimeError(f"GPU is bound to {report['driver_after_load']}")
|
||||
# Read the loaded module's parameters rather than guessing from a spelling such as
|
||||
# runtime_engines=Y/on/1. Any positive bringup=N overrides runtime_engines in
|
||||
# resolve_bringup_mode(), so diagnostic mode expects EOPNOTSUPP while effective
|
||||
# runtime mode (runtime_engines=Y and bringup=0) must open successfully (#57).
|
||||
runtime = Path("/sys/module/nvidia_rs/parameters/runtime_engines").read_text().strip()
|
||||
if runtime not in ("Y", "N"):
|
||||
raise RuntimeError(f"unexpected runtime_engines value {runtime!r}")
|
||||
bringup_raw = Path("/sys/module/nvidia_rs/parameters/bringup").read_text().strip()
|
||||
try:
|
||||
bringup_param = int(bringup_raw, 0)
|
||||
except ValueError as error:
|
||||
raise RuntimeError(f"unexpected bringup value {bringup_raw!r}") from error
|
||||
if bringup_param < 0:
|
||||
raise RuntimeError(f"unexpected negative bringup value {bringup_param!r}")
|
||||
report["runtime_engines"] = runtime == "Y"
|
||||
report["effective_runtime_engines"] = (runtime == "Y") and (bringup_param == 0)
|
||||
for _ in range(50):
|
||||
if node.exists():
|
||||
break
|
||||
@ -195,7 +211,10 @@ try:
|
||||
report["first_open"] = errno.errorcode.get(error.errno, str(error.errno))
|
||||
report["first_open_errno"] = error.errno
|
||||
# Linux gives EOPNOTSUPP and ENOTSUP the same number; errorcode names it ENOTSUP.
|
||||
if report.get("first_open_errno") != errno.EOPNOTSUPP:
|
||||
expected_open = (report.get("first_open") == "succeeded"
|
||||
if report["effective_runtime_engines"]
|
||||
else report.get("first_open_errno") == errno.EOPNOTSUPP)
|
||||
if not expected_open:
|
||||
raise RuntimeError(f"unexpected first open result {report['first_open']}")
|
||||
except Exception as error: # the restore below must still run
|
||||
failure = str(error)
|
||||
|
||||
@ -50,6 +50,7 @@ optional_step test_native_compute sh tools/test_native_compute.sh
|
||||
step test_kernel_module_gate python3 tests/kernel-module-gate/test_gate_cases.py
|
||||
step test_symbol_conformance python3 tests/kernel-module-gate/test_symbol_conformance.py
|
||||
step test_kernel_archive python3 tests/kernel-module-gate/test_kernel_archive.py
|
||||
step test_first_open_verdict python3 tests/first-open-verdict/test_runner.py
|
||||
for t in gpu_firmware_owner lsf_image_owner; do step test_$t bash tools/test_$t.sh; done
|
||||
step modules make modules
|
||||
step audit make -C src/nvidia audit-codegen
|
||||
|
||||
Reference in New Issue
Block a user