Last active 5 hours ago

Adjust Nvidia Passthrough Device to Primary Card

Revision 65bb88583c63146d6085ff7709cdd21a496ef623

primary_vm.sh Raw
1#!/bin/bash
2
3# Set a primary VM to use first NVIDIA card as PCI Passthrough
4# And REMOVE those 2 PCI devices from any other VM
5# mReschke 2025-03-16
6
7# Input
8primary_vmid="$1"
9primary=109
10
11# Validate
12if [ "$primary_vmid" == "" ]; then
13 echo "You must provide a VMID you want to be the seconday"
14 exit 1
15fi
16
17
18# Define PCI devices to add/remove
19hostpci0="0000:81:00,pcie=1,x-vga=1"
20hostpci1="0000:04:00.3,pcie=1"
21
22# Get all VMID from qm list
23vmids=($(qm list | tail -n +2 | cut -d\ -f8))
24
25# Loop each VM and remove our pci devices if exist
26found_primary=0
27for vmid in "${vmids[@]}"
28do
29 echo "Analyzing VMID $vmid"
30 if [ "$vmid" == "$primary_vmid" ]; then
31 found_primary=1
32 fi
33
34 # TODO check status
35 # qm status 102 | cut -d: -f2 | xargs
36 # will be running or stopped
37 # if running and PCI device exist, do NOT remove it
38 # and if I can't remove it, do NOT add it second VM
39
40 # Remove hostpci0 if matches our desired device
41 if result=$(qm config $vmid | grep $hostpci0); then
42 echo " VMID $vmid has option $result"
43 qm set $vmid --delete hostpci0
44 echo " VMID $vmid removed hostpci0"
45 fi
46
47 # Remove hostpci1 is matches our desired device
48 if result=$(qm config $vmid | grep $hostpci1); then
49 echo " VMID $vmid has option $result"
50 qm set $vmid --delete hostpci1
51 echo " VMID $vmid removed hostpci1"
52 fi
53
54done
55
56# Finally add our PIC devices to the desired VMID
57if [ "$found_primary" == 1 ]; then
58 echo
59 echo "Setting primary VM to $primary_vmid"
60 qm set $primary_vmid -hostpci0 $hostpci0
61 qm set $primary_vmid -hostpci1 $hostpci1
62else
63 echo "The primary VMID $primary_vmid was not found in qm list, not setting primary"
64 exit 1
65fi