Re: [PATCH v11 30/35] KVM: x86: Add gmem hook for determining max NPT mapping level

Paolo Bonzini
2024-02-12T10:50:43Z

On Sat, Dec 30, 2023 at 6:32 PM Michael Roth <michael.roth@amd.com> wrote:
> int max_order, r;
> + u8 max_level;
>
> if (!kvm_slot_can_be_private(fault->slot)) {
> kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
> @@ -4321,8 +4322,15 @@ static int kvm_faultin_pfn_private(struct kvm_vcpu *vcpu,
> return r;
> }
>
> - fault->max_level = min(kvm_max_level_for_order(max_order),
> - fault->max_level);
> + max_level = kvm_max_level_for_order(max_order);
> + r = static_call(kvm_x86_gmem_max_level)(vcpu->kvm, fault->pfn,
> + fault->gfn, &max_level);

Might as well pass &fault->max_level directly to the callback, with no
change to the vendor-specific code.

I'll include the MMU part in a generic series to be the base for both
Intel TDX and AMD SEV-SNP, and will do that change.

Paolo

> + if (r) {
> + kvm_release_pfn_clean(fault->pfn);
> + return r;
> + }
> +
> + fault->max_level = min(max_level, fault->max_level);
> fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
>
> return RET_PF_CONTINUE;
> diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
> index 85f63b6842b6..5eb836b73131 100644
> --- a/arch/x86/kvm/svm/sev.c
> +++ b/arch/x86/kvm/svm/sev.c
> @@ -4315,3 +4315,30 @@ void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
> pfn += use_2m_update ? PTRS_PER_PMD : 1;
> }
> }
> +
> +int sev_gmem_max_level(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, u8 *max_level)
> +{
> + int level, rc;
> + bool assigned;
> +
> + if (!sev_snp_guest(kvm))
> + return 0;
> +
> + rc = snp_lookup_rmpentry(pfn, &assigned, &level);
> + if (rc) {
> + pr_err_ratelimited("SEV: RMP entry not found: GFN %llx PFN %llx level %d error %d\n",
> + gfn, pfn, level, rc);
> + return -ENOENT;
> + }
> +
> + if (!assigned) {
> + pr_err_ratelimited("SEV: RMP entry is not assigned: GFN %llx PFN %llx level %d\n",
> + gfn, pfn, level);
> + return -EINVAL;
> + }
> +
> + if (level < *max_level)
> + *max_level = level;
> +
> + return 0;
> +}
> diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
> index f26b8c2a8be4..f745022f7454 100644
> --- a/arch/x86/kvm/svm/svm.c
> +++ b/arch/x86/kvm/svm/svm.c
> @@ -5067,6 +5067,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
> .alloc_apic_backing_page = svm_alloc_apic_backing_page,
>
> .gmem_prepare = sev_gmem_prepare,
> + .gmem_max_level = sev_gmem_max_level,
> .gmem_invalidate = sev_gmem_invalidate,
> };
>
> --
> 2.25.1
>