Skip to contentSkip to conversation

Make RamDiscardManager work with multiple sources & virtio-mem

PATCH Applied Marc-André Lureau 7 participants 28 messages Jun 4 – Jun 22

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v5 cover Make RamDiscardManager work with multiple sources & virtio-mem

Hi,

This is an attempt to fix the incompatibility of virtio-mem with confidential VMs. The solution implements what was discussed earlier with D. Hildenbrand:
https://patchwork.ozlabs.org/project/qemu-devel/patch/[email protected]/#3502238

The first patches are misc cleanups. Then some code refactoring to have split a manager/source. And finally, the manager learns to deal with multiple sources.

This has been tested together with the Linux kernel series from Zhenzhong Duan [1] for TDX guests.

(help fix https://issues.redhat.com/browse/RHEL-131968)

v5:
- explain why InterfaceClass in rust binding is not needed after moving RamDiscardSource
- drop extraneous added blank line
- replaced a runtime "if (has_rdm)"" with an assert()
- dropped "RFC: hw/virtio: start virtio-mem guest_memfd regions as shared", in favour of start-private memory approach from "[RFC PATCH 0/6] Support virtio-mem memory hotplug in TDX guests" [1]
- demote "monitor: add 'info ramblock-attributes'" as RFC
- rebased and collected trailers

v4:
- added "system/physmem: make ram_block_discard_range() handle guest_memfd"
- added "monitor: add 'info ramblock-attributes' command"
- added "RFC: hw/virtio: start virtio-mem guest_memfd regions as shared"
- skip calling source in notify_populate (it may not have updated its internal state)
- rebased, collected trailer tags

v3: issues found by Cédric
- fix assertion error on shutdown, due to rcu-defer cleanup
- fix API doc warnings

v2:
- drop replay_{populated,discarded} from source, suggested by Peter Xu
- add extra manager cleanup
- add r-b tags for preliminary patches

- Link to v4: https://lore.kernel.org/qemu-devel/[email protected]

[1]: https://lore.kernel.org/lkml/[email protected]/

---
Marc-André Lureau (12):
system/memory: split RamDiscardManager into source and manager system/memory: move RamDiscardManager to separate compilation unit system/memory: constify section arguments system/ram-discard-manager: implement replay via is_populated iteration
virtio-mem: remove replay_populated/replay_discarded implementation system/ram-discard-manager: drop replay from source interface system/memory: implement RamDiscardManager multi-source aggregation system/physmem: destroy ram block attributes before RCU-deferred reclaim system/memory: add RamDiscardManager reference counting and cleanup
tests: add unit tests for RamDiscardManager multi-source aggregation system/physmem: make ram_block_discard_range() handle guest_memfd
RFC: monitor: add 'info ramblock-attributes' command

 MAINTAINERS                                 |    4 +
 qapi/machine.json                           |   56 ++
 include/hw/vfio/vfio-container.h            |    2 +-
 include/hw/vfio/vfio-cpr.h                  |    2 +-
 include/hw/virtio/virtio-mem.h              |    3 -
 include/monitor/hmp.h                       |    1 +
 include/system/memory.h                     |  279 +-----
 include/system/ram-discard-manager.h        |  358 ++++++++
 include/system/ramblock.h                   |    5 +-
 accel/kvm/kvm-all.c                         |    2 +-
 hw/core/machine-hmp-cmds.c                  |   32 +
 hw/vfio/cpr-legacy.c                        |    4 +-
 hw/vfio/listener.c                          |   10 +-
 hw/virtio/virtio-mem.c                      |  259 +-----
 migration/ram.c                             |    6 +-
 system/memory.c                             |   88 +-
 system/memory_mapping.c                     |    4 +-
 system/physmem.c                            |   27 +-
 system/ram-block-attributes.c               |  328 +++----
 system/ram-discard-manager.c                |  612 +++++++++++++
 target/i386/kvm/tdx.c                       |    2 +-
 tests/unit/test-ram-discard-manager-stubs.c |   48 ++
 tests/unit/test-ram-discard-manager.c       | 1235 +++++++++++++++++++++++++++
 hmp-commands-info.hx                        |   13 +
 rust/bindings/system-sys/lib.rs             |    2 +-
 system/meson.build                          |    1 +
 system/trace-events                         |    2 +-
 tests/unit/meson.build                      |    8 +-
 28 files changed, 2569 insertions(+), 824 deletions(-)

---
base-commit: 405c32d2b18a683ba36301351af75125d9afda08
change-id: 20260414-rdm5-b6df2366d603

Best regards,

Signature · 1 line
Marc-André Lureau <[email protected]>
#1 lore raw

PATCH v5 1/12 system/memory: split RamDiscardManager into source and manager

Refactor the RamDiscardManager interface into two distinct components:
- RamDiscardSource: An interface that state providers (virtio-mem, RamBlockAttributes) implement to provide discard state information (granularity, populated/discarded ranges, replay callbacks).
- RamDiscardManager: A concrete QOM object that wraps a source, owns the listener list, and handles listener registration/unregistration and notifications.

This separation moves the listener management logic from individual source implementations into the central RamDiscardManager, reducing code duplication between virtio-mem and RamBlockAttributes.

The change prepares for future work where a RamDiscardManager could aggregate multiple sources.

Note, the original virtio-mem code had conditions before discard:

  if (vmem->size) {
      rdl->notify_discard(rdl, rdl->section);

}
however, the new code calls discard unconditionally. This is considered safe, since the populate/discard of sections are already asymmetrical (unplug & unregister all listener section unconditionally).

---
 include/hw/virtio/virtio-mem.h |   3 -
 include/system/memory.h        | 197 +++++++++++++++++++++----------------
 include/system/ramblock.h      |   2 -
 hw/virtio/virtio-mem.c         | 163 ++++++------------------------
 system/memory.c                | 218 ++++++++++++++++++++++++++++++++++++-----
 system/ram-block-attributes.c  | 171 ++++++++++----------------------
 6 files changed, 385 insertions(+), 369 deletions(-)
include/hw/virtio/virtio-mem.h +0 -3
index 221cfd76bf9..5d1d19c6bec 100644
@@ -118,9 +118,6 @@ struct VirtIOMEM {
     /* notifiers to notify when "size" changes */
     NotifierList size_change_notifiers;
 
-    /* listeners to notify on plug/unplug activity. */
-    QLIST_HEAD(, RamDiscardListener) rdl_list;
-
     /* Catch system resets -> qemu_devices_reset() only. */
     VirtioMemSystemReset *system_reset;
 };
include/system/memory.h +111 -86

302 lines not on this page · raw message

include/system/ramblock.h +0 -2
index 4435f8d55fe..2b38718fe5f 100644
@@ -99,8 +99,6 @@ struct RamBlockAttributes {
     /* 1-setting of the bitmap represents ram is populated (shared) */
     unsigned bitmap_size;
     unsigned long *bitmap;
-
-    QLIST_HEAD(, RamDiscardListener) rdl_list;
 };
 
 /* @offset: the offset within the RAMBlock */
hw/virtio/virtio-mem.c +32 -131

297 lines not on this page · raw message

system/memory.c +191 -27

279 lines not on this page · raw message

system/ram-block-attributes.c +51 -120

262 lines not on this page · raw message

Signature · 1 line
2.54.0
Reviewed-by on v5 1/12
#2 lore raw

Re: [PATCH v5 01/12] system/memory: split RamDiscardManager into source and manager

Quoted 45 lines · Marc-André Lureau

Refactor the RamDiscardManager interface into two distinct components:
- RamDiscardSource: An interface that state providers (virtio-mem, RamBlockAttributes) implement to provide discard state information (granularity, populated/discarded ranges, replay callbacks).
- RamDiscardManager: A concrete QOM object that wraps a source, owns the listener list, and handles listener registration/unregistration and notifications.

This separation moves the listener management logic from individual source implementations into the central RamDiscardManager, reducing code duplication between virtio-mem and RamBlockAttributes.

The change prepares for future work where a RamDiscardManager could aggregate multiple sources.

Note, the original virtio-mem code had conditions before discard:

   if (vmem->size) {
       rdl->notify_discard(rdl, rdl->section);
   }

however, the new code calls discard unconditionally. This is considered safe, since the populate/discard of sections are already asymmetrical (unplug & unregister all listener section unconditionally).

---
  include/hw/virtio/virtio-mem.h |   3 -
  include/system/memory.h        | 197 +++++++++++++++++++++----------------
  include/system/ramblock.h      |   2 -
  hw/virtio/virtio-mem.c         | 163 ++++++------------------------
  system/memory.c                | 218 ++++++++++++++++++++++++++++++++++++-----
  system/ram-block-attributes.c  | 171 ++++++++++----------------------
  6 files changed, 385 insertions(+), 369 deletions(-)
system/memory.c +9 -0
+int ram_discard_manager_notify_populate(RamDiscardManager *rdm,
+                                        uint64_t offset, uint64_t size)
+{
+    RamDiscardListener *rdl, *rdl2;
+    int ret = 0;
+
+    QLIST_FOREACH(rdl, &rdm->rdl_list, next) {
+        MemoryRegionSection tmp = *rdl->section;
+

system/memory.c int ram_discard_manager_replay_discarded(const RamDiscardManager *rdm, · line 2178

Quoted 10 lines
system/memory.c +10 -0
+        if (!memory_region_section_intersect_range(&tmp, offset, size)) {
+            continue;
+        }
+        ret = rdl->notify_populate(rdl, &tmp);
+        if (ret) {
+            break;
+        }
+    }
+
+    if (ret) {

(Pre-existing, reduce scope?)

           RamDiscardListener *rdl2;
Quoted 26 lines
system/memory.c +19 -1
+        /* Notify all already-notified listeners about discard. */
+        QLIST_FOREACH(rdl2, &rdm->rdl_list, next) {
+            MemoryRegionSection tmp = *rdl2->section;
+
+            if (rdl2 == rdl) {
+                break;
+            }
+            if (!memory_region_section_intersect_range(&tmp, offset, size)) {
+                continue;
+            }
+            rdl2->notify_discard(rdl2, &tmp);
+        }
+    }
+    return ret;
+}
 
 
  void ram_discard_manager_register_listener(RamDiscardManager *rdm,
                                             RamDiscardListener *rdl,
                                             MemoryRegionSection *section)
  {
-    RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
+    int ret;
+
+    g_assert(section->mr == rdm->mr);
+

system/memory.c int ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,

Quoted 10 lines
system/memory.c +7 -2
+    rdl->section = memory_region_section_new_copy(section);
+    QLIST_INSERT_HEAD(&rdm->rdl_list, rdl, next);
 
-    g_assert(rdmc->register_listener);
-    rdmc->register_listener(rdm, rdl, section);
+    ret = ram_discard_source_replay_populated(rdm->rds, rdl->section,
+                                              rdm_populate_cb, rdl);
+    if (ret) {
+        error_report("%s: Replaying populated ranges failed: %s", __func__,
+                     strerror(-ret));

Pre-existing, should ram_discard_manager_register_listener propagate Error*? For example the current caller provides an errp (vfio_ram_discard_register_listener). Can be improved on top of course.

Quoted 2 lines

+ }
}

#3 lore raw

PATCH v5 2/12 system/memory: move RamDiscardManager to separate compilation unit

In reply to Marc-André Lureau

Extract RamDiscardManager and RamDiscardSource from system/memory.c into dedicated a unit.

This reduces coupling and allows code that only needs the RamDiscardManager interface to avoid pulling in all of memory.h dependencies.

rust-sys bindings are no longer generated for RamDiscardSourceClass at this point, thus we drop the unneeded InterfaceClass use.

---
 MAINTAINERS                          |   2 +
 include/system/memory.h              | 280 +--------------------------------
 include/system/ram-discard-manager.h | 297 +++++++++++++++++++++++++++++++++++
 system/memory.c                      | 221 --------------------------
 system/ram-discard-manager.c         | 240 ++++++++++++++++++++++++++++
 rust/bindings/system-sys/lib.rs      |   2 +-
 system/meson.build                   |   1 +
 7 files changed, 542 insertions(+), 501 deletions(-)
MAINTAINERS +2 -0
index 7752917d8cf..25dbb9f1a77 100644
@@ -3346,6 +3346,7 @@ F: include/system/memory.h
 F: include/system/memory_cached.h
 F: include/system/memory_ldst*
 F: include/system/physmem.h
+F: include/system/ram-discard-manager.h
 F: include/system/ramblock.h
 F: include/system/memory_mapping.h
 F: system/dma-helpers.c
@@ -3356,6 +3357,7 @@ F: system/physmem.c
 F: system/memory_ldst*
 F: system/memory-internal.h
 F: system/ram-block-attributes.c
+F: system/ram-discard-manager.c
 F: scripts/coccinelle/memory-region-housekeeping.cocci
 
 Memory devices
include/system/memory.h +1 -279

298 lines not on this page · raw message

include/system/ram-discard-manager.h new file +297 -0

297 lines not on this page · raw message

system/memory.c +0 -221

243 lines not on this page · raw message

system/ram-discard-manager.c new file +240 -0

240 lines not on this page · raw message

rust/bindings/system-sys/lib.rs +1 -1
index 022fe65dd83..30adf683c35 100644
@@ -20,7 +20,7 @@
 
 use common::Zeroable;
 use hwcore_sys::{qemu_irq, DeviceClass, DeviceState};
-use qom_sys::{InterfaceClass, Object, ObjectClass};
+use qom_sys::{Object, ObjectClass};
 use util_sys::{Error, EventNotifier, QEMUBH};
 
 #[cfg(MESON)]
system/meson.build +1 -0
index 9cdfe1b3e75..cd3193d170b 100644
@@ -14,6 +14,7 @@ system_ss.add(files(
   'globals.c',
   'ioport.c',
   'ram-block-attributes.c',
+  'ram-discard-manager.c',
   'memory_mapping.c',
   'memory.c',
   'physmem.c',
Signature · 1 line
2.54.0
Reviewed-by on v5 2/12
#4 lore raw

Re: [PATCH v5 02/12] system/memory: move RamDiscardManager to separate compilation unit

Quoted 31 lines · Marc-André Lureau

Extract RamDiscardManager and RamDiscardSource from system/memory.c into dedicated a unit.

This reduces coupling and allows code that only needs the RamDiscardManager interface to avoid pulling in all of memory.h dependencies.

rust-sys bindings are no longer generated for RamDiscardSourceClass at this point, thus we drop the unneeded InterfaceClass use.

---
  MAINTAINERS                          |   2 +
  include/system/memory.h              | 280 +--------------------------------
  include/system/ram-discard-manager.h | 297 +++++++++++++++++++++++++++++++++++
  system/memory.c                      | 221 --------------------------
  system/ram-discard-manager.c         | 240 ++++++++++++++++++++++++++++
  rust/bindings/system-sys/lib.rs      |   2 +-
  system/meson.build                   |   1 +
  7 files changed, 542 insertions(+), 501 deletions(-)
include/system/ram-discard-manager.h new file +1 -0
new file mode 100644
index 00000000000..da55658169f
@@ -0,0 +1,297 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */

include/system/ram-discard-manager.h line 11

Quoted 10 lines
include/system/ram-discard-manager.h new file +10 -0
+/*
+ * RAM Discard Manager
+ *
+ * Copyright Red Hat, Inc. 2026
+ */
+
+#ifndef RAM_DISCARD_MANAGER_H
+#define RAM_DISCARD_MANAGER_H
+
+#include "qemu/typedefs.h"

Not needed, already provided in sources by "qemu/osdep.h".

Quoted 53 lines
include/system/ram-discard-manager.h new file +53 -0
+#include "qom/object.h"
+#include "qemu/queue.h"
+
+#define TYPE_RAM_DISCARD_MANAGER "ram-discard-manager"
+typedef struct RamDiscardManagerClass RamDiscardManagerClass;
+typedef struct RamDiscardManager RamDiscardManager;
+DECLARE_OBJ_CHECKERS(RamDiscardManager, RamDiscardManagerClass,
+                     RAM_DISCARD_MANAGER, TYPE_RAM_DISCARD_MANAGER);
+
+#define TYPE_RAM_DISCARD_SOURCE "ram-discard-source"
+typedef struct RamDiscardSourceClass RamDiscardSourceClass;
+typedef struct RamDiscardSource RamDiscardSource;
+DECLARE_OBJ_CHECKERS(RamDiscardSource, RamDiscardSourceClass,
+                     RAM_DISCARD_SOURCE, TYPE_RAM_DISCARD_SOURCE);
+
+typedef struct RamDiscardListener RamDiscardListener;
+typedef int (*NotifyRamPopulate)(RamDiscardListener *rdl,
+                                 MemoryRegionSection *section);
+typedef void (*NotifyRamDiscard)(RamDiscardListener *rdl,
+                                 MemoryRegionSection *section);
+
+struct RamDiscardListener {
+    /*
+     * @notify_populate:
+     *
+     * Notification that previously discarded memory is about to get populated.
+     * Listeners are able to object. If any listener objects, already
+     * successfully notified listeners are notified about a discard again.
+     *
+     * @rdl: the #RamDiscardListener getting notified
+     * @section: the #MemoryRegionSection to get populated. The section
+     *           is aligned within the memory region to the minimum granularity
+     *           unless it would exceed the registered section.
+     *
+     * Returns 0 on success. If the notification is rejected by the listener,
+     * an error is returned.
+     */
+    NotifyRamPopulate notify_populate;
+
+    /*
+     * @notify_discard:
+     *
+     * Notification that previously populated memory was discarded successfully
+     * and listeners should drop all references to such memory and prevent
+     * new population (e.g., unmap).
+     *
+     * @rdl: the #RamDiscardListener getting notified
+     * @section: the #MemoryRegionSection to get discarded. The section
+     *           is aligned within the memory region to the minimum granularity
+     *           unless it would exceed the registered section.
+     */
+    NotifyRamDiscard notify_discard;
+

include/system/ram-discard-manager.h line 74

Quoted 10 lines
include/system/ram-discard-manager.h new file +10 -0
+    MemoryRegionSection *section;
+    QLIST_ENTRY(RamDiscardListener) next;
+};
+
+static inline void ram_discard_listener_init(RamDiscardListener *rdl,
+                                             NotifyRamPopulate populate_fn,
+                                             NotifyRamDiscard discard_fn)
+{
+    rdl->notify_populate = populate_fn;
+    rdl->notify_discard = discard_fn;

Pre-existing, this initializer doesn't justify inlining in header.

Otherwise,

Quoted 1 line
include/system/ram-discard-manager.h new file +1 -0
+}
#5 lore raw

PATCH v5 3/12 system/memory: constify section arguments

In reply to Marc-André Lureau

The sections shouldn't be modified.

---
 include/hw/vfio/vfio-container.h     |  2 +-
 include/hw/vfio/vfio-cpr.h           |  2 +-
 include/system/ram-discard-manager.h | 14 +++++++-------
 hw/vfio/cpr-legacy.c                 |  4 ++--
 hw/vfio/listener.c                   | 10 +++++-----
 hw/virtio/virtio-mem.c               | 10 +++++-----
 migration/ram.c                      |  6 +++---
 system/memory_mapping.c              |  4 ++--
 system/ram-block-attributes.c        |  8 ++++----
 system/ram-discard-manager.c         | 10 +++++-----
 10 files changed, 35 insertions(+), 35 deletions(-)
include/hw/vfio/vfio-container.h +1 -1
index a7d5c5ed679..b2e7f4312c3 100644
@@ -277,7 +277,7 @@ struct VFIOIOMMUClass {
 };
 
 VFIORamDiscardListener *vfio_find_ram_discard_listener(
-    VFIOContainer *bcontainer, MemoryRegionSection *section);
+    VFIOContainer *bcontainer, const MemoryRegionSection *section);
 
 void vfio_container_region_add(VFIOContainer *bcontainer,
                                MemoryRegionSection *section, bool cpr_remap);
include/hw/vfio/vfio-cpr.h +1 -1
index 4606da500a7..ecabe0c747d 100644
@@ -69,7 +69,7 @@ void vfio_cpr_giommu_remap(struct VFIOContainer *bcontainer,
                            MemoryRegionSection *section);
 
 bool vfio_cpr_ram_discard_replay_populated(
-    struct VFIOContainer *bcontainer, MemoryRegionSection *section);
+    struct VFIOContainer *bcontainer, const MemoryRegionSection *section);
 
 void vfio_cpr_save_vector_fd(struct VFIOPCIDevice *vdev, const char *name,
                              int nr, int fd);
include/system/ram-discard-manager.h +7 -7
index da55658169f..b188e09a30f 100644
@@ -26,9 +26,9 @@ DECLARE_OBJ_CHECKERS(RamDiscardSource, RamDiscardSourceClass,
 
 typedef struct RamDiscardListener RamDiscardListener;
 typedef int (*NotifyRamPopulate)(RamDiscardListener *rdl,
-                                 MemoryRegionSection *section);
+                                 const MemoryRegionSection *section);
 typedef void (*NotifyRamDiscard)(RamDiscardListener *rdl,
-                                 MemoryRegionSection *section);
+                                 const MemoryRegionSection *section);
 
 struct RamDiscardListener {
     /*
@@ -86,7 +86,7 @@ static inline void ram_discard_listener_init(RamDiscardListener *rdl,
  *
  * Returns 0 on success, or a negative error if failed.
  */
-typedef int (*ReplayRamDiscardState)(MemoryRegionSection *section,
+typedef int (*ReplayRamDiscardState)(const MemoryRegionSection *section,
                                      void *opaque);
 
 /*
@@ -151,7 +151,7 @@ struct RamDiscardSourceClass {
      * Returns 0 on success, or a negative error if any notification failed.
      */
     int (*replay_populated)(const RamDiscardSource *rds,
-                            MemoryRegionSection *section,
+                            const MemoryRegionSection *section,
                             ReplayRamDiscardState replay_fn, void *opaque);
 
     /**
@@ -168,7 +168,7 @@ struct RamDiscardSourceClass {
      * Returns 0 on success, or a negative error if any notification failed.
      */
     int (*replay_discarded)(const RamDiscardSource *rds,
-                            MemoryRegionSection *section,
+                            const MemoryRegionSection *section,
                             ReplayRamDiscardState replay_fn, void *opaque);
 };
 
@@ -237,7 +237,7 @@ bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
  * Returns 0 on success, or a negative error if any notification failed.
  */
 int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
-                                         MemoryRegionSection *section,
+                                         const MemoryRegionSection *section,
                                          ReplayRamDiscardState replay_fn,
                                          void *opaque);
 
@@ -255,7 +255,7 @@ int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
  * Returns 0 on success, or a negative error if any notification failed.
  */
 int ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
-                                         MemoryRegionSection *section,
+                                         const MemoryRegionSection *section,
                                          ReplayRamDiscardState replay_fn,
                                          void *opaque);
 
hw/vfio/cpr-legacy.c +2 -2
index c431d899731..2d40d8baeaf 100644
@@ -226,7 +226,7 @@ void vfio_cpr_giommu_remap(VFIOContainer *bcontainer,
     memory_region_iommu_replay(giommu->iommu_mr, &giommu->n);
 }
 
-static int vfio_cpr_rdm_remap(MemoryRegionSection *section, void *opaque)
+static int vfio_cpr_rdm_remap(const MemoryRegionSection *section, void *opaque)
 {
     RamDiscardListener *rdl = opaque;
 
@@ -242,7 +242,7 @@ static int vfio_cpr_rdm_remap(MemoryRegionSection *section, void *opaque)
  * directly, which calls vfio_legacy_cpr_dma_map.
  */
 bool vfio_cpr_ram_discard_replay_populated(VFIOContainer *bcontainer,
-                                           MemoryRegionSection *section)
+                                           const MemoryRegionSection *section)
 {
     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
     VFIORamDiscardListener *vrdl =
hw/vfio/listener.c +5 -5
index 0b72a2cf5e5..fbff1344448 100644
@@ -201,7 +201,7 @@ out:
 }
 
 static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl,
-                                            MemoryRegionSection *section)
+                                            const MemoryRegionSection *section)
 {
     VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
                                                 listener);
@@ -219,7 +219,7 @@ static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl,
 }
 
 static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl,
-                                            MemoryRegionSection *section)
+                                            const MemoryRegionSection *section)
 {
     VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
                                                 listener);
@@ -461,7 +461,7 @@ static void vfio_device_error_append(VFIODevice *vbasedev, Error **errp)
 }
 
 VFIORamDiscardListener *vfio_find_ram_discard_listener(
-    VFIOContainer *bcontainer, MemoryRegionSection *section)
+    VFIOContainer *bcontainer, const MemoryRegionSection *section)
 {
     VFIORamDiscardListener *vrdl;
 
@@ -1143,8 +1143,8 @@ out:
     }
 }
 
-static int vfio_ram_discard_query_dirty_bitmap(MemoryRegionSection *section,
-                                             void *opaque)
+static int vfio_ram_discard_query_dirty_bitmap(const MemoryRegionSection *section,
+                                               void *opaque)
 {
     const hwaddr size = int128_get64(section->size);
     const hwaddr iova = section->offset_within_address_space;
hw/virtio/virtio-mem.c +5 -5
index be149ee9441..ec165503205 100644
@@ -262,7 +262,7 @@ static int virtio_mem_for_each_plugged_range(VirtIOMEM *vmem, void *arg,
 typedef int (*virtio_mem_section_cb)(MemoryRegionSection *s, void *arg);
 
 static int virtio_mem_for_each_plugged_section(const VirtIOMEM *vmem,
-                                               MemoryRegionSection *s,
+                                               const MemoryRegionSection *s,
                                                void *arg,
                                                virtio_mem_section_cb cb)
 {
@@ -294,7 +294,7 @@ static int virtio_mem_for_each_plugged_section(const VirtIOMEM *vmem,
 }
 
 static int virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem,
-                                                 MemoryRegionSection *s,
+                                                 const MemoryRegionSection *s,
                                                  void *arg,
                                                  virtio_mem_section_cb cb)
 {
@@ -1680,7 +1680,7 @@ static int virtio_mem_rds_replay_cb(MemoryRegionSection *s, void *arg)
 }
 
 static int virtio_mem_rds_replay_populated(const RamDiscardSource *rds,
-                                           MemoryRegionSection *s,
+                                           const MemoryRegionSection *s,
                                            ReplayRamDiscardState replay_fn,
                                            void *opaque)
 {
@@ -1692,11 +1692,11 @@ static int virtio_mem_rds_replay_populated(const RamDiscardSource *rds,
 
     g_assert(s->mr == &vmem->memdev->mr);
     return virtio_mem_for_each_plugged_section(vmem, s, &data,
-                                            virtio_mem_rds_replay_cb);
+                                               virtio_mem_rds_replay_cb);
 }
 
 static int virtio_mem_rds_replay_discarded(const RamDiscardSource *rds,
-                                           MemoryRegionSection *s,
+                                           const MemoryRegionSection *s,
                                            ReplayRamDiscardState replay_fn,
                                            void *opaque)
 {
migration/ram.c +3 -3
index fc38ffbf8af..b2c7ec43b6a 100644
@@ -860,7 +860,7 @@ static inline bool migration_bitmap_clear_dirty(RAMState *rs,
     return ret;
 }
 
-static int dirty_bitmap_clear_section(MemoryRegionSection *section,
+static int dirty_bitmap_clear_section(const MemoryRegionSection *section,
                                       void *opaque)
 {
     const hwaddr offset = section->offset_within_region;
@@ -1588,7 +1588,7 @@ static inline void populate_read_range(RAMBlock *block, ram_addr_t offset,
     }
 }
 
-static inline int populate_read_section(MemoryRegionSection *section,
+static inline int populate_read_section(const MemoryRegionSection *section,
                                         void *opaque)
 {
     const hwaddr size = int128_get64(section->size);
@@ -1663,7 +1663,7 @@ void ram_write_tracking_prepare(void)
     }
 }
 
-static inline int uffd_protect_section(MemoryRegionSection *section,
+static inline int uffd_protect_section(const MemoryRegionSection *section,
                                        void *opaque)
 {
     const hwaddr size = int128_get64(section->size);
system/memory_mapping.c +2 -2
index da708a08ab7..cacef504f68 100644
@@ -196,7 +196,7 @@ typedef struct GuestPhysListener {
 } GuestPhysListener;
 
 static void guest_phys_block_add_section(GuestPhysListener *g,
-                                         MemoryRegionSection *section)
+                                         const MemoryRegionSection *section)
 {
     const hwaddr target_start = section->offset_within_address_space;
     const hwaddr target_end = target_start + int128_get64(section->size);
@@ -248,7 +248,7 @@ static void guest_phys_block_add_section(GuestPhysListener *g,
 #endif
 }
 
-static int guest_phys_ram_populate_cb(MemoryRegionSection *section,
+static int guest_phys_ram_populate_cb(const MemoryRegionSection *section,
                                       void *opaque)
 {
     GuestPhysListener *g = opaque;
system/ram-block-attributes.c +4 -4
index a72924eea7d..79c7e97d9a1 100644
@@ -37,7 +37,7 @@ typedef int (*ram_block_attributes_section_cb)(MemoryRegionSection *s,
 
 static int
 ram_block_attributes_for_each_populated_section(const RamBlockAttributes *attr,
-                                                MemoryRegionSection *section,
+                                                const MemoryRegionSection *section,
                                                 void *arg,
                                                 ram_block_attributes_section_cb cb)
 {
@@ -78,7 +78,7 @@ ram_block_attributes_for_each_populated_section(const RamBlockAttributes *attr,
 
 static int
 ram_block_attributes_for_each_discarded_section(const RamBlockAttributes *attr,
-                                                MemoryRegionSection *section,
+                                                const MemoryRegionSection *section,
                                                 void *arg,
                                                 ram_block_attributes_section_cb cb)
 {
@@ -161,7 +161,7 @@ ram_block_attributes_rds_is_populated(const RamDiscardSource *rds,
 
 static int
 ram_block_attributes_rds_replay_populated(const RamDiscardSource *rds,
-                                          MemoryRegionSection *section,
+                                          const MemoryRegionSection *section,
                                           ReplayRamDiscardState replay_fn,
                                           void *opaque)
 {
@@ -175,7 +175,7 @@ ram_block_attributes_rds_replay_populated(const RamDiscardSource *rds,
 
 static int
 ram_block_attributes_rds_replay_discarded(const RamDiscardSource *rds,
-                                          MemoryRegionSection *section,
+                                          const MemoryRegionSection *section,
                                           ReplayRamDiscardState replay_fn,
                                           void *opaque)
 {
system/ram-discard-manager.c +5 -5
index 3d8c85617d7..1c9ff7fda58 100644
@@ -28,7 +28,7 @@ static bool ram_discard_source_is_populated(const RamDiscardSource *rds,
 }
 
 static int ram_discard_source_replay_populated(const RamDiscardSource *rds,
-                                               MemoryRegionSection *section,
+                                               const MemoryRegionSection *section,
                                                ReplayRamDiscardState replay_fn,
                                                void *opaque)
 {
@@ -39,7 +39,7 @@ static int ram_discard_source_replay_populated(const RamDiscardSource *rds,
 }
 
 static int ram_discard_source_replay_discarded(const RamDiscardSource *rds,
-                                               MemoryRegionSection *section,
+                                               const MemoryRegionSection *section,
                                                ReplayRamDiscardState replay_fn,
                                                void *opaque)
 {
@@ -74,7 +74,7 @@ bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
 }
 
 int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
-                                         MemoryRegionSection *section,
+                                         const MemoryRegionSection *section,
                                          ReplayRamDiscardState replay_fn,
                                          void *opaque)
 {
@@ -83,7 +83,7 @@ int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
 }
 
 int ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
-                                         MemoryRegionSection *section,
+                                         const MemoryRegionSection *section,
                                          ReplayRamDiscardState replay_fn,
                                          void *opaque)
 {
@@ -164,7 +164,7 @@ void ram_discard_manager_notify_discard_all(RamDiscardManager *rdm)
     }
 }
 
-static int rdm_populate_cb(MemoryRegionSection *section, void *opaque)
+static int rdm_populate_cb(const MemoryRegionSection *section, void *opaque)
 {
     RamDiscardListener *rdl = opaque;
 
Signature · 1 line
2.54.0
Acked-by on v5 3/12
#7 lore raw

Re: [PATCH v5 03/12] system/memory: constify section arguments

In reply to Marc-André Lureau
Quoted 5 lines · Marc-André Lureau

The sections shouldn't be modified.

Quoted 13 lines
---
  include/hw/vfio/vfio-container.h     |  2 +-
  include/hw/vfio/vfio-cpr.h           |  2 +-
  include/system/ram-discard-manager.h | 14 +++++++-------
  hw/vfio/cpr-legacy.c                 |  4 ++--
  hw/vfio/listener.c                   | 10 +++++-----
  hw/virtio/virtio-mem.c               | 10 +++++-----
  migration/ram.c                      |  6 +++---
  system/memory_mapping.c              |  4 ++--
  system/ram-block-attributes.c        |  8 ++++----
  system/ram-discard-manager.c         | 10 +++++-----
  10 files changed, 35 insertions(+), 35 deletions(-)

Thanks,
Maciej

Reviewed-by on v5 3/12
#8 lore raw

Re: [PATCH v5 03/12] system/memory: constify section arguments

In reply to Marc-André Lureau
Quoted 5 lines · Marc-André Lureau

The sections shouldn't be modified.

Quoted 12 lines
---
  include/hw/vfio/vfio-container.h     |  2 +-
  include/hw/vfio/vfio-cpr.h           |  2 +-
  include/system/ram-discard-manager.h | 14 +++++++-------
  hw/vfio/cpr-legacy.c                 |  4 ++--
  hw/vfio/listener.c                   | 10 +++++-----
  hw/virtio/virtio-mem.c               | 10 +++++-----
  migration/ram.c                      |  6 +++---
  system/memory_mapping.c              |  4 ++--
  system/ram-block-attributes.c        |  8 ++++----
  system/ram-discard-manager.c         | 10 +++++-----
  10 files changed, 35 insertions(+), 35 deletions(-)
#9 lore raw

PATCH v5 4/12 system/ram-discard-manager: implement replay via is_populated iteration

In reply to Marc-André Lureau

Replace the source-level replay wrappers with a new replay_by_populated_state() helper that iterates the section at min-granularity, calls is_populated() for each chunk, and aggregates consecutive chunks of the same state before invoking the callback.

This moves the iteration logic from individual sources into the manager, preparing for multi-source aggregation where the manager must combine state from multiple sources anyway.

The replay_populated/replay_discarded vtable entries in RamDiscardSourceClass are no longer called but remain in the interface for now; they will be removed in follow-up commits along with the now-dead source implementations.

---
 system/ram-discard-manager.c | 85 +++++++++++++++++++++++++++++++-------------
 1 file changed, 61 insertions(+), 24 deletions(-)
system/ram-discard-manager.c +61 -24
index 1c9ff7fda58..a907ddf3708 100644
@@ -27,26 +27,65 @@ static bool ram_discard_source_is_populated(const RamDiscardSource *rds,
     return rdsc->is_populated(rds, section);
 }
 
-static int ram_discard_source_replay_populated(const RamDiscardSource *rds,
-                                               const MemoryRegionSection *section,
-                                               ReplayRamDiscardState replay_fn,
-                                               void *opaque)
+/*
+ * Iterate the section at source granularity, aggregating consecutive chunks
+ * with matching populated state, and call replay_fn for each run.
+ */
+static int replay_by_populated_state(const RamDiscardManager *rdm,
+                                     const MemoryRegionSection *section,
+                                     bool replay_populated,
+                                     ReplayRamDiscardState replay_fn,
+                                     void *opaque)
 {
-    RamDiscardSourceClass *rdsc = RAM_DISCARD_SOURCE_GET_CLASS(rds);
+    uint64_t granularity, offset, size, end, pos, run_start = 0;
+    bool in_run = false;
+    int ret = 0;
 
-    g_assert(rdsc->replay_populated);
-    return rdsc->replay_populated(rds, section, replay_fn, opaque);
-}
+    granularity = ram_discard_source_get_min_granularity(rdm->rds, rdm->mr);
+    offset = section->offset_within_region;
+    size = int128_get64(section->size);
+    end = offset + size;
+
+    /* Align iteration to granularity boundaries */
+    pos = QEMU_ALIGN_DOWN(offset, granularity);
+
+    for (; pos < end; pos += granularity) {
+        MemoryRegionSection chunk = {
+            .mr = section->mr,
+            .offset_within_region = pos,
+            .size = int128_make64(granularity),
+        };
+        bool populated = ram_discard_source_is_populated(rdm->rds, &chunk);
+
+        if (populated == replay_populated) {
+            if (!in_run) {
+                run_start = pos;
+                in_run = true;
+            }
+        } else if (in_run) {
+            MemoryRegionSection tmp = *section;
+
+            if (memory_region_section_intersect_range(&tmp, run_start,
+                                                      pos - run_start)) {
+                ret = replay_fn(&tmp, opaque);
+                if (ret) {
+                    return ret;
+                }
+            }
+            in_run = false;
+        }
+    }
 
-static int ram_discard_source_replay_discarded(const RamDiscardSource *rds,
-                                               const MemoryRegionSection *section,
-                                               ReplayRamDiscardState replay_fn,
-                                               void *opaque)
-{
-    RamDiscardSourceClass *rdsc = RAM_DISCARD_SOURCE_GET_CLASS(rds);
+    if (in_run) {
+        MemoryRegionSection tmp = *section;
 
-    g_assert(rdsc->replay_discarded);
-    return rdsc->replay_discarded(rds, section, replay_fn, opaque);
+        if (memory_region_section_intersect_range(&tmp, run_start,
+                                                  pos - run_start)) {
+            ret = replay_fn(&tmp, opaque);
+        }
+    }
+
+    return ret;
 }
 
 RamDiscardManager *ram_discard_manager_new(MemoryRegion *mr,
@@ -78,8 +117,7 @@ int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
                                          ReplayRamDiscardState replay_fn,
                                          void *opaque)
 {
-    return ram_discard_source_replay_populated(rdm->rds, section,
-                                               replay_fn, opaque);
+    return replay_by_populated_state(rdm, section, true, replay_fn, opaque);
 }
 
 int ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
@@ -87,8 +125,7 @@ int ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
                                          ReplayRamDiscardState replay_fn,
                                          void *opaque)
 {
-    return ram_discard_source_replay_discarded(rdm->rds, section,
-                                               replay_fn, opaque);
+    return replay_by_populated_state(rdm, section, false, replay_fn, opaque);
 }
 
 static void ram_discard_manager_initfn(Object *obj)
@@ -182,8 +219,8 @@ void ram_discard_manager_register_listener(RamDiscardManager *rdm,
     rdl->section = memory_region_section_new_copy(section);
     QLIST_INSERT_HEAD(&rdm->rdl_list, rdl, next);
 
-    ret = ram_discard_source_replay_populated(rdm->rds, rdl->section,
-                                              rdm_populate_cb, rdl);
+    ret = ram_discard_manager_replay_populated(rdm, rdl->section,
+                                               rdm_populate_cb, rdl);
     if (ret) {
         error_report("%s: Replaying populated ranges failed: %s", __func__,
                      strerror(-ret));
@@ -208,8 +245,8 @@ int ram_discard_manager_replay_populated_to_listeners(RamDiscardManager *rdm)
     int ret = 0;
 
     QLIST_FOREACH(rdl, &rdm->rdl_list, next) {
-        ret = ram_discard_source_replay_populated(rdm->rds, rdl->section,
-                                                  rdm_populate_cb, rdl);
+        ret = ram_discard_manager_replay_populated(rdm, rdl->section,
+                                                   rdm_populate_cb, rdl);
         if (ret) {
             break;
         }
Signature · 1 line
2.54.0
Acked-by on v5 4/12
#10 lore raw

Re: [PATCH v5 04/12] system/ram-discard-manager: implement replay via is_populated iteration

Quoted 9 lines · Marc-André Lureau

Replace the source-level replay wrappers with a new replay_by_populated_state() helper that iterates the section at min-granularity, calls is_populated() for each chunk, and aggregates consecutive chunks of the same state before invoking the callback.

This moves the iteration logic from individual sources into the manager, preparing for multi-source aggregation where the manager must combine state from multiple sources anyway.

Quoted 8 lines

The replay_populated/replay_discarded vtable entries in RamDiscardSourceClass are no longer called but remain in the interface for now; they will be removed in follow-up commits along with the now-dead source implementations.

---

Signature · 3 lines
Cheers,

David
#11 lore raw

PATCH v5 5/12 virtio-mem: remove replay_populated/replay_discarded implementation

In reply to Marc-André Lureau

The replay iteration logic has been moved into the RamDiscardManager, which now iterates at source granularity using is_populated(). The source-level replay_populated/replay_discarded methods and their helpers are no longer called.

Remove the now-dead replay methods, the VirtIOMEMReplayData struct, the virtio_mem_for_each_plugged/unplugged_section() helpers (only used by the replay methods), and the virtio_mem_section_cb typedef.

---
 hw/virtio/virtio-mem.c | 112 -------------------------------------------------
 1 file changed, 112 deletions(-)
hw/virtio/virtio-mem.c +0 -112
index ec165503205..2b67b2882d2 100644
@@ -259,72 +259,6 @@ static int virtio_mem_for_each_plugged_range(VirtIOMEM *vmem, void *arg,
     return ret;
 }
 
-typedef int (*virtio_mem_section_cb)(MemoryRegionSection *s, void *arg);
-
-static int virtio_mem_for_each_plugged_section(const VirtIOMEM *vmem,
-                                               const MemoryRegionSection *s,
-                                               void *arg,
-                                               virtio_mem_section_cb cb)
-{
-    unsigned long first_bit, last_bit;
-    uint64_t offset, size;
-    int ret = 0;
-
-    first_bit = s->offset_within_region / vmem->block_size;
-    first_bit = find_next_bit(vmem->bitmap, vmem->bitmap_size, first_bit);
-    while (first_bit < vmem->bitmap_size) {
-        MemoryRegionSection tmp = *s;
-
-        offset = first_bit * vmem->block_size;
-        last_bit = find_next_zero_bit(vmem->bitmap, vmem->bitmap_size,
-                                      first_bit + 1) - 1;
-        size = (last_bit - first_bit + 1) * vmem->block_size;
-
-        if (!memory_region_section_intersect_range(&tmp, offset, size)) {
-            break;
-        }
-        ret = cb(&tmp, arg);
-        if (ret) {
-            break;
-        }
-        first_bit = find_next_bit(vmem->bitmap, vmem->bitmap_size,
-                                  last_bit + 2);
-    }
-    return ret;
-}
-
-static int virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem,
-                                                 const MemoryRegionSection *s,
-                                                 void *arg,
-                                                 virtio_mem_section_cb cb)
-{
-    unsigned long first_bit, last_bit;
-    uint64_t offset, size;
-    int ret = 0;
-
-    first_bit = s->offset_within_region / vmem->block_size;
-    first_bit = find_next_zero_bit(vmem->bitmap, vmem->bitmap_size, first_bit);
-    while (first_bit < vmem->bitmap_size) {
-        MemoryRegionSection tmp = *s;
-
-        offset = first_bit * vmem->block_size;
-        last_bit = find_next_bit(vmem->bitmap, vmem->bitmap_size,
-                                 first_bit + 1) - 1;
-        size = (last_bit - first_bit + 1) * vmem->block_size;
-
-        if (!memory_region_section_intersect_range(&tmp, offset, size)) {
-            break;
-        }
-        ret = cb(&tmp, arg);
-        if (ret) {
-            break;
-        }
-        first_bit = find_next_zero_bit(vmem->bitmap, vmem->bitmap_size,
-                                       last_bit + 2);
-    }
-    return ret;
-}
-
 static void virtio_mem_notify_unplug(VirtIOMEM *vmem, uint64_t offset,
                                      uint64_t size)
 {
@@ -1667,50 +1601,6 @@ static bool virtio_mem_rds_is_populated(const RamDiscardSource *rds,
     return virtio_mem_is_range_plugged(vmem, start_gpa, end_gpa - start_gpa);
 }
 
-struct VirtIOMEMReplayData {
-    ReplayRamDiscardState fn;
-    void *opaque;
-};
-
-static int virtio_mem_rds_replay_cb(MemoryRegionSection *s, void *arg)
-{
-    struct VirtIOMEMReplayData *data = arg;
-
-    return data->fn(s, data->opaque);
-}
-
-static int virtio_mem_rds_replay_populated(const RamDiscardSource *rds,
-                                           const MemoryRegionSection *s,
-                                           ReplayRamDiscardState replay_fn,
-                                           void *opaque)
-{
-    const VirtIOMEM *vmem = VIRTIO_MEM(rds);
-    struct VirtIOMEMReplayData data = {
-        .fn = replay_fn,
-        .opaque = opaque,
-    };
-
-    g_assert(s->mr == &vmem->memdev->mr);
-    return virtio_mem_for_each_plugged_section(vmem, s, &data,
-                                               virtio_mem_rds_replay_cb);
-}
-
-static int virtio_mem_rds_replay_discarded(const RamDiscardSource *rds,
-                                           const MemoryRegionSection *s,
-                                           ReplayRamDiscardState replay_fn,
-                                           void *opaque)
-{
-    const VirtIOMEM *vmem = VIRTIO_MEM(rds);
-    struct VirtIOMEMReplayData data = {
-        .fn = replay_fn,
-        .opaque = opaque,
-    };
-
-    g_assert(s->mr == &vmem->memdev->mr);
-    return virtio_mem_for_each_unplugged_section(vmem, s, &data,
-                                                 virtio_mem_rds_replay_cb);
-}
-
 static void virtio_mem_unplug_request_check(VirtIOMEM *vmem, Error **errp)
 {
     if (vmem->unplugged_inaccessible == ON_OFF_AUTO_OFF) {
@@ -1766,8 +1656,6 @@ static void virtio_mem_class_init(ObjectClass *klass, const void *data)
 
     rdsc->get_min_granularity = virtio_mem_rds_get_min_granularity;
     rdsc->is_populated = virtio_mem_rds_is_populated;
-    rdsc->replay_populated = virtio_mem_rds_replay_populated;
-    rdsc->replay_discarded = virtio_mem_rds_replay_discarded;
 }
 
 static const TypeInfo virtio_mem_info = {
Signature · 1 line
2.54.0
#12 lore raw

PATCH v5 6/12 system/ram-discard-manager: drop replay from source interface

In reply to Marc-André Lureau

Remove replay_populated and replay_discarded from RamDiscardSourceClass now that the RamDiscardManager handles replay iteration internally via is_populated.

Remove the now-dead replay methods, helpers, and for_each_populated/discarded_section() from ram-block-attributes, which was the last source still carrying this code.

---
 include/system/ram-discard-manager.h |  52 +++-----------
 system/ram-block-attributes.c        | 130 -----------------------------------
 2 files changed, 10 insertions(+), 172 deletions(-)
include/system/ram-discard-manager.h +10 -42
index b188e09a30f..b5dbcb4a82d 100644
@@ -77,8 +77,8 @@ static inline void ram_discard_listener_init(RamDiscardListener *rdl,
 /**
  * typedef ReplayRamDiscardState:
  *
- * The callback handler for #RamDiscardSourceClass.replay_populated/
- * #RamDiscardSourceClass.replay_discarded to invoke on populated/discarded
+ * The callback handler used by ram_discard_manager_replay_populated() and
+ * ram_discard_manager_replay_discarded() to invoke on populated/discarded
  * parts.
  *
  * @section: the #MemoryRegionSection of populated/discarded part
@@ -134,42 +134,6 @@ struct RamDiscardSourceClass {
      */
     bool (*is_populated)(const RamDiscardSource *rds,
                          const MemoryRegionSection *section);
-
-    /**
-     * @replay_populated:
-     *
-     * Call the #ReplayRamDiscardState callback for all populated parts within
-     * the #MemoryRegionSection via the #RamDiscardSource.
-     *
-     * In case any call fails, no further calls are made.
-     *
-     * @rds: the #RamDiscardSource
-     * @section: the #MemoryRegionSection
-     * @replay_fn: the #ReplayRamDiscardState callback
-     * @opaque: pointer to forward to the callback
-     *
-     * Returns 0 on success, or a negative error if any notification failed.
-     */
-    int (*replay_populated)(const RamDiscardSource *rds,
-                            const MemoryRegionSection *section,
-                            ReplayRamDiscardState replay_fn, void *opaque);
-
-    /**
-     * @replay_discarded:
-     *
-     * Call the #ReplayRamDiscardState callback for all discarded parts within
-     * the #MemoryRegionSection via the #RamDiscardSource.
-     *
-     * @rds: the #RamDiscardSource
-     * @section: the #MemoryRegionSection
-     * @replay_fn: the #ReplayRamDiscardState callback
-     * @opaque: pointer to forward to the callback
-     *
-     * Returns 0 on success, or a negative error if any notification failed.
-     */
-    int (*replay_discarded)(const RamDiscardSource *rds,
-                            const MemoryRegionSection *section,
-                            ReplayRamDiscardState replay_fn, void *opaque);
 };
 
 /**
@@ -226,8 +190,10 @@ bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
 /**
  * ram_discard_manager_replay_populated:
  *
- * A wrapper to call the #RamDiscardSourceClass.replay_populated callback
- * of the #RamDiscardSource sources.
+ * Iterate the given #MemoryRegionSection at minimum granularity, calling
+ * #RamDiscardSourceClass.is_populated for each chunk, and invoke @replay_fn
+ * for each contiguous populated range. In case any call fails, no further
+ * calls are made.
  *
  * @rdm: the #RamDiscardManager
  * @section: the #MemoryRegionSection
@@ -244,8 +210,10 @@ int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
 /**
  * ram_discard_manager_replay_discarded:
  *
- * A wrapper to call the #RamDiscardSourceClass.replay_discarded callback
- * of the #RamDiscardSource sources.
+ * Iterate the given #MemoryRegionSection at minimum granularity, calling
+ * #RamDiscardSourceClass.is_populated for each chunk, and invoke @replay_fn
+ * for each contiguous discarded range. In case any call fails, no further
+ * calls are made.
  *
  * @rdm: the #RamDiscardManager
  * @section: the #MemoryRegionSection
system/ram-block-attributes.c +0 -130

146 lines not on this page · raw message

Signature · 1 line
2.54.0
#13 lore raw

PATCH v5 7/12 system/memory: implement RamDiscardManager multi-source aggregation

In reply to Marc-André Lureau

Refactor RamDiscardManager to aggregate multiple RamDiscardSource instances. This enables scenarios where multiple components (e.g., virtio-mem and RamBlockAttributes) can coordinate memory discard state for the same memory region.

The aggregation uses:
- Populated: ALL sources populated
- Discarded: ANY source discarded

When a source is added with existing listeners, they are notified about regions that become discarded. When a source is removed, listeners are notified about regions that become populated.

---
 include/system/memory.h              |   4 +-
 include/system/ram-discard-manager.h | 141 ++++++++++--
 hw/virtio/virtio-mem.c               |   8 +-
 system/memory.c                      |  17 +-
 system/ram-block-attributes.c        |   6 +-
 system/ram-discard-manager.c         | 427 +++++++++++++++++++++++++++++++----
 6 files changed, 518 insertions(+), 85 deletions(-)
include/system/memory.h +3 -1
index 28a75dac4ae..7857164078f 100644
@@ -2243,8 +2243,10 @@ int memory_region_add_ram_discard_source(MemoryRegion *mr, RamDiscardSource *sou
  *
  * @mr: the #MemoryRegion
  * @source: #RamDiscardSource to remove
+ *
+ * Returns: 0 on success, or a negative error code on failure.
  */
-void memory_region_del_ram_discard_source(MemoryRegion *mr, RamDiscardSource *source);
+int memory_region_del_ram_discard_source(MemoryRegion *mr, RamDiscardSource *source);
 
 /**
  * memory_region_find: translate an address/size relative to a
include/system/ram-discard-manager.h +117 -24

188 lines not on this page · raw message

hw/virtio/virtio-mem.c +5 -3
index 2b67b2882d2..35e03ed7599 100644
@@ -264,7 +264,8 @@ static void virtio_mem_notify_unplug(VirtIOMEM *vmem, uint64_t offset,
 {
     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(&vmem->memdev->mr);
 
-    ram_discard_manager_notify_discard(rdm, offset, size);
+    ram_discard_manager_notify_discard(rdm, RAM_DISCARD_SOURCE(vmem),
+                                       offset, size);
 }
 
 static int virtio_mem_notify_plug(VirtIOMEM *vmem, uint64_t offset,
@@ -272,7 +273,8 @@ static int virtio_mem_notify_plug(VirtIOMEM *vmem, uint64_t offset,
 {
     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(&vmem->memdev->mr);
 
-    return ram_discard_manager_notify_populate(rdm, offset, size);
+    return ram_discard_manager_notify_populate(rdm, RAM_DISCARD_SOURCE(vmem),
+                                               offset, size);
 }
 
 static void virtio_mem_notify_unplug_all(VirtIOMEM *vmem)
@@ -283,7 +285,7 @@ static void virtio_mem_notify_unplug_all(VirtIOMEM *vmem)
         return;
     }
 
-    ram_discard_manager_notify_discard_all(rdm);
+    ram_discard_manager_notify_discard_all(rdm, RAM_DISCARD_SOURCE(vmem));
 }
 
 static bool virtio_mem_is_range_plugged(const VirtIOMEM *vmem,
system/memory.c +9 -8
index 243e69abd75..7c75eef1cec 100644
@@ -2047,21 +2047,22 @@ int memory_region_add_ram_discard_source(MemoryRegion *mr,
                                          RamDiscardSource *source)
 {
     g_assert(memory_region_is_ram(mr));
-    if (mr->rdm) {
-        return -EBUSY;
+
+    if (!mr->rdm) {
+        mr->rdm = ram_discard_manager_new(mr);
     }
 
-    mr->rdm = ram_discard_manager_new(mr, RAM_DISCARD_SOURCE(source));
-    return 0;
+    return ram_discard_manager_add_source(mr->rdm, source);
 }
 
-void memory_region_del_ram_discard_source(MemoryRegion *mr,
+int memory_region_del_ram_discard_source(MemoryRegion *mr,
                                           RamDiscardSource *source)
 {
-    g_assert(mr->rdm->rds == source);
+    g_assert(mr->rdm);
+
+    return ram_discard_manager_del_source(mr->rdm, source);
 
-    object_unref(mr->rdm);
-    mr->rdm = NULL;
+    /* if there is no source and no listener left, we could free rdm */
 }
 
 /* Called with rcu_read_lock held.  */
system/ram-block-attributes.c +4 -2
index 718c7075cec..59ec7a28eb0 100644
@@ -90,7 +90,8 @@ ram_block_attributes_notify_discard(RamBlockAttributes *attr,
 {
     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(attr->ram_block->mr);
 
-    ram_discard_manager_notify_discard(rdm, offset, size);
+    ram_discard_manager_notify_discard(rdm, RAM_DISCARD_SOURCE(attr),
+                                       offset, size);
 }
 
 static int
@@ -99,7 +100,8 @@ ram_block_attributes_notify_populate(RamBlockAttributes *attr,
 {
     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(attr->ram_block->mr);
 
-    return ram_discard_manager_notify_populate(rdm, offset, size);
+    return ram_discard_manager_notify_populate(rdm, RAM_DISCARD_SOURCE(attr),
+                                               offset, size);
 }
 
 int ram_block_attributes_state_change(RamBlockAttributes *attr,
system/ram-discard-manager.c +380 -47

550 lines not on this page · raw message

Signature · 1 line
2.54.0
#14 lore raw

PATCH v5 8/12 system/physmem: destroy ram block attributes before RCU-deferred reclaim

In reply to Marc-André Lureau

ram_block_attributes_destroy() was called from reclaim_ramblock(), which runs as an RCU callback deferred by call_rcu().

However,when the RamDiscardManager is finalized, it will assert that its source_list is empty in the next commit. Since the RCU callback hasn't run yet, the source added by ram_block_attributes_create() is still attached.

Move ram_block_attributes_destroy() into qemu_ram_free() so the source is removed synchronously. This is safe because qemu_ram_free() during shutdown runs after pause_all_vcpus(), so no vCPU thread can concurrently access the attributes via kvm_convert_memory().

---
 system/physmem.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
system/physmem.c +1 -1
index 7bcbf875736..ddb67ba2359 100644
@@ -2583,7 +2583,6 @@ static void reclaim_ramblock(RAMBlock *block)
     }
 
     if (block->guest_memfd >= 0) {
-        ram_block_attributes_destroy(block->attributes);
         close(block->guest_memfd);
         ram_block_coordinated_discard_require(false);
     }
@@ -2612,6 +2611,7 @@ void qemu_ram_free(RAMBlock *block)
     /* Write list before version */
     smp_wmb();
     ram_list.version++;
+    g_clear_pointer(&block->attributes, ram_block_attributes_destroy);
     call_rcu(block, reclaim_ramblock, rcu);
     qemu_mutex_unlock_ramlist();
 }
Signature · 1 line
2.54.0
#15 lore raw

PATCH v5 9/12 system/memory: add RamDiscardManager reference counting and cleanup

In reply to Marc-André Lureau

Listeners now hold a reference to the RamDiscardManager, ensuring it stays alive while listeners are registered. The RDM is eagerly freed when the last source and listener are removed, and also unreffed during MemoryRegion finalization as a safety net.

This completes the TODO left in the previous commit and prevents both use-after-free and memory leaks of the RamDiscardManager.

---
 system/memory.c              | 14 +++++++++++---
 system/ram-discard-manager.c |  2 ++
 2 files changed, 13 insertions(+), 3 deletions(-)
system/memory.c +11 -3
index 7c75eef1cec..ee1a1a1cd53 100644
@@ -1755,6 +1755,7 @@ static void memory_region_finalize(Object *obj)
     memory_region_clear_coalescing(mr);
     g_free((char *)mr->name);
     g_free(mr->ioeventfds);
+    object_unref(mr->rdm);
 }
 
 Object *memory_region_owner(const MemoryRegion *mr)
@@ -2058,11 +2059,18 @@ int memory_region_add_ram_discard_source(MemoryRegion *mr,
 int memory_region_del_ram_discard_source(MemoryRegion *mr,
                                           RamDiscardSource *source)
 {
+    int ret;
     g_assert(mr->rdm);
 
-    return ram_discard_manager_del_source(mr->rdm, source);
-
-    /* if there is no source and no listener left, we could free rdm */
+    ret = ram_discard_manager_del_source(mr->rdm, source);
+    if (ret != 0) {
+        return ret;
+    }
+    if (QLIST_EMPTY(&mr->rdm->source_list) && QLIST_EMPTY(&mr->rdm->rdl_list)) {
+        object_unref(mr->rdm);
+        mr->rdm = NULL;
+    }
+    return 0;
 }
 
 /* Called with rcu_read_lock held.  */
system/ram-discard-manager.c +2 -0
index 7da91bf648a..4e8816e5a2f 100644
@@ -549,6 +549,7 @@ void ram_discard_manager_register_listener(RamDiscardManager *rdm,
 
     g_assert(section->mr == rdm->mr);
 
+    object_ref(rdm);
     rdl->section = memory_region_section_new_copy(section);
     QLIST_INSERT_HEAD(&rdm->rdl_list, rdl, next);
 
@@ -570,6 +571,7 @@ void ram_discard_manager_unregister_listener(RamDiscardManager *rdm,
     memory_region_section_free_copy(rdl->section);
     rdl->section = NULL;
     QLIST_REMOVE(rdl, next);
+    object_unref(rdm);
 }
 
 int ram_discard_manager_replay_populated_to_listeners(RamDiscardManager *rdm)
Signature · 1 line
2.54.0
#16 lore raw

PATCH v5 10/12 tests: add unit tests for RamDiscardManager multi-source aggregation

In reply to Marc-André Lureau

Add various unit tests for the RamDiscardManager multi-source aggregation functionality.

The test uses a TestRamDiscardSource QOM object that tracks populated state via a bitmap, similar to RamBlockAttributes implementation.

---
 MAINTAINERS                                 |    2 +
 tests/unit/test-ram-discard-manager-stubs.c |   48 ++
 tests/unit/test-ram-discard-manager.c       | 1235 +++++++++++++++++++++++++++
 tests/unit/meson.build                      |    8 +-
 4 files changed, 1292 insertions(+), 1 deletion(-)
MAINTAINERS +2 -0
index 25dbb9f1a77..0cb909c0671 100644
@@ -3359,6 +3359,8 @@ F: system/memory-internal.h
 F: system/ram-block-attributes.c
 F: system/ram-discard-manager.c
 F: scripts/coccinelle/memory-region-housekeeping.cocci
+F: tests/unit/test-ram-discard-manager.c
+F: tests/unit/test-ram-discard-manager-stubs.c
 
 Memory devices
 M: David Hildenbrand <[email protected]>
tests/unit/test-ram-discard-manager-stubs.c new file +48 -0

48 lines not on this page · raw message

tests/unit/test-ram-discard-manager.c new file +1235 -0

1,235 lines not on this page · raw message

tests/unit/meson.build +7 -1
index de64f9501f2..f3c4ad0fc58 100644
@@ -137,7 +137,13 @@ if have_system
     'test-bufferiszero': [],
     'test-smp-parse': [qom, meson.project_source_root() / 'hw/core/machine-smp.c'],
     'test-vmstate': [migration, io],
-    'test-yank': ['socket-helpers.c', qom, io, chardev]
+    'test-yank': ['socket-helpers.c', qom, io, chardev],
+    'test-ram-discard-manager': [
+      'test-ram-discard-manager.c',
+      'test-ram-discard-manager-stubs.c',
+      meson.project_source_root() / 'system/ram-discard-manager.c',
+      genh, qemuutil, qom
+    ],
   }
   if config_host_data.get('CONFIG_INOTIFY1')
     tests += {'test-util-filemonitor': []}
Signature · 1 line
2.54.0
#17 lore raw

PATCH v5 11/12 system/physmem: make ram_block_discard_range() handle guest_memfd

In reply to Marc-André Lureau

Most callers of ram_block_discard_range() want to discard both the shared and guest_memfd backing. Only kvm_convert_memory() intentionally discards a single plane during private/shared conversions.

Rename the current implementation to ram_block_discard_shared_range() and make ram_block_discard_range() a composite that also discards guest_memfd when present (rb->guest_memfd >= 0). This ensures callers like virtio-mem, virtio-balloon, hv-balloon, migration.. reclaim private pages on discard.

Update kvm_convert_memory() to use the plane-specific ram_block_discard_shared_range() since it only needs to discard the shared backing when converting to private.

Likewise, after TDVF image copy, use ram_block_discard_shared_range().

---
 include/system/ramblock.h |  3 ++-
 accel/kvm/kvm-all.c       |  2 +-
 system/physmem.c          | 25 +++++++++++++++++++++----
 target/i386/kvm/tdx.c     |  2 +-
 system/trace-events       |  2 +-
 5 files changed, 26 insertions(+), 8 deletions(-)
include/system/ramblock.h +2 -1
index 2b38718fe5f..f0639287bf0 100644
@@ -103,7 +103,8 @@ struct RamBlockAttributes {
 
 /* @offset: the offset within the RAMBlock */
 int ram_block_discard_range(RAMBlock *rb, uint64_t offset, size_t length);
-/* @offset: the offset within the RAMBlock */
+int ram_block_discard_shared_range(RAMBlock *rb, uint64_t offset,
+                                   size_t length);
 int ram_block_discard_guest_memfd_range(RAMBlock *rb, uint64_t offset,
                                         size_t length);
 
accel/kvm/kvm-all.c +1 -1
index 96f90ebb240..dcfb99cdf74 100644
@@ -3426,7 +3426,7 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
              */
             goto out_unref;
         }
-        ret = ram_block_discard_range(rb, offset, size);
+        ret = ram_block_discard_shared_range(rb, offset, size);
     } else {
         ret = ram_block_discard_guest_memfd_range(rb, offset, size);
     }
system/physmem.c +21 -4
index ddb67ba2359..0ff80a74917 100644
@@ -4095,7 +4095,7 @@ int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
  * Returns: 0 on success, none-0 on failure
  *
  */
-int ram_block_discard_range(RAMBlock *rb, uint64_t offset, size_t length)
+int ram_block_discard_shared_range(RAMBlock *rb, uint64_t offset, size_t length)
 {
     int ret = -1;
 
@@ -4144,7 +4144,7 @@ int ram_block_discard_range(RAMBlock *rb, uint64_t offset, size_t length)
              * have a MAP_PRIVATE mapping, possibly messing with other
              * MAP_PRIVATE/MAP_SHARED mappings. There is no easy way to
              * change that behavior whithout violating the promised
-             * semantics of ram_block_discard_range().
+             * semantics of ram_block_discard_shared_range().
              *
              * Only warn, because it works as long as nobody else uses that
              * file.
@@ -4200,8 +4200,9 @@ int ram_block_discard_range(RAMBlock *rb, uint64_t offset, size_t length)
             goto err;
 #endif
         }
-        trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
-                                      need_madvise, need_fallocate, ret);
+        trace_ram_block_discard_shared_range(rb->idstr, host_startaddr, length,
+                                             need_madvise, need_fallocate,
+                                             ret);
     } else {
         error_report("%s: Overrun block '%s' (%" PRIu64 "/%zx/" RAM_ADDR_FMT")",
                      __func__, rb->idstr, offset, length, rb->max_length);
@@ -4211,6 +4212,22 @@ err:
     return ret;
 }
 
+int ram_block_discard_range(RAMBlock *rb, uint64_t offset, size_t length)
+{
+    int ret;
+
+    ret = ram_block_discard_shared_range(rb, offset, length);
+    if (ret) {
+        return ret;
+    }
+
+    if (rb->guest_memfd >= 0) {
+        ret = ram_block_discard_guest_memfd_range(rb, offset, length);
+    }
+
+    return ret;
+}
+
 int ram_block_discard_guest_memfd_range(RAMBlock *rb, uint64_t offset,
                                         size_t length)
 {
target/i386/kvm/tdx.c +1 -1
index 4714c9d514e..fcb11aa67e4 100644
@@ -385,7 +385,7 @@ static void tdx_finalize_vm(Notifier *notifier, void *unused)
      * KVM_MEMORY_MAPPING. It becomes useless.
      */
     ram_block = tdx_guest->tdvf_mr->ram_block;
-    ram_block_discard_range(ram_block, 0, ram_block->max_length);
+    ram_block_discard_shared_range(ram_block, 0, ram_block->max_length);
 
     tdx_vm_ioctl(KVM_TDX_FINALIZE_VM, 0, NULL, &error_fatal);
     CONFIDENTIAL_GUEST_SUPPORT(tdx_guest)->ready = true;
system/trace-events +1 -1
index e6e1b612798..51b4a4679a2 100644
@@ -32,7 +32,7 @@ global_dirty_changed(unsigned int bitmask) "bitmask 0x%"PRIx32
 address_space_map(void *as, uint64_t addr, uint64_t len, bool is_write, uint32_t attrs) "as:%p addr 0x%"PRIx64":%"PRIx64" write:%d attrs:0x%x"
 find_ram_offset(uint64_t size, uint64_t offset) "size: 0x%" PRIx64 " @ 0x%" PRIx64
 find_ram_offset_loop(uint64_t size, uint64_t candidate, uint64_t offset, uint64_t next, uint64_t mingap) "trying size: 0x%" PRIx64 " @ 0x%" PRIx64 ", offset: 0x%" PRIx64" next: 0x%" PRIx64 " mingap: 0x%" PRIx64
-ram_block_discard_range(const char *rbname, void *hva, size_t length, bool need_madvise, bool need_fallocate, int ret) "%s@%p + 0x%zx: madvise: %d fallocate: %d ret: %d"
+ram_block_discard_shared_range(const char *rbname, void *hva, size_t length, bool need_madvise, bool need_fallocate, int ret) "%s@%p + 0x%zx: madvise: %d fallocate: %d ret: %d"
 qemu_ram_alloc_shared(const char *name, size_t size, size_t max_size, int fd, void *host) "%s size %zu max_size %zu fd %d host %p"
 
 subpage_register(void *subpage, uint32_t start, uint32_t end, int idx, int eidx, uint16_t section) "subpage %p start 0x%08x end 0x%08x idx 0x%08x eidx 0x%08x section %u"
Signature · 1 line
2.54.0
#18 lore raw

PATCH v5 12/12 RFC: monitor: add 'info ramblock-attributes' command

In reply to Marc-André Lureau

Add a new 'info ramblock-attributes' HMP command and the corresponding 'x-query-ramblock-attributes' QMP command to display the shared/private memory attributes for ram blocks.

The QMP command returns structured data (RamBlockAttributesInfo list with per-range shared/populated attributes), while HMP formats it for human consumption.

This is useful for debugging confidential guests (TDX, SNP) to inspect which memory regions are shared vs private, and their population state when a RamDiscardManager is present (e.g. virtio-mem).

---
 qapi/machine.json             | 56 ++++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 71 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
qapi/machine.json +56 -0
index 685e4e29b87..a1af5c61176 100644
@@ -1738,6 +1738,62 @@
   'returns': 'HumanReadableText',
   'features': [ 'unstable' ] }
 
+##
+# @RamBlockAttributeRange:
+#
+# A contiguous range within a ram block with uniform attributes.
+#
+# @start: start offset in bytes within the ram block
+#
+# @length: length in bytes of the range
+#
+# @shared: true if the range is shared, false if private
+#
+# @populated: true if the entire range is fully populated across all
+#     RamDiscardManager sources; false if any sub-block is discarded.
+#     Only present when a RamDiscardManager is managing the block.
+#
+# Since: 11.1
+##
+{ 'struct': 'RamBlockAttributeRange',
+  'data': { 'start': 'uint64',
+            'length': 'uint64',
+            'shared': 'bool',
+            '*populated': 'bool' } }
+
+##
+# @RamBlockAttributesInfo:
+#
+# Shared/private memory attributes for a ram block.
+#
+# @name: the ram block identifier
+#
+# @ranges: list of attribute ranges
+#
+# Since: 11.1
+##
+{ 'struct': 'RamBlockAttributesInfo',
+  'data': { 'name': 'str',
+            'ranges': [ 'RamBlockAttributeRange' ] } }
+
+##
+# @x-query-ramblock-attributes:
+#
+# Query ram block shared/private attributes.  This is useful
+# to debug confidential guests.
+#
+# Features:
+#
+# @unstable: This command is meant for debugging.
+#
+# Returns: list of ram block attributes
+#
+# Since: 11.1
+##
+{ 'command': 'x-query-ramblock-attributes',
+  'returns': [ 'RamBlockAttributesInfo' ],
+  'features': [ 'unstable' ] }
+
 ##
 # @x-query-roms:
 #
include/monitor/hmp.h +1 -0
index 9258a049bff..c069d5de8d1 100644
@@ -137,6 +137,7 @@ void hmp_info_dump(Monitor *mon, const QDict *qdict);
 void hmp_hotpluggable_cpus(Monitor *mon, const QDict *qdict);
 void hmp_info_vm_generation_id(Monitor *mon, const QDict *qdict);
 void hmp_info_memory_size_summary(Monitor *mon, const QDict *qdict);
+void hmp_info_ramblock_attributes(Monitor *mon, const QDict *qdict);
 void hmp_info_replay(Monitor *mon, const QDict *qdict);
 void hmp_replay_break(Monitor *mon, const QDict *qdict);
 void hmp_replay_delete_break(Monitor *mon, const QDict *qdict);
hw/core/machine-hmp-cmds.c +32 -0
index 46846f741a2..122e1a0f735 100644
@@ -24,6 +24,7 @@
 #include "qapi/string-output-visitor.h"
 #include "qemu/error-report.h"
 #include "system/numa.h"
+#include "system/ramblock.h"
 #include "hw/core/boards.h"
 
 void hmp_info_cpus(Monitor *mon, const QDict *qdict)
@@ -388,3 +389,34 @@ void hmp_info_memory_size_summary(Monitor *mon, const QDict *qdict)
     }
     hmp_handle_error(mon, err);
 }
+
+void hmp_info_ramblock_attributes(Monitor *mon, const QDict *qdict)
+{
+    Error *err = NULL;
+    g_autoptr(RamBlockAttributesInfoList) list = NULL;
+    RamBlockAttributesInfoList *it;
+
+    list = qmp_x_query_ramblock_attributes(&err);
+    if (hmp_handle_error(mon, err)) {
+        return;
+    }
+
+    for (it = list; it; it = it->next) {
+        RamBlockAttributesInfo *rba = it->value;
+        RamBlockAttributeRangeList *r;
+
+        monitor_printf(mon, "%s:\n", rba->name);
+        for (r = rba->ranges; r; r = r->next) {
+            RamBlockAttributeRange *range = r->value;
+            const char *shared = range->shared ? "shared" : "private";
+            const char *pop = range->has_populated ?
+                (range->populated ? "+populated" : "-populated") : "";
+
+            monitor_printf(mon,
+                           "  0x%016" PRIx64 "-0x%016" PRIx64 " %s%s\n",
+                           range->start,
+                           range->start + range->length - 1,
+                           shared, pop);
+        }
+    }
+}
system/ram-block-attributes.c +71 -0

80 lines not on this page · raw message

hmp-commands-info.hx +13 -0
index 82134eb6c21..f119b9cfebc 100644
@@ -761,6 +761,19 @@ SRST
     Dump all the ramblocks of the system.
 ERST
 
+    {
+        .name       = "ramblock-attributes",
+        .args_type  = "",
+        .params     = "",
+        .help       = "Display ramblock shared/private attributes",
+        .cmd        = hmp_info_ramblock_attributes,
+    },
+
+SRST
+  ``info ramblock-attributes``
+    Display the shared/private memory attributes for ram blocks.
+ERST
+
     {
         .name       = "hotpluggable-cpus",
         .args_type  = "",
Signature · 1 line
2.54.0
Acked-by on v5 12/12
#19 lore raw

Re: [PATCH v5 12/12] RFC: monitor: add 'info ramblock-attributes' command

Quoted 12 lines · * Marc-André Lureau ([email protected]) wrote:

Add a new 'info ramblock-attributes' HMP command and the corresponding 'x-query-ramblock-attributes' QMP command to display the shared/private memory attributes for ram blocks.

The QMP command returns structured data (RamBlockAttributesInfo list with per-range shared/populated attributes), while HMP formats it for human consumption.

This is useful for debugging confidential guests (TDX, SNP) to inspect which memory regions are shared vs private, and their population state when a RamDiscardManager is present (e.g. virtio-mem).

Quoted 9 lines
---
 qapi/machine.json             | 56 ++++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 71 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)

<snip>

For HMP,

however, you might consider whether it would be better to add it to the existing "info ramblock"

Dave

Quoted 144 lines
hw/core/machine-hmp-cmds.c +30 -0
+void hmp_info_ramblock_attributes(Monitor *mon, const QDict *qdict)
+{
+    Error *err = NULL;
+    g_autoptr(RamBlockAttributesInfoList) list = NULL;
+    RamBlockAttributesInfoList *it;
+
+    list = qmp_x_query_ramblock_attributes(&err);
+    if (hmp_handle_error(mon, err)) {
+        return;
+    }
+
+    for (it = list; it; it = it->next) {
+        RamBlockAttributesInfo *rba = it->value;
+        RamBlockAttributeRangeList *r;
+
+        monitor_printf(mon, "%s:\n", rba->name);
+        for (r = rba->ranges; r; r = r->next) {
+            RamBlockAttributeRange *range = r->value;
+            const char *shared = range->shared ? "shared" : "private";
+            const char *pop = range->has_populated ?
+                (range->populated ? "+populated" : "-populated") : "";
+
+            monitor_printf(mon,
+                           "  0x%016" PRIx64 "-0x%016" PRIx64 " %s%s\n",
+                           range->start,
+                           range->start + range->length - 1,
+                           shared, pop);
+        }
+    }
+}
system/ram-block-attributes.c +71 -0
index 59ec7a28eb0..fb657ffca35 100644
@@ -11,6 +11,7 @@
 
 #include "qemu/osdep.h"
 #include "qemu/error-report.h"
+#include "qapi/qapi-commands-machine.h"
 #include "system/ramblock.h"
 #include "trace.h"
 
@@ -221,3 +222,73 @@ static void ram_block_attributes_class_init(ObjectClass *klass,
     rdsc->get_min_granularity = ram_block_attributes_rds_get_min_granularity;
     rdsc->is_populated = ram_block_attributes_rds_is_populated;
 }
+
+RamBlockAttributesInfoList *qmp_x_query_ramblock_attributes(Error **errp)
+{
+    RamBlockAttributesInfoList *head = NULL, **tail = &head;
+    RAMBlock *block;
+    size_t rba_block_size = ram_block_attributes_get_block_size();
+
+    RCU_READ_LOCK_GUARD();
+
+    RAMBLOCK_FOREACH(block) {
+        RamBlockAttributesInfo *rba;
+        RamBlockAttributeRangeList **range_tail;
+        RamBlockAttributes *attr = block->attributes;
+        RamDiscardManager *rdm;
+        unsigned long pos;
+
+        if (!attr) {
+            continue;
+        }
+
+        rdm = memory_region_get_ram_discard_manager(block->mr);
+        g_assert(rdm);
+
+        rba = g_new0(RamBlockAttributesInfo, 1);
+        rba->name = g_strdup(block->idstr);
+        range_tail = &rba->ranges;
+
+        pos = 0;
+        while (pos < attr->bitmap_size) {
+            bool is_shared = test_bit(pos, attr->bitmap);
+            unsigned long next;
+            uint64_t start_offset, length;
+            RamBlockAttributeRange *range;
+
+            if (is_shared) {
+                next = find_next_zero_bit(attr->bitmap,
+                                          attr->bitmap_size, pos);
+            } else {
+                next = find_next_bit(attr->bitmap,
+                                     attr->bitmap_size, pos);
+            }
+
+            start_offset = (uint64_t)pos * rba_block_size;
+            length = (uint64_t)(next - pos) * rba_block_size;
+
+            range = g_new0(RamBlockAttributeRange, 1);
+            range->start = start_offset;
+            range->length = length;
+            range->shared = is_shared;
+
+            {
+                MemoryRegionSection section = {
+                    .mr = block->mr,
+                    .offset_within_region = start_offset,
+                    .size = int128_make64(length),
+                };
+                range->has_populated = true;
+                range->populated =
+                    ram_discard_manager_is_populated(rdm, &section);
+            }
+
+            QAPI_LIST_APPEND(range_tail, range);
+            pos = next;
+        }
+
+        QAPI_LIST_APPEND(tail, rba);
+    }
+
+    return head;
+}
hmp-commands-info.hx +13 -0
index 82134eb6c21..f119b9cfebc 100644
@@ -761,6 +761,19 @@ SRST
     Dump all the ramblocks of the system.
 ERST
 
+    {
+        .name       = "ramblock-attributes",
+        .args_type  = "",
+        .params     = "",
+        .help       = "Display ramblock shared/private attributes",
+        .cmd        = hmp_info_ramblock_attributes,
+    },
+
+SRST
+  ``info ramblock-attributes``
+    Display the shared/private memory attributes for ram blocks.
+ERST
+
     {
         .name       = "hotpluggable-cpus",
         .args_type  = "",
Signature · 2 lines
-- 
2.54.0
Signature · 4 lines
 -----Open up your eyes, open up your mind, open up your code -------   
/ Dr. David Alan Gilbert    |       Running GNU/Linux       | Happy  \ 
\        dave @ treblig.org |                               | In Hex /
 \ _________________________|_____ http://www.treblig.org   |_______/
#20 lore raw

Re: [PATCH v5 12/12] RFC: monitor: add 'info ramblock-attributes' command

Quoted 23 lines · Dr. David Alan Gilbert
Quoted 12 lines · * Marc-André Lureau ([email protected]) wrote:

Add a new 'info ramblock-attributes' HMP command and the corresponding 'x-query-ramblock-attributes' QMP command to display the shared/private memory attributes for ram blocks.

The QMP command returns structured data (RamBlockAttributesInfo list with per-range shared/populated attributes), while HMP formats it for human consumption.

This is useful for debugging confidential guests (TDX, SNP) to inspect which memory regions are shared vs private, and their population state when a RamDiscardManager is present (e.g. virtio-mem).

Quoted 9 lines
---
 qapi/machine.json             | 56 ++++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 71 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
Quoted 8 lines

<snip>

For HMP,

however, you might consider whether it would be better to add it to the existing "info ramblock"

Valid suggestion.

HMP "info ramblock" wraps around QMP x-query-ramblock, which returns HumanReadableText.

HMP "info ramblock-attributes" wraps around QMP x-query-ramblock-attributes, which returns a list of RamBlockAttributesInfo.

So, basic x-query-ramblock returns unstructured text, and x-query-ramblock-attributes returns structured data. Hmm. Feels a bit odd.

[...]

#21 lore raw

Re: [PATCH v5 12/12] RFC: monitor: add 'info ramblock-attributes' command

In reply to Marc-André Lureau
Quoted 26 lines · Marc-André Lureau

Add a new 'info ramblock-attributes' HMP command and the corresponding 'x-query-ramblock-attributes' QMP command to display the shared/private memory attributes for ram blocks.

The QMP command returns structured data (RamBlockAttributesInfo list with per-range shared/populated attributes), while HMP formats it for human consumption.

This is useful for debugging confidential guests (TDX, SNP) to inspect which memory regions are shared vs private, and their population state when a RamDiscardManager is present (e.g. virtio-mem).

---
 qapi/machine.json             | 56 ++++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 71 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
qapi/machine.json +0 -0
index 685e4e29b87..a1af5c61176 100644

qapi/machine.json line 1744

Quoted 7 lines
qapi/machine.json +4 -0
@@ -1738,6 +1738,62 @@
   'returns': 'HumanReadableText',
   'features': [ 'unstable' ] }
 
+##
+# @RamBlockAttributeRange:
+#
+# A contiguous range within a ram block with uniform attributes.

RAM please. More of the same below, not flagging it again.

qapi/machine.json line 1750

Quoted 6 lines
qapi/machine.json +6 -0
+#
+# @start: start offset in bytes within the ram block
+#
+# @length: length in bytes of the range
+#
+# @shared: true if the range is shared, false if private

Can we assume that anybody with a use for x-query-ramblock-attributes understands what "range is shared" means?

qapi/machine.json line 1754

Quoted 4 lines
qapi/machine.json +4 -0
+#
+# @populated: true if the entire range is fully populated across all
+#     RamDiscardManager sources; false if any sub-block is discarded.
+#     Only present when a RamDiscardManager is managing the block.

Can we assume that anybody with a use for x-query-ramblock-attributes understands what "a RamDiscardManager is managing the block" means?

I can't find anything about RamDiscardManager in docs. Would it make sense to have something there, so we can point to it here?

Quoted 5 lines
qapi/machine.json +5 -0
+#
+# Since: 11.1
+##
+{ 'struct': 'RamBlockAttributeRange',
+  'data': { 'start': 'uint64',

qapi/machine.json line 1769

Quoted 10 lines
qapi/machine.json +10 -0
+            'length': 'uint64',
+            'shared': 'bool',
+            '*populated': 'bool' } }
+
+##
+# @RamBlockAttributesInfo:
+#
+# Shared/private memory attributes for a ram block.
+#
+# @name: the ram block identifier

Apparently, this is a memory region name, obtained with memory_region_name(). Correct?

If yes, then what about "@name: the memory region name"? Or maybe "the name of the RAM block's memory region"?

Quoted 4 lines
qapi/machine.json +4 -0
+#
+# @ranges: list of attribute ranges
+#
+# Since: 11.1

qapi/machine.json line 1783

Quoted 10 lines
qapi/machine.json +10 -0
+##
+{ 'struct': 'RamBlockAttributesInfo',
+  'data': { 'name': 'str',
+            'ranges': [ 'RamBlockAttributeRange' ] } }
+
+##
+# @x-query-ramblock-attributes:
+#
+# Query ram block shared/private attributes.  This is useful
+# to debug confidential guests.

Ignorant question: how are RAM blocks related to memory regions?

Quoted 16 lines
qapi/machine.json +13 -0
+#
+# Features:
+#
+# @unstable: This command is meant for debugging.
+#
+# Returns: list of ram block attributes
+#
+# Since: 11.1
+##
+{ 'command': 'x-query-ramblock-attributes',
+  'returns': [ 'RamBlockAttributesInfo' ],
+  'features': [ 'unstable' ] }
+
 ##
 # @x-query-roms:
 #

[...]

#22 lore raw
In reply to Marc-André Lureau

Hi

Quoted 7 lines · Marc-André Lureau

Hi,

This is an attempt to fix the incompatibility of virtio-mem with confidential VMs. The solution implements what was discussed earlier with D. Hildenbrand:
https://patchwork.ozlabs.org/project/qemu-devel/patch/[email protected]/#3502238

Quoted 7 lines

The first patches are misc cleanups. Then some code refactoring to have split a manager/source. And finally, the manager learns to deal with multiple sources.

This has been tested together with the Linux kernel series from Zhenzhong Duan [1] for TDX guests.

(help fix https://issues.redhat.com/browse/RHEL-131968)

Can the patch 1-11 be queued or are we missing something? (RFC patch 12 can be dropped for now)

thanks

Quoted 86 lines

v5:
- explain why InterfaceClass in rust binding is not needed after moving RamDiscardSource
- drop extraneous added blank line
- replaced a runtime "if (has_rdm)"" with an assert()
- dropped "RFC: hw/virtio: start virtio-mem guest_memfd regions as shared", in favour of start-private memory approach from "[RFC PATCH 0/6] Support virtio-mem memory hotplug in TDX guests" [1]
- demote "monitor: add 'info ramblock-attributes'" as RFC
- rebased and collected trailers

v4:
- added "system/physmem: make ram_block_discard_range() handle guest_memfd"
- added "monitor: add 'info ramblock-attributes' command"
- added "RFC: hw/virtio: start virtio-mem guest_memfd regions as shared"
- skip calling source in notify_populate (it may not have updated its internal state)
- rebased, collected trailer tags

v3: issues found by Cédric
- fix assertion error on shutdown, due to rcu-defer cleanup
- fix API doc warnings

v2:
- drop replay_{populated,discarded} from source, suggested by Peter Xu
- add extra manager cleanup
- add r-b tags for preliminary patches

- Link to v4: https://lore.kernel.org/qemu-devel/[email protected]

[1]: https://lore.kernel.org/lkml/[email protected]/

---
Marc-André Lureau (12):
system/memory: split RamDiscardManager into source and manager system/memory: move RamDiscardManager to separate compilation unit system/memory: constify section arguments system/ram-discard-manager: implement replay via is_populated iteration
virtio-mem: remove replay_populated/replay_discarded implementation system/ram-discard-manager: drop replay from source interface system/memory: implement RamDiscardManager multi-source aggregation system/physmem: destroy ram block attributes before RCU-deferred reclaim system/memory: add RamDiscardManager reference counting and cleanup
tests: add unit tests for RamDiscardManager multi-source aggregation system/physmem: make ram_block_discard_range() handle guest_memfd
RFC: monitor: add 'info ramblock-attributes' command

 MAINTAINERS                                 |    4 +
 qapi/machine.json                           |   56 ++
 include/hw/vfio/vfio-container.h            |    2 +-
 include/hw/vfio/vfio-cpr.h                  |    2 +-
 include/hw/virtio/virtio-mem.h              |    3 -
 include/monitor/hmp.h                       |    1 +
 include/system/memory.h                     |  279 +-----
 include/system/ram-discard-manager.h        |  358 ++++++++
 include/system/ramblock.h                   |    5 +-
 accel/kvm/kvm-all.c                         |    2 +-
 hw/core/machine-hmp-cmds.c                  |   32 +
 hw/vfio/cpr-legacy.c                        |    4 +-
 hw/vfio/listener.c                          |   10 +-
 hw/virtio/virtio-mem.c                      |  259 +-----
 migration/ram.c                             |    6 +-
 system/memory.c                             |   88 +-
 system/memory_mapping.c                     |    4 +-
 system/physmem.c                            |   27 +-
 system/ram-block-attributes.c               |  328 +++----
 system/ram-discard-manager.c                |  612 +++++++++++++
 target/i386/kvm/tdx.c                       |    2 +-
 tests/unit/test-ram-discard-manager-stubs.c |   48 ++
 tests/unit/test-ram-discard-manager.c       | 1235 +++++++++++++++++++++++++++
 hmp-commands-info.hx                        |   13 +
 rust/bindings/system-sys/lib.rs             |    2 +-
 system/meson.build                          |    1 +
 system/trace-events                         |    2 +-
 tests/unit/meson.build                      |    8 +-
 28 files changed, 2569 insertions(+), 824 deletions(-)

---
base-commit: 405c32d2b18a683ba36301351af75125d9afda08
change-id: 20260414-rdm5-b6df2366d603

Best regards,
--
Marc-André Lureau <[email protected]>

#23 lore raw
Quoted 14 lines · Marc-André Lureau

Hi

Quoted 10 lines · Marc-André Lureau

Hi,

This is an attempt to fix the incompatibility of virtio-mem with confidential VMs. The solution implements what was discussed earlier with D. Hildenbrand:
https://patchwork.ozlabs.org/project/qemu-devel/patch/[email protected]/#3502238

The first patches are misc cleanups. Then some code refactoring to have split a manager/source. And finally, the manager learns to deal with multiple sources.

Quoted 7 lines
Quoted 4 lines

This has been tested together with the Linux kernel series from Zhenzhong Duan [1] for TDX guests.

(help fix https://issues.redhat.com/browse/RHEL-131968)

Can the patch 1-11 be queued or are we missing something? (RFC patch 12 can be dropped for now)

Likely yes.. one thing to double check with you before I do: We don't need the kernel series, do we? Since when unplug, I expect with the truncation approach that this series proposed, KVM will emit TDH.MEM.PAGE.REMOVE then unaccept is done (?).

Say, what happens if we run QEMU with this series applied, but without the kernel series?

What confused me a bit is the dependency of this series v.s. the kernel one. It seems to use different approaches, but then I don't understand why this series was tested with the kernel change.

Thanks,

Signature · 1 line
Peter Xu
#24 lore raw

Hi Peter

Quoted 24 lines · Peter Xu
Quoted 14 lines · Marc-André Lureau

Hi

Quoted 10 lines · Marc-André Lureau

Hi,

This is an attempt to fix the incompatibility of virtio-mem with confidential VMs. The solution implements what was discussed earlier with D. Hildenbrand:
https://patchwork.ozlabs.org/project/qemu-devel/patch/[email protected]/#3502238

The first patches are misc cleanups. Then some code refactoring to have split a manager/source. And finally, the manager learns to deal with multiple sources.

Quoted 7 lines
Quoted 4 lines

This has been tested together with the Linux kernel series from Zhenzhong Duan [1] for TDX guests.

(help fix https://issues.redhat.com/browse/RHEL-131968)

Can the patch 1-11 be queued or are we missing something? (RFC patch 12 can be dropped for now)

Quoted 7 lines

Likely yes.. one thing to double check with you before I do: We don't need the kernel series, do we? Since when unplug, I expect with the truncation approach that this series proposed, KVM will emit TDH.MEM.PAGE.REMOVE then unaccept is done (?).

Say, what happens if we run QEMU with this series applied, but without the kernel series?

The kernel series is needed at least for PAGE.ACCEPT. Without it, QEMU will have KVM_RUN return EIO, and finish into assert (while tearing down ioeventfd).

Quoted 3 lines

What confused me a bit is the dependency of this series v.s. the kernel one. It seems to use different approaches, but then I don't understand why this series was tested with the kernel change.

My understanding is that the kernel may perform TDG.MEM.PAGE.RELEASE. That depends on TDX config TDCS_CONFIG_PAGE_RELEASE which qemu/kvm doesnt currently control. I don't know whether this is then redundant/needless with qemu doing discard on the guest_memfd..

#25 lore raw
Quoted 32 lines · Marc-André Lureau

Hi Peter

Quoted 28 lines · Peter Xu
Quoted 14 lines · Marc-André Lureau

Hi

Quoted 10 lines · Marc-André Lureau

Hi,

This is an attempt to fix the incompatibility of virtio-mem with confidential VMs. The solution implements what was discussed earlier with D. Hildenbrand:
https://patchwork.ozlabs.org/project/qemu-devel/patch/[email protected]/#3502238

The first patches are misc cleanups. Then some code refactoring to have split a manager/source. And finally, the manager learns to deal with multiple sources.

Quoted 7 lines
Quoted 4 lines

This has been tested together with the Linux kernel series from Zhenzhong Duan [1] for TDX guests.

(help fix https://issues.redhat.com/browse/RHEL-131968)

Can the patch 1-11 be queued or are we missing something? (RFC patch 12 can be dropped for now)

Likely yes.. one thing to double check with you before I do: We don't need the kernel series, do we? Since when unplug, I expect with the truncation approach that this series proposed, KVM will emit TDH.MEM.PAGE.REMOVE then unaccept is done (?).

Quoted 6 lines
Quoted 2 lines

Say, what happens if we run QEMU with this series applied, but without the kernel series?

The kernel series is needed at least for PAGE.ACCEPT. Without it, QEMU will have KVM_RUN return EIO, and finish into assert (while tearing down ioeventfd).

Could you elaborate a bit more on why ACCEPT would fail?

I used to ask the event flow here:

https://lore.kernel.org/qemu-devel/[email protected]/

If AUG existed, then why ACCEPT would fail?

PS: I didn't read a lot of what a Linux guest would do; I know there're some lazy accept approach, but IIUC it's only a matter of time to ACCEPT, not correctness. My understanding is if we properly notify these new slots with AUG, then it should be able to ACCEPT?

Quoted 9 lines
Quoted 4 lines

What confused me a bit is the dependency of this series v.s. the kernel one. It seems to use different approaches, but then I don't understand why this series was tested with the kernel change.

My understanding is that the kernel may perform TDG.MEM.PAGE.RELEASE. That depends on TDX config TDCS_CONFIG_PAGE_RELEASE which qemu/kvm doesnt currently control. I don't know whether this is then redundant/needless with qemu doing discard on the guest_memfd..

The problem is if this series depends on the kernel series, should we then wait for the kernel solution be accepted first in case it'll change?

But obviously I still don't yet fully understand how this whole thing works.. :(

Thanks,

Signature · 1 line
Peter Xu
#26 lore raw

Hi Peter

Quoted 45 lines · Peter Xu
Quoted 32 lines · Marc-André Lureau

Hi Peter

Quoted 28 lines · Peter Xu
Quoted 14 lines · Marc-André Lureau

Hi

Quoted 10 lines · Marc-André Lureau

Hi,

This is an attempt to fix the incompatibility of virtio-mem with confidential VMs. The solution implements what was discussed earlier with D. Hildenbrand:
https://patchwork.ozlabs.org/project/qemu-devel/patch/[email protected]/#3502238

The first patches are misc cleanups. Then some code refactoring to have split a manager/source. And finally, the manager learns to deal with multiple sources.

Quoted 7 lines
Quoted 4 lines

This has been tested together with the Linux kernel series from Zhenzhong Duan [1] for TDX guests.

(help fix https://issues.redhat.com/browse/RHEL-131968)

Can the patch 1-11 be queued or are we missing something? (RFC patch 12 can be dropped for now)

Likely yes.. one thing to double check with you before I do: We don't need the kernel series, do we? Since when unplug, I expect with the truncation approach that this series proposed, KVM will emit TDH.MEM.PAGE.REMOVE then unaccept is done (?).

Quoted 6 lines
Quoted 2 lines

Say, what happens if we run QEMU with this series applied, but without the kernel series?

The kernel series is needed at least for PAGE.ACCEPT. Without it, QEMU will have KVM_RUN return EIO, and finish into assert (while tearing down ioeventfd).

Could you elaborate a bit more on why ACCEPT would fail?

I used to ask the event flow here:

Quoted 8 lines

https://lore.kernel.org/qemu-devel/[email protected]/

If AUG existed, then why ACCEPT would fail?

PS: I didn't read a lot of what a Linux guest would do; I know there're some lazy accept approach, but IIUC it's only a matter of time to ACCEPT, not correctness. My understanding is if we properly notify these new slots with AUG, then it should be able to ACCEPT?

Yes, it will, but it needs the kernel patches to do it (or virtio-mem will let the guest access un-accepted pages and qemu will crash). I submitted a few proposals before Zhenzhong Duan proposed the last iteration.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

What confused me a bit is the dependency of this series v.s. the kernel one. It seems to use different approaches, but then I don't understand why this series was tested with the kernel change.

Quoted 7 lines
Quoted 4 lines

My understanding is that the kernel may perform TDG.MEM.PAGE.RELEASE. That depends on TDX config TDCS_CONFIG_PAGE_RELEASE which qemu/kvm doesnt currently control. I don't know whether this is then redundant/needless with qemu doing discard on the guest_memfd..

The problem is if this series depends on the kernel series, should we then wait for the kernel solution be accepted first in case it'll change?

I don't think qemu needs to wait for the kernel to be fixed. Furthermore, this series is not tdx/sev/etc specific

Quoted 3 lines

But obviously I still don't yet fully understand how this whole thing works.. :(

I am also slow, because I don't focus on this most of the time. Someone with more experience and dedication would handle it better.

Applied
#27 lore raw
Quoted 57 lines · Marc-André Lureau

Hi Peter

Quoted 45 lines · Peter Xu
Quoted 32 lines · Marc-André Lureau

Hi Peter

Quoted 28 lines · Peter Xu
Quoted 14 lines · Marc-André Lureau

Hi

Quoted 10 lines · Marc-André Lureau

Hi,

This is an attempt to fix the incompatibility of virtio-mem with confidential VMs. The solution implements what was discussed earlier with D. Hildenbrand:
https://patchwork.ozlabs.org/project/qemu-devel/patch/[email protected]/#3502238

The first patches are misc cleanups. Then some code refactoring to have split a manager/source. And finally, the manager learns to deal with multiple sources.

Quoted 7 lines
Quoted 4 lines

This has been tested together with the Linux kernel series from Zhenzhong Duan [1] for TDX guests.

(help fix https://issues.redhat.com/browse/RHEL-131968)

Can the patch 1-11 be queued or are we missing something? (RFC patch 12 can be dropped for now)

Likely yes.. one thing to double check with you before I do: We don't need the kernel series, do we? Since when unplug, I expect with the truncation approach that this series proposed, KVM will emit TDH.MEM.PAGE.REMOVE then unaccept is done (?).

Quoted 6 lines
Quoted 2 lines

Say, what happens if we run QEMU with this series applied, but without the kernel series?

The kernel series is needed at least for PAGE.ACCEPT. Without it, QEMU will have KVM_RUN return EIO, and finish into assert (while tearing down ioeventfd).

Could you elaborate a bit more on why ACCEPT would fail?

I used to ask the event flow here:

Quoted 8 lines

https://lore.kernel.org/qemu-devel/[email protected]/

If AUG existed, then why ACCEPT would fail?

PS: I didn't read a lot of what a Linux guest would do; I know there're some lazy accept approach, but IIUC it's only a matter of time to ACCEPT, not correctness. My understanding is if we properly notify these new slots with AUG, then it should be able to ACCEPT?

Quoted 4 lines

Yes, it will, but it needs the kernel patches to do it (or virtio-mem will let the guest access un-accepted pages and qemu will crash). I submitted a few proposals before Zhenzhong Duan proposed the last iteration.

OK, I think I misunderstood both the crash and also what Zhenzhong's series is trying to do. After a closer look, it seems to be a proposal for any plug/unplug to work. I'm surprised (if I get it right this time..) that TD didn't seem to support DIMM hotplugs besides virtio-mem.

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
Quoted 5 lines

What confused me a bit is the dependency of this series v.s. the kernel one. It seems to use different approaches, but then I don't understand why this series was tested with the kernel change.

My understanding is that the kernel may perform TDG.MEM.PAGE.RELEASE. That depends on TDX config TDCS_CONFIG_PAGE_RELEASE which qemu/kvm doesnt currently control. I don't know whether this is then redundant/needless with qemu doing discard on the guest_memfd..

Quoted 5 lines
Quoted 2 lines

The problem is if this series depends on the kernel series, should we then wait for the kernel solution be accepted first in case it'll change?

I don't think qemu needs to wait for the kernel to be fixed. Furthermore, this series is not tdx/sev/etc specific

AFAIU it is coco specific, otherwise we only always have 1 source, hence no need for this series to provide this function.

Said that, I agree with you.. Looks like there's no major plan to add anything specific to QEMU.

Patch 1-10 are all reviewed patches and correctly resolve the known >1 ram sources and it's a design problem, I don't see how we can bypass that.

Patch 11 is very reasonable on its own, then I assume the guest ACCEPT problem will need to evolve on its own. Looks like the direction is correct, and only some corner cases to think about (acpi coverage, lazy accept, etc.) that I saw in the discussion.

Quoted 7 lines
Quoted 4 lines

But obviously I still don't yet fully understand how this whole thing works.. :(

I am also slow, because I don't focus on this most of the time. Someone with more experience and dedication would handle it better.

I queued patch 1-11, will send a pull this week. Thanks for all the explanations.

Signature · 1 line
Peter Xu