interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

CUDA++ swap command, one way and back

merged ac6f2aacfd83f942 #3 · opened 2026-10-22 04:51 UTC · closed 2026-10-22 04:51 UTC · merged 2026-10-22 04:51 UTC

Imported from GitHub aien-dev/CUDApp#3, by drakestapleton

Base 2b4b2b14f1c67473b80878d2eff73b32b3522d54 · Head 27b46ccda8a82a33b4f290fc1526e13495fedc99

Merged on GitHub as 4ccf9b613b3c89646784dd17b0f7e4141d355db9; reachable from main 21d8de285f713adf09e0d6ba6db2b37139d0674e (observed 2026-11-18T16:38:31Z)

drakestapleton wrote on 2026-10-22 04:51 UTC

Host test tests/swap/test_swap_cli.sh after rebase onto main: 54 passed, 0 failed. Dry run by default. Does not reboot. libcuda.so.1 is not in this commit.

Apply it

git checkout -b patch-ac6f2aacfd83f942 2b4b2b14f1c67473b80878d2eff73b32b3522d54
curl -fsSL https://interplane.io/drakestapleton/CUDApp/patches/ac6f2aacfd83f942.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/CUDApp
3
27b46ccda8a82a33b4f290fc1526e13495fedc99
{"kind":"github-import","owner":"aien-dev","repo":"CUDApp","number":3,"url":"https://github.com/aien-dev/CUDApp/pull/3","export_sha256":"0aafd51b77ff5776d6baaf9b88b48c8b36a6e27c8d829ae8ded561b71712b17a","imported_utc":"2026-11-18T16:38:31Z"}

Changes

diff --git a/swap/cudapp b/swap/cudapp
new file mode 100755
index 00000000..5e68e4dc
--- /dev/null
+++ b/swap/cudapp
@@ -0,0 +1,239 @@
+#!/bin/bash
+# SPDX-License-Identifier: MIT
+# cudapp: swap NVIDIA's CUDA stack for CUDA++ and back, one command each way.
+#
+#   cudapp swap status            what is installed, what is loaded, what the loader finds, who holds the GPU
+#   cudapp swap user   [--yes]    user space: programs load CUDA++'s libcuda.so.1 instead of NVIDIA's
+#   cudapp swap kernel [--yes]    kernel: NVIDIA's modules held back, AIEN's aien_gpu driver loads (next boot)
+#   cudapp swap all    [--yes]    both
+#   cudapp swap back   [--yes]    NVIDIA's stack exactly as it was (every touched file checked by SHA-256)
+#   cudapp run CMD...             one program on CUDA++'s libcuda.so.1, nothing on the system changed
+#
+# Without --yes every level is a dry run: it checks, prints what it would change, and changes nothing.
+# Every file it changes is copied first into /var/lib/cudapp-swap/backup-<UTC>-<level>/ with a manifest of
+# path, state and SHA-256; `back` copies them back and checks every hash. NVIDIA's own files are never edited or
+# removed: the user level only adds a library directory the loader searches first, the kernel level only adds a
+# hold-back file and our module. It never reboots unless --reboot is given.
+#
+# Exit codes: 0 done (or dry run printed), 1 failed (back: a hash did not match), 2 usage, 3 refused by a check.
+# docs/SWAP.md has the details and the receipts.
+set -u
+ROOT=${CUDAPP_ROOT:-}
+STATE=$ROOT/var/lib/cudapp-swap
+SELF_DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
+LIB_SRC=${CUDAPP_LIB:-$SELF_DIR/../build/swap/libcuda.so.1}
+DRIVER_SRC=${CUDAPP_DRIVER_SRC:-$HOME/workspace/aienos-own-gpu-driver/native/linux/aien-gpu}
+KVER=$(uname -r)
+KDIR=${CUDAPP_KDIR:-/lib/modules/$KVER/build}
+
+OUR_LIBDIR=/usr/lib/cudapp
+LDCONF=/etc/ld.so.conf.d/00000-cudapp-swap.conf   # sorts before every other entry in C and UTF-8 collation
+LDCACHE=/etc/ld.so.cache
+MODCONF=/etc/modprobe.d/cudapp-swap-kernel.conf
+MODLOAD=/etc/modules-load.d/cudapp-aien-gpu.conf
+MODDIR=/lib/modules/$KVER/updates/cudapp
+INITRD=/boot/initrd.img-$KVER
+NV_MODULES="nvidia nvidia_uvm nvidia_modeset nvidia_drm"
+
+YES=0; REBOOT=0; HOLDERS_OK=0
+die()    { echo "cudapp: $*" >&2; exit 1; }
+refuse() { echo "REFUSED: $*" >&2; exit 3; }
+usage()  { sed -n '3,9p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
+sha()    { if [ -e "$1" ] || [ -L "$1" ]; then sha256sum < "$1" | cut -d' ' -f1; else echo -; fi; }
+
+# ---------------------------------------------------------------- facts
+gpu_ids() { # prints "vendor:device" of every NVIDIA PCI function
+    local d
+    for d in "$ROOT"/sys/bus/pci/devices/*; do
+        [ -r "$d/vendor" ] || continue
+        [ "$(cat "$d/vendor")" = 0x10de ] || continue
+        echo "10de:$(sed 's/^0x//' "$d/device")"
+    done
+}
+is_gb10()       { gpu_ids | grep -qx "10de:2e12"; }
+nv_version()    { cat "$ROOT/sys/module/nvidia/version" 2>/dev/null || echo "not loaded"; }
+secure_boot()   { local s; s=$(mokutil --sb-state 2>/dev/null); case $s in *enabled*) echo enabled;; *disabled*) echo disabled;; *) echo unknown;; esac; }
+holders()       { fuser "$ROOT"/dev/nvidia* 2>/dev/null | tr -s ' :' '\n' | grep -E '^[0-9]+$' | sort -un | tr '\n' ' '; }
+free_mb()       { df -Pm "${ROOT:-/}" 2>/dev/null | awk 'NR==2{print $4}'; }
+loader_choice() { # which libcuda.so.1 the dynamic loader finds first
+    if [ -n "$ROOT" ]; then
+        if [ -f "$ROOT$LDCONF" ] && [ -e "$ROOT$OUR_LIBDIR/libcuda.so.1" ]; then echo "$OUR_LIBDIR/libcuda.so.1"; return; fi
+        echo "/usr/lib/aarch64-linux-gnu/libcuda.so.1"; return
+    fi
+    ldconfig -p 2>/dev/null | awk '$1=="libcuda.so.1"{print $NF; exit}'
+}
+user_swapped()   { [ -f "$ROOT$LDCONF" ]; }
+kernel_staged()  { [ -f "$ROOT$MODCONF" ]; }
+nv_in_initramfs(){ lsinitramfs "$ROOT$INITRD" 2>/dev/null | grep -qE '/nvidia(_uvm|_modeset|_drm)?\.ko'; }
+
+status() {
+    local ids; ids=$(gpu_ids | tr '\n' ' ')
+    if is_gb10; then echo "GPU: NVIDIA GB10 (10de:2e12)"; else echo "GPU: ${ids:-no NVIDIA GPU found} (not a GB10)"; fi
+    echo "NVIDIA kernel driver: $(nv_version)"
+    echo "Secure Boot: $(secure_boot)"
+    echo "free disk: $(free_mb) MB"
+    local h; h=$(holders); echo "holding /dev/nvidia*: ${h:-nobody}"
+    local c; c=$(loader_choice)
+    case $c in *cudapp*) echo "libcuda.so.1: CUDA++ ($c)";; "") echo "libcuda.so.1: none found";; *) echo "libcuda.so.1: NVIDIA ($c)";; esac
+    if user_swapped; then echo "user level: SWAPPED (CUDA++ libcuda.so.1 first in the loader's search)"; else echo "user level: NVIDIA"; fi
+    if kernel_staged; then
+        if [ -d "$ROOT/sys/module/aien_gpu" ] && [ ! -d "$ROOT/sys/module/nvidia" ]; then echo "kernel level: SWAPPED (aien_gpu loaded, NVIDIA held back)"
+        else echo "kernel level: STAGED (takes effect at the next boot)"; fi
+    else echo "kernel level: NVIDIA"; fi
+    local b; b=$(ls -d "$STATE"/backup-* 2>/dev/null | tr '\n' ' '); echo "backups: ${b:-none}"
+}
+
+# ---------------------------------------------------------------- backup + restore
+BK=""
+backup_begin() { # $1 = level
+    BK=$STATE/backup-$(date -u +%Y%m%dT%H%M%SZ)-$1
+    mkdir -p "$BK/files" || die "cannot create $BK"
+    : > "$BK/manifest.tsv"
+}
+backup_file() { # $1 = path (system path, without ROOT): copy + record state and hash before we touch it
+    local p=$1 f=$ROOT$1
+    grep -q "^$p	" "$BK/manifest.tsv" 2>/dev/null && return 0
+    if [ -L "$f" ]; then
+        printf '%s\tlink\t%s\n' "$p" "$(readlink "$f")" >> "$BK/manifest.tsv"
+    elif [ -e "$f" ]; then
+        mkdir -p "$BK/files$(dirname "$p")"; cp -p "$f" "$BK/files$p" || die "backup of $p failed"
+        printf '%s\tfile\t%s\n' "$p" "$(sha "$f")" >> "$BK/manifest.tsv"
+    else
+        printf '%s\tabsent\t-\n' "$p" >> "$BK/manifest.tsv"
+    fi
+}
+backup_done() { echo applied > "$BK/APPLIED"; echo "backup: $BK ($(wc -l < "$BK/manifest.tsv") files recorded)"; }
+
+restore_one() { # $1 = backup dir; restores and checks; prints MISMATCH lines; returns count of mismatches
+    local b=$1 bad=0 p kind val f
+    while IFS=$'\t' read -r p kind val; do
+        f=$ROOT$p
+        case $kind in
+            absent) rm -f "$f"
+                    if [ -e "$f" ] || [ -L "$f" ]; then echo "MISMATCH $p: still present"; bad=$((bad+1)); fi ;;
+            link)   rm -f "$f"; ln -s "$val" "$f"
+                    [ "$(readlink "$f")" = "$val" ] || { echo "MISMATCH $p: link"; bad=$((bad+1)); } ;;
+            file)   mkdir -p "$(dirname "$f")"; rm -f "$f"; cp -p "$b/files$p" "$f"
+                    [ "$(sha "$f")" = "$val" ] || { echo "MISMATCH $p: sha256 $(sha "$f") != recorded $val"; bad=$((bad+1)); } ;;
+        esac
+    done < <(tac "$b/manifest.tsv")
+    rmdir "$ROOT$OUR_LIBDIR" "$ROOT$MODDIR" 2>/dev/null   # only the directories this tool creates, and only if empty
+    return $bad
+}
+
+# ---------------------------------------------------------------- levels
+plan() { if [ $YES -eq 1 ]; then echo "  * $*"; else echo "  - would: $*"; fi; }
+
+user_level() {
+    echo "== user level: CUDA++ libcuda.so.1 replaces NVIDIA's for every program the loader starts"
+    [ -f "$LIB_SRC" ] || refuse "CUDA++ libcuda.so.1 not built at $LIB_SRC (run: make libcuda)"
+    user_swapped && { echo "already swapped ($LDCONF present); nothing to do"; return 0; }
+    plan "install $LIB_SRC as $OUR_LIBDIR/libcuda.so.1 (sha256 $(sha "$LIB_SRC" | cut -c1-16))"
+    plan "write $LDCONF -> $OUR_LIBDIR, so the loader searches it before $(loader_choice | xargs -r dirname)"
+    plan "run ldconfig (rewrites $LDCACHE; the old one is kept in the backup)"
+    echo "  NVIDIA's libcuda files stay installed and unchanged; 'cudapp swap back' restores the old search order."
+    [ $YES -eq 1 ] || return 0
+    backup_begin user
+    backup_file "$OUR_LIBDIR/libcuda.so.1"; backup_file "$LDCONF"; backup_file "$LDCACHE"
+    mkdir -p "$ROOT$OUR_LIBDIR" && install -m 0755 "$LIB_SRC" "$ROOT$OUR_LIBDIR/libcuda.so.1" || die "install failed"
+    echo "$OUR_LIBDIR" > "$ROOT$LDCONF"
+    ldconfig ${ROOT:+-r "$ROOT"} || die "ldconfig failed"
+    backup_done
+    local c; c=$(loader_choice)
+    case $c in *cudapp*) echo "loader now finds: $c";; *) echo "loader still finds $c: restoring"; restore_one "$BK"; mv "$BK" "$BK.undone"; die "swap did not take";; esac
+}
+
+kernel_level() {
+    echo "== kernel level: AIEN's aien_gpu driver (ledger L332) instead of NVIDIA's open kernel modules"
+    is_gb10 || refuse "no GB10 here (found: $(gpu_ids | tr '\n' ' ')); aien_gpu drives the GB10 (10de:2e12) only"
+    local sb; sb=$(secure_boot)
+    [ "$sb" = enabled ] && refuse "Secure Boot is enabled: the kernel would refuse the unsigned aien_gpu module and boot with no GPU driver. Disable Secure Boot or enrol a signing key first."
+    [ -f "$DRIVER_SRC/Kbuild" ] || refuse "aien_gpu source not found at $DRIVER_SRC (set CUDAPP_DRIVER_SRC)"
+    [ -d "$KDIR" ] || refuse "kernel headers for $KVER not found at $KDIR (install linux-headers-$KVER)"
+    local h; h=$(holders)
+    if [ -n "$h" ]; then
+        echo "  processes holding /dev/nvidia* (they lose the GPU at the reboot): $h"
+        [ $YES -eq 1 ] && [ $HOLDERS_OK -eq 0 ] && refuse "processes hold /dev/nvidia*: $h. Stop them (or pass --holders-ok to stage the switch for the next boot anyway)."
+    fi
+    local need=$(( $(stat -c %s "$ROOT$INITRD" 2>/dev/null || echo 0) / 1048576 * 2 + 64 ))
+    [ "$(free_mb)" -ge "$need" ] 2>/dev/null || refuse "not enough free disk: need $need MB for the module and the initramfs backup, have $(free_mb) MB"
+    plan "build aien_gpu.ko from $DRIVER_SRC for kernel $KVER and install it as $MODDIR/aien_gpu.ko"
+    plan "write $MODCONF: blacklist + 'install <m> /bin/false' for $NV_MODULES (nothing loads them, not even an explicit modprobe)"
+    plan "write $MODLOAD: load aien_gpu at boot (options aien_gpu allow_bind=1)"
+    plan "run depmod -a $KVER (modules.* files are kept in the backup)"
+    if nv_in_initramfs; then plan "run update-initramfs -u -k $KVER (NVIDIA modules are in $INITRD; the old initramfs is kept in the backup)"
+    else echo "  initramfs: no NVIDIA module in $INITRD, the hold-back file is enough (not rebuilt)"; fi
+    echo "  takes effect at the next reboot: NVIDIA's modules then stay unloaded and aien_gpu owns the GB10."
+    echo "  Why a reboot: unloading nvidia_modeset can hang on this machine (L158), so the switch never unloads a live driver."
+    echo "  NVIDIA's signed GSP firmware stays installed; aien_gpu loads it (the chip checks its signature)."
+    [ $YES -eq 1 ] || return 0
+    backup_begin kernel
+    local m
+    backup_file "$MODDIR/aien_gpu.ko"; backup_file "$MODCONF"; backup_file "$MODLOAD"
+    for m in "$ROOT"/lib/modules/$KVER/modules.*; do [ -e "$m" ] && backup_file "${m#$ROOT}"; done
+    nv_in_initramfs && backup_file "$INITRD"
+    local B; B=$(mktemp -d) && cp -r "$DRIVER_SRC"/. "$B"/ || die "copy of driver source failed"
+    make -C "$KDIR" M="$B" modules > "$BK/build.log" 2>&1 || { cat "$BK/build.log" >&2; die "aien_gpu build failed (log $BK/build.log)"; }
+    local vm; vm=$(modinfo -F vermagic "$B/aien_gpu.ko" 2>/dev/null; modinfo "$B/aien_gpu.ko" 2>/dev/null | awk '/^vermagic/{print $2}')
+    grep -q "$KVER" <<<"$vm" || die "built module vermagic '$vm' does not match running kernel $KVER"
+    mkdir -p "$ROOT$MODDIR" && install -m 0644 "$B/aien_gpu.ko" "$ROOT$MODDIR/aien_gpu.ko" || die "module install failed"
+    rm -rf "$B"
+    { echo "# cudapp swap kernel: NVIDIA's kernel modules held back, AIEN aien_gpu drives the GB10. Undo: cudapp swap back"
+      for m in $NV_MODULES; do echo "blacklist $m"; echo "install $m /bin/false"; done
+      echo "options aien_gpu allow_bind=1"; } > "$ROOT$MODCONF"
+    { echo "# cudapp swap kernel"; echo "aien_gpu"; } > "$ROOT$MODLOAD"
+    depmod -a "$KVER" || die "depmod failed"
+    if nv_in_initramfs || [ -f "$BK/files$INITRD" ]; then update-initramfs -u -k "$KVER" || die "update-initramfs failed"; fi
+    backup_done
+    echo "kernel level STAGED: reboot to switch. To return: cudapp swap back --yes, then reboot."
+    if [ $REBOOT -eq 1 ]; then
+        [ "$(hostname 2>/dev/null)" = spark-b87b ] && [ -z "${SPARK_WINDOW:-}" ] && refuse "on the Spark the reboot runs only inside a scheduled spark-window"
+        echo "rebooting (--reboot)"; reboot
+    fi
+}
+
+back_level() {
+    local list; list=$(ls -d "$STATE"/backup-* 2>/dev/null | grep -v -e '\.undone$' -e '\.restored$' | LC_ALL=C sort -r)
+    [ -n "$list" ] || { echo "nothing to restore: no applied backup in $STATE"; return 0; }
+    echo "== back: restore NVIDIA's stack from"; echo "$list" | sed 's/^/   /'
+    local b
+    for b in $list; do [ -f "$b/APPLIED" ] && sed 's/^/  - restore: /' "$b/manifest.tsv"; done
+    [ $YES -eq 1 ] || { echo "DRY RUN: nothing changed. Run again with --yes."; return 0; }
+    local total=0 bad=0 n
+    for b in $list; do
+        [ -f "$b/APPLIED" ] || continue
+        restore_one "$b"; n=$?; bad=$((bad+n)); total=$((total+$(wc -l < "$b/manifest.tsv")))
+        [ $n -eq 0 ] && mv "$b" "$b.restored"
+    done
+    if [ $bad -eq 0 ]; then
+        echo "BACK PASS: $total files match their pre-swap state (sha256)"
+        [ -d "$ROOT/sys/module/aien_gpu" ] && echo "aien_gpu is loaded now: reboot to give the GB10 back to NVIDIA's driver."
+        return 0
+    fi
+    echo "BACK FAIL: $bad of $total files do not match; backups kept in $STATE"; return 1
+}
+
+# ---------------------------------------------------------------- main
+[ $# -ge 1 ] || usage
+cmd=$1; shift
+if [ "$cmd" = run ]; then
+    [ $# -ge 1 ] || usage
+    d=$(cd "$(dirname "$LIB_SRC")" 2>/dev/null && pwd) || refuse "CUDA++ libcuda.so.1 not built at $LIB_SRC (run: make libcuda)"
+    LD_LIBRARY_PATH=$d${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} exec "$@"
+fi
+[ "$cmd" = swap ] || usage
+[ $# -ge 1 ] || usage
+level=$1; shift
+for a in "$@"; do case $a in --yes) YES=1;; --reboot) REBOOT=1;; --holders-ok) HOLDERS_OK=1;; *) usage;; esac; done
+case $level in status|user|kernel|all|back) ;; *) usage;; esac
+if [ $YES -eq 1 ] && [ -z "$ROOT" ] && [ "$(id -u)" -ne 0 ]; then exec sudo -E "$0" swap "$level" "$@"; fi
+case $level in
+    status) status ;;
+    user)   user_level ;;
+    kernel) kernel_level ;;
+    all)    user_level && kernel_level ;;
+    back)   back_level ;;
+esac
+rc=$?
+[ $YES -eq 0 ] && [ "$level" != status ] && [ "$level" != back ] && echo "DRY RUN: nothing changed. Run again with --yes."
+exit $rc
diff --git a/tests/swap/test_swap_cli.sh b/tests/swap/test_swap_cli.sh
new file mode 100755
index 00000000..2c46fd12
--- /dev/null
+++ b/tests/swap/test_swap_cli.sh
@@ -0,0 +1,161 @@
+#!/bin/bash
+# SPDX-License-Identifier: MIT
+# Host test of `cudapp swap` on a fake machine root (no root rights, no GPU, nothing outside a temp dir touched).
+# Every system command the tool runs (ldconfig, depmod, update-initramfs, lsinitramfs, mokutil, fuser, make, modinfo,
+# uname) is a fake on PATH that logs its call, so the test sees exactly what the tool would do.
+#   bash tests/swap/test_swap_cli.sh [path/to/cudapp]
+set -u
+TOOL=${1:-$(cd "$(dirname "$0")/../.." && pwd)/swap/cudapp}
+PASS=0; FAIL=0
+ok()   { PASS=$((PASS+1)); echo "ok   $*"; }
+bad()  { FAIL=$((FAIL+1)); echo "FAIL $*"; }
+check(){ local name=$1; shift; if "$@"; then ok "$name"; else bad "$name"; fi; }
+
+KVER=7.0.0-1019-nvidia
+mkroot() { # $1 = dir; builds a fake GB10 machine with NVIDIA's stack installed
+    local R=$1
+    mkdir -p "$R"/usr/lib/aarch64-linux-gnu "$R"/etc/ld.so.conf.d "$R"/etc/modprobe.d "$R"/etc/modules-load.d \
+             "$R"/lib/modules/$KVER/kernel/drivers/video "$R"/boot "$R"/sys/bus/pci/devices/000f:01:00.0 \
+             "$R"/sys/module/nvidia "$R"/dev "$R"/fakebin "$R"/driver-src "$R"/build
+    echo nvidia-libcuda-580 > "$R"/usr/lib/aarch64-linux-gnu/libcuda.so.580.173.02
+    ln -s libcuda.so.580.173.02 "$R"/usr/lib/aarch64-linux-gnu/libcuda.so.1
+    echo "/usr/lib/aarch64-linux-gnu" > "$R"/etc/ld.so.conf.d/aarch64-linux-gnu.conf
+    echo "original-cache" > "$R"/etc/ld.so.cache
+    echo "nvidia.ko" > "$R"/lib/modules/$KVER/kernel/drivers/video/nvidia.ko
+    echo "dep-original" > "$R"/lib/modules/$KVER/modules.dep
+    echo "alias-original" > "$R"/lib/modules/$KVER/modules.alias
+    echo "initrd-original" > "$R"/boot/initrd.img-$KVER
+    echo 0x10de > "$R"/sys/bus/pci/devices/000f:01:00.0/vendor
+    echo 0x2e12 > "$R"/sys/bus/pci/devices/000f:01:00.0/device
+    echo 580.173.02 > "$R"/sys/module/nvidia/version
+    touch "$R"/dev/nvidia0 "$R"/dev/nvidiactl
+    echo "our-libcuda" > "$R"/build/libcuda.so.1
+    echo "obj-m := aien_gpu.o" > "$R"/driver-src/Kbuild
+    echo "/* aien_gpu */" > "$R"/driver-src/aien_gpu.c
+    local F="$R"/fakebin
+    for c in ldconfig depmod update-initramfs; do
+        printf '#!/bin/bash\necho "%s $*" >> "%s/calls.log"\n' "$c" "$R" > "$F/$c"
+    done
+    # ldconfig also rewrites the cache (as the real one does), so the restore must bring the old bytes back
+    printf '#!/bin/bash\necho "ldconfig $*" >> "%s/calls.log"\necho "cache-with-cudapp" > "%s/etc/ld.so.cache"\n' "$R" "$R" > "$F/ldconfig"
+    printf '#!/bin/bash\necho "depmod $*" >> "%s/calls.log"\necho "dep-new" > "%s/lib/modules/%s/modules.dep"\n' "$R" "$R" $KVER > "$F/depmod"
+    printf '#!/bin/bash\necho "update-initramfs $*" >> "%s/calls.log"\necho "initrd-new" > "%s/boot/initrd.img-%s"\n' "$R" "$R" $KVER > "$F/update-initramfs"
+    printf '#!/bin/bash\ncat "%s/lsinitramfs.out" 2>/dev/null\n' "$R" > "$F/lsinitramfs"
+    printf '#!/bin/bash\ncat "%s/sb.out" 2>/dev/null || echo "SecureBoot disabled"\n' "$R" > "$F/mokutil"
+    printf '#!/bin/bash\ncat "%s/fuser.out" 2>/dev/null; exit 0\n' "$R" > "$F/fuser"
+    printf '#!/bin/bash\necho %s\n' $KVER > "$F/uname"
+    # make: "builds" aien_gpu.ko in M=dir
+    printf '#!/bin/bash\necho "make $*" >> "%s/calls.log"\nfor a in "$@"; do case $a in M=*) echo "aien_gpu.ko built" > "${a#M=}/aien_gpu.ko";; esac; done\n' "$R" > "$F/make"
+    printf '#!/bin/bash\necho "vermagic:       %s SMP preempt mod_unload modversions aarch64"\n' $KVER > "$F/modinfo"
+    mkdir -p "$R"/lib/modules/$KVER/build
+    chmod +x "$F"/*
+}
+tree_hash() { # hashes of every file and link under the fake root, minus the tool's own state and the fake tools
+    (cd "$1" && find . \( -path ./var/lib/cudapp-swap -o -path ./fakebin -o -name calls.log -o -path ./driver-src -o -path ./build \) -prune -o \
+        \( -type f -o -type l \) -print | LC_ALL=C sort | while read -r f; do
+        if [ -L "$f" ]; then echo "L $f $(readlink "$f")"; else echo "F $f $(sha256sum < "$f" | cut -c1-16)"; fi; done)
+}
+run() { # run the tool against root $R
+    PATH="$R/fakebin:$PATH" CUDAPP_ROOT="$R" CUDAPP_LIB="$R/build/libcuda.so.1" CUDAPP_DRIVER_SRC="$R/driver-src" \
+        CUDAPP_KDIR="$R/lib/modules/$KVER/build" bash "$TOOL" "$@"
+}
+
+T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
+
+# 1. status names the GPU, the driver, Secure Boot, the holders and which libcuda.so.1 the loader finds
+R=$T/r1; mkroot "$R"; echo "/dev/nvidia0: 108356" > "$R/fuser.out"
+out=$(run swap status 2>&1); rc=$?
+check "status exits 0" [ $rc -eq 0 ]
+check "status names GB10" grep -q "GB10 (10de:2e12)" <<<"$out"
+check "status names driver 580.173.02" grep -q "580.173.02" <<<"$out"
+check "status names Secure Boot" grep -q "Secure Boot: disabled" <<<"$out"
+check "status lists holder pid" grep -q "108356" <<<"$out"
+check "status says NVIDIA libcuda is in use" grep -q "libcuda.so.1: NVIDIA" <<<"$out"
+
+# 2. user without --yes is a dry run: prints the plan, changes nothing
+R=$T/r2; mkroot "$R"; before=$(tree_hash "$R")
+out=$(run swap user 2>&1); rc=$?
+check "dry run exits 0" [ $rc -eq 0 ]
+check "dry run says DRY RUN" grep -q "DRY RUN" <<<"$out"
+check "dry run lists the ld.so.conf.d file" grep -q "etc/ld.so.conf.d/00000-cudapp-swap.conf" <<<"$out"
+check "dry run changes nothing" [ "$before" = "$(tree_hash "$R")" ]
+check "dry run runs no ldconfig" [ ! -s "$R/calls.log" ]
+
+# 3. user --yes installs our lib first in the loader's search, keeps a dated backup; back restores every hash
+out=$(run swap user --yes 2>&1); rc=$?
+check "user --yes exits 0" [ $rc -eq 0 ]
+check "our libcuda installed" cmp -s "$R/usr/lib/cudapp/libcuda.so.1" "$R/build/libcuda.so.1"
+check "ld.so.conf.d entry points at /usr/lib/cudapp" grep -qx "/usr/lib/cudapp" "$R/etc/ld.so.conf.d/00000-cudapp-swap.conf"
+check "ldconfig ran" grep -q "^ldconfig" "$R/calls.log"
+check "NVIDIA libcuda untouched" [ "$(cat "$R/usr/lib/aarch64-linux-gnu/libcuda.so.580.173.02")" = nvidia-libcuda-580 ]
+check "backup manifest written" bash -c "ls >/dev/null '$R'/var/lib/cudapp-swap/backup-*-user/manifest.tsv"
+check "status now says user level swapped" bash -c "PATH='$R/fakebin:$PATH' CUDAPP_ROOT='$R' bash '$TOOL' swap status | grep -q 'user level: SWAPPED'"
+out=$(run swap back --yes 2>&1); rc=$?
+check "back exits 0" [ $rc -eq 0 ]
+check "back reports PASS" grep -q "BACK PASS" <<<"$out"
+check "back restores every hash" [ "$before" = "$(tree_hash "$R")" ]
+
+# 4. kernel refuses with Secure Boot on (an unsigned module would be refused at boot)
+R=$T/r4; mkroot "$R"; echo "SecureBoot enabled" > "$R/sb.out"
+out=$(run swap kernel --yes 2>&1); rc=$?
+check "kernel refuses under Secure Boot (exit 3)" [ $rc -eq 3 ]
+check "refusal names Secure Boot" grep -q "Secure Boot is enabled" <<<"$out"
+
+# 5. kernel --yes refuses while processes hold /dev/nvidia*, naming them
+R=$T/r5; mkroot "$R"; echo "/dev/nvidia0: 108356 1816" > "$R/fuser.out"; before=$(tree_hash "$R")
+out=$(run swap kernel --yes 2>&1); rc=$?
+check "kernel refuses with holders (exit 3)" [ $rc -eq 3 ]
+check "refusal names the holder" grep -q "108356" <<<"$out"
+check "refusal changed nothing" [ "$before" = "$(tree_hash "$R")" ]
+
+# 6. kernel refuses on a machine without a GB10
+R=$T/r6; mkroot "$R"; echo 0x2b85 > "$R/sys/bus/pci/devices/000f:01:00.0/device"
+out=$(run swap kernel 2>&1); rc=$?
+check "kernel refuses without GB10 (exit 3)" [ $rc -eq 3 ]
+check "refusal names the device found" grep -q "10de:2b85" <<<"$out"
+
+# 7. kernel --yes stages the switch (module, hold-back, autoload, initramfs when NVIDIA is in it); back restores hashes
+R=$T/r7; mkroot "$R"; echo "usr/lib/modules/$KVER/kernel/drivers/video/nvidia.ko" > "$R/lsinitramfs.out"; before=$(tree_hash "$R")
+out=$(run swap kernel 2>&1)
+check "kernel dry run names the reboot" grep -q "reboot" <<<"$out"
+check "kernel dry run changed nothing" [ "$before" = "$(tree_hash "$R")" ]
+out=$(run swap kernel --yes 2>&1); rc=$?
+check "kernel --yes exits 0" [ $rc -eq 0 ]
+MC="$R/etc/modprobe.d/cudapp-swap-kernel.conf"
+for m in nvidia nvidia_uvm nvidia_modeset nvidia_drm; do
+    check "hold-back blacklists $m" grep -qx "blacklist $m" "$MC"
+    check "hold-back stops explicit modprobe $m" grep -qx "install $m /bin/false" "$MC"
+done
+check "aien_gpu installed for the running kernel" [ -f "$R/lib/modules/$KVER/updates/cudapp/aien_gpu.ko" ]
+check "aien_gpu loads at boot" grep -qx "aien_gpu" "$R/etc/modules-load.d/cudapp-aien-gpu.conf"
+check "depmod ran for $KVER" grep -q "^depmod -a $KVER" "$R/calls.log"
+check "initramfs rebuilt (NVIDIA was in it)" grep -q "^update-initramfs -u -k $KVER" "$R/calls.log"
+check "nvidia.ko untouched" [ "$(cat "$R/lib/modules/$KVER/kernel/drivers/video/nvidia.ko")" = nvidia.ko ]
+check "never reboots by itself" bash -c "! grep -q reboot '$R/calls.log'"
+out=$(run swap back --yes 2>&1); rc=$?
+check "kernel back exits 0" [ $rc -eq 0 ]
+check "kernel back restores every hash (initrd, modules.dep, conf files)" [ "$before" = "$(tree_hash "$R")" ]
+
+# 8. negative control for the back check: a backup copy damaged on disk must make back FAIL, not PASS
+R=$T/r8; mkroot "$R"; run swap user --yes > /dev/null 2>&1
+b=$(ls -d "$R"/var/lib/cudapp-swap/backup-*-user | head -1)
+echo "damaged" > "$b/files/etc/ld.so.cache"
+out=$(run swap back --yes 2>&1); rc=$?
+check "back with a damaged backup exits 1" [ $rc -eq 1 ]
+check "back names the file that does not match" grep -q "MISMATCH.*etc/ld.so.cache" <<<"$out"
+
+# 9. all = user + kernel, and one back undoes both
+R=$T/r9; mkroot "$R"; before=$(tree_hash "$R")
+run swap all --yes > /dev/null 2>&1; rc=$?
+check "all --yes exits 0" [ $rc -eq 0 ]
+check "all staged the user level" [ -f "$R/etc/ld.so.conf.d/00000-cudapp-swap.conf" ]
+check "all staged the kernel level" [ -f "$R/etc/modprobe.d/cudapp-swap-kernel.conf" ]
+run swap back --yes > /dev/null 2>&1
+check "one back undoes all" [ "$before" = "$(tree_hash "$R")" ]
+
+# 10. unknown level is refused with usage, exit 2
+out=$(run swap sideways 2>&1); rc=$?
+check "unknown level exits 2" [ $rc -eq 2 ]
+
+echo "swap cli: $PASS passed, $FAIL failed"
+[ $FAIL -eq 0 ]