#!/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 unbind an idle GPU from the original `nvidia` driver restore unload nvidia_rs if present, rebind to `nvidia`, verify cycle 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 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 smi_row(bdf): code, out, error = smi("--query-gpu=pci.bus_id,memory.used,name", "--format=csv,noheader,nounits") if code != 0: raise SystemExit(f"nvidia-smi failed: {error or out}") for line in out.splitlines(): bus, used, name = (field.strip() for field in line.split(",", 2)) if bus.lower().endswith(bdf): return {"memory_used_mib": int(used), "name": name} return None def compute_processes(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}") return [line for line in out.splitlines() if line.split(",")[0].strip().lower().endswith(bdf)] def write(path, text): with open(path, "w") as handle: handle.write(text) def release(bdf, report): 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): 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.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) 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']}") 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() 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) raise SystemExit(0 if report.get("passed", True) else 1)