summaryrefslogtreecommitdiffstats
path: root/scripts/create_mdev.sh
blob: a6ea91e403af3ce2776621278320d8bc96d96593 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/bin/bash
# create_mdev.sh - Create NVIDIA vGPU mediated device for QEMU
# Usage: ./create_mdev.sh [PCI_ADDRESS] [VGPU_TYPE]

set -euo pipefail

PCI_ADDR="${1:-}"
VGPU_TYPE="${2:-pci-nvidia-vgpu-turing}"

# Supported vGPU types (matching the mdev type names)
VALID_TYPES=("pci-nvidia-vgpu-ampere" "pci-nvidia-vgpu-hopper" "pci-nvidia-vgpu-turing" "pci-nvidia-vgpu-pascal")

# Find NVIDIA GPU if not specified
if [[ -z "$PCI_ADDR" ]]; then
    echo "Scanning for NVIDIA GPUs..."
    mapfile -t GPUS < <(lspci -D -d 10de: | grep -E "VGA|3D controller" | awk '{print $1}')
    if [[ ${#GPUS[@]} -eq 0 ]]; then
        echo "ERROR: No NVIDIA GPU found"
        exit 1
    elif [[ ${#GPUS[@]} -eq 1 ]]; then
        PCI_ADDR="${GPUS[0]}"
        echo "Auto-selected GPU: $PCI_ADDR"
    else
        echo "Multiple GPUs found:"
        for i in "${!GPUS[@]}"; do
            echo "  [$i] ${GPUS[$i]}"
        done
        read -p "Select GPU [0-$((${#GPUS[@]}-1))]: " idx
        PCI_ADDR="${GPUS[$idx]}"
    fi
fi

# Validate PCI address format
if [[ ! "$PCI_ADDR" =~ ^[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-9a-fA-F]$ ]]; then
    echo "ERROR: Invalid PCI address format. Expected: dddd:bb:dd.f"
    exit 1
fi

# Check if GPU exists
if [[ ! -e "/sys/bus/pci/devices/$PCI_ADDR" ]]; then
    echo "ERROR: PCI device $PCI_ADDR not found"
    exit 1
fi

# Validate vGPU type
if [[ ! " ${VALID_TYPES[*]} " =~ " ${VGPU_TYPE} " ]]; then
    echo "ERROR: Invalid vGPU type. Valid types: ${VALID_TYPES[*]}"
    exit 1
fi

MDEV_TYPE_PATH="/sys/bus/pci/devices/$PCI_ADDR/mdev_supported_types/$VGPU_TYPE"

if [[ ! -d "$MDEV_TYPE_PATH" ]]; then
    echo "ERROR: vGPU type $VGPU_TYPE not supported on $PCI_ADDR"
    echo "Available types:"
    ls "/sys/bus/pci/devices/$PCI_ADDR/mdev_supported_types/" 2>/dev/null || echo "  (none - check driver loaded)"
    exit 1
fi

# Check available instances
AVAILABLE=$(cat "$MDEV_TYPE_PATH/available_instances" 2>/dev/null || echo "0")
if [[ "$AVAILABLE" -le 0 ]]; then
    echo "ERROR: No available instances for $VGPU_TYPE on $PCI_ADDR"
    exit 1
fi

echo "Creating $VGPU_TYPE on $PCI_ADDR..."

# Generate UUID
UUID=$(uuidgen)
echo "$UUID" | sudo tee "$MDEV_TYPE_PATH/create" > /dev/null

# Verify creation
MDEV_PATH="/sys/bus/mdev/devices/$UUID"
if [[ -d "$MDEV_PATH" ]]; then
    echo "SUCCESS: Created mdev device $UUID"
    echo "  Path: $MDEV_PATH"
    echo "  PCI:  $PCI_ADDR"
    echo "  Type: $VGPU_TYPE"
    echo ""
    echo "For QEMU, use:"
    echo "  -device vfio-pci,sysfsdev=$MDEV_PATH,display=off"
else
    echo "ERROR: Failed to create mdev device"
    exit 1
fi