#!/usr/bin/env sh
# Script for switching a GPU driver between vfio-pci and amdgpu

# Resources:
# https://reddit.2dkun.xyz/r/VFIO/comments/12dbvzv/rx_6800_r7_5700g_successful_passthrough_does_not/
# https://reddit.2dkun.xyz/r/VFIO/comments/z4gxo9/dynamic_unbind_amdgpu_on_one_of_two_amd_gpus/
# https://wiki.archlinux.org/title/PRIME

# Specify ID of card
VID="1002"
PID="687f"

MODE="$1"
# Get path with lspci
PATH="0000:$(lspci -d "$VID:$PID" | awk -F' ' '{print $1}')"

#if [ "$MODE" = "host" ]; then
	## Remove the ID from vfio-pci
	#echo "$VID $PID" > "/sys/bus/pci/drivers/vfio-pci/remove_id"
	## Unbind from vfio-pci
	#echo "$PATH" > "/sys/bus/pci/drivers/vfio-pci/unbind"
	## Bind to amdgpu
	#echo "$PATH" > "/sys/bus/pci/drivers/amdgpu/bind"
#elif [ "$MODE" = "guest" ]; then
	## Unbind from amdgpu
	#echo "$PATH" > "/sys/bus/pci/drivers/amdgpu/unbind"
	## Add the ID to vfio-pci
	#echo "$VID $PID" > "/sys/bus/pci/drivers/vfio-pci/new_id"
	## Bind to vfio-pci
	#echo "$PATH" > "/sys/bus/pci/drivers/vfio-pci/bind"
#else
	#echo "Usage: gpu-switch.sh host/guest"
	#echo ""
	#echo "Host will bind the GPU to the host GPU driver for the card."
	#echo "Guest will bind the GPU to vfio-pci for GPU passthrough."
#fi

if [ "$MODE" = "host" ]; then
	# Remove the ID from vfio-pci
	echo "$VID $PID" > "/sys/bus/pci/drivers/vfio-pci/remove_id"
	# Remove the card
	echo '1' > "/sys/bus/pci/devices/$PATH/remove"
	# Rescan to load the amdgpu driver
	echo '1' > "/sys/bus/pci/rescan"
elif [ "$MODE" = "guest" ]; then
	# Add the ID to vfio-pci
	echo "$VID $PID" > "/sys/bus/pci/drivers/vfio-pci/new_id"
	# Remove the card
	echo '1' > "/sys/bus/pci/devices/$PATH/remove"
	# Rescan to load the vfio-pci driver
	echo '1' > "/sys/bus/pci/rescan"
else
	echo "Usage: gpu-switch.sh host/guest"
	echo ""
	echo "Host will bind the GPU to the host GPU driver for the card."
	echo "Guest will bind the GPU to vfio-pci for GPU passthrough."
fi

