Re: [RFC v2 PATCH 06/13] KVM: Register/unregister memfd backed memslot

From: Steven Price
Date: Thu Nov 25 2021 - 11:58:02 EST


On 19/11/2021 13:47, Chao Peng wrote:
> Signed-off-by: Yu Zhang <yu.c.zhang@xxxxxxxxxxxxxxx>
> Signed-off-by: Chao Peng <chao.p.peng@xxxxxxxxxxxxxxx>
> ---
> virt/kvm/kvm_main.c | 23 +++++++++++++++++++----
> 1 file changed, 19 insertions(+), 4 deletions(-)
>
> diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
> index 271cef8d1cd0..b8673490d301 100644
> --- a/virt/kvm/kvm_main.c
> +++ b/virt/kvm/kvm_main.c
> @@ -1426,7 +1426,7 @@ static void update_memslots(struct kvm_memslots *slots,
> static int check_memory_region_flags(struct kvm *kvm,
> const struct kvm_userspace_memory_region_ext *mem)
> {
> - u32 valid_flags = 0;
> + u32 valid_flags = KVM_MEM_FD;
>
> if (!kvm->dirty_log_unsupported)
> valid_flags |= KVM_MEM_LOG_DIRTY_PAGES;
> @@ -1604,10 +1604,20 @@ static int kvm_set_memslot(struct kvm *kvm,
> kvm_copy_memslots(slots, __kvm_memslots(kvm, as_id));
> }
>
> + if (mem->flags & KVM_MEM_FD && change == KVM_MR_CREATE) {
> + r = kvm_memfd_register(kvm, mem, new);
> + if (r)
> + goto out_slots;
> + }
> +
> r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
> if (r)
> goto out_slots;
>
> + if (mem->flags & KVM_MEM_FD && (r || change == KVM_MR_DELETE)) {
^
r will never be non-zero as the 'if' above will catch that case and jump
to out_slots.

I *think* the intention was that the "if (r)" code should be after this
check to clean up in the case of error from
kvm_arch_prepare_memory_region() (as well as an explicit MR_DELETE).

Steve

> + kvm_memfd_unregister(kvm, new);
> + }
> +
> update_memslots(slots, new, change);
> slots = install_new_memslots(kvm, as_id, slots);
>
> @@ -1683,10 +1693,12 @@ int __kvm_set_memory_region(struct kvm *kvm,
> return -EINVAL;
> if (mem->guest_phys_addr & (PAGE_SIZE - 1))
> return -EINVAL;
> - /* We can read the guest memory with __xxx_user() later on. */
> if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
> - (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
> - !access_ok((void __user *)(unsigned long)mem->userspace_addr,
> + (mem->userspace_addr != untagged_addr(mem->userspace_addr)))
> + return -EINVAL;
> + /* We can read the guest memory with __xxx_user() later on. */
> + if (!(mem->flags & KVM_MEM_FD) &&
> + !access_ok((void __user *)(unsigned long)mem->userspace_addr,
> mem->memory_size))
> return -EINVAL;
> if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
> @@ -1727,6 +1739,9 @@ int __kvm_set_memory_region(struct kvm *kvm,
> new.dirty_bitmap = NULL;
> memset(&new.arch, 0, sizeof(new.arch));
> } else { /* Modify an existing slot. */
> + /* Private memslots are immutable, they can only be deleted. */
> + if (mem->flags & KVM_MEM_FD && mem->private_fd >= 0)
> + return -EINVAL;
> if ((new.userspace_addr != old.userspace_addr) ||
> (new.npages != old.npages) ||
> ((new.flags ^ old.flags) & KVM_MEM_READONLY))
>