On 11/20/2025 1:29 AM, Peter Xu wrote:
Detect supported guest-memfd flags by the current kernel, and reject
creations of guest-memfd using invalid flags.  When the cap isn't
available, then no flag is supported.

Signed-off-by: Peter Xu <[email protected]>
---
  accel/kvm/kvm-all.c | 11 +++++++++++
  1 file changed, 11 insertions(+)

diff --git a/accel/kvm/kvm-all.c b/accel/kvm/kvm-all.c
index 96c194ce54..f477014126 100644
--- a/accel/kvm/kvm-all.c
+++ b/accel/kvm/kvm-all.c
@@ -108,6 +108,7 @@ static int kvm_sstep_flags;
  static bool kvm_immediate_exit;
  static uint64_t kvm_supported_memory_attributes;
  static bool kvm_guest_memfd_supported;
+static uint64_t kvm_guest_memfd_flags_supported;
  static hwaddr kvm_max_slot_size = ~0;
static const KVMCapabilityInfo kvm_required_capabilites[] = {
@@ -2787,6 +2788,10 @@ static int kvm_init(AccelState *as, MachineState *ms)
      kvm_guest_memfd_supported =
          kvm_vm_check_extension(s, KVM_CAP_GUEST_MEMFD) &&
          kvm_vm_check_extension(s, KVM_CAP_USER_MEMORY2);
+
+    ret = kvm_vm_check_extension(s, KVM_CAP_GUEST_MEMFD_FLAGS);
+    kvm_guest_memfd_flags_supported = ret > 0 ? ret : 0;
+
      kvm_pre_fault_memory_supported = kvm_vm_check_extension(s, 
KVM_CAP_PRE_FAULT_MEMORY);
if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
@@ -4492,6 +4497,12 @@ int kvm_create_guest_memfd(uint64_t size, uint64_t 
flags, Error **errp)
          return -1;
      }
+ if (flags & ~kvm_guest_memfd_flags_supported) {
+        error_setg(errp, "KVM does not support guest-memfd flag: 0x%"PRIx64,

I'm thinking if need to add "for current VM" like:

        KVM does not support guest-memfd flag: xxx for current VM

because kvm_guest_memfd_flags_supported is got from VM-scope CAP and varies for different VM types.

+                   flags & ~kvm_guest_memfd_flags_supported);
+        return -1;
+    }
+
      fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
      if (fd < 0) {
          error_setg_errno(errp, errno, "Error creating KVM guest_memfd");


Reply via email to