# Permission problem with vfio-pci

## rabcor

I am trying to run a qemu virtual machine with a VGA Passthrough setup.

In short, I enabled pci-stub to claim my graphics card on boot, then using the kernel "vfio-pci" module I run the following script

```
#!/bin/bash

modprobe vfio-pci

for dev in "$@"; do

        vendor=$(cat /sys/bus/pci/devices/$dev/vendor)

        device=$(cat /sys/bus/pci/devices/$dev/device)

        if [ -e /sys/bus/pci/devices/$dev/driver ]; then

                echo $dev > /sys/bus/pci/devices/$dev/driver/unbind

        fi

        echo $vendor $device > /sys/bus/pci/drivers/vfio-pci/new_id

done
```

To bind the GPU to vfio. Then I launch qemu with these commands to bind the card to my VM:

```
-device vfio-pci,host=02:00.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on -device vfio-pci,host=02:00.1,bus=root.1,addr=00.1
```

It executes just fine as root, but if I run it as a user it fails and gives me a permission error:

```
qemu-system-x86_64: -device vfio-pci,host=02:00.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on: vfio: error opening /dev/vfio/13: Permission denied

qemu-system-x86_64: -device vfio-pci,host=02:00.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on: vfio: failed to get group 13

qemu-system-x86_64: -device vfio-pci,host=02:00.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on: Device initialization failed.

qemu-system-x86_64: -device vfio-pci,host=02:00.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on: Device 'vfio-pci' could not be initialized

```

For more info here are my groups:

```
$ groups

disk wheel audio video kvm users plugdev rabcor

```

What would you think is the safest way to solve that? (Running a VM as root is not something I would consider safe)

----------

## khayyam

rabcor ... I can't answer your specific problem, but I'd suggest the following improvements to your script: 

```
#!/bin/sh

modprobe vfio-pci

for dev in "$@"; do

    read -r vendor </sys/bus/pci/devices/$dev/vendor

    read -r device </sys/bus/pci/devices/$dev/device

    if [ -e /sys/bus/pci/devices/$dev/driver ]; then

        echo $dev > /sys/bus/pci/devices/$dev/driver/unbind

    fi

    echo $vendor $device > /sys/bus/pci/drivers/vfio-pci/new_id

done
```

----------

## rabcor

Thanks   :Cool:  I have no idea how that's an improvement though, isn't it just a different way to achieve the same result?

----------

## khayyam

 *rabcor wrote:*   

> Thanks  8) I have no idea how that's an improvement though, isn't it just a different way to achieve the same result?

 

rabcor ... you're welcome ... well, yes, it achieves the same result, but 'read' is a shell builtin whereas 'cat' isn't (so, a UUoC).

The reason we have various shell builtins is to make tasks like the above easy, and so that rather than call an external command, we can use the shell itself (which, generally, will make our code less resource intensive).

best ... khay

----------

