#!/bin/sh

PREREQ=""
prereqs()
{
    echo "$PREREQ"
}
case $1 in
# get pre-requisites
prereqs)
    prereqs
    exit 0
    ;;
esac

echo "Running vfio-pci early-bind script"

# shellcheck disable=SC2013
for x in $(cat /proc/cmdline); do
    case ${x} in
    vfio_pci_addresses=*)
        # Find the PCI address from the kernel command line
        PCI_ADDRESSES="${x#vfio_pci_addresses=}"

        # If no address is provided, do nothing
        if [ -z "${PCI_ADDRESSES}" ]; then
            echo "No PCI_ADDRESSES found"
            exit 0
        fi

        # Inform user
        echo "Found PCI_ADDRESSES=$PCI_ADDRESSES"

        # Set the override for the given devices
        for PCI_ADDRESS in $(echo $PCI_ADDRESSES | tr ',' ' '); do
            echo "Binding $PCI_ADDRESS to vfio-pci"
            echo "vfio-pci" > /sys/bus/pci/devices/$PCI_ADDRESS/driver_override
        done

        # Load VFIO modules
        /sbin/modprobe vfio
        /sbin/modprobe vfio_iommu_type1
        /sbin/modprobe vfio_pci
        /sbin/modprobe vhost_net
        ;;
    esac
done

exit 0
