Created
May 1, 2023 10:10
-
-
Save SoapyMan/01c3b86b1c529c6e7a93d7c41b112b98 to your computer and use it in GitHub Desktop.
Generate virsh scripts for GPU attach/detach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| mkdir "gen" | |
| # Detect GPU and HDMI audio device PCI IDs | |
| gpu_pci_ids=$(lspci -nnk | awk '/VGA|3D|Display/ && /NVIDIA|AMD/ {print $1}') | |
| hdmi_audio_device_pci_ids="" | |
| for gpu_pci_id in $gpu_pci_ids; do | |
| echo "GPU Device $gpu_pci_id" | |
| # try get HDMI audio device for this GPU | |
| audio_device_pci_id=$(lspci -nnk -s "${gpu_pci_id%.0}" | awk '/Audio/ {print $1}') | |
| echo "GPU Audio Device $audio_device_pci_id" | |
| hdmi_audio_device_pci_ids+="${audio_device_pci_id} " | |
| done | |
| attach_file="gen/attach_devices.sh" | |
| detach_file="gen/detach_devices.sh" | |
| # Generate attach and detach scripts | |
| echo "#!/bin/bash" > ${attach_file} | |
| echo "# call before modprobe vfio-pci" >> ${attach_file} | |
| echo "#!/bin/bash" > ${detach_file} | |
| echo "# call before modprobe your-gpu-driver" >> ${detach_file} | |
| for pci_id in $gpu_pci_ids $hdmi_audio_device_pci_ids; do | |
| # FIXME: need to detect proper domain | |
| DOMAIN="0000" | |
| IFS='.' read -ra ADDR <<< "$pci_id" | |
| bus_slot="${ADDR[0]}" | |
| pci_function="${ADDR[1]}" | |
| IFS=':' read -ra ADDR <<< "$bus_slot" | |
| nodedev_name="pci_${DOMAIN}_${ADDR[0]}_${ADDR[1]}_${pci_function}" | |
| xml_file="gen/pci_${pci_id//:/_}.xml" | |
| cat > "$xml_file" <<EOL | |
| <hostdev mode='subsystem' type='pci' managed='yes'> | |
| <source> | |
| <address domain='0x${DOMAIN}' bus='0x${ADDR[0]}' slot='0x${ADDR[1]}' function='0x${pci_function}'/> | |
| </source> | |
| </hostdev> | |
| EOL | |
| # Add commands to attach and detach scripts | |
| echo "virsh attach-device $vm_name $xml_file --config" >> ${attach_file} | |
| echo "virsh nodedev-detach $nodedev_name" >> ${attach_file} | |
| echo "virsh detach-device $vm_name $xml_file --config" >> ${detach_file} | |
| echo "virsh nodedev-attach $nodedev_name" >> ${detach_file} | |
| done | |
| # Make the scripts executable | |
| chmod +x ${attach_file} | |
| chmod +x ${detach_file} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment