Re: [PATCH v7 11/14] KVM: Register/unregister the guest private memory regions

From: Vishal Annapurve
Date: Fri Aug 19 2022 - 15:38:00 EST


> ...
> diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
> index 230c8ff9659c..bb714c2a4b06 100644
> --- a/virt/kvm/kvm_main.c
> +++ b/virt/kvm/kvm_main.c
> @@ -914,6 +914,35 @@ static int kvm_init_mmu_notifier(struct kvm *kvm)
>
> #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
>
> +#ifdef CONFIG_HAVE_KVM_PRIVATE_MEM
> +#define KVM_MEM_ATTR_PRIVATE 0x0001
> +static int kvm_vm_ioctl_set_encrypted_region(struct kvm *kvm, unsigned int ioctl,
> + struct kvm_enc_region *region)
> +{
> + unsigned long start, end;
> + void *entry;
> + int r;
> +
> + if (region->size == 0 || region->addr + region->size < region->addr)
> + return -EINVAL;
> + if (region->addr & (PAGE_SIZE - 1) || region->size & (PAGE_SIZE - 1))
> + return -EINVAL;
> +
> + start = region->addr >> PAGE_SHIFT;
> + end = (region->addr + region->size - 1) >> PAGE_SHIFT;
> +
> + entry = ioctl == KVM_MEMORY_ENCRYPT_REG_REGION ?
> + xa_mk_value(KVM_MEM_ATTR_PRIVATE) : NULL;
> +
> + r = xa_err(xa_store_range(&kvm->mem_attr_array, start, end,
> + entry, GFP_KERNEL_ACCOUNT));

xa_store_range seems to create multi-index entries by default.
Subsequent xa_store_range call changes all the entries stored
previously.
xa_store needs to be used here instead of xa_store_range to achieve
the intended behavior.

> +
> + kvm_zap_gfn_range(kvm, start, end + 1);
> +
> + return r;
> +}
> +#endif /* CONFIG_HAVE_KVM_PRIVATE_MEM */
> +
> ...