Skip to content

Instantly share code, notes, and snippets.

@drkpkg
Created December 3, 2022 03:41
Show Gist options
  • Save drkpkg/b1d6b67f3cfadd220693c0e02e0fa22a to your computer and use it in GitHub Desktop.
Save drkpkg/b1d6b67f3cfadd220693c0e02e0fa22a to your computer and use it in GitHub Desktop.
Gpu passthrough
# Import libraries
import os
# Define function to detect GPU
def detect_gpu():
# Use lspci command to list PCI devices
result = os.popen("lspci | grep -i 'vga\|3d\|2d'").read()
# Extract GPU information from lspci output
if result:
gpu_info = result.strip().split("\n")[0]
gpu_vendor = gpu_info.split(":")[0]
gpu_model = gpu_info.split(":")[1].strip()
# Return GPU information
return gpu_vendor, gpu_model
else:
return None, None
# Detect GPU
gpu_vendor, gpu_model = detect_gpu()
# Check if GPU is detected
if gpu_vendor and gpu_model:
print("GPU detected: ", gpu_vendor, " ", gpu_model)
# Check if GPU passthrough is supported by VM
if "kvm" in os.popen("lsmod | grep kvm").read():
print("KVM module detected, GPU passthrough supported")
# Add GPU to VM configuration
vm_config = open("/etc/libvirt/qemu/vm.xml", "r")
config_lines = vm_config.readlines()
vm_config.close()
for i in range(len(config_lines)):
if "<devices>" in config_lines[i]:
config_lines.insert(i+1, "<hostdev mode='subsystem' type='pci' managed='yes'>\n")
config_lines.insert(i+2, " <source>\n")
config_lines.insert(i+3, " <address domain='0x0000' bus='0x00' slot='0x" + gpu_vendor + "' function='0x" + gpu_model + "'/>\n")
config_lines.insert(i+4, " </source>\n")
config_lines.insert(i+5, "</hostdev>\n")
break
vm_config = open("/etc/libvirt/qemu/vm.xml", "w")
vm_config.writelines(config_lines)
vm_config.close()
# Restart VM to apply changes
os.popen("systemctl restart libvirtd")
# Check if GPU is available to VM
result = os.popen("virsh nodedev-list | grep pci").read()
if gpu_vendor in result and gpu_model in result:
print("GPU passthrough successful, GPU available to VM")
else:
print("Error: GPU passthrough failed, GPU not available to VM")
else:
print("Error: KVM module not detected, GPU passthrough not supported")
else:
print("Error: No GPU detected")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment