Skip to contentSkip to conversation

kvm: Implement atomic memory region resizes

RFC PATCH In review David Hildenbrand 2 participants 6 messages Mar 12, 2020 – Mar 13, 2020 KVM

lore
Share & tools
lore
#0 lore raw

v2 cover kvm: Implement atomic memory region resizes

Currently, when doing a

    memory_region_ram_resize() -> memory_region_set_size()

the old KVM slot will first get removed and the new, resized one, will be re-added. This is fine as long as no IOCTL is currently using any data from such a memory slot (e.g., when building ACPI tables). However, if e.g., a VCPU is in KVM_RUN and tries to access any data on such a slot while we're growing it, we will get wrong faults while the slot is temporarily removed.

Let's allow to resize memory regions while the guest is running and might be using the regions. Inhibit any KVM ioctl while we are replacing the memory slot(s).

This is a preparation for virtio-mem (initially, x86-64 only), which wants to resize (esp., grow, but also shrink) ram memory regions while the guest is running via memory_region_ram_resize().

Using pause_all_vcpus()/resume_all_vcpus() is not possible, as it will temporarily drop the BQL - something most callers can't handle (esp. when called from vcpu context e.g., in virtio code).

Once we can handle resizes in the kernel (e.g., via KVM_SET_USER_MEMORY_REGION), we can make inhibiting optional at runtime. Handling atomic KVM slot resizes in the kernel does not seem to be easy as well and I want to avoid depending on new kernel features.

Instead of inhibiting during the region_resize(), we could inhibit for the hole memory transaction (from begin() to commit()). This could be nice, because also splitting of memory regions would be atomic (I remember there was a BUG report regarding that), however, I am not sure if that might impact any RT users.

Tested so far with x86-64 KVM only.

RFC v1 -> RFC v2:
- "openpic_kvm: Use kvm_device_ioctl() instead of ioctl()" -- Use now "-ret" instead of errno
- "intc/s390_flic_kvm.c: Use kvm_device_ioctl() instead of ioctl()" -- As -ret now corresponds to errno, we can simplify the code
- "kvm: Implement atomic memory region resizes via region_resize()" -- Use a per-cpu spinlock instead of a global rwsem.
-- Clarify in the description why we cannot deadlock even if holding the
BQL - in contrast to other approaches

David Hildenbrand (4):
openpic_kvm: Use kvm_device_ioctl() instead of ioctl() intc/s390_flic_kvm.c: Use kvm_device_ioctl() instead of ioctl()
memory: Add region_resize() callback to memory notifier
kvm: Implement atomic memory region resizes via region_resize()

 accel/kvm/kvm-all.c     | 129 +++++++++++++++++++++++++++++++++++++---
 hw/core/cpu.c           |   2 +
 hw/intc/openpic_kvm.c   |  16 ++---
 hw/intc/s390_flic_kvm.c |  43 ++++----------
 include/exec/memory.h   |  18 ++++++
 include/hw/core/cpu.h   |   4 ++
 memory.c                |  72 ++++++++++++++++++++--
 7 files changed, 233 insertions(+), 51 deletions(-)
Signature · 1 line
2.24.1
#1 lore raw

RFC PATCH v2 1/4 openpic_kvm: Use kvm_device_ioctl() instead of ioctl()

Let's use the official variant, which will e.g., trace the call.

Cc Markus Armbruster <[email protected]>
Cc "Philippe Mathieu-Daudé" <[email protected]>
Cc "Marc-André Lureau" <[email protected]>
Cc Paolo Bonzini <[email protected]>
---
 hw/intc/openpic_kvm.c | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
hw/intc/openpic_kvm.c +8 -8
index e4bf47d885..a5aa0ce915 100644
@@ -70,10 +70,10 @@ static void kvm_openpic_write(void *opaque, hwaddr addr, uint64_t val,
     attr.attr = addr;
     attr.addr = (uint64_t)(unsigned long)&val32;
 
-    ret = ioctl(opp->fd, KVM_SET_DEVICE_ATTR, &attr);
+    ret = kvm_device_ioctl(opp->fd, KVM_SET_DEVICE_ATTR, &attr);
     if (ret < 0) {
         qemu_log_mask(LOG_UNIMP, "%s: %s %" PRIx64 "\n", __func__,
-                      strerror(errno), attr.attr);
+                      strerror(-ret), attr.attr);
     }
 }
 
@@ -96,10 +96,10 @@ static uint64_t kvm_openpic_read(void *opaque, hwaddr addr, unsigned size)
     attr.attr = addr;
     attr.addr = (uint64_t)(unsigned long)&val;
 
-    ret = ioctl(opp->fd, KVM_GET_DEVICE_ATTR, &attr);
+    ret = kvm_device_ioctl(opp->fd, KVM_GET_DEVICE_ATTR, &attr);
     if (ret < 0) {
         qemu_log_mask(LOG_UNIMP, "%s: %s %" PRIx64 "\n", __func__,
-                      strerror(errno), attr.attr);
+                      strerror(-ret), attr.attr);
         return 0;
     }
 
@@ -145,10 +145,10 @@ static void kvm_openpic_region_add(MemoryListener *listener,
     attr.attr = KVM_DEV_MPIC_BASE_ADDR;
     attr.addr = (uint64_t)(unsigned long)&reg_base;
 
-    ret = ioctl(opp->fd, KVM_SET_DEVICE_ATTR, &attr);
+    ret = kvm_device_ioctl(opp->fd, KVM_SET_DEVICE_ATTR, &attr);
     if (ret < 0) {
         fprintf(stderr, "%s: %s %" PRIx64 "\n", __func__,
-                strerror(errno), reg_base);
+                strerror(-ret), reg_base);
     }
 }
 
@@ -179,10 +179,10 @@ static void kvm_openpic_region_del(MemoryListener *listener,
     attr.attr = KVM_DEV_MPIC_BASE_ADDR;
     attr.addr = (uint64_t)(unsigned long)&reg_base;
 
-    ret = ioctl(opp->fd, KVM_SET_DEVICE_ATTR, &attr);
+    ret = kvm_device_ioctl(opp->fd, KVM_SET_DEVICE_ATTR, &attr);
     if (ret < 0) {
         fprintf(stderr, "%s: %s %" PRIx64 "\n", __func__,
-                strerror(errno), reg_base);
+                strerror(-ret), reg_base);
     }
 }
 
Signature · 1 line
2.24.1
#2 lore raw

RFC PATCH v2 2/4 intc/s390_flic_kvm.c: Use kvm_device_ioctl() instead of ioctl()

In reply to David Hildenbrand

Let's use the official variant, which will e.g., trace the call. kvm_device_ioctl() will do the rc -> -errno conversion automatically, so we can drop that code.

Cc Cornelia Huck <[email protected]>
Cc Halil Pasic <[email protected]>
Cc Christian Borntraeger <[email protected]>
---
 hw/intc/s390_flic_kvm.c | 43 ++++++++++++-----------------------------
 1 file changed, 12 insertions(+), 31 deletions(-)
hw/intc/s390_flic_kvm.c +12 -31
index a306b26faa..ce05306406 100644
@@ -66,11 +66,8 @@ static int flic_get_all_irqs(KVMS390FLICState *flic,
         .addr = (uint64_t) buf,
         .attr = len,
     };
-    int rc;
 
-    rc = ioctl(flic->fd, KVM_GET_DEVICE_ATTR, &attr);
-
-    return rc == -1 ? -errno : rc;
+    return kvm_device_ioctl(flic->fd, KVM_GET_DEVICE_ATTR, &attr);
 }
 
 static void flic_enable_pfault(KVMS390FLICState *flic)
@@ -78,11 +75,8 @@ static void flic_enable_pfault(KVMS390FLICState *flic)
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_APF_ENABLE,
     };
-    int rc;
-
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 
-    if (rc) {
+    if (kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr)) {
         fprintf(stderr, "flic: couldn't enable pfault\n");
     }
 }
@@ -92,11 +86,8 @@ static void flic_disable_wait_pfault(KVMS390FLICState *flic)
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_APF_DISABLE_WAIT,
     };
-    int rc;
 
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-
-    if (rc) {
+    if (kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr)) {
         fprintf(stderr, "flic: couldn't disable pfault\n");
     }
 }
@@ -111,16 +102,13 @@ static void flic_disable_wait_pfault(KVMS390FLICState *flic)
 static int flic_enqueue_irqs(void *buf, uint64_t len,
                             KVMS390FLICState *flic)
 {
-    int rc;
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_ENQUEUE,
         .addr = (uint64_t) buf,
         .attr = len,
     };
 
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-
-    return rc ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static void kvm_s390_inject_flic(S390FLICState *fs, struct kvm_s390_irq *irq)
@@ -187,7 +175,6 @@ static int kvm_s390_clear_io_flic(S390FLICState *fs, uint16_t subchannel_id,
                            uint16_t subchannel_nr)
 {
     KVMS390FLICState *flic = s390_get_kvm_flic(fs);
-    int rc;
     uint32_t sid = subchannel_id << 16 | subchannel_nr;
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_CLEAR_IO_IRQ,
@@ -197,8 +184,7 @@ static int kvm_s390_clear_io_flic(S390FLICState *fs, uint16_t subchannel_id,
     if (unlikely(!flic->clear_io_supported)) {
         return -ENOSYS;
     }
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-    return rc ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_modify_ais_mode(S390FLICState *fs, uint8_t isc,
@@ -218,7 +204,7 @@ static int kvm_s390_modify_ais_mode(S390FLICState *fs, uint8_t isc,
         return -ENOSYS;
     }
 
-    return ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr) ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_inject_airq(S390FLICState *fs, uint8_t type,
@@ -235,7 +221,7 @@ static int kvm_s390_inject_airq(S390FLICState *fs, uint8_t type,
         return -ENOSYS;
     }
 
-    return ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr) ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 /**
@@ -285,7 +271,6 @@ static int kvm_s390_register_io_adapter(S390FLICState *fs, uint32_t id,
         .flags = flags,
     };
     KVMS390FLICState *flic = KVM_S390_FLIC(fs);
-    int r;
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_ADAPTER_REGISTER,
         .addr = (uint64_t)&adapter,
@@ -296,9 +281,7 @@ static int kvm_s390_register_io_adapter(S390FLICState *fs, uint32_t id,
         return 0;
     }
 
-    r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-
-    return r ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_io_adapter_map(S390FLICState *fs, uint32_t id,
@@ -314,15 +297,13 @@ static int kvm_s390_io_adapter_map(S390FLICState *fs, uint32_t id,
         .addr = (uint64_t)&req,
     };
     KVMS390FLICState *flic = s390_get_kvm_flic(fs);
-    int r;
 
     if (!kvm_gsi_routing_enabled()) {
         /* nothing to do */
         return 0;
     }
 
-    r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-    return r ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_add_adapter_routes(S390FLICState *fs,
@@ -519,7 +500,7 @@ static int kvm_flic_ais_post_load(void *opaque, int version_id)
         return -ENOSYS;
     }
 
-    return ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr) ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static const VMStateDescription kvm_s390_flic_ais_tmp = {
@@ -636,9 +617,9 @@ static void kvm_s390_flic_reset(DeviceState *dev)
         }
     }
 
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
+    rc = kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
     if (rc) {
-        trace_flic_reset_failed(errno);
+        trace_flic_reset_failed(-rc);
     }
 
     flic_enable_pfault(flic);
Signature · 1 line
2.24.1
Reviewed-by on v2 2/4
#3 lore raw

Re: [PATCH RFCv2 2/4] intc/s390_flic_kvm.c: Use kvm_device_ioctl() instead of ioctl()

Quoted 9 lines · David Hildenbrand

Let's use the official variant, which will e.g., trace the call. kvm_device_ioctl() will do the rc -> -errno conversion automatically, so we can drop that code.

Cc Cornelia Huck <[email protected]>
Cc Halil Pasic <[email protected]>
Cc Christian Borntraeger <[email protected]>
Quoted 159 lines
---
 hw/intc/s390_flic_kvm.c | 43 ++++++++++++-----------------------------
 1 file changed, 12 insertions(+), 31 deletions(-)
hw/intc/s390_flic_kvm.c +12 -31
index a306b26faa..ce05306406 100644
@@ -66,11 +66,8 @@ static int flic_get_all_irqs(KVMS390FLICState *flic,
         .addr = (uint64_t) buf,
         .attr = len,
     };
-    int rc;
 
-    rc = ioctl(flic->fd, KVM_GET_DEVICE_ATTR, &attr);
-
-    return rc == -1 ? -errno : rc;
+    return kvm_device_ioctl(flic->fd, KVM_GET_DEVICE_ATTR, &attr);
 }
 
 static void flic_enable_pfault(KVMS390FLICState *flic)
@@ -78,11 +75,8 @@ static void flic_enable_pfault(KVMS390FLICState *flic)
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_APF_ENABLE,
     };
-    int rc;
-
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 
-    if (rc) {
+    if (kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr)) {
         fprintf(stderr, "flic: couldn't enable pfault\n");
     }
 }
@@ -92,11 +86,8 @@ static void flic_disable_wait_pfault(KVMS390FLICState *flic)
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_APF_DISABLE_WAIT,
     };
-    int rc;
 
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-
-    if (rc) {
+    if (kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr)) {
         fprintf(stderr, "flic: couldn't disable pfault\n");
     }
 }
@@ -111,16 +102,13 @@ static void flic_disable_wait_pfault(KVMS390FLICState *flic)
 static int flic_enqueue_irqs(void *buf, uint64_t len,
                             KVMS390FLICState *flic)
 {
-    int rc;
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_ENQUEUE,
         .addr = (uint64_t) buf,
         .attr = len,
     };
 
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-
-    return rc ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static void kvm_s390_inject_flic(S390FLICState *fs, struct kvm_s390_irq *irq)
@@ -187,7 +175,6 @@ static int kvm_s390_clear_io_flic(S390FLICState *fs, uint16_t subchannel_id,
                            uint16_t subchannel_nr)
 {
     KVMS390FLICState *flic = s390_get_kvm_flic(fs);
-    int rc;
     uint32_t sid = subchannel_id << 16 | subchannel_nr;
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_CLEAR_IO_IRQ,
@@ -197,8 +184,7 @@ static int kvm_s390_clear_io_flic(S390FLICState *fs, uint16_t subchannel_id,
     if (unlikely(!flic->clear_io_supported)) {
         return -ENOSYS;
     }
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-    return rc ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_modify_ais_mode(S390FLICState *fs, uint8_t isc,
@@ -218,7 +204,7 @@ static int kvm_s390_modify_ais_mode(S390FLICState *fs, uint8_t isc,
         return -ENOSYS;
     }
 
-    return ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr) ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_inject_airq(S390FLICState *fs, uint8_t type,
@@ -235,7 +221,7 @@ static int kvm_s390_inject_airq(S390FLICState *fs, uint8_t type,
         return -ENOSYS;
     }
 
-    return ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr) ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 /**
@@ -285,7 +271,6 @@ static int kvm_s390_register_io_adapter(S390FLICState *fs, uint32_t id,
         .flags = flags,
     };
     KVMS390FLICState *flic = KVM_S390_FLIC(fs);
-    int r;
     struct kvm_device_attr attr = {
         .group = KVM_DEV_FLIC_ADAPTER_REGISTER,
         .addr = (uint64_t)&adapter,
@@ -296,9 +281,7 @@ static int kvm_s390_register_io_adapter(S390FLICState *fs, uint32_t id,
         return 0;
     }
 
-    r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-
-    return r ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_io_adapter_map(S390FLICState *fs, uint32_t id,
@@ -314,15 +297,13 @@ static int kvm_s390_io_adapter_map(S390FLICState *fs, uint32_t id,
         .addr = (uint64_t)&req,
     };
     KVMS390FLICState *flic = s390_get_kvm_flic(fs);
-    int r;
 
     if (!kvm_gsi_routing_enabled()) {
         /* nothing to do */
         return 0;
     }
 
-    r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
-    return r ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static int kvm_s390_add_adapter_routes(S390FLICState *fs,
@@ -519,7 +500,7 @@ static int kvm_flic_ais_post_load(void *opaque, int version_id)
         return -ENOSYS;
     }
 
-    return ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr) ? -errno : 0;
+    return kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
 }
 
 static const VMStateDescription kvm_s390_flic_ais_tmp = {
@@ -636,9 +617,9 @@ static void kvm_s390_flic_reset(DeviceState *dev)
         }
     }
 
-    rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
+    rc = kvm_device_ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr);
     if (rc) {
-        trace_flic_reset_failed(errno);
+        trace_flic_reset_failed(-rc);
     }
 
     flic_enable_pfault(flic);
#4 lore raw

RFC PATCH v2 3/4 memory: Add region_resize() callback to memory notifier

In reply to David Hildenbrand

Let's provide a way for memory notifiers to get notified about a resize. If the region_resize() callback is not implemented by a notifier, we mimic the old behavior by removing the old section and adding the new, resized section.

This callback is helpful when backends (like KVM) want to implement atomic resizes of memory sections (e.g., resize while VCPUs are running and using the section).

For now, we won't bother about a resize() callback for coalesced MMIO regions. The main future use case is for virtio-mem to resize ram memory regions while the guest is running.

Cc Richard Henderson <[email protected]>
Cc Paolo Bonzini <[email protected]>
Cc "Dr. David Alan Gilbert" <[email protected]>
Cc Eduardo Habkost <[email protected]>
Cc Marcel Apfelbaum <[email protected]>
Cc Igor Mammedov <[email protected]>
---
 include/exec/memory.h | 18 +++++++++++
 memory.c              | 72 ++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 85 insertions(+), 5 deletions(-)
include/exec/memory.h +18 -0
index 74805dd448..704eb64d75 100644
@@ -492,6 +492,24 @@ struct MemoryListener {
      */
     void (*region_nop)(MemoryListener *listener, MemoryRegionSection *section);
 
+    /**
+     * @region_resize:
+     *
+     * Called during an address space update transaction,
+     * for a section of the address space that is in the same place in the
+     * address space as in the last transaction, however, the size changed.
+     * Dirty memory logging can change as well.
+     *
+     * Note: If this callback is not implemented, the resize is communicated
+     *       via a region_del(), followed by a region_add() instead.
+     *
+     * @listener: The #MemoryListener.
+     * @section: The old #MemoryRegionSection.
+     * @new: The new size.
+     */
+    void (*region_resize)(MemoryListener *listener,
+                          MemoryRegionSection *section, Int128 new);
+
     /**
      * @log_start:
      *
memory.c +67 -5

90 lines not on this page · raw message

Signature · 1 line
2.24.1
#5 lore raw

RFC PATCH v2 4/4 kvm: Implement atomic memory region resizes via region_resize()

In reply to David Hildenbrand

virtio-mem wants to resize (esp. grow) ram memory regions while the guest is already aware of them and makes use of them. Resizing a KVM slot can only currently be done by removing it and re-adding it. While the kvm slot is temporarily removed, VCPUs that try to access memory on these slots (via KVM_RUN) will fault. But also, other ioctls might depend on all slots being in place.

Let's inhibit most KVM ioctls while performing the resize. Once we have an ioctl that can perform atomic resizes (e.g., KVM_SET_USER_MEMORY_REGION extensions), we can make inhibiting optional at runtime.

To minimize cache-line bouncing, use separate indicators (in_ioctl) and locks (ioctl_mutex) per CPU. Also, make sure to hold the kvm_slots_lock while performing both actions (removing+re-adding).

We have to wait until all IOCTLs were exited and block new ones from getting executed. Kick all CPUs, so they will exit the KVM_RUN ioctl.

This approach cannot result in a deadlock as long as the inhibitor does not hold any locks that might hinder an IOCTL from getting finished and exited - something fairly unusual. The inhibitor will always hold the BQL.

AFAIKs, one possible candidate would be userfaultfd. If a page cannot be placed (e.g., during postcopy), because we're waiting for a lock, or if the userfaultfd thread cannot process a fault, because it is waiting for a lock, there could be a deadlock. However, the BQL is not applicable here, because any other guest memory access while holding the BQL would already result in a deadlock.

Nothing else in the kernel should block forever and wait for userspace intervention.

Note1: Resizes of memory regions currently seems to happen during bootup only, so I don't think any existing RT users should be affected.

Note2: pause_all_vcpus()/resume_all_vcpus() or start_exclusive()/end_exclusive() cannot be used, as they either drop the BQL or require to be called without the BQL - something inhibitors cannot handle. We need a low-level locking mechanism that is deadlock-free even when not releasing the BQL.

Cc Richard Henderson <[email protected]>
Cc Paolo Bonzini <[email protected]>
Cc "Dr. David Alan Gilbert" <[email protected]>
Cc Eduardo Habkost <[email protected]>
Cc Marcel Apfelbaum <[email protected]>
Cc Igor Mammedov <[email protected]>
---
 accel/kvm/kvm-all.c   | 129 +++++++++++++++++++++++++++++++++++++++---
 hw/core/cpu.c         |   2 +
 include/hw/core/cpu.h |   4 ++
 3 files changed, 128 insertions(+), 7 deletions(-)
accel/kvm/kvm-all.c +122 -7
index 439a4efe52..be159a2f78 100644
@@ -149,6 +149,21 @@ bool kvm_msi_use_devid;
 static bool kvm_immediate_exit;
 static hwaddr kvm_max_slot_size = ~0;
 
+/*
+ * While holding kvm_ioctl_mutex and all cpu->ioctl_mutex, no new KVM ioctls
+ * can be started, but kvm ioctl inhibitors will have to wait for existing ones
+ * to finish (indicated by cpu->in_ioctl and kvm_in_ioctl, both updated with
+ * kvm_ioctl_mutex or under the cpu->ioctl_mutex when entering the ioctl).
+ */
+QemuMutex kvm_ioctl_mutex;
+/*
+ * Atomic counter of active KVM ioctls except
+ * - The KVM ioctl inhibitor is doing an ioctl
+ * - kvm_ioctl(): Harmless and not interesting for inhibitors.
+ * - kvm_vcpu_ioctl(): Tracked via cpu->in_ioctl.
+ */
+static int kvm_in_ioctl;
+
 static const KVMCapabilityInfo kvm_required_capabilites[] = {
     KVM_CAP_INFO(USER_MEMORY),
     KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
@@ -1023,6 +1038,7 @@ void kvm_set_max_memslot_size(hwaddr max_slot_size)
     kvm_max_slot_size = max_slot_size;
 }
 
+/* Called with KVMMemoryListener.slots_lock held */
 static void kvm_set_phys_mem(KVMMemoryListener *kml,
                              MemoryRegionSection *section, bool add)
 {
@@ -1052,14 +1068,12 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,
     ram = memory_region_get_ram_ptr(mr) + section->offset_within_region +
           (start_addr - section->offset_within_address_space);
 
-    kvm_slots_lock(kml);
-
     if (!add) {
         do {
             slot_size = MIN(kvm_max_slot_size, size);
             mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
             if (!mem) {
-                goto out;
+                return;
             }
             if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
                 kvm_physical_sync_dirty_bitmap(kml, section);
@@ -1079,7 +1093,7 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,
             start_addr += slot_size;
             size -= slot_size;
         } while (size);
-        goto out;
+        return;
     }
 
     /* register the new slot */
@@ -1108,9 +1122,6 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,
         ram += slot_size;
         size -= slot_size;
     } while (size);
-
-out:
-    kvm_slots_unlock(kml);
 }
 
 static void kvm_region_add(MemoryListener *listener,
@@ -1119,7 +1130,9 @@ static void kvm_region_add(MemoryListener *listener,
     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
 
     memory_region_ref(section->mr);
+    kvm_slots_lock(kml);
     kvm_set_phys_mem(kml, section, true);
+    kvm_slots_unlock(kml);
 }
 
 static void kvm_region_del(MemoryListener *listener,
@@ -1127,10 +1140,76 @@ static void kvm_region_del(MemoryListener *listener,
 {
     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
 
+    kvm_slots_lock(kml);
     kvm_set_phys_mem(kml, section, false);
+    kvm_slots_unlock(kml);
     memory_region_unref(section->mr);
 }
 
+/*
+ * Certain updates (e.g., resizing memory regions) require temporarily removing
+ * kvm memory slots. Make sure any ioctl sees a consistent memory slot state.
+ */
+static void kvm_ioctl_inhibit_begin(void)
+{
+    CPUState *cpu;
+
+    /*
+     * We allow to inhibit only when holding the BQL, so we can identify
+     * when an inhibitor wants to issue an ioctl easily.
+     */
+    g_assert(qemu_mutex_iothread_locked());
+
+    CPU_FOREACH(cpu) {
+        qemu_mutex_lock(&cpu->ioctl_mutex);
+    }
+    qemu_mutex_lock(&kvm_ioctl_mutex);
+
+    /* Inhibiting happens rarely, we can keep things simple and spin here. */
+    while (true) {
+        bool any_cpu_in_ioctl = false;
+
+        CPU_FOREACH(cpu) {
+            if (atomic_read(&cpu->in_ioctl)) {
+                any_cpu_in_ioctl = true;
+                qemu_cpu_kick(cpu);
+            }
+        }
+        if (!any_cpu_in_ioctl && !atomic_read(&kvm_in_ioctl)) {
+            break;
+        }
+        g_usleep(100);
+    }
+}
+
+static void kvm_ioctl_inhibit_end(void)
+{
+    CPUState *cpu;
+
+    qemu_mutex_unlock(&kvm_ioctl_mutex);
+    CPU_FOREACH(cpu) {
+        qemu_mutex_unlock(&cpu->ioctl_mutex);
+    }
+}
+
+static void kvm_region_resize(MemoryListener *listener,
+                              MemoryRegionSection *section, Int128 new)
+{
+    KVMMemoryListener *kml = container_of(listener, KVMMemoryListener,
+                                          listener);
+    MemoryRegionSection new_section = *section;
+
+    new_section.size = new;
+
+    kvm_slots_lock(kml);
+    /* Inhibit KVM ioctls while temporarily removing slots. */
+    kvm_ioctl_inhibit_begin();
+    kvm_set_phys_mem(kml, section, false);
+    kvm_set_phys_mem(kml, &new_section, true);
+    kvm_ioctl_inhibit_end();
+    kvm_slots_unlock(kml);
+}
+
 static void kvm_log_sync(MemoryListener *listener,
                          MemoryRegionSection *section)
 {
@@ -1249,6 +1328,7 @@ void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
 
     kml->listener.region_add = kvm_region_add;
     kml->listener.region_del = kvm_region_del;
+    kml->listener.region_resize = kvm_region_resize;
     kml->listener.log_start = kvm_log_start;
     kml->listener.log_stop = kvm_log_stop;
     kml->listener.log_sync = kvm_log_sync;
@@ -1894,6 +1974,7 @@ static int kvm_init(MachineState *ms)
     assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size);
 
     s->sigmask_len = 8;
+    qemu_mutex_init(&kvm_ioctl_mutex);
 
 #ifdef KVM_CAP_SET_GUEST_DEBUG
     QTAILQ_INIT(&s->kvm_sw_breakpoints);
@@ -2304,6 +2385,34 @@ static void kvm_eat_signals(CPUState *cpu)
     } while (sigismember(&chkset, SIG_IPI));
 }
 
+static void kvm_cpu_set_in_ioctl(CPUState *cpu, bool in_ioctl)
+{
+    if (unlikely(qemu_mutex_iothread_locked())) {
+        return;
+    }
+    if (in_ioctl) {
+        qemu_mutex_lock(&cpu->ioctl_mutex);
+        cpu->in_ioctl = true;
+        qemu_mutex_unlock(&cpu->ioctl_mutex);
+    } else {
+        atomic_set(&cpu->in_ioctl, false);
+    }
+}
+
+static void kvm_set_in_ioctl(bool in_ioctl)
+{
+    if (likely(qemu_mutex_iothread_locked())) {
+        return;
+    }
+    if (in_ioctl) {
+        qemu_mutex_lock(&kvm_ioctl_mutex);
+        kvm_in_ioctl++;
+        qemu_mutex_unlock(&kvm_ioctl_mutex);
+    } else {
+        atomic_dec(&kvm_in_ioctl);
+    }
+}
+
 int kvm_cpu_exec(CPUState *cpu)
 {
     struct kvm_run *run = cpu->kvm_run;
@@ -2488,7 +2597,9 @@ int kvm_vm_ioctl(KVMState *s, int type, ...)
     va_end(ap);
 
     trace_kvm_vm_ioctl(type, arg);
+    kvm_set_in_ioctl(true);
     ret = ioctl(s->vmfd, type, arg);
+    kvm_set_in_ioctl(false);
     if (ret == -1) {
         ret = -errno;
     }
@@ -2506,7 +2617,9 @@ int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
     va_end(ap);
 
     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
+    kvm_cpu_set_in_ioctl(cpu, true);
     ret = ioctl(cpu->kvm_fd, type, arg);
+    kvm_cpu_set_in_ioctl(cpu, false);
     if (ret == -1) {
         ret = -errno;
     }
@@ -2524,7 +2637,9 @@ int kvm_device_ioctl(int fd, int type, ...)
     va_end(ap);
 
     trace_kvm_device_ioctl(fd, type, arg);
+    kvm_set_in_ioctl(true);
     ret = ioctl(fd, type, arg);
+    kvm_set_in_ioctl(false);
     if (ret == -1) {
         ret = -errno;
     }
hw/core/cpu.c +2 -0
index fe65ca62ac..3591dc3874 100644
@@ -379,6 +379,7 @@ static void cpu_common_initfn(Object *obj)
     cpu->nr_threads = 1;
 
     qemu_mutex_init(&cpu->work_mutex);
+    qemu_mutex_init(&cpu->ioctl_mutex);
     QTAILQ_INIT(&cpu->breakpoints);
     QTAILQ_INIT(&cpu->watchpoints);
 
@@ -389,6 +390,7 @@ static void cpu_common_finalize(Object *obj)
 {
     CPUState *cpu = CPU(obj);
 
+    qemu_mutex_destroy(&cpu->ioctl_mutex);
     qemu_mutex_destroy(&cpu->work_mutex);
 }
 
include/hw/core/cpu.h +4 -0
index 73e9a869a4..3abf251037 100644
@@ -431,6 +431,10 @@ struct CPUState {
     /* shared by kvm, hax and hvf */
     bool vcpu_dirty;
 
+    /* kvm only for now: CPU is in kvm_vcpu_ioctl() (esp. KVM_RUN) */
+    bool in_ioctl;
+    QemuMutex ioctl_mutex;
+
     /* Used to keep track of an outstanding cpu throttle thread for migration
      * autoconverge
      */
Signature · 1 line
2.24.1