#!/bin/bash
# https://github.com/joeknock90/Single-GPU-Passthrough
# https://passthroughpo.st/simple-per-vm-libvirt-hooks-with-the-vfio-tools-hook-helper/
# https://wiki.archlinux.org/index.php/PCI_passthrough_via_OVMF
# https://pve.proxmox.com/wiki/Pci_passthrough
# set PARAM_KERNEL="video=vesafb:off,efifb:off rd.driver.pre=vfio_pci amd_iommu=on iommu=pt vfio-pci.ids=10de:1287,10de:0e0f vfio-pci.disable_vga=1 snd-hda-intel.enable_msi=1"

# Helpful to read output when debugging
set -x

# Stop display manager
systemctl stop display-manager.service
## Uncomment the following line if you use GDM
#killall gdm-x-session

# Unbind VTconsoles
echo 0 > /sys/class/vtconsole/vtcon0/bind
echo 0 > /sys/class/vtconsole/vtcon1/bind

# Unbind EFI-Framebuffer
echo efi-framebuffer.0 > /sys/bus/platform/drivers/efi-framebuffer/unbind

# Avoid a Race condition by waiting 2 seconds. This can be calibrated to be shorter or longer if required for your system
sleep 2

modprobe -r vfio-pci
modprobe -r nvidia_drm
modprobe -r nvidia_modeset
modprobe -r drm_kms_helper
modprobe -r drm
modprobe -r nvidia_uvm
modprobe -r nvidia

# Unbind the GPU from display driver
virsh nodedev-detach pci_0000_09_00_0
virsh nodedev-detach pci_0000_09_00_1

# Load VFIO Kernel Module
modprobe vfio-pci