Skip to contentSkip to conversation

Make RamDiscardManager work with multiple sources & virtio-mem

PATCH Superseded Marc-André Lureau 7 participants 42 messages May 4 – Jun 4

Subsystems (3)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v4 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.

I haven't done thorough testing. I only launched a SEV guest with a virtio-mem device. It would be nice to have more tests for those scenarios with VFIO/virtio-mem/confvm.. In any case, review & testing needed!

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

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

---
Marc-André Lureau (13):
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
monitor: add 'info ramblock-attributes' command
RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

 MAINTAINERS                                 |    4 +
 qapi/machine.json                           |   55 ++
 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                     |  283 +-----
 include/system/ram-discard-manager.h        |  358 ++++++++
 include/system/ramblock.h                   |    6 +-
 accel/kvm/kvm-all.c                         |    5 +-
 hw/core/machine-hmp-cmds.c                  |   32 +
 hw/vfio/cpr-legacy.c                        |    4 +-
 hw/vfio/listener.c                          |   10 +-
 hw/virtio/virtio-mem.c                      |  286 ++-----
 migration/ram.c                             |    6 +-
 system/memory.c                             |   83 +-
 system/memory_mapping.c                     |    4 +-
 system/physmem.c                            |   27 +-
 system/ram-block-attributes.c               |  329 +++----
 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, 2597 insertions(+), 826 deletions(-)

---
base-commit: ac0cc20ad2fe0b8df2e5d9458e90a095ac711ab1
change-id: 20260414-rdm5-b6df2366d603

Best regards,

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

PATCH v4 1/13 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      |   3 +-
 hw/virtio/virtio-mem.c         | 163 ++++++------------------------
 system/memory.c                | 218 ++++++++++++++++++++++++++++++++++++-----
 system/ram-block-attributes.c  | 171 ++++++++++----------------------
 6 files changed, 386 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 +1 -2
index 4435f8d55fe..f0b557af416 100644
@@ -99,11 +99,10 @@ 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 */
+
 int ram_block_discard_range(RAMBlock *rb, uint64_t offset, size_t length);
 /* @offset: the offset within the RAMBlock */
 int ram_block_discard_guest_memfd_range(RAMBlock *rb, uint64_t offset,
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
Acked-by on v4 1/13
#2 lore raw

Re: [PATCH v4 01/13] system/memory: split RamDiscardManager into source and manager

Quoted 26 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).

---

[...]

Quoted 3 lines

/* @offset: the offset within the RAMBlock */
+

Unrelated?

Quoted 16 lines

int ram_block_discard_range(RAMBlock *rb, uint64_t offset, size_t length); /* @offset: the offset within the RAMBlock */
int ram_block_discard_guest_memfd_range(RAMBlock *rb, uint64_t offset,

hw/virtio/virtio-mem.c +1 -0
index a4b71974a1c..be149ee9441 100644
@@ -16,6 +16,7 @@
 #include "qemu/error-report.h"
 #include "qemu/units.h"
 #include "qemu/target-info-qapi.h"
+#include "system/memory.h"
 #include "system/numa.h"
 #include "system/system.h"
 #include "system/ramblock.h"

hw/virtio/virtio-mem.c static int virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem, · line 327

Quoted 3 lines
hw/virtio/virtio-mem.c +0 -0
@@ -324,74 +325,31 @@ static int virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem,
     return ret;
 }
 

LGTM

Signature · 3 lines
Cheers,

David
#3 lore raw

PATCH v4 2/13 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.

---
 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 afa178c5cce..239218bc1f1 100644
@@ -3315,6 +3315,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
@@ -3325,6 +3326,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
Acked-by on v4 2/13
#4 lore raw

Re: [PATCH v4 02/13] system/memory: move RamDiscardManager to separate compilation unit

Quoted 10 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/bindings/system-sys/lib.rs line 24

Quoted 13 lines
system/ram-discard-manager.c new file +2 -0
+
+type_init(ram_discard_manager_register_types)
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};

Why does that belong here? If it actually belongs here, spell it out in the patch description, please.

LGTM

Signature · 3 lines
Cheers,

David
#5 lore raw

PATCH v4 3/13 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 033a546c301..cca7dd08dfc 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 31c3113f8fb..e784868f62a 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 = NULL;
 
@@ -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 2046f16caa2..3f69b8733eb 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;
@@ -1595,7 +1595,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);
@@ -1670,7 +1670,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
Reviewed-by on v4 3/13
#6 lore raw

Re: [PATCH v4 03/13] system/memory: constify section arguments

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(-)
#8 lore raw

PATCH v4 4/13 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
Reviewed-by on v4 4/13
#9 lore raw

Re: [PATCH v4 04/13] 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 6 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 · 1 line
Peter Xu
#10 lore raw

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

In reply to Marc-André Lureau
Quoted 137 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.

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 +59 -22
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));

system/ram-discard-manager.c int ram_discard_manager_replay_populated_to_listeners(RamDiscardManager *rdm) · line 249

Quoted 7 lines
system/ram-discard-manager.c +2 -2
@@ -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);

I'm probably missing something. You are changing the parameters passed to ram_discard_manager_replay_populated(), but ram_discard_manager_replay_populated() is not actually modified in this patch to take other parameters?

Signature · 3 lines
Cheers,

David
#11 lore raw

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

Hi

Quoted 11 lines · David Hildenbrand (Arm)

system/ram-discard-manager.c void ram_discard_manager_register_listener(RamDiscardManager *rdm, · line 223

Quoted 4 lines · Marc-André Lureau
system/ram-discard-manager.c +2 -2
-        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);

I'm probably missing something. You are changing the parameters passed to ram_discard_manager_replay_populated(), but ram_discard_manager_replay_populated() is not actually modified in this patch to take other parameters?

We are switching from calling RamDiscard "Source" replay() to RamDiscard "Manager" (with a single source for now).

thanks

#12 lore raw

PATCH v4 5/13 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
Reviewed-by on v4 5/13
#13 lore raw

Re: [PATCH v4 05/13] virtio-mem: remove replay_populated/replay_discarded implementation

Quoted 10 lines · 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.

Signature · 1 line
Peter Xu
Acked-by on v4 5/13
#14 lore raw

Re: [PATCH v4 05/13] virtio-mem: remove replay_populated/replay_discarded implementation

In reply to Marc-André Lureau
Quoted 11 lines · 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.

---

As raised, I wonder what the cost of that will be for large (e.g., 1 TiB?) devices.

Time will tell whether you'll have to fix a regression :P

Signature · 3 lines
Cheers,

David
#15 lore raw

PATCH v4 6/13 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
Reviewed-by on v4 6/13
#16 lore raw

Re: [PATCH v4 06/13] system/ram-discard-manager: drop replay from source interface

Quoted 9 lines · 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.

Signature · 1 line
Peter Xu
Acked-by on v4 6/13
#17 lore raw

Re: [PATCH v4 06/13] system/ram-discard-manager: drop replay from source interface

In reply to Marc-André Lureau
Quoted 10 lines · 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.

---

Signature · 3 lines
Cheers,

David
#18 lore raw

PATCH v4 7/13 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/ram-discard-manager.h | 141 ++++++++++--
 hw/virtio/virtio-mem.c               |   8 +-
 system/memory.c                      |  15 +-
 system/ram-block-attributes.c        |   6 +-
 system/ram-discard-manager.c         | 427 +++++++++++++++++++++++++++++++----
 5 files changed, 514 insertions(+), 83 deletions(-)
include/system/ram-discard-manager.h +117 -24
index b5dbcb4a82d..05d3d31b55a 100644
@@ -170,30 +170,96 @@ struct RamDiscardSourceClass {
  * becoming discarded in a different granularity than it was populated and the
  * other way around.
  */
+
+typedef struct RamDiscardSourceEntry RamDiscardSourceEntry;
+
+struct RamDiscardSourceEntry {
+    RamDiscardSource *rds;
+    QLIST_ENTRY(RamDiscardSourceEntry) next;
+};
+
 struct RamDiscardManager {
     Object parent;
 
-    RamDiscardSource *rds;
     MemoryRegion *mr;
+    QLIST_HEAD(, RamDiscardSourceEntry) source_list;
+    uint64_t min_granularity;
     QLIST_HEAD(, RamDiscardListener) rdl_list;
 };
 
-RamDiscardManager *ram_discard_manager_new(MemoryRegion *mr,
-                                           RamDiscardSource *rds);
+RamDiscardManager *ram_discard_manager_new(MemoryRegion *mr);
+
+/**
+ * ram_discard_manager_add_source:
+ *
+ * Register a #RamDiscardSource with the #RamDiscardManager. The manager
+ * aggregates state from all registered sources using AND semantics: a region
+ * is considered populated only if ALL sources report it as populated.
+ *
+ * If listeners are already registered, they will be notified about any
+ * regions that become discarded due to adding this source. Specifically,
+ * for each region that the new source reports as discarded, if all other
+ * sources reported it as populated, listeners receive a discard notification.
+ *
+ * If any listener rejects the notification (returns an error), previously
+ * notified listeners are rolled back with populate notifications and the
+ * source is not added.
+ *
+ * @rdm: the #RamDiscardManager
+ * @source: the #RamDiscardSource to add
+ *
+ * Returns: 0 on success, -EBUSY if @source is already registered, or a
+ *          negative error code if a listener rejected the state change.
+ */
+int ram_discard_manager_add_source(RamDiscardManager *rdm,
+                                   RamDiscardSource *source);
+
+/**
+ * ram_discard_manager_del_source:
+ *
+ * Unregister a #RamDiscardSource from the #RamDiscardManager.
+ *
+ * If listeners are already registered, they will be notified about any
+ * regions that become populated due to removing this source. Specifically,
+ * for each region that the removed source reported as discarded, if all
+ * remaining sources report it as populated, listeners receive a populate
+ * notification.
+ *
+ * If any listener rejects the notification (returns an error), previously
+ * notified listeners are rolled back with discard notifications and the
+ * source is not removed.
+ *
+ * @rdm: the #RamDiscardManager
+ * @source: the #RamDiscardSource to remove
+ *
+ * Returns: 0 on success, -ENOENT if @source is not registered, or a
+ *          negative error code if a listener rejected the state change.
+ */
+int ram_discard_manager_del_source(RamDiscardManager *rdm,
+                                   RamDiscardSource *source);
+
 
 uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,
                                                  const MemoryRegion *mr);
 
+/**
+ * ram_discard_manager_is_populated:
+ *
+ * Check if the given memory region section is populated.
+ * If the manager has no sources, it is considered populated.
+ *
+ * @rdm: the #RamDiscardManager
+ * @section: the #MemoryRegionSection to check
+ *
+ * Returns: true if the section is populated, false otherwise.
+ */
 bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
                                       const MemoryRegionSection *section);
 
 /**
  * ram_discard_manager_replay_populated:
  *
- * 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.
+ * Call @replay_fn on regions that are populated in all sources.
  *
  * @rdm: the #RamDiscardManager
  * @section: the #MemoryRegionSection
@@ -210,10 +276,7 @@ int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
 /**
  * ram_discard_manager_replay_discarded:
  *
- * 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.
+ * Call @replay_fn on regions that are discarded in any sources.
  *
  * @rdm: the #RamDiscardManager
  * @section: the #MemoryRegionSection
@@ -234,31 +297,61 @@ void ram_discard_manager_register_listener(RamDiscardManager *rdm,
 void ram_discard_manager_unregister_listener(RamDiscardManager *rdm,
                                              RamDiscardListener *rdl);
 
-/*
- * Note: later refactoring should take the source into account and the manager
- *       should be able to aggregate multiple sources.
+/**
+ * ram_discard_manager_notify_populate:
+ *
+ * Notify listeners that a region is about to be populated by a source.
+ * For multi-source aggregation, only notifies when all sources agree
+ * the region is populated (intersection).
+ *
+ * @rdm: the #RamDiscardManager
+ * @source: the #RamDiscardSource that is populating
+ * @offset: offset within the memory region
+ * @size: size of the region being populated
+ *
+ * Returns 0 on success, or a negative error if any listener rejects.
  */
 int ram_discard_manager_notify_populate(RamDiscardManager *rdm,
+                                        RamDiscardSource *source,
                                         uint64_t offset, uint64_t size);
 
-/*
- * Note: later refactoring should take the source into account and the manager
- *       should be able to aggregate multiple sources.
+/**
+ * ram_discard_manager_notify_discard:
+ *
+ * Notify listeners that a region has been discarded by a source.
+ * For multi-source aggregation, always notifies immediately
+ * (union semantics - any source discarding makes region discarded).
+ *
+ * @rdm: the #RamDiscardManager
+ * @source: the #RamDiscardSource that is discarding
+ * @offset: offset within the memory region
+ * @size: size of the region being discarded
  */
 void ram_discard_manager_notify_discard(RamDiscardManager *rdm,
+                                        RamDiscardSource *source,
                                         uint64_t offset, uint64_t size);
 
-/*
- * Note: later refactoring should take the source into account and the manager
- *       should be able to aggregate multiple sources.
+/**
+ * ram_discard_manager_notify_discard_all:
+ *
+ * Notify listeners that all regions have been discarded by a source.
+ *
+ * @rdm: the #RamDiscardManager
+ * @source: the #RamDiscardSource that is discarding
  */
-void ram_discard_manager_notify_discard_all(RamDiscardManager *rdm);
+void ram_discard_manager_notify_discard_all(RamDiscardManager *rdm,
+                                            RamDiscardSource *source);
 
-/*
+/**
+ * ram_discard_manager_replay_populated_to_listeners:
+ *
  * Replay populated sections to all registered listeners.
+ * For multi-source aggregation, only replays regions where all sources
+ * are populated (intersection).
  *
- * Note: later refactoring should take the source into account and the manager
- *       should be able to aggregate multiple sources.
+ * @rdm: the #RamDiscardManager
+ *
+ * Returns 0 on success, or a negative error if any notification failed.
  */
 int ram_discard_manager_replay_populated_to_listeners(RamDiscardManager *rdm);
 
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 +8 -7
index 97695a253e6..4768375053a 100644
@@ -2046,21 +2046,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,
                                           RamDiscardSource *source)
 {
-    g_assert(mr->rdm->rds == source);
+    g_assert(mr->rdm);
+
+    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
#19 lore raw

PATCH v4 8/13 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 c58d940e807..a8472c91dff 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
#20 lore raw

PATCH v4 9/13 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              | 7 +++++--
 system/ram-discard-manager.c | 2 ++
 2 files changed, 7 insertions(+), 2 deletions(-)
system/memory.c +5 -2
index 4768375053a..456c53a1af4 100644
@@ -1754,6 +1754,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)
@@ -2060,8 +2061,10 @@ void memory_region_del_ram_discard_source(MemoryRegion *mr,
     g_assert(mr->rdm);
 
     ram_discard_manager_del_source(mr->rdm, source);
-
-    /* if there is no source and no listener left, we could free rdm */
+    if (QLIST_EMPTY(&mr->rdm->source_list) && QLIST_EMPTY(&mr->rdm->rdl_list)) {
+        object_unref(mr->rdm);
+        mr->rdm = NULL;
+    }
 }
 
 /* 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
#21 lore raw

PATCH v4 10/13 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 239218bc1f1..3601da89080 100644
@@ -3328,6 +3328,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 03d36748c73..e303f80119f 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
#22 lore raw

PATCH v4 11/13 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 f0b557af416..76a84fd9c88 100644
@@ -104,7 +104,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 92af42503b1..97463a683f4 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 a8472c91dff..5af9d5ac1a8 100644
@@ -4085,7 +4085,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;
 
@@ -4134,7 +4134,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.
@@ -4190,8 +4190,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);
@@ -4201,6 +4202,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
Reviewed-by on v4 11/13
#23 lore raw

Re: [PATCH v4 11/13] system/physmem: make ram_block_discard_range() handle guest_memfd

Quoted 10 lines · 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.

Quoted 7 lines

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().

Signature · 1 line
Peter Xu
Reviewed-by on v4 11/13
#24 lore raw

Re: [PATCH v4 11/13] system/physmem: make ram_block_discard_range() handle guest_memfd

In reply to Marc-André Lureau
Quoted 10 lines · 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.

Quoted 7 lines

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().

#25 lore raw

PATCH v4 12/13 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             | 55 +++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 72 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
qapi/machine.json +55 -0
index 685e4e29b87..aac8a235cf6 100644
@@ -1738,6 +1738,61 @@
   '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 range is populated (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 e222bea60cd..4493952b417 100644
@@ -143,6 +143,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 +72 -0

81 lines not on this page · raw message

hmp-commands-info.hx +13 -0
index 74c741f80e2..1168b4c20ca 100644
@@ -774,6 +774,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
#26 lore raw

Re: [PATCH v4 12/13] monitor: add 'info ramblock-attributes' command

Quoted 8 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.

Quoted 5 lines

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).

Nobody is copied on this patch.. Let me add Markus and Dave at minimum..

Only one trivial question below:

Quoted 191 lines
---
 qapi/machine.json             | 55 +++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 72 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
qapi/machine.json +55 -0
index 685e4e29b87..aac8a235cf6 100644
@@ -1738,6 +1738,61 @@
   '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 range is populated (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 e222bea60cd..4493952b417 100644
@@ -143,6 +143,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 +43 -0
index 59ec7a28eb0..f9573801b60 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,74 @@ 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;
+        bool has_rdm;
+        unsigned long pos;
+
+        if (!attr) {
+            continue;
+        }
+
+        rdm = memory_region_get_ram_discard_manager(block->mr);
+        has_rdm = rdm != NULL;
+
+        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);
+            }

system/ram-block-attributes.c static void ram_block_attributes_class_init(ObjectClass *klass, · line 276

Quoted 10 lines
system/ram-block-attributes.c +10 -0
+
+            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;
+
+            if (has_rdm) {

Is this only for extra safety? My understanding is when reaching here, attr!=NULL, which means we have at least one disgard manager source, then the manager must be there. So I wonder if we could assert. But not a big deal. Maybe I overlooked that it is needed?

Quoted 48 lines
system/ram-block-attributes.c +19 -0
+                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 74c741f80e2..1168b4c20ca 100644
@@ -774,6 +774,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 · 1 line
Peter Xu
#27 lore raw

Re: [PATCH v4 12/13] monitor: add 'info ramblock-attributes' command

Hi,

Quoted 8 lines · Peter Xu

system/ram-block-attributes.c static void ram_block_attributes_class_init(ObjectClass *klass, · line 276

Quoted 6 lines · Marc-André Lureau
system/ram-block-attributes.c +6 -0
+            range = g_new0(RamBlockAttributeRange, 1);
+            range->start = start_offset;
+            range->length = length;
+            range->shared = is_shared;
+
+            if (has_rdm) {
Quoted 4 lines

Is this only for extra safety? My understanding is when reaching here, attr!=NULL, which means we have at least one disgard manager source, then the manager must be there. So I wonder if we could assert. But not a big deal. Maybe I overlooked that it is needed?

Correct, a RAM block attribute ensures the presence of a discard manager. This should remain valid in the future, I'll use assert().

#28 lore raw

Re: [PATCH v4 12/13] monitor: add 'info ramblock-attributes' command

In reply to Marc-André Lureau

qapi/machine.json

Quoted 25 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             | 55 +++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 72 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
qapi/machine.json +0 -0
index 685e4e29b87..aac8a235cf6 100644

I have a few fairly ignorant questions. They may or may not indicate a need for doc improvements.

qapi/machine.json line 1744

Quoted 8 lines
qapi/machine.json +4 -0
@@ -1738,6 +1738,61 @@
   '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

What does it mean for a range to be shared?

qapi/machine.json line 1753

Quoted 3 lines
qapi/machine.json +3 -0
+#
+# @populated: true if the range is populated (only present when a
+#     RamDiscardManager is managing the block)

What's a RamDiscardManager?

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

qapi/machine.json line 1768

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

Where do RAM block names come from?

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

qapi/machine.json line 1782

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.

What are RAM blocks?

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:
 #

[...]

#29 lore raw

Re: [PATCH v4 12/13] monitor: add 'info ramblock-attributes' command

Hi Markus

I am not an expert in this area, and I am only working on this series occasionally (too little activity to keep me fresh on the topic, unfortunately). Bear with me.

Quoted 36 lines · Markus Armbruster

qapi/machine.json

Quoted 25 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             | 55 +++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 72 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
qapi/machine.json +0 -0
index 685e4e29b87..aac8a235cf6 100644

I have a few fairly ignorant questions. They may or may not indicate a need for doc improvements.

Quoted 4 lines
qapi/machine.json +0 -0
@@ -1738,6 +1738,61 @@
   'returns': 'HumanReadableText',
   'features': [ 'unstable' ] }
 
Quoted 7 lines

qapi/machine.json line 1744

Quoted 4 lines
qapi/machine.json +4 -0
+##
+# @RamBlockAttributeRange:
+#
+# A contiguous range within a ram block with uniform attributes.

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

ok

Quoted 8 lines

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

What does it mean for a range to be shared?

commit 5d6483edaa9232d8f3709f68c8eab4bc2033fb70
"in the current context
of RamDiscardManager for guest_memfd, the shared state is analogous to being populated, while the private state can be considered discarded for simplicity. In the future, it would be more complicated if considering more states like private/shared/discarded at the same time."

Quoted 6 lines

qapi/machine.json line 1753

Quoted 4 lines
qapi/machine.json +3 -0
+#
+# @populated: true if the range is populated (only present when a
+#     RamDiscardManager is managing the block)

What's a RamDiscardManager?

commit 8947d7fc4e77d36fae44411b1b63c513863f89a7
* A #RamDiscardManager coordinates which parts of specific RAM #MemoryRegion
* regions are currently populated to be used/accessed by the VM, notifying
* after parts were discarded (freeing up memory) and before parts will be
* populated (consuming memory), to be used/accessed by the VM.

In this series, RamDiscardManager learned to aggregate from multiple sources (virtio-mem + RamBlockAttributes), so virtio-mem can work with confidential VMs.

Quoted 10 lines
Quoted 10 lines
qapi/machine.json +9 -0
+#
+# Since: 11.1
+##
+{ 'struct': 'RamBlockAttributeRange',
+  'data': { 'start': 'uint64',
+            'length': 'uint64',
+            'shared': 'bool',
+            '*populated': 'bool' } }
+
Quoted 8 lines

qapi/machine.json line 1768

Quoted 6 lines
qapi/machine.json +6 -0
+##
+# @RamBlockAttributesInfo:
+#
+# Shared/private memory attributes for a ram block.
+#
+# @name: the ram block identifier

Where do RAM block names come from?

They are set during vmstate_register_ram(). "idstr" and "name" are used interchangeably to refer to it.

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

qapi/machine.json line 1782

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.

What are RAM blocks?

They are the actual host allocated memory backing guest RAM MemoryRegions

Quoted 21 lines
Quoted 17 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:
 #

[...]

#30 lore raw

Re: [PATCH v4 12/13] monitor: add 'info ramblock-attributes' command

Quoted 5 lines · Marc-André Lureau

Hi Markus

I am not an expert in this area, and I am only working on this series occasionally (too little activity to keep me fresh on the topic, unfortunately). Bear with me.

Sure!

Quoted 56 lines · Markus Armbruster
Quoted 36 lines

qapi/machine.json

Quoted 25 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             | 55 +++++++++++++++++++++++++++++++++
 include/monitor/hmp.h         |  1 +
 hw/core/machine-hmp-cmds.c    | 32 +++++++++++++++++++
 system/ram-block-attributes.c | 72 +++++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx          | 13 ++++++++
 5 files changed, 173 insertions(+)
qapi/machine.json +0 -0
index 685e4e29b87..aac8a235cf6 100644

I have a few fairly ignorant questions. They may or may not indicate a need for doc improvements.

Quoted 4 lines
qapi/machine.json +0 -0
@@ -1738,6 +1738,61 @@
   'returns': 'HumanReadableText',
   'features': [ 'unstable' ] }
 
Quoted 7 lines

qapi/machine.json line 1744

Quoted 4 lines
qapi/machine.json +4 -0
+##
+# @RamBlockAttributeRange:
+#
+# A contiguous range within a ram block with uniform attributes.

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

ok

Quoted 8 lines

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

What does it mean for a range to be shared?

Quoted 6 lines

commit 5d6483edaa9232d8f3709f68c8eab4bc2033fb70
"in the current context
of RamDiscardManager for guest_memfd, the shared state is analogous to being populated, while the private state can be considered discarded for simplicity. In the future, it would be more complicated if considering more states like private/shared/discarded at the same time."

Thought and care went into that commit message. Unfortunately, it's still greek to me. Not criticism! It needs to make sense to the people working in that area, and I'm not.

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

Quoted 12 lines
Quoted 5 lines

qapi/machine.json line 1753

Quoted 3 lines
qapi/machine.json +3 -0
+#
+# @populated: true if the range is populated (only present when a
+#     RamDiscardManager is managing the block)

What's a RamDiscardManager?

commit 8947d7fc4e77d36fae44411b1b63c513863f89a7
* A #RamDiscardManager coordinates which parts of specific RAM #MemoryRegion
* regions are currently populated to be used/accessed by the VM, notifying
* after parts were discarded (freeing up memory) and before parts will be
* populated (consuming memory), to be used/accessed by the VM.

Quoted 3 lines

In this series, RamDiscardManager learned to aggregate from multiple sources (virtio-mem + RamBlockAttributes), so virtio-mem can work with confidential VMs.

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 18 lines
Quoted 9 lines
Quoted 9 lines
qapi/machine.json +9 -0
+#
+# Since: 11.1
+##
+{ 'struct': 'RamBlockAttributeRange',
+  'data': { 'start': 'uint64',
+            'length': 'uint64',
+            'shared': 'bool',
+            '*populated': 'bool' } }
+
Quoted 8 lines

qapi/machine.json line 1768

Quoted 6 lines
qapi/machine.json +6 -0
+##
+# @RamBlockAttributesInfo:
+#
+# Shared/private memory attributes for a ram block.
+#
+# @name: the ram block identifier

Where do RAM block names come from?

Quoted 2 lines

They are set during vmstate_register_ram(). "idstr" and "name" are used interchangeably to refer to it.

    void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
    {
        qemu_ram_set_idstr(mr->ram_block,
                           memory_region_name(mr), dev);
        qemu_ram_set_migratable(mr->ram_block);
        ram_block_add_cpr_blocker(mr->ram_block, &error_fatal);
    }

Looks like it's the name of the memory region associated with the RAM block. Would "the memory region name" do? Or would something like "the name of the RAM block's memory region" be better?

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

qapi/machine.json line 1782

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.

What are RAM blocks?

Quoted 1 line

They are the actual host allocated memory backing guest RAM MemoryRegions

How are RAM blocks related to memory regions?

Quoted 18 lines
Quoted 18 lines
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:
 #

[...]

#31 lore raw

Re: [PATCH v4 12/13] monitor: add 'info ramblock-attributes' command

In reply to Marc-André Lureau
Quoted 3 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.

Can we abstract the "ramblock" stuff somehow, and refer to it as (hypervisor-specific) memory attributs somehow?

Signature · 3 lines
Cheers,

David
#32 lore raw

Re: [PATCH v4 12/13] monitor: add 'info ramblock-attributes' command

Hi David

Quoted 9 lines · David Hildenbrand (Arm)
Quoted 3 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.

Can we abstract the "ramblock" stuff somehow, and refer to it as (hypervisor-specific) memory attributs somehow?

I am not sure we can abstract this meaningfully; it would likely make things more confusing, imho.

The x- prefix command and documentation indicate this is internal debugging, subject to change.

We can just drop this command if it's not useful or generic enough.

#33 lore raw

PATCH v4 13/13 RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

In reply to Marc-André Lureau

In TDX guests, virtio-mem plug/unplug/re-plug fails because kvm_set_phys_mem() unconditionally sets KVM memory attributes to PRIVATE for all guest_memfd regions. On re-plug, the PRIVATE->PRIVATE transition is a no-op, so KVM doesn't re-AUG pages and the guest's TDG.MEM.PAGE.ACCEPT fails.

Implement the "start-shared" approach: virtio-mem memory starts with shared KVM attributes. The guest converts shared->private on plug (via set_memory_encrypted -> MapGPA + ACCEPT), and back to shared on unplug (via set_memory_decrypted). This ensures every plug triggers a real SHARED->PRIVATE transition, causing KVM to AUG fresh pages.

Add RAM_GUEST_MEMFD_START_SHARED flag and set it during virtio-mem realize for guest_memfd-backed regions. Use ram_block_attributes_state_change() to properly update the attributes bitmap through the API. Skip setting PRIVATE in kvm_set_phys_mem() when the flag is set. On unplug, explicitly reset KVM attributes to shared on the host side to handle the case where the guest skips set_memory_decrypted().

See also virtio-comment "[PATCH RFC] virtio-mem: add shared/private memory property details".

---
 include/system/memory.h |  6 ++++++
 accel/kvm/kvm-all.c     |  3 ++-
 hw/virtio/virtio-mem.c  | 27 ++++++++++++++++++++++++++-
 3 files changed, 34 insertions(+), 2 deletions(-)
include/system/memory.h +6 -0
index 28a75dac4ae..9dbf67efe50 100644
@@ -277,6 +277,12 @@ typedef struct IOMMUTLBEvent {
  */
 #define RAM_PRIVATE (1 << 13)
 
+/*
+ * RAM with guest_memfd that should start with shared KVM memory
+ * attributes. The guest converts to private on use.
+ */
+#define RAM_GUEST_MEMFD_START_SHARED (1 << 14)
+
 static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
                                        IOMMUNotifierFlag flags,
                                        hwaddr start, hwaddr end,
accel/kvm/kvm-all.c +2 -1
index 97463a683f4..c034e74c8e5 100644
@@ -1737,7 +1737,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,
             abort();
         }
 
-        if (memory_region_has_guest_memfd(mr)) {
+        if (memory_region_has_guest_memfd(mr) &&
+            !(mr->ram_block->flags & RAM_GUEST_MEMFD_START_SHARED)) {
             err = kvm_set_memory_attributes_private(start_addr, slot_size);
             if (err) {
                 error_report("%s: failed to set memory attribute private: %s",
hw/virtio/virtio-mem.c +26 -1
index 35e03ed7599..b46efe21126 100644
@@ -19,6 +19,7 @@
 #include "system/memory.h"
 #include "system/numa.h"
 #include "system/system.h"
+#include "system/kvm.h"
 #include "system/ramblock.h"
 #include "system/reset.h"
 #include "system/runstate.h"
@@ -479,6 +480,11 @@ static int virtio_mem_set_block_state(VirtIOMEM *vmem, uint64_t start_gpa,
         if (vmem->dynamic_memslots) {
             virtio_mem_deactivate_unplugged_memslots(vmem, offset, size);
         }
+        if (rb->flags & RAM_GUEST_MEMFD_START_SHARED) {
+            kvm_set_memory_attributes_shared(start_gpa, size);
+            ram_block_attributes_state_change(rb->attributes,
+                                              offset, size, false);
+        }
         return 0;
     }
 
@@ -606,10 +612,12 @@ static int virtio_mem_unplug_all(VirtIOMEM *vmem)
     RAMBlock *rb = vmem->memdev->mr.ram_block;
 
     if (vmem->size) {
+        uint64_t used = qemu_ram_get_used_length(rb);
+
         if (virtio_mem_is_busy()) {
             return -EBUSY;
         }
-        if (ram_block_discard_range(rb, 0, qemu_ram_get_used_length(rb))) {
+        if (ram_block_discard_range(rb, 0, used)) {
             return -EBUSY;
         }
         virtio_mem_notify_unplug_all(vmem);
@@ -622,6 +630,11 @@ static int virtio_mem_unplug_all(VirtIOMEM *vmem)
         if (vmem->dynamic_memslots) {
             virtio_mem_deactivate_unplugged_memslots(vmem, 0, region_size);
         }
+        if (rb->flags & RAM_GUEST_MEMFD_START_SHARED) {
+            kvm_set_memory_attributes_shared(vmem->addr, used);
+            ram_block_attributes_state_change(rb->attributes,
+                                              0, used, false);
+        }
     }
 
     trace_virtio_mem_unplugged_all();
@@ -859,6 +872,18 @@ static void virtio_mem_device_realize(DeviceState *dev, Error **errp)
     rb = vmem->memdev->mr.ram_block;
     page_size = qemu_ram_pagesize(rb);
 
+    /*
+     * For CoCo VMs with guest_memfd, use the "start-shared" model:
+     * memory starts as shared and the guest converts to private on
+     * plug.
+     */
+    if (rb->flags & RAM_GUEST_MEMFD) {
+        rb->flags |= RAM_GUEST_MEMFD_START_SHARED;
+        ram_block_attributes_state_change(rb->attributes, 0,
+                                          qemu_ram_get_used_length(rb),
+                                          false);
+    }
+
     if (virtio_mem_has_legacy_guests()) {
         switch (vmem->unplugged_inaccessible) {
         case ON_OFF_AUTO_AUTO:
Signature · 1 line
2.54.0
#34 lore raw

Re: [PATCH v4 13/13] RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

Quoted 5 lines · Marc-André Lureau

In TDX guests, virtio-mem plug/unplug/re-plug fails because kvm_set_phys_mem() unconditionally sets KVM memory attributes to PRIVATE for all guest_memfd regions. On re-plug, the PRIVATE->PRIVATE transition is a no-op, so KVM doesn't re-AUG pages and the guest's TDG.MEM.PAGE.ACCEPT fails.

Know little on TDX, please bare with me..

I saw KVM does a seamcall to ADD or AUG whenever a new EPT pte is set, via this path:

        __tdp_mmu_set_spte_atomic
        set_external_spte_present
        tdx_sept_set_private_spte <------

On unplug, I'm expecting with your prior patches, gmem pages will be truncated properly, so they'll be all gone.

Then, qemu does replug -> guest gets that event, start access page -> EPT violation, KVM resolving page fault with __tdp_mmu_set_spte_atomic() (per above) and a new page -> triggering AUG (not ADD, since it's post-boot).

Could you elaborate here why AUG is missing in the first place?

Thanks,

Quoted 129 lines

Implement the "start-shared" approach: virtio-mem memory starts with shared KVM attributes. The guest converts shared->private on plug (via set_memory_encrypted -> MapGPA + ACCEPT), and back to shared on unplug (via set_memory_decrypted). This ensures every plug triggers a real SHARED->PRIVATE transition, causing KVM to AUG fresh pages.

Add RAM_GUEST_MEMFD_START_SHARED flag and set it during virtio-mem realize for guest_memfd-backed regions. Use ram_block_attributes_state_change() to properly update the attributes bitmap through the API. Skip setting PRIVATE in kvm_set_phys_mem() when the flag is set. On unplug, explicitly reset KVM attributes to shared on the host side to handle the case where the guest skips set_memory_decrypted().

See also virtio-comment "[PATCH RFC] virtio-mem: add shared/private memory property details".

---
 include/system/memory.h |  6 ++++++
 accel/kvm/kvm-all.c     |  3 ++-
 hw/virtio/virtio-mem.c  | 27 ++++++++++++++++++++++++++-
 3 files changed, 34 insertions(+), 2 deletions(-)
include/system/memory.h +6 -0
index 28a75dac4ae..9dbf67efe50 100644
@@ -277,6 +277,12 @@ typedef struct IOMMUTLBEvent {
  */
 #define RAM_PRIVATE (1 << 13)
 
+/*
+ * RAM with guest_memfd that should start with shared KVM memory
+ * attributes. The guest converts to private on use.
+ */
+#define RAM_GUEST_MEMFD_START_SHARED (1 << 14)
+
 static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
                                        IOMMUNotifierFlag flags,
                                        hwaddr start, hwaddr end,
accel/kvm/kvm-all.c +2 -1
index 97463a683f4..c034e74c8e5 100644
@@ -1737,7 +1737,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,
             abort();
         }
 
-        if (memory_region_has_guest_memfd(mr)) {
+        if (memory_region_has_guest_memfd(mr) &&
+            !(mr->ram_block->flags & RAM_GUEST_MEMFD_START_SHARED)) {
             err = kvm_set_memory_attributes_private(start_addr, slot_size);
             if (err) {
                 error_report("%s: failed to set memory attribute private: %s",
hw/virtio/virtio-mem.c +26 -1
index 35e03ed7599..b46efe21126 100644
@@ -19,6 +19,7 @@
 #include "system/memory.h"
 #include "system/numa.h"
 #include "system/system.h"
+#include "system/kvm.h"
 #include "system/ramblock.h"
 #include "system/reset.h"
 #include "system/runstate.h"
@@ -479,6 +480,11 @@ static int virtio_mem_set_block_state(VirtIOMEM *vmem, uint64_t start_gpa,
         if (vmem->dynamic_memslots) {
             virtio_mem_deactivate_unplugged_memslots(vmem, offset, size);
         }
+        if (rb->flags & RAM_GUEST_MEMFD_START_SHARED) {
+            kvm_set_memory_attributes_shared(start_gpa, size);
+            ram_block_attributes_state_change(rb->attributes,
+                                              offset, size, false);
+        }
         return 0;
     }
 
@@ -606,10 +612,12 @@ static int virtio_mem_unplug_all(VirtIOMEM *vmem)
     RAMBlock *rb = vmem->memdev->mr.ram_block;
 
     if (vmem->size) {
+        uint64_t used = qemu_ram_get_used_length(rb);
+
         if (virtio_mem_is_busy()) {
             return -EBUSY;
         }
-        if (ram_block_discard_range(rb, 0, qemu_ram_get_used_length(rb))) {
+        if (ram_block_discard_range(rb, 0, used)) {
             return -EBUSY;
         }
         virtio_mem_notify_unplug_all(vmem);
@@ -622,6 +630,11 @@ static int virtio_mem_unplug_all(VirtIOMEM *vmem)
         if (vmem->dynamic_memslots) {
             virtio_mem_deactivate_unplugged_memslots(vmem, 0, region_size);
         }
+        if (rb->flags & RAM_GUEST_MEMFD_START_SHARED) {
+            kvm_set_memory_attributes_shared(vmem->addr, used);
+            ram_block_attributes_state_change(rb->attributes,
+                                              0, used, false);
+        }
     }
 
     trace_virtio_mem_unplugged_all();
@@ -859,6 +872,18 @@ static void virtio_mem_device_realize(DeviceState *dev, Error **errp)
     rb = vmem->memdev->mr.ram_block;
     page_size = qemu_ram_pagesize(rb);
 
+    /*
+     * For CoCo VMs with guest_memfd, use the "start-shared" model:
+     * memory starts as shared and the guest converts to private on
+     * plug.
+     */
+    if (rb->flags & RAM_GUEST_MEMFD) {
+        rb->flags |= RAM_GUEST_MEMFD_START_SHARED;
+        ram_block_attributes_state_change(rb->attributes, 0,
+                                          qemu_ram_get_used_length(rb),
+                                          false);
+    }
+
     if (virtio_mem_has_legacy_guests()) {
         switch (vmem->unplugged_inaccessible) {
         case ON_OFF_AUTO_AUTO:
Signature · 2 lines
-- 
2.54.0
Signature · 1 line
Peter Xu
#35 lore raw

Re: [PATCH v4 13/13] RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

Quoted 16 lines · Peter Xu
Quoted 5 lines · Marc-André Lureau

In TDX guests, virtio-mem plug/unplug/re-plug fails because kvm_set_phys_mem() unconditionally sets KVM memory attributes to PRIVATE for all guest_memfd regions. On re-plug, the PRIVATE->PRIVATE transition is a no-op, so KVM doesn't re-AUG pages and the guest's TDG.MEM.PAGE.ACCEPT fails.

Know little on TDX, please bare with me..

I saw KVM does a seamcall to ADD or AUG whenever a new EPT pte is set, via this path:

         __tdp_mmu_set_spte_atomic
         set_external_spte_present
         tdx_sept_set_private_spte <------
Quoted 8 lines

On unplug, I'm expecting with your prior patches, gmem pages will be truncated properly, so they'll be all gone.

Then, qemu does replug -> guest gets that event, start access page -> EPT violation, KVM resolving page fault with __tdp_mmu_set_spte_atomic() (per above) and a new page -> triggering AUG (not ADD, since it's post-boot).

Could you elaborate here why AUG is missing in the first place?

Peter, you analysis is correct.

The reason why plug -> unplug -> re-plug fails, is QEMU fails to discard the private memory so that KVM doesn't zap the private mapping. When re-plug and guest re-accepts, KVM doesn't get involved. Not discard the private memory on unplug leads to another issue that the private memory is still accessible to the guest.

But patch 11 fixes this. Patch 11 should be enough and we don't need this patch. For guest kernel side, we need to ensure the guest kernel accepts the new plugged memory, and no "start-shared" trick is required.

BTW, "start-shared" memory for coco is not something good. It violates the contract that all the memory for Coco VM is initial private (accepted or unaccepted) from EFI spec. We probably should avoid introducing exception unless we have to.

#36 lore raw

Re: [PATCH v4 13/13] RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

Quoted 34 lines · Xiaoyao Li
Quoted 16 lines · Peter Xu
Quoted 5 lines · Marc-André Lureau

In TDX guests, virtio-mem plug/unplug/re-plug fails because kvm_set_phys_mem() unconditionally sets KVM memory attributes to PRIVATE for all guest_memfd regions. On re-plug, the PRIVATE->PRIVATE transition is a no-op, so KVM doesn't re-AUG pages and the guest's TDG.MEM.PAGE.ACCEPT fails.

Know little on TDX, please bare with me..

I saw KVM does a seamcall to ADD or AUG whenever a new EPT pte is set, via this path:

         __tdp_mmu_set_spte_atomic
         set_external_spte_present
         tdx_sept_set_private_spte <------

Quoted 8 lines

On unplug, I'm expecting with your prior patches, gmem pages will be truncated properly, so they'll be all gone.

Then, qemu does replug -> guest gets that event, start access page -> EPT violation, KVM resolving page fault with __tdp_mmu_set_spte_atomic() (per above) and a new page -> triggering AUG (not ADD, since it's post-boot).

Could you elaborate here why AUG is missing in the first place?

Peter, you analysis is correct.

The reason why plug -> unplug -> re-plug fails, is QEMU fails to discard the private memory so that KVM doesn't zap the private mapping. When re-plug and guest re-accepts, KVM doesn't get involved. Not discard the private memory on unplug leads to another issue that the private memory is still accessible to the guest.

Quoted 9 lines

But patch 11 fixes this. Patch 11 should be enough and we don't need this patch. For guest kernel side, we need to ensure the guest kernel accepts the new plugged memory, and no "start-shared" trick is required.

BTW, "start-shared" memory for coco is not something good. It violates the contract that all the memory for Coco VM is initial private (accepted or unaccepted) from EFI spec. We probably should avoid introducing exception unless we have to.

Sorry, I have to double check: you are saying we do not need this patch, and instead the guest has to do the right thing after plugging memory?

Signature · 3 lines
Cheers,

David
#37 lore raw

Re: [PATCH v4 13/13] RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

Quoted 39 lines · David Hildenbrand (Arm)
Quoted 38 lines · Xiaoyao Li
Quoted 16 lines · Peter Xu
Quoted 5 lines · Marc-André Lureau

In TDX guests, virtio-mem plug/unplug/re-plug fails because kvm_set_phys_mem() unconditionally sets KVM memory attributes to PRIVATE for all guest_memfd regions. On re-plug, the PRIVATE->PRIVATE transition is a no-op, so KVM doesn't re-AUG pages and the guest's TDG.MEM.PAGE.ACCEPT fails.

Know little on TDX, please bare with me..

I saw KVM does a seamcall to ADD or AUG whenever a new EPT pte is set, via this path:

         __tdp_mmu_set_spte_atomic
         set_external_spte_present
         tdx_sept_set_private_spte <------

Quoted 8 lines

On unplug, I'm expecting with your prior patches, gmem pages will be truncated properly, so they'll be all gone.

Then, qemu does replug -> guest gets that event, start access page -> EPT violation, KVM resolving page fault with __tdp_mmu_set_spte_atomic() (per above) and a new page -> triggering AUG (not ADD, since it's post-boot).

Could you elaborate here why AUG is missing in the first place?

Peter, you analysis is correct.

The reason why plug -> unplug -> re-plug fails, is QEMU fails to discard the private memory so that KVM doesn't zap the private mapping. When re-plug and guest re-accepts, KVM doesn't get involved. Not discard the private memory on unplug leads to another issue that the private memory is still accessible to the guest.

But patch 11 fixes this. Patch 11 should be enough and we don't need this patch. For guest kernel side, we need to ensure the guest kernel accepts the new plugged memory, and no "start-shared" trick is required.

Quoted 8 lines
Quoted 5 lines

BTW, "start-shared" memory for coco is not something good. It violates the contract that all the memory for Coco VM is initial private (accepted or unaccepted) from EFI spec. We probably should avoid introducing exception unless we have to.

Sorry, I have to double check: you are saying we do not need this patch, and instead the guest has to do the right thing after plugging memory?

right, that's what I meant.

Whether the initial state of the (re-)hotplugged virtio-mem is shared or private doesn't matter. Guest has to try to accept it before using it as private memory. If guest hits the re-accept error, which means the memory has not been taken off at the previous unplug and means the memory is actually always available to the guest.

What matters is the host VMM needs to ensure the memory is actually unplug'ed on the unplug operation, which is achieved by the patch 11 in this series.

#38 lore raw

Re: [PATCH v4 13/13] RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

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

In TDX guests, virtio-mem plug/unplug/re-plug fails because kvm_set_phys_mem() unconditionally sets KVM memory attributes to PRIVATE for all guest_memfd regions. On re-plug, the PRIVATE->PRIVATE transition is a no-op, so KVM doesn't re-AUG pages and the guest's TDG.MEM.PAGE.ACCEPT fails.

I think private->private conversion is a no-op success, it will continue to do KVM_PRE_FAULT_MEMORY in kvm_handle_hc_map_gpa_range() and KVM will AUG pages.

Quoted 7 lines

Implement the "start-shared" approach: virtio-mem memory starts with shared KVM attributes. The guest converts shared->private on plug (via set_memory_encrypted -> MapGPA + ACCEPT), and back to shared on unplug (via set_memory_decrypted). This ensures every plug triggers a real SHARED->PRIVATE transition, causing KVM to AUG fresh pages.

Quoted 7 lines

Add RAM_GUEST_MEMFD_START_SHARED flag and set it during virtio-mem realize for guest_memfd-backed regions. Use ram_block_attributes_state_change() to properly update the attributes bitmap through the API. Skip setting PRIVATE in kvm_set_phys_mem() when the flag is set. On unplug, explicitly reset KVM attributes to shared on the host side to handle the case where the guest skips set_memory_decrypted().

If we only want to support unplug the shared memory, should we restrict it to check the attribute instead of resetting to shared unconditionally?

Quoted 2 lines

See also virtio-comment "[PATCH RFC] virtio-mem: add shared/private memory property details".

Maybe I missed some context, can you provide the link to this RFC patch?

#39 lore raw
In reply to Marc-André Lureau
Quoted 6 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 8 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.

I haven't done thorough testing. I only launched a SEV guest with a virtio-mem device. It would be nice to have more tests for those scenarios with VFIO/virtio-mem/confvm.. In any case, review & testing needed!

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

Copy David for virtio-mem: David, please see if you're OK with virtio-mem side of things; if you have time look at everything it'll be even better.

Copy Chenyi: would you please check with your environment on whether you still hit issue with this series?

The whole series can be found here:

https://lore.kernel.org/all/[email protected]/

Side note: this version still contain quite some "over 80 chars" checkpatch complains... please consider fixing them when repost.

Thanks,

Quoted 71 lines

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

---
Marc-André Lureau (13):
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
monitor: add 'info ramblock-attributes' command
RFC: hw/virtio: start virtio-mem guest_memfd regions as shared

 MAINTAINERS                                 |    4 +
 qapi/machine.json                           |   55 ++
 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                     |  283 +-----
 include/system/ram-discard-manager.h        |  358 ++++++++
 include/system/ramblock.h                   |    6 +-
 accel/kvm/kvm-all.c                         |    5 +-
 hw/core/machine-hmp-cmds.c                  |   32 +
 hw/vfio/cpr-legacy.c                        |    4 +-
 hw/vfio/listener.c                          |   10 +-
 hw/virtio/virtio-mem.c                      |  286 ++-----
 migration/ram.c                             |    6 +-
 system/memory.c                             |   83 +-
 system/memory_mapping.c                     |    4 +-
 system/physmem.c                            |   27 +-
 system/ram-block-attributes.c               |  329 +++----
 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, 2597 insertions(+), 826 deletions(-)

---
base-commit: ac0cc20ad2fe0b8df2e5d9458e90a095ac711ab1
change-id: 20260414-rdm5-b6df2366d603

Best regards,

Signature · 1 line
Marc-André Lureau <[email protected]>
Signature · 1 line
Peter Xu
#40 lore raw
Quoted 14 lines · Peter Xu
Quoted 13 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.

I haven't done thorough testing. I only launched a SEV guest with a virtio-mem device. It would be nice to have more tests for those scenarios with VFIO/virtio-mem/confvm.. In any case, review & testing needed!

Quoted 7 lines
Quoted 1 line

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

Copy David for virtio-mem: David, please see if you're OK with virtio-mem side of things; if you have time look at everything it'll be even better.

Copy Chenyi: would you please check with your environment on whether you still hit issue with this series?

With this series along with the ongoing virtio-mem guest change[1], I can launch the TD guest with a virtio-mem device and do the plug/unplug/replug operations successfully.

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

#41 lore raw
In reply to Peter Xu
Quoted 10 lines · Peter Xu
Quoted 9 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 8 lines
Quoted 5 lines

I haven't done thorough testing. I only launched a SEV guest with a virtio-mem device. It would be nice to have more tests for those scenarios with VFIO/virtio-mem/confvm.. In any case, review & testing needed!

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

Copy David for virtio-mem: David, please see if you're OK with virtio-mem side of things; if you have time look at everything it'll be even better.

Sorry for the delay, conferences and holiday ...

let me take a look.

Signature · 3 lines
Cheers,

David