How to auto-hotplug usb devices to libvirt VMs (Update 1)
2014-02-26:
I've updated this HowTo for current versions of udev and kvm.
libvirt/kvm allows you to expose any usb device attached to your physical maschine to the guests. Just edit the domain's XML definition and add the following <hostdev>
to the <devices>
area:
<domain type='kvm'>
...
<devices>
....
<!-- The XHCI driver includes support for USB 2 devices, which makes
it easier as with UHCI/EHCI to add an USB controller. Remove
existing USB controllers from definition. -->
<controller type='usb' index='0' model='nec-xhci' />
<hostdev mode='subsystem' type='usb' managed='yes'>
<source startupPolicy='optional'>
<vendor id='0x03f0'/>
<product id='0x4217'/>
</source>
</hostdev>
</devices>
</domain>
Vendor id and product id can be determined with lsusb
:
$ lsusb
...
Bus 002 Device 018: ID 03f0:4217 Hewlett-Packard EWS CM1015
...
Sadly this only works if the device is attached and enabled when the VM is started. The connection will be lost whenever the device is disabled or removed. But you can re-attach it at runtime. Just put the hostdev
-definition into it's own file:
hostdev-03f0:4217.xml
:
<hostdev mode='subsystem' type='usb'>
<source>
<vendor id='0x03f0'/>
<product id='0x4217'/>
</source>
</hostdev>
And execute the following command when the device is available again:
$ virsh attach-device GUESTNAME /path/to/hostdev-03f0:4217.xml
You can use udev to automatically run this command whenever the device is attached:
/etc/udev/rules.d/90-libvirt-usb.rules
:
ACTION=="add", \
SUBSYSTEM=="usb", \
ENV{ID_VENDOR_ID}=="03f0", \
ENV{ID_MODEL_ID}=="4217", \
RUN+="/usr/bin/virsh attach-device GUESTNAME /path/to/hostdev-03f0:4217.xml"
ACTION=="remove", \
SUBSYSTEM=="usb", \
ENV{ID\_VENDOR\_ID}=="03f0", \
ENV{ID\_MODEL\_ID}=="4217", \
RUN+="/usr/bin/virsh detach-device GUESTNAME /path/to/hostdev-03f0:4217.xml"
Previously, this example depended on sysFs{idVendor}
and sysFs{idProduct}
in order to match the correct USB device. These do not exist any longer, so I replaced them with environment variables containing the same information. To find out what attributes are available for matching, run udev monitor --property --udev
while attaching and detaching the device.
Update: Fixed Typo