[libvirt] [PATCH v3 REBASE 09/12] qemu: handle host usb device plug/unplug when libvirtd is down

Nikolay Shirokovskiy nshirokovskiy at virtuozzo.com
Tue Oct 15 14:29:53 UTC 2019


Somebody can easily unplug usb device from host while libvirtd is being
stopped. Also usb device can be plugged or unplugged/plugged back and so
forth. Let's handle such cases.

Signed-off-by: Nikolay Shirokovskiy <nshirokovskiy at virtuozzo.com>
Reviewed-by: Daniel Henrique Barboza <danielhb413 at gmail.com>
---
 src/qemu/qemu_process.c | 56 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)

diff --git a/src/qemu/qemu_process.c b/src/qemu/qemu_process.c
index 0afb7c79e4..82e10f4743 100644
--- a/src/qemu/qemu_process.c
+++ b/src/qemu/qemu_process.c
@@ -3734,6 +3734,59 @@ qemuProcessUpdateDevices(virQEMUDriverPtr driver,
     return ret;
 }
 
+
+static int
+qemuProcessReattachUSBDevices(virQEMUDriverPtr driver,
+                              virDomainObjPtr vm)
+{
+    size_t i;
+
+    for (i = 0; i < vm->def->nhostdevs; i++) {
+        virDomainHostdevDefPtr hostdev = vm->def->hostdevs[i];
+        virDomainHostdevSubsysUSBPtr usbsrc = &hostdev->source.subsys.u.usb;
+
+        if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB ||
+            !usbsrc->replug)
+            continue;
+
+        /* don't mess with devices that don't use stable host addressing
+         * with respect to unplug/plug to host
+         */
+        if (!usbsrc->vendor || !usbsrc->product)
+            continue;
+
+        if (!usbsrc->bus && !usbsrc->device) {
+            int num;
+
+            if ((num = virUSBDeviceFindByVendor(usbsrc->vendor, usbsrc->product,
+                                                NULL, false, NULL)) < 0)
+                return -1;
+
+            if (num > 0 &&
+                qemuDomainAttachHostDevice(driver, vm, hostdev) < 0)
+                return -1;
+        } else {
+            virUSBDevicePtr usb;
+
+            if (virUSBDeviceFindByBus(usbsrc->bus, usbsrc->device,
+                                      NULL, false, &usb) < 0)
+                return -1;
+
+            if (!usb) {
+                virDomainDeviceDef dev = { .type = VIR_DOMAIN_DEVICE_HOSTDEV };
+
+                dev.data.hostdev = hostdev;
+                if (qemuDomainDetachDeviceLive(vm, &dev, driver, true, true) < 0)
+                    return -1;
+            }
+            virUSBDeviceFree(usb);
+        }
+    }
+
+    return 0;
+}
+
+
 static int
 qemuDomainPerfRestart(virDomainObjPtr vm)
 {
@@ -8220,6 +8273,9 @@ qemuProcessReconnect(void *opaque)
     if (qemuProcessUpdateDevices(driver, obj) < 0)
         goto error;
 
+    if (qemuProcessReattachUSBDevices(driver, obj) < 0)
+        goto error;
+
     if (qemuRefreshPRManagerState(driver, obj) < 0)
         goto error;
 
-- 
2.23.0




More information about the libvir-list mailing list