Files
nvdriver/tools/gpu_binding.py

219 lines
7.9 KiB
Python

#!/usr/bin/env python3
"""Release one NVIDIA GPU from the original driver and restore it afterwards.
status record every NVIDIA display function and its driver
release <bdf> unbind an idle GPU from the original `nvidia` driver
restore <bdf> unload nvidia_rs if present, rebind to `nvidia`, verify
cycle <bdf> release then restore, as a recovery rehearsal
`release` refuses a GPU that has compute processes or allocated memory, and
refuses when nvidia_rs is already loaded. `restore` is the recovery route: it
is safe to run at any time and verifies the result through nvidia-smi. Nothing
here loads the replacement driver. Run with sudo.
"""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
DEVICES = Path("/sys/bus/pci/devices")
ORIGINAL = Path("/sys/bus/pci/drivers/nvidia")
REPLACEMENT = Path("/sys/module/nvidia_rs")
def functions():
found = {}
for device in sorted(DEVICES.iterdir()):
try:
if (device / "vendor").read_text().strip() != "0x10de":
continue
if int((device / "class").read_text(), 16) >> 16 != 3:
continue
except OSError:
continue
driver = device / "driver"
found[device.name] = driver.resolve().name if driver.exists() else None
return found
BDF_RE = re.compile(r"^([0-9a-fA-F]{1,8}):([0-9a-fA-F]{2}):([0-9a-fA-F]{2})\.([0-7])$")
def normalize_bdf(text):
m = BDF_RE.fullmatch(text.strip())
if not m:
return None
dom = int(m.group(1), 16)
return f"{dom:04x}:{m.group(2).lower()}:{m.group(3).lower()}.{m.group(4)}"
def blocked_nvidia_task():
result = subprocess.run(["ps", "-eo", "stat,comm"], capture_output=True, text=True, timeout=15)
if result.returncode != 0:
detail = result.stderr.strip() or f"exit status {result.returncode}"
raise SystemExit(f"failed to inspect process list via ps ({detail}); refusing to touch /dev/nvidia*")
for line in result.stdout.splitlines():
parts = line.split(None, 1)
if len(parts) == 2 and parts[0].startswith("D") and ("nv_open_q" in parts[1] or "nvidia" in parts[1]):
return line.strip()
return None
def check_no_d_state():
task = blocked_nvidia_task()
if task:
raise SystemExit(f"D-state NVIDIA kernel task detected ({task}); refusing to touch /dev/nvidia*")
def smi(*query):
result = subprocess.run(["nvidia-smi", *query], capture_output=True, text=True, timeout=120)
return result.returncode, result.stdout.strip(), result.stderr.strip()
def parse_smi_row(out, bdf):
want = normalize_bdf(bdf)
if want is None:
return None
for line in out.splitlines():
if "," not in line:
continue
fields = [field.strip() for field in line.split(",", 2)]
if len(fields) != 3:
continue
bus, used, name = fields
if normalize_bdf(bus) == want:
try:
used_mib = int(used)
except ValueError:
used_mib = None
return {"memory_used_mib": used_mib, "memory_used_raw": used, "name": name}
return None
def smi_row(bdf, allow_error=False):
code, out, error = smi("--query-gpu=pci.bus_id,memory.used,name", "--format=csv,noheader,nounits")
if code != 0:
if allow_error:
return None
raise SystemExit(f"nvidia-smi failed: {error or out}")
return parse_smi_row(out, bdf)
def compute_processes(bdf):
want = normalize_bdf(bdf)
code, out, error = smi("--query-compute-apps=gpu_bus_id,pid,process_name",
"--format=csv,noheader")
if code != 0:
raise SystemExit(f"nvidia-smi failed: {error or out}")
matches = []
for line in out.splitlines():
if not line.strip():
continue
bus = line.split(",", 1)[0].strip()
if want is not None and normalize_bdf(bus) == want:
matches.append(line)
return matches
def write(path, text):
with open(path, "w") as handle:
handle.write(text)
def release(bdf, report):
check_no_d_state()
before = functions()
if before.get(bdf) != "nvidia":
raise SystemExit(f"{bdf} is bound to {before.get(bdf)}, not the original driver")
if REPLACEMENT.exists():
raise SystemExit("nvidia_rs is already loaded; restore first")
row = smi_row(bdf)
if row is None:
raise SystemExit(f"nvidia-smi does not list {bdf}")
busy = compute_processes(bdf)
if busy or row["memory_used_mib"] != 0:
raise SystemExit(f"{bdf} is in use: {busy or row}")
report["released"] = {"device": row, "bindings_before": before}
write(ORIGINAL / "unbind", bdf)
after = functions()
report["released"]["bindings_after"] = after
changed = {name for name in before if before[name] != after.get(name)}
if after.get(bdf) is not None or changed != {bdf}:
raise SystemExit(f"unexpected bindings after release: {after}")
def restore(bdf, report):
check_no_d_state()
steps = []
if REPLACEMENT.exists():
result = subprocess.run(["rmmod", "nvidia_rs"], capture_output=True, text=True, timeout=120)
steps.append({"rmmod_nvidia_rs": result.returncode, "stderr": result.stderr.strip()})
if result.returncode != 0:
report["restore_steps"] = steps
raise SystemExit("could not unload nvidia_rs; the GPU stays with it")
override = DEVICES / bdf / "driver_override"
if override.exists() and override.read_text().strip() not in ("", "(null)"):
write(override, "\n")
steps.append("cleared driver_override")
current = functions().get(bdf)
if current is None:
write(ORIGINAL / "bind", bdf)
steps.append("bound to nvidia")
elif current != "nvidia":
report["restore_steps"] = steps
raise SystemExit(f"{bdf} is held by {current}; unbind that driver first")
row = None
for _ in range(30):
row = smi_row(bdf, allow_error=True)
if row is not None:
break
time.sleep(1)
after = functions()
report["restored"] = {"steps": steps, "bindings": after, "device": row,
"all_original": all(driver == "nvidia" for driver in after.values())}
if after.get(bdf) != "nvidia" or row is None:
raise SystemExit(f"restore did not complete: {report['restored']}")
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("action", choices=("status", "release", "restore", "cycle"))
parser.add_argument("bdf", nargs="?")
parser.add_argument("--report")
arguments = parser.parse_args(argv)
report = {"action": arguments.action, "kernel": os.uname().release,
"replacement_loaded_before": REPLACEMENT.exists()}
if arguments.action == "status":
report["bindings"] = functions()
else:
if os.geteuid() != 0:
raise SystemExit("run with sudo")
if not arguments.bdf or not re.fullmatch(r"[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]",
arguments.bdf):
parser.error("a lowercase domain:bus:device.function is required")
report["bdf"] = arguments.bdf
failure = None
try:
if arguments.action in ("release", "cycle"):
release(arguments.bdf, report)
if arguments.action in ("restore", "cycle"):
restore(arguments.bdf, report)
except SystemExit as error:
failure = str(error)
report["error"] = failure
report["passed"] = failure is None
report["bindings_final"] = functions()
text = json.dumps(report, indent=2) + "\n"
if arguments.report:
Path(arguments.report).write_text(text)
sys.stdout.write(text)
return 0 if report.get("passed", True) else 1
if __name__ == "__main__":
raise SystemExit(main())