Files
stambha/xtask/scripts/vfio-gpu.sh
T

257 lines
8.9 KiB
Bash
Executable File

#!/bin/bash
# Lend a host's GPU to one `cargo xtask boot run --kvm --vfio-gpu` and take it
# back. Linux keeps no VFIO configuration between runs: the card is bound to
# vfio-pci for the command's life and returned to its driver afterwards.
#
# vfio-gpu.sh status
# sudo vfio-gpu.sh run [--stop-desktop] [--seconds N] -- COMMAND...
#
# COMMAND runs as the sudo caller, with memory locking unlimited so VFIO can
# pin guest RAM. --stop-desktop stops the display manager first and restarts
# it afterwards: a card that drives the only display cannot be unbound, and
# every graphical session on it ends. Start such a run detached so it survives
# them; it always gives the desktop back, within --seconds at the latest:
#
# sudo systemd-run --unit=stela-vfio --collect xtask/scripts/vfio-gpu.sh \
# run --stop-desktop --seconds 1800 -- COMMAND...
#
# STELA_VFIO_GPU names the card, by default the first NVIDIA display function.
set -euo pipefail
die() { echo "vfio-gpu: $*" >&2; exit 1; }
devices=/sys/bus/pci/devices
gpu() {
if [[ -n ${STELA_VFIO_GPU:-} ]]; then
echo "$STELA_VFIO_GPU"
return
fi
local device
for device in "$devices"/*; do
[[ $(<"$device/vendor") == 0x10de && $(<"$device/class") == 0x03* ]] || continue
basename "$device"
return
done
die "no NVIDIA display function"
}
# The functions of the card's slot that go to the guest together, as
# `cargo xtask boot run --vfio-gpu` lends them: the whole slot when every
# function in it has the display function's vendor and is one a card carries
# (display 0x03, HD audio 0x0403, USB-C's USB 0x0c03 and UCSI 0x0c80);
# otherwise only that vendor's display and HD audio functions. An integrated
# GPU's slot also holds the platform's USB controllers and security processor,
# which stay with the host.
functions() {
local card=$1 device vendor class whole=1 members=()
vendor=$(<"$devices/$card/vendor")
for device in "$devices/${card%.*}".*; do
class=$(<"$device/class")
if [[ $(<"$device/vendor") != "$vendor" ]] ||
[[ $class != 0x03* && $class != 0x0403* && $class != 0x0c03* && $class != 0x0c80* ]]; then
whole=0
fi
done
for device in "$devices/${card%.*}".*; do
class=$(<"$device/class")
if ((whole)) || [[ $(<"$device/vendor") == "$vendor" && ($class == 0x03* || $class == 0x0403*) ]]; then
members+=("$(basename "$device")")
fi
done
printf '%s\n' "${members[@]}"
}
# The IOMMU groups of the lent functions; an integrated GPU's functions each
# have one.
groups() {
local function
for function in "$@"; do basename "$(readlink "$devices/$function/iommu_group")"; done | sort -u
}
driver() {
local link="$devices/$1/driver"
if [[ -e $link ]]; then basename "$(readlink -f "$link")"; else echo none; fi
}
status() {
local card function device lent
card=$(gpu)
echo "card $card: $(lspci -s "$card" | cut -d' ' -f2-)"
echo "boot VGA: $(<"$devices/$card/boot_vga")"
mapfile -t lent < <(functions "$card")
for function in "${lent[@]}"; do
echo "$function: driver $(driver "$function"), IOMMU group $(basename "$(readlink "$devices/$function/iommu_group")")"
done
for device in "$devices/${card%.*}".*; do
[[ " ${lent[*]} " == *" $(basename "$device") "* ]] && continue
echo "$(basename "$device"): stays with the host, driver $(driver "$(basename "$device")")"
done
for function in "${lent[@]}"; do
for device in "$devices/$function/iommu_group/devices"/*; do
[[ " ${lent[*]} " == *" $(basename "$device") "* ]] && continue
echo "WARNING: $(basename "$device") shares the IOMMU group of $function"
done
done
local displays=()
for device in "$devices"/*; do
[[ $(<"$device/class") == 0x03* && " ${lent[*]} " != *" $(basename "$device") "* ]] || continue
displays+=("$(basename "$device")")
done
if ((${#displays[@]})); then
echo "other display functions: ${displays[*]}: this desktop can stay up"
else
echo "no other display function: a run needs --stop-desktop and ends this desktop"
fi
}
bind() {
local function=$1
local current
current=$(driver "$function")
# A function vfio-pci held before the run (a vfio-pci.ids= option) stays
# with it afterwards.
[[ $current == vfio-pci ]] && kept+=("$function")
if [[ $current != none ]]; then
echo "$function" >"$devices/$function/driver/unbind"
fi
echo vfio-pci >"$devices/$function/driver_override"
echo "$function" >/sys/bus/pci/drivers_probe
[[ $(driver "$function") == vfio-pci ]] || die "$function did not bind to vfio-pci"
# An FLR of a card whose GSP has served work never completes and takes the
# link with it. Without it QEMU resets the slot, which does bring it back.
if [[ -e $devices/$function/reset_method ]]; then
echo >"$devices/$function/reset_method"
fi
}
# What the host's IOMMU driver left enabled on a lent function. VFIO drops a
# guest's writes to these controls and shows it the card's own values, so a
# guest that stops a function before it drives it cannot switch them off. A
# host booted with pci=noats never enables ATS.
requester_controls() {
local function=$1 control value
for control in ATS+6 PRI+4 PASID+6; do
value=$(setpci -s "$function" "ECAP_$control.w" 2>/dev/null) || continue
echo "vfio-gpu: $function ${control%+*} control reads $value" >&2
if [[ $control == ATS+6 ]] && ((0x$value & 0x8000)); then
echo "vfio-gpu: the host keeps ATS enabled on $function and the guest cannot switch it off; boot the host with pci=noats" >&2
fi
done
}
release() {
local function=$1
[[ " ${kept[*]} " == *" $function "* ]] && return
if [[ $(driver "$function") == vfio-pci ]]; then
echo "$function" >"$devices/$function/driver/unbind"
fi
echo >"$devices/$function/driver_override"
}
# Stop what holds an NVIDIA card: its services, consoles and modules.
unload_nvidia() {
local console
systemctl stop nvidia-persistenced.service 2>/dev/null || true
for console in /sys/class/vtconsole/vtcon*; do
if grep -q 'frame buffer' "$console/name"; then
echo 0 >"$console/bind"
fi
done
local module
for module in nvidia_uvm nvidia_drm nvidia_modeset nvidia; do
if [[ -d /sys/module/$module ]]; then
modprobe -r "$module" || die "cannot unload $module: something still holds the card"
fi
done
}
restore() {
local function console
set +e
for function in "${members[@]}"; do release "$function"; done
for group in $(groups "${members[@]}"); do
[[ -e /dev/vfio/$group ]] && chown root:root "/dev/vfio/$group"
done
if ((nvidia)); then
modprobe nvidia_drm
modprobe nvidia_uvm
systemctl start nvidia-persistenced.service 2>/dev/null
fi
for function in "${members[@]}"; do
[[ " ${kept[*]} " == *" $function "* ]] && continue
echo "$function" >/sys/bus/pci/drivers_probe
done
for console in /sys/class/vtconsole/vtcon*; do
echo 1 >"$console/bind" 2>/dev/null
done
[[ -n $vfct ]] && rm -f "$vfct"
((stopped)) && systemctl start display-manager.service
set -e
}
run() {
local stop_desktop=0 seconds=3600
while (($#)); do
case $1 in
--stop-desktop) stop_desktop=1 ;;
--seconds) seconds=$2; shift ;;
--) shift; break ;;
*) die "unknown option $1" ;;
esac
shift
done
(($#)) || die "no command"
((EUID == 0)) || die "run needs root"
local owner=${SUDO_USER:-${STELA_VFIO_USER:-}}
[[ -n $owner && $owner != root ]] || die "set STELA_VFIO_USER to the user who runs the command"
local card
card=$(gpu)
mapfile -t members < <(functions "$card")
kept=()
vfct=
stopped=0
nvidia=0
trap restore EXIT
modprobe vfio-pci
if ((stop_desktop)); then
systemctl stop display-manager.service
stopped=1
sleep 3
fi
if [[ $(driver "$card") == nvidia ]]; then
nvidia=1
unload_nvidia
fi
local function
for function in "${members[@]}"; do bind "$function"; done
for function in "${members[@]}"; do requester_controls "$function"; done
local group
for group in $(groups "${members[@]}"); do chown "$owner" "/dev/vfio/$group"; done
# The host's ACPI VFCT table, where firmware publishes an integrated AMD
# GPU's video BIOS, is root's in sysfs: the command gets a copy it may
# read, which `cargo xtask boot run` gives the run's firmware.
if [[ -r /sys/firmware/acpi/tables/VFCT ]]; then
vfct=$(mktemp --tmpdir stela-vfct.XXXXXX)
cat /sys/firmware/acpi/tables/VFCT >"$vfct"
chown "$owner" "$vfct"
export STELA_HOST_VFCT=$vfct
fi
ulimit -l unlimited
local code=0
# Stopping the service ends the command too: first let the card write no
# more to memory QEMU is about to unmap.
trap 'for function in "${members[@]}"; do setpci -s "$function" COMMAND=0:4; done; kill "$child" 2>/dev/null' TERM
timeout --kill-after=30 "$seconds" runuser -u "$owner" -- "$@" &
child=$!
wait "$child" || code=$?
wait "$child" 2>/dev/null || true
return "$code"
}
case ${1:-} in
status) status ;;
run) shift; run "$@" ;;
*) die "usage: vfio-gpu.sh status | run [--stop-desktop] [--seconds N] -- COMMAND..." ;;
esac