[PATCH v1 03/13] KVM: Allow late setting of KVM_MEM_USERFAULT on guest_memfd memslot

James Houghton
2024-12-04T19:14:18Z

Currently guest_memfd memslots can only be deleted. Slightly change the
logic to allow KVM_MR_FLAGS_ONLY changes when the only flag being
changed is KVM_MEM_USERFAULT.

Signed-off-by: James Houghton <jthoughton@google.com>
---
virt/kvm/kvm_main.c | 15 +++++++++++----
1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index 23fa3e911c4e..fa851704db94 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -2009,9 +2009,6 @@ int __kvm_set_memory_region(struct kvm *kvm,
if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
return -EINVAL;
} else { /* Modify an existing slot. */
- /* Private memslots are immutable, they can only be deleted. */
- if (mem->flags & KVM_MEM_GUEST_MEMFD)
- return -EINVAL;
if ((mem->userspace_addr != old->userspace_addr) ||
(npages != old->npages) ||
((mem->flags ^ old->flags) & KVM_MEM_READONLY))
@@ -2025,6 +2022,16 @@ int __kvm_set_memory_region(struct kvm *kvm,
return 0;
}

+ /*
+ * Except for being able to set KVM_MEM_USERFAULT, private memslots are
+ * immutable, they can only be deleted.
+ */
+ if (mem->flags & KVM_MEM_GUEST_MEMFD &&
+ !(change == KVM_MR_CREATE ||
+ (change == KVM_MR_FLAGS_ONLY &&
+ (mem->flags ^ old->flags) == KVM_MEM_USERFAULT)))
+ return -EINVAL;
+
if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
return -EEXIST;
@@ -2040,7 +2047,7 @@ int __kvm_set_memory_region(struct kvm *kvm,
new->npages = npages;
new->flags = mem->flags;
new->userspace_addr = mem->userspace_addr;
- if (mem->flags & KVM_MEM_GUEST_MEMFD) {
+ if (mem->flags & KVM_MEM_GUEST_MEMFD && change == KVM_MR_CREATE) {
r = kvm_gmem_bind(kvm, new, mem->guest_memfd, mem->guest_memfd_offset);
if (r)
goto out;
--
2.47.0.338.g60cca15819-goog