Add AMD Secure Nested Paging (SEV-SNP) Hypervisor Support
Subsystems (12)
v4 cover Add AMD Secure Nested Paging (SEV-SNP) Hypervisor Support
This part of the Secure Encrypted Paging (SEV-SNP) series focuses on the changes required in a host OS for SEV-SNP support. The series builds upon SEV-SNP Part-1.
This series provides the basic building blocks to support booting the SEV-SNP VMs, it does not cover all the security enhancement introduced by the SEV-SNP such as interrupt protection.
The CCP driver is enhanced to provide new APIs that use the SEV-SNP specific commands defined in the SEV-SNP firmware specification. The KVM driver uses those APIs to create and managed the SEV-SNP guests.
The GHCB specification version 2 introduces new set of NAE's that is used by the SEV-SNP guest to communicate with the hypervisor. The series provides support to handle the following new NAE events:
- Register GHCB GPA
- Page State Change Request
- Hypevisor feature
- Guest message request
The RMP check is enforced as soon as SEV-SNP is enabled. Not every memory access requires an RMP check. In particular, the read accesses from the hypervisor do not require RMP checks because the data confidentiality is already protected via memory encryption. When hardware encounters an RMP checks failure, it raises a page-fault exception. If RMP check failure is due to the page-size mismatch, then split the large page to resolve the fault.
The series does not provide support for the following SEV-SNP specific NAE's yet:
* Interrupt security
The series is based on the commit:
a4345a7cecfb (origin/next, next) Merge tag 'kvmarm-fixes-5.13-1'
Changes since v3:
* Add support for extended guest message request.
* Add ioctl to query the SNP Platform status.
* Add ioctl to get and set the SNP config.
* Add check to verify that memory reserved for the RMP covers the full system RAM.
* Start the SNP specific commands from 256 instead of 255.
* Multiple cleanup and fixes based on the review feedback.
Changes since v2:
* Add AP creation support.
* Drop the patch to handle the RMP fault for the kernel address.
* Add functions to track the write access from the hypervisor.
* Do not enable the SNP feature when IOMMU is disabled or is in passthrough mode.
* Dump the RMP entry on RMP violation for the debug.
* Shorten the GHCB macro names.
* Start the SNP_INIT command id from 255 to give some gap for the legacy SEV.
* Sync the header with the latest 0.9 SNP spec.
Changes since v1:
* Add AP reset MSR protocol VMGEXIT NAE.
* Add Hypervisor features VMGEXIT NAE.
* Move the RMP table initialization and RMPUPDATE/PSMASH helper in arch/x86/kernel/sev.c.
* Add support to map/unmap SEV legacy command buffer to firmware state when SNP is active.
* Enhance PSP driver to provide helper to allocate/free memory used for the firmware context page.
* Add support to handle RMP fault for the kernel address.
* Add support to handle GUEST_REQUEST NAE event for attestation.
* Rename RMP table lookup helper.
* Drop typedef from rmpentry struct definition.
* Drop SNP static key and use cpu_feature_enabled() to check whether SEV-SNP is active.
* Multiple cleanup/fixes to address Boris review feedback.
Brijesh Singh (37):
KVM: SVM: Provide the Hypervisor Feature support VMGEXIT x86/cpufeatures: Add SEV-SNP CPU feature
x86/sev: Add the host SEV-SNP initialization support x86/sev: Add RMP entry lookup helpers
x86/sev: Add helper functions for RMPUPDATE and PSMASH instruction x86/sev: Split the physmap when adding the page in RMP table x86/traps: Define RMP violation #PF error code
x86/fault: Add support to dump RMP entry on fault x86/fault: Add support to handle the RMP fault for user address crypto:ccp: Define the SEV-SNP commands
crypto: ccp: Add support to initialize the AMD-SP for SEV-SNP
crypto: ccp: Shutdown SNP firmware on kexec
crypto:ccp: Provide APIs to issue SEV-SNP commands
crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
crypto: ccp: Handle the legacy SEV command when SNP is enabled
crypto: ccp: Add the SNP_PLATFORM_STATUS command
crypto: ccp: Add the SNP_{SET,GET}_EXT_CONFIG command
crypto: ccp: provide APIs to query extended attestation report
KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
KVM: SVM: Add initial SEV-SNP support
KVM: SVM: Add KVM_SNP_INIT command
KVM: SVM: Add KVM_SEV_SNP_LAUNCH_START command
KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command
KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
KVM: X86: Add kvm_x86_ops to get the max page level for the TDP
KVM: X86: Introduce kvm_mmu_map_tdp_page() for use by SEV
KVM: X86: Introduce kvm_mmu_get_tdp_walk() for SEV-SNP use
KVM: X86: Define new RMP check related #NPF error bits
KVM: X86: update page-fault trace to log the 64-bit error code
KVM: SVM: Add support to handle GHCB GPA register VMGEXIT
KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
KVM: SVM: Add support to handle Page State Change VMGEXIT
KVM: Add arch hooks to track the host write to guest memory
KVM: X86: Export the kvm_zap_gfn_range() for the SNP use
KVM: SVM: Add support to handle the RMP nested page fault
KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event
Tom Lendacky (3):
KVM: SVM: Add support to handle AP reset MSR protocol
KVM: SVM: Use a VMSA physical address variable for populating VMCB
KVM: SVM: Support SEV-SNP AP Creation NAE event
Documentation/virt/coco/sevguest.rst | 55 + .../virt/kvm/amd-memory-encryption.rst | 91 ++ arch/x86/include/asm/cpufeatures.h | 1 + arch/x86/include/asm/disabled-features.h | 8 +- arch/x86/include/asm/kvm_host.h | 24 + arch/x86/include/asm/msr-index.h | 6 + arch/x86/include/asm/sev-common.h | 18 + arch/x86/include/asm/sev.h | 4 +- arch/x86/include/asm/svm.h | 3 + arch/x86/include/asm/trap_pf.h | 18 +- arch/x86/include/uapi/asm/svm.h | 4 +- arch/x86/kernel/cpu/amd.c | 3 +- arch/x86/kernel/sev.c | 217 +++ arch/x86/kvm/lapic.c | 5 +- arch/x86/kvm/mmu.h | 5 +- arch/x86/kvm/mmu/mmu.c | 76 +- arch/x86/kvm/svm/sev.c | 1321 ++++++++++++++++- arch/x86/kvm/svm/svm.c | 37 +- arch/x86/kvm/svm/svm.h | 48 +- arch/x86/kvm/trace.h | 6 +- arch/x86/kvm/vmx/vmx.c | 8 + arch/x86/kvm/x86.c | 89 +- arch/x86/mm/fault.c | 149 ++ drivers/crypto/ccp/sev-dev.c | 863 ++++++++++- drivers/crypto/ccp/sev-dev.h | 18 + drivers/crypto/ccp/sp-pci.c | 12 + include/linux/kvm_host.h | 3 + include/linux/mm.h | 6 +- include/linux/psp-sev.h | 347 +++++ include/linux/sev.h | 76 + include/uapi/linux/kvm.h | 47 + include/uapi/linux/psp-sev.h | 60 + mm/memory.c | 13 + tools/arch/x86/include/asm/cpufeatures.h | 1 + virt/kvm/kvm_main.c | 21 +- 35 files changed, 3571 insertions(+), 92 deletions(-) create mode 100644 include/linux/sev.h
Signature · 1 line
2.17.1
RFC PATCH v4 1/40 KVM: SVM: Add support to handle AP reset MSR protocol
From: Tom Lendacky <[email protected]>
Add support for AP Reset Hold being invoked using the GHCB MSR protocol, available in version 2 of the GHCB specification.
--- arch/x86/include/asm/sev-common.h | 6 ++++ arch/x86/kvm/svm/sev.c | 56 ++++++++++++++++++++++++++----- arch/x86/kvm/svm/svm.h | 1 + 3 files changed, 55 insertions(+), 8 deletions(-)
arch/x86/include/asm/sev-common.h +6 -0
@@ -45,6 +45,12 @@ (((unsigned long)reg & GHCB_MSR_CPUID_REG_MASK) << GHCB_MSR_CPUID_REG_POS) | \ (((unsigned long)fn) << GHCB_MSR_CPUID_FUNC_POS)) +/* AP Reset Hold */ +#define GHCB_MSR_AP_RESET_HOLD_REQ 0x006 +#define GHCB_MSR_AP_RESET_HOLD_RESP 0x007 +#define GHCB_MSR_AP_RESET_HOLD_RESULT_POS 12 +#define GHCB_MSR_AP_RESET_HOLD_RESULT_MASK GENMASK_ULL(51, 0) +/* GHCB GPA Register */ #define GHCB_MSR_GPA_REG_REQ 0x012#define GHCB_MSR_GPA_REG_VALUE_POS 12
arch/x86/kvm/svm/sev.c +48 -8
85 lines not on this page · raw message
arch/x86/kvm/svm/svm.h +1 -0
@@ -174,6 +174,7 @@ struct vcpu_svm {struct ghcb *ghcb;struct kvm_host_map ghcb_map;bool received_first_sipi; +unsigned int ap_reset_hold_type;/* SEV-ES scratch area support */ void *ghcb_sa;
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 01/40] KVM: SVM: Add support to handle AP reset MSR protocol
Quoted 4 lines · Brijesh Singh
From: Tom Lendacky <[email protected]>
Add support for AP Reset Hold being invoked using the GHCB MSR protocol, available in version 2 of the GHCB specification.
Please provide a brief overview of the protocol, and why it's needed. I assume it's to allow AP wakeup without a shared GHCB?
Quoted 3 lines
Signed-off-by Tom Lendacky <[email protected]>Signed-off-by Brijesh Singh <[email protected]>---
...
Quoted 14 lines
static u8
sev_enc_bit;
staticDECLARE_RWSEM(sev_deactivate_lock);
staticDEFINE_MUTEX(sev_bitmap_lock);arch/x86/kvm/svm/sev.c +3
-0@@ -2199,6 +2203,9 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)void sev_es_unmap_ghcb (struct vcpu_svm *svm) { +/* Clear any indication that the vCPU is in a type of AP Reset Hold */ + svm->ap_reset_hold_type =AP_RESET_HOLD_NONE ; +if (!svm->ghcb)return ;
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2416
Quoted 6 lines
arch/x86/kvm/svm/sev.c +3
-0@@ -2404,6 +2411,22 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_AP_RESET_HOLD_REQ : + svm->ap_reset_hold_type =AP_RESET_HOLD_MSR_PROTO ; + ret =kvm_emulate_ap_reset_hold (&svm->vcpu);
The hold type feels like it should be a param to kvm_emulate_ap_reset_hold().
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2428
Quoted 12 lines
arch/x86/kvm/svm/sev.c +12
-0+ +/* +* Preset the result to a non-SIPI return and then only set +* the result to non-zero when delivering a SIPI. +*/ +set_ghcb_msr_bits (svm,0 , +GHCB_MSR_AP_RESET_HOLD_RESULT_MASK , +GHCB_MSR_AP_RESET_HOLD_RESULT_POS ); + +set_ghcb_msr_bits (svm,GHCB_MSR_AP_RESET_HOLD_RESP , +GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS );
It looks like all uses set an arbitrary value and then the response. I think folding the response into the helper would improve both readability and robustness. I also suspect the helper needs to do WRITE_ONCE() to guarantee the guest sees what it's supposed to see, though memory ordering is not my strong suit.
Might even be able to squeeze in a build-time assertion.
Also, do the guest-provided contents actually need to be preserved? That seems somewhat odd.
E.g. can it be
static void set_ghcb_msr_response(struct vcpu_svm *svm, u64 response, u64 value,
u64 mask, unsigned int pos)
{
u64 val = (response << GHCB_MSR_INFO_POS) | (val << pos);
WRITE_ONCE(svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
}and
set_ghcb_msr_response(svm, GHCB_MSR_AP_RESET_HOLD_RESP, GHCB_MSR_AP_RESET_HOLD_RESULT_MASK, GHCB_MSR_AP_RESET_HOLD_RESULT_POS);
Quoted 55 lines
arch/x86/kvm/svm/sev.c +26
-8+break ;case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;@@ -2491,6 +2514,7 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu) ret =svm_invoke_exit_handler (vcpu,SVM_EXIT_IRET );break ;case SVM_VMGEXIT_AP_HLT_LOOP : + svm->ap_reset_hold_type =AP_RESET_HOLD_NAE_EVENT ; ret =kvm_emulate_ap_reset_hold (vcpu);break ;case SVM_VMGEXIT_AP_JUMP_TABLE : {@@ -2628,13 +2652,29 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)return ; } -/* -* Subsequent SIPI: Return from an AP Reset Hold VMGEXIT, where -* the guest will set the CS and RIP. Set SW_EXIT_INFO_2 to a -* non-zero value. -*/ -if (!svm->ghcb) -return ; +/* Subsequent SIPI */ +switch (svm->ap_reset_hold_type) { +case AP_RESET_HOLD_NAE_EVENT : +/* +* Return from an AP Reset Hold VMGEXIT, where the guest will +* set the CS and RIP. Set SW_EXIT_INFO_2 to a non-zero value. +*/ +ghcb_set_sw_exit_info_2 (svm->ghcb,1 ); +break ; +case AP_RESET_HOLD_MSR_PROTO : +/* +* Return from an AP Reset Hold VMGEXIT, where the guest will +* set the CS and RIP. Set GHCB data field to a non-zero value. +*/ +set_ghcb_msr_bits (svm,1 , +GHCB_MSR_AP_RESET_HOLD_RESULT_MASK , +GHCB_MSR_AP_RESET_HOLD_RESULT_POS ); -ghcb_set_sw_exit_info_2 (svm->ghcb,1 ); +set_ghcb_msr_bits (svm,GHCB_MSR_AP_RESET_HOLD_RESP , +GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS ); +break ; +default : +break ; + } }arch/x86/kvm/svm/svm.h +0
-0
arch/x86/kvm/svm/svm.h struct vcpu_svm { · line 177
Quoted 4 lines
arch/x86/kvm/svm/svm.h +1
-0@@ -174,6 +174,7 @@ struct vcpu_svm {struct ghcb *ghcb;struct kvm_host_map ghcb_map;bool received_first_sipi; +unsigned int ap_reset_hold_type;
Can't this be a u8?
Quoted 6 lines
arch/x86/kvm/svm/svm.h +0
-0/* SEV-ES scratch area support */ void *ghcb_sa;Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 01/40] KVM: SVM: Add support to handle AP reset MSR protocol
Quoted 8 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh
From: Tom Lendacky <[email protected]>
Add support for AP Reset Hold being invoked using the GHCB MSR protocol, available in version 2 of the GHCB specification.
Please provide a brief overview of the protocol, and why it's needed. I assume it's to allow AP wakeup without a shared GHCB?
Yes, this is needed for SEV-ES kexec support to park APs without the need for memory that will be owned by the new kernel when APs are woken up.
You can have a look into my SEV-ES kexec/kdump patch-set for details:
https://lore.kernel.org/lkml/[email protected]/
I also sent this patch separatly earlier this week to enable GHCB protocol version 2 support in KVM.
Regards,
Joerg
Tom Lendacky
maintainerRe: [PATCH Part2 RFC v4 01/40] KVM: SVM: Add support to handle AP reset MSR protocol
In reply to Sean ChristophersonQuoted 8 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh
From: Tom Lendacky <[email protected]>
Add support for AP Reset Hold being invoked using the GHCB MSR protocol, available in version 2 of the GHCB specification.
Please provide a brief overview of the protocol, and why it's needed. I assume it's to allow AP wakeup without a shared GHCB?
Right, mainly the ability to be able to issue an AP reset hold from a mode that would not be able to access the GHCB as a shared page, e.g. 32-bit mode without paging enabled where reads/writes are always encrypted for an SEV guest.
Quoted 20 lines
Quoted 4 lines
Signed-off-by Tom Lendacky <[email protected]>Signed-off-by Brijesh Singh <[email protected]>---
...
Quoted 13 lines
static u8
sev_enc_bit;
staticDECLARE_RWSEM(sev_deactivate_lock);
staticDEFINE_MUTEX(sev_bitmap_lock);arch/x86/kvm/svm/sev.c +3
-0@@ -2199,6 +2203,9 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)void sev_es_unmap_ghcb (struct vcpu_svm *svm) { +/* Clear any indication that the vCPU is in a type of AP Reset Hold */ + svm->ap_reset_hold_type =AP_RESET_HOLD_NONE ; +if (!svm->ghcb)return ;
Quoted 9 lines
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2416
Quoted 7 lines
arch/x86/kvm/svm/sev.c +3
-0@@ -2404,6 +2411,22 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_AP_RESET_HOLD_REQ : + svm->ap_reset_hold_type =AP_RESET_HOLD_MSR_PROTO ; + ret =kvm_emulate_ap_reset_hold (&svm->vcpu);The hold type feels like it should be a param to
kvm_emulate_ap_reset_hold().
I suppose it could be, but then the type would have to be tracked in the kvm_vcpu_arch struct instead of the vcpu_svm struct, so I opted for the latter. Maybe a helper function, sev_ap_reset_hold(), that sets the type and then calls kvm_emulate_ap_reset_hold(), but I'm not seeing a big need for it.
Quoted 16 lines
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2428
Quoted 13 lines
arch/x86/kvm/svm/sev.c +12
-0+ +/* +* Preset the result to a non-SIPI return and then only set +* the result to non-zero when delivering a SIPI. +*/ +set_ghcb_msr_bits (svm,0 , +GHCB_MSR_AP_RESET_HOLD_RESULT_MASK , +GHCB_MSR_AP_RESET_HOLD_RESULT_POS ); + +set_ghcb_msr_bits (svm,GHCB_MSR_AP_RESET_HOLD_RESP , +GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS );It looks like all uses set an arbitrary value and then the response. I think folding the response into the helper would improve both readability and robustness.
Joerg pulled this patch out and submitted it as part of a small, three patch series, so it might be best to address this in general in the SEV-SNP patches or as a follow-on series specifically for this re-work.
Quoted 2 lines
I also suspect the helper needs to do
WRITE_ONCE()to guarantee the guest sees what it's supposed to see, though memory ordering is not my strong suit.
This is writing to the VMCB that is then used to set the value of the guest MSR. I don't see anything done in general for writes to the VMCB, so I wouldn't think this should be any different.
Quoted 5 lines
Might even be able to squeeze in a build-time assertion.
Also, do the guest-provided contents actually need to be preserved? That seems somewhat odd.
Hmmm... not sure I see where the guest contents are being preserved.
Quoted 70 lines
E.g. can it be
static void set_ghcb_msr_response(struct
vcpu_svm*svm, u64 response, u64 value,
u64 mask, unsigned int pos){ u64 val = (response << GHCB_MSR_INFO_POS) | (val << pos); WRITE_ONCE(svm->vmcb->control.ghcb_gpa |= (value & mask) << pos; }and
set_ghcb_msr_response(svm, GHCB_MSR_AP_RESET_HOLD_RESP, GHCB_MSR_AP_RESET_HOLD_RESULT_MASK, GHCB_MSR_AP_RESET_HOLD_RESULT_POS);Quoted 53 lines
arch/x86/kvm/svm/sev.c +26
-8+break ;case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;@@ -2491,6 +2514,7 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu) ret =svm_invoke_exit_handler (vcpu,SVM_EXIT_IRET );break ;case SVM_VMGEXIT_AP_HLT_LOOP : + svm->ap_reset_hold_type =AP_RESET_HOLD_NAE_EVENT ; ret =kvm_emulate_ap_reset_hold (vcpu);break ;case SVM_VMGEXIT_AP_JUMP_TABLE : {@@ -2628,13 +2652,29 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)return ; } -/* -* Subsequent SIPI: Return from an AP Reset Hold VMGEXIT, where -* the guest will set the CS and RIP. Set SW_EXIT_INFO_2 to a -* non-zero value. -*/ -if (!svm->ghcb) -return ; +/* Subsequent SIPI */ +switch (svm->ap_reset_hold_type) { +case AP_RESET_HOLD_NAE_EVENT : +/* +* Return from an AP Reset Hold VMGEXIT, where the guest will +* set the CS and RIP. Set SW_EXIT_INFO_2 to a non-zero value. +*/ +ghcb_set_sw_exit_info_2 (svm->ghcb,1 ); +break ; +case AP_RESET_HOLD_MSR_PROTO : +/* +* Return from an AP Reset Hold VMGEXIT, where the guest will +* set the CS and RIP. Set GHCB data field to a non-zero value. +*/ +set_ghcb_msr_bits (svm,1 , +GHCB_MSR_AP_RESET_HOLD_RESULT_MASK , +GHCB_MSR_AP_RESET_HOLD_RESULT_POS ); -ghcb_set_sw_exit_info_2 (svm->ghcb,1 ); +set_ghcb_msr_bits (svm,GHCB_MSR_AP_RESET_HOLD_RESP , +GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS ); +break ; +default : +break ; + } }arch/x86/kvm/svm/svm.h +0
-1--- a/arch/x86/kvm/svm/svm.h
Quoted 8 lines
arch/x86/kvm/svm/svm.h struct vcpu_svm { · line 177
Quoted 6 lines
+++
b/arch/x86/kvm/svm/svm.harch/x86/kvm/svm/svm.h +1
-0@@ -174,6 +174,7 @@ struct vcpu_svm {struct ghcb *ghcb;struct kvm_host_map ghcb_map;bool received_first_sipi; +unsigned int ap_reset_hold_type;Can't this be a u8?
Yes, it could be, maybe even an enum and let the compiler decide on the size.
Thanks,
Tom
Quoted 7 lines
Quoted 7 lines
arch/x86/kvm/svm/svm.h +0
-0/* SEV-ES scratch area support */ void *ghcb_sa;Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 01/40] KVM: SVM: Add support to handle AP reset MSR protocol
Quoted 7 lines · Tom Lendacky
Quoted 5 lines · Sean Christopherson
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2416
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+case GHCB_MSR_AP_RESET_HOLD_REQ : + svm->ap_reset_hold_type =AP_RESET_HOLD_MSR_PROTO ; + ret =kvm_emulate_ap_reset_hold (&svm->vcpu);The hold type feels like it should be a param to
kvm_emulate_ap_reset_hold().
Quoted 5 lines
I suppose it could be, but then the type would have to be tracked in the
kvm_vcpu_archstruct instead of thevcpu_svmstruct, so I opted for the latter. Maybe a helper function,sev_ap_reset_hold(), that sets the type and then callskvm_emulate_ap_reset_hold(), but I'm not seeing a big need for it.
Huh. Why is kvm_emulate_ap_reset_hold() in x86.c? That entire concept is very much SEV specific. And if anyone argues its not SEV specific, then the hold type should also be considered generic, i.e. put in kvm_vcpu_arch.
Quoted 20 lines
Quoted 7 lines
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+ +/* +* Preset the result to a non-SIPI return and then only set +* the result to non-zero when delivering a SIPI. +*/ + set_ghcb_msr_bits(svm, 0, + GHCB_MSR_AP_RESET_HOLD_RESULT_MASK,Quoted 8 lines
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2428
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+ GHCB_MSR_AP_RESET_HOLD_RESULT_POS); + +set_ghcb_msr_bits (svm,GHCB_MSR_AP_RESET_HOLD_RESP , +GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS );It looks like all uses set an arbitrary value and then the response. I think folding the response into the helper would improve both readability and robustness.
Joerg pulled this patch out and submitted it as part of a small, three patch series, so it might be best to address this in general in the SEV-SNP patches or as a follow-on series specifically for this re-work.
Quoted 6 lines
Quoted 2 lines
I also suspect the helper needs to do
WRITE_ONCE()to guarantee the guest sees what it's supposed to see, though memory ordering is not my strong suit.This is writing to the VMCB that is then used to set the value of the guest MSR. I don't see anything done in general for writes to the VMCB, so I wouldn't think this should be any different.
Ooooh, right. I was thinking this was writing memory that's shared with the guest, but this is KVM's copy of the GCHB MSR, not the GHCB itself. Thanks!
Quoted 6 lines
Quoted 4 lines
Might even be able to squeeze in a build-time assertion.
Also, do the guest-provided contents actually need to be preserved? That seems somewhat odd.
Hmmm... not sure I see where the guest contents are being preserved.
The fact that set_ghcb_msr_bits() is a RMW flow implies _something_ is being preserved. And unless KVM explicitly zeros/initializes control.ghcb_gpa, the value being preserved is the value last written by the guest. E.g. for CPUID emulation, KVM reads the guest-requested function and register from ghcb_gpa, then writes back the result. But set_ghcb_msr_bits() is a RMW on a subset of bits, and thus it's preserving the guest's value for the bits not being written.
Unless there is an explicit need to preserve the guest value, the whole RMW thing is unnecessary and confusing.
case GHCB_MSR_CPUID_REQ: {
u64 cpuid_fn, cpuid_reg, cpuid_value;
cpuid_fn = get_ghcb_msr_bits(svm,
GHCB_MSR_CPUID_FUNC_MASK,
GHCB_MSR_CPUID_FUNC_POS);
/* Initialize the registers needed by the CPUID intercept */
vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
vcpu->arch.regs[VCPU_REGS_RCX] = 0;
ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID);
if (!ret) {
ret = -EINVAL;
break;
}
cpuid_reg = get_ghcb_msr_bits(svm,
GHCB_MSR_CPUID_REG_MASK,
GHCB_MSR_CPUID_REG_POS);
if (cpuid_reg == 0)
cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
else if (cpuid_reg == 1)
cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
else if (cpuid_reg == 2)
cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
else
cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
set_ghcb_msr_bits(svm, cpuid_value,
GHCB_MSR_CPUID_VALUE_MASK,
GHCB_MSR_CPUID_VALUE_POS);
set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
GHCB_MSR_INFO_MASK,
GHCB_MSR_INFO_POS);
break;
}Tom Lendacky
maintainerRe: [PATCH Part2 RFC v4 01/40] KVM: SVM: Add support to handle AP reset MSR protocol
Quoted 14 lines · Sean Christopherson
Quoted 7 lines · Tom Lendacky
Quoted 5 lines · Sean Christopherson
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2416
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+case GHCB_MSR_AP_RESET_HOLD_REQ : + svm->ap_reset_hold_type =AP_RESET_HOLD_MSR_PROTO ; + ret =kvm_emulate_ap_reset_hold (&svm->vcpu);The hold type feels like it should be a param to
kvm_emulate_ap_reset_hold().Quoted 5 lines
I suppose it could be, but then the type would have to be tracked in the
kvm_vcpu_archstruct instead of thevcpu_svmstruct, so I opted for the latter. Maybe a helper function,sev_ap_reset_hold(), that sets the type and then callskvm_emulate_ap_reset_hold(), but I'm not seeing a big need for it.
Quoted 3 lines
Huh. Why is
kvm_emulate_ap_reset_hold()inx86.c? That entire concept is very much SEV specific. And if anyone argues its not SEV specific, then the hold type should also be considered generic, i.e. put inkvm_vcpu_arch.
That was based on review comments where it was desired that the halt be identified as specifically from the AP reset hold vs a normal halt. So kvm_emulate_ap_reset_hold() was created using KVM_MP_STATE_AP_RESET_HOLD and KVM_EXIT_AP_RESET_HOLD instead of exporting a version of kvm_vcpu_halt() with the state and reason as arguments.
If there's no objection, then I don't have any issues with moving the hold type to kvm_vcpu_arch and adding a param to kvm_emulate_ap_reset_hold().
Quoted 36 lines
Quoted 21 lines
Quoted 16 lines
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2428
Quoted 13 lines
arch/x86/kvm/svm/sev.c +12
-0+ +/* +* Preset the result to a non-SIPI return and then only set +* the result to non-zero when delivering a SIPI. +*/ +set_ghcb_msr_bits (svm,0 , +GHCB_MSR_AP_RESET_HOLD_RESULT_MASK , +GHCB_MSR_AP_RESET_HOLD_RESULT_POS ); + +set_ghcb_msr_bits (svm,GHCB_MSR_AP_RESET_HOLD_RESP , +GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS );It looks like all uses set an arbitrary value and then the response. I think folding the response into the helper would improve both readability and robustness.
Joerg pulled this patch out and submitted it as part of a small, three patch series, so it might be best to address this in general in the SEV-SNP patches or as a follow-on series specifically for this re-work.
Quoted 6 lines
Quoted 2 lines
I also suspect the helper needs to do
WRITE_ONCE()to guarantee the guest sees what it's supposed to see, though memory ordering is not my strong suit.This is writing to the VMCB that is then used to set the value of the guest MSR. I don't see anything done in general for writes to the VMCB, so I wouldn't think this should be any different.
Ooooh, right. I was thinking this was writing memory that's shared with the guest, but this is KVM's copy of the GCHB MSR, not the GHCB itself. Thanks!
Quoted 5 lines
Quoted 4 lines
Might even be able to squeeze in a build-time assertion.
Also, do the guest-provided contents actually need to be preserved? That seems somewhat odd.
Quoted 8 lines
Quoted 1 line
Hmmm... not sure I see where the guest contents are being preserved.
The fact that
set_ghcb_msr_bits()is a RMW flow implies _something_ is being preserved. And unless KVM explicitly zeros/initializes control.ghcb_gpa, the value being preserved is the value last written by the guest. E.g. for CPUID emulation, KVM reads the guest-requested function and register fromghcb_gpa, then writes back the result. Butset_ghcb_msr_bits()is a RMW on a subset of bits, and thus it's preserving the guest's value for the bits not being written.
Yes, set_ghcb_msr_bits() is a RMW helper, but the intent was to set every bit. So for CPUID, I missed setting the reserved area to 0. There wouldn't be an issue initializing the whole field to zero once everything has been pulled out for the MSR protocol function being invoked.
Quoted 3 lines
Unless there is an explicit need to preserve the guest value, the whole RMW thing is unnecessary and confusing.
I guess it depends on who's reading the code. I don't find it confusing, which is probably why I implemented it that way :) But, yes, it certainly can be changed to create the result and then have a single function that combines the result and response code and sets the ghcb_gpa, which would have eliminated the missed setting of the reserved area.
Thanks,
Tom
RFC PATCH v4 2/40 KVM: SVM: Provide the Hypervisor Feature support VMGEXIT
In reply to Brijesh SinghVersion 2 of the GHCB specification introduced advertisement of features that are supported by the Hypervisor.
Now that KVM supports version 2 of the GHCB specification, bump the maximum supported protocol version.
--- arch/x86/include/uapi/asm/svm.h | 4 ++-- arch/x86/kvm/svm/sev.c | 14 ++++++++++++++ arch/x86/kvm/svm/svm.h | 3 ++- 3 files changed, 18 insertions(+), 3 deletions(-)
arch/x86/include/uapi/asm/svm.h +2 -2
@@ -115,7 +115,7 @@#define SVM_VMGEXIT_AP_CREATE_ON_INIT 0#define SVM_VMGEXIT_AP_CREATE 1#define SVM_VMGEXIT_AP_DESTROY 2 -#define SVM_VMGEXIT_HYPERVISOR_FEATURES 0x8000fffd +#define SVM_VMGEXIT_HV_FT 0x8000fffd#define SVM_VMGEXIT_UNSUPPORTED_EVENT 0x8000ffff#define SVM_EXIT_ERR -1
@@ -227,7 +227,7 @@ { SVM_VMGEXIT_EXT_GUEST_REQUEST, "vmgexit_ext_guest_request" }, \ { SVM_VMGEXIT_PSC, "vmgexit_page_state_change" }, \ { SVM_VMGEXIT_AP_CREATION, "vmgexit_ap_creation" }, \ - { SVM_VMGEXIT_HYPERVISOR_FEATURES, "vmgexit_hypervisor_feature" }, \ + { SVM_VMGEXIT_HV_FT, "vmgexit_hypervisor_feature" }, \ { SVM_EXIT_ERR, "invalid_guest_state" }
arch/x86/kvm/svm/sev.c +14 -0
@@ -2173,6 +2173,7 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)case SVM_VMGEXIT_AP_HLT_LOOP :case SVM_VMGEXIT_AP_JUMP_TABLE :case SVM_VMGEXIT_UNSUPPORTED_EVENT : +case SVM_VMGEXIT_HV_FT :break ;default : goto vmgexit_err;
@@ -2427,6 +2428,13 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)GHCB_MSR_INFO_MASK , GHCB_MSR_INFO_POS);break ; +case GHCB_MSR_HV_FT_REQ : { +set_ghcb_msr_bits (svm,GHCB_HV_FT_SUPPORTED , +GHCB_MSR_HV_FT_MASK ,GHCB_MSR_HV_FT_POS ); +set_ghcb_msr_bits (svm,GHCB_MSR_HV_FT_RESP , +GHCB_MSR_INFO_MASK ,GHCB_MSR_INFO_POS ); +break ; + }case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;
@@ -2542,6 +2550,12 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu) ret =1 ;break ; } +case SVM_VMGEXIT_HV_FT : { +ghcb_set_sw_exit_info_2 (ghcb,GHCB_HV_FT_SUPPORTED ); + + ret =1 ; +break ; + }case SVM_VMGEXIT_UNSUPPORTED_EVENT : vcpu_unimpl(vcpu, "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
arch/x86/kvm/svm/svm.h +2 -1
@@ -527,9 +527,10 @@ void svm_vcpu_unblocking(struct kvm_vcpu *vcpu);/* sev.c */ -#define GHCB_VERSION_MAX 1ULL +#define GHCB_VERSION_MAX 2ULL#define GHCB_VERSION_MIN 1ULL +#define GHCB_HV_FT_SUPPORTED 0extern unsigned int max_sev_asid;
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 02/40] KVM: SVM: Provide the Hypervisor Feature support VMGEXIT
Quoted 5 lines · Brijesh Singh
Version 2 of the GHCB specification introduced advertisement of features that are supported by the Hypervisor.
Now that KVM supports version 2 of the GHCB specification, bump the maximum supported protocol version.
Heh, the changelog doesn't actually state that it's adding support for said advertisement of features. It took me a few seconds to figure out what the patch was doing, even though it's quite trivial in the end.
Quoted 12 lines
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/uapi/asm/svm.h | 4 ++-- arch/x86/kvm/svm/sev.c | 14 ++++++++++++++ arch/x86/kvm/svm/svm.h | 3 ++- 3 files changed, 18 insertions(+), 3 deletions(-)arch/x86/include/uapi/asm/svm.h +0
-0
arch/x86/include/uapi/asm/svm.h line 118
Quoted 5 lines
arch/x86/include/uapi/asm/svm.h +1
-1@@ -115,7 +115,7 @@#define SVM_VMGEXIT_AP_CREATE_ON_INIT 0#define SVM_VMGEXIT_AP_CREATE 1#define SVM_VMGEXIT_AP_DESTROY 2 -#define SVM_VMGEXIT_HYPERVISOR_FEATURES 0x8000fffd +#define SVM_VMGEXIT_HV_FT 0x8000fffd
This is fixing up commit 3 from Part1, though I think it can and should be omitted from that patch entirely since it's not relevant to the guest, only to KVM.
And FWIW, I like the verbose name, though it looks like Boris requested the shorter names for the guest. Can we keep the verbose form for KVM-only VMEGXIT name? Hyper-V has mostly laid claim to "HV", and feature is not the first thing that comes to mind for "FT".
Quoted 1 line
arch/x86/include/uapi/asm/svm.h +0
-0#define SVM_VMGEXIT_UNSUPPORTED_EVENT 0x8000ffff
Re: [PATCH Part2 RFC v4 02/40] KVM: SVM: Provide the Hypervisor Feature support VMGEXIT
Quoted 5 lines · Sean Christopherson
Quoted 1 line
+#define
SVM_VMGEXIT_HV_FT0x8000fffdThis is fixing up commit 3 from Part1, though I think it can and should be omitted from that patch entirely since it's not relevant to the guest, only to KVM.
Yes, one of the thing which I was struggling header files between the kvm/queue and tip/master was not in sync. I had to do some cherry-picks to make my part2 still build. I hope this will get addressed in next rebase.
Quoted 6 lines
And FWIW, I like the verbose name, though it looks like Boris requested the shorter names for the guest. Can we keep the verbose form for KVM-only VMEGXIT name? Hyper-V has mostly laid claim to "HV", and feature is not the first thing that comes to mind for "FT".
For the uapi/asm/svm.h, I can stick with the verbose name.
thanks
RFC PATCH v4 3/40 x86/cpufeatures: Add SEV-SNP CPU feature
In reply to Brijesh SinghAdd CPU feature detection for Secure Encrypted Virtualization with Secure Nested Paging. This feature adds a strong memory integrity protection to help prevent malicious hypervisor-based attacks like data replay, memory re-mapping, and more.
--- arch/x86/include/asm/cpufeatures.h | 1 + arch/x86/kernel/cpu/amd.c | 3 ++- tools/arch/x86/include/asm/cpufeatures.h | 1 + 3 files changed, 4 insertions(+), 1 deletion(-)
arch/x86/include/asm/cpufeatures.h +1 -0
@@ -397,6 +397,7 @@#define X86_FEATURE_SEV (19*32+ 1)/* AMD Secure Encrypted Virtualization */ #define X86_FEATURE_VM_PAGE_FLUSH (19*32+ 2)/* "" VM Page Flush MSR is supported */ #define X86_FEATURE_SEV_ES (19*32+ 3)/* AMD Secure Encrypted Virtualization - Encrypted State */ +#define X86_FEATURE_SEV_SNP (19*32+4)/* AMD Secure Encrypted Virtualization - Secure Nested Paging */ #define X86_FEATURE_SME_COHERENT (19*32+10)/* "" AMD hardware-enforced cache coherency */ /*
arch/x86/kernel/cpu/amd.c +2 -1
@@ -586,7 +586,7 @@ static void early_detect_mem_encrypt(struct cpuinfo_x86 *c)* If BIOS has not enabled SME then don't advertise the * SME feature (set in scattered.c). * For SEV: If BIOS has not enabled SEV then don't advertise the -* SEV and SEV_ES feature (set in scattered.c). +* SEV, SEV_ES and SEV_SNP feature. * * In all cases, since support for SME and SEV requires long mode, * don't advertise the feature under CONFIG_X86_32.
@@ -618,6 +618,7 @@ static void early_detect_mem_encrypt(struct cpuinfo_x86 *c) clear_sev:setup_clear_cpu_cap (X86_FEATURE_SEV );setup_clear_cpu_cap (X86_FEATURE_SEV_ES ); +setup_clear_cpu_cap (X86_FEATURE_SEV_SNP ); } }
tools/arch/x86/include/asm/cpufeatures.h +1 -0
@@ -390,6 +390,7 @@#define X86_FEATURE_SEV (19*32+ 1)/* AMD Secure Encrypted Virtualization */ #define X86_FEATURE_VM_PAGE_FLUSH (19*32+ 2)/* "" VM Page Flush MSR is supported */ #define X86_FEATURE_SEV_ES (19*32+ 3)/* AMD Secure Encrypted Virtualization - Encrypted State */ +#define X86_FEATURE_SEV_SNP (19*32+4)/* AMD Secure Encrypted Virtualization - Secure Nested Paging */ #define X86_FEATURE_SME_COHERENT (19*32+10)/* "" AMD hardware-enforced cache coherency */ /*
Signature · 1 line
2.17.1
RFC PATCH v4 4/40 x86/sev: Add the host SEV-SNP initialization support
In reply to Brijesh SinghThe memory integrity guarantees of SEV-SNP are enforced through a new structure called the Reverse Map Table (RMP). The RMP is a single data structure shared across the system that contains one entry for every 4K page of DRAM that may be used by SEV-SNP VMs. The goal of RMP is to track the owner of each page of memory. Pages of memory can be owned by the hypervisor, owned by a specific VM or owned by the AMD-SP. See APM2 section 15.36.3 for more detail on RMP.
The RMP table is used to enforce access control to memory. The table itself is not directly writable by the software. New CPU instructions (RMPUPDATE, PVALIDATE, RMPADJUST) are used to manipulate the RMP entries.
Based on the platform configuration, the BIOS reserves the memory used for the RMP table. The start and end address of the RMP table must be queried by reading the RMP_BASE and RMP_END MSRs. If the RMP_BASE and RMP_END are not set then disable the SEV-SNP feature.
The SEV-SNP feature is enabled only after the RMP table is successfully initialized.
--- arch/x86/include/asm/disabled-features.h | 8 +- arch/x86/include/asm/msr-index.h | 6 + arch/x86/kernel/sev.c | 143 +++++++++++++++++++++++ 3 files changed, 156 insertions(+), 1 deletion(-)
arch/x86/include/asm/disabled-features.h +7 -1
@@ -68,6 +68,12 @@# define DISABLE_SGX (1 << (X86_FEATURE_SGX & 31))#endif +#ifdef CONFIG_AMD_MEM_ENCRYPT +# define DISABLE_SEV_SNP 0 +#else +# define DISABLE_SEV_SNP (1 << (X86_FEATURE_SEV_SNP & 31)) +#endif +/* * Make sure to add features to the correct mask */
@@ -91,7 +97,7 @@ DISABLE_ENQCMD)#define DISABLED_MASK17 0#define DISABLED_MASK18 0 -#define DISABLED_MASK19 0 +#define DISABLED_MASK19 (DISABLE_SEV_SNP)#define DISABLED_MASK_CHECK BUILD_BUG_ON_ZERO(NCAPINTS != 20)#endif /* _ASM_X86_DISABLED_FEATURES_H */
arch/x86/include/asm/msr-index.h +6 -0
@@ -485,6 +485,8 @@#define MSR_AMD64_SEV_ENABLED BIT_ULL(MSR_AMD64_SEV_ENABLED_BIT)#define MSR_AMD64_SEV_ES_ENABLED BIT_ULL(MSR_AMD64_SEV_ES_ENABLED_BIT)#define MSR_AMD64_SEV_SNP_ENABLED BIT_ULL(MSR_AMD64_SEV_SNP_ENABLED_BIT) +#define MSR_AMD64_RMP_BASE 0xc0010132 +#define MSR_AMD64_RMP_END 0xc0010133#define MSR_AMD64_VIRT_SPEC_CTRL 0xc001011f
@@ -542,6 +544,10 @@#define MSR_AMD64_SYSCFG 0xc0010010#define MSR_AMD64_SYSCFG_MEM_ENCRYPT_BIT 23#define MSR_AMD64_SYSCFG_MEM_ENCRYPT BIT_ULL(MSR_AMD64_SYSCFG_MEM_ENCRYPT_BIT) +#define MSR_AMD64_SYSCFG_SNP_EN_BIT 24 +#define MSR_AMD64_SYSCFG_SNP_EN BIT_ULL(MSR_AMD64_SYSCFG_SNP_EN_BIT) +#define MSR_AMD64_SYSCFG_SNP_VMPL_EN_BIT 25 +#define MSR_AMD64_SYSCFG_SNP_VMPL_EN BIT_ULL(MSR_AMD64_SYSCFG_SNP_VMPL_EN_BIT)#define MSR_K8_INT_PENDING_MSG 0xc0010055/* C1E active bits in int pending message */ #define K8_INTP_C1E_ACTIVE_MASK 0x18000000
arch/x86/kernel/sev.c +143 -0
169 lines not on this page · raw message
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 04/40] x86/sev: Add the host SEV-SNP initialization support
Quoted 14 lines · Brijesh Singh
arch/x86/kernel/sev.c +2
-0@@ -24,6 +24,8 @@#include <linux/sev-guest.h> #include <linux/platform_device.h> #include <linux/io.h> +#include <linux/io.h> +#include <linux/iommu.h> #include <asm/cpu_entry_area.h> #include <asm/stacktrace.h>
arch/x86/kernel/sev.c line 51
Quoted 10 lines
arch/x86/kernel/sev.c +2
-0@@ -40,11 +42,14 @@#include <asm/efi.h> #include <asm/cpuid-indexed.h> #include <asm/setup.h> +#include <asm/iommu.h> #include "sev-internal.h" #define DR7_RESET_VALUE 0x400 +#define RMPTABLE_ENTRIES_OFFSET 0x4000
A comment and/or blurb in the changelog describing this magic number would be quite helpful. And maybe call out that this is for the bookkeeping, e.g.
#define RMPTABLE_CPU_BOOKKEEPING_SIZE 0x4000
Also, the APM doesn't actually state the exact location of the bookkeeping region, it only states that it's somewhere between RMP_BASE and RMP_END. This seems to imply that the bookkeeping region is always at RMP_BASE?
The region of memory between RMP_BASE and RMP_END contains a 16KB region used for processor bookkeeping followed by the RMP entries, which are each 16B in size. The size of the RMP determines the range of physical memory that the hypervisor can assign to SNP-active virtual machines at runtime. The RMP covers the system physical address space from address 0h to the address calculated by:
((RMP_END + 1 – RMP_BASE – 16KB) / 16B) x 4KB
Quoted 22 lines
arch/x86/kernel/sev.c +8
-0/* For early boot hypervisor communication in SEV-ES enabled guests */ static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);@@ -56,6 +61,9 @@ static struct ghcb __initdata *boot_ghcb;static u64 snp_secrets_phys; +static unsigned long rmptable_start__ro_after_init ; +static unsigned long rmptable_end__ro_after_init ; +/* #VC handler runtime per-CPU data */ struct sev_es_runtime_data {struct ghcb ghcb_page;@@ -2176,3 +2184,138 @@ static int __init add_snp_guest_request(void)return 0 ; }device_initcall (add_snp_guest_request); + +#undef pr_fmt +#define pr_fmt (fmt) "SEV-SNP: " fmt + +static int __snp_enable (unsigned int cpu)
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2201
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+{ +u64 val; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return 0 ; + +rdmsrl (MSR_AMD64_SYSCFG , val); + + val |=MSR_AMD64_SYSCFG_SNP_EN ; + val |=MSR_AMD64_SYSCFG_SNP_VMPL_EN ;
Is VMPL required? Do we plan on using VMPL out of the gate?
Quoted 9 lines
arch/x86/kernel/sev.c +9
-0+ +wrmsrl (MSR_AMD64_SYSCFG , val); + +return 0 ; +} + +static __init void snp_enable (void *arg) +{ +__snp_enable (smp_processor_id ());
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2220
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+} + +static bool get_rmptable_info (u64 *start,u64 *len) +{ +u64 calc_rmp_sz, rmp_sz, rmp_base, rmp_end, nr_pages; + +rdmsrl (MSR_AMD64_RMP_BASE , rmp_base); +rdmsrl (MSR_AMD64_RMP_END , rmp_end); + +if (!rmp_base || !rmp_end) {
Can BIOS put the RMP at PA=0?
Also, why is it a BIOS decision? AFAICT, the MSRs aren't locked until SNP_EN is set in SYSCFG, and that appears to be a kernel decision (ignoring kexec), i.e. nothing would prevent the kernel from configuring it's own RMP.
Quoted 9 lines
arch/x86/kernel/sev.c +9
-0+pr_info ("Memory for the RMP table has not been reserved by BIOS\n" ); +return false; + } + + rmp_sz = rmp_end - rmp_base +1 ; + +/* +* Calculate the amount the memory that must be reserved by the BIOS to +* address the full system RAM. The reserved memory should also cover the
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2239
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+* RMP table itself. +* +* See PPR section 2.1.5.2 for more information on memory requirement. +*/ + nr_pages =totalram_pages (); + calc_rmp_sz = (((rmp_sz >>PAGE_SHIFT ) + nr_pages) <<4 ) +RMPTABLE_ENTRIES_OFFSET ; + +if (calc_rmp_sz > rmp_sz) { +pr_info ("Memory reserved for the RMP table does not cover the full system " +"RAM (expected 0x%llx got 0x%llx)\n" , calc_rmp_sz, rmp_sz);
Is BIOS expected to provide exact coverage, e.g. should this be s/expected/need?
Should the kernel also sanity check other requirements, e.g. the 8kb alignment, or does the CPU enforce those things at WRMSR?
Quoted 22 lines
arch/x86/kernel/sev.c +22
-0+return false; + } + + *start = rmp_base; + *len = rmp_sz; + +pr_info ("RMP table physical address 0x%016llx - 0x%016llx\n" , rmp_base, rmp_end); + +return true; +} + +static __init int __snp_rmptable_init (void ) +{ +u64 rmp_base, sz; +void *start; +u64 val; + +if (!get_rmptable_info (&rmp_base, &sz)) +return 1 ; + + start =memremap (rmp_base, sz,MEMREMAP_WB ); +if (!start) {
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2271
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+pr_err ("Failed to map RMP table 0x%llx+0x%llx\n" , rmp_base, sz); +return 1 ; + } + +/* +* Check if SEV-SNP is already enabled, this can happen if we are coming from +* kexec boot. +*/ +rdmsrl (MSR_AMD64_SYSCFG , val); +if (val &MSR_AMD64_SYSCFG_SNP_EN )
Hmm, it kinda feels like there should be a sanity check for the case where SNP is already enabled but get_rmptable_info() fails, e.g. due to insufficient RMP size.
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2284
Quoted 13 lines
arch/x86/kernel/sev.c +13
-0+ goto skip_enable; + +/* Initialize the RMP table to zero */ +memset (start,0 , sz); + +/* Flush the caches to ensure that data is written before SNP is enabled. */ +wbinvd_on_all_cpus (); + +/* Enable SNP on all CPUs. */ +on_each_cpu (snp_enable,NULL ,1 ); + +skip_enable: + rmptable_start = (unsigned long )start;
Mostly out of curiosity, why store start/end as unsigned longs? This is all 64-bit only so it doesn't actually affect the code generation, but it feels odd to store things that absolutely have to be 64-bit values as unsigned long.
Similar question for why asm/sev-common.h cases to unsigned long instead of u64. E.g. the below in particular looks wrong because we're shifting an unsigned long b y32 bits, i.e. the value _must_ be a 64-bit value, why obfuscate that?
#define GHCB_CPUID_REQ(fn, reg) \ (GHCB_MSR_CPUID_REQ | \ (((unsigned long)reg & GHCB_MSR_CPUID_REG_MASK) << GHCB_MSR_CPUID_REG_POS) | \ (((unsigned long)fn) << GHCB_MSR_CPUID_FUNC_POS))
Quoted 5 lines
arch/x86/kernel/sev.c +5
-0+ rmptable_end = rmptable_start + sz; + +return 0 ; +} +
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2299
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+static int __init snp_rmptable_init (void ) +{ +if (!boot_cpu_has (X86_FEATURE_SEV_SNP )) +return 0 ; + +/* +* The SEV-SNP support requires that IOMMU must be enabled, and is not +* configured in the passthrough mode. +*/ +if (no_iommu ||iommu_default_passthrough ()) {
Similar comment regarding the sanity check, kexec'ing into a kernel with SNP already enabled should probably fail explicitly if the new kernel is booted with incompatible params.
Quoted 25 lines
arch/x86/kernel/sev.c +22
-0+setup_clear_cpu_cap (X86_FEATURE_SEV_SNP ); +pr_err ("IOMMU is either disabled or configured in passthrough mode.\n" ); +return 0 ; + } + +if (__snp_rmptable_init ()) { +setup_clear_cpu_cap (X86_FEATURE_SEV_SNP ); +return 1 ; + } + +cpuhp_setup_state (CPUHP_AP_ONLINE_DYN ,"x86/rmptable_init:online" , __snp_enable,NULL ); + +return 0 ; +} + +/* +* This must be called after the PCI subsystem. This is because before enabling +* the SNP feature we need to ensure that IOMMU is not configured in the +* passthrough mode. The iommu_default_passthrough() is used for checking the +* passthough state, and it is available after subsys_initcall(). +*/ +fs_initcall (snp_rmptable_init);Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 04/40] x86/sev: Add the host SEV-SNP initialization support
Quoted 7 lines · Sean Christopherson
Quoted 2 lines
+#define
RMPTABLE_ENTRIES_OFFSET0x4000A comment and/or blurb in the changelog describing this magic number would be quite helpful. And maybe call out that this is for the bookkeeping, e.g.
#define RMPTABLE_CPU_BOOKKEEPING_SIZE 0x4000
Noted.
Quoted 5 lines
Also, the APM doesn't actually state the exact location of the bookkeeping region, it only states that it's somewhere between
RMP_BASEandRMP_END. This seems to imply that the bookkeeping region is always atRMP_BASE?
Quoted 8 lines
The region of memory between
RMP_BASEandRMP_ENDcontains a 16KB region used for processor bookkeeping followed by the RMP entries, which are each 16B in size. The size of the RMP determines the range of physical memory that the hypervisor can assign to SNP-active virtual machines at runtime. The RMP covers the system physical address space from address 0h to the address calculated by:((RMP_END + 1 – RMP_BASE – 16KB) / 16B) x 4KB
The bookkeeping region is at the start of the RMP_BASE. If we look at the PPR then it provides a formula which we should use to read the RMP entry location. And in that it adds the bookkeeping to the RMP_BASE.
RMP Entry Address = RMP_BASE + 0x4000 + x>>8
Quoted 6 lines
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2201
Quoted 3 lines
arch/x86/kernel/sev.c +3
-0+ + val |=MSR_AMD64_SYSCFG_SNP_EN ; + val |=MSR_AMD64_SYSCFG_SNP_VMPL_EN ;Is VMPL required? Do we plan on using VMPL out of the gate?
The SEV-SNP firmware requires that VMPL must be enabled otherwise it will fail to initialize. However, the current SEV-SNP support is limited to the VMPL0.
Quoted 2 lines
Can BIOS put the RMP at PA=0?
No, they should not. As per the PPR, the 0h is a reset value (means the MSR is not programmed).
Quoted 4 lines
Also, why is it a BIOS decision? AFAICT, the MSRs aren't locked until
SNP_ENis set in SYSCFG, and that appears to be a kernel decision (ignoring kexec), i.e. nothing would prevent the kernel from configuring it's own RMP.
In the current patch set, we assume that user is configuring the BIOS to reserve memory for the RMP table. From hardware point-of-view, it does not matter who reserves the memory (bios or kernel). In future, we could look into reserving the memory from the kernel before through the memblock etc.
Quoted 14 lines
Quoted 14 lines
arch/x86/kernel/sev.c +13
-0+pr_info ("Memory for the RMP table has not been reserved by BIOS\n" ); +return false; + } + + rmp_sz = rmp_end - rmp_base +1 ; + +/* +* Calculate the amount the memory that must be reserved by the BIOS to +* address the full system RAM. The reserved memory should also cover the +* RMP table itself. +* +* See PPR section 2.1.5.2 for more information on memory requirement. +*/
Quoted 9 lines
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2239
Quoted 6 lines
arch/x86/kernel/sev.c +6
-0+ nr_pages =totalram_pages (); + calc_rmp_sz = (((rmp_sz >>PAGE_SHIFT ) + nr_pages) <<4 ) +RMPTABLE_ENTRIES_OFFSET ; + +if (calc_rmp_sz > rmp_sz) { +pr_info ("Memory reserved for the RMP table does not cover the full system " +"RAM (expected 0x%llx got 0x%llx)\n" , calc_rmp_sz, rmp_sz);Is BIOS expected to provide exact coverage, e.g. should this be s/expected/need?
BIOS provides option to reserve the required memory. If they don't cover the entire system ram then its a BIOS bug.
Yes, I will fix the wording s/expected/need.
To make things interesting, it also has option where user can specify amount of memory to be reserved. If user does not cover the full system ram then we need to warn and not enable the SNP. We cannot work with partially reserved RMP table memory.
Quoted 3 lines
Should the kernel also sanity check other requirements, e.g. the 8kb alignment, or does the CPU enforce those things at WRMSR?
The SNP firmware enforces those requirement. It is documented in the SNP firmware specification (SNP_INIT).
Quoted 11 lines
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2271
Quoted 7 lines
arch/x86/kernel/sev.c +7
-0+ +/* +* Check if SEV-SNP is already enabled, this can happen if we are coming from +* kexec boot. +*/ +rdmsrl (MSR_AMD64_SYSCFG , val); +if (val &MSR_AMD64_SYSCFG_SNP_EN )Hmm, it kinda feels like there should be a sanity check for the case where SNP is already enabled but
get_rmptable_info()fails, e.g. due to insufficient RMP size.
Hmm, I am not sure if we need to do this. We enabled the SNP only after all the sanity check is completed, so the get_rmptable_info() will not fail after the SNP is enabled. The RMP MSR's are locked after the SNP is enabled so we should not see a different size.
Quoted 9 lines
Quoted 9 lines
arch/x86/kernel/sev.c +9
-0+ goto skip_enable; + +/* Initialize the RMP table to zero */ +memset (start,0 , sz); + +/* Flush the caches to ensure that data is written before SNP is enabled. */ +wbinvd_on_all_cpus (); + +/* Enable SNP on all CPUs. */
Quoted 9 lines
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2284
Quoted 4 lines
arch/x86/kernel/sev.c +4
-0+on_each_cpu (snp_enable,NULL ,1 ); + +skip_enable: + rmptable_start = (unsigned long )start;Mostly out of curiosity, why store start/end as unsigned longs? This is all 64-bit only so it doesn't actually affect the code generation, but it feels odd to store things that absolutely have to be 64-bit values as unsigned long.
The AMD memory encryption support is compiled when 64-bit is enabled in the Kconfig; Having said that, I am okay to use the u64.
Quoted 20 lines
Similar question for why
asm/sev-common.hcases to unsigned long instead of u64. E.g. the below in particular looks wrong because we're shifting an unsigned long b y32 bits, i.e. the value _must_ be a 64-bit value, why obfuscate that?#define GHCB_CPUID_REQ(fn, reg) \ (GHCB_MSR_CPUID_REQ | \ (((unsigned long)reg & GHCB_MSR_CPUID_REG_MASK) << GHCB_MSR_CPUID_REG_POS) | \ (((unsigned long)fn) << GHCB_MSR_CPUID_FUNC_POS))Quoted 11 lines
arch/x86/kernel/sev.c +11
-0+ rmptable_end = rmptable_start + sz; + +return 0 ; +} + +static int __init snp_rmptable_init (void ) +{ +if (!boot_cpu_has (X86_FEATURE_SEV_SNP )) +return 0 ; + +/*
Quoted 8 lines
arch/x86/kernel/sev.c static int __init add_snp_guest_request(void) · line 2299
Quoted 4 lines
arch/x86/kernel/sev.c +4
-0+* The SEV-SNP support requires that IOMMU must be enabled, and is not +* configured in the passthrough mode. +*/ +if (no_iommu ||iommu_default_passthrough ()) {Similar comment regarding the sanity check, kexec'ing into a kernel with SNP already enabled should probably fail explicitly if the new kernel is booted with incompatible params.
Good point on the kexec, I'll look to cover it.
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 04/40] x86/sev: Add the host SEV-SNP initialization support
Quoted 2 lines · Brijesh Singh
The bookkeeping region is at the start of the
RMP_BASE. If we look at the PPR then it provides a formula which we should use to read the RMP entry
What's the PPR? I get the feeling I'm missing a spec :-)
Re: [PATCH Part2 RFC v4 04/40] x86/sev: Add the host SEV-SNP initialization support
Quoted 1 line · Sean Christopherson
What's the PPR? I get the feeling I'm missing a spec:-)
My bad, I should have provided the link in my previous response
Processor Programming Reference (PPR) for AMD Family 19h Model 01h, Revision B1 Processors
https://www.amd.com/system/files/TechDocs/55898_B1_pub_0.50.zip
look for the PPR_B1_PUB_1.pdf for RMP entry details.
SEV-SNP firmware spec is at developer.amd.com/sev
https://www.amd.com/system/files/TechDocs/56860.pdf
thanks
Re: [PATCH Part2 RFC v4 04/40] x86/sev: Add the host SEV-SNP initialization support
In reply to Brijesh SinghQuoted 11 lines · Brijesh Singh
The memory integrity guarantees of SEV-SNP are enforced through a new structure called the Reverse Map Table (RMP). The RMP is a single data structure shared across the system that contains one entry for every 4K page of DRAM that may be used by SEV-SNP VMs. The goal of RMP is to track the owner of each page of memory. Pages of memory can be owned by the hypervisor, owned by a specific VM or owned by the AMD-SP. See APM2 section 15.36.3 for more detail on RMP.
The RMP table is used to enforce access control to memory. The table itself is not directly writable by the software. New CPU instructions (RMPUPDATE, PVALIDATE, RMPADJUST) are used to manipulate the RMP entries.
What's the point of throwing out a set of opcodes, if there's no explanation what they do?
BR, Jarkko
Re: [PATCH Part2 RFC v4 04/40] x86/sev: Add the host SEV-SNP initialization support
Quoted 9 lines · * Jarkko Sakkinen ([email protected]) wrote:
Quoted 8 lines · Brijesh Singh
The memory integrity guarantees of SEV-SNP are enforced through a new structure called the Reverse Map Table (RMP). The RMP is a single data structure shared across the system that contains one entry for every 4K page of DRAM that may be used by SEV-SNP VMs. The goal of RMP is to track the owner of each page of memory. Pages of memory can be owned by the hypervisor, owned by a specific VM or owned by the AMD-SP. See APM2 section 15.36.3 for more detail on RMP.
Quoted 6 lines
Quoted 3 lines
The RMP table is used to enforce access control to memory. The table itself is not directly writable by the software. New CPU instructions (RMPUPDATE, PVALIDATE, RMPADJUST) are used to manipulate the RMP entries.
What's the point of throwing out a set of opcodes, if there's no explanation what they do?
TBF They are described in the public document section linked in the previous paragraph.
Dave
Quoted 2 lines
BR, Jarkko
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
RFC PATCH v4 5/40 x86/sev: Add RMP entry lookup helpers
In reply to Brijesh SinghThe snp_lookup_page_in_rmptable() can be used by the host to read the RMP entry for a given page. The RMP entry format is documented in AMD PPR, see
https://bugzilla.kernel.org/attachment.cgi?id=296015.
--- arch/x86/include/asm/sev.h | 4 +-- arch/x86/kernel/sev.c | 26 +++++++++++++++++++ include/linux/sev.h | 51 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 include/linux/sev.h
arch/x86/include/asm/sev.h +1 -3
@@ -9,6 +9,7 @@#define __ASM_ENCRYPTED_STATE_H#include <linux/types.h> +#include <linux/sev.h> #include <asm/insn.h> #include <asm/sev-common.h> #include <asm/bootparam.h>
@@ -75,9 +76,6 @@ extern bool handle_vc_boot_ghcb(struct pt_regs *regs);/* Software defined (when rFlags.CF = 1) */ #define PVALIDATE_FAIL_NOUPDATE 255 -/* RMP page size */ -#define RMP_PG_SIZE_4K 0 -#define RMPADJUST_VMSA_PAGE_BIT BIT(16)#ifdef CONFIG_AMD_MEM_ENCRYPT
arch/x86/kernel/sev.c +26 -0
@@ -49,6 +49,8 @@#define DR7_RESET_VALUE 0x400#define RMPTABLE_ENTRIES_OFFSET 0x4000 +#define RMPENTRY_SHIFT 8 +#define rmptable_page_offset (x) (RMPTABLE_ENTRIES_OFFSET + (((unsigned long)x) >> RMPENTRY_SHIFT))/* For early boot hypervisor communication in SEV-ES enabled guests */ static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
@@ -2319,3 +2321,27 @@ static int __init snp_rmptable_init(void)* passthough state, and it is available after subsys_initcall(). */ fs_initcall (snp_rmptable_init); + +struct rmpentry *snp_lookup_page_in_rmptable (struct page *page,int *level) +{ +unsigned long phys =page_to_pfn (page) <<PAGE_SHIFT ; +struct rmpentry *entry, *large_entry; +unsigned long vaddr; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return NULL ; + + vaddr = rmptable_start +rmptable_page_offset (phys); +if (unlikely (vaddr > rmptable_end)) +return NULL ; + + entry = (struct rmpentry *)vaddr; + +/* Read a large RMP entry to get the correct page level used in RMP entry. */ + vaddr = rmptable_start +rmptable_page_offset (phys &PMD_MASK ); + large_entry = (struct rmpentry *)vaddr; + *level =RMP_TO_X86_PG_LEVEL (rmpentry_pagesize (large_entry)); + +return entry; +} +EXPORT_SYMBOL_GPL (snp_lookup_page_in_rmptable);
include/linux/sev.h new file +51 -0
51 lines not on this page · raw message
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 05/40] x86/sev: Add RMP entry lookup helpers
Quoted 3 lines · Brijesh Singh
The
snp_lookup_page_in_rmptable()can be used by the host to read the RMP entry for a given page. The RMP entry format is documented in AMD PPR, see
https://bugzilla.kernel.org/attachment.cgi?id=296015.
Ewwwwww, the RMP format isn't architectural!?
Architecturally the format of RMP entries are not specified in APM. In order to assist software, the following table specifies select portions of the RMP entry format for this specific product.
I know we generally don't want to add infrastructure without good reason, but on the other hand exposing a microarchitectural data structure to the kernel at large is going to be a disaster if the format does change on a future processor.
Looking at the future patches, dump_rmpentry() is the only power user, e.g. everything else mostly looks at "assigned" and "level" (and one ratelimited warn on "validated" in snp_make_page_shared(), but I suspect that particular check can and should be dropped).
So, what about hiding "struct rmpentry" and possibly renaming it to something scary/microarchitectural, e.g. something like
/*
* Returns 1 if the RMP entry is assigned, 0 if it exists but is not assigned,
* and -errno if there is no corresponding RMP entry.
*/
int snp_lookup_rmpentry(struct page *page, int *level)
{
unsigned long phys = page_to_pfn(page) << PAGE_SHIFT;
struct rmpentry *entry, *large_entry;
unsigned long vaddr;
if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
return -ENXIO;
vaddr = rmptable_start + rmptable_page_offset(phys);
if (unlikely(vaddr > rmptable_end))
return -EXNIO;
entry = (struct rmpentry *)vaddr;
/* Read a large RMP entry to get the correct page level used in RMP entry. */
vaddr = rmptable_start + rmptable_page_offset(phys & PMD_MASK);
large_entry = (struct rmpentry *)vaddr;
*level = RMP_TO_X86_PG_LEVEL(rmpentry_pagesize(large_entry));
return !!entry->assigned;
}And then move dump_rmpentry() (or add a helper) in sev.c so that "struct rmpentry" can be declared in sev.c.
Quoted 13 lines
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/sev.h | 4 +-- arch/x86/kernel/sev.c | 26 +++++++++++++++++++ include/linux/sev.h | 51 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 include/linux/sev.harch/x86/include/asm/sev.h +0
-0
arch/x86/include/asm/sev.h line 12
Quoted 4 lines
arch/x86/include/asm/sev.h +1
-0@@ -9,6 +9,7 @@#define __ASM_ENCRYPTED_STATE_H#include <linux/types.h> +#include <linux/sev.h>
Why move things to linux/sev.h? AFAICT, even at the end of the series, the only users of anything in this file all reside somewhere in arch/x86.
Quoted 27 lines
arch/x86/include/asm/sev.h +0
-3#include <asm/insn.h> #include <asm/sev-common.h> #include <asm/bootparam.h> @@ -75,9 +76,6 @@ extern bool handle_vc_boot_ghcb(struct pt_regs *regs);/* Software defined (when rFlags.CF = 1) */ #define PVALIDATE_FAIL_NOUPDATE 255 -/* RMP page size */ -#define RMP_PG_SIZE_4K 0 -#define RMPADJUST_VMSA_PAGE_BIT BIT(16)#ifdef CONFIG_AMD_MEM_ENCRYPT arch/x86/kernel/sev.c +2
-0@@ -49,6 +49,8 @@#define DR7_RESET_VALUE 0x400#define RMPTABLE_ENTRIES_OFFSET 0x4000 +#define RMPENTRY_SHIFT 8 +#define rmptable_page_offset (x) (RMPTABLE_ENTRIES_OFFSET + (((unsigned long)x) >> RMPENTRY_SHIFT))/* For early boot hypervisor communication in SEV-ES enabled guests */ static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
arch/x86/kernel/sev.c static int __init snp_rmptable_init(void) · line 2325
Quoted 5 lines
arch/x86/kernel/sev.c +2
-0@@ -2319,3 +2321,27 @@ static int __init snp_rmptable_init(void)* passthough state, and it is available after subsys_initcall(). */ fs_initcall (snp_rmptable_init); + +struct rmpentry *snp_lookup_page_in_rmptable (struct page *page,int *level)
Maybe just snp_get_rmpentry? Or snp_lookup_rmpentry? I'm guessing the name was chosen to align with e.g. lookup_address_in_mm, but IMO the lookup_address helpers are oddly named.
Quoted 21 lines
arch/x86/kernel/sev.c +21
-0+{ +unsigned long phys =page_to_pfn (page) <<PAGE_SHIFT ; +struct rmpentry *entry, *large_entry; +unsigned long vaddr; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return NULL ; + + vaddr = rmptable_start +rmptable_page_offset (phys); +if (unlikely (vaddr > rmptable_end)) +return NULL ; + + entry = (struct rmpentry *)vaddr; + +/* Read a large RMP entry to get the correct page level used in RMP entry. */ + vaddr = rmptable_start +rmptable_page_offset (phys &PMD_MASK ); + large_entry = (struct rmpentry *)vaddr; + *level =RMP_TO_X86_PG_LEVEL (rmpentry_pagesize (large_entry)); + +return entry; +}
Re: [PATCH Part2 RFC v4 05/40] x86/sev: Add RMP entry lookup helpers
Quoted 11 lines · Sean Christopherson
Quoted 3 lines · Brijesh Singh
The
snp_lookup_page_in_rmptable()can be used by the host to read the RMP entry for a given page. The RMP entry format is documented in AMD PPR, see
https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fbugzilla.kernel.org%2Fattachment.cgi%3Fid%3D296015&data=04%7C01%7Cbrijesh.singh%40amd.com%7C2140214b3fbd4a71617008d947bf9ae7%7C3dd8961fe4884e608e11a82d994e183d%7C0%7C0%7C637619710568694335%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=AkCyolw0P%2BrRFF%2FAnRozld4GkegQ0hR%2F523DI48jB4g%3D&reserved=0.Ewwwwww, the RMP format isn't architectural!?
Architecturally the format of RMP entries are not specified in APM. In order to assist software, the following table specifies select portions of the RMP entry format for this specific product.
Unfortunately yes.
But the documented fields in the RMP entry is architectural. The entry fields are documented in the APM section 15.36. So, in future we are guaranteed to have those fields available. If we are reading the RMP table directly, then architecture should provide some other means to get to fields from the RMP entry.
Quoted 9 lines
I know we generally don't want to add infrastructure without good reason, but on the other hand exposing a microarchitectural data structure to the kernel at large is going to be a disaster if the format does change on a future processor.
Looking at the future patches,
dump_rmpentry()is the only power user, e.g. everything else mostly looks at "assigned" and "level" (and one ratelimited warn on "validated" insnp_make_page_shared(), but I suspect that particular check can and should be dropped).
Yes, we need "assigned" and "level" and other entries are mainly for the debug purposes.
Quoted 3 lines
So, what about hiding "struct rmpentry" and possibly renaming it to something scary/microarchitectural, e.g. something like
Yes, it will work fine.
Quoted 28 lines
/*
* Returns 1 if the RMP entry is assigned, 0 if it exists but is not assigned,
* and -errno if there is no corresponding RMP entry.
*/
intsnp_lookup_rmpentry(struct page *page, int *level){ unsigned long phys = page_to_pfn(page) << PAGE_SHIFT; struct rmpentry *entry, *large_entry; unsigned long vaddr; if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP)) return -ENXIO; vaddr = rmptable_start + rmptable_page_offset(phys); if (unlikely(vaddr > rmptable_end)) return -EXNIO; entry = (struct rmpentry *)vaddr; /* Read a large RMP entry to get the correct page level used in RMP entry. */ vaddr = rmptable_start + rmptable_page_offset(phys & PMD_MASK); large_entry = (struct rmpentry *)vaddr; *level = RMP_TO_X86_PG_LEVEL(rmpentry_pagesize(large_entry)); return !!entry->assigned; }
Quoted 3 lines
And then move
dump_rmpentry()(or add a helper) insev.cso that "struct rmpentry" can be declared insev.c.
Ack.
Quoted 15 lines
Quoted 15 lines
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/sev.h | 4 +-- arch/x86/kernel/sev.c | 26 +++++++++++++++++++ include/linux/sev.h | 51 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 3 deletions(-)create mode 100644
include/linux/sev.harch/x86/include/asm/sev.h +0
-0@@ -9,6 +9,7 @@#define __ASM_ENCRYPTED_STATE_H
Quoted 6 lines
arch/x86/include/asm/sev.h line 12
Quoted 2 lines
arch/x86/include/asm/sev.h +1
-0#include <linux/types.h> +#include <linux/sev.h> Why move things to
linux/sev.h? AFAICT, even at the end of the series, the only users of anything in this file all reside somewhere inarch/x86.
If we go with approach where the 'struct rmpentry' is not visible outside the arch/x86/kernel/sev.c then there is no need to define all these bit fields in linux/sev.h. I kept in linux/sev.h because driver (KVM, and PSP) uses the rmpentry_xxx() to read the fields.
Quoted 24 lines
Quoted 24 lines
arch/x86/include/asm/sev.h +0
-3#include <asm/insn.h> #include <asm/sev-common.h> #include <asm/bootparam.h> @@ -75,9 +76,6 @@ extern bool handle_vc_boot_ghcb(struct pt_regs *regs);/* Software defined (when rFlags.CF = 1) */ #define PVALIDATE_FAIL_NOUPDATE 255 -/* RMP page size */ -#define RMP_PG_SIZE_4K 0 -#define RMPADJUST_VMSA_PAGE_BIT BIT(16)#ifdef CONFIG_AMD_MEM_ENCRYPT arch/x86/kernel/sev.c +2
-0@@ -49,6 +49,8 @@#define DR7_RESET_VALUE 0x400#define RMPTABLE_ENTRIES_OFFSET 0x4000 +#define RMPENTRY_SHIFT 8 +#define rmptable_page_offset (x) (RMPTABLE_ENTRIES_OFFSET + (((unsigned long)x) >> RMPENTRY_SHIFT))
Quoted 13 lines
arch/x86/kernel/sev.c static int __init snp_rmptable_init(void) · line 2325
Quoted 8 lines
arch/x86/kernel/sev.c +2
-0/* For early boot hypervisor communication in SEV-ES enabled guests */ static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);@@ -2319,3 +2321,27 @@ static int __init snp_rmptable_init(void)* passthough state, and it is available after subsys_initcall(). */ fs_initcall (snp_rmptable_init); + +struct rmpentry *snp_lookup_page_in_rmptable (struct page *page,int *level)Maybe just
snp_get_rmpentry? Orsnp_lookup_rmpentry? I'm guessing the name was chosen to align with e.g.lookup_address_in_mm, but IMO thelookup_addresshelpers are oddly named.
Yes, it was mostly choose to align with it. Dave recommended dropping the 'struct page *' arg from it and accept the pfn directly. Based on your feedbacks, I am going to add
int snp_lookup_rmpentry(unsigned long pfn, int *level);
thanks
Re: [PATCH Part2 RFC v4 05/40] x86/sev: Add RMP entry lookup helpers
Quoted 45 lines · Brijesh Singh
Quoted 8 lines · Sean Christopherson
Quoted 6 lines · Brijesh Singh
The
snp_lookup_page_in_rmptable()can be used by the host to read the RMP
entry for a given page. The RMP entry format is documented in AMD PPR, see
https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fbugzilla.kernel.org%2Fattachment.cgi%3Fid%3D296015&data=04%7C01%7Cbrijesh.singh%40amd.com%7C2140214b3fbd4a71617008d947bf9ae7%7C3dd8961fe4884e608e11a82d994e183d%7C0%7C0%7C637619710568694335%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=AkCyolw0P%2BrRFF%2FAnRozld4GkegQ0hR%2F523DI48jB4g%3D&reserved=0.Quoted 8 lines
Ewwwwww, the RMP format isn't architectural!?
Architecturally the format of RMP entries are not specified in APM. In order
to assist software, the following table specifies select portions of the RMP
entry format for this specific product.Unfortunately yes.
But the documented fields in the RMP entry is architectural. The entry fields are documented in the APM section 15.36. So, in future we are guaranteed to have those fields available. If we are reading the RMP table directly, then architecture should provide some other means to get to fields from the RMP entry.
Quoted 7 lines
I know we generally don't want to add infrastructure without good reason, but on
the other hand exposing a microarchitectural data structure to the kernel at large
is going to be a disaster if the format does change on a future processor.Quoted 8 lines
Looking at the future patches,
dump_rmpentry()is the only power user, e.g.
everything else mostly looks at "assigned" and "level" (and one ratelimited warn
on "validated" insnp_make_page_shared(), but I suspect that particular check
can and should be dropped).
Quoted 3 lines
Yes, we need "assigned" and "level" and other entries are mainly for the debug purposes.
For the debug purposes, we would like to dump additional RMP entries. If we go with your proposed function then how do we get those information in the dump_rmpentry()? How about if we provide two functions; the first function provides architectural format and second provides the raw values which can be used by the dump_rmpentry() helper.
struct rmpentry *snp_lookup_rmpentry(unsigned long paddr, int *level);
The 'struct rmpentry' uses the format defined in APM Table 15-36.
struct _rmpentry *_snp_lookup_rmpentry(unsigned long paddr, int *level);
The 'struct _rmpentry' will use include the PPR definition (basically what we have today in this patch).
Thoughts ?
Quoted 42 lines
Quoted 4 lines
So, what about hiding "struct rmpentry" and possibly renaming it to something
scary/microarchitectural, e.g. something likeYes, it will work fine.
Quoted 34 lines
/*
* Returns 1 if the RMP entry is assigned, 0 if it exists but is not assigned,
* and -errno if there is no corresponding RMP entry.
*/
intsnp_lookup_rmpentry(struct page *page, int *level)
{
unsigned long phys =page_to_pfn(page)<<PAGE_SHIFT; struct rmpentry *entry,*large_entry;
unsigned long vaddr;if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP)) return
-ENXIO;vaddr =
rmptable_start+rmptable_page_offset(phys); if (unlikely(vaddr > rmptable_end))
return-EXNIO;entry = (struct rmpentry *)vaddr;
/* Read a large RMP entry to get the correct page level used in RMP entry. */
vaddr =rmptable_start+rmptable_page_offset(phys & PMD_MASK);large_entry= (struct rmpentry *)vaddr;
*level = RMP_TO_X86_PG_LEVEL(rmpentry_pagesize(large_entry));return !!entry->assigned;
}And then move
dump_rmpentry()(or add a helper) insev.cso that "struct rmpentry"
can be declared insev.c.
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 05/40] x86/sev: Add RMP entry lookup helpers
Quoted 7 lines · Brijesh Singh
Quoted 5 lines · Brijesh Singh
Quoted 4 lines
Looking at the future patches,
dump_rmpentry()is the only power user, e.g. everything else mostly looks at "assigned" and "level" (and one ratelimited warn on "validated" insnp_make_page_shared(), but I suspect that particular check can and should be dropped).
Quoted 6 lines
Quoted 3 lines
Yes, we need "assigned" and "level" and other entries are mainly for the debug purposes.
For the debug purposes, we would like to dump additional RMP entries. If we go with your proposed function then how do we get those information in the
dump_rmpentry()?
As suggested below, move dump_rmpentry() into sev.c so that it can use the microarchitectural version. For debug, I'm pretty that's what we'll want anyways, e.g. dump the raw value along with the meaning of various bits.
Quoted 6 lines
How about if we provide two functions; the first function provides architectural format and second provides the raw values which can be used by the
dump_rmpentry()helper.struct rmpentry *snp_lookup_rmpentry(unsigned long paddr, int *level);
Quoted 8 lines
The 'struct rmpentry' uses the format defined in APM Table 15-36.
struct
_rmpentry*_snp_lookup_rmpentry(unsigned long paddr, int *level);The 'struct
_rmpentry' will use include the PPR definition (basically what we have today in this patch).Thoughts ?
Why define an architectural "struct rmpentry"? IIUC, there isn't a true architectural RMP entry; the APM defines architectural fields but doesn't define a layout. Functionally, making up our own struct isn't a problem, I just don't see the point since all use cases only care about Assigned and Page-Size, and we can do them a favor by translating Page-Size to X86_PG_LEVEL.
Quoted 31 lines
Quoted 31 lines
Quoted 31 lines
/*
* Returns 1 if the RMP entry is assigned, 0 if it exists but is not
* assigned, and -errno if there is no corresponding RMP entry.
*/
intsnp_lookup_rmpentry(struct page *page, int *level)
{
unsigned long phys =page_to_pfn(page)<<PAGE_SHIFT; struct rmpentry *entry,*large_entry;
unsigned long vaddr;if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP)) return
-ENXIO;vaddr =
rmptable_start+rmptable_page_offset(phys); if (unlikely(vaddr > rmptable_end))
return-EXNIO;entry = (struct rmpentry *)vaddr;
/* Read a large RMP entry to get the correct page level used in RMP entry. */
vaddr =rmptable_start+rmptable_page_offset(phys & PMD_MASK);large_entry= (struct rmpentry *)vaddr;
*level = RMP_TO_X86_PG_LEVEL(rmpentry_pagesize(large_entry));return !!entry->assigned;
}And then move
dump_rmpentry()(or add a helper) insev.cso that "struct rmpentry" can be declared insev.c.
Re: [PATCH Part2 RFC v4 05/40] x86/sev: Add RMP entry lookup helpers
Quoted 9 lines · Sean Christopherson
Quoted 8 lines · Brijesh Singh
Quoted 7 lines · Brijesh Singh
Quoted 4 lines
Looking at the future patches,
dump_rmpentry()is the only power user, e.g. everything else mostly looks at "assigned" and "level" (and one ratelimited warn on "validated" insnp_make_page_shared(), but I suspect that particular check can and should be dropped).Yes, we need "assigned" and "level" and other entries are mainly for the debug purposes.
Quoted 6 lines
Quoted 3 lines
For the debug purposes, we would like to dump additional RMP entries. If we go with your proposed function then how do we get those information in the
dump_rmpentry()?As suggested below, move
dump_rmpentry()intosev.cso that it can use the microarchitectural version. For debug, I'm pretty that's what we'll want anyways, e.g. dump the raw value along with the meaning of various bits.
Based on other feedbacks, I am not sure if we need to dump the RMP entry; In other feedback we agreed to unmap the pages from the direct map while adding them in the RMP table, so, if anyone attempts to access those pages they will now get the page-not-present instead of the RMP violation.
thanks
RFC PATCH v4 6/40 x86/sev: Add helper functions for RMPUPDATE and PSMASH instruction
In reply to Brijesh SinghThe RMPUPDATE instruction writes a new RMP entry in the RMP Table. The hypervisor will use the instruction to add pages to the RMP table. See APM3 for details on the instruction operations.
The PSMASH instruction expands a 2MB RMP entry into a corresponding set of contiguous 4KB-Page RMP entries. The hypervisor will use this instruction to adjust the RMP entry without invalidating the previous RMP entry.
--- arch/x86/kernel/sev.c | 42 ++++++++++++++++++++++++++++++++++++++++++ include/linux/sev.h | 20 ++++++++++++++++++++ 2 files changed, 62 insertions(+)
arch/x86/kernel/sev.c +42 -0
@@ -2345,3 +2345,45 @@ struct rmpentry *snp_lookup_page_in_rmptable(struct page *page, int *level)return entry; }EXPORT_SYMBOL_GPL (snp_lookup_page_in_rmptable); + +int psmash (struct page *page) +{ +unsigned long spa =page_to_pfn (page) <<PAGE_SHIFT ; +int ret; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return -ENXIO ; + +/* Retry if another processor is modifying the RMP entry. */ +do { +/* Binutils version 2.36 supports the PSMASH mnemonic. */ + asmvolatile (".byte 0xF3, 0x0F, 0x01, 0xFF" + :"=a" (ret) + :"a" (spa) + :"memory" ,"cc" ); + }while (ret ==FAIL_INUSE ); + +return ret; +} +EXPORT_SYMBOL_GPL (psmash); + +int rmpupdate (struct page *page,struct rmpupdate *val) +{ +unsigned long spa =page_to_pfn (page) <<PAGE_SHIFT ; +int ret; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return -ENXIO ; + +/* Retry if another processor is modifying the RMP entry. */ +do { +/* Binutils version 2.36 supports the RMPUPDATE mnemonic. */ + asmvolatile (".byte 0xF2, 0x0F, 0x01, 0xFE" + :"=a" (ret) + :"a" (spa),"c" ((unsigned long )val) + :"memory" ,"cc" ); + }while (ret ==FAIL_INUSE ); + +return ret; +} +EXPORT_SYMBOL_GPL (rmpupdate);
include/linux/sev.h +20 -0
@@ -39,13 +39,33 @@ struct __packed rmpentry {#define RMP_TO_X86_PG_LEVEL (level) (((level) == RMP_PG_SIZE_4K) ? PG_LEVEL_4K : PG_LEVEL_2M) +struct rmpupdate { +u64 gpa; +u8 assigned; +u8 pagesize; +u8 immutable; +u8 rsvd; +u32 asid; +} __packed; + + +/* +* The psmash() and rmpupdate() returns FAIL_INUSE when another processor is +* modifying the RMP entry. +*/ +#define FAIL_INUSE 3 +#ifdef CONFIG_AMD_MEM_ENCRYPT struct rmpentry *snp_lookup_page_in_rmptable (struct page *page,int *level); +int psmash (struct page *page); +int rmpupdate (struct page *page,struct rmpupdate *e);#else static inline struct rmpentry *snp_lookup_page_in_rmptable (struct page *page,int *level) {return NULL ; } +static inline int psmash (struct page *page) {return -ENXIO ; } +static inline int rmpupdate (struct page *page,struct rmpupdate *e) {return -ENXIO ; }#endif /* CONFIG_AMD_MEM_ENCRYPT */ #endif /* __LINUX_SEV_H */
Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 06/40] x86/sev: Add helper functions for RMPUPDATE and PSMASH instruction
Quoted 6 lines
arch/x86/kernel/sev.c +6
-0+int psmash (struct page *page) +{ +unsigned long spa =page_to_pfn (page) <<PAGE_SHIFT ; +int ret; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))
arch/x86/kernel/sev.c struct rmpentry *snp_lookup_page_in_rmptable(struct page *page, int *level) · line 2364
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+return -ENXIO ; + +/* Retry if another processor is modifying the RMP entry. */ +do { +/* Binutils version 2.36 supports the PSMASH mnemonic. */ + asmvolatile (".byte 0xF3, 0x0F, 0x01, 0xFF" + :"=a" (ret) + :"a" (spa) + :"memory" ,"cc" ); + }while (ret ==FAIL_INUSE );
Should there be some retry limit here for safety? Or do we know that we'll never be stuck in this loop? Ditto for the loop in rmpupdate.
Quoted 5 lines
arch/x86/kernel/sev.c +4
-0+ +return ret; +} +EXPORT_SYMBOL_GPL (psmash);
Re: [PATCH Part2 RFC v4 06/40] x86/sev: Add helper functions for RMPUPDATE and PSMASH instruction
Quoted 10 lines · Peter Gonda
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+int psmash (struct page *page) +{ +unsigned long spa =page_to_pfn (page) <<PAGE_SHIFT ; +int ret; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return -ENXIO ; + +/* Retry if another processor is modifying the RMP entry. */ + do {
Quoted 8 lines
arch/x86/kernel/sev.c struct rmpentry *snp_lookup_page_in_rmptable(struct page *page, int *level) · line 2364
Quoted 6 lines
arch/x86/kernel/sev.c +6
-0+/* Binutils version 2.36 supports the PSMASH mnemonic. */ + asmvolatile (".byte 0xF3, 0x0F, 0x01, 0xFF" + :"=a" (ret) + :"a" (spa) + :"memory" ,"cc" ); + }while (ret ==FAIL_INUSE );Should there be some retry limit here for safety? Or do we know that we'll never be stuck in this loop? Ditto for the loop in rmpupdate.
It's probably fine to just leave this. While you could *theoretically* lose this race forever, it's unlikely to happen in practice. If it does, you'll get an easy-to-understand softlockup backtrace which should point here pretty quickly.
I think TDX has a few of these as well. Most of the "SEAMCALL"s from host to the firmware doing the security enforcement have something like an -EBUSY as well. I believe they just retry forever too.
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 06/40] x86/sev: Add helper functions for RMPUPDATE and PSMASH instruction
Quoted 20 lines · Dave Hansen
Quoted 10 lines · Peter Gonda
Quoted 10 lines
arch/x86/kernel/sev.c +10
-0+int psmash (struct page *page) +{ +unsigned long spa =page_to_pfn (page) <<PAGE_SHIFT ; +int ret; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return -ENXIO ; + +/* Retry if another processor is modifying the RMP entry. */ + do {Quoted 8 lines
arch/x86/kernel/sev.c struct rmpentry *snp_lookup_page_in_rmptable(struct page *page, int *level) · line 2364
Quoted 6 lines
arch/x86/kernel/sev.c +6
-0+/* Binutils version 2.36 supports the PSMASH mnemonic. */ + asmvolatile (".byte 0xF3, 0x0F, 0x01, 0xFF" + :"=a" (ret) + :"a" (spa) + :"memory" ,"cc" ); + }while (ret ==FAIL_INUSE );Should there be some retry limit here for safety? Or do we know that we'll never be stuck in this loop? Ditto for the loop in rmpupdate.
Quoted 4 lines
It's probably fine to just leave this. While you could *theoretically* lose this race forever, it's unlikely to happen in practice. If it does, you'll get an easy-to-understand softlockup backtrace which should point here pretty quickly.
But should failure here even be tolerated? The TDX cases spin on flows that are _not_ due to (direct) contenion, e.g. a pending interrupt while flushing the cache or lack of randomness when generating a key. In this case, there are two CPUs racing to modify the RMP entry, which implies that the final state of the RMP entry is not deterministic.
Quoted 3 lines
I think TDX has a few of these as well. Most of the "SEAMCALL"s from host to the firmware doing the security enforcement have something like an
-EBUSYas well. I believe they just retry forever too.
Re: [PATCH Part2 RFC v4 06/40] x86/sev: Add helper functions for RMPUPDATE and PSMASH instruction
Quoted 14 lines · Sean Christopherson
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
arch/x86/kernel/sev.c +8
-0+/* Retry if another processor is modifying the RMP entry. */ +do { +/* Binutils version 2.36 supports the PSMASH mnemonic. */ + asmvolatile (".byte 0xF3, 0x0F, 0x01, 0xFF" + :"=a" (ret) + :"a" (spa) + :"memory" ,"cc" ); + }while (ret ==FAIL_INUSE );Quoted 6 lines
Quoted 2 lines
Should there be some retry limit here for safety? Or do we know that we'll never be stuck in this loop? Ditto for the loop in rmpupdate.
It's probably fine to just leave this. While you could *theoretically* lose this race forever, it's unlikely to happen in practice. If it does, you'll get an easy-to-understand softlockup backtrace which should point here pretty quickly.
Quoted 5 lines
But should failure here even be tolerated? The TDX cases spin on flows that are _not_ due to (direct) contenion, e.g. a pending interrupt while flushing the cache or lack of randomness when generating a key. In this case, there are two CPUs racing to modify the RMP entry, which implies that the final state of the RMP entry is not deterministic.
I was envisioning that two different CPUs could try to smash two *different* 4k physical pages, but collide since they share a 2M page.
But, in patch 33, this is called via:
Review
Quoted 5 lines
(quoted diff) +5
-0+ write_lock(&kvm->mmu_lock); + + switch (op) { + case SNP_PAGE_STATE_SHARED: + rc = snp_make_page_shared(vcpu, gpa, pfn, level);
...
Which should make collisions impossible. Did I miss another call-site?
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 06/40] x86/sev: Add helper functions for RMPUPDATE and PSMASH instruction
Quoted 27 lines · Dave Hansen
Quoted 14 lines · Sean Christopherson
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
arch/x86/kernel/sev.c +8
-0+/* Retry if another processor is modifying the RMP entry. */ +do { +/* Binutils version 2.36 supports the PSMASH mnemonic. */ + asmvolatile (".byte 0xF3, 0x0F, 0x01, 0xFF" + :"=a" (ret) + :"a" (spa) + :"memory" ,"cc" ); + }while (ret ==FAIL_INUSE );Quoted 6 lines
Quoted 2 lines
Should there be some retry limit here for safety? Or do we know that we'll never be stuck in this loop? Ditto for the loop in rmpupdate.
It's probably fine to just leave this. While you could *theoretically* lose this race forever, it's unlikely to happen in practice. If it does, you'll get an easy-to-understand softlockup backtrace which should point here pretty quickly.
Quoted 5 lines
But should failure here even be tolerated? The TDX cases spin on flows that are _not_ due to (direct) contenion, e.g. a pending interrupt while flushing the cache or lack of randomness when generating a key. In this case, there are two CPUs racing to modify the RMP entry, which implies that the final state of the RMP entry is not deterministic.
I was envisioning that two different CPUs could try to smash two *different* 4k physical pages, but collide since they share a 2M page.
But, in patch 33, this is called via:
Quoted 8 lines
Review
Quoted 5 lines
(quoted diff) +5
-0+ write_lock(&kvm->mmu_lock); + + switch (op) { + case SNP_PAGE_STATE_SHARED: + rc = snp_make_page_shared(vcpu, gpa, pfn, level);...
Which should make collisions impossible. Did I miss another call-site?
Ya, there's more, e.g. sev_snp_write_page_begin() and snp_handle_rmp_page_fault(), both of which run without holding mmu_lock. The PSMASH operation isn't too concerning, but the associated RMPUDATE is most definitely a concern, e.g. if two vCPUs are trying to access different variants of a page. It's ok if KVM's "response" in such a situation does weird things to the guest, but one of the two operations should "win", which I don't think is guaranteed if multiple RMP violations are racing.
I'll circle back to this patch after I've gone through the KVM MMU changes.
RFC PATCH v4 7/40 x86/sev: Split the physmap when adding the page in RMP table
In reply to Brijesh SinghThe integrity guarantee of SEV-SNP is enforced through the RMP table. The RMP is used in conjuntion with standard x86 and IOMMU page tables to enforce memory restrictions and page access rights. The RMP is indexed by system physical address, and is checked at the end of CPU and IOMMU table walks. The RMP check is enforced as soon as SEV-SNP is enabled globally in the system. Not every memory access requires an RMP check. In particular, the read accesses from the hypervisor do not require RMP checks because the data confidentiality is already protected via memory encryption. When hardware encounters an RMP checks failure, it raise a page-fault exception. The RMP bit in fault error code can be used to determine if the fault was due to an RMP checks failure.
A write from the hypervisor goes through the RMP checks. When the hypervisor writes to pages, hardware checks to ensures that the assigned bit in the RMP is zero (i.e page is shared). If the page table entry that gives the sPA indicates that the target page size is a large page, then all RMP entries for the 4KB constituting pages of the target must have the assigned bit 0. If one of entry does not have assigned bit 0 then hardware will raise an RMP violation. To resolve it, split the page table entry leading to target page into 4K.
This poses a challenge in the Linux memory model. The Linux kernel creates a direct mapping of all the physical memory -- referred to as the physmap. The physmap may contain a valid mapping of guest owned pages. During the page table walk, the host access may get into the situation where one of the pages within the large page is owned by the guest (i.e assigned bit is set in RMP). A write to a non-guest within the large page will raise an RMP violation. Call set_memory_4k() to split the physmap before adding the page in the RMP table. This ensures that the pages added in the RMP table are used as 4K in the physmap.
--- arch/x86/kernel/sev.c | 6 ++++++ 1 file changed, 6 insertions(+)
arch/x86/kernel/sev.c +6 -0
@@ -2375,6 +2375,12 @@ int rmpupdate(struct page *page, struct rmpupdate *val)if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))return -ENXIO ; + ret =set_memory_4k ((unsigned long )page_to_virt (page),1 ); +if (ret) { +pr_err ("Failed to split physical address 0x%lx (%d)\n" , spa, ret); +return ret; + } +/* Retry if another processor is modifying the RMP entry. */ do { /* Binutils version 2.36 supports the RMPUPDATE mnemonic. */
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 13 lines · Brijesh Singh
The integrity guarantee of SEV-SNP is enforced through the RMP table. The RMP is used in conjuntion with standard x86 and IOMMU page tables to enforce memory restrictions and page access rights. The RMP is indexed by system physical address, and is checked at the end of CPU and IOMMU table walks. The RMP check is enforced as soon as SEV-SNP is enabled globally in the system. Not every memory access requires an RMP check. In particular, the read accesses from the hypervisor do not require RMP checks because the data confidentiality is already protected via memory encryption. When hardware encounters an RMP checks failure, it raise a page-fault exception. The RMP bit in fault error code can be used to determine if the fault was due to an RMP checks failure.
Quoted 8 lines
A write from the hypervisor goes through the RMP checks. When the hypervisor writes to pages, hardware checks to ensures that the assigned bit in the RMP is zero (i.e page is shared). If the page table entry that gives the sPA indicates that the target page size is a large page, then all RMP entries for the 4KB constituting pages of the target must have the assigned bit 0. If one of entry does not have assigned bit 0 then hardware will raise an RMP violation. To resolve it, split the page table entry leading to target page into 4K.
Isn't the above just saying:
All RMP entries covered by a large page must match the shared vs. encrypted state of the page, e.g. host large pages must have assigned=0 for all relevant RMP entries.
Quoted 20 lines
This poses a challenge in the Linux memory model. The Linux kernel creates a direct mapping of all the physical memory -- referred to as the physmap. The physmap may contain a valid mapping of guest owned pages. During the page table walk, the host access may get into the situation where one of the pages within the large page is owned by the guest (i.e assigned bit is set in RMP). A write to a non-guest within the large page will raise an RMP violation. Call
set_memory_4k()to split the physmap before adding the page in the RMP table. This ensures that the pages added in the RMP table are used as 4K in the physmap.Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/kernel/sev.c | 6 ++++++ 1 file changed, 6 insertions(+)arch/x86/kernel/sev.c +0
-0
arch/x86/kernel/sev.c int rmpupdate(struct page *page, struct rmpupdate *val) · line 2378
Quoted 4 lines
arch/x86/kernel/sev.c +1
-0@@ -2375,6 +2375,12 @@ int rmpupdate(struct page *page, struct rmpupdate *val)if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))return -ENXIO ; + ret =set_memory_4k ((unsigned long )page_to_virt (page),1 );
IIUC, this shatters the direct map for page that's assigned to an SNP guest, and the large pages are never recovered?
I believe a better approach would be to do something similar to memfd_secret[*], which encountered a similar problem with the direct map. Instead of forcing the direct map to be forever 4k, unmap the direct map when making a page guest private, and restore the direct map when it's made shared (or freed).
I thought memfd_secret had also solved the problem of restoring large pages in the direct map, but at a glance I can't tell if that's actually implemented anywhere. But, even if it's not currently implemented, I think it makes sense to mimic the memfd_secret approach so that both features can benefit if large page preservation/restoration is ever added.
Quoted 11 lines
arch/x86/kernel/sev.c +5
-0+if (ret) { +pr_err ("Failed to split physical address 0x%lx (%d)\n" , spa, ret); +return ret; + } +/* Retry if another processor is modifying the RMP entry. */ do { /* Binutils version 2.36 supports the RMPUPDATE mnemonic. */Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 9 lines · Sean Christopherson
Quoted 8 lines
A write from the hypervisor goes through the RMP checks. When the hypervisor writes to pages, hardware checks to ensures that the assigned bit in the RMP is zero (i.e page is shared). If the page table entry that gives the sPA indicates that the target page size is a large page, then all RMP entries for the 4KB constituting pages of the target must have the assigned bit 0. If one of entry does not have assigned bit 0 then hardware will raise an RMP violation. To resolve it, split the page table entry leading to target page into 4K.
Quoted 6 lines
Isn't the above just saying:
All RMP entries covered by a large page must match the shared vs. encrypted state of the page, e.g. host large pages must have assigned=0 for all relevant RMP entries.
Yes.
Quoted 14 lines
arch/x86/kernel/sev.c int rmpupdate(struct page *page, struct rmpupdate *val) · line 2378
Quoted 5 lines
arch/x86/kernel/sev.c +1
-0@@ -2375,6 +2375,12 @@ int rmpupdate(struct page *page, struct rmpupdate *val)if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))return -ENXIO ; + ret =set_memory_4k ((unsigned long )page_to_virt (page),1 );IIUC, this shatters the direct map for page that's assigned to an SNP guest, and the large pages are never recovered?
I believe a better approach would be to do something similar to memfd_secret[*], which encountered a similar problem with the direct map. Instead of forcing the direct map to be forever 4k, unmap the direct map when making a page guest private, and restore the direct map when it's made shared (or freed).
Quoted 6 lines
I thought
memfd_secrethad also solved the problem of restoring large pages in the direct map, but at a glance I can't tell if that's actually implemented anywhere. But, even if it's not currently implemented, I think it makes sense to mimic thememfd_secretapproach so that both features can benefit if large page preservation/restoration is ever added.
thanks for the memfd_secrets pointer. At the lowest level it shares the same logic to split the physmap. We both end up calling to change_page_attrs_set_clr() which split the page and updates the page table attributes.
Given this, I believe in future if the change_page_attrs_set_clr() is enhanced to track the splitting of the pages and restore it later then it should work transparently.
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 22 lines · Brijesh Singh
Quoted 13 lines · Sean Christopherson
arch/x86/kernel/sev.c int rmpupdate(struct page *page, struct rmpupdate *val) · line 2377
Quoted 4 lines
arch/x86/kernel/sev.c +1
-0@@ -2375,6 +2375,12 @@ int rmpupdate(struct page *page, struct rmpupdate *val)if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))return -ENXIO ; + ret =set_memory_4k ((unsigned long )page_to_virt (page),1 );IIUC, this shatters the direct map for page that's assigned to an SNP guest, and the large pages are never recovered?
I believe a better approach would be to do something similar to memfd_secret[*], which encountered a similar problem with the direct map. Instead of forcing the direct map to be forever 4k, unmap the direct map when making a page guest private, and restore the direct map when it's made shared (or freed).
Quoted 6 lines
I thought
memfd_secrethad also solved the problem of restoring large pages in the direct map, but at a glance I can't tell if that's actually implemented anywhere. But, even if it's not currently implemented, I think it makes sense to mimic thememfd_secretapproach so that both features can benefit if large page preservation/restoration is ever added.
Quoted 8 lines
thanks for the
memfd_secretspointer. At the lowest level it shares the same logic to split the physmap. We both end up calling tochange_page_attrs_set_clr()which split the page and updates the page table attributes.Given this, I believe in future if the
change_page_attrs_set_clr()is enhanced to track the splitting of the pages and restore it later then it should work transparently.
But something actually needs to initiate the restore. If the RMPUDATE path just force 4k pages then there will never be a restore. And zapping the direct map for private pages is a good thing, e.g. prevents the kernel from reading garbage, which IIUC isn't enforced by the RMP?
Re: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 28 lines · Sean Christopherson
Quoted 27 lines · Brijesh Singh
Quoted 13 lines · Sean Christopherson
arch/x86/kernel/sev.c int rmpupdate(struct page *page, struct rmpupdate *val) · line 2377
Quoted 4 lines
arch/x86/kernel/sev.c +1
-0@@ -2375,6 +2375,12 @@ int rmpupdate(struct page *page, struct rmpupdate *val)if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))return -ENXIO ; + ret =set_memory_4k ((unsigned long )page_to_virt (page),1 );IIUC, this shatters the direct map for page that's assigned to an SNP guest, and the large pages are never recovered?
I believe a better approach would be to do something similar to memfd_secret[*], which encountered a similar problem with the direct map. Instead of forcing the direct map to be forever 4k, unmap the direct map when making a page guest private, and restore the direct map when it's made shared (or freed).
Quoted 6 lines
I thought
memfd_secrethad also solved the problem of restoring large pages in the direct map, but at a glance I can't tell if that's actually implemented anywhere. But, even if it's not currently implemented, I think it makes sense to mimic thememfd_secretapproach so that both features can benefit if large page preservation/restoration is ever added.thanks for the
memfd_secretspointer. At the lowest level it shares the same logic to split the physmap. We both end up calling tochange_page_attrs_set_clr()which split the page and updates the page table attributes.
Quoted 9 lines
Quoted 3 lines
Given this, I believe in future if the
change_page_attrs_set_clr()is enhanced to track the splitting of the pages and restore it later then it should work transparently.But something actually needs to initiate the restore. If the RMPUDATE path just force 4k pages then there will never be a restore. And zapping the direct map for private pages is a good thing, e.g. prevents the kernel from reading garbage, which IIUC isn't enforced by the RMP?
Yes, something need to initiated the restore. Since the restore support is not present today so its difficult to say how it will be look. I am thinking that restore thread may use some kind of notifier to check with the caller whether its safe to restore the page ranges. In case of the SEV-SNP, the SNP registered notifier will reject if the guest is running.
The memfd_secrets uses the set_direct_map_{invalid,default}_noflush() and it is designed to remove/add the present bit in the direct map. We can't use them, because in our case the page may get accessed by the KVM (e.g kvm_guest_write, kvm_guest_map etc).
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 4 lines · Brijesh Singh
The
memfd_secretsuses the set_direct_map_{invalid,default}_noflush() and it is designed to remove/add the present bit in the direct map. We can't use them, because in our case the page may get accessed by the KVM (e.gkvm_guest_write,kvm_guest_mapetc).
But KVM should never access a guest private page, i.e. the direct map should always be restored to PRESENT before KVM attempts to access the page.
Re: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 9 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh
The
memfd_secretsuses the set_direct_map_{invalid,default}_noflush() and it is designed to remove/add the present bit in the direct map. We can't use them, because in our case the page may get accessed by the KVM (e.gkvm_guest_write,kvm_guest_mapetc).But KVM should never access a guest private page, i.e. the direct map should always be restored to PRESENT before KVM attempts to access the page.
Yes, KVM should *never* access the guest private pages. So, we could potentially enhance the RMPUPDATE() to check for the assigned and act accordingly.
Are you thinking something along the line of this:
int rmpupdate(struct page *page, struct rmpupdate *val)
{
...
/*
* If page is getting assigned in the RMP entry then unmap
* it from the direct map before its added in the RMP table.
*/
if (val.assigned)
set_direct_map_invalid_noflush(page_to_virt(page), 1);
...
/*
* If the page is getting unassigned then restore the mapping
* in the direct map after its removed from the RMP table.
*/
if (!val.assigned)
set_direct_map_default_noflush(page_to_virt(page), 1);
...
}thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 33 lines · Brijesh Singh
Quoted 9 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh
The
memfd_secretsuses the set_direct_map_{invalid,default}_noflush() and it is designed to remove/add the present bit in the direct map. We can't use them, because in our case the page may get accessed by the KVM (e.gkvm_guest_write,kvm_guest_mapetc).But KVM should never access a guest private page, i.e. the direct map should always be restored to PRESENT before KVM attempts to access the page.
Yes, KVM should *never* access the guest private pages. So, we could potentially enhance the
RMPUPDATE()to check for the assigned and act accordingly.Are you thinking something along the line of this:
int
rmpupdate(struct page *page, struct rmpupdate *val){ ... /* * If page is getting assigned in the RMP entry then unmap * it from the direct map before its added in the RMP table. */ if (val.assigned) set_direct_map_invalid_noflush(page_to_virt(page), 1); ... /*
Quoted 8 lines
* If the page is getting unassigned then restore the mapping * in the direct map after its removed from the RMP table. */ if (!val.assigned) set_direct_map_default_noflush(page_to_virt(page), 1); ... }
Yep.
However, looking at the KVM usage, rmpupdate() appears to be broken. When handling a page state change, the guest can specify a 2mb page. In that case, rmpupdate() will be called once for a 2mb page, but this flow assumes a single 4kb page. The current code works because set_memory_4k() will cause the entire 2mb page to be shattered, but it's technically wrong and switching to the above would cause problems.
Re: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 39 lines · Sean Christopherson
Quoted 30 lines · Brijesh Singh
Quoted 8 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh
The
memfd_secretsuses the set_direct_map_{invalid,default}_noflush() and it is designed to remove/add the present bit in the direct map. We can't use them, because in our case the page may get accessed by the KVM (e.gkvm_guest_write,kvm_guest_mapetc).But KVM should never access a guest private page, i.e. the direct map should always be restored to PRESENT before KVM attempts to access the page.
Yes, KVM should *never* access the guest private pages. So, we could potentially enhance the
RMPUPDATE()to check for the assigned and act accordingly.Are you thinking something along the line of this:
int
rmpupdate(struct page *page, struct rmpupdate *val){ ... /* * If page is getting assigned in the RMP entry then unmap * it from the direct map before its added in the RMP table. */ if (val.assigned) set_direct_map_invalid_noflush(page_to_virt(page), 1); ... /*Quoted 8 lines
* If the page is getting unassigned then restore the mapping * in the direct map after its removed from the RMP table. */ if (!val.assigned) set_direct_map_default_noflush(page_to_virt(page), 1); ... }
Quoted 8 lines
Yep.
However, looking at the KVM usage,
rmpupdate()appears to be broken. When handling a page state change, the guest can specify a 2mb page. In that case,rmpupdate()will be called once for a 2mb page, but this flow assumes a single 4kb page. The current code works becauseset_memory_4k()will cause the entire 2mb page to be shattered, but it's technically wrong and switching to the above would cause problems.
Yep, this was just an example to make sure I am able to follow you correctly. In the actual patch I am going to read the pagesize from the RMPUPDATE structure and calculated npages for the set_direct_map_default(...). As you said it was not needed in the case of set_memory_4k() because the function force splits the large page. Whereas with set_direct_map_default(), it first checks whether the split is required, if not, then skip and update the attributes.
-Brijesh
Re: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
In reply to Brijesh SinghQuoted 9 lines · Brijesh Singh
Quoted 6 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh
The
memfd_secretsuses the set_direct_map_{invalid,default}_noflush() and it is designed to remove/add the present bit in the direct map. We can't use them, because in our case the page may get accessed by the KVM (e.gkvm_guest_write,kvm_guest_mapetc).
Quoted 6 lines
Quoted 3 lines
But KVM should never access a guest private page, i.e. the direct map should always be restored to PRESENT before KVM attempts to access the page.
Yes, KVM should *never* access the guest private pages. So, we could potentially enhance the
RMPUPDATE()to check for the assigned and act accordingly.
I think I'm not the first one suggesting it, but IMHO the best solution would be to leave direct map alone (except maybe in some debugging/development mode where you could do the unmapping to catch unexpected host accesses), and once there's a situation with host accessing a shared page of the guest, it would temporarily kmap() it outside of the direct map. Shouldn't these situations be rare enough, and already recognizable due to the need to set up the page sharing in the first place, that this approach would be feasible?
Quoted 26 lines
Are you thinking something along the line of this:
int
rmpupdate(struct page *page, struct rmpupdate *val){
...
/*
* If page is getting assigned in the RMP entry then unmap
* it from the direct map before its added in the RMP table. */
if (val.assigned)set_direct_map_invalid_noflush(page_to_virt(page), 1);...
/*
* If the page is getting unassigned then restore the mapping
* in the direct map after its removed from the RMP table. */
if (!val.assigned)set_direct_map_default_noflush(page_to_virt(page), 1);
...
}thanks
Re: [PATCH Part2 RFC v4 07/40] x86/sev: Split the physmap when adding the page in RMP table
Quoted 13 lines · Vlastimil Babka
Quoted 7 lines · Brijesh Singh
Quoted 5 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh
The
memfd_secretsuses the set_direct_map_{invalid,default}_noflush() and it is designed to remove/add the present bit in the direct map. We can't use them, because in our case the page may get accessed by the KVM (e.gkvm_guest_write,kvm_guest_mapetc).Quoted 5 lines
Quoted 3 lines
But KVM should never access a guest private page, i.e. the direct map should always be restored to PRESENT before KVM attempts to access the page.
Yes, KVM should *never* access the guest private pages. So, we could potentially enhance the
RMPUPDATE()to check for the assigned and act accordingly.
Quoted 7 lines
I think I'm not the first one suggesting it, but IMHO the best solution would be to leave direct map alone (except maybe in some debugging/development mode where you could do the unmapping to catch unexpected host accesses), and once there's a situation with host accessing a shared page of the guest, it would temporarily
kmap()it outside of the direct map. Shouldn't these situations be rare enough, and already recognizable due to the need to set up the page sharing in the first place, that this approach would be feasible?
The host accessing a guest shared is not rare, some shared pages are accessed on every VM-Entry and Exit. However, there are limited number of such pages and we could track and temporary kmap() outside of the direct map. The main challenge is when a host pages are added as 'private' in the RMP table.
e.g
page = alloc_page(GFP_KERNEL_ACCOUNT);
// firmware context page
rmp_make_firmware(page_to_pfn(page), PG_LEVEL_4K);
or
// VMSA page
rmp_make_private(page_to_pfn(page), 0, sev->asid, PG_LEVEL_4K);
The page is added as 4K in the RMP entry; If the pfn is part of the large direct map then hardware will raise an RMP violation and to resolve the fault we must split the direct map.
thanks
Quoted 27 lines
Quoted 27 lines
Are you thinking something along the line of this:
int
rmpupdate(struct page *page, struct rmpupdate *val){
...
/*
* If page is getting assigned in the RMP entry then unmap
* it from the direct map before its added in the RMP table. */
if (val.assigned)set_direct_map_invalid_noflush(page_to_virt(page), 1);...
/*
* If the page is getting unassigned then restore the mapping
* in the direct map after its removed from the RMP table. */
if (!val.assigned)set_direct_map_default_noflush(page_to_virt(page), 1);
...
}thanks
RFC PATCH v4 8/40 x86/traps: Define RMP violation #PF error code
In reply to Brijesh SinghBit 31 in the page fault-error bit will be set when processor encounters an RMP violation.
While at it, use the BIT() macro.
--- arch/x86/include/asm/trap_pf.h | 18 +++++++++++------- arch/x86/mm/fault.c | 1 + 2 files changed, 12 insertions(+), 7 deletions(-)
arch/x86/include/asm/trap_pf.h +11 -7
@@ -2,6 +2,8 @@#ifndef _ASM_X86_TRAP_PF_H#define _ASM_X86_TRAP_PF_H +#include <vdso/bits.h> /* BIT() macro */ +/* * Page fault error code bits: *
@@ -12,15 +14,17 @@* bit 4 == 1: fault was an instruction fetch * bit 5 == 1: protection keys block access * bit 15 == 1: SGX MMU page-fault +* bit 31 == 1: fault was an RMP violation */ enum x86_pf_error_code { -X86_PF_PROT =1 <<0 , -X86_PF_WRITE =1 <<1 , -X86_PF_USER =1 <<2 , -X86_PF_RSVD =1 <<3 , -X86_PF_INSTR =1 <<4 , -X86_PF_PK =1 <<5 , -X86_PF_SGX =1 <<15 , +X86_PF_PROT =BIT (0 ), +X86_PF_WRITE =BIT (1 ), +X86_PF_USER =BIT (2 ), +X86_PF_RSVD =BIT (3 ), +X86_PF_INSTR =BIT (4 ), +X86_PF_PK =BIT (5 ), +X86_PF_SGX =BIT (15 ), +X86_PF_RMP =BIT (31 ), };#endif /* _ASM_X86_TRAP_PF_H */
arch/x86/mm/fault.c +1 -0
@@ -545,6 +545,7 @@ show_fault_oops(struct pt_regs *regs, unsigned long error_code, unsigned long ad !(error_code &X86_PF_PROT ) ?"not-present page" : (error_code &X86_PF_RSVD ) ?"reserved bit violation" : (error_code &X86_PF_PK ) ?"protection keys violation" : + (error_code &X86_PF_RMP ) ?"rmp violation" : "permissions violation");if (!(error_code &X86_PF_USER ) &&user_mode (regs)) {
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 08/40] x86/traps: Define RMP violation #PF error code
Quoted 16 lines · Brijesh Singh
Bit 31 in the page fault-error bit will be set when processor encounters an RMP violation.
While at it, use the
BIT()macro.Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/trap_pf.h | 18 +++++++++++------- arch/x86/mm/fault.c | 1 + 2 files changed, 12 insertions(+), 7 deletions(-)arch/x86/include/asm/trap_pf.h +0
-0
arch/x86/include/asm/trap_pf.h line 5
Quoted 4 lines
arch/x86/include/asm/trap_pf.h +1
-0@@ -2,6 +2,8 @@#ifndef _ASM_X86_TRAP_PF_H#define _ASM_X86_TRAP_PF_H +#include <vdso/bits.h> /* BIT() macro */
What are people's thoughts on using linux/bits.h instead of vdso.bits.h, even though the vDSO version is technically sufficient? Seeing the "vdso" reference definitely made me blink slowly a few times.
Quoted 44 lines
arch/x86/include/asm/trap_pf.h +10
-7+/* * Page fault error code bits: * @@ -12,15 +14,17 @@* bit 4 == 1: fault was an instruction fetch * bit 5 == 1: protection keys block access * bit 15 == 1: SGX MMU page-fault +* bit 31 == 1: fault was an RMP violation */ enum x86_pf_error_code { -X86_PF_PROT =1 <<0 , -X86_PF_WRITE =1 <<1 , -X86_PF_USER =1 <<2 , -X86_PF_RSVD =1 <<3 , -X86_PF_INSTR =1 <<4 , -X86_PF_PK =1 <<5 , -X86_PF_SGX =1 <<15 , +X86_PF_PROT =BIT (0 ), +X86_PF_WRITE =BIT (1 ), +X86_PF_USER =BIT (2 ), +X86_PF_RSVD =BIT (3 ), +X86_PF_INSTR =BIT (4 ), +X86_PF_PK =BIT (5 ), +X86_PF_SGX =BIT (15 ), +X86_PF_RMP =BIT (31 ), };#endif /* _ASM_X86_TRAP_PF_H */ arch/x86/mm/fault.c +1
-0@@ -545,6 +545,7 @@ show_fault_oops(struct pt_regs *regs, unsigned long error_code, unsigned long ad !(error_code &X86_PF_PROT ) ?"not-present page" : (error_code &X86_PF_RSVD ) ?"reserved bit violation" : (error_code &X86_PF_PK ) ?"protection keys violation" : + (error_code &X86_PF_RMP ) ?"rmp violation" : "permissions violation");if (!(error_code &X86_PF_USER ) &&user_mode (regs)) {Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 08/40] x86/traps: Define RMP violation #PF error code
Quoted 7 lines · Sean Christopherson
Quoted 4 lines
#ifndef
_ASM_X86_TRAP_PF_H
#define_ASM_X86_TRAP_PF_H+#include <
vdso/bits.h> /*BIT()macro */What are people's thoughts on using
linux/bits.hinstead ofvdso.bits.h, even though the vDSO version is technically sufficient? Seeing the "vdso" reference definitely made me blink slowly a few times.
Ugh, missed that. Yes, that does look very weird.
I don't see any reason to use that vdso/ version instead of BIT_ULL(). I suspect I said to use BIT() when I commented on this in a previous round. If so, that was wrong.
RFC PATCH v4 9/40 x86/fault: Add support to dump RMP entry on fault
In reply to Brijesh SinghWhen SEV-SNP is enabled globally, a write from the host goes through the RMP check. If the hardware encounters the check failure, then it raises the #PF (with RMP set). Dump the RMP table to help the debug.
--- arch/x86/mm/fault.c | 79 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+)
arch/x86/mm/fault.c +79 -0
@@ -19,6 +19,7 @@#include <linux/uaccess.h> /* faulthandler_disabled() */ #include <linux/efi.h> /* efi_crash_gracefully_on_page_fault()*/ #include <linux/mm_types.h> +#include <linux/sev.h> /* snp_lookup_page_in_rmptable() */ #include <asm/cpufeature.h> /* boot_cpu_has, ... */ #include <asm/traps.h> /* dotraplinkage, ... */
@@ -502,6 +503,81 @@ static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) name, index, addr, (desc.limit0 | (desc.limit1 << 16))); } +static void dump_rmpentry (unsigned long address) +{ +struct rmpentry *e; +unsigned long pfn; +pgd_t *pgd; +pte_t *pte; +int level; + + pgd =__va (read_cr3_pa ()); + pgd +=pgd_index (address); + + pte =lookup_address_in_pgd (pgd, address, &level); +if (unlikely (!pte)) +return ; + +switch (level) { +case PG_LEVEL_4K : { + pfn =pte_pfn (*pte); +break ; + } +case PG_LEVEL_2M : { + pfn =pmd_pfn (*(pmd_t *)pte); +break ; + } +case PG_LEVEL_1G : { + pfn =pud_pfn (*(pud_t *)pte); +break ; + } +case PG_LEVEL_512G : { + pfn =p4d_pfn (*(p4d_t *)pte); +break ; + } +default : +return ; + } + + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level); +if (unlikely (!e)) +return ; + +/* +* If the RMP entry at the faulting address was not assigned, then +* dump may not provide any useful debug information. Iterate +* through the entire 2MB region, and dump the RMP entries if one +* of the bit in the RMP entry is set. +*/ +if (rmpentry_assigned (e)) { +pr_alert ("RMPEntry paddr 0x%lx [assigned=%d immutable=%d pagesize=%d gpa=0x%lx" +" asid=%d vmsa=%d validated=%d]\n" , pfn <<PAGE_SHIFT , +rmpentry_assigned (e),rmpentry_immutable (e),rmpentry_pagesize (e), +rmpentry_gpa (e),rmpentry_asid (e),rmpentry_vmsa (e), +rmpentry_validated (e)); + +pr_alert ("RMPEntry paddr 0x%lx %016llx %016llx\n" , pfn <<PAGE_SHIFT , + e->high, e->low); + }else { +unsigned long pfn_end; + + pfn = pfn & ~0x1ff ; + pfn_end = pfn +PTRS_PER_PMD ; + +while (pfn < pfn_end) { + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level); + +if (unlikely (!e)) +return ; + +if (e->low || e->high) +pr_alert ("RMPEntry paddr 0x%lx: %016llx %016llx\n" , + pfn <<PAGE_SHIFT , e->high, e->low); + pfn++; + } + } +} +static void show_fault_oops (struct pt_regs *regs,unsigned long error_code,unsigned long address) {
@@ -578,6 +654,9 @@ show_fault_oops(struct pt_regs *regs, unsigned long error_code, unsigned long ad }dump_pagetable (address); + +if (error_code &X86_PF_RMP ) +dump_rmpentry (address); }static noinline void
Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 09/40] x86/fault: Add support to dump RMP entry on fault
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 507
Quoted 6 lines
arch/x86/mm/fault.c +2
-0@@ -502,6 +503,81 @@ static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) name, index, addr, (desc.limit0 | (desc.limit1 << 16))); } +static void dump_rmpentry (unsigned long address) +{
A comment on this sucker would be nice. I *think* this must be a kernel virtual address. Reflecting that into the naming or a comment would be nice.
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 519
Quoted 12 lines
arch/x86/mm/fault.c +12
-0+struct rmpentry *e; +unsigned long pfn; +pgd_t *pgd; +pte_t *pte; +int level; + + pgd =__va (read_cr3_pa ()); + pgd +=pgd_index (address); + + pte =lookup_address_in_pgd (pgd, address, &level); +if (unlikely (!pte)) +return ;
It's a little annoying this is doing *another* separate page walk. Don't we already do this for dumping the page tables themselves at oops time?
Also, please get rid of all of the likely/unlikely()s in your patches. They are pure noise unless you have specific knowledge of the compiler getting something so horribly wrong that it affects real-world performance.
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 525
Quoted 5 lines
arch/x86/mm/fault.c +5
-0+switch (level) { +case PG_LEVEL_4K : { + pfn =pte_pfn (*pte); +break ; + }
These superfluous brackets are really strange looking. Could you remove them, please?
Quoted 7 lines
arch/x86/mm/fault.c +7
-0+case PG_LEVEL_2M : { + pfn =pmd_pfn (*(pmd_t *)pte); +break ; + } +case PG_LEVEL_1G : { + pfn =pud_pfn (*(pud_t *)pte); +break ;
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 542
Quoted 10 lines
arch/x86/mm/fault.c +10
-0+ } +case PG_LEVEL_512G : { + pfn =p4d_pfn (*(p4d_t *)pte); +break ; + } +default : +return ; + } + + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level);
So, lookup_address_in_pgd() looks to me like it will return pretty random page table entries as long as the entry isn't p{gd,4d,ud,md,te}_none(). It can certainly return !p*_present() entries. Those are *NOT* safe to call pfn_to_page() on.
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 551
Quoted 9 lines
arch/x86/mm/fault.c +9
-0+if (unlikely (!e)) +return ; + +/* +* If the RMP entry at the faulting address was not assigned, then +* dump may not provide any useful debug information. Iterate +* through the entire 2MB region, and dump the RMP entries if one +* of the bit in the RMP entry is set. +*/
Some of this comment should be moved down to the loop itself.
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 560
Quoted 9 lines
arch/x86/mm/fault.c +9
-0+if (rmpentry_assigned (e)) { +pr_alert ("RMPEntry paddr 0x%lx [assigned=%d immutable=%d pagesize=%d gpa=0x%lx" +" asid=%d vmsa=%d validated=%d]\n" , pfn <<PAGE_SHIFT , +rmpentry_assigned (e),rmpentry_immutable (e),rmpentry_pagesize (e), +rmpentry_gpa (e),rmpentry_asid (e),rmpentry_vmsa (e), +rmpentry_validated (e)); + +pr_alert ("RMPEntry paddr 0x%lx %016llx %016llx\n" , pfn <<PAGE_SHIFT , + e->high, e->low);
Could you please include an entire oops in the changelog that also includes this information? It would be really nice if this was at least consistent in style to the stuff around it.
Also, how much of this stuff like rmpentry_asid() is duplicated in the "raw" dump of e->high and e->low?
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 564
Quoted 4 lines
arch/x86/mm/fault.c +4
-0+ }else { +unsigned long pfn_end; + + pfn = pfn & ~0x1ff ;
There's a nice magic number. Why not:
pfn = pfn & ~(PTRS_PER_PMD-1);
?
This also needs a comment about *WHY* this case is looking at a 2MB region.
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 575
Quoted 11 lines
arch/x86/mm/fault.c +11
-0+ pfn_end = pfn +PTRS_PER_PMD ; + +while (pfn < pfn_end) { + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level); + +if (unlikely (!e)) +return ; + +if (e->low || e->high) +pr_alert ("RMPEntry paddr 0x%lx: %016llx %016llx\n" , + pfn <<PAGE_SHIFT , e->high, e->low);
Why does this dump "raw" RMP entries while the above stuff filters them through a bunch of helper macros?
Quoted 19 lines
arch/x86/mm/fault.c +8
-0+ pfn++; + } + } +} +static void show_fault_oops (struct pt_regs *regs,unsigned long error_code,unsigned long address) {@@ -578,6 +654,9 @@ show_fault_oops(struct pt_regs *regs, unsigned long error_code, unsigned long ad }dump_pagetable (address); + +if (error_code &X86_PF_RMP ) +dump_rmpentry (address); }static noinline void
Re: [PATCH Part2 RFC v4 09/40] x86/fault: Add support to dump RMP entry on fault
Hi Dave,
Quoted 10 lines · Dave Hansen
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 507
Quoted 6 lines
arch/x86/mm/fault.c +2
-0@@ -502,6 +503,81 @@ static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) name, index, addr, (desc.limit0 | (desc.limit1 << 16))); } +static void dump_rmpentry (unsigned long address) +{A comment on this sucker would be nice. I *think* this must be a kernel virtual address. Reflecting that into the naming or a comment would be nice.
Ack, I will add some comment.
Quoted 18 lines
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 519
Quoted 13 lines
arch/x86/mm/fault.c +12
-0+struct rmpentry *e; +unsigned long pfn; +pgd_t *pgd; +pte_t *pte; +int level; + + pgd =__va (read_cr3_pa ()); + pgd +=pgd_index (address); + + pte =lookup_address_in_pgd (pgd, address, &level); +if (unlikely (!pte)) +return ;It's a little annoying this is doing *another* separate page walk. Don't we already do this for dumping the page tables themselves at oops time?
Yes, we already do the walk in oops function, I'll extend the dump_rmpentry() to use the level from the oops to avoid the duplicate walk.
Quoted 4 lines
Also, please get rid of all of the likely/unlikely()s in your patches. They are pure noise unless you have specific knowledge of the compiler getting something so horribly wrong that it affects real-world performance.
Quoted 8 lines
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 525
Quoted 5 lines
arch/x86/mm/fault.c +5
-0+switch (level) { +case PG_LEVEL_4K : { + pfn =pte_pfn (*pte); +break ; + }These superfluous brackets are really strange looking. Could you remove them, please?
Noted.
Quoted 15 lines
Quoted 15 lines
arch/x86/mm/fault.c +14
-0+case PG_LEVEL_2M : { + pfn =pmd_pfn (*(pmd_t *)pte); +break ; + } +case PG_LEVEL_1G : { + pfn =pud_pfn (*(pud_t *)pte); +break ; + } +case PG_LEVEL_512G : { + pfn =p4d_pfn (*(p4d_t *)pte); +break ; + } +default : +return ;
Quoted 9 lines
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 542
Quoted 3 lines
arch/x86/mm/fault.c +3
-0+ } + + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level);So,
lookup_address_in_pgd()looks to me like it will return pretty random page table entries as long as the entry isn't p{gd,4d,ud,md,te}_none(). It can certainly return !p*_present() entries. Those are *NOT* safe to callpfn_to_page()on.
I will add some checks to make sure that we are accessing only safe pfn's.
Quoted 11 lines
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 551
Quoted 9 lines
arch/x86/mm/fault.c +9
-0+if (unlikely (!e)) +return ; + +/* +* If the RMP entry at the faulting address was not assigned, then +* dump may not provide any useful debug information. Iterate +* through the entire 2MB region, and dump the RMP entries if one +* of the bit in the RMP entry is set. +*/ Some of this comment should be moved down to the loop itself.
Noted.
Quoted 14 lines
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 560
Quoted 10 lines
arch/x86/mm/fault.c +9
-0+if (rmpentry_assigned (e)) { +pr_alert ("RMPEntry paddr 0x%lx [assigned=%d immutable=%d pagesize=%d gpa=0x%lx" +" asid=%d vmsa=%d validated=%d]\n" , pfn <<PAGE_SHIFT , +rmpentry_assigned (e),rmpentry_immutable (e),rmpentry_pagesize (e), +rmpentry_gpa (e),rmpentry_asid (e),rmpentry_vmsa (e), +rmpentry_validated (e)); + +pr_alert ("RMPEntry paddr 0x%lx %016llx %016llx\n" , pfn <<PAGE_SHIFT , + e->high, e->low);Could you please include an entire oops in the changelog that also includes this information? It would be really nice if this was at least consistent in style to the stuff around it.
Here is one example: (in this case page was immutable and HV attempted to write to it).
BUG: unable to handle page fault for address: ffff98c78ee00000
#PF: supervisor write access in kernel mode
#PF: error_code(0x80000003) - rmp violation
PGD 304b201067 P4D 304b201067 PUD 20c7f06063 PMD 20c8976063 PTE 80000020cee00163 RMPEntry paddr 0x20cee00000 [assigned=1 immutable=1 pagesize=0 gpa=0x0 asid=0 vmsa=0 validated=0] RMPEntry paddr 0x20cee00000 000000000000000f 8000000000000ffd
Quoted 4 lines
Also, how much of this stuff like
rmpentry_asid()is duplicated in the "raw" dump ofe->highande->low?
Most of the rmpentry_xxx assessors read the e->low. The RMP entry is a 16-bytes. AMD APM defines only a few bits and keeps everything else reserved. We are in the process of updating APM to document few more bits. I am not adding assessors for the undocumented fields. Until then, we dump the entire 16-bytes.
I agree that we are duplicating the information. I can live with just a raw dump. That means anyone who is debugging the crash will look at the APM to decode the fields.
Quoted 10 lines
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 564
Quoted 4 lines
arch/x86/mm/fault.c +4
-0+ }else { +unsigned long pfn_end; + + pfn = pfn & ~0x1ff ;There's a nice magic number. Why not:
pfn = pfn & ~(PTRS_PER_PMD-1);?
Noted.
Quoted 3 lines
This also needs a comment about *WHY* this case is looking at a 2MB region.
Actually the comment above says why we are looking for the 2MB region. Let me rearrange the comment block so that its more clear.
The reason for iterating through 2MB region is; if the faulting address is not assigned in the RMP table, and page table walk level is 2MB then one of entry within the large page is the root cause of the fault. Since we don't know which entry hence I dump all the non-zero entries.
Quoted 6 lines
Quoted 6 lines
arch/x86/mm/fault.c +6
-0+ pfn_end = pfn +PTRS_PER_PMD ; + +while (pfn < pfn_end) { + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level); + +if (unlikely (!e))
Quoted 9 lines
arch/x86/mm/fault.c static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index) · line 575
Quoted 5 lines
arch/x86/mm/fault.c +5
-0+return ; + +if (e->low || e->high) +pr_alert ("RMPEntry paddr 0x%lx: %016llx %016llx\n" , + pfn <<PAGE_SHIFT , e->high, e->low);Why does this dump "raw" RMP entries while the above stuff filters them through a bunch of helper macros?
There are two cases which we need to consider:
1) the faulting page is a guest private (aka assigned)
2) the faulting page is a hypervisor (aka shared)
We will be primarily seeing #1. In this case, we know its a assigned page, and we can decode the fields.
The #2 will happen in rare conditions, if it happens, one of the undocumented bit in the RMP entry can provide us some useful information hence we dump the raw values.
-Brijesh
Re: [PATCH Part2 RFC v4 09/40] x86/fault: Add support to dump RMP entry on fault
On 7/8/21 8:02 AM, Brijesh Singh wrote:
...
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
+ pgd = __va(read_cr3_pa());
+ pgd +=pgd_index(address);
+
+ pte =lookup_address_in_pgd(pgd, address, &level); + if (unlikely(!pte))
+ return;
Quoted 6 lines
Quoted 3 lines
It's a little annoying this is doing *another* separate page walk. Don't we already do this for dumping the page tables themselves at oops time?
Yes, we already do the walk in oops function, I'll extend the
dump_rmpentry()to use the level from the oops to avoid the duplicate walk.
I was even thinking that you could use the pmd/pte entries that come from the walk in dump_pagetable().
BTW, I think the snp_lookup_page_in_rmptable() interface is probably wrong. It takes a 'struct page':
+struct rmpentry *snp_lookup_page_in_rmptable(struct page *page, int *level)
but then immediately converts it to a paddr:
Review
Quoted 1 line
(quoted diff) +1
-0+ unsigned long phys = page_to_pfn(page) << PAGE_SHIFT;
If you just had it take a paddr, you wouldn't have to mess with all of this pfn_valid() and phys_to_page() error checking.
Quoted 18 lines
Quoted 18 lines
Quoted 17 lines
+ case
PG_LEVEL_2M: {
+ pfn =pmd_pfn(*(pmd_t *)pte);
+ break;
+ }
+ casePG_LEVEL_1G: {
+ pfn =pud_pfn(*(pud_t *)pte);
+ break;
+ }
+ casePG_LEVEL_512G: {
+ pfn =p4d_pfn(*(p4d_t *)pte);
+ break;
+ }
+ default:
+ return;
+ }
+
+ e =snp_lookup_page_in_rmptable(pfn_to_page(pfn), &level);
Quoted 7 lines
Quoted 5 lines
So,
lookup_address_in_pgd()looks to me like it will return pretty random page table entries as long as the entry isn't p{gd,4d,ud,md,te}_none(). It can certainly return !p*_present() entries. Those are *NOT* safe to callpfn_to_page()on.I will add some checks to make sure that we are accessing only safe pfn's.
Or fix the snp_lookup_page_in_rmptable() interface, please.
Quoted 17 lines
Quoted 13 lines
Quoted 4 lines
+ if (
rmpentry_assigned(e)) {
+ pr_alert("RMPEntry paddr 0x%lx [assigned=%d immutable=%d pagesize=%d gpa=0x%lx"
+ " asid=%d vmsa=%d validated=%d]\n", pfn <<PAGE_SHIFT,Quoted 8 lines
+
rmpentry_assigned(e),rmpentry_immutable(e),rmpentry_pagesize(e),
+rmpentry_gpa(e),rmpentry_asid(e),rmpentry_vmsa(e), +rmpentry_validated(e));
+
+ pr_alert("RMPEntry paddr 0x%lx %016llx %016llx\n", pfn <<PAGE_SHIFT,
+e->high,e->low);Quoted 3 lines
Could you please include an entire oops in the changelog that also includes this information? It would be really nice if this was at least consistent in style to the stuff around it.
Quoted 6 lines
Here is one example: (in this case page was immutable and HV attempted to write to it).
BUG: unable to handle page fault for address: ffff98c78ee00000#PF: supervisor write access in kernel mode
#PF:error_code(0x80000003)- rmp violation
Let's capitalize "RMP" here, please.
Quoted 5 lines
PGD
304b201067P4D304b201067PUD20c7f06063PMD20c8976063PTE80000020cee00163
RMPEntry paddr0x20cee00000[assigned=1 immutable=1 pagesize=0 gpa=0x0 asid=0 vmsa=0 validated=0]
RMPEntry paddr0x20cee00000000000000000000f8000000000000ffd
That's a good example, thanks!
But, it does make me think that we shouldn't be spitting out "immutable". Should we call it "readonly" or something so that folks have a better chance of figuring out what's wrong? Even better, should we be looking specifically for X86_PF_RMP *and* immutable=1 and spitting out something in english about it?
This also *looks* to be spitting out the same "RMPEntry paddr 0x20cee00000" more than once. Maybe we should just indent the extra entries instead of repeating things. The high/low are missing a "0x" prefix, they also don't have any kind of text label.
Quoted 9 lines
Quoted 2 lines
Also, how much of this stuff like
rmpentry_asid()is duplicated in the "raw" dump ofe->highande->low?Most of the
rmpentry_xxxassessors read thee->low. The RMP entry is a 16-bytes. AMD APM defines only a few bits and keeps everything else reserved. We are in the process of updating APM to document few more bits. I am not adding assessors for the undocumented fields. Until then, we dump the entire 16-bytes.
Quoted 3 lines
I agree that we are duplicating the information. I can live with just a raw dump. That means anyone who is debugging the crash will look at the APM to decode the fields.
I actually really like processing the fields. I think it's a good investment to make the error messages as self-documenting as possible and not require the poor souls who are decoding oopses to also keep each vendor's architecture manuals at hand.
Quoted 11 lines
Quoted 3 lines
This also needs a comment about *WHY* this case is looking at a 2MB region.
Actually the comment above says why we are looking for the 2MB region. Let me rearrange the comment block so that its more clear.
The reason for iterating through 2MB region is; if the faulting address is not assigned in the RMP table, and page table walk level is 2MB then one of entry within the large page is the root cause of the fault. Since we don't know which entry hence I dump all the non-zero entries.
Logically you can figure this out though, right? Why throw 511 entries at the console when we *know* they're useless?
Quoted 17 lines
Quoted 6 lines
Quoted 6 lines
+
pfn_end= pfn +PTRS_PER_PMD;arch/x86/mm/fault.c +5
-0+ + while (pfn < pfn_end) { + e = snp_lookup_page_in_rmptable(pfn_to_page(pfn), &level); + + if (unlikely(!e))Quoted 8 lines
Quoted 5 lines
+ return;
+
+ if (e->low||e->high)
+ pr_alert("RMPEntry paddr 0x%lx: %016llx %016llx\n", + pfn <<PAGE_SHIFT,e->high,e->low);Why does this dump "raw" RMP entries while the above stuff filters them through a bunch of helper macros?
There are two cases which we need to consider:
Quoted 7 lines
1) the faulting page is a guest private (aka assigned)
2) the faulting page is a hypervisor (aka shared)We will be primarily seeing #1. In this case, we know its a assigned page, and we can decode the fields.
The #2 will happen in rare conditions,
What rare conditions?
Quoted 2 lines
if it happens, one of the undocumented bit in the RMP entry can provide us some useful information hence we dump the raw values.
You're saying that there are things that can cause RMP faults that aren't documented? That's rather nasty for your users, don't you think?
I'd be fine if you want to define a mask of unknown bits and spit out to the users that some unknown bits are set.
Re: [PATCH Part2 RFC v4 09/40] x86/fault: Add support to dump RMP entry on fault
Quoted 6 lines · Dave Hansen
I was even thinking that you could use the pmd/pte entries that come from the walk in
dump_pagetable().BTW, I think the
snp_lookup_page_in_rmptable()interface is probably wrong. It takes a 'struct page':
In some cases the caller already have 'struct page' so it was easier on them. I can change it to snp_lookup_pfn_in_rmptable() to simplify the things. In the cases where the caller already have 'struct page' will simply do page_to_pfn().
Quoted 8 lines
+struct rmpentry *snp_lookup_page_in_rmptable(struct page *page, int *level)
but then immediately converts it to a paddr:
Review
Quoted 1 line
(quoted diff) +1
-0+ unsigned long phys = page_to_pfn(page) << PAGE_SHIFT;If you just had it take a paddr, you wouldn't have to mess with all of this
pfn_valid()andphys_to_page()error checking.
Noted.
Quoted 2 lines
Or fix the
snp_lookup_page_in_rmptable()interface, please.
Yes.
Quoted 2 lines
Let's capitalize "RMP" here, please.
Noted.
Quoted 4 lines
Quoted 4 lines
PGD
304b201067P4D304b201067PUD20c7f06063PMD20c8976063PTE80000020cee00163
RMPEntry paddr0x20cee00000[assigned=1 immutable=1 pagesize=0 gpa=0x0
^^^^^^^^^^
Quoted 11 lines
Quoted 2 lines
asid=0 vmsa=0 validated=0]
RMPEntry paddr0x20cee00000000000000000000f8000000000000ffdThat's a good example, thanks!
But, it does make me think that we shouldn't be spitting out "immutable". Should we call it "readonly" or something so that folks have a better chance of figuring out what's wrong? Even better, should we be looking specifically for
X86_PF_RMP*and* immutable=1 and spitting out something in english about it?
A write to an assigned page will cause the RMP violation. In this case, the page happen to be firmware page hence the immutable bit was also set. I am trying to use the field name as documented in the APM and SEV-SNP firmware spec.
Quoted 5 lines
This also *looks* to be spitting out the same "RMPEntry paddr
0x20cee00000" more than once. Maybe we should just indent the extra entries instead of repeating things. The high/low are missing a "0x" prefix, they also don't have any kind of text label.
Noted, I will fix it.
Quoted 6 lines
I actually really like processing the fields. I think it's a good investment to make the error messages as self-documenting as possible and not require the poor souls who are decoding oopses to also keep each vendor's architecture manuals at hand.
Sounds good, I will keep it as-is.
Quoted 8 lines
Quoted 5 lines
The reason for iterating through 2MB region is; if the faulting address is not assigned in the RMP table, and page table walk level is 2MB then one of entry within the large page is the root cause of the fault. Since we don't know which entry hence I dump all the non-zero entries.
Logically you can figure this out though, right? Why throw 511 entries at the console when we *know* they're useless?
Logically its going to be tricky to figure out which exact entry caused the fault, hence I dump any non-zero entry. I understand it may dump some useless.
Quoted 5 lines
Quoted 5 lines
There are two cases which we need to consider:
1) the faulting page is a guest private (aka assigned)
2) the faulting page is a hypervisor (aka shared)
Quoted 7 lines
Quoted 4 lines
We will be primarily seeing #1. In this case, we know its a assigned page, and we can decode the fields.
The #2 will happen in rare conditions,
What rare conditions?
One such condition is RMP "in-use" bit is set; see the patch 20/40. After applying the patch we should not see "in-use" bit set. If we run into similar issues, a full RMP dump will greatly help debug.
Quoted 5 lines
Quoted 2 lines
if it happens, one of the undocumented bit in the RMP entry can provide us some useful information hence we dump the raw values.
You're saying that there are things that can cause RMP faults that aren't documented? That's rather nasty for your users, don't you think?
The "in-use" bit in the RMP entry caught me off guard. The AMD APM does says that hardware sets in-use bit but it *never* explained in the detail on how to check if the fault was due to in-use bit in the RMP table. As I said, the documentation folks will be updating the RMP entry to document the in-use bit. I hope we will not see any other undocumented surprises, I am keeping my finger cross :)
Quoted 3 lines
I'd be fine if you want to define a mask of unknown bits and spit out to the users that some unknown bits are set.
Re: [PATCH Part2 RFC v4 09/40] x86/fault: Add support to dump RMP entry on fault
Quoted 6 lines · Brijesh Singh
Quoted 5 lines · Dave Hansen
Quoted 4 lines
The reason for iterating through 2MB region is; if the faulting address is not assigned in the RMP table, and page table walk level is 2MB then one of entry within the large page is the root cause of the fault. Since we don't know which entry hence I dump all the non-zero entries.
Quoted 6 lines
Quoted 2 lines
Logically you can figure this out though, right? Why throw 511 entries at the console when we *know* they're useless?
Logically its going to be tricky to figure out which exact entry caused the fault, hence I dump any non-zero entry. I understand it may dump some useless.
What's tricky about it?
Sure, there's a possibility that more than one entry could contribute to a fault. But, you always know *IF* an entry could contribute to a fault.
I'm fine if you run through the logic, don't find a known reason (specific RMP entry) for the fault, and dump the whole table in that case. But, unconditionally polluting the kernel log with noise isn't very nice for debugging.
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
There are two cases which we need to consider:
1) the faulting page is a guest private (aka assigned)
2) the faulting page is a hypervisor (aka shared)We will be primarily seeing #1. In this case, we know its a assigned page, and we can decode the fields.
Quoted 7 lines
Quoted 3 lines
Quoted 1 line
The #2 will happen in rare conditions,
What rare conditions?
One such condition is RMP "in-use" bit is set; see the patch 20/40. After applying the patch we should not see "in-use" bit set. If we run into similar issues, a full RMP dump will greatly help debug.
OK... so dump the "in-use" bit here if you see it.
Quoted 11 lines
Quoted 4 lines
Quoted 2 lines
if it happens, one of the undocumented bit in the RMP entry can provide us some useful information hence we dump the raw values.
You're saying that there are things that can cause RMP faults that aren't documented? That's rather nasty for your users, don't you think?
The "in-use" bit in the RMP entry caught me off guard. The AMD APM does says that hardware sets in-use bit but it *never* explained in the detail on how to check if the fault was due to in-use bit in the RMP table. As I said, the documentation folks will be updating the RMP entry to document the in-use bit. I hope we will not see any other undocumented surprises, I am keeping my finger cross :)
Oh, ok. That sounds fine. Documentation is out of date all the time.
Re: [PATCH Part2 RFC v4 09/40] x86/fault: Add support to dump RMP entry on fault
On 7/8/21 11:58 AM, Dave Hansen wrote:>> Logically its going to be tricky to figure out which exact entry caused
Quoted 5 lines
Quoted 2 lines
the fault, hence I dump any non-zero entry. I understand it may dump some useless.
What's tricky about it?
Quoted 7 lines
Sure, there's a possibility that more than one entry could contribute to a fault. But, you always know *IF* an entry could contribute to a fault.
I'm fine if you run through the logic, don't find a known reason (specific RMP entry) for the fault, and dump the whole table in that case. But, unconditionally polluting the kernel log with noise isn't very nice for debugging.
The tricky part is to determine which undocumented bit to check to know that we should stop dump. I can go with your suggestion that first try with the known reasons and fallback to dump whole table for unknown reasons only.
thanks
Re: [PATCH Part2 RFC v4 09/40] x86/fault: Add support to dump RMP entry on fault
Quoted 15 lines · Brijesh Singh
On 7/8/21 11:58 AM, Dave Hansen wrote:>> Logically its going to be tricky to figure out which exact entry caused
Quoted 5 lines
Quoted 2 lines
the fault, hence I dump any non-zero entry. I understand it may dump some useless.
What's tricky about it?
Quoted 7 lines
Sure, there's a possibility that more than one entry could contribute to a fault. But, you always know *IF* an entry could contribute to a fault.
I'm fine if you run through the logic, don't find a known reason (specific RMP entry) for the fault, and dump the whole table in that case. But, unconditionally polluting the kernel log with noise isn't very nice for debugging.
Quoted 4 lines
The tricky part is to determine which undocumented bit to check to know that we should stop dump. I can go with your suggestion that first try with the known reasons and fallback to dump whole table for unknown reasons only.
You *can't* stop because of undocumented bits. Fundamentally. You literally don't know if the bit means "this caused a fault" versus "this definitely couldn't cause a fault".
Basically, if we get to the point of dumping the whole table, we should also spit out an error message saying that the kernel is dazed and confused and can't figure out why the hardware caused a fault. Then, dump out the whole table so that the "hardware" folks can have a look.
RFC PATCH v4 10/40 x86/fault: Add support to handle the RMP fault for user address
In reply to Brijesh SinghWhen SEV-SNP is enabled globally, a write from the host goes through the RMP check. When the host writes to pages, hardware checks the following conditions at the end of page walk:
1. Assigned bit in the RMP table is zero (i.e page is shared).
2. If the page table entry that gives the sPA indicates that the target page size is a large page, then all RMP entries for the 4KB constituting pages of the target must have the assigned bit 0.
3. Immutable bit in the RMP table is not zero.
The hardware will raise page fault if one of the above conditions is not met. Try resolving the fault instead of taking fault again and again. If the host attempts to write to the guest private memory then send the SIGBUG signal to kill the process. If the page level between the host and RMP entry does not match, then split the address to keep the RMP and host page levels in sync.
--- arch/x86/mm/fault.c | 69 +++++++++++++++++++++++++++++++++++++++++++++ include/linux/mm.h | 6 +++- mm/memory.c | 13 +++++++++ 3 files changed, 87 insertions(+), 1 deletion(-)
arch/x86/mm/fault.c +69 -0
@@ -1281,6 +1281,58 @@ do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, }NOKPROBE_SYMBOL (do_kern_addr_fault); +#define RMP_FAULT_RETRY 0 +#define RMP_FAULT_KILL 1 +#define RMP_FAULT_PAGE_SPLIT 2 + +static inline size_t pages_per_hpage (int level) +{ +return page_level_size (level) /PAGE_SIZE ; +} + +static int handle_user_rmp_page_fault (unsigned long hw_error_code,unsigned long address) +{ +unsigned long pfn, mask; +int rmp_level, level; +struct rmpentry *e; +pte_t *pte; + +if (unlikely (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))) +return RMP_FAULT_KILL ; + +/* Get the native page level */ + pte =lookup_address_in_mm (current->mm, address, &level); +if (unlikely (!pte)) +return RMP_FAULT_KILL ; + + pfn =pte_pfn (*pte); +if (level >PG_LEVEL_4K ) { + mask =pages_per_hpage (level) -pages_per_hpage (level -1 ); + pfn |= (address >>PAGE_SHIFT ) & mask; + } + +/* Get the page level from the RMP entry. */ + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &rmp_level); +if (!e) +return RMP_FAULT_KILL ; + +/* +* Check if the RMP violation is due to the guest private page access. +* We can not resolve this RMP fault, ask to kill the guest. +*/ +if (rmpentry_assigned (e)) +return RMP_FAULT_KILL ; + +/* +* The backing page level is higher than the RMP page level, request +* to split the page. +*/ +if (level > rmp_level) +return RMP_FAULT_PAGE_SPLIT ; + +return RMP_FAULT_RETRY ; +} +/* * Handle faults in the user portion of the address space. Nothing in here * should check X86_PF_USER without a specific justification: for almost
@@ -1298,6 +1350,7 @@ void do_user_addr_fault(struct pt_regs *regs,struct task_struct *tsk;struct mm_struct *mm;vm_fault_t fault; +int ret;unsigned int flags =FAULT_FLAG_DEFAULT ; tsk = current;
@@ -1378,6 +1431,22 @@ void do_user_addr_fault(struct pt_regs *regs,if (error_code &X86_PF_INSTR ) flags |=FAULT_FLAG_INSTRUCTION ; +/* +* If its an RMP violation, try resolving it. +*/ +if (error_code &X86_PF_RMP ) { + ret =handle_user_rmp_page_fault (error_code, address); +if (ret ==RMP_FAULT_PAGE_SPLIT ) { + flags |=FAULT_FLAG_PAGE_SPLIT ; + }else if (ret ==RMP_FAULT_KILL ) { + fault |=VM_FAULT_SIGBUS ; +do_sigbus (regs, error_code, address, fault); +return ; + }else { +return ; + } + } +#ifdef CONFIG_X86_64 /* * Faults in the vsyscall page might need emulation. The
include/linux/mm.h +5 -1
@@ -450,6 +450,8 @@ extern pgprot_t protection_map[16];* @FAULT_FLAG_REMOTE: The fault is not for current task/mm. * @FAULT_FLAG_INSTRUCTION: The fault was during an instruction fetch. * @FAULT_FLAG_INTERRUPTIBLE: The fault can be interrupted by non-fatal signals. +* @FAULT_FLAG_PAGE_SPLIT: The fault was due page size mismatch, split the +* region to smaller page size and retry. * * About @FAULT_FLAG_ALLOW_RETRY and @FAULT_FLAG_TRIED: we can specify * whether we would allow page faults to retry by specifying these two
@@ -481,6 +483,7 @@ enum fault_flag {FAULT_FLAG_REMOTE =1 <<7 ,FAULT_FLAG_INSTRUCTION =1 <<8 ,FAULT_FLAG_INTERRUPTIBLE =1 <<9 , + FAULT_FLAG_PAGE_SPLIT = 1 << 10, };/*
@@ -520,7 +523,8 @@ static inline bool fault_flag_allow_retry_first(enum fault_flag flags) { FAULT_FLAG_USER, "USER" }, \ { FAULT_FLAG_REMOTE, "REMOTE" }, \ { FAULT_FLAG_INSTRUCTION, "INSTRUCTION" }, \ - { FAULT_FLAG_INTERRUPTIBLE, "INTERRUPTIBLE" } + { FAULT_FLAG_INTERRUPTIBLE, "INTERRUPTIBLE" }, \ + { FAULT_FLAG_PAGE_SPLIT, "PAGESPLIT" }/* * vm_fault is filled by the pagefault handler and passed to the vma's
mm/memory.c +13 -0
@@ -4407,6 +4407,15 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf)return 0 ; } +static int handle_split_page_fault (struct vm_fault *vmf) +{ +if (!IS_ENABLED (CONFIG_AMD_MEM_ENCRYPT )) +return VM_FAULT_SIGBUS ; + +__split_huge_pmd (vmf->vma, vmf->pmd, vmf->address, false,NULL ); +return 0 ; +} +/* * By the time we get here, we already hold the mm semaphore *
@@ -4484,6 +4493,10 @@ static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,pmd_migration_entry_wait (mm, vmf.pmd);return 0 ; } + +if (flags &FAULT_FLAG_PAGE_SPLIT ) +return handle_split_page_fault (&vmf); +if (pmd_trans_huge (orig_pmd) ||pmd_devmap (orig_pmd)) {if (pmd_protnone (orig_pmd) &&vma_is_accessible (vma))return do_huge_pmd_numa_page (&vmf, orig_pmd);
Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Oh, here's the THP code. The subject just changed.
Quoted 10 lines · Brijesh Singh
When SEV-SNP is enabled globally, a write from the host goes through the RMP check. When the host writes to pages, hardware checks the following conditions at the end of page walk:
1. Assigned bit in the RMP table is zero (i.e page is shared).
2. If the page table entry that gives the sPA indicates that the target page size is a large page, then all RMP entries for the 4KB constituting pages of the target must have the assigned bit 0.
3. Immutable bit in the RMP table is not zero.
Quoted 4 lines
The hardware will raise page fault if one of the above conditions is not met. Try resolving the fault instead of taking fault again and again. If the host attempts to write to the guest private memory then send the SIGBUG signal to kill the process. If the page level between the host and
"SIGBUG"?
Quoted 26 lines
RMP entry does not match, then split the address to keep the RMP and host page levels in sync.
--- arch/x86/mm/fault.c | 69 +++++++++++++++++++++++++++++++++++++++++++++ include/linux/mm.h | 6 +++- mm/memory.c | 13 +++++++++ 3 files changed, 87 insertions(+), 1 deletion(-)arch/x86/mm/fault.c +8
-0@@ -1281,6 +1281,58 @@ do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, }NOKPROBE_SYMBOL (do_kern_addr_fault); +#define RMP_FAULT_RETRY 0 +#define RMP_FAULT_KILL 1 +#define RMP_FAULT_PAGE_SPLIT 2 + +static inline size_t pages_per_hpage (int level) +{ +return page_level_size (level) /PAGE_SIZE ; +}
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1301
Quoted 10 lines
arch/x86/mm/fault.c +10
-0+ +static int handle_user_rmp_page_fault (unsigned long hw_error_code,unsigned long address) +{ +unsigned long pfn, mask; +int rmp_level, level; +struct rmpentry *e; +pte_t *pte; + +if (unlikely (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))) +return RMP_FAULT_KILL ;
Shouldn't this be a WARN_ON_ONCE()? How can we get RMP faults without SEV-SNP?
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1306
Quoted 4 lines
arch/x86/mm/fault.c +4
-0+/* Get the native page level */ + pte =lookup_address_in_mm (current->mm, address, &level); +if (unlikely (!pte)) +return RMP_FAULT_KILL ;
What would this mean? There was an RMP fault on a non-present page? How could that happen? What if there was a race between an unmapping event and the RMP fault delivery?
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1312
Quoted 5 lines
arch/x86/mm/fault.c +5
-0+ pfn =pte_pfn (*pte); +if (level >PG_LEVEL_4K ) { + mask =pages_per_hpage (level) -pages_per_hpage (level -1 ); + pfn |= (address >>PAGE_SHIFT ) & mask; + }
This looks inherently racy. What happens if there are two parallel RMP faults on the same 2M page. One of them splits the page tables, the other gets a fault for an already-split page table.
Is that handled here somehow?
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1317
Quoted 4 lines
arch/x86/mm/fault.c +4
-0+/* Get the page level from the RMP entry. */ + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &rmp_level); +if (!e) +return RMP_FAULT_KILL ;
The snp_lookup_page_in_rmptable() failure cases looks WARN-worthly. Either you're doing a lookup for something not *IN* the RMP table, or you don't support SEV-SNP, in which case you shouldn't be in this code in the first place.
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1324
Quoted 6 lines
arch/x86/mm/fault.c +6
-0+/* +* Check if the RMP violation is due to the guest private page access. +* We can not resolve this RMP fault, ask to kill the guest. +*/ +if (rmpentry_assigned (e)) +return RMP_FAULT_KILL ;
No "We's", please. Speak in imperative voice.
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1331
Quoted 6 lines
arch/x86/mm/fault.c +6
-0+/* +* The backing page level is higher than the RMP page level, request +* to split the page. +*/ +if (level > rmp_level) +return RMP_FAULT_PAGE_SPLIT ;
This can theoretically trigger on a hugetlbfs page. Right?
I thought I asked about this before... more below...
arch/x86/mm/fault.c void
Quoted 15 lines
arch/x86/mm/fault.c +4
-0+return RMP_FAULT_RETRY ; +} +/* * Handle faults in the user portion of the address space. Nothing in here * should check X86_PF_USER without a specific justification: for almost @@ -1298,6 +1350,7 @@ void do_user_addr_fault(struct pt_regs *regs,struct task_struct *tsk;struct mm_struct *mm;vm_fault_t fault; +int ret;unsigned int flags =FAULT_FLAG_DEFAULT ; tsk = current;@@ -1378,6 +1431,22 @@ void
(struct pt_regs *regs,
Quoted 8 lines
arch/x86/mm/fault.c +5
-0if (error_code &X86_PF_INSTR ) flags |=FAULT_FLAG_INSTRUCTION ; +/* +* If its an RMP violation, try resolving it. +*/ +if (error_code &X86_PF_RMP ) { + ret =handle_user_rmp_page_fault (error_code, address);
arch/x86/mm/fault.c void do_user_addr_fault(struct pt_regs *regs, · line 1448
Quoted 10 lines
arch/x86/mm/fault.c +10
-0+if (ret ==RMP_FAULT_PAGE_SPLIT ) { + flags |=FAULT_FLAG_PAGE_SPLIT ; + }else if (ret ==RMP_FAULT_KILL ) { + fault |=VM_FAULT_SIGBUS ; +do_sigbus (regs, error_code, address, fault); +return ; + }else { +return ; + } + }
Why not just have handle_user_rmp_page_fault() return a VM_FAULT_* code directly?
I also suspect you can just set VM_FAULT_SIGBUS and let the do_sigbus() call later on in the function do its work.
Quoted 38 lines
arch/x86/mm/fault.c +0
-0* Faults in the vsyscall page might need emulation. The include/linux/mm.h +5
-1@@ -450,6 +450,8 @@ extern pgprot_t protection_map[16];* @FAULT_FLAG_REMOTE: The fault is not for current task/mm. * @FAULT_FLAG_INSTRUCTION: The fault was during an instruction fetch. * @FAULT_FLAG_INTERRUPTIBLE: The fault can be interrupted by non-fatal signals. +* @FAULT_FLAG_PAGE_SPLIT: The fault was due page size mismatch, split the +* region to smaller page size and retry. * * About @FAULT_FLAG_ALLOW_RETRY and @FAULT_FLAG_TRIED: we can specify * whether we would allow page faults to retry by specifying these two @@ -481,6 +483,7 @@ enum fault_flag {FAULT_FLAG_REMOTE =1 <<7 ,FAULT_FLAG_INSTRUCTION =1 <<8 ,FAULT_FLAG_INTERRUPTIBLE =1 <<9 , + FAULT_FLAG_PAGE_SPLIT = 1 << 10, };/* @@ -520,7 +523,8 @@ static inline bool fault_flag_allow_retry_first(enum fault_flag flags) { FAULT_FLAG_USER, "USER" }, \ { FAULT_FLAG_REMOTE, "REMOTE" }, \ { FAULT_FLAG_INSTRUCTION, "INSTRUCTION" }, \ - { FAULT_FLAG_INTERRUPTIBLE, "INTERRUPTIBLE" } + { FAULT_FLAG_INTERRUPTIBLE, "INTERRUPTIBLE" }, \ + { FAULT_FLAG_PAGE_SPLIT, "PAGESPLIT" }/* * vm_fault is filled by the pagefault handler and passed to the vma's mm/memory.c +0
-0@@ -4407,6 +4407,15 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf)return 0 ;
mm/memory.c static vm_fault_t handle_pte_fault(struct vm_fault *vmf) · line 4417
Quoted 10 lines
mm/memory.c +8
-0} +static int handle_split_page_fault (struct vm_fault *vmf) +{ +if (!IS_ENABLED (CONFIG_AMD_MEM_ENCRYPT )) +return VM_FAULT_SIGBUS ; + +__split_huge_pmd (vmf->vma, vmf->pmd, vmf->address, false,NULL ); +return 0 ; +}
What will this do when you hand it a hugetlbfs page?
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Hi Dave,
Quoted 2 lines · Dave Hansen
"SIGBUG"?
Its typo, it should be SIGBUS
Quoted 6 lines
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1301
Quoted 3 lines
arch/x86/mm/fault.c +3
-0+ +if (unlikely (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))) +return RMP_FAULT_KILL ;Shouldn't this be a
WARN_ON_ONCE()? How can we get RMP faults without SEV-SNP?
Yes, we should *not* get RMP fault if SEV-SNP is not enabled. I can use the WARN_ON_ONCE().
Quoted 9 lines
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1306
Quoted 5 lines
arch/x86/mm/fault.c +4
-0+/* Get the native page level */ + pte =lookup_address_in_mm (current->mm, address, &level); +if (unlikely (!pte)) +return RMP_FAULT_KILL ;What would this mean? There was an RMP fault on a non-present page? How could that happen? What if there was a race between an unmapping event and the RMP fault delivery?
We should not have RMP fault for non-present pages. But you have a good point that there maybe a race between the unmap event and RMP fault. Instead of terminating the process we should simply retry.
Quoted 11 lines
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1312
Quoted 6 lines
arch/x86/mm/fault.c +5
-0+ pfn =pte_pfn (*pte); +if (level >PG_LEVEL_4K ) { + mask =pages_per_hpage (level) -pages_per_hpage (level -1 ); + pfn |= (address >>PAGE_SHIFT ) & mask; + }This looks inherently racy. What happens if there are two parallel RMP faults on the same 2M page. One of them splits the page tables, the other gets a fault for an already-split page table.
Quoted 1 line
Is that handled here somehow?
Yes, in this particular case we simply retry and hardware should re-evaluate the page level and take the corrective action.
Quoted 10 lines
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1317
Quoted 5 lines
arch/x86/mm/fault.c +4
-0+/* Get the page level from the RMP entry. */ + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &rmp_level); +if (!e) +return RMP_FAULT_KILL ;The
snp_lookup_page_in_rmptable()failure cases looks WARN-worthly. Either you're doing a lookup for something not *IN* the RMP table, or you don't support SEV-SNP, in which case you shouldn't be in this code in the first place.
Noted.
Quoted 9 lines
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1324
Quoted 7 lines
arch/x86/mm/fault.c +6
-0+/* +* Check if the RMP violation is due to the guest private page access. +* We can not resolve this RMP fault, ask to kill the guest. +*/ +if (rmpentry_assigned (e)) +return RMP_FAULT_KILL ;No "We's", please. Speak in imperative voice.
Noted.
Quoted 10 lines
arch/x86/mm/fault.c do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code, · line 1331
Quoted 7 lines
arch/x86/mm/fault.c +6
-0+/* +* The backing page level is higher than the RMP page level, request +* to split the page. +*/ +if (level > rmp_level) +return RMP_FAULT_PAGE_SPLIT ;This can theoretically trigger on a hugetlbfs page. Right?
Yes, theoretically.
In the current implementation, the VMM is enlightened to not use the hugetlbfs for backing page when creating the SEV-SNP guests.
Quoted 31 lines
I thought I asked about this before... more below...
arch/x86/mm/fault.c void
Quoted 15 lines
arch/x86/mm/fault.c +4
-0+return RMP_FAULT_RETRY ; +} +/* * Handle faults in the user portion of the address space. Nothing in here * should check X86_PF_USER without a specific justification: for almost @@ -1298,6 +1350,7 @@ void do_user_addr_fault(struct pt_regs *regs,struct task_struct *tsk;struct mm_struct *mm;vm_fault_t fault; +int ret;unsigned int flags =FAULT_FLAG_DEFAULT ; tsk = current;@@ -1378,6 +1431,22 @@ void(struct
pt_regs*regs,Quoted 13 lines
arch/x86/mm/fault.c +10
-0if (error_code &X86_PF_INSTR ) flags |=FAULT_FLAG_INSTRUCTION ; +/* +* If its an RMP violation, try resolving it. +*/ +if (error_code &X86_PF_RMP ) { + ret =handle_user_rmp_page_fault (error_code, address); +if (ret ==RMP_FAULT_PAGE_SPLIT ) { + flags |=FAULT_FLAG_PAGE_SPLIT ; + }else if (ret ==RMP_FAULT_KILL ) { + fault |=VM_FAULT_SIGBUS ; +do_sigbus (regs, error_code, address, fault);
Quoted 9 lines
arch/x86/mm/fault.c void do_user_addr_fault(struct pt_regs *regs, · line 1448
Quoted 5 lines
arch/x86/mm/fault.c +5
-0+return ; + }else { +return ; + } + }Why not just have
handle_user_rmp_page_fault()return a VM_FAULT_* code directly?
I don't have any strong reason against it. In next rev, I can update to use the VM_FAULT_* code and call the do_sigbus() etc.
Quoted 14 lines
I also suspect you can just set
VM_FAULT_SIGBUSand let thedo_sigbus()call later on in the function do its work.mm/memory.c static vm_fault_t handle_pte_fault(struct vm_fault *vmf) · line 4417
Quoted 9 lines
mm/memory.c +8
-0+static int handle_split_page_fault (struct vm_fault *vmf) +{ +if (!IS_ENABLED (CONFIG_AMD_MEM_ENCRYPT )) +return VM_FAULT_SIGBUS ; + +__split_huge_pmd (vmf->vma, vmf->pmd, vmf->address, false,NULL ); +return 0 ; +}What will this do when you hand it a hugetlbfs page?
VMM is updated to not use the hugetlbfs when creating SEV-SNP guests. So, we should not run into it.
-Brijesh
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 8 lines · Brijesh Singh
Quoted 8 lines
Quoted 7 lines
+ /*
+ * The backing page level is higher than the RMP page level, request
+ * to split the page.
+ */
+ if (level >rmp_level)
+ returnRMP_FAULT_PAGE_SPLIT;
Quoted 6 lines
Quoted 1 line
This can theoretically trigger on a hugetlbfs page. Right?
Yes, theoretically.
In the current implementation, the VMM is enlightened to not use the hugetlbfs for backing page when creating the SEV-SNP guests.
"The VMM"?
We try to write kernel code so that it "works" and doesn't do unexpected things with whatever userspace might throw at it. This seems to be written with an assumption that no VMM will ever use hugetlbfs with SEV-SNP.
That worries me. Not only because someone is sure to try it, but it's the kind of assumption that an attacker or a fuzzer might try.
Could you please test this kernel code in practice with hugetblfs?
Quoted 13 lines
Quoted 12 lines
I also suspect you can just set
VM_FAULT_SIGBUSand let thedo_sigbus()call later on in the function do its work.mm/memory.c static vm_fault_t handle_pte_fault(struct vm_fault *vmf) · line 4417
Quoted 8 lines
+static int
handle_split_page_fault(struct vm_fault *vmf)mm/memory.c +7
-0+{ + if (!IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) + return VM_FAULT_SIGBUS; + + __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL); + return 0; +}What will this do when you hand it a hugetlbfs page?
Quoted 2 lines
VMM is updated to not use the hugetlbfs when creating SEV-SNP guests. So, we should not run into it.
Please fix this code to handle hugetlbfs along with any other non-THP source of level>0 mappings. DAX comes to mind. "Handle" can mean rejecting these. You don't have to find some way to split them and make the VM work, just fail safely, ideally as early as possible.
To me, this is a fundamental requirement before this code can be accepted.
How many more parts of this series are predicated on the behavior of the VMM like this?
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 9 lines · Dave Hansen
Quoted 8 lines · Brijesh Singh
Quoted 8 lines
Quoted 7 lines
+ /*
+ * The backing page level is higher than the RMP page level, request
+ * to split the page.
+ */
+ if (level >rmp_level)
+ returnRMP_FAULT_PAGE_SPLIT;
Quoted 8 lines
Quoted 6 lines
Quoted 1 line
This can theoretically trigger on a hugetlbfs page. Right?
Yes, theoretically.
In the current implementation, the VMM is enlightened to not use the hugetlbfs for backing page when creating the SEV-SNP guests.
"The VMM"?
I was meaning a userspace qemu.
Quoted 9 lines
We try to write kernel code so that it "works" and doesn't do unexpected things with whatever userspace might throw at it. This seems to be written with an assumption that no VMM will ever use hugetlbfs with SEV-SNP.
That worries me. Not only because someone is sure to try it, but it's the kind of assumption that an attacker or a fuzzer might try.
Could you please test this kernel code in practice with hugetblfs?
Yes, I will make sure that hugetlbfs path is tested in non-RFC version.
Quoted 17 lines
Quoted 14 lines
Quoted 13 lines
I also suspect you can just set
VM_FAULT_SIGBUSand let thedo_sigbus()call later on in the function do its work.mm/memory.c static vm_fault_t handle_pte_fault(struct vm_fault *vmf) · line 4417
Quoted 8 lines
+static int
handle_split_page_fault(struct vm_fault *vmf)mm/memory.c +7
-0+{ + if (!IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) + return VM_FAULT_SIGBUS; + + __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL); + return 0; +}What will this do when you hand it a hugetlbfs page?
Quoted 2 lines
VMM is updated to not use the hugetlbfs when creating SEV-SNP guests. So, we should not run into it.
Quoted 6 lines
Please fix this code to handle hugetlbfs along with any other non-THP source of level>0 mappings. DAX comes to mind. "Handle" can mean rejecting these. You don't have to find some way to split them and make the VM work, just fail safely, ideally as early as possible.
To me, this is a fundamental requirement before this code can be accepted.
Understood, if userspace decided to use the hugetlbfs backing pages then I believe earliest we can detect is when we go about adding the pages in the RMP table. I'll add a check, and fail the page state change.
-Brijesh
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 11 lines · Brijesh Singh
Quoted 7 lines
Please fix this code to handle hugetlbfs along with any other non-THP source of level>0 mappings. DAX comes to mind. "Handle" can mean rejecting these. You don't have to find some way to split them and make the VM work, just fail safely, ideally as early as possible.
To me, this is a fundamental requirement before this code can be accepted.
Understood, if userspace decided to use the hugetlbfs backing pages then I believe earliest we can detect is when we go about adding the pages in the RMP table. I'll add a check, and fail the page state change.
Really? You had to feed the RMP entries from *some* mapping in the first place. Is there a reason the originating mapping can't be checked at that point instead of waiting for the fault?
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 9 lines · Dave Hansen
Quoted 8 lines · Brijesh Singh
Quoted 7 lines
Please fix this code to handle hugetlbfs along with any other non-THP source of level>0 mappings. DAX comes to mind. "Handle" can mean rejecting these. You don't have to find some way to split them and make the VM work, just fail safely, ideally as early as possible.
To me, this is a fundamental requirement before this code can be accepted.
Quoted 8 lines
Quoted 3 lines
Understood, if userspace decided to use the hugetlbfs backing pages then I believe earliest we can detect is when we go about adding the pages in the RMP table. I'll add a check, and fail the page state change.
Really? You had to feed the RMP entries from *some* mapping in the first place. Is there a reason the originating mapping can't be checked at that point instead of waiting for the fault?
Apologies if I was not clear in the messaging, that's exactly what I mean that we don't feed RMP entries during the page state change.
The sequence of the operation is:
1. Guest issues a VMGEXIT (page state change) to add a page in the RMP
2. Hyperivosr adds the page in the RMP table.
The check will be inside the hypervisor (#2), to query the backing page type, if the backing page is from the hugetlbfs, then don't add the page in the RMP, and fail the page state change VMGEXIT.
-Brijesh
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 11 lines · Brijesh Singh
Apologies if I was not clear in the messaging, that's exactly what I mean that we don't feed RMP entries during the page state change.
The sequence of the operation is:
1. Guest issues a VMGEXIT (page state change) to add a page in the RMP
2. Hyperivosr adds the page in the RMP table.The check will be inside the hypervisor (#2), to query the backing page type, if the backing page is from the hugetlbfs, then don't add the page in the RMP, and fail the page state change VMGEXIT.
Right, but *LOOOOOONG* before that, something walked the page tables and stuffed the PFN into the NPT (that's the AMD equivalent of EPT, right?).
You could also avoid this whole mess by refusing to allow hugetblfs to
be mapped into the guest in the first place.
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 9 lines · Dave Hansen
Quoted 8 lines · Brijesh Singh
Apologies if I was not clear in the messaging, that's exactly what I mean that we don't feed RMP entries during the page state change.
The sequence of the operation is:
1. Guest issues a VMGEXIT (page state change) to add a page in the RMP
2. Hyperivosr adds the page in the RMP table.
Quoted 9 lines
Quoted 3 lines
The check will be inside the hypervisor (#2), to query the backing page type, if the backing page is from the hugetlbfs, then don't add the page in the RMP, and fail the page state change VMGEXIT.
Right, but *LOOOOOONG* before that, something walked the page tables and stuffed the PFN into the NPT (that's the AMD equivalent of EPT, right?).
You could also avoid this whole mess by refusing to allow hugetblfs to
be mapped into the guest in the first place.
Ah, that should be doable. For SEV stuff, we require the VMM to register the memory region to the hypervisor during the VM creation time. I can check the hugetlbfs while registering the memory region and fail much earlier.
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 22 lines · Brijesh Singh
Quoted 9 lines · Dave Hansen
Quoted 8 lines · Brijesh Singh
Apologies if I was not clear in the messaging, that's exactly what I mean that we don't feed RMP entries during the page state change.
The sequence of the operation is:
1. Guest issues a VMGEXIT (page state change) to add a page in the RMP
2. Hyperivosr adds the page in the RMP table.Quoted 9 lines
Quoted 3 lines
The check will be inside the hypervisor (#2), to query the backing page type, if the backing page is from the hugetlbfs, then don't add the page in the RMP, and fail the page state change VMGEXIT.
Right, but *LOOOOOONG* before that, something walked the page tables and stuffed the PFN into the NPT (that's the AMD equivalent of EPT, right?).
You could also avoid this whole mess by refusing to allow hugetblfs to
be mapped into the guest in the first place.
Quoted 3 lines
Ah, that should be doable. For SEV stuff, we require the VMM to register the memory region to the hypervisor during the VM creation time. I can check the hugetlbfs while registering the memory region and fail much earlier.
That's technically unnecessary, because this patch is working on the wrong set of page tables when handling faults from KVM.
The host page tables constrain KVM's NPT, but the two are not mirrors of each other. Specifically, KVM cannot exceed the size of the host page tables because that would give the guest access to memory it does not own, but KVM isn't required to use the same size as the host. E.g. a 1gb page in the host can be 1gb, 2mb, or 4kb in the NPT.
The code "works" because the size contraints mean it can't get false negatives, only false positives, false positives will never be fatal, e.g. the fault handler may unnecessarily demote a 1gb, and demoting a host page will further constrain KVM's NPT.
The distinction matters because it changes our options. For RMP violations on NPT due to page size mismatches, KVM can and should handle the fault without consulting the primary MMU, i.e. by demoting the NPT entry. That means KVM does not need to care about hugetlbfs or any other backing type that cannot be split since KVM will never initiate a host page split in response to a #NPT RMP violation.
That doesn't mean that hugetlbfs will magically work since e.g. get/put_user() will fault and fail, but that's a generic non-KVM problem since nothing prevents remapping and/or accessing the page(s) outside of KVM context.
The other reason to not disallow hugetlbfs and co. is that a guest that's enlightened to operate at 2mb granularity, e.g. always do page state changes on 2mb chunks, can play nice with hugetlbfs without ever hitting an RMP violation.
Last thought, have we taken care in the guest side of things to work at 2mb granularity when possible? AFAICT, PSMASH is effectively a one-way street since RMPUPDATE to restore a 2mb RMP is destructive, i.e. requires PVALIDATE on the entire 2mb chunk, and the guest can't safely do that without reinitializing the whole page, e.g. would either lose data or have to save/init/restore.
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
In reply to Brijesh SinghQuoted 5 lines · Brijesh Singh
mm/memory.c +0
-0@@ -4407,6 +4407,15 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf)return 0 ; }
mm/memory.c static vm_fault_t handle_pte_fault(struct vm_fault *vmf) · line 4418
Quoted 10 lines
mm/memory.c +9
-0+static int handle_split_page_fault (struct vm_fault *vmf) +{ +if (!IS_ENABLED (CONFIG_AMD_MEM_ENCRYPT )) +return VM_FAULT_SIGBUS ; + +__split_huge_pmd (vmf->vma, vmf->pmd, vmf->address, false,NULL ); +return 0 ; +} +
I think back in v1 Dave asked if khugepaged will just coalesce this back, and it wasn't ever answered AFAICS.
I've checked the code and I think the answer is: no. Khugepaged isn't designed to coalesce a pte-mapped hugepage back to pmd in place. And the usual way (copy to a new huge page) I think will not succeed because IIRC the page is also FOLL_PIN pinned and khugepaged_scan_pmd() will see the elevated refcounts via is_refcount_suitable() and give up.
So the lack of coalescing (in case the sub-page leading to split becomes guest private again later) is somewhat suboptimal, but not critical.
Re: [PATCH Part2 RFC v4 10/40] x86/fault: Add support to handle the RMP fault for user address
Quoted 19 lines · Vlastimil Babka
Quoted 5 lines · Brijesh Singh
mm/memory.c +0
-0@@ -4407,6 +4407,15 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf)return 0 ; }mm/memory.c static vm_fault_t handle_pte_fault(struct vm_fault *vmf) · line 4418
Quoted 10 lines
mm/memory.c +9
-0+static int handle_split_page_fault (struct vm_fault *vmf) +{ +if (!IS_ENABLED (CONFIG_AMD_MEM_ENCRYPT )) +return VM_FAULT_SIGBUS ; + +__split_huge_pmd (vmf->vma, vmf->pmd, vmf->address, false,NULL ); +return 0 ; +} +I think back in v1 Dave asked if khugepaged will just coalesce this back, and it wasn't ever answered AFAICS.
Quoted 5 lines
I've checked the code and I think the answer is: no. Khugepaged isn't designed to coalesce a pte-mapped hugepage back to pmd in place. And the usual way (copy to a new huge page) I think will not succeed because IIRC the page is also
FOLL_PINpinned andkhugepaged_scan_pmd()will see the elevated refcounts viais_refcount_suitable()and give up.
I _thought_ this was the whole "PTE mapped THP" bit of code, like collapse_pte_mapped_thp(). But, looking at it again, I think that code is just for the huge tmpfs flavor of THP.
Either way, I'm kinda surprised that we don't collapse things in place.
Especially in the early days, there were lots of crazy things that
split THPs. I think even things like /proc/$pid/smaps split them.
In any case, it sounds like SEV-SNP users should probably be advised to use MADV_NOHUGEPAGE to avoid any future surprises. At least until the hardware folks get their act together and teach the TLB how to fracture 2M entries properly. :)
RFC PATCH v4 11/40 crypto:ccp: Define the SEV-SNP commands
In reply to Brijesh SinghAMD introduced the next generation of SEV called SEV-SNP (Secure Nested Paging). SEV-SNP builds upon existing SEV and SEV-ES functionality while adding new hardware security protection.
Define the commands and structures used to communicate with the AMD-SP when creating and managing the SEV-SNP guests. The SEV-SNP firmware spec is available at developer.amd.com/sev.
--- drivers/crypto/ccp/sev-dev.c | 16 ++- include/linux/psp-sev.h | 222 +++++++++++++++++++++++++++++++++++ include/uapi/linux/psp-sev.h | 43 +++++++ 3 files changed, 280 insertions(+), 1 deletion(-)
drivers/crypto/ccp/sev-dev.c +15 -1
@@ -130,7 +130,21 @@ static int sev_cmd_buffer_len(int cmd)case SEV_CMD_DOWNLOAD_FIRMWARE :return sizeof (struct sev_data_download_firmware );case SEV_CMD_GET_ID :return sizeof (struct sev_data_get_id );case SEV_CMD_ATTESTATION_REPORT :return sizeof (struct sev_data_attestation_report ); -case SEV_CMD_SEND_CANCEL :return sizeof (struct sev_data_send_cancel ); +case SEV_CMD_SEND_CANCEL :return sizeof (struct sev_data_send_cancel ); +case SEV_CMD_SNP_GCTX_CREATE :return sizeof (struct sev_data_snp_gctx_create ); +case SEV_CMD_SNP_LAUNCH_START :return sizeof (struct sev_data_snp_launch_start ); +case SEV_CMD_SNP_LAUNCH_UPDATE :return sizeof (struct sev_data_snp_launch_update ); +case SEV_CMD_SNP_ACTIVATE :return sizeof (struct sev_data_snp_activate ); +case SEV_CMD_SNP_DECOMMISSION :return sizeof (struct sev_data_snp_decommission ); +case SEV_CMD_SNP_PAGE_RECLAIM :return sizeof (struct sev_data_snp_page_reclaim ); +case SEV_CMD_SNP_GUEST_STATUS :return sizeof (struct sev_data_snp_guest_status ); +case SEV_CMD_SNP_LAUNCH_FINISH :return sizeof (struct sev_data_snp_launch_finish ); +case SEV_CMD_SNP_DBG_DECRYPT :return sizeof (struct sev_data_snp_dbg ); +case SEV_CMD_SNP_DBG_ENCRYPT :return sizeof (struct sev_data_snp_dbg ); +case SEV_CMD_SNP_PAGE_UNSMASH :return sizeof (struct sev_data_snp_page_unsmash ); +case SEV_CMD_SNP_PLATFORM_STATUS :return sizeof (struct sev_data_snp_platform_status_buf ); +case SEV_CMD_SNP_GUEST_REQUEST :return sizeof (struct sev_data_snp_guest_request ); +case SEV_CMD_SNP_CONFIG :return sizeof (struct sev_user_data_snp_config );default :return 0 ; }
include/linux/psp-sev.h +222 -0
234 lines not on this page · raw message
include/uapi/linux/psp-sev.h +43 -0
55 lines not on this page · raw message
Signature · 1 line
2.17.1
RFC PATCH v4 12/40 crypto: ccp: Add support to initialize the AMD-SP for SEV-SNP
In reply to Brijesh SinghBefore SNP VMs can be launched, the platform must be appropriately configured and initialized. Platform initialization is accomplished via the SNP_INIT command.
--- drivers/crypto/ccp/sev-dev.c | 114 +++++++++++++++++++++++++++++++++-- drivers/crypto/ccp/sev-dev.h | 2 + include/linux/psp-sev.h | 16 +++++ 3 files changed, 127 insertions(+), 5 deletions(-)
drivers/crypto/ccp/sev-dev.c +109 -5
@@ -591,6 +591,95 @@ static int sev_update_firmware(struct device *dev)return ret; } +static void snp_set_hsave_pa (void *arg) +{ +wrmsrl (MSR_VM_HSAVE_PA ,0 ); +} + +static int __sev_snp_init_locked (int *error) +{ +struct psp_device *psp = psp_master; +struct sev_device *sev; +int rc =0 ; + +if (!psp || !psp->sev_data) +return -ENODEV ; + + sev = psp->sev_data; + +if (sev->snp_inited) +return 0 ; + +/* +* The SNP_INIT requires the MSR_VM_HSAVE_PA must be set to 0h +* across all cores. +*/ +on_each_cpu (snp_set_hsave_pa,NULL ,1 ); + +/* Prepare for first SEV guest launch after INIT */ +wbinvd_on_all_cpus (); + +/* Issue the SNP_INIT firmware command. */ + rc =__sev_do_cmd_locked (SEV_CMD_SNP_INIT ,NULL , error); +if (rc) +return rc; + + sev->snp_inited = true; +dev_dbg (sev->dev,"SEV-SNP firmware initialized\n" ); + +return rc; +} + +int sev_snp_init (int *error) +{ +int rc; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return -ENODEV ; + +mutex_lock (&sev_cmd_mutex); + rc =__sev_snp_init_locked (error); +mutex_unlock (&sev_cmd_mutex); + +return rc; +} +EXPORT_SYMBOL_GPL (sev_snp_init); + +static int __sev_snp_shutdown_locked (int *error) +{ +struct sev_device *sev = psp_master->sev_data; +int ret; + +if (!sev->snp_inited) +return 0 ; + +/* SHUTDOWN requires the DF_FLUSH */ +wbinvd_on_all_cpus (); +__sev_do_cmd_locked (SEV_CMD_SNP_DF_FLUSH ,NULL ,NULL ); + + ret =__sev_do_cmd_locked (SEV_CMD_SNP_SHUTDOWN ,NULL , error); +if (ret) { +dev_err (sev->dev,"SEV-SNP firmware shutdown failed\n" ); +return ret; + } + + sev->snp_inited = false; +dev_dbg (sev->dev,"SEV-SNP firmware shutdown\n" ); + +return ret; +} + +static int sev_snp_shutdown (int *error) +{ +int rc; + +mutex_lock (&sev_cmd_mutex); + rc =__sev_snp_shutdown_locked (NULL ); +mutex_unlock (&sev_cmd_mutex); + +return rc; +} +static int sev_ioctl_do_pek_import (struct sev_issue_cmd *argp,bool writable) {struct sev_device *sev = psp_master->sev_data;
@@ -1095,6 +1184,21 @@ void sev_pci_init(void) "SEV: TMR allocation failed, SEV-ES support unavailable\n"); } +/* +* If boot CPU supports the SNP, then first attempt to initialize +* the SNP firmware. +*/ +if (cpu_feature_enabled (X86_FEATURE_SEV_SNP )) { + rc =sev_snp_init (&error); +if (rc) { +/* +* If we failed to INIT SNP then don't abort the probe. +* Continue to initialize the legacy SEV firmware. +*/ +dev_err (sev->dev,"SEV-SNP: failed to INIT error %#x\n" , error); + } + } +/* Initialize the platform */ rc =sev_platform_init (&error);if (rc && (error ==SEV_RET_SECURE_DATA_INVALID )) {
@@ -1109,13 +1213,11 @@ void sev_pci_init(void) rc =sev_platform_init (&error); } -if (rc) { +if (rc)dev_err (sev->dev,"SEV: failed to INIT error %#x\n" , error); -return ; - } -dev_info (sev->dev,"SEV API:%d.%d build:%d\n" , sev->api_major, - sev->api_minor, sev->build); +dev_info (sev->dev,"SEV%s API:%d.%d build:%d\n" , sev->snp_inited ? +"-SNP" :"" , sev->api_major, sev->api_minor, sev->build);return ;
@@ -1138,4 +1240,6 @@ void sev_pci_exit(void) get_order(SEV_ES_TMR_SIZE)); sev_es_tmr =NULL ; } + +sev_snp_shutdown (NULL ); }
drivers/crypto/ccp/sev-dev.h +2 -0
@@ -52,6 +52,8 @@ struct sev_device {u8 build;void *cmd_buf; + +bool snp_inited; };int sev_dev_init (struct psp_device *psp);
include/linux/psp-sev.h +16 -0
@@ -748,6 +748,20 @@ struct sev_data_snp_init_ex {*/ int sev_platform_init (int *error); +/** +* sev_snp_init - perform SEV SNP_INIT command +* +* @error: SEV command return code +* +* Returns: +* 0 if the SEV successfully processed the command +* -%ENODEV if the SEV device is not available +* -%ENOTSUPP if the SEV does not support SEV +* -%ETIMEDOUT if the SEV command timed out +* -%EIO if the SEV returned a non-zero return code +*/ +int sev_snp_init (int *error); +/** * sev_platform_status - perform SEV PLATFORM_STATUS command *
@@ -855,6 +869,8 @@ sev_platform_status(struct sev_user_data_status *status, int *error) { return -Estatic inline int sev_platform_init (int *error) {return -ENODEV ; } +static inline int sev_snp_init (int *error) {return -ENODEV ; } +static inline int sev_guest_deactivate (struct sev_data_deactivate *data,int *error) {return -ENODEV ; }
Signature · 1 line
2.17.1
RFC PATCH v4 13/40 crypto: ccp: Shutdown SNP firmware on kexec
In reply to Brijesh SinghWhen the kernel is getting ready to kexec, it calls the device_shutdown() to allow drivers to cleanup before the kexec. If SEV firmware is initialized then shutdown it before kexec'ing the new kernel.
--- drivers/crypto/ccp/sev-dev.c | 53 +++++++++++++++++------------------- drivers/crypto/ccp/sp-pci.c | 12 ++++++++ 2 files changed, 37 insertions(+), 28 deletions(-)
drivers/crypto/ccp/sev-dev.c +25 -28
@@ -310,6 +310,9 @@ static int __sev_platform_shutdown_locked(int *error)struct sev_device *sev = psp_master->sev_data;int ret; +if (sev->state ==SEV_STATE_UNINIT ) +return 0 ; + ret =__sev_do_cmd_locked (SEV_CMD_SHUTDOWN ,NULL , error);if (ret)return ret;
@@ -1118,6 +1121,22 @@ int sev_dev_init(struct psp_device *psp)return ret; } +static void sev_firmware_shutdown (struct sev_device *sev) +{ +sev_platform_shutdown (NULL ); + +if (sev_es_tmr) { +/* The TMR area was encrypted, flush it from the cache */ +wbinvd_on_all_cpus (); + +free_pages ((unsigned long )sev_es_tmr, +get_order (SEV_ES_TMR_SIZE )); + sev_es_tmr =NULL ; + } + +sev_snp_shutdown (NULL ); +} +void sev_dev_destroy (struct psp_device *psp) {struct sev_device *sev = psp->sev_data;
@@ -1125,6 +1144,8 @@ void sev_dev_destroy(struct psp_device *psp)if (!sev)return ; +sev_firmware_shutdown (sev); +if (sev->misc)kref_put (&misc_dev->refcount, sev_exit);
@@ -1155,21 +1176,6 @@ void sev_pci_init(void)if (sev_get_api_version ()) goto err; -/* -* If platform is not in UNINIT state then firmware upgrade and/or -* platform INIT command will fail. These command require UNINIT state. -* -* In a normal boot we should never run into case where the firmware -* is not in UNINIT state on boot. But in case of kexec boot, a reboot -* may not go through a typical shutdown sequence and may leave the -* firmware in INIT or WORKING state. -*/ - -if (sev->state !=SEV_STATE_UNINIT ) { -sev_platform_shutdown (NULL ); - sev->state =SEV_STATE_UNINIT ; - } -if (sev_version_greater_or_equal (0 ,15 ) &&sev_update_firmware (sev->dev) ==0 )sev_get_api_version ();
@@ -1227,19 +1233,10 @@ void sev_pci_init(void)void sev_pci_exit (void ) { -if (!psp_master->sev_data) -return ; - -sev_platform_shutdown (NULL ); - -if (sev_es_tmr) { -/* The TMR area was encrypted, flush it from the cache */ -wbinvd_on_all_cpus (); +struct sev_device *sev = psp_master->sev_data; -free_pages ((unsigned long )sev_es_tmr, -get_order (SEV_ES_TMR_SIZE )); - sev_es_tmr =NULL ; - } +if (!sev) +return ; -sev_snp_shutdown (NULL ); +sev_firmware_shutdown (sev); }
drivers/crypto/ccp/sp-pci.c +12 -0
@@ -239,6 +239,17 @@ static int sp_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)return ret; } +static void sp_pci_shutdown (struct pci_dev *pdev) +{ +struct device *dev = &pdev->dev; +struct sp_device *sp =dev_get_drvdata (dev); + +if (!sp) +return ; + +sp_destroy (sp); +} +static void sp_pci_remove (struct pci_dev *pdev) {struct device *dev = &pdev->dev;
@@ -369,6 +380,7 @@ static struct pci_driver sp_pci_driver = { .id_table = sp_pci_table, .probe = sp_pci_probe, .remove = sp_pci_remove, + .shutdown = sp_pci_shutdown, .driver.pm = &sp_pci_pm_ops, };
Signature · 1 line
2.17.1
RFC PATCH v4 14/40 crypto:ccp: Provide APIs to issue SEV-SNP commands
In reply to Brijesh SinghProvide the APIs for the hypervisor to manage an SEV-SNP guest. The commands for SEV-SNP is defined in the SEV-SNP firmware specification.
--- drivers/crypto/ccp/sev-dev.c | 24 ++++++++++++ include/linux/psp-sev.h | 74 ++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+)
drivers/crypto/ccp/sev-dev.c +24 -0
@@ -1017,6 +1017,30 @@ int sev_guest_df_flush(int *error) }EXPORT_SYMBOL_GPL (sev_guest_df_flush); +int snp_guest_decommission (struct sev_data_snp_decommission *data,int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_DECOMMISSION , data, error); +} +EXPORT_SYMBOL_GPL (snp_guest_decommission); + +int snp_guest_df_flush (int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_DF_FLUSH ,NULL , error); +} +EXPORT_SYMBOL_GPL (snp_guest_df_flush); + +int snp_guest_page_reclaim (struct sev_data_snp_page_reclaim *data,int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_PAGE_RECLAIM , data, error); +} +EXPORT_SYMBOL_GPL (snp_guest_page_reclaim); + +int snp_guest_dbg_decrypt (struct sev_data_snp_dbg *data,int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_DBG_DECRYPT , data, error); +} +EXPORT_SYMBOL_GPL (snp_guest_dbg_decrypt); +static void sev_exit (struct kref *ref) {misc_deregister (&misc_dev->misc);
include/linux/psp-sev.h +74 -0
86 lines not on this page · raw message
Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 14/40] crypto:ccp: Provide APIs to issue SEV-SNP commands
Quoted 51 lines · * Brijesh Singh ([email protected]) wrote:
Provide the APIs for the hypervisor to manage an SEV-SNP guest. The commands for SEV-SNP is defined in the SEV-SNP firmware specification.
Signed-off-by Brijesh Singh <[email protected]>--- drivers/crypto/ccp/sev-dev.c | 24 ++++++++++++ include/linux/psp-sev.h | 74 ++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+)drivers/crypto/ccp/sev-dev.c +24
-0@@ -1017,6 +1017,30 @@ int sev_guest_df_flush(int *error) }EXPORT_SYMBOL_GPL (sev_guest_df_flush); +int snp_guest_decommission (struct sev_data_snp_decommission *data,int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_DECOMMISSION , data, error); +} +EXPORT_SYMBOL_GPL (snp_guest_decommission); + +int snp_guest_df_flush (int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_DF_FLUSH ,NULL , error); +} +EXPORT_SYMBOL_GPL (snp_guest_df_flush); + +int snp_guest_page_reclaim (struct sev_data_snp_page_reclaim *data,int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_PAGE_RECLAIM , data, error); +} +EXPORT_SYMBOL_GPL (snp_guest_page_reclaim); + +int snp_guest_dbg_decrypt (struct sev_data_snp_dbg *data,int *error) +{ +return sev_do_cmd (SEV_CMD_SNP_DBG_DECRYPT , data, error); +} +EXPORT_SYMBOL_GPL (snp_guest_dbg_decrypt); +static void sev_exit (struct kref *ref) {misc_deregister (&misc_dev->misc);include/linux/psp-sev.h +0
-0@@ -860,6 +860,65 @@ int sev_guest_df_flush(int *error);*/ int sev_guest_decommission (struct sev_data_decommission *data,int *error);
include/linux/psp-sev.h int sev_guest_df_flush(int *error); · line 871
Quoted 10 lines
include/linux/psp-sev.h +9
-0+/** +* snp_guest_df_flush - perform SNP DF_FLUSH command +* +* @sev_ret: sev command return code +* +* Returns: +* 0 if the sev successfully processed the command +* -%ENODEV if the sev device is not available +* -%ENOTSUPP if the sev does not support SEV
Weird wording.
Quoted 79 lines
include/linux/psp-sev.h +65
-0+* -%ETIMEDOUT if the sev command timed out +* -%EIO if the sev returned a non-zero return code +*/ +int snp_guest_df_flush (int *error); + +/** +* snp_guest_decommission - perform SNP_DECOMMISSION command +* +* @decommission: sev_data_decommission structure to be processed +* @sev_ret: sev command return code +* +* Returns: +* 0 if the sev successfully processed the command +* -%ENODEV if the sev device is not available +* -%ENOTSUPP if the sev does not support SEV +* -%ETIMEDOUT if the sev command timed out +* -%EIO if the sev returned a non-zero return code +*/ +int snp_guest_decommission (struct sev_data_snp_decommission *data,int *error); + +/** +* snp_guest_page_reclaim - perform SNP_PAGE_RECLAIM command +* +* @decommission: sev_snp_page_reclaim structure to be processed +* @sev_ret: sev command return code +* +* Returns: +* 0 if the sev successfully processed the command +* -%ENODEV if the sev device is not available +* -%ENOTSUPP if the sev does not support SEV +* -%ETIMEDOUT if the sev command timed out +* -%EIO if the sev returned a non-zero return code +*/ +int snp_guest_page_reclaim (struct sev_data_snp_page_reclaim *data,int *error); + +/** +* snp_guest_dbg_decrypt - perform SEV SNP_DBG_DECRYPT command +* +* @sev_ret: sev command return code +* +* Returns: +* 0 if the sev successfully processed the command +* -%ENODEV if the sev device is not available +* -%ENOTSUPP if the sev does not support SEV +* -%ETIMEDOUT if the sev command timed out +* -%EIO if the sev returned a non-zero return code +*/ +int snp_guest_dbg_decrypt (struct sev_data_snp_dbg *data,int *error); + +void *psp_copy_user_blob (u64 uaddr,u32 len);#else /* !CONFIG_CRYPTO_DEV_SP_PSP */ @@ -887,6 +946,21 @@ sev_issue_cmd_external_user(struct file *filep, unsigned int id, void *data, intstatic inline void *psp_copy_user_blob (u64 __user uaddr,u32 len) {return ERR_PTR (-EINVAL ); } +static inline int +snp_guest_decommission (struct sev_data_snp_decommission *data,int *error) {return -ENODEV ; } + +static inline int snp_guest_df_flush (int *error) {return -ENODEV ; } + +static inline int snp_guest_page_reclaim (struct sev_data_snp_page_reclaim *data,int *error) +{ +return -ENODEV ; +} + +static inline int snp_guest_dbg_decrypt (struct sev_data_snp_dbg *data,int *error) +{ +return -ENODEV ; +} +#endif /* CONFIG_CRYPTO_DEV_SP_PSP */ #endif /* __PSP_SEV_H__ */ Signature · 1 line
2.17.1
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
RFC PATCH v4 15/40 crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
In reply to Brijesh SinghThe behavior and requirement for the SEV-legacy command is altered when the SNP firmware is in the INIT state. See SEV-SNP firmware specification for more details.
When SNP is INIT state, all the SEV-legacy commands that cause the firmware to write memory must be in the firmware state. The TMR memory is allocated by the host but updated by the firmware, so, it must be in the firmware state. Additionally, the TMR memory must be a 2MB aligned instead of the 1MB, and the TMR length need to be 2MB instead of 1MB. The helper __snp_{alloc,free}_firmware_pages() can be used for allocating and freeing the memory used by the firmware.
While at it, provide API that can be used by others to allocate a page that can be used by the firmware. The immediate user for this API will be the KVM driver. The KVM driver to need to allocate a firmware context page during the guest creation. The context page need to be updated by the firmware. See the SEV-SNP specification for further details.
--- drivers/crypto/ccp/sev-dev.c | 144 +++++++++++++++++++++++++++++++---- include/linux/psp-sev.h | 11 +++ 2 files changed, 142 insertions(+), 13 deletions(-)
drivers/crypto/ccp/sev-dev.c +131 -13
@@ -54,6 +54,14 @@ static int psp_timeout;#define SEV_ES_TMR_SIZE (1024 * 1024)static void *sev_es_tmr; +/* When SEV-SNP is enabled the TMR need to be 2MB aligned and 2MB size. */ +#define SEV_SNP_ES_TMR_SIZE (2 * 1024 * 1024) + +static size_t sev_es_tmr_size =SEV_ES_TMR_SIZE ; + +static int __sev_do_cmd_locked (int cmd,void *data,int *psp_ret); +static int sev_do_cmd (int cmd,void *data,int *psp_ret); +static inline bool sev_version_greater_or_equal (u8 maj,u8 min) {struct sev_device *sev = psp_master->sev_data;
@@ -151,6 +159,112 @@ static int sev_cmd_buffer_len(int cmd)return 0 ; } +static int snp_reclaim_page (struct page *page,bool locked) +{ +struct sev_data_snp_page_reclaim data = {}; +int ret, err; + + data.paddr =page_to_pfn (page) <<PAGE_SHIFT ; + +if (locked) + ret =__sev_do_cmd_locked (SEV_CMD_SNP_PAGE_RECLAIM , &data, &err); +else + ret =sev_do_cmd (SEV_CMD_SNP_PAGE_RECLAIM , &data, &err); + +return ret; +} + +static int snp_set_rmptable_state (unsigned long paddr,int npages, +struct rmpupdate *val,bool locked,bool need_reclaim) +{ +unsigned long pfn =__sme_clr (paddr) >>PAGE_SHIFT ; +unsigned long pfn_end = pfn + npages; +struct psp_device *psp = psp_master; +struct sev_device *sev; +int rc; + +if (!psp || !psp->sev_data) +return 0 ; + +/* If SEV-SNP is initialized then add the page in RMP table. */ + sev = psp->sev_data; +if (!sev->snp_inited) +return 0 ; + +while (pfn < pfn_end) { +if (need_reclaim) +if (snp_reclaim_page (pfn_to_page (pfn), locked)) +return -EFAULT ; + + rc =rmpupdate (pfn_to_page (pfn), val); +if (rc) +return rc; + + pfn++; + } + +return 0 ; +} + +static struct page *__snp_alloc_firmware_pages (gfp_t gfp_mask,int order,bool locked) +{ +struct rmpupdate val = {}; +unsigned long paddr; +struct page *page; + + page =alloc_pages (gfp_mask, order); +if (!page) +return NULL ; + + val.assigned =1 ; + val.immutable =1 ; + paddr =__pa ((unsigned long )page_address (page)); + +if (snp_set_rmptable_state (paddr,1 << order, &val, locked, false)) { +pr_warn ("Failed to set page state (leaking it)\n" ); +return NULL ; + } + +return page; +} + +void *snp_alloc_firmware_page (gfp_t gfp_mask) +{ +struct page *page; + + page =__snp_alloc_firmware_pages (gfp_mask,0 , false); + +return page ?page_address (page) :NULL ; +} +EXPORT_SYMBOL_GPL (snp_alloc_firmware_page); + +static void __snp_free_firmware_pages (struct page *page,int order,bool locked) +{ +struct rmpupdate val = {}; +unsigned long paddr; + +if (!page) +return ; + + paddr =__pa ((unsigned long )page_address (page)); + +if (snp_set_rmptable_state (paddr,1 << order, &val, locked, true)) { +pr_warn ("Failed to set page state (leaking it)\n" ); +return ; + } + +__free_pages (page, order); +} + +void snp_free_firmware_page (void *addr) +{ +if (!addr) +return ; + +__snp_free_firmware_pages (virt_to_page (addr),0 , false); +} +EXPORT_SYMBOL (snp_free_firmware_page); +static int __sev_do_cmd_locked (int cmd,void *data,int *psp_ret) {struct psp_device *psp = psp_master;
@@ -273,7 +387,7 @@ static int __sev_platform_init_locked(int *error) data.flags |=SEV_INIT_FLAGS_SEV_ES ; data.tmr_address = tmr_pa; - data.tmr_len =SEV_ES_TMR_SIZE ; + data.tmr_len = sev_es_tmr_size; } rc =__sev_do_cmd_locked (SEV_CMD_INIT , &data, error);
@@ -630,6 +744,8 @@ static int __sev_snp_init_locked(int *error) sev->snp_inited = true;dev_dbg (sev->dev,"SEV-SNP firmware initialized\n" ); + sev_es_tmr_size =SEV_SNP_ES_TMR_SIZE ; +return rc; }
@@ -1153,8 +1269,10 @@ static void sev_firmware_shutdown(struct sev_device *sev)/* The TMR area was encrypted, flush it from the cache */ wbinvd_on_all_cpus (); -free_pages ((unsigned long )sev_es_tmr, -get_order (SEV_ES_TMR_SIZE )); + +__snp_free_firmware_pages (virt_to_page (sev_es_tmr), +get_order (sev_es_tmr_size), + false); sev_es_tmr =NULL ; }
@@ -1204,16 +1322,6 @@ void sev_pci_init(void) sev_update_firmware(sev->dev) == 0)sev_get_api_version (); -/* Obtain the TMR memory area for SEV-ES use */ - tmr_page =alloc_pages (GFP_KERNEL ,get_order (SEV_ES_TMR_SIZE )); -if (tmr_page) { - sev_es_tmr =page_address (tmr_page); - }else { - sev_es_tmr =NULL ; -dev_warn (sev->dev, -"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); - } -/* * If boot CPU supports the SNP, then first attempt to initialize * the SNP firmware.
@@ -1229,6 +1337,16 @@ void sev_pci_init(void) } } +/* Obtain the TMR memory area for SEV-ES use */ + tmr_page =__snp_alloc_firmware_pages (GFP_KERNEL ,get_order (sev_es_tmr_size), false); +if (tmr_page) { + sev_es_tmr =page_address (tmr_page); + }else { + sev_es_tmr =NULL ; +dev_warn (sev->dev, +"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); + } +/* Initialize the platform */ rc =sev_platform_init (&error);if (rc && (error ==SEV_RET_SECURE_DATA_INVALID )) {
include/linux/psp-sev.h +11 -0
@@ -12,6 +12,8 @@#ifndef __PSP_SEV_H__#define __PSP_SEV_H__ +#include <linux/sev.h> +#include <uapi/linux/psp-sev.h> #ifdef CONFIG_X86
@@ -920,6 +922,8 @@ int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *error);void *psp_copy_user_blob (u64 uaddr,u32 len); +void *snp_alloc_firmware_page (gfp_t mask); +void snp_free_firmware_page (void *addr);#else /* !CONFIG_CRYPTO_DEV_SP_PSP */
@@ -961,6 +965,13 @@ static inline int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *erroreturn -ENODEV ; } +static inline void *snp_alloc_firmware_page (gfp_t mask) +{ +return NULL ; +} + +static inline void snp_free_firmware_page (void *addr) { } +#endif /* CONFIG_CRYPTO_DEV_SP_PSP */ #endif /* __PSP_SEV_H__ */
Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 15/40] crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
Quoted 30 lines · Brijesh Singh
The behavior and requirement for the SEV-legacy command is altered when the SNP firmware is in the INIT state. See SEV-SNP firmware specification for more details.
When SNP is INIT state, all the SEV-legacy commands that cause the firmware to write memory must be in the firmware state. The TMR memory is allocated by the host but updated by the firmware, so, it must be in the firmware state. Additionally, the TMR memory must be a 2MB aligned instead of the 1MB, and the TMR length need to be 2MB instead of 1MB. The helper __snp_{alloc,free}_firmware_pages() can be used for allocating and freeing the memory used by the firmware.
While at it, provide API that can be used by others to allocate a page that can be used by the firmware. The immediate user for this API will be the KVM driver. The KVM driver to need to allocate a firmware context page during the guest creation. The context page need to be updated by the firmware. See the SEV-SNP specification for further details.
Signed-off-by Brijesh Singh <[email protected]>--- drivers/crypto/ccp/sev-dev.c | 144 +++++++++++++++++++++++++++++++---- include/linux/psp-sev.h | 11 +++ 2 files changed, 142 insertions(+), 13 deletions(-)drivers/crypto/ccp/sev-dev.c +0
-0
drivers/crypto/ccp/sev-dev.c static int psp_timeout; · line 57
Quoted 4 lines
drivers/crypto/ccp/sev-dev.c +1
-0@@ -54,6 +54,14 @@ static int psp_timeout;#define SEV_ES_TMR_SIZE (1024 * 1024)static void *sev_es_tmr; +/* When SEV-SNP is enabled the TMR need to be 2MB aligned and 2MB size. */
nit: "the TMR need" -> "the TMR needs"
Quoted 11 lines
drivers/crypto/ccp/sev-dev.c +7
-0+#define SEV_SNP_ES_TMR_SIZE (2 * 1024 * 1024) + +static size_t sev_es_tmr_size =SEV_ES_TMR_SIZE ; + +static int __sev_do_cmd_locked (int cmd,void *data,int *psp_ret); +static int sev_do_cmd (int cmd,void *data,int *psp_ret); +static inline bool sev_version_greater_or_equal (u8 maj,u8 min) {struct sev_device *sev = psp_master->sev_data;
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 164
Quoted 6 lines
drivers/crypto/ccp/sev-dev.c +3
-0@@ -151,6 +159,112 @@ static int sev_cmd_buffer_len(int cmd)return 0 ; } +static int snp_reclaim_page (struct page *page,bool locked) +{ +struct sev_data_snp_page_reclaim data = {};
Hmmm.. according to some things I read online, an empty initializer list is not legal in C. For example:
https://stackoverflow.com/questions/17589533/is-an-empty-initializer-list-valid-c-code
I'm sure this is compiling. Should we change this to {0}, which I believe will initialize all fields in this struct to zero, according
to: https://stackoverflow.com/questions/11152160/initializing-a-struct-to-0?
Quoted 13 lines
drivers/crypto/ccp/sev-dev.c +13
-0+int ret, err; + + data.paddr =page_to_pfn (page) <<PAGE_SHIFT ; + +if (locked) + ret =__sev_do_cmd_locked (SEV_CMD_SNP_PAGE_RECLAIM , &data, &err); +else + ret =sev_do_cmd (SEV_CMD_SNP_PAGE_RECLAIM , &data, &err); + +return ret; +} + +static int snp_set_rmptable_state(unsigned long paddr, int npages,
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 187
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +10
-0+ struct rmpupdate *val, bool locked, bool need_reclaim) +{ + unsigned long pfn = __sme_clr(paddr) >> PAGE_SHIFT; +unsigned long pfn_end = pfn + npages; +struct psp_device *psp = psp_master; +struct sev_device *sev; +int rc; + +if (!psp || !psp->sev_data) +return 0 ;
Should this return a non-zero value -- maybe -ENODEV? Otherwise, the snp_alloc_firmware_page() API will return a page that the caller believes is suitable to use with FW. My concern is that someone decides to use this API to stash a page very early on during kernel boot and that page becomes a time bomb.
If we initialize rc to -ENODEV (or something similar), then every return in this function can be return rc.
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 192
Quoted 5 lines
drivers/crypto/ccp/sev-dev.c +5
-0+ +/* If SEV-SNP is initialized then add the page in RMP table. */ + sev = psp->sev_data; +if (!sev->snp_inited) +return 0 ;
Ditto. Should this turn a non-zero value?
Quoted 9 lines
drivers/crypto/ccp/sev-dev.c +9
-0+ +while (pfn < pfn_end) { +if (need_reclaim) +if (snp_reclaim_page (pfn_to_page (pfn), locked)) +return -EFAULT ; + + rc =rmpupdate (pfn_to_page (pfn), val); +if (rc) +return rc;
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 211
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +10
-0+ + pfn++; + } + +return 0 ; +} + +static struct page *__snp_alloc_firmware_pages (gfp_t gfp_mask,int order,bool locked) +{ +struct rmpupdate val = {};
{} -> {0}? (Not sure, see my previous comment.)
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 224
Quoted 13 lines
drivers/crypto/ccp/sev-dev.c +13
-0+unsigned long paddr; +struct page *page; + + page =alloc_pages (gfp_mask, order); +if (!page) +return NULL ; + + val.assigned =1 ; + val.immutable =1 ; + paddr =__pa ((unsigned long )page_address (page)); + +if (snp_set_rmptable_state (paddr,1 << order, &val, locked, false)) { +pr_warn ("Failed to set page state (leaking it)\n" );
Maybe WARN_ONCE instead of pr_warn? It's both a big attention grabber and also rate limited.
Quoted 9 lines
drivers/crypto/ccp/sev-dev.c +9
-0+return NULL ; + } + +return page; +} + +void *snp_alloc_firmware_page (gfp_t gfp_mask) +{ +struct page *page;
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 243
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +9
-0+ + page =__snp_alloc_firmware_pages (gfp_mask,0 , false); + +return page ?page_address (page) :NULL ; +} +EXPORT_SYMBOL_GPL (snp_alloc_firmware_page); +static void __snp_free_firmware_pages (struct page *page,int order,bool locked) +{ +struct rmpupdate val = {};
{} -> {0}? (Not sure, see my previous comment.)
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 252
Quoted 9 lines
drivers/crypto/ccp/sev-dev.c +9
-0+unsigned long paddr; + +if (!page) +return ; + + paddr =__pa ((unsigned long )page_address (page)); + +if (snp_set_rmptable_state (paddr,1 << order, &val, locked, true)) { +pr_warn ("Failed to set page state (leaking it)\n" );
WARN_ONCE?
Quoted 123 lines
drivers/crypto/ccp/sev-dev.c +32
-13+return ; + } + +__free_pages (page, order); +} + +void snp_free_firmware_page (void *addr) +{ +if (!addr) +return ; + +__snp_free_firmware_pages (virt_to_page (addr),0 , false); +} +EXPORT_SYMBOL (snp_free_firmware_page); +static int __sev_do_cmd_locked (int cmd,void *data,int *psp_ret) {struct psp_device *psp = psp_master;@@ -273,7 +387,7 @@ static int __sev_platform_init_locked(int *error) data.flags |=SEV_INIT_FLAGS_SEV_ES ; data.tmr_address = tmr_pa; - data.tmr_len =SEV_ES_TMR_SIZE ; + data.tmr_len = sev_es_tmr_size; } rc =__sev_do_cmd_locked (SEV_CMD_INIT , &data, error);@@ -630,6 +744,8 @@ static int __sev_snp_init_locked(int *error) sev->snp_inited = true;dev_dbg (sev->dev,"SEV-SNP firmware initialized\n" ); + sev_es_tmr_size =SEV_SNP_ES_TMR_SIZE ; +return rc; }@@ -1153,8 +1269,10 @@ static void sev_firmware_shutdown(struct sev_device *sev)/* The TMR area was encrypted, flush it from the cache */ wbinvd_on_all_cpus (); -free_pages ((unsigned long )sev_es_tmr, -get_order (SEV_ES_TMR_SIZE )); + +__snp_free_firmware_pages (virt_to_page (sev_es_tmr), +get_order (sev_es_tmr_size), + false); sev_es_tmr =NULL ; }@@ -1204,16 +1322,6 @@ void sev_pci_init(void) sev_update_firmware(sev->dev) == 0)sev_get_api_version (); -/* Obtain the TMR memory area for SEV-ES use */ - tmr_page =alloc_pages (GFP_KERNEL ,get_order (SEV_ES_TMR_SIZE )); -if (tmr_page) { - sev_es_tmr =page_address (tmr_page); - }else { - sev_es_tmr =NULL ; -dev_warn (sev->dev, -"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); - } -/* * If boot CPU supports the SNP, then first attempt to initialize * the SNP firmware. @@ -1229,6 +1337,16 @@ void sev_pci_init(void) } } +/* Obtain the TMR memory area for SEV-ES use */ + tmr_page =__snp_alloc_firmware_pages (GFP_KERNEL ,get_order (sev_es_tmr_size), false); +if (tmr_page) { + sev_es_tmr =page_address (tmr_page); + }else { + sev_es_tmr =NULL ; +dev_warn (sev->dev, +"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); + } +/* Initialize the platform */ rc =sev_platform_init (&error);if (rc && (error ==SEV_RET_SECURE_DATA_INVALID )) {include/linux/psp-sev.h +11
-1@@ -12,6 +12,8 @@#ifndef __PSP_SEV_H__#define __PSP_SEV_H__ +#include <linux/sev.h> +#include <uapi/linux/psp-sev.h> #ifdef CONFIG_X86 @@ -920,6 +922,8 @@ int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *error);void *psp_copy_user_blob (u64 uaddr,u32 len); +void *snp_alloc_firmware_page (gfp_t mask); +void snp_free_firmware_page (void *addr);#else /* !CONFIG_CRYPTO_DEV_SP_PSP */ @@ -961,6 +965,13 @@ static inline int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *erroreturn -ENODEV ; } +static inline void *snp_alloc_firmware_page (gfp_t mask) +{ +return NULL ; +} + +static inline void snp_free_firmware_page (void *addr) { } +#endif /* CONFIG_CRYPTO_DEV_SP_PSP */ #endif /* __PSP_SEV_H__ */ --2.17.1
Re: [PATCH Part2 RFC v4 15/40] crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
Quoted 12 lines · Marc Orr
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 164
Quoted 4 lines
drivers/crypto/ccp/sev-dev.c +3
-0+static int snp_reclaim_page (struct page *page,bool locked) +{ +struct sev_data_snp_page_reclaim data = {};Hmmm.. according to some things I read online, an empty initializer
list is not legal in C. For example:
https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F17589533%2Fis-an-empty-initializer-list-valid-c-code&data=04%7C01%7Cbrijesh.singh%40amd.com%7Cda82a72de9ab40237b1208d946ca78e6%7C3dd8961fe4884e608e11a82d994e183d%7C0%7C0%7C637618657748568732%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=zrK%2BUfXYGFVB5MfsmIIM0LtPDQ9UsAJxksCunosP9MY%3D&reserved=0
I'm sure this is compiling. Should we change this to{0}, which I
believe will initialize all fields in this struct to zero, according
to: https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F11152160%2Finitializing-a-struct-to-0&data=04%7C01%7Cbrijesh.singh%40amd.com%7Cda82a72de9ab40237b1208d946ca78e6%7C3dd8961fe4884e608e11a82d994e183d%7C0%7C0%7C637618657748568732%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=vpyAtB%2BZ6b%2BXD3VthQy2b8JtYzYnMceWb9cdj5UGlPg%3D&reserved=0?
Ah, good point. I will fix in next version.
Quoted 6 lines
Should this return a non-zero value -- maybe
-ENODEV? Otherwise, thesnp_alloc_firmware_page()API will return a page that the caller believes is suitable to use with FW. My concern is that someone decides to use this API to stash a page very early on during kernel boot and that page becomes a time bomb.
But that means the caller now need to know that SNP is enabled before calling the APIs. The idea behind the API was that caller does not need to know whether the firmware is in the INIT state. If the firmware has initialized the SNP, then it will transparently set the immutable bit in the RMP table.
Quoted 34 lines
If we initialize
rcto-ENODEV(or something similar), then every return in this function can bereturn rc.drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 192
Quoted 5 lines
drivers/crypto/ccp/sev-dev.c +5
-0+ +/* If SEV-SNP is initialized then add the page in RMP table. */ + sev = psp->sev_data; +if (!sev->snp_inited) +return 0 ;Ditto. Should this turn a non-zero value?
Quoted 9 lines
drivers/crypto/ccp/sev-dev.c +9
-0+ +while (pfn < pfn_end) { +if (need_reclaim) +if (snp_reclaim_page (pfn_to_page (pfn), locked)) +return -EFAULT ; + + rc =rmpupdate (pfn_to_page (pfn), val); +if (rc) +return rc;drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 211
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +10
-0+ + pfn++; + } + +return 0 ; +} + +static struct page *__snp_alloc_firmware_pages (gfp_t gfp_mask,int order,bool locked) +{ +struct rmpupdate val = {};
{}->{0}? (Not sure, see my previous comment.)
Quoted 16 lines
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 224
Quoted 13 lines
drivers/crypto/ccp/sev-dev.c +13
-0+unsigned long paddr; +struct page *page; + + page =alloc_pages (gfp_mask, order); +if (!page) +return NULL ; + + val.assigned =1 ; + val.immutable =1 ; + paddr =__pa ((unsigned long )page_address (page)); + +if (snp_set_rmptable_state (paddr,1 << order, &val, locked, false)) { +pr_warn ("Failed to set page state (leaking it)\n" );Maybe
WARN_ONCEinstead ofpr_warn? It's both a big attention grabber and also rate limited.
Noted.
Quoted 23 lines
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +9
-0+return NULL ; + } + +return page; +} + +void *snp_alloc_firmware_page (gfp_t gfp_mask) +{ +struct page *page;drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 243
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +9
-0+ + page =__snp_alloc_firmware_pages (gfp_mask,0 , false); + +return page ?page_address (page) :NULL ; +} +EXPORT_SYMBOL_GPL (snp_alloc_firmware_page); +static void __snp_free_firmware_pages (struct page *page,int order,bool locked) +{ +struct rmpupdate val = {};
{}->{0}? (Not sure, see my previous comment.)
Quoted 11 lines
drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 252
Quoted 9 lines
drivers/crypto/ccp/sev-dev.c +9
-0+unsigned long paddr; + +if (!page) +return ; + + paddr =__pa ((unsigned long )page_address (page)); + +if (snp_set_rmptable_state (paddr,1 << order, &val, locked, true)) { +pr_warn ("Failed to set page state (leaking it)\n" );
WARN_ONCE?
Noted.
thanks
Re: [PATCH Part2 RFC v4 15/40] crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
Quoted 11 lines
Quoted 5 lines
Should this return a non-zero value -- maybe
-ENODEV? Otherwise, thesnp_alloc_firmware_page()API will return a page that the caller believes is suitable to use with FW. My concern is that someone decides to use this API to stash a page very early on during kernel boot and that page becomes a time bomb.But that means the caller now need to know that SNP is enabled before calling the APIs. The idea behind the API was that caller does not need to know whether the firmware is in the INIT state. If the firmware has initialized the SNP, then it will transparently set the immutable bit in the RMP table.
For SNP, isn't that already the case? There are three scenarios:
#1: The PSP driver is loaded and snp_inited is true: These returns are never hit.
#2: The PSP driver is not loaded. The first return, !psp || !psp->sev_data fires. As written, it returns 0, indicating success. However, we never called RMPUPDATE on the page. Thus, later, when the PSP driver is loaded, the page that was previously returned as usable with FW is in fact not usable with FW. Unless SNP is disabled (e.g., SEV, SEV-ES only). In which case I guess the page is OK.
#3 The PSP driver is loaded but the SNP_INIT command has not been issued. Looking at this again, I guess return 0 is OK. Because if we got this far, then sev_pci_init() has been called, and the SNP_INIT command has been issued if we're supporting SNP VMs.
So in summary, I think we should change the first return to return an error and leave the 2nd return as is.
Quoted 26 lines
Quoted 26 lines
If we initialize
rcto-ENODEV(or something similar), then every return in this function can bereturn rc.drivers/crypto/ccp/sev-dev.c static int sev_cmd_buffer_len(int cmd) · line 192
Quoted 5 lines
drivers/crypto/ccp/sev-dev.c +5
-0+ +/* If SEV-SNP is initialized then add the page in RMP table. */ + sev = psp->sev_data; +if (!sev->snp_inited) +return 0 ;Ditto. Should this turn a non-zero value?
Quoted 15 lines
drivers/crypto/ccp/sev-dev.c +15
-0+ +while (pfn < pfn_end) { +if (need_reclaim) +if (snp_reclaim_page (pfn_to_page (pfn), locked)) +return -EFAULT ; + + rc =rmpupdate (pfn_to_page (pfn), val); +if (rc) +return rc; + + pfn++; + } + +return 0 ; +}
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 15/40] crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
In reply to Brijesh SinghQuoted 6 lines · Brijesh Singh
The behavior and requirement for the SEV-legacy command is altered when the SNP firmware is in the INIT state. See SEV-SNP firmware specification for more details.
When SNP is INIT state, all the SEV-legacy commands that cause the firmware to write memory must be in the firmware state. The TMR memory
It'd be helpful to spell out Trusted Memory Region, I hadn't seen that term before and for some reason my brain immediately thought "xAPIC register!".
Quoted 5 lines
is allocated by the host but updated by the firmware, so, it must be in the firmware state. Additionally, the TMR memory must be a 2MB aligned instead of the 1MB, and the TMR length need to be 2MB instead of 1MB. The helper __snp_{alloc,free}_firmware_pages() can be used for allocating and freeing the memory used by the firmware.
None of this actually states what the patch does, e.g. it's not clear whether all allocations are being converted to 2mb or just the SNP. Looks like it's just SNP. Something like this?
Allocate the Trusted Memory Region (TMR) as a 2mb sized/aligned region when SNP is enabled to satisfy new requirements for SNP. Continue allocating a 1mb region for !SNP configuration.
Quoted 5 lines
While at it, provide API that can be used by others to allocate a page that can be used by the firmware. The immediate user for this API will be the KVM driver. The KVM driver to need to allocate a firmware context page during the guest creation. The context page need to be updated by the firmware. See the SEV-SNP specification for further details.
...
Quoted 33 lines
drivers/crypto/ccp/sev-dev.c +4
-12@@ -1153,8 +1269,10 @@ static void sev_firmware_shutdown(struct sev_device *sev)/* The TMR area was encrypted, flush it from the cache */ wbinvd_on_all_cpus (); -free_pages ((unsigned long )sev_es_tmr, -get_order (SEV_ES_TMR_SIZE )); + +__snp_free_firmware_pages (virt_to_page (sev_es_tmr), +get_order (sev_es_tmr_size), + false); sev_es_tmr =NULL ; }@@ -1204,16 +1322,6 @@ void sev_pci_init(void) sev_update_firmware(sev->dev) == 0)sev_get_api_version (); -/* Obtain the TMR memory area for SEV-ES use */ - tmr_page =alloc_pages (GFP_KERNEL ,get_order (SEV_ES_TMR_SIZE )); -if (tmr_page) { - sev_es_tmr =page_address (tmr_page); - }else { - sev_es_tmr =NULL ; -dev_warn (sev->dev, -"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); - } -/* * If boot CPU supports the SNP, then first attempt to initialize * the SNP firmware. @@ -1229,6 +1337,16 @@ void sev_pci_init(void) } }
drivers/crypto/ccp/sev-dev.c void sev_pci_init(void) · line 1348
Quoted 10 lines
drivers/crypto/ccp/sev-dev.c +9
-0+/* Obtain the TMR memory area for SEV-ES use */ + tmr_page =__snp_alloc_firmware_pages (GFP_KERNEL ,get_order (sev_es_tmr_size), false); +if (tmr_page) { + sev_es_tmr =page_address (tmr_page); + }else { + sev_es_tmr =NULL ; +dev_warn (sev->dev, +"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); + }
I think your patch ordering got a bit wonky. AFAICT, the chunk that added sev_snp_init() and friends in the previous patch 14 should have landed above the TMR allocation, i.e. the code movement here should be unnecessary.
Quoted 3 lines
drivers/crypto/ccp/sev-dev.c +0
-0/* Initialize the platform */ rc =sev_platform_init (&error);if (rc && (error ==SEV_RET_SECURE_DATA_INVALID )) {
...
include/linux/psp-sev.h static inline int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *erro · line 973
Quoted 10 lines
include/linux/psp-sev.h +6
-0@@ -961,6 +965,13 @@ static inline int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *erroreturn -ENODEV ; } +static inline void *snp_alloc_firmware_page (gfp_t mask) +{ +return NULL ; +} + +static inline void snp_free_firmware_page (void *addr) { }
Hmm, I think we should probably bite the bullet and #ifdef and/or stub out large swaths of svm/sev.c before adding SNP support. sev.c is getting quite massive, and we're accumulating more and more stubs outside of KVM because its SEV code is compiled unconditionally.
Re: [PATCH Part2 RFC v4 15/40] crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
Quoted 9 lines · Sean Christopherson
Quoted 6 lines · Brijesh Singh
The behavior and requirement for the SEV-legacy command is altered when the SNP firmware is in the INIT state. See SEV-SNP firmware specification for more details.
When SNP is INIT state, all the SEV-legacy commands that cause the firmware to write memory must be in the firmware state. The TMR memory
It'd be helpful to spell out Trusted Memory Region, I hadn't seen that term before and for some reason my brain immediately thought "xAPIC register!".
Noted.
Quoted 6 lines
Quoted 6 lines
is allocated by the host but updated by the firmware, so, it must be in the firmware state. Additionally, the TMR memory must be a 2MB aligned instead of the 1MB, and the TMR length need to be 2MB instead of 1MB. The helper __snp_{alloc,free}_firmware_pages() can be used for allocating and freeing the memory used by the firmware.
Quoted 8 lines
None of this actually states what the patch does, e.g. it's not clear whether all allocations are being converted to 2mb or just the SNP. Looks like it's just SNP. Something like this?
Allocate the Trusted Memory Region (TMR) as a 2mb sized/aligned region when SNP is enabled to satisfy new requirements for SNP. Continue allocating a 1mb region for !SNP configuration.
Only the TMR allocation is converted to use the 2mb when SNP is enabled.
Quoted 41 lines
Quoted 5 lines
While at it, provide API that can be used by others to allocate a page that can be used by the firmware. The immediate user for this API will be the KVM driver. The KVM driver to need to allocate a firmware context page during the guest creation. The context page need to be updated by the firmware. See the SEV-SNP specification for further details.
...
Quoted 34 lines
drivers/crypto/ccp/sev-dev.c +4
-12@@ -1153,8 +1269,10 @@ static void sev_firmware_shutdown(struct sev_device *sev)/* The TMR area was encrypted, flush it from the cache */ wbinvd_on_all_cpus (); -free_pages ((unsigned long )sev_es_tmr, -get_order (SEV_ES_TMR_SIZE )); + +__snp_free_firmware_pages (virt_to_page (sev_es_tmr), +get_order (sev_es_tmr_size), + false); sev_es_tmr =NULL ; }@@ -1204,16 +1322,6 @@ void sev_pci_init(void) sev_update_firmware(sev->dev) == 0)sev_get_api_version (); -/* Obtain the TMR memory area for SEV-ES use */ - tmr_page =alloc_pages (GFP_KERNEL ,get_order (SEV_ES_TMR_SIZE )); -if (tmr_page) { - sev_es_tmr =page_address (tmr_page); - }else { - sev_es_tmr =NULL ; -dev_warn (sev->dev, -"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); - } -/* * If boot CPU supports the SNP, then first attempt to initialize * the SNP firmware. @@ -1229,6 +1337,16 @@ void sev_pci_init(void) } }
Quoted 12 lines
drivers/crypto/ccp/sev-dev.c void sev_pci_init(void) · line 1348
Quoted 9 lines
drivers/crypto/ccp/sev-dev.c +9
-0+/* Obtain the TMR memory area for SEV-ES use */ + tmr_page =__snp_alloc_firmware_pages (GFP_KERNEL ,get_order (sev_es_tmr_size), false); +if (tmr_page) { + sev_es_tmr =page_address (tmr_page); + }else { + sev_es_tmr =NULL ; +dev_warn (sev->dev, +"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); + }I think your patch ordering got a bit wonky. AFAICT, the chunk that added
sev_snp_init()and friends in the previous patch 14 should have landed above the TMR allocation, i.e. the code movement here should be unnecessary.
I was debating about it whether to include all the SNP supports in one patch or divide it up. If I had included all legacy support new requirement in the same patch which adds the SNP then it will be a big patch. I had feeling that others may ask me to split it. So my approach is:
* In the first patch adds SNP support only
* Improve the legacy SEV/ES for the requirement when SNP is enabled. Once SNP is enabled, there are two new requirement for the legacy SEV/ES guests
1) TMR must be 2mb
2) The buffer given to the firmware for the write must be in the firmware state.
I also divided both of the new requirement in separate patches so that its easy to review.
Quoted 20 lines
Quoted 4 lines
drivers/crypto/ccp/sev-dev.c +0
-0/* Initialize the platform */ rc =sev_platform_init (&error);if (rc && (error ==SEV_RET_SECURE_DATA_INVALID )) {...
include/linux/psp-sev.h static inline int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *erro · line 973
Quoted 10 lines
include/linux/psp-sev.h +6
-0@@ -961,6 +965,13 @@ static inline int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *erroreturn -ENODEV ; } +static inline void *snp_alloc_firmware_page (gfp_t mask) +{ +return NULL ; +} + +static inline void snp_free_firmware_page (void *addr) { }Hmm, I think we should probably bite the bullet and #ifdef and/or stub out large swaths of
svm/sev.cbefore adding SNP support.sev.cis getting quite massive, and we're accumulating more and more stubs outside of KVM because its SEV code is compiled unconditionally.
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 15/40] crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
Quoted 37 lines · Brijesh Singh
Quoted 22 lines · Sean Christopherson
Quoted 21 lines · Brijesh Singh
drivers/crypto/ccp/sev-dev.c +0
-10@@ -1204,16 +1322,6 @@ void sev_pci_init(void) sev_update_firmware(sev->dev) == 0)sev_get_api_version (); -/* Obtain the TMR memory area for SEV-ES use */ - tmr_page =alloc_pages (GFP_KERNEL ,get_order (SEV_ES_TMR_SIZE )); -if (tmr_page) { - sev_es_tmr =page_address (tmr_page); - }else { - sev_es_tmr =NULL ; -dev_warn (sev->dev, -"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); - } -/* * If boot CPU supports the SNP, then first attempt to initialize * the SNP firmware. @@ -1229,6 +1337,16 @@ void sev_pci_init(void) } }Quoted 12 lines
drivers/crypto/ccp/sev-dev.c void sev_pci_init(void) · line 1348
Quoted 9 lines
drivers/crypto/ccp/sev-dev.c +9
-0+/* Obtain the TMR memory area for SEV-ES use */ + tmr_page =__snp_alloc_firmware_pages (GFP_KERNEL ,get_order (sev_es_tmr_size), false); +if (tmr_page) { + sev_es_tmr =page_address (tmr_page); + }else { + sev_es_tmr =NULL ; +dev_warn (sev->dev, +"SEV: TMR allocation failed, SEV-ES support unavailable\n" ); + }I think your patch ordering got a bit wonky. AFAICT, the chunk that added
sev_snp_init()and friends in the previous patch 14 should have landed above the TMR allocation, i.e. the code movement here should be unnecessary.
Quoted 4 lines
I was debating about it whether to include all the SNP supports in one patch or divide it up. If I had included all legacy support new requirement in the same patch which adds the SNP then it will be a big patch. I had feeling that others may ask me to split it.
It wasn't comment on the patch organization, rather that the code added in patch 14 appears to have landed in the wrong location within the code. The above diff shows that the TMR allocation is being moved around the SNP initialization code that was added in patch 14 (the immediately prior patch). Presumably the required order doesn't magically change just because the TMR is now being allocated as a 2mb blob, so either the code movement is unnecessary churn or the original location was wrong. In either case, landing the SNP initialization code above the TMR allocation in patch 14 would eliminate the above code movement.
Re: [PATCH Part2 RFC v4 15/40] crypto: ccp: Handle the legacy TMR allocation when SNP is enabled
Quoted 8 lines · Sean Christopherson
It wasn't comment on the patch organization, rather that the code added in patch 14 appears to have landed in the wrong location within the code. The above diff shows that the TMR allocation is being moved around the SNP initialization code that was added in patch 14 (the immediately prior patch). Presumably the required order doesn't magically change just because the TMR is now being allocated as a 2mb blob, so either the code movement is unnecessary churn or the original location was wrong. In either case, landing the SNP initialization code above the TMR allocation in patch 14 would eliminate the above code movement.
Got it, I'll rearrange things in the previous patch to avoid this hunk.
thanks
RFC PATCH v4 16/40 crypto: ccp: Handle the legacy SEV command when SNP is enabled
In reply to Brijesh SinghThe behavior of the SEV-legacy commands is altered when the SNP firmware is in the INIT state. When SNP is in INIT state, all the SEV-legacy commands that cause the firmware to write to memory must be in the firmware state before issuing the command..
A command buffer may contains a system physical address that the firmware may write to. There are two cases that need to be handled:
1) system physical address points to a guest memory
2) system physical address points to a host memory
To handle the case #1, map_firmware_writeable() helper simply changes the page state in the RMP table before and after the command is sent to the firmware.
For the case #2, the map_firmware_writeable() replaces the host system physical memory with a pre-allocated firmware page, and after the command completes, the unmap_firmware_writeable() copies the content from pre-allocated firmware page to original host system physical.
The unmap_firmware_writeable() calls a __sev_do_cmd_locked() to clear the immutable bit from the memory page. To support the nested calling, a separate command buffer is required. Allocate a backup command buffer and keep reference count of it. If a nested call is detected then use the backup cmd_buf to complete the command submission.
--- drivers/crypto/ccp/sev-dev.c | 349 ++++++++++++++++++++++++++++++++++- drivers/crypto/ccp/sev-dev.h | 12 ++ 2 files changed, 351 insertions(+), 10 deletions(-)
drivers/crypto/ccp/sev-dev.c +339 -10
@@ -265,12 +265,300 @@ void snp_free_firmware_page(void *addr) }EXPORT_SYMBOL (snp_free_firmware_page); +static int alloc_snp_host_map (struct sev_device *sev) +{ +struct page *page; +int i; + +for (i =0 ; i <MAX_SNP_HOST_MAP_BUFS ; i++) { +struct snp_host_map *map = &sev->snp_host_map[i]; + +memset (map,0 ,sizeof (*map)); + + page =__snp_alloc_firmware_pages (GFP_KERNEL_ACCOUNT , +get_order (SEV_FW_BLOB_MAX_SIZE ), false); +if (!page) +return -ENOMEM ; + + map->host =page_address (page); + } + +return 0 ; +} + +static void free_snp_host_map (struct sev_device *sev) +{ +int i; + +for (i =0 ; i <MAX_SNP_HOST_MAP_BUFS ; i++) { +struct snp_host_map *map = &sev->snp_host_map[i]; + +if (map->host) { +__snp_free_firmware_pages (virt_to_page (map->host), +get_order (SEV_FW_BLOB_MAX_SIZE ), + false); +memset (map,0 ,sizeof (*map)); + } + } +} + +static int map_firmware_writeable (u64 *paddr,u32 len,bool guest,struct snp_host_map *map) +{ +unsigned int npages =PAGE_ALIGN (len) >>PAGE_SHIFT ; +int ret; + + map->active = false; + +if (!paddr || !len) +return 0 ; + + map->paddr = *paddr; + map->len = len; + +/* If paddr points to a guest memory then change the page state to firmwware. */ +if (guest) { +struct rmpupdate val = {}; + + val.immutable = true; + val.assigned = true; + ret =snp_set_rmptable_state (*paddr, npages, &val, true, false); +if (ret) +return ret; + + goto done; + } + +if (unlikely (!map->host)) +return -EINVAL ; + +/* Check if the pre-allocated buffer can be used to fullfil the request. */ +if (unlikely (len >SEV_FW_BLOB_MAX_SIZE )) +return -EINVAL ; + +/* Set the paddr to use an intermediate firmware buffer */ + *paddr =__psp_pa (map->host); + +done: + map->active = true; +return 0 ; +} + +static int unmap_firmware_writeable (u64 *paddr,u32 len,bool guest,struct snp_host_map *map) +{ +unsigned int npages =PAGE_ALIGN (len) >>PAGE_SHIFT ; +int ret; + +if (!map->active) +return 0 ; + +/* If paddr points to a guest memory then restore the page state to hypervisor. */ +if (guest) { +struct rmpupdate val = {}; + + ret =snp_set_rmptable_state (*paddr, npages, &val, true, true); +if (ret) +return ret; + + goto done; + } + +/* Copy the response data firmware buffer to the callers buffer. */ +memcpy (__va (__sme_clr (map->paddr)), map->host,min_t (size_t, len, map->len)); + *paddr = map->paddr; + +done: + map->active = false; +return 0 ; +} + +static bool sev_legacy_cmd_buf_writable (int cmd) +{ +switch (cmd) { +case SEV_CMD_PLATFORM_STATUS : +case SEV_CMD_GUEST_STATUS : +case SEV_CMD_LAUNCH_START : +case SEV_CMD_RECEIVE_START : +case SEV_CMD_LAUNCH_MEASURE : +case SEV_CMD_SEND_START : +case SEV_CMD_SEND_UPDATE_DATA : +case SEV_CMD_SEND_UPDATE_VMSA : +case SEV_CMD_PEK_CSR : +case SEV_CMD_PDH_CERT_EXPORT : +case SEV_CMD_GET_ID : +case SEV_CMD_ATTESTATION_REPORT : +return true; +default : +return false; + } +} + +#define prep_buffer (name, addr, len, guest, map) \ + func(&((typeof(name *))cmd_buf)->addr, ((typeof(name *))cmd_buf)->len, guest, map) + +static int __snp_cmd_buf_copy (int cmd,void *cmd_buf,bool to_fw,int fw_err) +{ +int (*func)(u64 *paddr,u32 len,bool guest,struct snp_host_map *map); +struct sev_device *sev = psp_master->sev_data; +struct rmpupdate val = {}; +bool from_fw = !to_fw; +int ret; + +/* +* After the command is completed, change the command buffer memory to +* hypervisor state. +* +* The immutable bit is automatically cleared by the firmware, so +* no not need to reclaim the page. +*/ +if (from_fw &&sev_legacy_cmd_buf_writable (cmd)) { + ret =snp_set_rmptable_state (__pa (cmd_buf),1 , &val, true, false); +if (ret) +return ret; + +/* No need to go further if firmware failed to execute command. */ +if (fw_err) +return 0 ; + } + +if (to_fw) + func = map_firmware_writeable; +else + func = unmap_firmware_writeable; + +/* +* A command buffer may contains a system physical address. If the address +* points to a host memory then use an intermediate firmware page otherwise +* change the page state in the RMP table. +*/ +switch (cmd) { +case SEV_CMD_PDH_CERT_EXPORT : + if (prep_buffer(struct sev_data_pdh_cert_export, pdh_cert_address, + pdh_cert_len, false, &sev->snp_host_map[0 ])) + goto err; + if (prep_buffer(struct sev_data_pdh_cert_export, cert_chain_address, + cert_chain_len, false, &sev->snp_host_map[1 ])) + goto err; +break ; +case SEV_CMD_GET_ID : + if (prep_buffer(struct sev_data_get_id, address, len, + false, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_PEK_CSR : + if (prep_buffer(struct sev_data_pek_csr, address, len, + false, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_LAUNCH_UPDATE_DATA : + if (prep_buffer(struct sev_data_launch_update_data, address, len, + true, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_LAUNCH_UPDATE_VMSA : + if (prep_buffer(struct sev_data_launch_update_vmsa, address, len, + true, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_LAUNCH_MEASURE : + if (prep_buffer(struct sev_data_launch_measure, address, len, + false, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_LAUNCH_UPDATE_SECRET : + if (prep_buffer(struct sev_data_launch_secret, guest_address, guest_len, + true, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_DBG_DECRYPT : + if (prep_buffer(struct sev_data_dbg, dst_addr, len, false, + &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_DBG_ENCRYPT : + if (prep_buffer(struct sev_data_dbg, dst_addr, len, true, + &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_ATTESTATION_REPORT : + if (prep_buffer(struct sev_data_attestation_report, address, len, + false, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_SEND_START : + if (prep_buffer(struct sev_data_send_start, session_address, + session_len, false, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_SEND_UPDATE_DATA : + if (prep_buffer(struct sev_data_send_update_data, hdr_address, hdr_len, + false, &sev->snp_host_map[0 ])) + goto err; + if (prep_buffer(struct sev_data_send_update_data, trans_address, + trans_len, false, &sev->snp_host_map[1 ])) + goto err; +break ; +case SEV_CMD_SEND_UPDATE_VMSA : + if (prep_buffer(struct sev_data_send_update_vmsa, hdr_address, hdr_len, + false, &sev->snp_host_map[0 ])) + goto err; + if (prep_buffer(struct sev_data_send_update_vmsa, trans_address, + trans_len, false, &sev->snp_host_map[1 ])) + goto err; +break ; +case SEV_CMD_RECEIVE_UPDATE_DATA : + if (prep_buffer(struct sev_data_receive_update_data, guest_address, + guest_len, true, &sev->snp_host_map[0 ])) + goto err; +break ; +case SEV_CMD_RECEIVE_UPDATE_VMSA : + if (prep_buffer(struct sev_data_receive_update_vmsa, guest_address, + guest_len, true, &sev->snp_host_map[0 ])) + goto err; +break ; +default : +break ; + } + +/* The command buffer need to be in the firmware state. */ +if (to_fw &&sev_legacy_cmd_buf_writable (cmd)) { + val.assigned = true; + val.immutable = true; + ret =snp_set_rmptable_state (__pa (cmd_buf),1 , &val, true, false); +if (ret) +return ret; + } + +return 0 ; + +err: +return -EINVAL ; +} + +static inline bool need_firmware_copy (int cmd) +{ +struct sev_device *sev = psp_master->sev_data; + +/* After SNP is INIT'ed, the behavior of legacy SEV command is changed. */ +return ((cmd <SEV_CMD_SNP_INIT ) && sev->snp_inited) ? true : false; +} + +static int snp_aware_copy_to_firmware (int cmd,void *data) +{ +return __snp_cmd_buf_copy (cmd, data, true,0 ); +} + +static int snp_aware_copy_from_firmware (int cmd,void *data,int fw_err) +{ +return __snp_cmd_buf_copy (cmd, data, false, fw_err); +} +static int __sev_do_cmd_locked (int cmd,void *data,int *psp_ret) {struct psp_device *psp = psp_master;struct sev_device *sev;unsigned int phys_lsb, phys_msb;unsigned int reg, ret =0 ; +void *cmd_buf;int buf_len;if (!psp || !psp->sev_data)
@@ -290,12 +578,26 @@ static int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret)* work for some memory, e.g. vmalloc'd addresses, and @data may not be * physically contiguous. */ -if (data) -memcpy (sev->cmd_buf, data, buf_len); +if (data) { +if (unlikely (sev->cmd_buf_active >2 )) +return -EBUSY ; + + cmd_buf = sev->cmd_buf_active ? sev->cmd_buf_backup : sev->cmd_buf; + +memcpy (cmd_buf, data, buf_len); + sev->cmd_buf_active++; + +/* +* The behavior of the SEV-legacy commands is altered when the +* SNP firmware is in the INIT state. +*/ +if (need_firmware_copy (cmd) &&snp_aware_copy_to_firmware (cmd, sev->cmd_buf)) +return -EFAULT ; + }/* Get the physical address of the command buffer */ - phys_lsb = data ?lower_32_bits (__psp_pa (sev->cmd_buf)) :0 ; - phys_msb = data ?upper_32_bits (__psp_pa (sev->cmd_buf)) :0 ; + phys_lsb = data ?lower_32_bits (__psp_pa (cmd_buf)) :0 ; + phys_msb = data ?upper_32_bits (__psp_pa (cmd_buf)) :0 ;dev_dbg (sev->dev,"sev command id %#x buffer 0x%08x%08x timeout %us\n" , cmd, phys_msb, phys_lsb, psp_timeout);
@@ -336,15 +638,24 @@ static int __sev_do_cmd_locked(int cmd, void *data, int *psp_ret) ret = -EIO ; } -print_hex_dump_debug ("(out): " ,DUMP_PREFIX_OFFSET ,16 ,2 , data, - buf_len, false); -/* * Copy potential output from the PSP back to data. Do this even on * failure in case the caller wants to glean something from the error. */ -if (data) -memcpy (data, sev->cmd_buf, buf_len); +if (data) { +/* +* Restore the page state after the command completes. +*/ +if (need_firmware_copy (cmd) && +snp_aware_copy_from_firmware (cmd, cmd_buf, ret)) +return -EFAULT ; + +memcpy (data, cmd_buf, buf_len); + sev->cmd_buf_active--; + } + +print_hex_dump_debug ("(out): " ,DUMP_PREFIX_OFFSET ,16 ,2 , data, + buf_len, false);return ret; }
@@ -1219,10 +1530,12 @@ int sev_dev_init(struct psp_device *psp)if (!sev) goto e_err; - sev->cmd_buf = (void *)devm_get_free_pages (dev,GFP_KERNEL ,0 ); + sev->cmd_buf = (void *)devm_get_free_pages (dev,GFP_KERNEL ,1 );if (!sev->cmd_buf) goto e_sev; + sev->cmd_buf_backup = (uint8_t *)sev->cmd_buf +PAGE_SIZE ; + psp->sev_data = sev; sev->dev = dev;
@@ -1276,6 +1589,12 @@ static void sev_firmware_shutdown(struct sev_device *sev) sev_es_tmr =NULL ; } +/* +* The host map need to clear the immutable bit so it must be free'd before the +* SNP firmware shutdown. +*/ +free_snp_host_map (sev); +sev_snp_shutdown (NULL ); }
@@ -1335,6 +1654,14 @@ void sev_pci_init(void)*/ dev_err (sev->dev,"SEV-SNP: failed to INIT error %#x\n" , error); } + +/* +* Allocate the intermediate buffers used for the legacy command handling. +*/ +if (alloc_snp_host_map (sev)) { +dev_notice (sev->dev,"Failed to alloc host map (disabling legacy SEV)\n" ); + goto skip_legacy; + } }/* Obtain the TMR memory area for SEV-ES use */
@@ -1364,12 +1691,14 @@ void sev_pci_init(void)if (rc)dev_err (sev->dev,"SEV: failed to INIT error %#x\n" , error); +skip_legacy:dev_info (sev->dev,"SEV%s API:%d.%d build:%d\n" , sev->snp_inited ?"-SNP" :"" , sev->api_major, sev->api_minor, sev->build);return ; err: +free_snp_host_map (sev); psp_master->sev_data =NULL ; }
drivers/crypto/ccp/sev-dev.h +12 -0
@@ -29,11 +29,20 @@#define SEV_CMDRESP_CMD_SHIFT 16#define SEV_CMDRESP_IOC BIT(0) +#define MAX_SNP_HOST_MAP_BUFS 2 +struct sev_misc_dev {struct kref refcount;struct miscdevice misc; }; +struct snp_host_map { +u64 paddr; +u32 len; +void *host; +bool active; +}; +struct sev_device {struct device *dev;struct psp_device *psp;
@@ -52,8 +61,11 @@ struct sev_device {u8 build;void *cmd_buf; +void *cmd_buf_backup; +int cmd_buf_active;bool snp_inited; +struct snp_host_map snp_host_map[MAX_SNP_HOST_MAP_BUFS ]; };int sev_dev_init (struct psp_device *psp);
Signature · 1 line
2.17.1
RFC PATCH v4 17/40 crypto: ccp: Add the SNP_PLATFORM_STATUS command
In reply to Brijesh SinghThe command can be used by the userspace to query the SNP platform status report. See the SEV-SNP spec for more details.
--- Documentation/virt/coco/sevguest.rst | 27 ++++++++++++++++++++++++ drivers/crypto/ccp/sev-dev.c | 31 ++++++++++++++++++++++++++++ drivers/crypto/ccp/sev-dev.h | 1 + include/uapi/linux/psp-sev.h | 1 + 4 files changed, 60 insertions(+)
Documentation/virt/coco/sevguest.rst +27 -0
@@ -52,6 +52,22 @@ to execute due to the firmware error, then fw_err code will be set. __u64 fw_err; }; +The host ioctl should be called to /dev/sev device. The ioctl accepts command +id and command input structure. + +:: + struct sev_issue_cmd { + /* Command ID */ + __u32 cmd; + + /* Command request structure */ + __u64 data; + + /* firmware error code on failure (see psp-sev.h) */ + __u32 error; + }; + + 2.1 SNP_GET_REPORT ------------------
@@ -107,3 +123,14 @@ length of the blob is lesser than expected then snp_ext_report_req.certs_len wil be updated with the expected value. See GHCB specification for further detail on how to parse the certificate blob. + +2.3 SNP_PLATFORM_STATUS +----------------------- +:Technology: sev-snp +:Type: hypervisor ioctl cmd +:Parameters (in): struct sev_data_snp_platform_status +:Returns (out): 0 on success, -negative on error + +The SNP_PLATFORM_STATUS command is used to query the SNP platform status. The +status includes API major, minor version and more. See the SEV-SNP +specification for further details.
drivers/crypto/ccp/sev-dev.c +31 -0
@@ -1056,6 +1056,7 @@ static int __sev_snp_init_locked(int *error)dev_dbg (sev->dev,"SEV-SNP firmware initialized\n" ); sev_es_tmr_size =SEV_SNP_ES_TMR_SIZE ; + sev->snp_plat_status_page =__snp_alloc_firmware_pages (GFP_KERNEL_ACCOUNT ,0 , true);return rc; }
@@ -1083,6 +1084,9 @@ static int __sev_snp_shutdown_locked(int *error)if (!sev->snp_inited)return 0 ; +/* Free the status page */ +__snp_free_firmware_pages (sev->snp_plat_status_page,0 , true); +/* SHUTDOWN requires the DF_FLUSH */ wbinvd_on_all_cpus ();__sev_do_cmd_locked (SEV_CMD_SNP_DF_FLUSH ,NULL ,NULL );
@@ -1345,6 +1349,30 @@ static int sev_ioctl_do_pdh_export(struct sev_issue_cmd *argp, bool writable)return ret; } +static int sev_ioctl_snp_platform_status (struct sev_issue_cmd *argp) +{ +struct sev_device *sev = psp_master->sev_data; +struct sev_data_snp_platform_status_buf buf; +int ret; + +if (!sev->snp_inited || !argp->data) +return -EINVAL ; + +if (!sev->snp_plat_status_page) +return -ENOMEM ; + + buf.status_paddr =__psp_pa (page_address (sev->snp_plat_status_page)); + ret =__sev_do_cmd_locked (SEV_CMD_SNP_PLATFORM_STATUS , &buf, &argp->error); +if (ret) +return ret; + +if (copy_to_user ((void __user *)argp->data,page_address (sev->snp_plat_status_page), +sizeof (struct sev_user_data_snp_status ))) +return -EFAULT ; + +return 0 ; +} +static long sev_ioctl (struct file *file,unsigned int ioctl,unsigned long arg) {void __user *argp = (void __user *)arg;
@@ -1396,6 +1424,9 @@ static long sev_ioctl(struct file *file, unsigned int ioctl, unsigned long arg)case SEV_GET_ID2 : ret =sev_ioctl_do_get_id2 (&input);break ; +case SNP_PLATFORM_STATUS : + ret =sev_ioctl_snp_platform_status (&input); +break ;default : ret = -EINVAL ; goto out;
drivers/crypto/ccp/sev-dev.h +1 -0
@@ -66,6 +66,7 @@ struct sev_device {bool snp_inited;struct snp_host_map snp_host_map[MAX_SNP_HOST_MAP_BUFS ]; +struct page *snp_plat_status_page; };int sev_dev_init (struct psp_device *psp);
include/uapi/linux/psp-sev.h +1 -0
@@ -28,6 +28,7 @@ enum {SEV_PEK_CERT_IMPORT ,SEV_GET_ID ,/* This command is deprecated, use SEV_GET_ID2 */ SEV_GET_ID2 , +SNP_PLATFORM_STATUS =256 , SEV_MAX, };
Signature · 1 line
2.17.1
RFC PATCH v4 18/40 crypto: ccp: Add the SNP_{SET,GET}_EXT_CONFIG command
In reply to Brijesh SinghThe SEV-SNP firmware provides the SNP_CONFIG command used to set the system-wide configuration value for SNP guests. The information includes the TCB version string to be reported in guest attestation reports.
Version 2 of the GHCB specification adds an NAE (SNP extended guest request) that a guest can use to query the reports that include additional certificates.
In both cases, userspace provided additional data is included in the attestation reports. The userspace will use the SNP_SET_EXT_CONFIG command to give the certificate blob and the reported TCB version string at once. Note that the specification defines certificate blob with a specific GUID format; the userspace is responsible for building the proper certificate blob. The ioctl treats it an opaque blob.
While it is not defined in the spec, but let's add SNP_GET_EXT_CONFIG command that can be used to obtain the data programmed through the SNP_SET_EXT_CONFIG.
--- Documentation/virt/coco/sevguest.rst | 28 +++++++ drivers/crypto/ccp/sev-dev.c | 117 +++++++++++++++++++++++++++ drivers/crypto/ccp/sev-dev.h | 3 + include/uapi/linux/psp-sev.h | 16 ++++ 4 files changed, 164 insertions(+)
Documentation/virt/coco/sevguest.rst +28 -0
@@ -134,3 +134,31 @@ See GHCB specification for further detail on how to parse the certificate blob. The SNP_PLATFORM_STATUS command is used to query the SNP platform status. The status includes API major, minor version and more. See the SEV-SNP specification for further details. + +2.4 SNP_SET_EXT_CONFIG +---------------------- +:Technology: sev-snp +:Type: hypervisor ioctl cmd +:Parameters (in): struct sev_data_snp_ext_config +:Returns (out): 0 on success, -negative on error + +The SNP_SET_EXT_CONFIG is used to set the system-wide configuration such as +reported TCB version in the attestation report. The command is similar to +SNP_CONFIG command defined in the SEV-SNP spec. The main difference is the +command also accepts an additional certificate blob defined in the GHCB +specification. + +If the certs_address is zero, then previous certificate blob will deleted. +For more information on the certificate blob layout, see the GHCB spec +(extended guest request message). + + +2.4 SNP_GET_EXT_CONFIG +---------------------- +:Technology: sev-snp +:Type: hypervisor ioctl cmd +:Parameters (in): struct sev_data_snp_ext_config +:Returns (out): 0 on success, -negative on error + +The SNP_SET_EXT_CONFIG is used to query the system-wide configuration set +through the SNP_SET_EXT_CONFIG.
drivers/crypto/ccp/sev-dev.c +117 -0
135 lines not on this page · raw message
drivers/crypto/ccp/sev-dev.h +3 -0
@@ -67,6 +67,9 @@ struct sev_device {bool snp_inited;struct snp_host_map snp_host_map[MAX_SNP_HOST_MAP_BUFS ];struct page *snp_plat_status_page; +void *snp_certs_data; +u32 snp_certs_len; +struct sev_user_data_snp_config snp_config; };int sev_dev_init (struct psp_device *psp);
include/uapi/linux/psp-sev.h +16 -0
@@ -29,6 +29,8 @@ enum {SEV_GET_ID ,/* This command is deprecated, use SEV_GET_ID2 */ SEV_GET_ID2 ,SNP_PLATFORM_STATUS =256 , +SNP_SET_EXT_CONFIG , +SNP_GET_EXT_CONFIG , SEV_MAX, };
@@ -190,6 +192,20 @@ struct sev_user_data_snp_config {__u8 rsvd[52 ]; } __packed; +/** +* struct sev_data_snp_ext_config - system wide configuration value for SNP. +* +* @config_address: address of the struct sev_user_data_snp_config or 0 when +* reported_tcb does not need to be updated. +* @certs_address: address of extended guest request certificate chain or +* 0 when previous certificate should be removed on SNP_SET_EXT_CONFIG. +* @certs_len: length of the certs +*/ +struct sev_user_data_ext_snp_config { +__u64 config_address;/* In */ +__u64 certs_address;/* In */ +__u32 certs_len;/* In */ +};/** * struct sev_issue_cmd - SEV ioctl parameters
Signature · 1 line
2.17.1
RFC PATCH v4 19/40 crypto: ccp: provide APIs to query extended attestation report
In reply to Brijesh SinghVersion 2 of the GHCB specification defines VMGEXIT that is used to get the extended attestation report. The extended attestation report includes the certificate blobs provided through the SNP_SET_EXT_CONFIG.
The snp_guest_ext_guest_request() will be used by the hypervisor to get the extended attestation report. See the GHCB specification for more details.
--- drivers/crypto/ccp/sev-dev.c | 43 ++++++++++++++++++++++++++++++++++++ include/linux/psp-sev.h | 24 ++++++++++++++++++++ 2 files changed, 67 insertions(+)
drivers/crypto/ccp/sev-dev.c +43 -0
@@ -22,6 +22,7 @@#include <linux/firmware.h> #include <linux/gfp.h> #include <linux/cpufeature.h> +#include <linux/sev-guest.h> #include <asm/smp.h>
@@ -1616,6 +1617,48 @@ int snp_guest_dbg_decrypt(struct sev_data_snp_dbg *data, int *error) }EXPORT_SYMBOL_GPL (snp_guest_dbg_decrypt); +int snp_guest_ext_guest_request (struct sev_data_snp_guest_request *data, +unsigned long vaddr,unsigned long *npages,unsigned long *fw_err) +{ +unsigned long expected_npages; +struct sev_device *sev; +int rc; + +if (!psp_master || !psp_master->sev_data) +return -ENODEV ; + + sev = psp_master->sev_data; + +if (!sev->snp_inited) +return -EINVAL ; + +/* +* Check if we have enough space to copy the certificate chain. Otherwise +* return ERROR code defined in the GHCB specification. +*/ + expected_npages = sev->snp_certs_len >>PAGE_SHIFT ; +if (*npages < expected_npages) { + *npages = expected_npages; + *fw_err =SNP_GUEST_REQ_INVALID_LEN ; +return -EINVAL ; + } + + rc =sev_do_cmd (SEV_CMD_SNP_GUEST_REQUEST , data, (int *)&fw_err); +if (rc) +return rc; + +/* Copy the certificate blob */ +if (sev->snp_certs_data) { + *npages = expected_npages; +memcpy ((void *)vaddr, sev->snp_certs_data, *npages <<PAGE_SHIFT ); + }else { + *npages =0 ; + } + +return rc; +} +EXPORT_SYMBOL_GPL (snp_guest_ext_guest_request); +static void sev_exit (struct kref *ref) {misc_deregister (&misc_dev->misc);
include/linux/psp-sev.h +24 -0
@@ -925,6 +925,23 @@ void *psp_copy_user_blob(u64 uaddr, u32 len);void *snp_alloc_firmware_page (gfp_t mask);void snp_free_firmware_page (void *addr); +/** +* snp_guest_ext_guest_request - perform the SNP extended guest request command +* defined in the GHCB specification. +* +* @data: the input guest request structure +* @vaddr: address where the certificate blob need to be copied. +* @npages: number of pages for the certificate blob. +* If the specified page count is less than the certificate blob size, then the +* required page count is returned with error code defined in the GHCB spec. +* If the specified page count is more than the certificate blob size, then +* page count is updated to reflect the amount of valid data copied in the +* vaddr. +*/ +int snp_guest_ext_guest_request (struct sev_data_snp_guest_request *data, +unsigned long vaddr,unsigned long *npages, +unsigned long *error); +#else /* !CONFIG_CRYPTO_DEV_SP_PSP */ static inline int
@@ -972,6 +989,13 @@ static inline void *snp_alloc_firmware_page(gfp_t mask)static inline void snp_free_firmware_page (void *addr) { } +static inline int snp_guest_ext_guest_request (struct sev_data_snp_guest_request *data, +unsigned long vaddr,unsigned long *n, +unsigned long *error) +{ +return -ENODEV ; +} +#endif /* CONFIG_CRYPTO_DEV_SP_PSP */ #endif /* __PSP_SEV_H__ */
Signature · 1 line
2.17.1
RFC PATCH v4 20/40 KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
In reply to Brijesh SinghWhen SEV-SNP is globally enabled on a system, the VMRUN instruction performs additional security checks on AVIC backing, VMSA, and VMCB page. On a successful VMRUN, these pages are marked "in-use" by the hardware in the RMP entry, and any attempt to modify the RMP entry for these pages will result in page-fault (RMP violation check).
While performing the RMP check, hardware will try to create a 2MB TLB entry for the large page accesses. When it does this, it first reads the RMP for the base of 2MB region and verifies that all this memory is safe. If AVIC backing, VMSA, and VMCB memory happen to be the base of 2MB region, then RMP check will fail because of the "in-use" marking for the base entry of this 2MB region.
e.g.
1. A VMCB was allocated on 2MB-aligned address.
2. The VMRUN instruction marks this RMP entry as "in-use".
3. Another process allocated some other page of memory that happened to be within the same 2MB region.
4. That process tried to write its page using physmap.
If the physmap entry in step #4 uses a large (1G/2M) page, then the hardware will attempt to create a 2M TLB entry. The hardware will find that the "in-use" bit is set in the RMP entry (because it was a VMCB page) and will cause an RMP violation check.
See APM2 section 15.36.12 for more information on VMRUN checks when SEV-SNP is globally active.
A generic allocator can return a page which are 2M aligned and will not be safe to be used when SEV-SNP is globally enabled. Add a snp_safe_alloc_page() helper that can be used for allocating the SNP safe memory. The helper allocated 2 pages and splits them into order-1 allocation. It frees one page and keeps one of the page which is not 2M aligned.
--- arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/lapic.c | 5 ++++- arch/x86/kvm/svm/sev.c | 27 +++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 16 ++++++++++++++-- arch/x86/kvm/svm/svm.h | 1 + 5 files changed, 47 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -0
@@ -1383,6 +1383,7 @@ struct kvm_x86_ops {int (*complete_emulated_msr)(struct kvm_vcpu *vcpu,int err);void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector); +void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu); };struct kvm_x86_nested_ops {
arch/x86/kvm/lapic.c +4 -1
@@ -2441,7 +2441,10 @@ int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns) vcpu->arch.apic = apic; - apic->regs = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT ); +if (kvm_x86_ops.alloc_apic_backing_page) + apic->regs = kvm_x86_ops.alloc_apic_backing_page (vcpu); +else + apic->regs = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT );if (!apic->regs) {printk (KERN_ERR "malloc apic regs error for vcpu %x\n" , vcpu->vcpu_id);
arch/x86/kvm/svm/sev.c +27 -0
@@ -2692,3 +2692,30 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)break ; } } + +struct page *snp_safe_alloc_page (struct kvm_vcpu *vcpu) +{ +unsigned long pfn; +struct page *p; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return alloc_page (GFP_KERNEL_ACCOUNT | __GFP_ZERO); + + p =alloc_pages (GFP_KERNEL_ACCOUNT | __GFP_ZERO,1 ); +if (!p) +return NULL ; + +/* split the page order */ +split_page (p,1 ); + +/* Find a non-2M aligned page */ + pfn =page_to_pfn (p); +if (IS_ALIGNED (__pfn_to_phys (pfn),PMD_SIZE )) { + pfn++; +__free_page (p); + }else { +__free_page (pfn_to_page (pfn +1 )); + } + +return pfn_to_page (pfn); +}
arch/x86/kvm/svm/svm.c +14 -2
@@ -1336,7 +1336,7 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu) svm =to_svm (vcpu); err = -ENOMEM ; - vmcb01_page =alloc_page (GFP_KERNEL_ACCOUNT | __GFP_ZERO); + vmcb01_page =snp_safe_alloc_page (vcpu);if (!vmcb01_page) goto out;
@@ -1345,7 +1345,7 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu)* SEV-ES guests require a separate VMSA page used to contain * the encrypted register state of the guest. */ - vmsa_page =alloc_page (GFP_KERNEL_ACCOUNT | __GFP_ZERO); + vmsa_page =snp_safe_alloc_page (vcpu);if (!vmsa_page) goto error_free_vmcb_page;
@@ -4439,6 +4439,16 @@ static int svm_vm_init(struct kvm *kvm)return 0 ; } +static void *svm_alloc_apic_backing_page (struct kvm_vcpu *vcpu) +{ +struct page *page =snp_safe_alloc_page (vcpu); + +if (!page) +return NULL ; + +return page_address (page); +} +static struct kvm_x86_ops svm_x86_ops__initdata = { .hardware_unsetup = svm_hardware_teardown, .hardware_enable = svm_hardware_enable,
@@ -4564,6 +4574,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = { .complete_emulated_msr = svm_complete_emulated_msr, .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector, + + .alloc_apic_backing_page = svm_alloc_apic_backing_page, };static struct kvm_x86_init_ops svm_init_ops__initdata = {
arch/x86/kvm/svm/svm.h +1 -0
@@ -554,6 +554,7 @@ void sev_es_create_vcpu(struct vcpu_svm *svm);void sev_vcpu_deliver_sipi_vector (struct kvm_vcpu *vcpu,u8 vector);void sev_es_prepare_guest_switch (struct vcpu_svm *svm,unsigned int cpu);void sev_es_unmap_ghcb (struct vcpu_svm *svm); +struct page *snp_safe_alloc_page (struct kvm_vcpu *vcpu);/* vmenter.S */
Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 20/40] KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
Quoted 30 lines · Brijesh Singh
When SEV-SNP is globally enabled on a system, the VMRUN instruction performs additional security checks on AVIC backing, VMSA, and VMCB page. On a successful VMRUN, these pages are marked "in-use" by the hardware in the RMP entry, and any attempt to modify the RMP entry for these pages will result in page-fault (RMP violation check).
While performing the RMP check, hardware will try to create a 2MB TLB entry for the large page accesses. When it does this, it first reads the RMP for the base of 2MB region and verifies that all this memory is safe. If AVIC backing, VMSA, and VMCB memory happen to be the base of 2MB region, then RMP check will fail because of the "in-use" marking for the base entry of this 2MB region.
e.g.
1. A VMCB was allocated on 2MB-aligned address.
2. The VMRUN instruction marks this RMP entry as "in-use".
3. Another process allocated some other page of memory that happened to be within the same 2MB region.
4. That process tried to write its page using physmap.If the physmap entry in step #4 uses a large (1G/2M) page, then the hardware will attempt to create a 2M TLB entry. The hardware will find that the "in-use" bit is set in the RMP entry (because it was a VMCB page) and will cause an RMP violation check.
See APM2 section 15.36.12 for more information on VMRUN checks when SEV-SNP is globally active.
Quoted 8 lines
A generic allocator can return a page which are 2M aligned and will not be safe to be used when SEV-SNP is globally enabled. Add a
snp_safe_alloc_page()helper that can be used for allocating the SNP safe memory. The helper allocated 2 pages and splits them into order-1 allocation. It frees one page and keeps one of the page which is not 2M aligned.Signed-off-by Brijesh Singh <[email protected]>
The original version of this patch had this tag. I think it got dropped on accident.
Quoted 135 lines
--- arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/lapic.c | 5 ++++- arch/x86/kvm/svm/sev.c | 27 +++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 16 ++++++++++++++-- arch/x86/kvm/svm/svm.h | 1 + 5 files changed, 47 insertions(+), 3 deletions(-)arch/x86/include/asm/kvm_host.h +1
-0@@ -1383,6 +1383,7 @@ struct kvm_x86_ops {int (*complete_emulated_msr)(struct kvm_vcpu *vcpu,int err);void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector); +void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu); };struct kvm_x86_nested_ops {arch/x86/kvm/lapic.c +4
-1@@ -2441,7 +2441,10 @@ int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns) vcpu->arch.apic = apic; - apic->regs = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT ); +if (kvm_x86_ops.alloc_apic_backing_page) + apic->regs = kvm_x86_ops.alloc_apic_backing_page (vcpu); +else + apic->regs = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT );if (!apic->regs) {printk (KERN_ERR "malloc apic regs error for vcpu %x\n" , vcpu->vcpu_id);arch/x86/kvm/svm/sev.c +27
-0@@ -2692,3 +2692,30 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)break ; } } + +struct page *snp_safe_alloc_page (struct kvm_vcpu *vcpu) +{ +unsigned long pfn; +struct page *p; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) +return alloc_page (GFP_KERNEL_ACCOUNT | __GFP_ZERO); + + p =alloc_pages (GFP_KERNEL_ACCOUNT | __GFP_ZERO,1 ); +if (!p) +return NULL ; + +/* split the page order */ +split_page (p,1 ); + +/* Find a non-2M aligned page */ + pfn =page_to_pfn (p); +if (IS_ALIGNED (__pfn_to_phys (pfn),PMD_SIZE )) { + pfn++; +__free_page (p); + }else { +__free_page (pfn_to_page (pfn +1 )); + } + +return pfn_to_page (pfn); +}arch/x86/kvm/svm/svm.c +14
-2@@ -1336,7 +1336,7 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu) svm =to_svm (vcpu); err = -ENOMEM ; - vmcb01_page =alloc_page (GFP_KERNEL_ACCOUNT | __GFP_ZERO); + vmcb01_page =snp_safe_alloc_page (vcpu);if (!vmcb01_page) goto out;@@ -1345,7 +1345,7 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu)* SEV-ES guests require a separate VMSA page used to contain * the encrypted register state of the guest. */ - vmsa_page =alloc_page (GFP_KERNEL_ACCOUNT | __GFP_ZERO); + vmsa_page =snp_safe_alloc_page (vcpu);if (!vmsa_page) goto error_free_vmcb_page;@@ -4439,6 +4439,16 @@ static int svm_vm_init(struct kvm *kvm)return 0 ; } +static void *svm_alloc_apic_backing_page (struct kvm_vcpu *vcpu) +{ +struct page *page =snp_safe_alloc_page (vcpu); + +if (!page) +return NULL ; + +return page_address (page); +} +static struct kvm_x86_ops svm_x86_ops__initdata = { .hardware_unsetup = svm_hardware_teardown, .hardware_enable = svm_hardware_enable,@@ -4564,6 +4574,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = { .complete_emulated_msr = svm_complete_emulated_msr, .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector, + + .alloc_apic_backing_page = svm_alloc_apic_backing_page, };static struct kvm_x86_init_ops svm_init_ops__initdata = {arch/x86/kvm/svm/svm.h +1
-1@@ -554,6 +554,7 @@ void sev_es_create_vcpu(struct vcpu_svm *svm);void sev_vcpu_deliver_sipi_vector (struct kvm_vcpu *vcpu,u8 vector);void sev_es_prepare_guest_switch (struct vcpu_svm *svm,unsigned int cpu);void sev_es_unmap_ghcb (struct vcpu_svm *svm); +struct page *snp_safe_alloc_page (struct kvm_vcpu *vcpu);/* vmenter.S */ --2.17.1
Re: [PATCH Part2 RFC v4 20/40] KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
Quoted 4 lines · Marc Orr
Quoted 1 line
Signed-off-by Brijesh Singh <[email protected]>Co-developed-by Marc Orr <[email protected]>
thank you for adding it, it was dropped accidentally.
-Brijesh
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 20/40] KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
In reply to Brijesh SinghIMO, the CPU behavior is a bug, even if the behavior is working as intended for the microarchitecture. I.e. this should be treated as an erratum.
Quoted 4 lines · Brijesh Singh
When SEV-SNP is globally enabled on a system, the VMRUN instruction performs additional security checks on AVIC backing, VMSA, and VMCB page. On a successful VMRUN, these pages are marked "in-use" by the hardware in the RMP entry
There's a lot of "noise" in this intro. That the CPU does additional checks at VMRUN isn't all that interesting, what's relevant is that the CPU tags the associated RMP entry with a special flag. And IIUC, it does that for _all_ VMs, not just SNP VMs.
Also, what happens if the pages aren't covered by the RMP? Table 15-41 states that the VMCB, AVIC, and VMSA for non-SNP guests need to be Hypervisor-Owned, but doesn't explicitly require them to be RMP covered. On the other hand, it does state that the VMSA for an SNP guest must be Guest-Owned and RMP-Covered. That implies that the Hypervisor-Owned pages do not need to contained within the RMP, but how does that work if the CPU is setting a magic flag in the RMP? Does VMRUN explode? Does the CPU corrupt random memory?
Is the in-use flag visible to software? We've already established that "struct rmpentry" is microarchitectural, so why not document it in the PPR? It could be useful info for debugging unexpected RMP violations, even if the flag isn't stable.
Are there other possible collisions with the in-use flag? The APM states that the in-use flag results in RMPUPDATE failing with FAIL_INUSE. That's the same error code that's returned if two CPUs attempt RMPUPDATE on the same entry. That implies that the RMPUPDATE also sets the in-use flag. If that's true, then isn't it possible that the spurious RMP violation #PF could happen if the kernel accesses a hugepage at the same time a CPU is doing RMPUPDATE on the associated 2mb-aligned entry?
Quoted 2 lines
and any attempt to modify the RMP entry for these pages will result in page-fault (RMP violation check).
Again, not that relevant since KVM isn't attempting to modify the RMP entry. I've no objection to mentioning this behavior in passing, but it should not be the focal point of the intro.
Quoted 6 lines
While performing the RMP check, hardware will try to create a 2MB TLB entry for the large page accesses. When it does this, it first reads the RMP for the base of 2MB region and verifies that all this memory is safe. If AVIC backing, VMSA, and VMCB memory happen to be the base of 2MB region, then RMP check will fail because of the "in-use" marking for the base entry of this 2MB region.
There's a critical piece missing here, which is why an RMP violation is thrown on "in-use" pages. E.g. are any translations problematic, or just writable translations? It may not affect the actual KVM workaround, but knowing exactly what goes awry is important.
Quoted 7 lines
e.g.
1. A VMCB was allocated on 2MB-aligned address.
2. The VMRUN instruction marks this RMP entry as "in-use".
3. Another process allocated some other page of memory that happened to be within the same 2MB region.
4. That process tried to write its page using physmap.
Please explicitly call out the relevance of the physmap. IIUC, only the physmap, a.k.a. direct map, is problematic because that's the only scenario where a large page can overlap one of the magic pages. That should be explicitly stated.
Quoted 1 line
If the physmap entry in step #4 uses a large (1G/2M) page, then the
Be consistent with 2MB vs. 2M, i.e. choose one.
Quoted 3 lines
hardware will attempt to create a 2M TLB entry. The hardware will find that the "in-use" bit is set in the RMP entry (because it was a VMCB page) and will cause an RMP violation check.
So what happens if the problematic page isn't 2mb aligned? The lack of an RMP violation on access implies that the hypervisor can bypass the in-use restriction and create a 2mb hugepage, i.e. access the in-use page. Same question for if the TLB entry exists before the page is marked in-use, which also begs the question of why the in-use flag is being checked at all on RMP lookups.
Quoted 10 lines
See APM2 section 15.36.12 for more information on VMRUN checks when SEV-SNP is globally active.
A generic allocator can return a page which are 2M aligned and will not be safe to be used when SEV-SNP is globally enabled.
Add a
snp_safe_alloc_page()helper that can be used for allocating the SNP safe memory. The helper allocated 2 pages and splits them into order-1 allocation. It frees one page and keeps one of the page which is not 2M aligned.
I know it's personal preference as to whether to lead with the solution or the problem statement, but in this case it would be very helpful to at least provide a brief summary early on so that the reader has some idea of where the changelog is headed. As is, the actual change is buried after a big pile of hardware details.
E.g. something like this
Implement a workaround for an SNP erratum where the CPU will incorrectly signal an RMP violation #PF if a hugepage (2mb or 1gb) collides with the RMP entry of a VMCB, VMSA, or AVIC backing page.
When SEV-SNP is globally enabled, the CPU marks the VMCB, VMSA, and AVIC
backing pages as "in-use" in the RMP after a successful VMRUN. This is
done for _all_ VMs, not just SNP-Active VMs.
If the hypervisor accesses an in-use page through a writable translation, the CPU will throw an RMP violation #PF. On early SNP hardware, if an in-use page is 2mb aligned and software accesses any part of the associated 2mb region with a hupage, the CPU will incorrectly treat the entire 2mb region as in-use and signal a spurious RMP violation #PF.
<gory details on the workaround>
Quoted 26 lines
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/lapic.c | 5 ++++- arch/x86/kvm/svm/sev.c | 27 +++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 16 ++++++++++++++-- arch/x86/kvm/svm/svm.h | 1 + 5 files changed, 47 insertions(+), 3 deletions(-)arch/x86/include/asm/kvm_host.h +1
-0@@ -1383,6 +1383,7 @@ struct kvm_x86_ops {int (*complete_emulated_msr)(struct kvm_vcpu *vcpu,int err);void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector); +void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu); };struct kvm_x86_nested_ops {arch/x86/kvm/lapic.c +0
-0
arch/x86/kvm/lapic.c int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns) · line 2445
Quoted 6 lines
arch/x86/kvm/lapic.c +2
-1@@ -2441,7 +2441,10 @@ int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns) vcpu->arch.apic = apic; - apic->regs = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT ); +if (kvm_x86_ops.alloc_apic_backing_page) + apic->regs = kvm_x86_ops.alloc_apic_backing_page (vcpu);
This can be a static_call().
Quoted 20 lines
arch/x86/kvm/lapic.c +2
-0+else + apic->regs = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT );if (!apic->regs) {printk (KERN_ERR "malloc apic regs error for vcpu %x\n" , vcpu->vcpu_id);arch/x86/kvm/svm/sev.c +7
-0@@ -2692,3 +2692,30 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)break ; } } + +struct page *snp_safe_alloc_page (struct kvm_vcpu *vcpu) +{ +unsigned long pfn; +struct page *p; + +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))
arch/x86/kvm/svm/sev.c void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector) · line 2711
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+return alloc_page (GFP_KERNEL_ACCOUNT | __GFP_ZERO); + + p =alloc_pages (GFP_KERNEL_ACCOUNT | __GFP_ZERO,1 ); +if (!p) +return NULL ; + +/* split the page order */ +split_page (p,1 ); + +/* Find a non-2M aligned page */
This isn't "finding" anything, it's identifying which of the two pages is _guaranteed_ to be unaligned. The whole function needs a much bigger comment to explain what's going on.
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ pfn =page_to_pfn (p); +if (IS_ALIGNED (__pfn_to_phys (pfn),PMD_SIZE )) { + pfn++; +__free_page (p); + }else { +__free_page (pfn_to_page (pfn +1 )); + } + +return pfn_to_page (pfn); +}
Re: [PATCH Part2 RFC v4 20/40] KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
Hi Sean,
Quoted 3 lines · Sean Christopherson
IMO, the CPU behavior is a bug, even if the behavior is working as intended for the microarchitecture. I.e. this should be treated as an erratum.
I agreed with your comment that it should be treated as an erratum. I now have agreement from the hardware team to publish this as an erratum with explanation and recommendation. This will certainly help in documenting on "why" we are making the page split.
...
Quoted 6 lines
arch/x86/kvm/lapic.c int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns) · line 2445
Quoted 4 lines
arch/x86/kvm/lapic.c +2
-1- apic->regs = (void *)get_zeroed_page (GFP_KERNEL_ACCOUNT ); +if (kvm_x86_ops.alloc_apic_backing_page) + apic->regs = kvm_x86_ops.alloc_apic_backing_page (vcpu);This can be a
static_call().
Noted.
Quoted 4 lines
This isn't "finding" anything, it's identifying which of the two pages is _guaranteed_ to be unaligned. The whole function needs a much bigger comment to explain what's going on.
Let me add more comment to clarify it.
Quoted 11 lines
arch/x86/kvm/svm/sev.c void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector) · line 2721
Quoted 11 lines
arch/x86/kvm/svm/sev.c +10
-0+ pfn =page_to_pfn (p); +if (IS_ALIGNED (__pfn_to_phys (pfn),PMD_SIZE )) { + pfn++; +__free_page (p); + }else { +__free_page (pfn_to_page (pfn +1 )); + } + +return pfn_to_page (pfn); +}
thanks
RFC PATCH v4 21/40 KVM: SVM: Add initial SEV-SNP support
In reply to Brijesh SinghThe next generation of SEV is called SEV-SNP (Secure Nested Paging). SEV-SNP builds upon existing SEV and SEV-ES functionality while adding new hardware based security protection. SEV-SNP adds strong memory encryption integrity protection to help prevent malicious hypervisor-based attacks such as data replay, memory re-mapping, and more, to create an isolated execution environment.
The SNP feature can be enabled in the KVM by passing the sev-snp module parameter.
--- arch/x86/kvm/svm/sev.c | 18 ++++++++++++++++++ arch/x86/kvm/svm/svm.h | 12 ++++++++++++ 2 files changed, 30 insertions(+)
arch/x86/kvm/svm/sev.c +18 -0
@@ -52,9 +52,14 @@ module_param_named(sev, sev_enabled, bool, 0444);/* enable/disable SEV-ES support */ static bool sev_es_enabled = true;module_param_named (sev_es, sev_es_enabled, bool,0444 ); + +/* enable/disable SEV-SNP support */ +static bool sev_snp_enabled = true; +module_param_named (sev_snp, sev_snp_enabled, bool,0444 );#else #define sev_enabled false#define sev_es_enabled false +#define sev_snp_enabled false#endif /* CONFIG_KVM_AMD_SEV */ #define AP_RESET_HOLD_NONE 0
@@ -1825,6 +1830,7 @@ void __init sev_hardware_setup(void) {#ifdef CONFIG_KVM_AMD_SEV unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count; +bool sev_snp_supported = false;bool sev_es_supported = false;bool sev_supported = false;
@@ -1888,9 +1894,21 @@ void __init sev_hardware_setup(void)pr_info ("SEV-ES supported: %u ASIDs\n" , sev_es_asid_count); sev_es_supported = true; +/* SEV-SNP support requested? */ +if (!sev_snp_enabled) + goto out; + +/* Is SEV-SNP enabled? */ +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP )) + goto out; + +pr_info ("SEV-SNP supported: %u ASIDs\n" , min_sev_asid -1 ); + sev_snp_supported = true; + out: sev_enabled = sev_supported; sev_es_enabled = sev_es_supported; + sev_snp_enabled = sev_snp_supported;#endif }
arch/x86/kvm/svm/svm.h +12 -0
@@ -58,6 +58,7 @@ enum {struct kvm_sev_info {bool active;/* SEV enabled guest */ bool es_active;/* SEV-ES enabled guest */ +bool snp_active;/* SEV-SNP enabled guest */ unsigned int asid;/* ASID used for this guest */ unsigned int handle;/* SEV firmware handle */ int fd;/* SEV device fd */
@@ -232,6 +233,17 @@ static inline bool sev_es_guest(struct kvm *kvm)#endif } +static inline bool sev_snp_guest (struct kvm *kvm) +{ +#ifdef CONFIG_KVM_AMD_SEV +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; + +return sev_es_guest (kvm) && sev->snp_active; +#else +return false; +#endif +} +static inline void vmcb_mark_all_dirty (struct vmcb *vmcb) { vmcb->control.clean =0 ;
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 21/40] KVM: SVM: Add initial SEV-SNP support
arch/x86/kvm/svm/sev.c module_param_named(sev, sev_enabled, bool, 0444); · line 57
Quoted 11 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +3
-0@@ -52,9 +52,14 @@ module_param_named(sev, sev_enabled, bool, 0444);/* enable/disable SEV-ES support */ static bool sev_es_enabled = true;module_param_named (sev_es, sev_es_enabled, bool,0444 ); + +/* enable/disable SEV-SNP support */ +static bool sev_snp_enabled = true;
Is it safe to incrementally introduce SNP support? Or should the module param be hidden until all support is in place? E.g. what will happen when KVM allows userspace to create SNP guests but doesn't yet have the RMP management added?
Quoted 17 lines
arch/x86/kvm/svm/sev.c +3
-0+module_param_named (sev_snp, sev_snp_enabled, bool,0444 );#else #define sev_enabled false#define sev_es_enabled false +#define sev_snp_enabled false#endif /* CONFIG_KVM_AMD_SEV */ #define AP_RESET_HOLD_NONE 0@@ -1825,6 +1830,7 @@ void __init sev_hardware_setup(void) {#ifdef CONFIG_KVM_AMD_SEV unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count; +bool sev_snp_supported = false;bool sev_es_supported = false;bool sev_supported = false;
arch/x86/kvm/svm/sev.c void __init sev_hardware_setup(void) · line 1902
Quoted 9 lines
arch/x86/kvm/svm/sev.c +6
-0@@ -1888,9 +1894,21 @@ void __init sev_hardware_setup(void)pr_info ("SEV-ES supported: %u ASIDs\n" , sev_es_asid_count); sev_es_supported = true; +/* SEV-SNP support requested? */ +if (!sev_snp_enabled) + goto out; + +/* Is SEV-SNP enabled? */ +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))
Random question, why use cpu_feature_enabled? Did something change in cpufeatures that prevents using boot_cpu_has() here?
arch/x86/kvm/svm/sev.c void __init sev_hardware_setup(void) · line 1905
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+ goto out; + +pr_info ("SEV-SNP supported: %u ASIDs\n" , min_sev_asid -1 );
Use sev_es_asid_count instead of manually recomputing the same; the latter obfuscates the fact that ES and SNP share the same ASID pool.
Even better would be to report ES+SNP together, otherwise the user could easily interpret ES and SNP having separate ASID pools. And IMO the gotos for SNP are overkill, e.g.
sev_es_supported = true;
sev_snp_supported = sev_snp_enabled &&
cpu_feature_enabled(X86_FEATURE_SEV_SNP);
pr_info("SEV-ES %ssupported: %u ASIDs\n",
sev_snp_supported ? "and SEV-SNP " : "", sev_es_asid_count);Quoted 22 lines
arch/x86/kvm/svm/sev.c +3
-0+ sev_snp_supported = true; + out: sev_enabled = sev_supported; sev_es_enabled = sev_es_supported; + sev_snp_enabled = sev_snp_supported;#endif }arch/x86/kvm/svm/svm.h +1
-0@@ -58,6 +58,7 @@ enum {struct kvm_sev_info {bool active;/* SEV enabled guest */ bool es_active;/* SEV-ES enabled guest */ +bool snp_active;/* SEV-SNP enabled guest */ unsigned int asid;/* ASID used for this guest */ unsigned int handle;/* SEV firmware handle */ int fd;/* SEV device fd */
arch/x86/kvm/svm/svm.h static inline bool sev_es_guest(struct kvm *kvm) · line 241
Quoted 9 lines
arch/x86/kvm/svm/svm.h +6
-0@@ -232,6 +233,17 @@ static inline bool sev_es_guest(struct kvm *kvm)#endif } +static inline bool sev_snp_guest (struct kvm *kvm) +{ +#ifdef CONFIG_KVM_AMD_SEV +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; + +return sev_es_guest (kvm) && sev->snp_active;
Can't this be reduced to:
return to_kvm_svm(kvm)->sev_info.snp_active;
KVM should never set snp_active without also setting es_active.
Side topic, I think it would also be worthwhile to add to_sev (or maybe to_kvm_sev) given the frequency of the "&to_kvm_svm(kvm)->sev_info" pattern.
Quoted 11 lines
arch/x86/kvm/svm/svm.h +5
-0+#else +return false; +#endif +} +static inline void vmcb_mark_all_dirty (struct vmcb *vmcb) { vmcb->control.clean =0 ;Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 21/40] KVM: SVM: Add initial SEV-SNP support
Quoted 15 lines · Sean Christopherson
arch/x86/kvm/svm/sev.c module_param_named(sev, sev_enabled, bool, 0444); · line 57
Quoted 11 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +3
-0@@ -52,9 +52,14 @@ module_param_named(sev, sev_enabled, bool, 0444);/* enable/disable SEV-ES support */ static bool sev_es_enabled = true;module_param_named (sev_es, sev_es_enabled, bool,0444 ); + +/* enable/disable SEV-SNP support */ +static bool sev_snp_enabled = true;Is it safe to incrementally introduce SNP support? Or should the module param be hidden until all support is in place? E.g. what will happen when KVM allows userspace to create SNP guests but doesn't yet have the RMP management added?
The SNP support depends on the RMP management. At least the patch ordering in this series adds the RMP management first then updates drivers to use the RMP specific APIs. If RMP is not initialized due to someone not picking the commits in the order, then SNP guest creation will fail. This is mainly because the first thing a guest creation does is to call the SNP_INIT. The SNP_INIT firmware command verifies that RMP is initialized before creating the guest context etc..
Quoted 20 lines
Quoted 20 lines
arch/x86/kvm/svm/sev.c +3
-0+module_param_named (sev_snp, sev_snp_enabled, bool,0444 );#else #define sev_enabled false#define sev_es_enabled false +#define sev_snp_enabled false#endif /* CONFIG_KVM_AMD_SEV */ #define AP_RESET_HOLD_NONE 0@@ -1825,6 +1830,7 @@ void __init sev_hardware_setup(void) {#ifdef CONFIG_KVM_AMD_SEV unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count; +bool sev_snp_supported = false;bool sev_es_supported = false;bool sev_supported = false;@@ -1888,9 +1894,21 @@ void __init sev_hardware_setup(void)pr_info ("SEV-ES supported: %u ASIDs\n" , sev_es_asid_count); sev_es_supported = true;
Quoted 8 lines
arch/x86/kvm/svm/sev.c void __init sev_hardware_setup(void) · line 1902
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+/* SEV-SNP support requested? */ +if (!sev_snp_enabled) + goto out; + +/* Is SEV-SNP enabled? */ +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))Random question, why use
cpu_feature_enabled? Did something change in cpufeatures that prevents usingboot_cpu_has()here?
During the boot the kernel initialize the RMP table. If RMP table initialization fail, then X86_FEATURE_SEV_SNP is cleared. In that case, the cpu_feature_enabled() should return false. The idea is, cpu_feature_enabled() will be set only when the RMP table is successfully initialized and SYSCFG.SNP is set.
Quoted 10 lines
arch/x86/kvm/svm/sev.c void __init sev_hardware_setup(void) · line 1905
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+ goto out; + +pr_info ("SEV-SNP supported: %u ASIDs\n" , min_sev_asid -1 );Use
sev_es_asid_countinstead of manually recomputing the same; the latter obfuscates the fact that ES and SNP share the same ASID pool.Even better would be to report ES+SNP together, otherwise the user could easily interpret ES and SNP having separate ASID pools. And IMO the gotos for SNP are overkill, e.g.
Quoted 7 lines
sev_es_supported = true;
sev_snp_supported = sev_snp_enabled &&
cpu_feature_enabled(X86_FEATURE_SEV_SNP);
pr_info("SEV-ES %ssupported: %u ASIDs\n",
sev_snp_supported ? "and SEV-SNP " : "", sev_es_asid_count);Noted.
Quoted 33 lines
Quoted 22 lines
arch/x86/kvm/svm/sev.c +3
-0+ sev_snp_supported = true; + out: sev_enabled = sev_supported; sev_es_enabled = sev_es_supported; + sev_snp_enabled = sev_snp_supported;#endif }arch/x86/kvm/svm/svm.h +1
-0@@ -58,6 +58,7 @@ enum {struct kvm_sev_info {bool active;/* SEV enabled guest */ bool es_active;/* SEV-ES enabled guest */ +bool snp_active;/* SEV-SNP enabled guest */ unsigned int asid;/* ASID used for this guest */ unsigned int handle;/* SEV firmware handle */ int fd;/* SEV device fd */ arch/x86/kvm/svm/svm.h static inline bool sev_es_guest(struct kvm *kvm) · line 241
Quoted 9 lines
arch/x86/kvm/svm/svm.h +6
-0@@ -232,6 +233,17 @@ static inline bool sev_es_guest(struct kvm *kvm)#endif } +static inline bool sev_snp_guest (struct kvm *kvm) +{ +#ifdef CONFIG_KVM_AMD_SEV +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; + +return sev_es_guest (kvm) && sev->snp_active;Can't this be reduced to:
Quoted 3 lines
return to_kvm_svm(kvm)->sev_info.snp_active;KVM should never set
snp_activewithout also settinges_active.
The approach here is similar to SEV/ES. IIRC, it was done mainly to avoid adding dead code when CONFIG_KVM_AMD_SEV is disabled. Most of the function related to SEV/ES/SNP call the sev_guest()/sev_es_guest()/sev_snp_guest() on the entry. Instead of #ifdef all those functions, we can #ifdef sev_snp_guest(); compiler will see that if() statement will always return false, so it will not include the remaining body of the function.
Quoted 15 lines
Side topic, I think it would also be worthwhile to add
to_sev(or maybeto_kvm_sev) given the frequency of the "&to_kvm_svm(kvm)->sev_info" pattern.Quoted 11 lines
arch/x86/kvm/svm/svm.h +5
-0+#else +return false; +#endif +} +static inline void vmcb_mark_all_dirty (struct vmcb *vmcb) { vmcb->control.clean =0 ;Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 21/40] KVM: SVM: Add initial SEV-SNP support
Quoted 18 lines · Brijesh Singh
Quoted 15 lines · Sean Christopherson
arch/x86/kvm/svm/sev.c module_param_named(sev, sev_enabled, bool, 0444); · line 57
Quoted 11 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +3
-0@@ -52,9 +52,14 @@ module_param_named(sev, sev_enabled, bool, 0444);/* enable/disable SEV-ES support */ static bool sev_es_enabled = true;module_param_named (sev_es, sev_es_enabled, bool,0444 ); + +/* enable/disable SEV-SNP support */ +static bool sev_snp_enabled = true;Is it safe to incrementally introduce SNP support? Or should the module param be hidden until all support is in place? E.g. what will happen when KVM allows userspace to create SNP guests but doesn't yet have the RMP management added?
Quoted 3 lines
The SNP support depends on the RMP management. At least the patch ordering in this series adds the RMP management first then updates drivers to use the RMP specific APIs.
Yep, got that.
Quoted 2 lines
If RMP is not initialized due to someone not picking the commits in the order, then SNP guest creation will fail.
That's not what I was asking. My question is if KVM will break/fail if someone runs a KVM build with SNP enabled halfway through the series. E.g. if I make a KVM build at patch 22, "KVM: SVM: Add KVM_SNP_INIT command", what will happen if I attempt to launch an SNP guest? Obviously it won't fully succeed, but will KVM fail gracefully and do all the proper cleanup? Repeat the question for all patches between this one and the final patch of the series.
SNP simply not working is ok, but if KVM explodes or does weird things without "full" SNP support, then at minimum the module param should be off by default until it's safe to enable. E.g. for the TDP MMU, I believe the approach was to put all the machinery in place but not actually let userspace flip on the module param until the full implementation was ready. Bisecting and testing the individual commits is a bit painful because it requires modifying KVM code, but on the plus side unrelated bisects won't stumble into a half-baked state.
Quoted 30 lines
Quoted 20 lines
Quoted 20 lines
arch/x86/kvm/svm/sev.c +3
-0+module_param_named (sev_snp, sev_snp_enabled, bool,0444 );#else #define sev_enabled false#define sev_es_enabled false +#define sev_snp_enabled false#endif /* CONFIG_KVM_AMD_SEV */ #define AP_RESET_HOLD_NONE 0@@ -1825,6 +1830,7 @@ void __init sev_hardware_setup(void) {#ifdef CONFIG_KVM_AMD_SEV unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count; +bool sev_snp_supported = false;bool sev_es_supported = false;bool sev_supported = false;@@ -1888,9 +1894,21 @@ void __init sev_hardware_setup(void)pr_info ("SEV-ES supported: %u ASIDs\n" , sev_es_asid_count); sev_es_supported = true;Quoted 8 lines
arch/x86/kvm/svm/sev.c void __init sev_hardware_setup(void) · line 1902
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+/* SEV-SNP support requested? */ +if (!sev_snp_enabled) + goto out; + +/* Is SEV-SNP enabled? */ +if (!cpu_feature_enabled (X86_FEATURE_SEV_SNP ))Random question, why use
cpu_feature_enabled? Did something change in cpufeatures that prevents usingboot_cpu_has()here?
Quoted 5 lines
During the boot the kernel initialize the RMP table. If RMP table initialization fail, then
X86_FEATURE_SEV_SNPis cleared. In that case, thecpu_feature_enabled()should return false. The idea is,cpu_feature_enabled()will be set only when the RMP table is successfully initialized and SYSCFG.SNP is set.
Ya, got that, but again not what I was asking :-) Why use cpu_feature_enabled() instead of boot_cpu_has()? As a random developer, I would fully expect that boot_cpu_has(X86_FEATURE_SEV_SNP) is true iff SNP is fully enabled by the kernel.
Quoted 25 lines
Quoted 25 lines
arch/x86/kvm/svm/sev.c void __init sev_hardware_setup(void) · line 1905
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+ goto out; + +pr_info ("SEV-SNP supported: %u ASIDs\n" , min_sev_asid -1 );Use
sev_es_asid_countinstead of manually recomputing the same; the latter obfuscates the fact that ES and SNP share the same ASID pool.Even better would be to report ES+SNP together, otherwise the user could easily interpret ES and SNP having separate ASID pools. And IMO the gotos for SNP are overkill, e.g.
sev_es_supported = true; sev_snp_supported = sev_snp_enabled && cpu_feature_enabled(X86_FEATURE_SEV_SNP); pr_info("SEV-ES %ssupported: %u ASIDs\n", sev_snp_supported ? "and SEV-SNP " : "", sev_es_asid_count);arch/x86/kvm/svm/sev.c void __init sev_hardware_setup(void) · line 1911
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+static inline bool sev_snp_guest (struct kvm *kvm) +{ +#ifdef CONFIG_KVM_AMD_SEV +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; + +return sev_es_guest (kvm) && sev->snp_active;Can't this be reduced to:
Quoted 7 lines
Quoted 3 lines
return to_kvm_svm(kvm)->sev_info.snp_active;KVM should never set
snp_activewithout also settinges_active.The approach here is similar to SEV/ES. IIRC, it was done mainly to avoid adding dead code when
CONFIG_KVM_AMD_SEVis disabled.
But this is already in an #ifdef, checking sev_es_guest() is pointless.
Re: [PATCH Part2 RFC v4 21/40] KVM: SVM: Add initial SEV-SNP support
Quoted 7 lines · Sean Christopherson
That's not what I was asking. My question is if KVM will break/fail if someone runs a KVM build with SNP enabled halfway through the series. E.g. if I make a KVM build at patch 22, "KVM: SVM: Add
KVM_SNP_INITcommand", what will happen if I attempt to launch an SNP guest? Obviously it won't fully succeed, but will KVM fail gracefully and do all the proper cleanup? Repeat the question for all patches between this one and the final patch of the series.
Quoted 7 lines
SNP simply not working is ok, but if KVM explodes or does weird things without "full" SNP support, then at minimum the module param should be off by default until it's safe to enable. E.g. for the TDP MMU, I believe the approach was to put all the machinery in place but not actually let userspace flip on the module param until the full implementation was ready. Bisecting and testing the individual commits is a bit painful because it requires modifying KVM code, but on the plus side unrelated bisects won't stumble into a half-baked state.
There is one to two patches where I can think of that we may break the KVM if SNP guest is created before applying the full series. In one patch we add LAUNCH_UPDATE but reclaim is done in next patch. I like your idea to push the module init later in the series.
Quoted 4 lines
Ya, got that, but again not what I was asking :-) Why use
cpu_feature_enabled()instead ofboot_cpu_has()? As a random developer, I would fully expect thatboot_cpu_has(X86_FEATURE_SEV_SNP)is true iff SNP is fully enabled by the kernel.
I have to check but I think boot_cpu_has(X64_FEATURE_SEV_SNP) will return true even when the CONFIG_MEM_ENCRYPT is disabled.
Quoted 4 lines
Quoted 3 lines
The approach here is similar to SEV/ES. IIRC, it was done mainly to avoid adding dead code when
CONFIG_KVM_AMD_SEVis disabled.But this is already in an #ifdef, checking
sev_es_guest()is pointless.
Ah Good point.
RFC PATCH v4 22/40 KVM: SVM: Add KVM_SNP_INIT command
In reply to Brijesh SinghThe KVM_SNP_INIT command is used by the hypervisor to initialize the SEV-SNP platform context. In a typical workflow, this command should be the first command issued. When creating SEV-SNP guest, the VMM must use this command instead of the KVM_SEV_INIT or KVM_SEV_ES_INIT.
The flags value must be zero, it will be extended in future SNP support to communicate the optional features (such as restricted INT injection etc).
--- .../virt/kvm/amd-memory-encryption.rst | 16 ++++++++ arch/x86/kvm/svm/sev.c | 37 ++++++++++++++++++- include/uapi/linux/kvm.h | 7 ++++ 3 files changed, 58 insertions(+), 2 deletions(-)
Documentation/virt/kvm/amd-memory-encryption.rst +16 -0
@@ -427,6 +427,22 @@ issued by the hypervisor to make the guest ready for execution. Returns: 0 on success, -negative on error +18. KVM_SNP_INIT +---------------- + +The KVM_SNP_INIT command can be used by the hypervisor to initialize SEV-SNP +context. In a typical workflow, this command should be the first command issued. + +Parameters (in): struct kvm_snp_init + +Returns: 0 on success, -negative on error + +:: + + struct kvm_snp_init { + __u64 flags; /* must be zero */ + }; + References ==========
arch/x86/kvm/svm/sev.c +35 -2
@@ -228,10 +228,24 @@ static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)sev_guest_decommission (&decommission,NULL ); } +static int verify_snp_init_flags (struct kvm *kvm,struct kvm_sev_cmd *argp) +{ +struct kvm_snp_init params; + +if (copy_from_user (¶ms, (void __user *)(uintptr_t )argp->data,sizeof (params))) +return -EFAULT ; + +if (params.flags) +return -EINVAL ; + +return 0 ; +} +static int sev_guest_init (struct kvm *kvm,struct kvm_sev_cmd *argp) { +bool es_active = (argp->id ==KVM_SEV_ES_INIT || argp->id ==KVM_SEV_SNP_INIT );struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; -bool es_active = argp->id ==KVM_SEV_ES_INIT ; +bool snp_active = argp->id ==KVM_SEV_SNP_INIT ;int asid, ret;if (kvm->created_vcpus)
@@ -242,12 +256,22 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)return ret; sev->es_active = es_active; + sev->snp_active = snp_active; asid =sev_asid_new (sev);if (asid <0 ) goto e_no_asid; sev->asid = asid; - ret =sev_platform_init (&argp->error); +if (snp_active) { + ret =verify_snp_init_flags (kvm, argp); +if (ret) + goto e_free; + + ret =sev_snp_init (&argp->error); + }else { + ret =sev_platform_init (&argp->error); + } +if (ret) goto e_free;
@@ -591,6 +615,9 @@ static int sev_es_sync_vmsa(struct vcpu_svm *svm) save->pkru = svm->vcpu.arch.pkru; save->xss = svm->vcpu.arch.ia32_xss; +if (sev_snp_guest (svm->vcpu.kvm)) + save->sev_features |=SVM_SEV_FEATURES_SNP_ACTIVE ; +return 0 ; }
@@ -1523,6 +1550,12 @@ int svm_mem_enc_op(struct kvm *kvm, void __user *argp) }switch (sev_cmd.id) { +case KVM_SEV_SNP_INIT : +if (!sev_snp_enabled) { + r = -ENOTTY ; + goto out; + } + fallthrough;case KVM_SEV_ES_INIT :if (!sev_es_enabled) { r = -ENOTTY ;
include/uapi/linux/kvm.h +7 -0
@@ -1678,6 +1678,9 @@ enum sev_cmd_id {/* Guest Migration Extension */ KVM_SEV_SEND_CANCEL , +/* SNP specific commands */ +KVM_SEV_SNP_INIT =256 , + KVM_SEV_NR_MAX, };
@@ -1774,6 +1777,10 @@ struct kvm_sev_receive_update_data {__u32 trans_len; }; +struct kvm_snp_init { +__u64 flags; +}; +#define KVM_DEV_ASSIGN_ENABLE_IOMMU (1 << 0)#define KVM_DEV_ASSIGN_PCI_2_3 (1 << 1)#define KVM_DEV_ASSIGN_MASK_INTX (1 << 2)
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 22/40] KVM: SVM: Add KVM_SNP_INIT command
include/uapi/linux/kvm.h enum sev_cmd_id { · line 1682
Quoted 10 lines · Brijesh Singh
include/uapi/linux/kvm.h +2
-0@@ -1678,6 +1678,9 @@ enum sev_cmd_id {/* Guest Migration Extension */ KVM_SEV_SEND_CANCEL , +/* SNP specific commands */ + KVM_SEV_SNP_INIT = 256,
Is there any meaning behind '256'? If not, why skip a big chunk? I wouldn't be concerned if it weren't for KVM_SEV_NR_MAX, whose existence arguably implies that 0-KVM_SEV_NR_MAX-1 are all valid SEV commands.
Quoted 3 lines
include/uapi/linux/kvm.h +1
-0+ KVM_SEV_NR_MAX, };
Re: [PATCH Part2 RFC v4 22/40] KVM: SVM: Add KVM_SNP_INIT command
Quoted 9 lines · Sean Christopherson
Quoted 8 lines · Brijesh Singh
include/uapi/linux/kvm.h +0
-0@@ -1678,6 +1678,9 @@ enum sev_cmd_id {/* Guest Migration Extension */ KVM_SEV_SEND_CANCEL,
Quoted 5 lines
include/uapi/linux/kvm.h enum sev_cmd_id { · line 1682
Quoted 2 lines
include/uapi/linux/kvm.h +2
-0+/* SNP specific commands */ + KVM_SEV_SNP_INIT = 256,Is there any meaning behind '256'? If not, why skip a big chunk? I wouldn't be concerned if it weren't for
KVM_SEV_NR_MAX, whose existence arguably implies that 0-KVM_SEV_NR_MAX-1 are all valid SEV commands.
In previous patches, Peter highlighted that we should keep some gap between the SEV/ES and SNP to leave room for legacy SEV/ES expansion. I was not sure how many we need to reserve without knowing what will come in the future; especially recently some of the command additional are not linked to the firmware. I am okay to reduce the gap or remove the gap all together.
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 22/40] KVM: SVM: Add KVM_SNP_INIT command
Quoted 17 lines · Brijesh Singh
Quoted 9 lines · Sean Christopherson
Quoted 8 lines · Brijesh Singh
include/uapi/linux/kvm.h +0
-0@@ -1678,6 +1678,9 @@ enum sev_cmd_id {/* Guest Migration Extension */ KVM_SEV_SEND_CANCEL,Quoted 5 lines
include/uapi/linux/kvm.h enum sev_cmd_id { · line 1682
Quoted 2 lines
include/uapi/linux/kvm.h +2
-0+/* SNP specific commands */ + KVM_SEV_SNP_INIT = 256,Is there any meaning behind '256'? If not, why skip a big chunk? I wouldn't be concerned if it weren't for
KVM_SEV_NR_MAX, whose existence arguably implies that 0-KVM_SEV_NR_MAX-1 are all valid SEV commands.
Quoted 6 lines
In previous patches, Peter highlighted that we should keep some gap between the SEV/ES and SNP to leave room for legacy SEV/ES expansion. I was not sure how many we need to reserve without knowing what will come in the future; especially recently some of the command additional are not linked to the firmware. I am okay to reduce the gap or remove the gap all together.
Unless the numbers themselves have meaning, which I don't think they do, I vote to keep the arbitrary numbers contiguous. KVM_SEV_NR_MAX makes me nervous, and there are already cases of related commands being discontiguous, e.g. KVM_SEND_CANCEL.
Peter or Paolo, any thoughts?
RFC PATCH v4 23/40 KVM: SVM: Add KVM_SEV_SNP_LAUNCH_START command
In reply to Brijesh SinghKVM_SEV_SNP_LAUNCH_START begins the launch process for an SEV-SNP guest. The command initializes a cryptographic digest context used to construct the measurement of the guest. If the guest is expected to be migrated, the command also binds a migration agent (MA) to the guest.
For more information see the SEV-SNP specification.
--- .../virt/kvm/amd-memory-encryption.rst | 25 ++++ arch/x86/kvm/svm/sev.c | 132 +++++++++++++++++- arch/x86/kvm/svm/svm.h | 1 + include/uapi/linux/kvm.h | 9 ++ 4 files changed, 166 insertions(+), 1 deletion(-)
Documentation/virt/kvm/amd-memory-encryption.rst +25 -0
@@ -443,6 +443,31 @@ Returns: 0 on success, -negative on error __u64 flags; /* must be zero */ }; + +19. KVM_SNP_LAUNCH_START +------------------------ + +The KVM_SNP_LAUNCH_START command is used for creating the memory encryption +context for the SEV-SNP guest. To create the encryption context, user must +provide a guest policy, migration agent (if any) and guest OS visible +workarounds value as defined SEV-SNP specification. + +Parameters (in): struct kvm_snp_launch_start + +Returns: 0 on success, -negative on error + +:: + + struct kvm_sev_snp_launch_start { + __u64 policy; /* Guest policy to use. */ + __u64 ma_uaddr; /* userspace address of migration agent */ + __u8 ma_en; /* 1 if the migtation agent is enabled */ + __u8 imi_en; /* set IMI to 1. */ + __u8 gosvw[16]; /* guest OS visible workarounds */ + }; + +See the SEV-SNP specification for further detail on the launch input. + References ==========
arch/x86/kvm/svm/sev.c +131 -1
168 lines not on this page · raw message
arch/x86/kvm/svm/svm.h +1 -0
@@ -67,6 +67,7 @@ struct kvm_sev_info {u64 ap_jump_table;/* SEV-ES AP Jump Table address */ struct kvm *enc_context_owner;/* Owner of copied encryption context */ struct misc_cg *misc_cg;/* For misc cgroup accounting */ +void *snp_context;/* SNP guest context page */ };struct kvm_svm {
include/uapi/linux/kvm.h +9 -0
@@ -1680,6 +1680,7 @@ enum sev_cmd_id {/* SNP specific commands */ KVM_SEV_SNP_INIT =256 , +KVM_SEV_SNP_LAUNCH_START , KVM_SEV_NR_MAX, };
@@ -1781,6 +1782,14 @@ struct kvm_snp_init {__u64 flags; }; +struct kvm_sev_snp_launch_start { +__u64 policy; +__u64 ma_uaddr; +__u8 ma_en; +__u8 imi_en; +__u8 gosvw[16 ]; +}; +#define KVM_DEV_ASSIGN_ENABLE_IOMMU (1 << 0)#define KVM_DEV_ASSIGN_PCI_2_3 (1 << 1)#define KVM_DEV_ASSIGN_MASK_INTX (1 << 2)
Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 23/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_START command
Quoted 5 lines
arch/x86/kvm/svm/sev.c +4
-0+static int snp_decommission_context (struct kvm *kvm) +{ +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +struct sev_data_snp_decommission data = {};
arch/x86/kvm/svm/sev.c int svm_vm_copy_asid_from(struct kvm *kvm, unsigned int source_fd) · line 1925
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+int ret; + +/* If context is not created then do nothing */ +if (!sev->snp_context) +return 0 ; + + data.gctx_paddr =__sme_pa (sev->snp_context); + ret =snp_guest_decommission (&data,NULL ); +if (ret) +return ret;
Should we WARN or pr_err here? I see in the case of snp_launch_start's e_free_context we do not warn the user they have leaked a firmware page.
Quoted 13 lines
arch/x86/kvm/svm/sev.c +8
-0+ +/* free the context page now */ +snp_free_firmware_page (sev->snp_context); + sev->snp_context =NULL ; + +return 0 ; +} +void sev_vm_destroy (struct kvm *kvm) {struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info;
arch/x86/kvm/svm/sev.c void sev_vm_destroy(struct kvm *kvm) · line 1974
Quoted 7 lines
arch/x86/kvm/svm/sev.c +3
-1@@ -1847,7 +1969,15 @@ void sev_vm_destroy(struct kvm *kvm)mutex_unlock (&kvm->lock); -sev_unbind_asid (kvm, sev->handle); +if (sev_snp_guest (kvm)) { +if (snp_decommission_context (kvm)) { +pr_err ("Failed to free SNP guest context, leaking asid!\n" );
Should these errors be a WARN since we are leaking some state?
Quoted 9 lines
arch/x86/kvm/svm/sev.c +6
-0+return ; + } + }else { +sev_unbind_asid (kvm, sev->handle); + } +sev_asid_free (sev); }
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 23/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_START command
In reply to Brijesh Singharch/x86/kvm/svm/sev.c static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1539
Quoted 11 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +7
-0@@ -1527,6 +1530,100 @@ static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)return sev_issue_cmd (kvm,SEV_CMD_RECEIVE_FINISH , &data, &argp->error); } +static void *snp_context_create (struct kvm *kvm,struct kvm_sev_cmd *argp) +{ +struct sev_data_snp_gctx_create data = {}; +void *context; +int rc; + +/* Allocate memory for context page */
Eh, I'd drop this comment. It's quite obvious that a page is being allocated and that it's being assigned to the context.
Quoted 18 lines
arch/x86/kvm/svm/sev.c +18
-0+ context =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT ); +if (!context) +return NULL ; + + data.gctx_paddr =__psp_pa (context); + rc =__sev_issue_cmd (argp->sev_fd,SEV_CMD_SNP_GCTX_CREATE , &data, &argp->error); +if (rc) { +snp_free_firmware_page (context); +return NULL ; + } + +return context; +} + +static int snp_bind_asid (struct kvm *kvm,int *error) +{ +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +struct sev_data_snp_activate data = {};
arch/x86/kvm/svm/sev.c static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1567
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+int asid =sev_get_asid (kvm); +int ret, retry_count =0 ; + +/* Activate ASID on the given context */ + data.gctx_paddr =__psp_pa (sev->snp_context); + data.asid = asid; +again: + ret =sev_issue_cmd (kvm,SEV_CMD_SNP_ACTIVATE , &data, error); + +/* Check if the DF_FLUSH is required, and try again */
Please provide more info on why this may be necessary. I can see from the code that it does a flush and retries, but I have no idea why a flush would be required in the first place, e.g. why can't KVM guarantee that everything is in the proper state before attempting to bind an ASID?
arch/x86/kvm/svm/sev.c static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1578
Quoted 11 lines
arch/x86/kvm/svm/sev.c +11
-0+if (ret && (*error ==SEV_RET_DFFLUSH_REQUIRED ) && (!retry_count)) { +/* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */ +down_read (&sev_deactivate_lock); +wbinvd_on_all_cpus (); + ret =snp_guest_df_flush (error); +up_read (&sev_deactivate_lock); + +if (ret) +return ret; + +/* only one retry */
Again, please explain why. Is this arbitrary? Is retrying more than once guaranteed to be useless?
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+ retry_count =1 ; + + goto again; + } + +return ret; +}
...
arch/x86/kvm/svm/sev.c void sev_vm_destroy(struct kvm *kvm) · line 1974
Quoted 11 lines
void
sev_vm_destroy(struct kvm *kvm)
{arch/x86/kvm/svm/sev.c +3
-1struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info;@@ -1847,7 +1969,15 @@ void sev_vm_destroy(struct kvm *kvm)mutex_unlock (&kvm->lock); -sev_unbind_asid (kvm, sev->handle); +if (sev_snp_guest (kvm)) { +if (snp_decommission_context (kvm)) { +pr_err ("Failed to free SNP guest context, leaking asid!\n" );
I agree with Peter that this likely warrants a WARN. If a WARN isn't justified, e.g. this can happen without a KVM/CPU bug, then there absolutely needs to be a massive comment explaining why we have code that result in memory leaks.
Quoted 34 lines
arch/x86/kvm/svm/sev.c +6
-0+return ; + } + }else { +sev_unbind_asid (kvm, sev->handle); + } +sev_asid_free (sev); }arch/x86/kvm/svm/svm.h +1
-0@@ -67,6 +67,7 @@ struct kvm_sev_info {u64 ap_jump_table;/* SEV-ES AP Jump Table address */ struct kvm *enc_context_owner;/* Owner of copied encryption context */ struct misc_cg *misc_cg;/* For misc cgroup accounting */ +void *snp_context;/* SNP guest context page */ };struct kvm_svm {include/uapi/linux/kvm.h +1
-0@@ -1680,6 +1680,7 @@ enum sev_cmd_id {/* SNP specific commands */ KVM_SEV_SNP_INIT =256 , +KVM_SEV_SNP_LAUNCH_START , KVM_SEV_NR_MAX, };
include/uapi/linux/kvm.h struct kvm_snp_init { · line 1790
Quoted 9 lines
include/uapi/linux/kvm.h +6
-0@@ -1781,6 +1782,14 @@ struct kvm_snp_init {__u64 flags; }; +struct kvm_sev_snp_launch_start { +__u64 policy; +__u64 ma_uaddr; +__u8 ma_en; +__u8 imi_en; +__u8 gosvw[16 ];
Hmm, I'd prefer to pad this out to be 8-byte sized.
Quoted 8 lines
include/uapi/linux/kvm.h +2
-0+}; +#define KVM_DEV_ASSIGN_ENABLE_IOMMU (1 << 0)#define KVM_DEV_ASSIGN_PCI_2_3 (1 << 1)#define KVM_DEV_ASSIGN_MASK_INTX (1 << 2)Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 23/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_START command
Quoted 39 lines · Sean Christopherson
arch/x86/kvm/svm/sev.c static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1539
Quoted 11 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +7
-0@@ -1527,6 +1530,100 @@ static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)return sev_issue_cmd (kvm,SEV_CMD_RECEIVE_FINISH , &data, &argp->error); } +static void *snp_context_create (struct kvm *kvm,struct kvm_sev_cmd *argp) +{ +struct sev_data_snp_gctx_create data = {}; +void *context; +int rc; + +/* Allocate memory for context page */ Eh, I'd drop this comment. It's quite obvious that a page is being allocated and that it's being assigned to the context.
Quoted 24 lines
arch/x86/kvm/svm/sev.c +24
-0+ context =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT ); +if (!context) +return NULL ; + + data.gctx_paddr =__psp_pa (context); + rc =__sev_issue_cmd (argp->sev_fd,SEV_CMD_SNP_GCTX_CREATE , &data, &argp->error); +if (rc) { +snp_free_firmware_page (context); +return NULL ; + } + +return context; +} + +static int snp_bind_asid (struct kvm *kvm,int *error) +{ +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +struct sev_data_snp_activate data = {}; +int asid =sev_get_asid (kvm); +int ret, retry_count =0 ; + +/* Activate ASID on the given context */ + data.gctx_paddr =__psp_pa (sev->snp_context); + data.asid = asid;
Quoted 8 lines
arch/x86/kvm/svm/sev.c static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1567
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+again: + ret =sev_issue_cmd (kvm,SEV_CMD_SNP_ACTIVATE , &data, error); + +/* Check if the DF_FLUSH is required, and try again */ Please provide more info on why this may be necessary. I can see from the code that it does a flush and retries, but I have no idea why a flush would be required in the first place, e.g. why can't KVM guarantee that everything is in the proper state before attempting to bind an ASID?
Ah good question, we already have function to recycle the ASIDs. The recycle happen during the ASID allocation. While recycling it issues the SEV/ES DF_FLUSH command. That function need to be enhanced to use the SNP specific DF_FLUSH command when ASID's are getting reused. I wish we had one DF_FLUSH which internally takes care of both the cases. Thinking loud, maybe firmware team decided to add a new one because what if someone is not using the SEV and SEV-ES or some fw does not support legacy SEV commands. I will fix it and remove the DF_FLUSH from the launch_start.
Quoted 31 lines
arch/x86/kvm/svm/sev.c static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1578
Quoted 12 lines
arch/x86/kvm/svm/sev.c +11
-0+if (ret && (*error ==SEV_RET_DFFLUSH_REQUIRED ) && (!retry_count)) { +/* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */ +down_read (&sev_deactivate_lock); +wbinvd_on_all_cpus (); + ret =snp_guest_df_flush (error); +up_read (&sev_deactivate_lock); + +if (ret) +return ret; + +/* only one retry */ Again, please explain why. Is this arbitrary? Is retrying more than once guaranteed to be useless?
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+ retry_count =1 ; + + goto again; + } + +return ret; +}...
Quoted 7 lines
void
sev_vm_destroy(struct kvm *kvm)
{arch/x86/kvm/svm/sev.c +0
-0struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info;@@ -1847,7 +1969,15 @@ void sev_vm_destroy(struct kvm *kvm)mutex_unlock (&kvm->lock);
Quoted 7 lines
arch/x86/kvm/svm/sev.c void sev_vm_destroy(struct kvm *kvm) · line 1974
Quoted 4 lines
arch/x86/kvm/svm/sev.c +3
-1-sev_unbind_asid (kvm, sev->handle); +if (sev_snp_guest (kvm)) { +if (snp_decommission_context (kvm)) { +pr_err ("Failed to free SNP guest context, leaking asid!\n" );I agree with Peter that this likely warrants a WARN. If a WARN isn't justified, e.g. this can happen without a KVM/CPU bug, then there absolutely needs to be a massive comment explaining why we have code that result in memory leaks.
Ack.
Quoted 38 lines
Quoted 38 lines
arch/x86/kvm/svm/sev.c +6
-0+return ; + } + }else { +sev_unbind_asid (kvm, sev->handle); + } +sev_asid_free (sev); }arch/x86/kvm/svm/svm.h +1
-0@@ -67,6 +67,7 @@ struct kvm_sev_info {u64 ap_jump_table;/* SEV-ES AP Jump Table address */ struct kvm *enc_context_owner;/* Owner of copied encryption context */ struct misc_cg *misc_cg;/* For misc cgroup accounting */ +void *snp_context;/* SNP guest context page */ };struct kvm_svm {include/uapi/linux/kvm.h +1
-0@@ -1680,6 +1680,7 @@ enum sev_cmd_id {/* SNP specific commands */ KVM_SEV_SNP_INIT =256 , +KVM_SEV_SNP_LAUNCH_START , KVM_SEV_NR_MAX, };@@ -1781,6 +1782,14 @@ struct kvm_snp_init {__u64 flags; };
Quoted 7 lines
include/uapi/linux/kvm.h struct kvm_snp_init { · line 1790
Quoted 6 lines
include/uapi/linux/kvm.h +6
-0+struct kvm_sev_snp_launch_start { +__u64 policy; +__u64 ma_uaddr; +__u8 ma_en; +__u8 imi_en; +__u8 gosvw[16 ];Hmm, I'd prefer to pad this out to be 8-byte sized.
Noted.
Quoted 8 lines
Quoted 8 lines
include/uapi/linux/kvm.h +2
-0+}; +#define KVM_DEV_ASSIGN_ENABLE_IOMMU (1 << 0)#define KVM_DEV_ASSIGN_PCI_2_3 (1 << 1)#define KVM_DEV_ASSIGN_MASK_INTX (1 << 2)Signature · 1 line
2.17.1
RFC PATCH v4 24/40 KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command
In reply to Brijesh SinghThe KVM_SEV_SNP_LAUNCH_UPDATE command can be used to insert data into the guest's memory. The data is encrypted with the cryptographic context created with the KVM_SEV_SNP_LAUNCH_START.
In addition to the inserting data, it can insert a two special pages into the guests memory: the secrets page and the CPUID page.
For more information see the SEV-SNP specification.
--- .../virt/kvm/amd-memory-encryption.rst | 28 ++++ arch/x86/kvm/svm/sev.c | 142 ++++++++++++++++++ include/linux/sev.h | 2 + include/uapi/linux/kvm.h | 18 +++ 4 files changed, 190 insertions(+)
Documentation/virt/kvm/amd-memory-encryption.rst +28 -0
@@ -468,6 +468,34 @@ Returns: 0 on success, -negative on error See the SEV-SNP specification for further detail on the launch input. +20. KVM_SNP_LAUNCH_UPDATE +------------------------- + +The KVM_SNP_LAUNCH_UPDATE is used for encrypting a memory region. It also +calculates a measurement of the memory contents. The measurement is a signature +of the memory contents that can be sent to the guest owner as an attestation +that the memory was encrypted correctly by the firmware. + +Parameters (in): struct kvm_snp_launch_update + +Returns: 0 on success, -negative on error + +:: + + struct kvm_sev_snp_launch_update { + __u64 uaddr; /* userspace address need to be encrypted */ + __u32 len; /* length of memory region */ + __u8 imi_page; /* 1 if memory is part of the IMI */ + __u8 page_type; /* page type */ + __u8 vmpl3_perms; /* VMPL3 permission mask */ + __u8 vmpl2_perms; /* VMPL2 permission mask */ + __u8 vmpl1_perms; /* VMPL1 permission mask */ + }; + +See the SEV-SNP spec for further details on how to build the VMPL permission +mask and page type. + + References ==========
arch/x86/kvm/svm/sev.c +142 -0
160 lines not on this page · raw message
include/linux/sev.h +2 -0
@@ -36,8 +36,10 @@ struct __packed rmpentry {/* RMP page size */ #define RMP_PG_SIZE_4K 0 +#define RMP_PG_SIZE_2M 1#define RMP_TO_X86_PG_LEVEL (level) (((level) == RMP_PG_SIZE_4K) ? PG_LEVEL_4K : PG_LEVEL_2M) +#define X86_TO_RMP_PG_LEVEL (level) (((level) == PG_LEVEL_4K) ? RMP_PG_SIZE_4K : RMP_PG_SIZE_2M)struct rmpupdate {u64 gpa;
include/uapi/linux/kvm.h +18 -0
@@ -1681,6 +1681,7 @@ enum sev_cmd_id {/* SNP specific commands */ KVM_SEV_SNP_INIT =256 ,KVM_SEV_SNP_LAUNCH_START , +KVM_SEV_SNP_LAUNCH_UPDATE , KVM_SEV_NR_MAX, };
@@ -1790,6 +1791,23 @@ struct kvm_sev_snp_launch_start {__u8 gosvw[16 ]; }; +#define KVM_SEV_SNP_PAGE_TYPE_NORMAL 0x1 +#define KVM_SEV_SNP_PAGE_TYPE_VMSA 0x2 +#define KVM_SEV_SNP_PAGE_TYPE_ZERO 0x3 +#define KVM_SEV_SNP_PAGE_TYPE_UNMEASURED 0x4 +#define KVM_SEV_SNP_PAGE_TYPE_SECRETS 0x5 +#define KVM_SEV_SNP_PAGE_TYPE_CPUID 0x6 + +struct kvm_sev_snp_launch_update { +__u64 uaddr; +__u32 len; +__u8 imi_page; +__u8 page_type; +__u8 vmpl3_perms; +__u8 vmpl2_perms; +__u8 vmpl1_perms; +}; +#define KVM_DEV_ASSIGN_ENABLE_IOMMU (1 << 0)#define KVM_DEV_ASSIGN_PCI_2_3 (1 << 1)#define KVM_DEV_ASSIGN_MASK_INTX (1 << 2)
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 24/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command
Quoted 15 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +15
-0+static int snp_launch_update (struct kvm *kvm,struct kvm_sev_cmd *argp) +{ +unsigned long npages, vaddr, vaddr_end, i, next_vaddr; +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +struct sev_data_snp_launch_update data = {}; +struct kvm_sev_snp_launch_update params; +int *error = &argp->error; +struct kvm_vcpu *vcpu; +struct page **inpages; +struct rmpupdate e; +int ret; + +if (!sev_snp_guest (kvm)) +return -ENOTTY ; +
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1695
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+if (!sev->snp_context) +return -EINVAL ; + +if (copy_from_user (¶ms, (void __user *)(uintptr_t )argp->data,sizeof (params))) +return -EFAULT ; + + data.gctx_paddr =__psp_pa (sev->snp_context); + +/* Lock the user memory. */ + inpages =sev_pin_memory (kvm, params.uaddr, params.len, &npages,1 );
params.uaddr needs to be checked for validity, e.g. proper alignment. sev_pin_memory() does some checks, but not all checks.
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1708
Quoted 13 lines
arch/x86/kvm/svm/sev.c +13
-0+if (!inpages) +return -ENOMEM ; + + vcpu =kvm_get_vcpu (kvm,0 ); + vaddr = params.uaddr; + vaddr_end = vaddr + params.len; + +for (i =0 ; vaddr < vaddr_end; vaddr = next_vaddr, i++) { +unsigned long psize, pmask; +int level =PG_LEVEL_4K ; +gpa_t gpa; + +if (!hva_to_gpa (kvm, vaddr, &gpa)) {
I'm having a bit of deja vu... This flow needs to hold kvm->srcu to do a memslot lookup.
That said, IMO having KVM do the hva->gpa is not a great ABI. The memslots are completely arbitrary (from a certain point of view) and have no impact on the validity of the memory pinning or PSP command. E.g. a memslot update while this code is in-flight would be all kinds of weird.
In other words, make userspace provide both the hva (because it's sadly needed to pin memory) as well as the target gpa. That prevents KVM from having to deal with memslot lookups and also means that userspace can issue the command before configuring the memslots (though I've no idea if that's actually feasible for any userspace VMM).
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1714
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ ret = -EINVAL ; + goto e_unpin; + } + + psize =page_level_size (level); + pmask =page_level_mask (level);
Is there any hope of this path supporting 2mb/1gb pages in the not-too-distant future? If not, then I vote to do away with the indirection and just hardcode 4kg sizes in the flow. I.e. if this works on 4kb chunks, make that obvious.
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1724
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ gpa = gpa & pmask; + +/* Transition the page state to pre-guest */ +memset (&e,0 ,sizeof (e)); + e.assigned =1 ; + e.gpa = gpa; + e.asid =sev_get_asid (kvm); + e.immutable = true; + e.pagesize =X86_TO_RMP_PG_LEVEL (level); + ret =rmpupdate (inpages[i], &e);
What happens if userspace pulls a stupid and assigns the same page to multiple SNP guests? Does RMPUPDATE fail? Can one RMPUPDATE overwrite another?
Quoted 23 lines
arch/x86/kvm/svm/sev.c +23
-0+if (ret) { + ret = -EFAULT ; + goto e_unpin; + } + + data.address =__sme_page_pa (inpages[i]); + data.page_size = e.pagesize; + data.page_type = params.page_type; + data.vmpl3_perms = params.vmpl3_perms; + data.vmpl2_perms = params.vmpl2_perms; + data.vmpl1_perms = params.vmpl1_perms; + ret =__sev_issue_cmd (argp->sev_fd,SEV_CMD_SNP_LAUNCH_UPDATE , &data, error); +if (ret) { +snp_page_reclaim (inpages[i], e.pagesize); + goto e_unpin; + } + + next_vaddr = (vaddr & pmask) + psize; + } + +e_unpin: +/* Content of memory is updated, mark pages dirty */ +memset (&e,0 ,sizeof (e));
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1757
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+for (i =0 ; i < npages; i++) { +set_page_dirty_lock (inpages[i]); +mark_page_accessed (inpages[i]); + +/* +* If its an error, then update RMP entry to change page ownership +* to the hypervisor. +*/ +if (ret) +rmpupdate (inpages[i], &e);
This feels wrong since it's purging _all_ RMP entries, not just those that were successfully modified. And maybe add a RMP "reset" helper, e.g. why is zeroing the RMP entry the correct behavior?
Quoted 8 lines
arch/x86/kvm/svm/sev.c +8
-0+ } + +/* Unlock the user pages */ +sev_unpin_memory (kvm, inpages, npages); + +return ret; +} +
Re: [PATCH Part2 RFC v4 24/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command
Quoted 20 lines · Sean Christopherson
Quoted 19 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +19
-0+static int snp_launch_update (struct kvm *kvm,struct kvm_sev_cmd *argp) +{ +unsigned long npages, vaddr, vaddr_end, i, next_vaddr; +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +struct sev_data_snp_launch_update data = {}; +struct kvm_sev_snp_launch_update params; +int *error = &argp->error; +struct kvm_vcpu *vcpu; +struct page **inpages; +struct rmpupdate e; +int ret; + +if (!sev_snp_guest (kvm)) +return -ENOTTY ; + +if (!sev->snp_context) +return -EINVAL ; + +if (copy_from_user (¶ms, (void __user *)(uintptr_t )argp->data,sizeof (params)))
Quoted 9 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1695
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+return -EFAULT ; + + data.gctx_paddr =__psp_pa (sev->snp_context); + +/* Lock the user memory. */ + inpages =sev_pin_memory (kvm, params.uaddr, params.len, &npages,1 );params.uaddr needs to be checked for validity, e.g. proper alignment.
sev_pin_memory()does some checks, but not all checks.
Noted
Quoted 21 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1708
Quoted 13 lines
arch/x86/kvm/svm/sev.c +13
-0+if (!inpages) +return -ENOMEM ; + + vcpu =kvm_get_vcpu (kvm,0 ); + vaddr = params.uaddr; + vaddr_end = vaddr + params.len; + +for (i =0 ; vaddr < vaddr_end; vaddr = next_vaddr, i++) { +unsigned long psize, pmask; +int level =PG_LEVEL_4K ; +gpa_t gpa; + +if (!hva_to_gpa (kvm, vaddr, &gpa)) {I'm having a bit of deja vu... This flow needs to hold
kvm->srcuto do a memslot lookup.That said, IMO having KVM do the
hva->gpais not a great ABI. The memslots are completely arbitrary (from a certain point of view) and have no impact on the validity of the memory pinning or PSP command. E.g. a memslot update while this code is in-flight would be all kinds of weird.
Quoted 5 lines
In other words, make userspace provide both the hva (because it's sadly needed to pin memory) as well as the target gpa. That prevents KVM from having to deal with memslot lookups and also means that userspace can issue the command before configuring the memslots (though I've no idea if that's actually feasible for any userspace VMM).
The operation happen during the guest creation time so I was not sure if memslot will be updated while we are executing this command. But I guess its possible that a VMM may run different thread which may update memslot while another thread calls the encryption. I'll let userspace provide both the HVA and GPA as you recommended.
Quoted 9 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1714
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ ret = -EINVAL ; + goto e_unpin; + } + + psize =page_level_size (level); + pmask =page_level_mask (level);Is there any hope of this path supporting 2mb/1gb pages in the not-too-distant future? If not, then I vote to do away with the indirection and just hardcode 4kg sizes in the flow. I.e. if this works on 4kb chunks, make that obvious.
No plans to do 1g/2mb in this path. I will make that obvious by hardcoding it.
Quoted 4 lines
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+ gpa = gpa & pmask; + +/* Transition the page state to pre-guest */ +memset (&e,0 ,sizeof (e));
Quoted 8 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1724
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ e.assigned =1 ; + e.gpa = gpa; + e.asid =sev_get_asid (kvm); + e.immutable = true; + e.pagesize =X86_TO_RMP_PG_LEVEL (level); + ret =rmpupdate (inpages[i], &e);What happens if userspace pulls a stupid and assigns the same page to multiple SNP guests? Does RMPUPDATE fail? Can one RMPUPDATE overwrite another?
The RMPUPDATE is available to the hv and it can call anytime with whatever it want. The important thing is the RMPUPDATE + PVALIDATE combination is what locks the page. In this case, PSP firmware updates the RMP table and also validates the page.
If someone else attempts to issue another RMPUPDATE then Validated bit will be cleared and page is no longer used as a private. Access to unvalidated page will cause #VC.
Quoted 29 lines
Quoted 29 lines
arch/x86/kvm/svm/sev.c +28
-0+if (ret) { + ret = -EFAULT ; + goto e_unpin; + } + + data.address =__sme_page_pa (inpages[i]); + data.page_size = e.pagesize; + data.page_type = params.page_type; + data.vmpl3_perms = params.vmpl3_perms; + data.vmpl2_perms = params.vmpl2_perms; + data.vmpl1_perms = params.vmpl1_perms; + ret =__sev_issue_cmd (argp->sev_fd,SEV_CMD_SNP_LAUNCH_UPDATE , &data, error); +if (ret) { +snp_page_reclaim (inpages[i], e.pagesize); + goto e_unpin; + } + + next_vaddr = (vaddr & pmask) + psize; + } + +e_unpin: +/* Content of memory is updated, mark pages dirty */ +memset (&e,0 ,sizeof (e)); +for (i =0 ; i < npages; i++) { +set_page_dirty_lock (inpages[i]); +mark_page_accessed (inpages[i]); + +/*
Quoted 8 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1757
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+* If its an error, then update RMP entry to change page ownership +* to the hypervisor. +*/ +if (ret) +rmpupdate (inpages[i], &e);This feels wrong since it's purging _all_ RMP entries, not just those that were successfully modified. And maybe add a RMP "reset" helper, e.g. why is zeroing the RMP entry the correct behavior?
By default all the pages are hypervior owned (i.e zero). If the LAUNCH_UPDATE was successful then page should have transition from the hypervisor owned to guest valid. By zero'ing it are reverting it back to hypevisor owned.
I agree that I optimize it to clear the modified entries only and leave everything else as a default.
thanks
Quoted 8 lines
Quoted 8 lines
arch/x86/kvm/svm/sev.c +8
-0+ } + +/* Unlock the user pages */ +sev_unpin_memory (kvm, inpages, npages); + +return ret; +} +
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 24/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command
Quoted 16 lines · Brijesh Singh
Quoted 8 lines · Sean Christopherson
I'm having a bit of deja vu... This flow needs to hold
kvm->srcuto do a memslot lookup.That said, IMO having KVM do the
hva->gpais not a great ABI. The memslots are completely arbitrary (from a certain point of view) and have no impact on the validity of the memory pinning or PSP command. E.g. a memslot update while this code is in-flight would be all kinds of weird.Quoted 5 lines
In other words, make userspace provide both the hva (because it's sadly needed to pin memory) as well as the target gpa. That prevents KVM from having to deal with memslot lookups and also means that userspace can issue the command before configuring the memslots (though I've no idea if that's actually feasible for any userspace VMM).
Quoted 5 lines
The operation happen during the guest creation time so I was not sure if memslot will be updated while we are executing this command. But I guess its possible that a VMM may run different thread which may update memslot while another thread calls the encryption. I'll let userspace provide both the HVA and GPA as you recommended.
I'm not worried about a well-behaved userspace VMM, I'm worried about the code KVM has to carry to guard against a misbehaving VMM.
Quoted 27 lines
Quoted 9 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1714
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ ret = -EINVAL ; + goto e_unpin; + } + + psize =page_level_size (level); + pmask =page_level_mask (level);Is there any hope of this path supporting 2mb/1gb pages in the not-too-distant future? If not, then I vote to do away with the indirection and just hardcode 4kg sizes in the flow. I.e. if this works on 4kb chunks, make that obvious.
No plans to do 1g/2mb in this path. I will make that obvious by hardcoding it.
Quoted 4 lines
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+ gpa = gpa & pmask; + +/* Transition the page state to pre-guest */ +memset (&e,0 ,sizeof (e));Quoted 8 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1724
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ e.assigned =1 ; + e.gpa = gpa; + e.asid =sev_get_asid (kvm); + e.immutable = true; + e.pagesize =X86_TO_RMP_PG_LEVEL (level); + ret =rmpupdate (inpages[i], &e);What happens if userspace pulls a stupid and assigns the same page to multiple SNP guests? Does RMPUPDATE fail? Can one RMPUPDATE overwrite another?
Quoted 8 lines
The RMPUPDATE is available to the hv and it can call anytime with whatever it want. The important thing is the RMPUPDATE + PVALIDATE combination is what locks the page. In this case, PSP firmware updates the RMP table and also validates the page.
If someone else attempts to issue another RMPUPDATE then Validated bit will be cleared and page is no longer used as a private. Access to unvalidated page will cause #VC.
Hmm, and there's no indication on success that the previous entry was assigned? Adding a tracepoint in rmpupdate() to allow tracking transitions is probably a good idea, otherwise debugging RMP violations and/or unexpected #VC is going to be painful.
And/or if the kernel/KVM behavior is to never reassign directly and reading an RMP entry isn't prohibitively expensive, then we could add a sanity check that the RMP is unassigned and reject rmpupdate() if the page is already assigned. Probably not worth it if the overhead is noticeable, but it could be nice to have if things go sideways.
Quoted 17 lines
Quoted 8 lines
Quoted 8 lines
arch/x86/kvm/svm/sev.c +8
-0+e_unpin: +/* Content of memory is updated, mark pages dirty */ +memset (&e,0 ,sizeof (e)); +for (i =0 ; i < npages; i++) { +set_page_dirty_lock (inpages[i]); +mark_page_accessed (inpages[i]); + +/* Quoted 8 lines
arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1757
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+* If its an error, then update RMP entry to change page ownership +* to the hypervisor. +*/ +if (ret) +rmpupdate (inpages[i], &e);This feels wrong since it's purging _all_ RMP entries, not just those that were successfully modified. And maybe add a RMP "reset" helper, e.g. why is zeroing the RMP entry the correct behavior?
Quoted 7 lines
By default all the pages are hypervior owned (i.e zero). If the
LAUNCH_UPDATEwas successful then page should have transition from the hypervisor owned to guest valid. By zero'ing it are reverting it back to hypevisor owned.I agree that I optimize it to clear the modified entries only and leave everything else as a default.
To be clear, it's not just an optimization. Pages that haven't yet been touched may be already owned by a different VM (or even this VM). I.e. "reverting" those pages would actually result in a form of corruption. It's somewhat of a moot point because assigning a single page to multiple guests is going to be fatal anyways, but potentially making a bug worse by introducing even more noise/confusion is not good.
Re: [PATCH Part2 RFC v4 24/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command
Quoted 6 lines · Sean Christopherson
Hmm, and there's no indication on success that the previous entry was assigned? Adding a tracepoint in
rmpupdate()to allow tracking transitions is probably a good idea, otherwise debugging RMP violations and/or unexpected #VC is going to be painful.
Absolutely agree. It's in my TODO list for v5. I have been using my private debug patches with all those trace debug and will try to pull some of those in v5.
Quoted 6 lines
And/or if the kernel/KVM behavior is to never reassign directly and reading an RMP entry isn't prohibitively expensive, then we could add a sanity check that the RMP is unassigned and reject
rmpupdate()if the page is already assigned. Probably not worth it if the overhead is noticeable, but it could be nice to have if things go sideways.
In later patches you see that during the page-state change, I do try to read RMP entry to detect some of these condition and warn user about them. The GHCB specification lets the hypervisor choose how it wants to handle the case in guest wanting to add the previously validated page.
Quoted 8 lines
To be clear, it's not just an optimization. Pages that haven't yet been touched may be already owned by a different VM (or even this VM). I.e. "reverting" those pages would actually result in a form of corruption. It's somewhat of a moot point because assigning a single page to multiple guests is going to be fatal anyways, but potentially making a bug worse by introducing even more noise/confusion is not good.
As you said, if a process is assigning the same page to multiple VMs then its fatal but I agree that we should do the right thing from the kernel ioctl handling. I will just clear the RMP entry for the pages which we touched.
thanks
Re: [PATCH Part2 RFC v4 24/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_UPDATE command
Quoted 5 lines · Brijesh Singh
Quoted 2 lines · Sean Christopherson
Hmm, and there's no indication on success that the previous entry was assigned?
I missed commenting on this.
Yes, there is no hint that page was previously assigned or validated.
thanks
RFC PATCH v4 25/40 KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
In reply to Brijesh SinghThe guest pages of the SEV-SNP VM maybe added as a private page in the RMP entry (assigned bit is set). The guest private pages must be transitioned to the hypervisor state before its freed.
--- arch/x86/kvm/svm/sev.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+)
arch/x86/kvm/svm/sev.c +39 -0
@@ -1940,6 +1940,45 @@ find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)static void __unregister_enc_region_locked (struct kvm *kvm,struct enc_region *region) { +struct rmpupdate val = {}; +unsigned long i, pfn; +struct rmpentry *e; +int level, rc; + +/* +* The guest memory pages are assigned in the RMP table. Unassign it +* before releasing the memory. +*/ +if (sev_snp_guest (kvm)) { +for (i =0 ; i < region->npages; i++) { + pfn =page_to_pfn (region->pages[i]); + +if (need_resched ()) +schedule (); + + e =snp_lookup_page_in_rmptable (region->pages[i], &level); +if (unlikely (!e)) +continue ; + +/* If its not a guest assigned page then skip it. */ +if (!rmpentry_assigned (e)) +continue ; + +/* Is the page part of a 2MB RMP entry? */ +if (level ==PG_LEVEL_2M ) { + val.pagesize =RMP_PG_SIZE_2M ; + pfn &= ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); + }else { + val.pagesize =RMP_PG_SIZE_4K ; + } + +/* Transition the page to hypervisor owned. */ + rc =rmpupdate (pfn_to_page (pfn), &val); +if (rc) +pr_err ("Failed to release pfn 0x%lx ret=%d\n" , pfn, rc); + } + } +sev_unpin_memory (kvm, region->pages, region->npages);list_del (®ion->list);kfree (region);
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 3 lines · Brijesh Singh
The guest pages of the SEV-SNP VM maybe added as a private page in the RMP entry (assigned bit is set). The guest private pages must be transitioned to the hypervisor state before its freed.
Isn't this patch needed much earlier in the series, i.e. when the first RMPUPDATE usage goes in?
Quoted 18 lines
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/kvm/svm/sev.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+)arch/x86/kvm/svm/sev.c +5
-0@@ -1940,6 +1940,45 @@ find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)static void __unregister_enc_region_locked (struct kvm *kvm,struct enc_region *region) { +struct rmpupdate val = {}; +unsigned long i, pfn; +struct rmpentry *e; +int level, rc; +
arch/x86/kvm/svm/sev.c find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) · line 1957
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+/* +* The guest memory pages are assigned in the RMP table. Unassign it +* before releasing the memory. +*/ +if (sev_snp_guest (kvm)) { +for (i =0 ; i < region->npages; i++) { + pfn =page_to_pfn (region->pages[i]); + +if (need_resched ()) +schedule ();
This can simply be "cond_resched();"
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+ + e =snp_lookup_page_in_rmptable (region->pages[i], &level); +if (unlikely (!e)) +continue ; +
arch/x86/kvm/svm/sev.c find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) · line 1972
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+/* If its not a guest assigned page then skip it. */ +if (!rmpentry_assigned (e)) +continue ; + +/* Is the page part of a 2MB RMP entry? */ +if (level ==PG_LEVEL_2M ) { + val.pagesize =RMP_PG_SIZE_2M ; + pfn &= ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); + }else { + val.pagesize =RMP_PG_SIZE_4K ;
This raises yet more questions (for me) as to the interaction between Page-Size and Hyperivsor-Owned flags in the RMP. It also raises questions on the correctness of zeroing the RMP entry if KVM_SEV_SNP_LAUNCH_START (in the previous patch).
arch/x86/kvm/svm/sev.c find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) · line 1978
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ } + +/* Transition the page to hypervisor owned. */ + rc =rmpupdate (pfn_to_page (pfn), &val); +if (rc) +pr_err ("Failed to release pfn 0x%lx ret=%d\n" , pfn, rc);
This is not robust, e.g. KVM will unpin the memory and release it back to the kernel with a stale RMP entry. Shouldn't this be a WARN+leak situation?
Quoted 9 lines
arch/x86/kvm/svm/sev.c +3
-0+ } + } +sev_unpin_memory (kvm, region->pages, region->npages);list_del (®ion->list);kfree (region);Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 6 lines · Sean Christopherson
Quoted 3 lines · Brijesh Singh
The guest pages of the SEV-SNP VM maybe added as a private page in the RMP entry (assigned bit is set). The guest private pages must be transitioned to the hypervisor state before its freed.
Isn't this patch needed much earlier in the series, i.e. when the first RMPUPDATE usage goes in?
Yes, the first RMPUPDATE usage is in the LAUNCH_UPDATE patch and this should be squashed in that patch.
Quoted 21 lines
Quoted 21 lines
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/kvm/svm/sev.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+)arch/x86/kvm/svm/sev.c +8
-0@@ -1940,6 +1940,45 @@ find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)static void __unregister_enc_region_locked (struct kvm *kvm,struct enc_region *region) { +struct rmpupdate val = {}; +unsigned long i, pfn; +struct rmpentry *e; +int level, rc; + +/* +* The guest memory pages are assigned in the RMP table. Unassign it +* before releasing the memory.
Quoted 8 lines
arch/x86/kvm/svm/sev.c find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) · line 1957
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+*/ +if (sev_snp_guest (kvm)) { +for (i =0 ; i < region->npages; i++) { + pfn =page_to_pfn (region->pages[i]); + +if (need_resched ()) +schedule ();This can simply be "
cond_resched();"
Yes.
Quoted 11 lines
Quoted 11 lines
arch/x86/kvm/svm/sev.c +10
-0+ + e =snp_lookup_page_in_rmptable (region->pages[i], &level); +if (unlikely (!e)) +continue ; + +/* If its not a guest assigned page then skip it. */ +if (!rmpentry_assigned (e)) +continue ; + +/* Is the page part of a 2MB RMP entry? */
Quoted 8 lines
arch/x86/kvm/svm/sev.c find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) · line 1972
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+if (level ==PG_LEVEL_2M ) { + val.pagesize =RMP_PG_SIZE_2M ; + pfn &= ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); + }else { + val.pagesize =RMP_PG_SIZE_4K ;This raises yet more questions (for me) as to the interaction between Page-Size and Hyperivsor-Owned flags in the RMP. It also raises questions on the correctness of zeroing the RMP entry if
KVM_SEV_SNP_LAUNCH_START(in the previous patch).
I assume you mean the LAUNCH_UPDATE because that's when we need to perform the RMPUPDATE. The hypervisor owned means all zero in the RMP entry.
Quoted 8 lines
arch/x86/kvm/svm/sev.c find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) · line 1978
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ } + +/* Transition the page to hypervisor owned. */ + rc =rmpupdate (pfn_to_page (pfn), &val); +if (rc) +pr_err ("Failed to release pfn 0x%lx ret=%d\n" , pfn, rc);This is not robust, e.g. KVM will unpin the memory and release it back to the kernel with a stale RMP entry. Shouldn't this be a WARN+leak situation?
Yes. Maybe we should increase the page refcount to ensure that this page is not reused after the process is terminated ?
Quoted 9 lines
Quoted 9 lines
arch/x86/kvm/svm/sev.c +3
-0+ } + } +sev_unpin_memory (kvm, region->pages, region->npages);list_del (®ion->list);kfree (region);Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 21 lines · Brijesh Singh
Quoted 10 lines · Sean Christopherson
Quoted 9 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +9
-0+ e =snp_lookup_page_in_rmptable (region->pages[i], &level); +if (unlikely (!e)) +continue ; + +/* If its not a guest assigned page then skip it. */ +if (!rmpentry_assigned (e)) +continue ; + +/* Is the page part of a 2MB RMP entry? */ Quoted 8 lines
arch/x86/kvm/svm/sev.c find_enc_region(struct kvm *kvm, struct kvm_enc_region *range) · line 1972
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+if (level ==PG_LEVEL_2M ) { + val.pagesize =RMP_PG_SIZE_2M ; + pfn &= ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); + }else { + val.pagesize =RMP_PG_SIZE_4K ;This raises yet more questions (for me) as to the interaction between Page-Size and Hyperivsor-Owned flags in the RMP. It also raises questions on the correctness of zeroing the RMP entry if
KVM_SEV_SNP_LAUNCH_START(in the previous patch).
Quoted 2 lines
I assume you mean the
LAUNCH_UPDATEbecause that's when we need to perform the RMPUPDATE.
Doh, yes.
Quoted 1 line
The hypervisor owned means all zero in the RMP entry.
Figured out where I went wrong after reading the RMPUDPATE pseudocode. RMPUPDATE takes the page size as a parameter even though it unconditionally zeros the page size flag in the RMP entry for unassigned pages.
A wrapper around rmpupdate() would definitely help, e.g. (though level might need to be an "int" to avoid a bunch of casts).
int rmp_make_shared(u64 pfn, enum pg_level level);
Wrappers for "private" and "firmware" would probably be helpful too. And if you do that, I think you can bury both "struct rmpupdate", rmpupdate(), and X86_TO_RMP_PG_LEVEL() in arch/x86/kernel/sev.c. snp_set_rmptable_state() might need some refactoring to avoid three booleans, but I guess maybe that could be an exception? Not sure. Anyways, was thinking something like:
int rmp_make_private(u64 pfn, u64 gpa, enum pg_level level, int asid); int rmp_make_firmware(u64 pfn);
It would consolidate a bit of code, and more importantly it would give visual cues to the reader, e.g. it's easy to overlook "val = {0}" meaning "make shared".
Side topic, what happens if a firmware entry is configured with page_size=1?
And one architectural question: what prevents a malicious VMM from punching a 4k shared page into a 2mb private page? E.g.
rmpupdate(1 << 20, [private, 2mb]); rmpupdate(1 << 20 + 4096, [shared, 4kb]);
I don't see any checks in the pseudocode that will detect this, and presumably the whole point of a 2mb private RMP entry is to not have to go walk the individual 4kb entries on a private access.
NEW_RMP = READ_MEM.o [NEW_RMP_PTR]
IF ((NEW_RMP.PAGE_SIZE == 2MB) && (SYSTEM_PA[20:12] != 0)) <-- not taken, 4kb entry
EAX = FAIL_INPUT
EXIT
IF (!NEW_RMP.ASSIGNED && (NEW_RMP.IMMUTABLE || (NEW_RMP.ASID != 0)) <-- not taken, new entry valid
EAX = FAIL_INPUT
EXIT RMP_ENTRY_PA = RMP_BASE + 0x4000 + (SYSTEM_PA / 0x1000) * 16 IF (RMP_ENTRY_PA > RMP_END)
EAX = FAIL_INPUT
EXIT
// System address must have an RMP entry
OLD_RMP = READ_MEM_PA.o [RMP_ENTRY_PA]
IF (OLD_RMP.IMMUTABLE) <-- passes, private entry not immutable
EAX = FAIL_PERMISSION
EXIT
IF (NEW_RMP.PAGE_SIZE == 4KB)
IF ((SYSTEM_PA[20:12] == 0) && (OLD_RMP.PAGE_SIZE == 2MB)) <- not taken, PA[12] == 1
EAX = FAIL_OVERLAP
EXIT
ELSE
IF (Any 4KB RMP entry with (RMP.ASSIGNED == 1) exists in 2MB region)
EAX = FAIL_OVERLAP
EXIT
ELSE
FOR (I = 1; I < 512, I++) {
temp_RMP = 0
temp_RMP.ASSIGNED = NEW_RMP.ASSIGNED
WRITE_MEM.o [RMP_ENTRY_PA + I * 16] = temp_RMP;
}Re: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 14 lines · Sean Christopherson
takes the page size as a parameter even though it unconditionally zeros the page size flag in the RMP entry for unassigned pages.
A wrapper around
rmpupdate()would definitely help, e.g. (though level might need to be an "int" to avoid a bunch of casts).int rmp_make_shared(u64 pfn, enum pg_level level);Wrappers for "private" and "firmware" would probably be helpful too. And if you do that, I think you can bury both "struct rmpupdate",
rmpupdate(), andX86_TO_RMP_PG_LEVEL()inarch/x86/kernel/sev.c.snp_set_rmptable_state()might need some refactoring to avoid three booleans, but I guess maybe that could be an exception? Not sure. Anyways, was thinking something like:
Quoted 5 lines
int
rmp_make_private(u64 pfn, u64 gpa, enum pg_level level, int asid); intrmp_make_firmware(u64 pfn);It would consolidate a bit of code, and more importantly it would give visual cues to the reader, e.g. it's easy to overlook "val = {0}" meaning "make shared".
Okay, I will add helper to make things easier. One case where we will need to directly call the rmpupdate() is during the LAUNCH_UPDATE command. In that case the page is private and its immutable bit is also set. This is because the firmware makes change to the page, and we are required to set the immutable bit before the call.
Quoted 2 lines
Side topic, what happens if a firmware entry is configured with page_size=1?
Its not any different from the guest requesting a page private with the page_size=1. Some firmware commands require the page_size=0, and others can work with page_size=1 or page_size=0.
Quoted 10 lines
And one architectural question: what prevents a malicious VMM from punching a 4k shared page into a 2mb private page? E.g.
rmpupdate(1 << 20, [private, 2mb]); rmpupdate(1 << 20 + 4096, [shared, 4kb]);I don't see any checks in the pseudocode that will detect this, and presumably the whole point of a 2mb private RMP entry is to not have to go walk the individual 4kb entries on a private access.
I believe pseudo-code is not meant to be exactly accurate and comprehensive, but it is intended to summarize the HW behavior and explain what can cause the different fault cases. In the real design we may have a separate checks to catch the above issue. I just tested on the hardware to ensure that HW correctly detects the above error condition. However, in this case we are missing a significant check (at least the check that the 2M region is not already assigned). I have raised the concern with the hardware team to look into updating the APM. thank you so much for the bringing this up.
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 20 lines · Brijesh Singh
Quoted 17 lines · Sean Christopherson
takes the page size as a parameter even though it unconditionally zeros the page size flag in the RMP entry for unassigned pages.
A wrapper around
rmpupdate()would definitely help, e.g. (though level might need to be an "int" to avoid a bunch of casts).int rmp_make_shared(u64 pfn, enum pg_level level);Wrappers for "private" and "firmware" would probably be helpful too. And if you do that, I think you can bury both "struct rmpupdate",
rmpupdate(), andX86_TO_RMP_PG_LEVEL()inarch/x86/kernel/sev.c.snp_set_rmptable_state()might need some refactoring to avoid three booleans, but I guess maybe that could be an exception? Not sure. Anyways, was thinking something like:int
rmp_make_private(u64 pfn, u64 gpa, enum pg_level level, int asid); intrmp_make_firmware(u64 pfn);
Quoted 8 lines
Quoted 2 lines
It would consolidate a bit of code, and more importantly it would give visual cues to the reader, e.g. it's easy to overlook "val = {0}" meaning "make shared".
Okay, I will add helper to make things easier. One case where we will need to directly call the
rmpupdate()is during theLAUNCH_UPDATEcommand. In that case the page is private and its immutable bit is also set. This is because the firmware makes change to the page, and we are required to set the immutable bit before the call.
Or do "int rmp_make_firmware(u64 pfn, bool immutable)"?
Quoted 10 lines
Quoted 9 lines
And one architectural question: what prevents a malicious VMM from punching a 4k shared page into a 2mb private page? E.g.
rmpupdate(1 << 20, [private, 2mb]); rmpupdate(1 << 20 + 4096, [shared, 4kb]);I don't see any checks in the pseudocode that will detect this, and presumably the whole point of a 2mb private RMP entry is to not have to go walk the individual 4kb entries on a private access.
Quoted 8 lines
I believe pseudo-code is not meant to be exactly accurate and comprehensive, but it is intended to summarize the HW behavior and explain what can cause the different fault cases. In the real design we may have a separate checks to catch the above issue. I just tested on the hardware to ensure that HW correctly detects the above error condition. However, in this case we are missing a significant check (at least the check that the 2M region is not already assigned). I have raised the concern with the hardware team to look into updating the APM.
Thanks! While you have their ear, please emphasive the importance of the pseudocode for us software folks. It's perfectly ok to omit or gloss over microarchitectural details, but ISA pseudocode is often the source of truth for behavior that is architecturally visible.
Re: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 9 lines · Sean Christopherson
Quoted 6 lines
Okay, I will add helper to make things easier. One case where we will need to directly call the
rmpupdate()is during theLAUNCH_UPDATEcommand. In that case the page is private and its immutable bit is also set. This is because the firmware makes change to the page, and we are required to set the immutable bit before the call.Or do "int
rmp_make_firmware(u64 pfn, bool immutable)"?
That's not what we need.
We need 'rmp_make_private() + immutable' all in one RMPUPDATE. Here is the snippet from SNP_LAUNCH_UPDATE.
+ /* Transition the page state to pre-guest */
+ memset(&e, 0, sizeof(e));
+ e.assigned = 1;
+ e.gpa = gpa;
+ e.asid = sev_get_asid(kvm);
+ e.immutable = true;
+ e.pagesize = X86_TO_RMP_PG_LEVEL(level);
+ ret = rmpupdate(inpages[i], &e);
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 9 lines · Brijesh Singh
Quoted 7 lines · Sean Christopherson
Quoted 6 lines
Okay, I will add helper to make things easier. One case where we will need to directly call the
rmpupdate()is during theLAUNCH_UPDATEcommand. In that case the page is private and its immutable bit is also set. This is because the firmware makes change to the page, and we are required to set the immutable bit before the call.
Quoted 6 lines
Quoted 1 line
Or do "int
rmp_make_firmware(u64 pfn, bool immutable)"?That's not what we need.
We need '
rmp_make_private()+ immutable' all in one RMPUPDATE. Here is the snippet fromSNP_LAUNCH_UPDATE.
Ah, not firmwrare, gotcha. But we can still use a helper, e.g. an inner double-underscore helper, __rmp_make_private().
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 12 lines · Sean Christopherson
Quoted 11 lines · Brijesh Singh
Quoted 8 lines · Sean Christopherson
Quoted 6 lines
Okay, I will add helper to make things easier. One case where we will need to directly call the
rmpupdate()is during theLAUNCH_UPDATEcommand. In that case the page is private and its immutable bit is also set. This is because the firmware makes change to the page, and we are required to set the immutable bit before the call.Or do "int
rmp_make_firmware(u64 pfn, bool immutable)"?
Quoted 7 lines
Quoted 4 lines
That's not what we need.
We need '
rmp_make_private()+ immutable' all in one RMPUPDATE. Here is the snippet fromSNP_LAUNCH_UPDATE.Ah, not firmwrare, gotcha. But we can still use a helper, e.g. an inner double-underscore helper,
__rmp_make_private().
Hmm, looking at it again, I think I also got confused by the comment for the VMSA page:
/* Transition the VMSA page to a firmware state. */ e.assigned = 1; e.immutable = 1; e.asid = sev->asid; e.gpa = -1; e.pagesize = RMP_PG_SIZE_4K;
Unlike __snp_alloc_firmware_pages() in the CCP code, the VMSA is associated with the guest's ASID, just not a GPA. I.e. the VMSA is more of a specialized guest private page, as opposed to a dedicated firmware page. I.e. a __rmp_make_private() and/or rmp_make_private_immutable() definitely seems like a good idea.
Re: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
In reply to Sean ChristophersonQuoted 12 lines · Sean Christopherson
Quoted 11 lines · Brijesh Singh
Quoted 8 lines · Sean Christopherson
Quoted 6 lines
Okay, I will add helper to make things easier. One case where we will need to directly call the
rmpupdate()is during theLAUNCH_UPDATEcommand. In that case the page is private and its immutable bit is also set. This is because the firmware makes change to the page, and we are required to set the immutable bit before the call.Or do "int
rmp_make_firmware(u64 pfn, bool immutable)"?
Quoted 8 lines
Quoted 4 lines
That's not what we need.
We need '
rmp_make_private()+ immutable' all in one RMPUPDATE. Here is the snippet fromSNP_LAUNCH_UPDATE.Ah, not firmwrare, gotcha. But we can still use a helper, e.g. an inner double-underscore helper,
__rmp_make_private().
In that case we are basically passing the all the fields defined in the 'struct rmpupdate' as individual arguments. How about something like this:
* core kernel exports the rmpupdate()
* the include/linux/sev.h header file defines the helper functions
int rmp_make_private(u64 pfn, u64 gpa, int psize, int asid) int rmp_make_firmware(u64 pfn, int psize); int rmp_make_shared(u64 pfn, int psize);
In most of the case above 3 helpers are good. If driver finds that the above helper does not fit its need (such as SNP_LAUNCH_UPDATE) then call the rmpupdate() without going through the helper.
-Brijesh
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 8 lines · Brijesh Singh
Quoted 3 lines · Sean Christopherson
On Mon, Jul 19, 2021, Brijesh Singh wrote:
Ah, not firmwrare, gotcha. But we can still use a helper, e.g. an inner double-underscore helper,__rmp_make_private().In that case we are basically passing the all the fields defined in the 'struct rmpupdate' as individual arguments.
Yes, but (a) not _all_ fields, (b) it would allow hiding "struct rmpupdate", and
(c) this is much friendlier to readers:
__rmp_make_private(pfn, gpa, PG_LEVEL_4K, svm->asid, true);
than:
rmpupdate(&rmpupdate);
For the former, I can see in a single line of code that KVM is creating a 4k private, immutable guest page. With the latter, I need to go hunt down all code that modifies rmpupdate to understand what the code is doing.
Quoted 6 lines
How about something like this:
* core kernel exports the
rmpupdate()
* theinclude/linux/sev.hheader file defines the helper functionsint
rmp_make_private(u64 pfn, u64 gpa, int psize, int asid)
I think we'll want s/psize/level, i.e. make it more obvious clear that the input is PG_LEVEL_*.
Re: [PATCH Part2 RFC v4 25/40] KVM: SVM: Reclaim the guest pages when SEV-SNP VM terminates
Quoted 10 lines · Sean Christopherson
Quoted 8 lines · Brijesh Singh
Quoted 3 lines · Sean Christopherson
On Mon, Jul 19, 2021, Brijesh Singh wrote:
Ah, not firmwrare, gotcha. But we can still use a helper, e.g. an inner double-underscore helper,__rmp_make_private().In that case we are basically passing the all the fields defined in the 'struct rmpupdate' as individual arguments.
Quoted 9 lines
Yes, but (a) not _all_ fields, (b) it would allow hiding "struct rmpupdate", and
(c) this is much friendlier to readers:__rmp_make_private(pfn, gpa, PG_LEVEL_4K, svm->asid, true);than:
rmpupdate(&rmpupdate);
Ok.
Quoted 6 lines
For the former, I can see in a single line of code that KVM is creating a 4k private, immutable guest page. With the latter, I need to go hunt down all code that modifies rmpupdate to understand what the code is doing.
Quoted 2 lines
How about something like this:
Quoted 8 lines
Quoted 4 lines
* core kernel exports the
rmpupdate()
* theinclude/linux/sev.hheader file defines the helper functionsint
rmp_make_private(u64 pfn, u64 gpa, int psize, int asid)I think we'll want s/psize/level, i.e. make it more obvious clear that the input is PG_LEVEL_*.
ok, I will stick to x86 PG_LEVEL_*
thanks
RFC PATCH v4 26/40 KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
In reply to Brijesh SinghThe KVM_SEV_SNP_LAUNCH_FINISH finalize the cryptographic digest and stores it as the measurement of the guest at launch.
While finalizing the launch flow, it also issues the LAUNCH_UPDATE command to encrypt the VMSA pages.
--- .../virt/kvm/amd-memory-encryption.rst | 22 +++ arch/x86/kvm/svm/sev.c | 125 ++++++++++++++++++ include/uapi/linux/kvm.h | 13 ++ 3 files changed, 160 insertions(+)
Documentation/virt/kvm/amd-memory-encryption.rst +22 -0
@@ -495,6 +495,28 @@ Returns: 0 on success, -negative on error See the SEV-SNP spec for further details on how to build the VMPL permission mask and page type. +21. KVM_SNP_LAUNCH_FINISH +------------------------- + +After completion of the SNP guest launch flow, the KVM_SNP_LAUNCH_FINISH command can be +issued to make the guest ready for the execution. + +Parameters (in): struct kvm_sev_snp_launch_finish + +Returns: 0 on success, -negative on error + +:: + + struct kvm_sev_snp_launch_finish { + __u64 id_block_uaddr; + __u64 id_auth_uaddr; + __u8 id_block_en; + __u8 auth_key_en; + __u8 host_data[32]; + }; + + +See SEV-SNP specification for further details on launch finish input parameters. References ==========
arch/x86/kvm/svm/sev.c +125 -0
145 lines not on this page · raw message
include/uapi/linux/kvm.h +13 -0
@@ -1682,6 +1682,7 @@ enum sev_cmd_id {KVM_SEV_SNP_INIT =256 ,KVM_SEV_SNP_LAUNCH_START ,KVM_SEV_SNP_LAUNCH_UPDATE , +KVM_SEV_SNP_LAUNCH_FINISH , KVM_SEV_NR_MAX, };
@@ -1808,6 +1809,18 @@ struct kvm_sev_snp_launch_update {__u8 vmpl1_perms; }; +#define KVM_SEV_SNP_ID_BLOCK_SIZE 96 +#define KVM_SEV_SNP_ID_AUTH_SIZE 4096 +#define KVM_SEV_SNP_FINISH_DATA_SIZE 32 + +struct kvm_sev_snp_launch_finish { +__u64 id_block_uaddr; +__u64 id_auth_uaddr; +__u8 id_block_en; +__u8 auth_key_en; +__u8 host_data[KVM_SEV_SNP_FINISH_DATA_SIZE ]; +}; +#define KVM_DEV_ASSIGN_ENABLE_IOMMU (1 << 0)#define KVM_DEV_ASSIGN_PCI_2_3 (1 << 1)#define KVM_DEV_ASSIGN_MASK_INTX (1 << 2)
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
Documentation/virt/kvm/amd-memory-encryption.rst Returns: 0 on success, -negative on error · line 515
Quoted 6 lines · Brijesh Singh
Documentation/virt/kvm/amd-memory-encryption.rst +6
-0+ struct kvm_sev_snp_launch_finish { + __u64 id_block_uaddr; + __u64 id_auth_uaddr; + __u8 id_block_en; + __u8 auth_key_en; + __u8 host_data[32];
Pad this one too?
Quoted 4 lines
Documentation/virt/kvm/amd-memory-encryption.rst +4
-0+ }; + + +See SEV-SNP specification for further details on launch finish input parameters.
...
arch/x86/kvm/svm/sev.c static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1858
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+ data->gctx_paddr =__psp_pa (sev->snp_context); + ret =sev_issue_cmd (kvm,SEV_CMD_SNP_LAUNCH_FINISH , data, &argp->error);
Shouldn't KVM unwind everything it did if LAUNCH_FINISH fails? And if that's not possible, take steps to make the VM unusable?
Quoted 12 lines
arch/x86/kvm/svm/sev.c +12
-0+ +kfree (id_auth); + +e_free_id_block: +kfree (id_block); + +e_free: +kfree (data); + +return ret; +} +
...
arch/x86/kvm/svm/sev.c void sev_free_vcpu(struct kvm_vcpu *vcpu) · line 2460
Quoted 8 lines
arch/x86/kvm/svm/sev.c +4
-0@@ -2346,8 +2454,25 @@ void sev_free_vcpu(struct kvm_vcpu *vcpu)if (vcpu->arch.guest_state_protected)sev_flush_guest_memory (svm, svm->vmsa,PAGE_SIZE ); + +/* +* If its an SNP guest, then VMSA was added in the RMP entry as a guest owned page. +* Transition the page to hyperivosr state before releasing it back to the system.
"hyperivosr" typo. And please wrap at 80 chars.
arch/x86/kvm/svm/sev.c void sev_free_vcpu(struct kvm_vcpu *vcpu) · line 2466
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+*/ +if (sev_snp_guest (vcpu->kvm)) { +struct rmpupdate e = {}; +int rc; + + rc =rmpupdate (virt_to_page (svm->vmsa), &e);
So why does this not need to go through snp_page_reclaim()?
arch/x86/kvm/svm/sev.c void sev_free_vcpu(struct kvm_vcpu *vcpu) · line 2468
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+if (rc) { +pr_err ("Failed to release SNP guest VMSA page (rc %d), leaking it\n" , rc);
Seems like a WARN would be simpler. But the more I see the rmpupdate(..., {0}) pattern, the more I believe that nuking an RMP entry needs a dedicated helper.
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+ goto skip_vmsa_free;
Re: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
Quoted 8 lines · Sean Christopherson
Documentation/virt/kvm/amd-memory-encryption.rst Returns: 0 on success, -negative on error · line 515
Quoted 6 lines · Brijesh Singh
Documentation/virt/kvm/amd-memory-encryption.rst +6
-0+ struct kvm_sev_snp_launch_finish { + __u64 id_block_uaddr; + __u64 id_auth_uaddr; + __u8 id_block_en; + __u8 auth_key_en; + __u8 host_data[32];Pad this one too?
Noted.
Quoted 11 lines
Quoted 5 lines
Documentation/virt/kvm/amd-memory-encryption.rst +4
-0+ }; + + +See SEV-SNP specification for further details on launch finish input parameters....
arch/x86/kvm/svm/sev.c static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1858
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+ data->gctx_paddr =__psp_pa (sev->snp_context); + ret =sev_issue_cmd (kvm,SEV_CMD_SNP_LAUNCH_FINISH , data, &argp->error);Shouldn't KVM unwind everything it did if
LAUNCH_FINISHfails? And if that's not possible, take steps to make the VM unusable?
Well, I am not sure if VM need to unwind. If the command fail but VMM decide to ignore the error then VMRUN will probably fail and user will get the KVM shutdown event. The LAUNCH_FINISH command finalizes the VM launch process, the firmware will probably not load the memory encryption keys until it moves to the running state.
Quoted 16 lines
Quoted 12 lines
arch/x86/kvm/svm/sev.c +12
-0+ +kfree (id_auth); + +e_free_id_block: +kfree (id_block); + +e_free: +kfree (data); + +return ret; +} +...
Quoted 2 lines
(quoted diff) +0
-0@@ -2346,8 +2454,25 @@ void sev_free_vcpu(struct kvm_vcpu *vcpu)
Quoted 7 lines
arch/x86/kvm/svm/sev.c void sev_free_vcpu(struct kvm_vcpu *vcpu) · line 2460
Quoted 6 lines
arch/x86/kvm/svm/sev.c +4
-0if (vcpu->arch.guest_state_protected)sev_flush_guest_memory (svm, svm->vmsa,PAGE_SIZE ); + +/* +* If its an SNP guest, then VMSA was added in the RMP entry as a guest owned page. +* Transition the page to hyperivosr state before releasing it back to the system. "hyperivosr" typo. And please wrap at 80 chars.
Noted.
Quoted 8 lines
arch/x86/kvm/svm/sev.c void sev_free_vcpu(struct kvm_vcpu *vcpu) · line 2466
Quoted 7 lines
arch/x86/kvm/svm/sev.c +6
-0+*/ +if (sev_snp_guest (vcpu->kvm)) { +struct rmpupdate e = {}; +int rc; + + rc =rmpupdate (virt_to_page (svm->vmsa), &e);So why does this not need to go through
snp_page_reclaim()?
As I said in previous comments that by default all the memory is in the hypervisor state. if the rmpupdate() failed that means nothing is changed in the RMP and there is no need to reclaim. The reclaim is required only if the pages are assigned in the RMP table.
Quoted 5 lines
arch/x86/kvm/svm/sev.c void sev_free_vcpu(struct kvm_vcpu *vcpu) · line 2468
Quoted 3 lines
arch/x86/kvm/svm/sev.c +2
-0+if (rc) { +pr_err ("Failed to release SNP guest VMSA page (rc %d), leaking it\n" , rc);Seems like a WARN would be simpler. But the more I see the
rmpupdate(..., {0})pattern, the more I believe that nuking an RMP entry needs a dedicated helper.
Yes, let me try coming up with helper for it.
Quoted 2 lines
Quoted 2 lines
arch/x86/kvm/svm/sev.c +1
-0+ goto skip_vmsa_free;
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
Quoted 8 lines · Brijesh Singh
Quoted 5 lines · Sean Christopherson
arch/x86/kvm/svm/sev.c static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1858
Quoted 2 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +2
-0+ data->gctx_paddr =__psp_pa (sev->snp_context); + ret =sev_issue_cmd (kvm,SEV_CMD_SNP_LAUNCH_FINISH , data, &argp->error);Shouldn't KVM unwind everything it did if
LAUNCH_FINISHfails? And if that's not possible, take steps to make the VM unusable?
Quoted 5 lines
Well, I am not sure if VM need to unwind. If the command fail but VMM decide to ignore the error then VMRUN will probably fail and user will get the KVM shutdown event. The
LAUNCH_FINISHcommand finalizes the VM launch process, the firmware will probably not load the memory encryption keys until it moves to the running state.
Within reason, KVM needs to provide consistent, deterministic behavior. Yes, more than likely failure at this point will be fatal to the VM, but that doesn't justify leaving the VM in a random/bogus state. In addition to being a poor ABI, it also makes it more difficult to reason about what is/isn't possible in KVM.
Quoted 8 lines
Quoted 7 lines
arch/x86/kvm/svm/sev.c void sev_free_vcpu(struct kvm_vcpu *vcpu) · line 2466
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+*/ +if (sev_snp_guest (vcpu->kvm)) { +struct rmpupdate e = {}; +int rc; + + rc =rmpupdate (virt_to_page (svm->vmsa), &e);So why does this not need to go through
snp_page_reclaim()?
Quoted 4 lines
As I said in previous comments that by default all the memory is in the hypervisor state. if the
rmpupdate()failed that means nothing is changed in the RMP and there is no need to reclaim. The reclaim is required only if the pages are assigned in the RMP table.
I wasn't referring to RMPUPDATE failing here (or anywhere). This is the vCPU free path, which I think means the svm->vmsa page was successfully updated in the RMP during LAUNCH_UPDATE. snp_launch_update_vmsa() goes through snp_page_reclaim() on LAUNCH_UPDATE failure, whereas this happy path does not. Is there some other transition during teardown that obviastes the need for reclaim? If so, a comment to explain that would be very helpful.
Re: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
Quoted 5 lines · Sean Christopherson
Quoted 4 lines
As I said in previous comments that by default all the memory is in the hypervisor state. if the
rmpupdate()failed that means nothing is changed in the RMP and there is no need to reclaim. The reclaim is required only if the pages are assigned in the RMP table.
Quoted 7 lines
I wasn't referring to RMPUPDATE failing here (or anywhere). This is the vCPU free path, which I think means the
svm->vmsapage was successfully updated in the RMP duringLAUNCH_UPDATE.snp_launch_update_vmsa()goes throughsnp_page_reclaim()onLAUNCH_UPDATEfailure, whereas this happy path does not. Is there some other transition during teardown that obviastes the need for reclaim? If so, a comment to explain that would be very helpful.
In this patch, the sev_free_vcpu() hunk takes care of reclaiming the vmsa pages before releasing it. I think it will make it more obvious after I add a helper so that we don't depend on user reading the comment block to see what its doing.
-Brijesh
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
Quoted 16 lines · Brijesh Singh
Quoted 5 lines · Sean Christopherson
Quoted 4 lines
As I said in previous comments that by default all the memory is in the hypervisor state. if the
rmpupdate()failed that means nothing is changed in the RMP and there is no need to reclaim. The reclaim is required only if the pages are assigned in the RMP table.Quoted 7 lines
I wasn't referring to RMPUPDATE failing here (or anywhere). This is the vCPU free path, which I think means the
svm->vmsapage was successfully updated in the RMP duringLAUNCH_UPDATE.snp_launch_update_vmsa()goes throughsnp_page_reclaim()onLAUNCH_UPDATEfailure, whereas this happy path does not. Is there some other transition during teardown that obviastes the need for reclaim? If so, a comment to explain that would be very helpful.
Quoted 4 lines
In this patch, the
sev_free_vcpu()hunk takes care of reclaiming the vmsa pages before releasing it. I think it will make it more obvious after I add a helper so that we don't depend on user reading the comment block to see what its doing.
Where? I feel like I'm missing something. The only change to sev_free_vcpu() I see is that addition of the rmpupdate(), I don't see any reclaim path.
@@ -2346,8 +2454,25 @@ void sev_free_vcpu(struct kvm_vcpu *vcpu)
if (vcpu->arch.guest_state_protected)
sev_flush_guest_memory(svm, svm->vmsa, PAGE_SIZE);
+
+ /*
+ * If its an SNP guest, then VMSA was added in the RMP entry as a guest owned page.
+ * Transition the page to hyperivosr state before releasing it back to the system.
+ */+ if (sev_snp_guest(vcpu->kvm)) {
+ struct rmpupdate e = {};
+ int rc;
+
+ rc = rmpupdate(virt_to_page(svm->vmsa), &e);
+ if (rc) {
+ pr_err("Failed to release SNP guest VMSA page (rc %d), leaking it\n", rc);
+ goto skip_vmsa_free;
+ }
+ }
+
__free_page(virt_to_page(svm->vmsa));
+skip_vmsa_free:
if (svm->ghcb_sa_free)
kfree(svm->ghcb_sa);}
Re: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
Quoted 3 lines · Sean Christopherson
Where? I feel like I'm missing something. The only change to
sev_free_vcpu()I see is that addition of thermpupdate(), I don't see any reclaim path.
Clearing of the immutable bit (aka reclaim) is done by the firmware after the command was successful. See the section 8.14.2.1 of the SEV-SNP spec[1].
The firmware encrypts the page with the VEK in place. The firmware sets the RMP.VMSA of the page to 1. The firmware sets the VMPL permissions for the page and transitions the page to Guest-Valid.
The Guest-Valid state means the immutable bit is cleared. In this case,
the hypervisor just need to make the page shared and that's what the sev_free_vcpu() does to ensure that page is transitioned from the Guest-Valid to Hypervisor.
[1] https://www.amd.com/system/files/TechDocs/56860.pdf
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
Quoted 8 lines · Brijesh Singh
Quoted 3 lines · Sean Christopherson
Where? I feel like I'm missing something. The only change to
sev_free_vcpu()I see is that addition of thermpupdate(), I don't see any reclaim path.Clearing of the immutable bit (aka reclaim) is done by the firmware after the command was successful.
Ah, which is why the failure path has to do manual reclaim of the immutable page. Thanks!
Re: [PATCH Part2 RFC v4 26/40] KVM: SVM: Add KVM_SEV_SNP_LAUNCH_FINISH command
In reply to Sean ChristophersonQuoted 16 lines · Sean Christopherson
Quoted 5 lines · Brijesh Singh
Quoted 3 lines · Sean Christopherson
Quoted 2 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +2
-0+ data->gctx_paddr =__psp_pa (sev->snp_context); + ret =sev_issue_cmd (kvm,SEV_CMD_SNP_LAUNCH_FINISH , data, &argp->error);Quoted 8 lines
Quoted 2 lines
Shouldn't KVM unwind everything it did if
LAUNCH_FINISHfails? And if that's not possible, take steps to make the VM unusable?Well, I am not sure if VM need to unwind. If the command fail but VMM decide to ignore the error then VMRUN will probably fail and user will get the KVM shutdown event. The
LAUNCH_FINISHcommand finalizes the VM launch process, the firmware will probably not load the memory encryption keys until it moves to the running state.
Quoted 4 lines
Within reason, KVM needs to provide consistent, deterministic behavior. Yes, more than likely failure at this point will be fatal to the VM, but that doesn't justify leaving the VM in a random/bogus state. In addition to being a poor ABI, it also makes it more difficult to reason about what is/isn't possible in KVM.
+1 to Sean's feedback to unwind everything here properly here. Comments of the nature of "XYZ should happen" -- without a test (e.g., selftest or kvm-unit-test) to ensure the XYZ _does_ happen -- are a time bomb waiting to happen.
Also, I wonder if we leave pages, RMPUPDATE'd to immutable in previous loop iterations, is it possible for them to remain as immutable and be reused later on (after this guest is destroyed)? And if this happens, will we get an RMP violation? Even if the answer is no -- go read this code 2,000 lines away -- it handles this case. That's still not a very satisfying answer. I'd rather see things cleaned up ASAP as soon as the code starts to go off the rails.
RFC PATCH v4 27/40 KVM: X86: Add kvm_x86_ops to get the max page level for the TDP
In reply to Brijesh SinghWhen running an SEV-SNP VM, the sPA used to index the RMP entry is obtained through the TDP translation (gva->gpa->spa). The TDP page level is checked against the page level programmed in the RMP entry. If the page level does not match, then it will cause a nested page fault with the RMP bit set to indicate the RMP violation.
To keep the TDP and RMP page level's in sync, the KVM fault handle kvm_handle_page_fault() will call get_tdp_max_page_level() to get the maximum allowed page level so that it can limit the TDP level.
In the case of SEV-SNP guest, the get_tdp_max_page_level() will consult the RMP table to compute the maximum allowed page level for a given GPA.
--- arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/mmu/mmu.c | 6 ++++-- arch/x86/kvm/svm/sev.c | 20 ++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 1 + arch/x86/kvm/svm/svm.h | 1 + arch/x86/kvm/vmx/vmx.c | 8 ++++++++ 6 files changed, 35 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -0
@@ -1384,6 +1384,7 @@ struct kvm_x86_ops {void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector);void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu); +int (*get_tdp_max_page_level)(struct kvm_vcpu *vcpu,gpa_t gpa,int max_level); };struct kvm_x86_nested_ops {
arch/x86/kvm/mmu/mmu.c +4 -2
@@ -3781,11 +3781,13 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,static int nonpaging_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,bool prefault) { +int max_level = kvm_x86_ops.get_tdp_max_page_level (vcpu, gpa,PG_LEVEL_2M ); +pgprintk ("%s: gva %lx error %x\n" , __func__, gpa, error_code);/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */ return direct_page_fault (vcpu, gpa &PAGE_MASK , error_code, prefault, -PG_LEVEL_2M , false); + max_level, false); } int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
@@ -3826,7 +3828,7 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, {int max_level; -for (max_level =KVM_MAX_HUGEPAGE_LEVEL ; +for (max_level = kvm_x86_ops.get_tdp_max_page_level (vcpu, gpa,KVM_MAX_HUGEPAGE_LEVEL ); max_level >PG_LEVEL_4K ; max_level--) {int page_num =KVM_PAGES_PER_HPAGE (max_level);
arch/x86/kvm/svm/sev.c +20 -0
@@ -3206,3 +3206,23 @@ struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu)return pfn_to_page (pfn); } + +int sev_get_tdp_max_page_level (struct kvm_vcpu *vcpu,gpa_t gpa,int max_level) +{ +struct rmpentry *e; +kvm_pfn_t pfn; +int level; + +if (!sev_snp_guest (vcpu->kvm)) +return max_level; + + pfn =gfn_to_pfn (vcpu->kvm,gpa_to_gfn (gpa)); +if (is_error_noslot_pfn (pfn)) +return max_level; + + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level); +if (unlikely (!e)) +return max_level; + +return min_t (uint32_t, level, max_level); +}
arch/x86/kvm/svm/svm.c +1 -0
@@ -4576,6 +4576,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = { .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector, .alloc_apic_backing_page = svm_alloc_apic_backing_page, + .get_tdp_max_page_level = sev_get_tdp_max_page_level, };static struct kvm_x86_init_ops svm_init_ops__initdata = {
arch/x86/kvm/svm/svm.h +1 -0
@@ -568,6 +568,7 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);void sev_es_prepare_guest_switch (struct vcpu_svm *svm,unsigned int cpu);void sev_es_unmap_ghcb (struct vcpu_svm *svm);struct page *snp_safe_alloc_page (struct kvm_vcpu *vcpu); +int sev_get_tdp_max_page_level (struct kvm_vcpu *vcpu,gpa_t gpa,int max_level);/* vmenter.S */
arch/x86/kvm/vmx/vmx.c +8 -0
@@ -7612,6 +7612,12 @@ static bool vmx_check_apicv_inhibit_reasons(ulong bit)return supported &BIT (bit); } + +static int vmx_get_tdp_max_page_level (struct kvm_vcpu *vcpu,gpa_t gpa,int max_level) +{ +return max_level; +} +static struct kvm_x86_ops vmx_x86_ops__initdata = { .hardware_unsetup = hardware_unsetup,
@@ -7742,6 +7748,8 @@ static struct kvm_x86_ops vmx_x86_ops __initdata = { .complete_emulated_msr = kvm_complete_insn_gp, .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector, + + .get_tdp_max_page_level = vmx_get_tdp_max_page_level, };static __init void vmx_setup_user_return_msrs (void )
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 27/40] KVM: X86: Add kvm_x86_ops to get the max page level for the TDP
Quoted 29 lines · Brijesh Singh
When running an SEV-SNP VM, the sPA used to index the RMP entry is obtained through the TDP translation (
gva->gpa->spa). The TDP page level is checked against the page level programmed in the RMP entry. If the page level does not match, then it will cause a nested page fault with the RMP bit set to indicate the RMP violation.To keep the TDP and RMP page level's in sync, the KVM fault handle
kvm_handle_page_fault()will callget_tdp_max_page_level()to get the maximum allowed page level so that it can limit the TDP level.In the case of SEV-SNP guest, the
get_tdp_max_page_level()will consult the RMP table to compute the maximum allowed page level for a given GPA.Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/mmu/mmu.c | 6 ++++-- arch/x86/kvm/svm/sev.c | 20 ++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 1 + arch/x86/kvm/svm/svm.h | 1 + arch/x86/kvm/vmx/vmx.c | 8 ++++++++ 6 files changed, 35 insertions(+), 2 deletions(-)arch/x86/include/asm/kvm_host.h +0
-0
arch/x86/include/asm/kvm_host.h struct kvm_x86_ops { · line 1387
Quoted 4 lines
arch/x86/include/asm/kvm_host.h +1
-0@@ -1384,6 +1384,7 @@ struct kvm_x86_ops {void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector);void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu); +int (*get_tdp_max_page_level)(struct kvm_vcpu *vcpu,gpa_t gpa,int max_level);
This is a poor name. The constraint comes from the RMP, not TDP, and technically speaking applies to all forms of paging. It just happens to be relevant only to TDP because NPT is required for SNP. And KVM already incorporates the max TDP level in kvm_configure_mmu().
Regarding the params, I'd much prefer to have this take "struct kvm *kvm" instead of the vCPU. It obviously doesn't change the functionality in any way, but I'd like it to be clear to readers that the adjustment is tied to the VM, not the vCPU.
I think I'd also vote to drop @max_level and make this a pure constraint input as opposed to an adjuster.
Another option would be to drop the kvm_x86_ops hooks entirely and call snp_lookup_page_in_rmptable() directly from MMU code. That would require tracking that a VM is SNP-enabled in arch code, but I'm pretty sure info has already bled into common KVM in one form or another.
arch/x86/kvm/mmu/mmu.c static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, · line 3784
Quoted 12 lines
arch/x86/include/asm/kvm_host.h +0
-0};struct kvm_x86_nested_ops {arch/x86/kvm/mmu/mmu.c +1
-0@@ -3781,11 +3781,13 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,static int nonpaging_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,bool prefault) { +int max_level = kvm_x86_ops.get_tdp_max_page_level (vcpu, gpa,PG_LEVEL_2M );
This is completely bogus, nonpaging_page_fault() is used iff TDP is disabled.
Quoted 11 lines
arch/x86/kvm/mmu/mmu.c +2
-1+pgprintk ("%s: gva %lx error %x\n" , __func__, gpa, error_code);/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */ return direct_page_fault (vcpu, gpa &PAGE_MASK , error_code, prefault, -PG_LEVEL_2M , false); + max_level, false); } int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
arch/x86/kvm/mmu/mmu.c int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, · line 3831
Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +1
-1@@ -3826,7 +3828,7 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, {int max_level; - for (max_level = KVM_MAX_HUGEPAGE_LEVEL; + for (max_level = kvm_x86_ops.get_tdp_max_page_level(vcpu, gpa, KVM_MAX_HUGEPAGE_LEVEL);
This is unnecessary. The max mapping level is computed by factoring in all constraints, of which there are many. In this case, KVM is consulting the guest's MTRR configuration to avoid creating a page that spans different memtypes (because the guest MTRRs are effectively represented in the TDP PTE). SNP's RMP constraints have no relevance to the MTRR constraint, or any other constraint for that matter.
TL;DR: the RMP constraint belong in kvm_mmu_max_mapping_level() and nowhere else. I would go so far as to argue it belong in host_pfn_mapping_level(), after the call to lookup_address_in_mm().
Quoted 9 lines
arch/x86/kvm/mmu/mmu.c +0
-0max_level >PG_LEVEL_4K ; max_level--) {int page_num =KVM_PAGES_PER_HPAGE (max_level);arch/x86/kvm/svm/sev.c +0
-0@@ -3206,3 +3206,23 @@ struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/sev.c struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu) · line 3216
Quoted 10 lines
arch/x86/kvm/svm/sev.c +8
-0return pfn_to_page (pfn); } + +int sev_get_tdp_max_page_level (struct kvm_vcpu *vcpu,gpa_t gpa,int max_level) +{ +struct rmpentry *e; +kvm_pfn_t pfn; +int level; + +if (!sev_snp_guest (vcpu->kvm))
I can't tell if this check is correct. Per the APM:
When SEV-SNP is enabled globally, the processor places restrictions on all memory accesses based on the contents of the RMP, whether the accesses are performed by the hypervisor, a legacy guest VM, a non-SNP guest VM or an SNP-active guest VM. The processor may perform one or more of the following checks depending on the context of the access:
...
Page-Size: Checks that the following conditions are met:
- If the nested page table indicates a 2MB or 1GB page size, the Page_Size field of the RMP entry of the target page is 1.
- If the nested page table indicates a 4KB page size, the Page_Size field of the RMP entry of the target page is 0.
The Page-Size bullet does not have any qualifiers about the NPT checks applying only to SNP guests. The Hypervisor-Owned bullet implies that unassigned pages do not need to have identical sizes, but it's not clear whether or not so called "Hypervisor-Owned" pages override the nested page tables.
Table 15.36 is similarly vague:
Assigned Flag indicating that the system physical page is assigned to a guest or to the AMD-SP.
0: Owned by the hypervisor
1: Owned by a guest or the AMD-SP
My assumption is that all of the "guest owned" stuff really means "SNP guest owned", e.g. section 15.36.5 says "The hypervisor manages the SEV-SNP security attributes of pages assigned to SNP-active guests by altering the RMP entries of those pages", but that's not at all clear throughout most of the RMP documentation.
Regardless of the actual behavior, the APM needs serious cleanup on the aforementioned sections. E.g. as written, the "processor may perform one or more of the following checks depending on the context of the access" verbiage basically gives the CPU carte blanche to do whatever the hell it wants.
arch/x86/kvm/svm/sev.c struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu) · line 3223
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+return max_level; + + pfn =gfn_to_pfn (vcpu->kvm,gpa_to_gfn (gpa)); +if (is_error_noslot_pfn (pfn)) +return max_level; + + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level);
Assuming pfn is backed by struct page is broken, at least given the existing call sites.. It might hold true that only struct page pfns are covered by the RMP, but assuming pfn_to_page() will return a valid pointer here is completely wrong. Unless I'm missing something, taking a struct page anywhere in the RMP helpers is at best sketchy and at worst broken in and of itself. IMO, the RMP code should always take a raw PFN and do the necessary checks before assuming anything about the PFN. At a glance, the only case that needs additional checks is the page_to_virt() logic in rmpupdate().
arch/x86/kvm/svm/sev.c struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu) · line 3227
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+if (unlikely (!e)) +return max_level; + +return min_t (uint32_t, level, max_level);
As the APM is currently worded, this is wrong, and the whole "tdp_max_page_level" name is wrong. As noted above, the Page-Size bullet points states that 2mb/1gb pages in the NPT _must_ have RMP.page_size=1, and 4kb pages in the NPT _must_ have RMP.page_size=0. That means that the RMP adjustment is not a constraint, it's an exact requirement. Specifically, if the RMP is a 2mb page then KVM must install a 2mb (or 1gb) page. Maybe it works because KVM will PSMASH the RMP after installing a bogus 4kb NPT and taking an RMP violation, but that's a very convoluted and sub-optimal solution.
That other obvious bug is that this doesn't play nice with 1gb pages. A 2mb RMP entry should _not_ force KVM to use a 2mb page instead of a 1gb page.
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+}
Re: [PATCH Part2 RFC v4 27/40] KVM: X86: Add kvm_x86_ops to get the max page level for the TDP
Quoted 31 lines · Sean Christopherson
Quoted 30 lines · Brijesh Singh
When running an SEV-SNP VM, the sPA used to index the RMP entry is obtained through the TDP translation (
gva->gpa->spa). The TDP page level is checked against the page level programmed in the RMP entry. If the page level does not match, then it will cause a nested page fault with the RMP bit set to indicate the RMP violation.To keep the TDP and RMP page level's in sync, the KVM fault handle
kvm_handle_page_fault()will callget_tdp_max_page_level()to get the maximum allowed page level so that it can limit the TDP level.In the case of SEV-SNP guest, the
get_tdp_max_page_level()will consult the RMP table to compute the maximum allowed page level for a given GPA.Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/mmu/mmu.c | 6 ++++-- arch/x86/kvm/svm/sev.c | 20 ++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 1 + arch/x86/kvm/svm/svm.h | 1 + arch/x86/kvm/vmx/vmx.c | 8 ++++++++ 6 files changed, 35 insertions(+), 2 deletions(-)arch/x86/include/asm/kvm_host.h +0
-0@@ -1384,6 +1384,7 @@ struct kvm_x86_ops {
Quoted 7 lines
arch/x86/include/asm/kvm_host.h struct kvm_x86_ops { · line 1387
Quoted 3 lines
arch/x86/include/asm/kvm_host.h +1
-0void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector);void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu); +int (*get_tdp_max_page_level)(struct kvm_vcpu *vcpu,gpa_t gpa,int max_level);This is a poor name. The constraint comes from the RMP, not TDP, and technically speaking applies to all forms of paging. It just happens to be relevant only to TDP because NPT is required for SNP. And KVM already incorporates the max TDP level in
kvm_configure_mmu().
Noted.
Quoted 4 lines
Regarding the params, I'd much prefer to have this take "struct kvm *kvm" instead of the vCPU. It obviously doesn't change the functionality in any way, but I'd like it to be clear to readers that the adjustment is tied to the VM, not the vCPU.
Noted.
Quoted 2 lines
I think I'd also vote to drop @max_level and make this a pure constraint input as opposed to an adjuster.
Noted.
Quoted 4 lines
Another option would be to drop the
kvm_x86_opshooks entirely and callsnp_lookup_page_in_rmptable()directly from MMU code. That would require tracking that a VM is SNP-enabled in arch code, but I'm pretty sure info has already bled into common KVM in one form or another.
I would prefer this as it eliminates some of the other unnecessary call sites. Unfortunately, currently there is no generic way to know if its an SEV guest (outside the svm/*). So far there was no need as such but with SNP having such information would help. Should we extend the 'struct kvm' to include a new field that can be used to determine the guest type. Something like
enum {
GUEST_TYPE_SEV,
GUEST_TYPE_SEV_ES,
GUEST_TYPE_SEV_SNP,
};
struct kvm {
...
u64 enc_type;
};
bool kvm_guest_enc_type(struct kvm *kvm, enum type); {
return !!kvm->enc_type & type;
}
The mmu.c can then call kvm_guest_enc_type() to check if its SNP guest and use the SNP lookup directly to determine the pagesize.
Quoted 14 lines
arch/x86/kvm/mmu/mmu.c static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, · line 3784
Quoted 13 lines
arch/x86/include/asm/kvm_host.h +0
-0};struct kvm_x86_nested_ops {arch/x86/kvm/mmu/mmu.c +1
-0@@ -3781,11 +3781,13 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,static int nonpaging_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,bool prefault) { +int max_level = kvm_x86_ops.get_tdp_max_page_level (vcpu, gpa,PG_LEVEL_2M );This is completely bogus,
nonpaging_page_fault()is used iff TDP is disabled.
Ah, I totally missed it.
Quoted 22 lines
Quoted 11 lines
arch/x86/kvm/mmu/mmu.c +2
-1+pgprintk ("%s: gva %lx error %x\n" , __func__, gpa, error_code);/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */ return direct_page_fault (vcpu, gpa &PAGE_MASK , error_code, prefault, -PG_LEVEL_2M , false); + max_level, false); } int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,arch/x86/kvm/mmu/mmu.c int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, · line 3831
Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +1
-1@@ -3826,7 +3828,7 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, {int max_level; - for (max_level = KVM_MAX_HUGEPAGE_LEVEL; + for (max_level = kvm_x86_ops.get_tdp_max_page_level(vcpu, gpa, KVM_MAX_HUGEPAGE_LEVEL);This is unnecessary. The max mapping level is computed by factoring in all constraints, of which there are many. In this case, KVM is consulting the guest's MTRR configuration to avoid creating a page that spans different memtypes (because the guest MTRRs are effectively represented in the TDP PTE). SNP's RMP constraints have no relevance to the MTRR constraint, or any other constraint for that matter.
Quoted 3 lines
TL;DR: the RMP constraint belong in
kvm_mmu_max_mapping_level()and nowhere else. I would go so far as to argue it belong inhost_pfn_mapping_level(), after the call tolookup_address_in_mm().
I agree with you; One of the case which I was trying to cover is what if we do a pre-fault and while generating the prefault we can tell the handler our max page level; The example is: "Guest issues a page state transition request to add the page as 2mb". We execute the below steps to fulfill the request
* create a prefault with a max_level set to 2mb.
* the fault handler may find that it cannot use the large page in the npt, and it may default to 4k
* read the page-size from the npt; use the npt pagesize in the rmptable instead of the guest requested page-size.
We keep the NPT and RMP in sync after the page state change is completed and avoid any extra RMP fault due to the size mismatch etc.
Quoted 52 lines
Quoted 9 lines
arch/x86/kvm/mmu/mmu.c +0
-0max_level >PG_LEVEL_4K ; max_level--) {int page_num =KVM_PAGES_PER_HPAGE (max_level);arch/x86/kvm/svm/sev.c +0
-0@@ -3206,3 +3206,23 @@ struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu)arch/x86/kvm/svm/sev.c struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu) · line 3216
Quoted 10 lines
arch/x86/kvm/svm/sev.c +8
-0return pfn_to_page (pfn); } + +int sev_get_tdp_max_page_level (struct kvm_vcpu *vcpu,gpa_t gpa,int max_level) +{ +struct rmpentry *e; +kvm_pfn_t pfn; +int level; + +if (!sev_snp_guest (vcpu->kvm))I can't tell if this check is correct. Per the APM:
When SEV-SNP is enabled globally, the processor places restrictions on all memory accesses based on the contents of the RMP, whether the accesses are performed by the hypervisor, a legacy guest VM, a non-SNP guest VM or an SNP-active guest VM. The processor may perform one or more of the following checks depending on the context of the access:
...
Page-Size: Checks that the following conditions are met:
- If the nested page table indicates a 2MB or 1GB page size, thePage_Sizefield of the RMP entry of the target page is 1.
- If the nested page table indicates a 4KB page size, thePage_Sizefield of the RMP entry of the target page is 0.The Page-Size bullet does not have any qualifiers about the NPT checks applying only to SNP guests. The Hypervisor-Owned bullet implies that unassigned pages do not need to have identical sizes, but it's not clear whether or not so called "Hypervisor-Owned" pages override the nested page tables.
Table 15.36 is similarly vague:
Assigned Flag indicating that the system physical page is assigned to a guest or to the AMD-SP.
0: Owned by the hypervisor
1: Owned by a guest or the AMD-SPMy assumption is that all of the "guest owned" stuff really means "SNP guest owned", e.g. section 15.36.5 says "The hypervisor manages the SEV-SNP security attributes of pages assigned to SNP-active guests by altering the RMP entries of those pages", but that's not at all clear throughout most of the RMP documentation.
Quoted 4 lines
Regardless of the actual behavior, the APM needs serious cleanup on the aforementioned sections. E.g. as written, the "processor may perform one or more of the following checks depending on the context of the access" verbiage basically gives the CPU carte blanche to do whatever the hell it wants.
I'll raise your concern to the documentation folks so that they clarify that the page-size check is applicable to the SNP active guests only.
Quoted 7 lines
arch/x86/kvm/svm/sev.c struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu) · line 3223
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+return max_level; + + pfn =gfn_to_pfn (vcpu->kvm,gpa_to_gfn (gpa)); +if (is_error_noslot_pfn (pfn)) +return max_level; + + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level);
Quoted 8 lines
Assuming pfn is backed by struct page is broken, at least given the existing call sites.. It might hold true that only struct page pfns are covered by the RMP, but assuming
pfn_to_page()will return a valid pointer here is completely wrong. Unless I'm missing something, taking a struct page anywhere in the RMP helpers is at best sketchy and at worst broken in and of itself. IMO, the RMP code should always take a raw PFN and do the necessary checks before assuming anything about the PFN. At a glance, the only case that needs additional checks is thepage_to_virt()logic inrmpupdate().
I agree. Dave also hinted the similar feedback. In next version of the patch I will stick to use the pfn and then SNP lookup with do the required checking.
Quoted 4 lines
arch/x86/kvm/svm/sev.c struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu) · line 3227
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+if (unlikely (!e)) +return max_level; + +return min_t (uint32_t, level, max_level);
Quoted 8 lines
As the APM is currently worded, this is wrong, and the whole "
tdp_max_page_level" name is wrong. As noted above, the Page-Size bullet points states that 2mb/1gb pages in the NPT _must_ have RMP.page_size=1, and 4kb pages in the NPT _must_ have RMP.page_size=0. That means that the RMP adjustment is not a constraint, it's an exact requirement. Specifically, if the RMP is a 2mb page then KVM must install a 2mb (or 1gb) page. Maybe it works because KVM will PSMASH the RMP after installing a bogus 4kb NPT and taking an RMP violation, but that's a very convoluted and sub-optimal solution.
This is why I was passing the preferred max_level in the pre-fault handle then later query the npt level; use the npt level in the RMP to make sure they are in sync.
There is yet another reason why we can't avoid the PSMASH after doing everything to ensure that NPT and RMP are in sync. e.g if NPT and RMP are programmed with 2mb size but the guest tries to PVALIDATE the page as a 4k. In that case, we will see #NPF with page size mismatch and have to perform psmash.
Quoted 5 lines
That other obvious bug is that this doesn't play nice with 1gb pages. A 2mb RMP entry should _not_ force KVM to use a 2mb page instead of a 1gb page.
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+}
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 27/40] KVM: X86: Add kvm_x86_ops to get the max page level for the TDP
Quoted 32 lines · Brijesh Singh
Quoted 5 lines · Sean Christopherson
On Wed, Jul 07, 2021, Brijesh Singh wrote:
Another option would be to drop thekvm_x86_opshooks entirely and callsnp_lookup_page_in_rmptable()directly from MMU code. That would require tracking that a VM is SNP-enabled in arch code, but I'm pretty sure info has already bled into common KVM in one form or another.I would prefer this as it eliminates some of the other unnecessary call sites. Unfortunately, currently there is no generic way to know if its an SEV guest (outside the svm/*). So far there was no need as such but with SNP having such information would help. Should we extend the 'struct kvm' to include a new field that can be used to determine the guest type. Something like
enum {
GUEST_TYPE_SEV,
GUEST_TYPE_SEV_ES,
GUEST_TYPE_SEV_SNP,};
struct kvm {
...
u64
enc_type;};
Quoted 8 lines
bool
kvm_guest_enc_type(struct kvm *kvm, enum type); {return !!kvm->enc_type & type;
}
The
mmu.ccan then callkvm_guest_enc_type()to check if its SNP guest and use the SNP lookup directly to determine the pagesize.
The other option is to use vm_type, which TDX is already planning on leveraging. Paolo raised the question of whether or not the TDX type could be reused for SNP. We should definitely sort that out before merging either series. I'm personally in favor of separating TDX and SNP, it seems inevitable that common code will want to differentiate between the two.
Quoted 13 lines
Quoted 8 lines
As the APM is currently worded, this is wrong, and the whole "
tdp_max_page_level" name is wrong. As noted above, the Page-Size bullet points states that 2mb/1gb pages in the NPT _must_ have RMP.page_size=1, and 4kb pages in the NPT _must_ have RMP.page_size=0. That means that the RMP adjustment is not a constraint, it's an exact requirement. Specifically, if the RMP is a 2mb page then KVM must install a 2mb (or 1gb) page. Maybe it works because KVM will PSMASH the RMP after installing a bogus 4kb NPT and taking an RMP violation, but that's a very convoluted and sub-optimal solution.This is why I was passing the preferred
max_levelin the pre-fault handle then later query the npt level; use the npt level in the RMP to make sure they are in sync.
Quoted 5 lines
There is yet another reason why we can't avoid the PSMASH after doing everything to ensure that NPT and RMP are in sync. e.g if NPT and RMP are programmed with 2mb size but the guest tries to PVALIDATE the page as a 4k. In that case, we will see #NPF with page size mismatch and have to perform psmash.
Boo, there's no way to communicate to the guest that it's doing PVALIDATE wrong is there?
Re: [PATCH Part2 RFC v4 27/40] KVM: X86: Add kvm_x86_ops to get the max page level for the TDP
On 7/20/21 2:38 PM, Sean Christopherson wrote:
...
Quoted 6 lines
The other option is to use
vm_type, which TDX is already planning on leveraging. Paolo raised the question of whether or not the TDX type could be reused for SNP. We should definitely sort that out before merging either series. I'm personally in favor of separating TDX and SNP, it seems inevitable that common code will want to differentiate between the two.
Yes, I did saw that and it seems much better.
...
Quoted 10 lines
Quoted 6 lines
There is yet another reason why we can't avoid the PSMASH after doing everything to ensure that NPT and RMP are in sync. e.g if NPT and RMP are programmed with 2mb size but the guest tries to PVALIDATE the page as a 4k. In that case, we will see #NPF with page size mismatch and have to perform psmash.
Boo, there's no way to communicate to the guest that it's doing PVALIDATE wrong is there?
if the guest chooses smaller page-size then we don't have any means to notify the guest; the hardware will cause an #NPF and its up to the hypervisor to resolve the fault.
However, if the guest attempts to validate with the larger page-level (e.g guest using 2mb and RMP entry was 4k) then PVALIDATE will return SIZEMISMATCH error to the guest.
thanks
RFC PATCH v4 28/40 KVM: X86: Introduce kvm_mmu_map_tdp_page() for use by SEV
In reply to Brijesh SinghIntroduce a helper to directly fault-in a TDP page without going through the full page fault path. This allows SEV-SNP to build the netsted page table while handling the page state change VMGEXIT. A guest may issue a page state change VMGEXIT before accessing the page. Create a fault so that VMGEXIT handler can get the TDP page level and keep the TDP and RMP page level in sync.
--- arch/x86/kvm/mmu.h | 2 ++ arch/x86/kvm/mmu/mmu.c | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+)
arch/x86/kvm/mmu.h +2 -0
@@ -114,6 +114,8 @@ static inline void kvm_mmu_load_pgd(struct kvm_vcpu *vcpu)int kvm_tdp_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,bool prefault); +int kvm_mmu_map_tdp_page (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,int max_level); +static inline int kvm_mmu_do_page_fault (struct kvm_vcpu *vcpu,gpa_t cr2_or_gpa,u32 err,bool prefault) {
arch/x86/kvm/mmu/mmu.c +20 -0
@@ -3842,6 +3842,26 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, max_level, true); } +int kvm_mmu_map_tdp_page (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,int max_level) +{ +int r; + +/* +* Loop on the page fault path to handle the case where an mmu_notifier +* invalidation triggers RET_PF_RETRY. In the normal page fault path, +* KVM needs to resume the guest in case the invalidation changed any +* of the page fault properties, i.e. the gpa or error code. For this +* path, the gpa and error code are fixed by the caller, and the caller +* expects failure if and only if the page fault can't be fixed. +*/ +do { + r =direct_page_fault (vcpu, gpa, error_code, false, max_level, true); + }while (r ==RET_PF_RETRY ); + +return r; +} +EXPORT_SYMBOL_GPL (kvm_mmu_map_tdp_page); +static void nonpaging_init_context (struct kvm_vcpu *vcpu,struct kvm_mmu *context) {
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 28/40] KVM: X86: Introduce kvm_mmu_map_tdp_page() for use by SEV
Quoted 7 lines · Brijesh Singh
arch/x86/kvm/mmu/mmu.c +7
-0+int kvm_mmu_map_tdp_page (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,int max_level) +{ +int r; + +/* +* Loop on the page fault path to handle the case where an mmu_notifier +* invalidation triggers RET_PF_RETRY. In the normal page fault path,
arch/x86/kvm/mmu/mmu.c int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, · line 3861
Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10
-0+* KVM needs to resume the guest in case the invalidation changed any +* of the page fault properties, i.e. the gpa or error code. For this +* path, the gpa and error code are fixed by the caller, and the caller +* expects failure if and only if the page fault can't be fixed. +*/ +do { + r =direct_page_fault (vcpu, gpa, error_code, false, max_level, true); + }while (r ==RET_PF_RETRY ); + +return r;
This implementation is completely broken, which in turn means that the page state change code is not well tested. The mess is likely masked to some extent because the call is bookendeda by calls to kvm_mmu_get_tdp_walk(), i.e. most of the time it's not called, and when it is called, the bugs are hidden by the second walk detecting that the mapping was not installed.
1. direct_page_fault() does not return a pfn, it returns the action that should be taken by the caller.
2. The while() can be optimized to bail on no_slot PFNs.
3. mmu_topup_memory_caches() needs to be called here, otherwise @pfn will be uninitialized. The alternative would be to set @pfn when that fails in direct_page_fault().
4. The 'int' return value is wrong, it needs to be kvm_pfn_t.
A correct implementation can be found in the TDX series, the easiest thing would be to suck in those patches.
https://lore.kernel.org/kvm/ceffc7ef0746c6064330ef5c30bc0bb5994a1928.1625186503.git.isaku.yamahata@intel.com/
https://lore.kernel.org/kvm/a7e7602375e1f63b32eda19cb8011f11794ebe28.1625186503.git.isaku.yamahata@intel.com/
Quoted 9 lines
arch/x86/kvm/mmu/mmu.c +3
-0+} +EXPORT_SYMBOL_GPL (kvm_mmu_map_tdp_page); +static void nonpaging_init_context (struct kvm_vcpu *vcpu,struct kvm_mmu *context) {Signature · 1 line
2.17.1
RFC PATCH v4 29/40 KVM: X86: Introduce kvm_mmu_get_tdp_walk() for SEV-SNP use
In reply to Brijesh SinghThe SEV-SNP VMs may call the page state change VMGEXIT to add the GPA as private or shared in the RMP table. The page state change VMGEXIT will contain the RMP page level to be used in the RMP entry. If the page level between the TDP and RMP does not match then, it will result in nested-page-fault (RMP violation).
The SEV-SNP VMGEXIT handler will use the kvm_mmu_get_tdp_walk() to get the current page-level in the TDP for the given GPA and calculate a workable page level. If a GPA is mapped as a 4K-page in the TDP, but the guest requested to add the GPA as a 2M in the RMP entry then the 2M request will be broken into 4K-pages to keep the RMP and TDP page-levels in sync.
--- arch/x86/kvm/mmu.h | 1 + arch/x86/kvm/mmu/mmu.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+)
arch/x86/kvm/mmu.h +1 -0
@@ -115,6 +115,7 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, bool prefault);int kvm_mmu_map_tdp_page (struct kvm_vcpu *vcpu,gpa_t gpa,u32 error_code,int max_level); +bool kvm_mmu_get_tdp_walk (struct kvm_vcpu *vcpu,gpa_t gpa,kvm_pfn_t *pfn,int *level);static inline int kvm_mmu_do_page_fault (struct kvm_vcpu *vcpu,gpa_t cr2_or_gpa,u32 err,bool prefault)
arch/x86/kvm/mmu/mmu.c +29 -0
@@ -3862,6 +3862,35 @@ int kvm_mmu_map_tdp_page(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code, int m }EXPORT_SYMBOL_GPL (kvm_mmu_map_tdp_page); +bool kvm_mmu_get_tdp_walk (struct kvm_vcpu *vcpu,gpa_t gpa,kvm_pfn_t *pfn,int *level) +{ +u64 sptes[PT64_ROOT_MAX_LEVEL +1 ]; +int leaf, root; + +if (is_tdp_mmu_root (vcpu->kvm, vcpu->arch.mmu->root_hpa)) + leaf =kvm_tdp_mmu_get_walk (vcpu, gpa, sptes, &root); +else + leaf =get_walk (vcpu, gpa, sptes, &root); + +if (unlikely (leaf <0 )) +return false; + +/* Check if the leaf SPTE is present */ +if (!is_shadow_present_pte (sptes[leaf])) +return false; + + *pfn =spte_to_pfn (sptes[leaf]); +if (leaf >PG_LEVEL_4K ) { +u64 page_mask =KVM_PAGES_PER_HPAGE (leaf) -KVM_PAGES_PER_HPAGE (leaf -1 ); + *pfn |= (gpa_to_gfn (gpa) & page_mask); + } + + *level = leaf; + +return true; +} +EXPORT_SYMBOL_GPL (kvm_mmu_get_tdp_walk); +static void nonpaging_init_context (struct kvm_vcpu *vcpu,struct kvm_mmu *context) {
Signature · 1 line
2.17.1
RFC PATCH v4 30/40 KVM: X86: Define new RMP check related #NPF error bits
In reply to Brijesh SinghWhen SEV-SNP is enabled globally, the hardware places restrictions on all memory accesses based on the RMP entry, whether the hyperviso or a VM, performs the accesses. When hardware encounters an RMP access violation during a guest access, it will cause a #VMEXIT(NPF).
See APM2 section 16.36.10 for more details.
--- arch/x86/include/asm/kvm_host.h | 8 ++++++++ 1 file changed, 8 insertions(+)
arch/x86/include/asm/kvm_host.h +8 -0
@@ -239,8 +239,12 @@ enum x86_intercept_stage;#define PFERR_FETCH_BIT 4#define PFERR_PK_BIT 5#define PFERR_SGX_BIT 15 +#define PFERR_GUEST_RMP_BIT 31#define PFERR_GUEST_FINAL_BIT 32#define PFERR_GUEST_PAGE_BIT 33 +#define PFERR_GUEST_ENC_BIT 34 +#define PFERR_GUEST_SIZEM_BIT 35 +#define PFERR_GUEST_VMPL_BIT 36#define PFERR_PRESENT_MASK (1U << PFERR_PRESENT_BIT)#define PFERR_WRITE_MASK (1U << PFERR_WRITE_BIT)
@@ -251,6 +255,10 @@ enum x86_intercept_stage;#define PFERR_SGX_MASK (1U << PFERR_SGX_BIT)#define PFERR_GUEST_FINAL_MASK (1ULL << PFERR_GUEST_FINAL_BIT)#define PFERR_GUEST_PAGE_MASK (1ULL << PFERR_GUEST_PAGE_BIT) +#define PFERR_GUEST_RMP_MASK (1ULL << PFERR_GUEST_RMP_BIT) +#define PFERR_GUEST_ENC_MASK (1ULL << PFERR_GUEST_ENC_BIT) +#define PFERR_GUEST_SIZEM_MASK (1ULL << PFERR_GUEST_SIZEM_BIT) +#define PFERR_GUEST_VMPL_MASK (1ULL << PFERR_GUEST_VMPL_BIT)#define PFERR_NESTED_GUEST_PAGE (PFERR_GUEST_PAGE_MASK | \ PFERR_WRITE_MASK | \
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 30/40] KVM: X86: Define new RMP check related #NPF error bits
Nit, please use "KVM: x86:" for the shortlogs. And ubernit, the "new" part is redundant and/or misleading, e.g. implies that more error code bits are being added to existing SNP/RMP checks. E.g.
KVM: x86: Define RMP page fault error code bits for #NPT
Quoted 2 lines · Brijesh Singh
When SEV-SNP is enabled globally, the hardware places restrictions on all memory accesses based on the RMP entry, whether the hyperviso or a VM,
Another typo.
Quoted 2 lines
performs the accesses. When hardware encounters an RMP access violation during a guest access, it will cause a #VMEXIT(NPF).
Re: [PATCH Part2 RFC v4 30/40] KVM: X86: Define new RMP check related #NPF error bits
Quoted 5 lines · Sean Christopherson
Nit, please use "KVM: x86:" for the shortlogs. And ubernit, the "new" part is redundant and/or misleading, e.g. implies that more error code bits are being added to existing SNP/RMP checks. E.g.
KVM: x86: Define RMP page fault error code bits for #NPT
Noted.
Quoted 4 lines · Brijesh Singh
Quoted 2 lines
When SEV-SNP is enabled globally, the hardware places restrictions on all memory accesses based on the RMP entry, whether the hyperviso or a VM,
Another typo.
Noted. thanks
RFC PATCH v4 31/40 KVM: X86: update page-fault trace to log the 64-bit error code
In reply to Brijesh SinghThe page-fault error code is a 64-bit value, but the trace prints only the lower 32-bits. Some of the SEV-SNP RMP fault error codes are available in the upper 32-bits.
--- arch/x86/kvm/trace.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
arch/x86/kvm/trace.h +3 -3
@@ -365,12 +365,12 @@ TRACE_EVENT(kvm_inj_exception,* Tracepoint for page fault. */ TRACE_EVENT(kvm_page_fault, - TP_PROTO(unsigned long fault_address, unsigned int error_code), + TP_PROTO(unsigned long fault_address, u64 error_code), TP_ARGS(fault_address, error_code), TP_STRUCT__entry( __field( unsigned long, fault_address ) - __field( unsigned int, error_code ) + __field( u64, error_code ) ), TP_fast_assign(
@@ -378,7 +378,7 @@ TRACE_EVENT(kvm_page_fault, __entry->error_code = error_code; ), -TP_printk ("address %lx error_code %x" , +TP_printk ("address %lx error_code %llx" , __entry->fault_address, __entry->error_code) );
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 31/40] KVM: X86: update page-fault trace to log the 64-bit error code
Quoted 1 line · Brijesh Singh
The page-fault error code is a 64-bit value, but the trace prints only
It's worth clarifying that #NPT has a 64-bit error code, and so KVM also passes around a 64-bit PFEC. E.g. the above statement is wrong for legacy #PF.
Quoted 2 lines
the lower 32-bits. Some of the SEV-SNP RMP fault error codes are available in the upper 32-bits.
Can you send this separately with Cc: stable@? And I guess tweak the changelog to replace "SEV-SNP RMP" with a reference to e.g. PFERR_GUEST_FINAL_MASK. KVM already has error codes that can set the upper bits.
Re: [PATCH Part2 RFC v4 31/40] KVM: X86: update page-fault trace to log the 64-bit error code
Quoted 10 lines · Sean Christopherson
Quoted 1 line · Brijesh Singh
The page-fault error code is a 64-bit value, but the trace prints only
It's worth clarifying that #NPT has a 64-bit error code, and so KVM also passes around a 64-bit PFEC. E.g. the above statement is wrong for legacy #PF.
Quoted 2 lines
the lower 32-bits. Some of the SEV-SNP RMP fault error codes are available in the upper 32-bits.
Can you send this separately with Cc: stable@? And I guess tweak the changelog to replace "SEV-SNP RMP" with a reference to e.g.
PFERR_GUEST_FINAL_MASK. KVM already has error codes that can set the upper bits.
Will do.
RFC PATCH v4 32/40 KVM: SVM: Add support to handle GHCB GPA register VMGEXIT
In reply to Brijesh SinghSEV-SNP guests are required to perform a GHCB GPA registration (see section 2.5.2 in GHCB specification). Before using a GHCB GPA for a vCPU the first time, a guest must register the vCPU GHCB GPA. If hypervisor can work with the guest requested GPA then it must respond back with the same GPA otherwise return -1.
On VMEXIT, Verify that GHCB GPA matches with the registered value. If a mismatch is detected then abort the guest.
--- arch/x86/include/asm/sev-common.h | 2 ++ arch/x86/kvm/svm/sev.c | 25 +++++++++++++++++++++++++ arch/x86/kvm/svm/svm.h | 7 +++++++ 3 files changed, 34 insertions(+)
arch/x86/include/asm/sev-common.h +2 -0
@@ -60,8 +60,10 @@ GHCB_MSR_GPA_REG_REQ)#define GHCB_MSR_GPA_REG_RESP 0x013 +#define GHCB_MSR_GPA_REG_ERROR GENMASK_ULL(51, 0)#define GHCB_MSR_GPA_REG_RESP_VAL (v) ((v) >> GHCB_MSR_GPA_REG_VALUE_POS) +/* SNP Page State Change */ #define GHCB_MSR_PSC_REQ 0x014#define SNP_PAGE_STATE_PRIVATE 1
arch/x86/kvm/svm/sev.c +25 -0
@@ -2922,6 +2922,25 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_GPA_REG_REQ : { +kvm_pfn_t pfn; +u64 gfn; + + gfn =get_ghcb_msr_bits (svm,GHCB_MSR_GPA_REG_GFN_MASK , +GHCB_MSR_GPA_REG_VALUE_POS ); + + pfn =kvm_vcpu_gfn_to_pfn (vcpu, gfn); +if (is_error_noslot_pfn (pfn)) + gfn =GHCB_MSR_GPA_REG_ERROR ; +else + svm->ghcb_registered_gpa =gfn_to_gpa (gfn); + +set_ghcb_msr_bits (svm, gfn,GHCB_MSR_GPA_REG_GFN_MASK , +GHCB_MSR_GPA_REG_VALUE_POS ); +set_ghcb_msr_bits (svm,GHCB_MSR_GPA_REG_RESP ,GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS ); +break ; + }case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;
@@ -2970,6 +2989,12 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)return -EINVAL ; } +/* SEV-SNP guest requires that the GHCB GPA must be registered */ +if (sev_snp_guest (svm->vcpu.kvm) && !ghcb_gpa_is_registered (svm, ghcb_gpa)) { +vcpu_unimpl (&svm->vcpu,"vmgexit: GHCB GPA [%#llx] is not registered.\n" , ghcb_gpa); +return -EINVAL ; + } + svm->ghcb = svm->ghcb_map.hva; ghcb = svm->ghcb_map.hva;
arch/x86/kvm/svm/svm.h +7 -0
@@ -185,6 +185,8 @@ struct vcpu_svm {bool ghcb_sa_free;bool guest_state_loaded; + +u64 ghcb_registered_gpa; };struct svm_cpu_data {
@@ -245,6 +247,11 @@ static inline bool sev_snp_guest(struct kvm *kvm)#endif } +static inline bool ghcb_gpa_is_registered (struct vcpu_svm *svm,u64 val) +{ +return svm->ghcb_registered_gpa == val; +} +static inline void vmcb_mark_all_dirty (struct vmcb *vmcb) { vmcb->control.clean =0 ;
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 32/40] KVM: SVM: Add support to handle GHCB GPA register VMGEXIT
Quoted 2 lines · Brijesh Singh
SEV-SNP guests are required to perform a GHCB GPA registration (see section 2.5.2 in GHCB specification). Before using a GHCB GPA for a vCPU
It's section 2.3.2 in version 2.0 of the spec.
Quoted 34 lines
the first time, a guest must register the vCPU GHCB GPA. If hypervisor can work with the guest requested GPA then it must respond back with the same GPA otherwise return -1.
On VMEXIT, Verify that GHCB GPA matches with the registered value. If a mismatch is detected then abort the guest.
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/sev-common.h | 2 ++ arch/x86/kvm/svm/sev.c | 25 +++++++++++++++++++++++++ arch/x86/kvm/svm/svm.h | 7 +++++++ 3 files changed, 34 insertions(+)arch/x86/include/asm/sev-common.h +2
-0@@ -60,8 +60,10 @@ GHCB_MSR_GPA_REG_REQ)#define GHCB_MSR_GPA_REG_RESP 0x013 +#define GHCB_MSR_GPA_REG_ERROR GENMASK_ULL(51, 0)#define GHCB_MSR_GPA_REG_RESP_VAL (v) ((v) >> GHCB_MSR_GPA_REG_VALUE_POS) +/* SNP Page State Change */ #define GHCB_MSR_PSC_REQ 0x014#define SNP_PAGE_STATE_PRIVATE 1arch/x86/kvm/svm/sev.c +0
-0
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2925
Quoted 4 lines
arch/x86/kvm/svm/sev.c +1
-0@@ -2922,6 +2922,25 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_GPA_REG_REQ : {
Shouldn't KVM also support "Get preferred GHCB GPA", at least to the point where it responds with "No preferred GPA". AFAICT, this series doesn't cover that, i.e. KVM will kill a guest that requests the VMM's preferred GPA.
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2930
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+kvm_pfn_t pfn; +u64 gfn; + + gfn =get_ghcb_msr_bits (svm,GHCB_MSR_GPA_REG_GFN_MASK , +GHCB_MSR_GPA_REG_VALUE_POS );
This is confusing, the MASK/POS reference both GPA and GFN.
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2933
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+ + pfn =kvm_vcpu_gfn_to_pfn (vcpu, gfn); +if (is_error_noslot_pfn (pfn))
Checking the mapped PFN at this time isn't wrong, but it's also not complete, e.g. nothing prevents userspace from changing the gpa->hva mapping after the initial registration. Not that that's likely to happen (or not break the guest), but my point is that random checks on the backing PFN really have no meaning in KVM unless KVM can guarantee that the PFN is stable for the duration of its use.
And conversely, the GHCB doesn't require the GHCB to be shared until the first use. E.g. arguably KVM should fully check the usability of the GPA, but the GHCB spec disallows that. And I honestly can't see why SNP is special with respect to the GHCB. ES guests will explode just as badly if the GPA points at garbage.
I guess I'm not against the check, but it feels extremely arbitrary.
Quoted 14 lines
arch/x86/kvm/svm/sev.c +10
-0+ gfn =GHCB_MSR_GPA_REG_ERROR ; + else + svm->ghcb_registered_gpa = gfn_to_gpa(gfn); + +set_ghcb_msr_bits (svm, gfn,GHCB_MSR_GPA_REG_GFN_MASK , +GHCB_MSR_GPA_REG_VALUE_POS ); +set_ghcb_msr_bits (svm,GHCB_MSR_GPA_REG_RESP ,GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS ); +break ; + }case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;
arch/x86/kvm/svm/sev.c int sev_handle_vmgexit(struct kvm_vcpu *vcpu) · line 2994
Quoted 6 lines
arch/x86/kvm/svm/sev.c +3
-0@@ -2970,6 +2989,12 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)return -EINVAL ; } +/* SEV-SNP guest requires that the GHCB GPA must be registered */ +if (sev_snp_guest (svm->vcpu.kvm) && !ghcb_gpa_is_registered (svm, ghcb_gpa)) { +vcpu_unimpl (&svm->vcpu,"vmgexit: GHCB GPA [%#llx] is not registered.\n" , ghcb_gpa);
I saw this a few other place. vcpu_unimpl() is not the right API. KVM supports the guest request, the problem is that the GHCB spec _requires_ KVM to terminate the guest in this case.
Quoted 34 lines
arch/x86/kvm/svm/sev.c +3
-0+return -EINVAL ; + } + svm->ghcb = svm->ghcb_map.hva; ghcb = svm->ghcb_map.hva;arch/x86/kvm/svm/svm.h +7
-0@@ -185,6 +185,8 @@ struct vcpu_svm {bool ghcb_sa_free;bool guest_state_loaded; + +u64 ghcb_registered_gpa; };struct svm_cpu_data {@@ -245,6 +247,11 @@ static inline bool sev_snp_guest(struct kvm *kvm)#endif } +static inline bool ghcb_gpa_is_registered (struct vcpu_svm *svm,u64 val) +{ +return svm->ghcb_registered_gpa == val; +} +static inline void vmcb_mark_all_dirty (struct vmcb *vmcb) { vmcb->control.clean =0 ;Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 32/40] KVM: SVM: Add support to handle GHCB GPA register VMGEXIT
Quoted 4 lines · Sean Christopherson
Quoted 2 lines · Brijesh Singh
SEV-SNP guests are required to perform a GHCB GPA registration (see section 2.5.2 in GHCB specification). Before using a GHCB GPA for a vCPU
It's section 2.3.2 in version 2.0 of the spec.
Ah, I will fix it.
Quoted 26 lines
Quoted 26 lines
the first time, a guest must register the vCPU GHCB GPA. If hypervisor can work with the guest requested GPA then it must respond back with the same GPA otherwise return -1.
On VMEXIT, Verify that GHCB GPA matches with the registered value. If a mismatch is detected then abort the guest.
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/sev-common.h | 2 ++ arch/x86/kvm/svm/sev.c | 25 +++++++++++++++++++++++++ arch/x86/kvm/svm/svm.h | 7 +++++++ 3 files changed, 34 insertions(+)arch/x86/include/asm/sev-common.h +1
-0@@ -60,8 +60,10 @@ GHCB_MSR_GPA_REG_REQ)#define GHCB_MSR_GPA_REG_RESP 0x013 +#define GHCB_MSR_GPA_REG_ERROR GENMASK_ULL(51, 0)#define GHCB_MSR_GPA_REG_RESP_VAL (v) ((v) >> GHCB_MSR_GPA_REG_VALUE_POS)
Quoted 16 lines
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2925
Quoted 13 lines
arch/x86/include/asm/sev-common.h +1
-0+/* SNP Page State Change */ #define GHCB_MSR_PSC_REQ 0x014#define SNP_PAGE_STATE_PRIVATE 1arch/x86/kvm/svm/sev.c +1
-0@@ -2922,6 +2922,25 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_GPA_REG_REQ : {Shouldn't KVM also support "Get preferred GHCB GPA", at least to the point where it responds with "No preferred GPA". AFAICT, this series doesn't cover that, i.e. KVM will kill a guest that requests the VMM's preferred GPA.
Good point, for the completeness we should add the preferred GPA MSR and return appropriate response code to cover the cases where non Linux guest may use this vmgexit to determine the GHCB GPA.
Quoted 7 lines
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2930
Quoted 6 lines
arch/x86/kvm/svm/sev.c +5
-0+kvm_pfn_t pfn; +u64 gfn; + + gfn =get_ghcb_msr_bits (svm,GHCB_MSR_GPA_REG_GFN_MASK , +GHCB_MSR_GPA_REG_VALUE_POS );This is confusing, the MASK/POS reference both GPA and GFN.
Let me see if I can improve it to avoid the naming confusion. Most of the naming recommending came during the part1 review, I will check with Boris and other to see if they are okay with new names.
Quoted 35 lines
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 2933
Quoted 4 lines
arch/x86/kvm/svm/sev.c +3
-0+ + pfn =kvm_vcpu_gfn_to_pfn (vcpu, gfn); +if (is_error_noslot_pfn (pfn))Checking the mapped PFN at this time isn't wrong, but it's also not complete, e.g. nothing prevents userspace from changing the
gpa->hvamapping after the initial registration. Not that that's likely to happen (or not break the guest), but my point is that random checks on the backing PFN really have no meaning in KVM unless KVM can guarantee that the PFN is stable for the duration of its use.And conversely, the GHCB doesn't require the GHCB to be shared until the first use. E.g. arguably KVM should fully check the usability of the GPA, but the GHCB spec disallows that. And I honestly can't see why SNP is special with respect to the GHCB. ES guests will explode just as badly if the GPA points at garbage.
I guess I'm not against the check, but it feels extremely arbitrary.
Quoted 17 lines
arch/x86/kvm/svm/sev.c +10
-0+ gfn =GHCB_MSR_GPA_REG_ERROR ; + else + svm->ghcb_registered_gpa = gfn_to_gpa(gfn); + +set_ghcb_msr_bits (svm, gfn,GHCB_MSR_GPA_REG_GFN_MASK , +GHCB_MSR_GPA_REG_VALUE_POS ); +set_ghcb_msr_bits (svm,GHCB_MSR_GPA_REG_RESP ,GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS ); +break ; + }case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;@@ -2970,6 +2989,12 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)return -EINVAL ; }
Quoted 6 lines
arch/x86/kvm/svm/sev.c int sev_handle_vmgexit(struct kvm_vcpu *vcpu) · line 2994
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+/* SEV-SNP guest requires that the GHCB GPA must be registered */ +if (sev_snp_guest (svm->vcpu.kvm) && !ghcb_gpa_is_registered (svm, ghcb_gpa)) { +vcpu_unimpl (&svm->vcpu,"vmgexit: GHCB GPA [%#llx] is not registered.\n" , ghcb_gpa);I saw this a few other place.
vcpu_unimpl()is not the right API. KVM supports the guest request, the problem is that the GHCB spec _requires_ KVM to terminate the guest in this case.
What is the preferred method to log it so that someone debugging know what went wrong.
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 32/40] KVM: SVM: Add support to handle GHCB GPA register VMGEXIT
Quoted 10 lines · Brijesh Singh
Quoted 7 lines · Sean Christopherson
arch/x86/kvm/svm/sev.c int sev_handle_vmgexit(struct kvm_vcpu *vcpu) · line 2994
Quoted 3 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +3
-0+/* SEV-SNP guest requires that the GHCB GPA must be registered */ +if (sev_snp_guest (svm->vcpu.kvm) && !ghcb_gpa_is_registered (svm, ghcb_gpa)) { +vcpu_unimpl (&svm->vcpu,"vmgexit: GHCB GPA [%#llx] is not registered.\n" , ghcb_gpa);I saw this a few other place.
vcpu_unimpl()is not the right API. KVM supports the guest request, the problem is that the GHCB spec _requires_ KVM to terminate the guest in this case.
Quoted 2 lines
What is the preferred method to log it so that someone debugging know what went wrong.
Using the kernel log is probably a bad choice in general for this error. Because this and the other GHCB GPA sanity checks can be triggered from the guest, any kernel logging needs to be ratelimited. Ratelimiting is problematic because it means some errors may not be logged; that's quite unlikely in this case, but it's less than ideal.
The other issue is that KVM can't dump the RIP because guest state is encrypted, e.g. KVM can provide the task PID, but that's it.
The best solution I can think of at the moment would be some form of KVM_EXIT_INTERNAL_ERROR, i.e. kick out to userspace with a meaningful error code and the bad GPA so that userspace can take action.
I believe Jim also has some thoughts on how to improve "logging" of guest errors, but he's on vacation for a few weeks.
RFC PATCH v4 33/40 KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
In reply to Brijesh SinghSEV-SNP VMs can ask the hypervisor to change the page state in the RMP table to be private or shared using the Page State Change MSR protocol as defined in the GHCB specification.
Before changing the page state in the RMP entry, we lookup the page in the TDP to make sure that there is a valid mapping for it. If the mapping exist then try to find a workable page level between the TDP and RMP for the page. If the page is not mapped in the TDP, then create a fault such that it gets mapped before we change the page state in the RMP entry.
--- arch/x86/include/asm/sev-common.h | 3 + arch/x86/kvm/svm/sev.c | 141 ++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+)
arch/x86/include/asm/sev-common.h +3 -0
@@ -81,6 +81,9 @@#define GHCB_MSR_PSC_RESP 0x015#define GHCB_MSR_PSC_ERROR_POS 32 +#define GHCB_MSR_PSC_ERROR_MASK GENMASK_ULL(31, 0) +#define GHCB_MSR_PSC_RSVD_POS 12 +#define GHCB_MSR_PSC_RSVD_MASK GENMASK_ULL(19, 0)#define GHCB_MSR_PSC_RESP_VAL (val) ((val) >> GHCB_MSR_PSC_ERROR_POS)/* GHCB Hypervisor Feature Request */
arch/x86/kvm/svm/sev.c +141 -0
159 lines not on this page · raw message
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 33/40] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 1 line · Brijesh Singh
+static int
__snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level)
I can live with e.g. GHCB_MSR_PSC_REQ, but I'd strongly prefer to spell this out, e.g. __snp_handle_page_state_change() or whatever. I had a hell of a time figuring out what PSC was the first time I saw it in some random context.
Quoted 19 lines
arch/x86/kvm/svm/sev.c +19
-0+{ +struct kvm *kvm = vcpu->kvm; +int rc, tdp_level; +kvm_pfn_t pfn; +gpa_t gpa_end; + + gpa_end = gpa +page_level_size (level); + +while (gpa < gpa_end) { +/* +* Get the pfn and level for the gpa from the nested page table. +* +* If the TDP walk failed, then its safe to say that we don't have a valid +* mapping for the gpa in the nested page table. Create a fault to map the +* page is nested page table. +*/ +if (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &tdp_level)) { + pfn =kvm_mmu_map_tdp_page (vcpu, gpa,PFERR_USER_MASK , level); +if (is_error_noslot_pfn (pfn))
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2939
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ goto out; + +if (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &tdp_level)) + goto out; + } + +/* Adjust the level so that we don't go higher than the backing page level */ + level =min_t (size_t, level, tdp_level); + +write_lock (&kvm->mmu_lock);
Retrieving the PFN and level outside of mmu_lock is not correct. Because the pages are pinned and the VMM is not malicious, it will function as intended, but it is far from correct.
The overall approach also feels wrong, e.g. a guest won't be able to convert a 2mb chunk back to a 2mb large page if KVM mapped the GPA as a 4kb page in the past (from a different conversion).
I'd also strongly prefer to have a common flow between SNP and TDX for converting between shared/prviate.
I'll circle back to this next week, it'll probably take a few hours of staring to figure out a solution, if a common one for SNP+TDX is even possible.
Quoted 36 lines
arch/x86/kvm/svm/sev.c +29
-0+ +switch (op) { +case SNP_PAGE_STATE_SHARED : + rc =snp_make_page_shared (vcpu, gpa, pfn, level); +break ; +case SNP_PAGE_STATE_PRIVATE : + rc =snp_make_page_private (vcpu, gpa, pfn, level); +break ; +default : + rc = -EINVAL ; +break ; + } + +write_unlock (&kvm->mmu_lock); + +if (rc) { +pr_err_ratelimited ("Error op %d gpa %llx pfn %llx level %d rc %d\n" , + op, gpa, pfn, level, rc); + goto out; + } + + gpa = gpa +page_level_size (level); + } + +out: +return rc; +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;@@ -2941,6 +3063,25 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_PSC_REQ : {
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3076
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+gfn_t gfn; +int ret; +u8 op; + + gfn =get_ghcb_msr_bits (svm,GHCB_MSR_PSC_GFN_MASK ,GHCB_MSR_PSC_GFN_POS ); + op =get_ghcb_msr_bits (svm,GHCB_MSR_PSC_OP_MASK ,GHCB_MSR_PSC_OP_POS ); + + ret =__snp_handle_psc (vcpu, op,gfn_to_gpa (gfn),PG_LEVEL_4K ); + +/* If failed to change the state then spec requires to return all F's */
That doesn't mesh with what I could find:
o 0x015 – SNP Page State Change Response
▪ GHCBData[63:32] – Error code
▪ GHCBData[31:12] – Reserved, must be zero
Written by the hypervisor in response to a Page State Change request. Any non- zero value for the error code indicates that the page state change was not successful.
And if "all Fs" is indeed the error code, 'int ret' probably only works by luck since the return value is a 64-bit value, where as ret is a 32-bit signed int.
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3078
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+if (ret) + ret =-1 ;
Uh, this is fubar. You've created a shadow of 'ret', i.e. the outer ret is likely
uninitialized.
Quoted 12 lines
arch/x86/kvm/svm/sev.c +6
-0+ +set_ghcb_msr_bits (svm, ret,GHCB_MSR_PSC_ERROR_MASK ,GHCB_MSR_PSC_ERROR_POS ); +set_ghcb_msr_bits (svm,0 ,GHCB_MSR_PSC_RSVD_MASK ,GHCB_MSR_PSC_RSVD_POS ); +set_ghcb_msr_bits (svm,GHCB_MSR_PSC_RESP ,GHCB_MSR_INFO_MASK ,GHCB_MSR_INFO_POS ); +break ; + }case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;Signature · 1 line
2.17.1
Re: [PATCH Part2 RFC v4 33/40] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 6 lines · Sean Christopherson
Quoted 1 line · Brijesh Singh
+static int
__snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level)I can live with e.g.
GHCB_MSR_PSC_REQ, but I'd strongly prefer to spell this out, e.g.__snp_handle_page_state_change()or whatever. I had a hell of a time figuring out what PSC was the first time I saw it in some random context.
Based on the previous review feedback I renamed from __snp_handle_page_state_change to __snp_handle_psc(). I will see what others say and based on that will rename accordingly.
Quoted 26 lines
Quoted 26 lines
arch/x86/kvm/svm/sev.c +25
-0+{ +struct kvm *kvm = vcpu->kvm; +int rc, tdp_level; +kvm_pfn_t pfn; +gpa_t gpa_end; + + gpa_end = gpa +page_level_size (level); + +while (gpa < gpa_end) { +/* +* Get the pfn and level for the gpa from the nested page table. +* +* If the TDP walk failed, then its safe to say that we don't have a valid +* mapping for the gpa in the nested page table. Create a fault to map the +* page is nested page table. +*/ +if (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &tdp_level)) { + pfn =kvm_mmu_map_tdp_page (vcpu, gpa,PFERR_USER_MASK , level); +if (is_error_noslot_pfn (pfn)) + goto out; + +if (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &tdp_level)) + goto out; + } +
Quoted 9 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2939
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+/* Adjust the level so that we don't go higher than the backing page level */ + level =min_t (size_t, level, tdp_level); + +write_lock (&kvm->mmu_lock);Retrieving the PFN and level outside of
mmu_lockis not correct. Because the pages are pinned and the VMM is not malicious, it will function as intended, but it is far from correct.
Good point, I should have retrieved the pfn and level inside the lock.
Quoted 4 lines
The overall approach also feels wrong, e.g. a guest won't be able to convert a 2mb chunk back to a 2mb large page if KVM mapped the GPA as a 4kb page in the past (from a different conversion).
Maybe I am missing something, I am not able to follow 'guest won't be able to convert a 2mb chunk back to a 2mb large page'. The page-size used inside the guest have to relationship with the RMP/NPT page-size. e.g, a guest can validate the page range as a 4k and still map the page range as a 2mb or 1gb in its pagetable.
Quoted 6 lines
I'd also strongly prefer to have a common flow between SNP and TDX for converting between shared/prviate.
I'll circle back to this next week, it'll probably take a few hours of staring to figure out a solution, if a common one for SNP+TDX is even possible.
Sounds good.
Quoted 56 lines
Quoted 36 lines
arch/x86/kvm/svm/sev.c +29
-0+ +switch (op) { +case SNP_PAGE_STATE_SHARED : + rc =snp_make_page_shared (vcpu, gpa, pfn, level); +break ; +case SNP_PAGE_STATE_PRIVATE : + rc =snp_make_page_private (vcpu, gpa, pfn, level); +break ; +default : + rc = -EINVAL ; +break ; + } + +write_unlock (&kvm->mmu_lock); + +if (rc) { +pr_err_ratelimited ("Error op %d gpa %llx pfn %llx level %d rc %d\n" , + op, gpa, pfn, level, rc); + goto out; + } + + gpa = gpa +page_level_size (level); + } + +out: +return rc; +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;@@ -2941,6 +3063,25 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_PSC_REQ : {arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3076
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+gfn_t gfn; +int ret; +u8 op; + + gfn =get_ghcb_msr_bits (svm,GHCB_MSR_PSC_GFN_MASK ,GHCB_MSR_PSC_GFN_POS ); + op =get_ghcb_msr_bits (svm,GHCB_MSR_PSC_OP_MASK ,GHCB_MSR_PSC_OP_POS ); + + ret =__snp_handle_psc (vcpu, op,gfn_to_gpa (gfn),PG_LEVEL_4K ); + +/* If failed to change the state then spec requires to return all F's */ That doesn't mesh with what I could find:
o
0x015– SNP Page State Change Response
▪ GHCBData[63:32] – Error code
▪ GHCBData[31:12] – Reserved, must be zero
Written by the hypervisor in response to a Page State Change request. Any non- zero value for the error code indicates that the page state change was not successful.
Quoted 9 lines
And if "all Fs" is indeed the error code, 'int ret' probably only works by luck since the return value is a 64-bit value, where as ret is a 32-bit signed int.
arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3078
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+if (ret) + ret =-1 ;Uh, this is fubar. You've created a shadow of 'ret', i.e. the outer ret is likely
uninitialized.
Ah, let me fix it in next rev.
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 33/40] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 5 lines · Brijesh Singh
Quoted 3 lines · Sean Christopherson
Quoted 1 line · Brijesh Singh
+static int
__snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level)
Quoted 7 lines
Quoted 3 lines
I can live with e.g.
GHCB_MSR_PSC_REQ, but I'd strongly prefer to spell this out, e.g.__snp_handle_page_state_change()or whatever. I had a hell of a time figuring out what PSC was the first time I saw it in some random context.Based on the previous review feedback I renamed from
__snp_handle_page_state_changeto__snp_handle_psc(). I will see what others say and based on that will rename accordingly.
I've no objection to using PSC for enums and whatnot, and I'll happily defer to Boris for functions in the core kernel and guest, but for KVM I'd really like to spell out the name for the two or so main handler functions.
Quoted 33 lines
Quoted 17 lines
Quoted 17 lines
arch/x86/kvm/svm/sev.c +17
-0+while (gpa < gpa_end) { +/* +* Get the pfn and level for the gpa from the nested page table. +* +* If the TDP walk failed, then its safe to say that we don't have a valid +* mapping for the gpa in the nested page table. Create a fault to map the +* page is nested page table. +*/ +if (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &tdp_level)) { + pfn =kvm_mmu_map_tdp_page (vcpu, gpa,PFERR_USER_MASK , level); +if (is_error_noslot_pfn (pfn)) + goto out; + +if (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &tdp_level)) + goto out; + } +Quoted 8 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2939
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+/* Adjust the level so that we don't go higher than the backing page level */ + level =min_t (size_t, level, tdp_level); + +write_lock (&kvm->mmu_lock);Retrieving the PFN and level outside of
mmu_lockis not correct. Because the pages are pinned and the VMM is not malicious, it will function as intended, but it is far from correct.Good point, I should have retrieved the pfn and level inside the lock.
Quoted 4 lines
The overall approach also feels wrong, e.g. a guest won't be able to convert a 2mb chunk back to a 2mb large page if KVM mapped the GPA as a 4kb page in the past (from a different conversion).
Quoted 5 lines
Maybe I am missing something, I am not able to follow 'guest won't be able to convert a 2mb chunk back to a 2mb large page'. The page-size used inside the guest have to relationship with the RMP/NPT page-size. e.g, a guest can validate the page range as a 4k and still map the page range as a 2mb or 1gb in its pagetable.
The proposed code walks KVM's TDP and adjusts the RMP level to be the min of the guest+host levels. Once KVM has installed a 4kb TDP SPTE, that walk will find the 4kb TDP SPTE and thus operate on the RMP at a 4kb granularity. To allow full restoration of 2mb PTE+SPTE+RMP, KVM needs to zap the 4kb SPTE(s) at some point to allow rebuilding a 2mb SPTE.
Re: [PATCH Part2 RFC v4 33/40] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 4 lines · Sean Christopherson
I've no objection to using PSC for enums and whatnot, and I'll happily defer to Boris for functions in the core kernel and guest, but for KVM I'd really like to spell out the name for the two or so main handler functions.
Noted.
Quoted 7 lines
Quoted 6 lines
Maybe I am missing something, I am not able to follow 'guest won't be able to convert a 2mb chunk back to a 2mb large page'. The page-size used inside the guest have to relationship with the RMP/NPT page-size. e.g, a guest can validate the page range as a 4k and still map the page range as a 2mb or 1gb in its pagetable.
Quoted 6 lines
The proposed code walks KVM's TDP and adjusts the RMP level to be the min of the guest+host levels. Once KVM has installed a 4kb TDP SPTE, that walk will find the 4kb TDP SPTE and thus operate on the RMP at a 4kb granularity. To allow full restoration of 2mb PTE+SPTE+RMP, KVM needs to zap the 4kb SPTE(s) at some point to allow rebuilding a 2mb SPTE.
Ah I see. In that case, SNP firmware provides a command "SNP_PAGE_UNMASH" that can be used by the hypervisor to combines the multiple 4k entry into a single 2mb without affecting the validation.
-Brijesh
Borislav Petkov
maintainerRe: [PATCH Part2 RFC v4 33/40] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
In reply to Sean ChristophersonQuoted 4 lines · Sean Christopherson
I've no objection to using PSC for enums and whatnot, and I'll happily defer to Boris for functions in the core kernel and guest, but for KVM I'd really like to spell out the name for the two or so main handler functions.
Well,
- we abbreviate things in the kernel all the time - this is no exception. We don't name it
secure_nested_paging_handle_page_state_change()
either. :-)
- If you don't know what PSC means, now you do :-P Also, comments above the function names help.
- I asked for the shortening because those function names were a mouthful and when you see
snp_handle_page_state_change()
I wonder, it is "handling", is it "changing" or what is it doing. And the page state change is a thing so the "handle" is important here. Thus the
snp_handle_psc()
variant.
Also, shorter function names make the code more readable. I'm sure you've read firmware code or other OS code before to understand what I mean.
Anyway, I felt I should give my arguments why I requested the shortening.
Thx.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteRFC PATCH v4 34/40 KVM: SVM: Add support to handle Page State Change VMGEXIT
In reply to Brijesh SinghSEV-SNP VMs can ask the hypervisor to change the page state in the RMP table to be private or shared using the Page State Change NAE event as defined in the GHCB specification section 4.1.6.
--- arch/x86/include/asm/sev-common.h | 7 +++ arch/x86/kvm/svm/sev.c | 80 ++++++++++++++++++++++++++++++- include/linux/sev.h | 3 ++ 3 files changed, 88 insertions(+), 2 deletions(-)
arch/x86/include/asm/sev-common.h +7 -0
@@ -101,6 +101,13 @@/* SNP Page State Change NAE event */ #define VMGEXIT_PSC_MAX_ENTRY 253 +/* The page state change hdr structure in not valid */ +#define PSC_INVALID_HDR 1 +/* The hdr.cur_entry or hdr.end_entry is not valid */ +#define PSC_INVALID_ENTRY 2 +/* Page state change encountered undefined error */ +#define PSC_UNDEF_ERR 3 +struct __packed psc_hdr {u16 cur_entry;u16 end_entry;
arch/x86/kvm/svm/sev.c +78 -2
111 lines not on this page · raw message
include/linux/sev.h +3 -0
@@ -57,6 +57,9 @@ struct rmpupdate {*/ #define FAIL_INUSE 3 +/* RMUPDATE detected 4K page and 2MB page overlap. */ +#define RMPUPDATE_FAIL_OVERLAP 7 +#ifdef CONFIG_AMD_MEM_ENCRYPT struct rmpentry *snp_lookup_page_in_rmptable (struct page *page,int *level);int psmash (struct page *page);
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 34/40] KVM: SVM: Add support to handle Page State Change VMGEXIT
Quoted 9 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +9
-0+static unsigned long snp_handle_psc (struct vcpu_svm *svm,struct ghcb *ghcb) +{ +struct kvm_vcpu *vcpu = &svm->vcpu; +int level, op, rc =PSC_UNDEF_ERR ; +struct snp_psc_desc *info; +struct psc_entry *entry; +gpa_t gpa; + +if (!sev_snp_guest (vcpu->kvm))
arch/x86/kvm/svm/sev.c static int __snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level) · line 3004
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ goto out; + +if (!setup_vmgexit_scratch (svm, true,sizeof (ghcb->save.sw_scratch))) { +pr_err ("vmgexit: scratch area is not setup.\n" ); + rc =PSC_INVALID_HDR ; + goto out; + } + + info = (struct snp_psc_desc *)svm->ghcb_sa; + entry = &info->entries[info->hdr.cur_entry];
Grabbing "entry" here is unnecessary and confusing.
arch/x86/kvm/svm/sev.c static int __snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level) · line 3008
Quoted 4 lines
arch/x86/kvm/svm/sev.c +4
-0+ +if ((info->hdr.cur_entry >=VMGEXIT_PSC_MAX_ENTRY ) || + (info->hdr.end_entry >=VMGEXIT_PSC_MAX_ENTRY ) || + (info->hdr.cur_entry > info->hdr.end_entry)) {
There's a TOCTOU bug here if the guest uses the GHCB instead of a scratch area. If the guest uses the scratch area, then KVM makes a full copy into kernel memory. But if the guest uses the GHCB, then KVM maps the GHCB into kernel address space but doesn't make a full copy, i.e. the guest can modify the data while it's being processed by KVM.
IIRC, Peter and I discussed the sketchiness of the GHCB mapping offline a few times, but determined that there were no existing SEV-ES bugs because the guest could only submarine its own emulation request. But here, it could coerce KVM into running off the end of a buffer.
I think you can get away with capturing cur_entry/end_entry locally, though copying the GHCB would be more robust. That would also make the code a bit prettier, e.g.
cur = info->hdr.cur_entry; end = info->hdr.end_entry;
arch/x86/kvm/svm/sev.c static int __snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level) · line 3013
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+ rc =PSC_INVALID_ENTRY ; + goto out; + } + +while (info->hdr.cur_entry <= info->hdr.end_entry) {
Make this a for loop?
for ( ; cur_entry < end_entry; cur_entry++)
Review
Quoted 1 line
(quoted diff) +1
-0+ entry = &info->entries[info->hdr.cur_entry];
Does this need array_index_nospec() treatment?
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+ gpa =gfn_to_gpa (entry->gfn); + level =RMP_TO_X86_PG_LEVEL (entry->pagesize); + op = entry->operation; + +if (!IS_ALIGNED (gpa,page_level_size (level))) { + rc =PSC_INVALID_ENTRY ; + goto out;
arch/x86/kvm/svm/sev.c static int __snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level) · line 3031
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ } + + rc =__snp_handle_psc (vcpu, op, gpa, level); +if (rc) + goto out; + + info->hdr.cur_entry++; + } + +out:
And for the copy case:
info->hdr.cur_entry = cur;
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+return rc ?map_to_psc_vmgexit_code (rc) :0 ; +}
Re: [PATCH Part2 RFC v4 34/40] KVM: SVM: Add support to handle Page State Change VMGEXIT
Quoted 14 lines · Sean Christopherson
Quoted 13 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +13
-0+static unsigned long snp_handle_psc (struct vcpu_svm *svm,struct ghcb *ghcb) +{ +struct kvm_vcpu *vcpu = &svm->vcpu; +int level, op, rc =PSC_UNDEF_ERR ; +struct snp_psc_desc *info; +struct psc_entry *entry; +gpa_t gpa; + +if (!sev_snp_guest (vcpu->kvm)) + goto out; + +if (!setup_vmgexit_scratch (svm, true,sizeof (ghcb->save.sw_scratch))) { +pr_err ("vmgexit: scratch area is not setup.\n" );
Quoted 8 lines
arch/x86/kvm/svm/sev.c static int __snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level) · line 3004
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+ rc =PSC_INVALID_HDR ; + goto out; + } + + info = (struct snp_psc_desc *)svm->ghcb_sa; + entry = &info->entries[info->hdr.cur_entry];Grabbing "entry" here is unnecessary and confusing.
Noted.
Quoted 12 lines
arch/x86/kvm/svm/sev.c static int __snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level) · line 3008
Quoted 5 lines
arch/x86/kvm/svm/sev.c +4
-0+ +if ((info->hdr.cur_entry >=VMGEXIT_PSC_MAX_ENTRY ) || + (info->hdr.end_entry >=VMGEXIT_PSC_MAX_ENTRY ) || + (info->hdr.cur_entry > info->hdr.end_entry)) {There's a TOCTOU bug here if the guest uses the GHCB instead of a scratch area. If the guest uses the scratch area, then KVM makes a full copy into kernel memory. But if the guest uses the GHCB, then KVM maps the GHCB into kernel address space but doesn't make a full copy, i.e. the guest can modify the data while it's being processed by KVM.
Sure, I can make a full copy of the page-state change buffer.
Quoted 12 lines
IIRC, Peter and I discussed the sketchiness of the GHCB mapping offline a few times, but determined that there were no existing SEV-ES bugs because the guest could only submarine its own emulation request. But here, it could coerce KVM into running off the end of a buffer.
I think you can get away with capturing cur_entry/end_entry locally, though copying the GHCB would be more robust. That would also make the code a bit prettier, e.g.
cur = info->hdr.cur_entry; end = info->hdr.end_entry;
Quoted 7 lines
arch/x86/kvm/svm/sev.c static int __snp_handle_psc(struct kvm_vcpu *vcpu, int op, gpa_t gpa, int level) · line 3013
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+ rc =PSC_INVALID_ENTRY ; + goto out; + } + +while (info->hdr.cur_entry <= info->hdr.end_entry) {Make this a for loop?
Sure, I can use the for loop. IIRC, in previous review feedbacks I got the feeling that while() was preferred in the part1 so I used the similar approach here.
Quoted 7 lines
for ( ;
cur_entry<end_entry; cur_entry++)Review
Quoted 1 line
(quoted diff) +1
-0+ entry = &info->entries[info->hdr.cur_entry];Does this need
array_index_nospec()treatment?
I don't think so.
thanks
RFC PATCH v4 35/40 KVM: Add arch hooks to track the host write to guest memory
In reply to Brijesh SinghThe kvm_write_guest{_page} and kvm_vcpu_write_guest{_page} are used by the hypevisor to write to the guest memory. The kvm_vcpu_map() and kvm_map_gfn() are used by the hypervisor to map the guest memory and and access it later.
When SEV-SNP is enabled in the guest VM, the guest memory pages can either be a private or shared. A write from the hypervisor goes through the RMP checks. If hardware sees that hypervisor is attempting to write to a guest private page, then it triggers an RMP violation (i.e, #PF with RMP bit set).
Enhance the KVM guest write helpers to invoke an architecture specific hooks (kvm_arch_write_gfn_{begin,end}) to track the write access from the hypervisor.
When SEV-SNP is enabled, the guest uses the PAGE_STATE vmgexit to ask the hypervisor to change the page state from shared to private or vice versa. While changing the page state to private, use the kvm_host_write_track_is_active() to check whether the page is being tracked for the host write access (i.e either mapped or kvm_write_guest is in progress). If its tracked, then do not change the page state.
--- arch/x86/include/asm/kvm_host.h | 6 +++ arch/x86/kvm/svm/sev.c | 51 +++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 2 + arch/x86/kvm/svm/svm.h | 1 + arch/x86/kvm/x86.c | 78 +++++++++++++++++++++++++++++++++ include/linux/kvm_host.h | 3 ++ virt/kvm/kvm_main.c | 21 +++++++-- 7 files changed, 159 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +6 -0
@@ -865,10 +865,13 @@ struct kvm_lpage_info {int disallow_lpage; }; +bool kvm_host_write_track_is_active (struct kvm *kvm,gfn_t gfn); +struct kvm_arch_memory_slot {struct kvm_rmap_head *rmap[KVM_NR_PAGE_SIZES ];struct kvm_lpage_info *lpage_info[KVM_NR_PAGE_SIZES -1 ];unsigned short *gfn_track[KVM_PAGE_TRACK_MAX ]; +unsigned short *host_write_track[KVM_PAGE_TRACK_MAX ]; };/*
@@ -1393,6 +1396,9 @@ struct kvm_x86_ops {void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector);void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu);int (*get_tdp_max_page_level)(struct kvm_vcpu *vcpu,gpa_t gpa,int max_level); + +void (*write_page_begin)(struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn); +void (*write_page_end)(struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn); };struct kvm_x86_nested_ops {
arch/x86/kvm/svm/sev.c +51 -0
66 lines not on this page · raw message
arch/x86/kvm/svm/svm.c +2 -0
@@ -4577,6 +4577,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = { .alloc_apic_backing_page = svm_alloc_apic_backing_page, .get_tdp_max_page_level = sev_get_tdp_max_page_level, + + .write_page_begin = sev_snp_write_page_begin, };static struct kvm_x86_init_ops svm_init_ops__initdata = {
arch/x86/kvm/svm/svm.h +1 -0
@@ -576,6 +576,7 @@ void sev_es_prepare_guest_switch(struct vcpu_svm *svm, unsigned int cpu);void sev_es_unmap_ghcb (struct vcpu_svm *svm);struct page *snp_safe_alloc_page (struct kvm_vcpu *vcpu);int sev_get_tdp_max_page_level (struct kvm_vcpu *vcpu,gpa_t gpa,int max_level); +void sev_snp_write_page_begin (struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn);/* vmenter.S */
arch/x86/kvm/x86.c +78 -0
98 lines not on this page · raw message
include/linux/kvm_host.h +3 -0
@@ -1550,6 +1550,9 @@ static inline long kvm_arch_vcpu_async_ioctl(struct file *filp,void kvm_arch_mmu_notifier_invalidate_range (struct kvm *kvm,unsigned long start,unsigned long end); +void kvm_arch_write_gfn_begin (struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn); +void kvm_arch_write_gfn_end (struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn); +#ifdef CONFIG_HAVE_KVM_VCPU_RUN_PID_CHANGE int kvm_arch_vcpu_run_pid_change (struct kvm_vcpu *vcpu);#else
virt/kvm/kvm_main.c +18 -3
@@ -160,6 +160,14 @@ __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm, { } +__weak void kvm_arch_write_gfn_begin (struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn) +{ +} + +__weak void kvm_arch_write_gfn_end (struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn) +{ +} +bool kvm_is_zone_device_pfn (kvm_pfn_t pfn) {/*
@@ -2309,7 +2317,8 @@ static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn, cache->generation = gen; } -static int __kvm_map_gfn (struct kvm_memslots *slots,gfn_t gfn, +static int __kvm_map_gfn (struct kvm *kvm, +struct kvm_memslots *slots,gfn_t gfn,struct kvm_host_map *map,struct gfn_to_pfn_cache *cache,bool atomic)
@@ -2361,20 +2370,22 @@ static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn, map->pfn = pfn; map->gfn = gfn; +kvm_arch_write_gfn_begin (kvm, slot, map->gfn); +return 0 ; }int kvm_map_gfn (struct kvm_vcpu *vcpu,gfn_t gfn,struct kvm_host_map *map,struct gfn_to_pfn_cache *cache,bool atomic) { -return __kvm_map_gfn (kvm_memslots (vcpu->kvm), gfn, map, +return __kvm_map_gfn (vcpu->kvm,kvm_memslots (vcpu->kvm), gfn, map, cache, atomic); }EXPORT_SYMBOL_GPL (kvm_map_gfn);int kvm_vcpu_map (struct kvm_vcpu *vcpu,gfn_t gfn,struct kvm_host_map *map) { -return __kvm_map_gfn (kvm_vcpu_memslots (vcpu), gfn, map, +return __kvm_map_gfn (vcpu->kvm,kvm_vcpu_memslots (vcpu), gfn, map,NULL , false); }EXPORT_SYMBOL_GPL (kvm_vcpu_map);
@@ -2412,6 +2423,8 @@ static void __kvm_unmap_gfn(struct kvm *kvm,else kvm_release_pfn (map->pfn, dirty,NULL ); +kvm_arch_write_gfn_end (kvm, memslot, map->gfn); + map->hva =NULL ; map->page =NULL ; }
@@ -2612,7 +2625,9 @@ static int __kvm_write_guest_page(struct kvm *kvm, addr =gfn_to_hva_memslot (memslot, gfn);if (kvm_is_error_hva (addr))return -EFAULT ; +kvm_arch_write_gfn_begin (kvm, memslot, gfn); r =__copy_to_user ((void __user *)addr + offset, data, len); +kvm_arch_write_gfn_end (kvm, memslot, gfn);if (r)return -EFAULT ;mark_page_dirty_in_slot (kvm, memslot, gfn);
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 RFC v4 35/40] KVM: Add arch hooks to track the host write to guest memory
Quoted 24 lines · Brijesh Singh
The kvm_write_guest{_page} and kvm_vcpu_write_guest{_page} are used by the hypevisor to write to the guest memory. The
kvm_vcpu_map()andkvm_map_gfn()are used by the hypervisor to map the guest memory and and access it later.When SEV-SNP is enabled in the guest VM, the guest memory pages can either be a private or shared. A write from the hypervisor goes through the RMP checks. If hardware sees that hypervisor is attempting to write to a guest private page, then it triggers an RMP violation (i.e, #PF with RMP bit set).
Enhance the KVM guest write helpers to invoke an architecture specific hooks (kvm_arch_write_gfn_{begin,end}) to track the write access from the hypervisor.
When SEV-SNP is enabled, the guest uses the
PAGE_STATEvmgexit to ask the hypervisor to change the page state from shared to private or vice versa. While changing the page state to private, use thekvm_host_write_track_is_active()to check whether the page is being tracked for the host write access (i.e either mapped orkvm_write_guestis in progress). If its tracked, then do not change the page state.Signed-off-by Brijesh Singh <[email protected]>---
...
Quoted 16 lines
arch/x86/kvm/svm/sev.c +12
-0@@ -3468,3 +3489,33 @@ int sev_get_tdp_max_page_level(struct kvm_vcpu *vcpu, gpa_t gpa, int max_level)return min_t (uint32_t, level, max_level); } + +void sev_snp_write_page_begin (struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn) +{ +struct rmpentry *e; +int level, rc; +kvm_pfn_t pfn; + +if (!sev_snp_guest (kvm)) +return ; + + pfn =gfn_to_pfn (kvm, gfn); +if (is_error_noslot_pfn (pfn))
arch/x86/kvm/svm/sev.c int sev_get_tdp_max_page_level(struct kvm_vcpu *vcpu, gpa_t gpa, int max_level) · line 3513
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+return ; + + e =snp_lookup_page_in_rmptable (pfn_to_page (pfn), &level); +if (unlikely (!e)) +return ; + +/* +* A hypervisor should never write to the guest private page. A write to the +* guest private will cause an RMP violation. If the guest page is private, +* then make it shared.
NAK on converting RMP entries in response to guest accesses. Corrupting guest data (due to dropping the "validated" flag) on a rogue/incorrect guest emulation request or misconfigured PV feature is double ungood. The potential kernel panic below isn't much better.
And I also don't think we need this heavyweight flow for user access, e.g. __copy_to_user(), just eat the RMP violation #PF like all other #PFs and exit to userspace with -EFAULT.
kvm_vcpu_map() and friends might need the manual lookup, at least initially, but in an ideal world that would be naturally handled by gup(), e.g. by unmapping guest private memory or whatever approach TDX ends up employing to avoid #MCs.
Quoted 8 lines
arch/x86/kvm/svm/sev.c +8
-0+*/ +if (rmpentry_assigned (e)) { +pr_err ("SEV-SNP: write to guest private gfn %llx\n" , gfn); + rc =snp_make_page_shared (kvm_get_vcpu (kvm,0 ), + gfn <<PAGE_SHIFT , pfn,PG_LEVEL_4K ); +BUG_ON (rc !=0 ); + } +}
...
arch/x86/kvm/x86.c void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm, · line 9110
Quoted 3 lines
arch/x86/kvm/x86.c +3
-0+void kvm_arch_write_gfn_begin (struct kvm *kvm,struct kvm_memory_slot *slot,gfn_t gfn) +{ +update_gfn_track (slot, gfn,KVM_PAGE_TRACK_WRITE ,1 );
Tracking only writes isn't correct, as KVM reads to guest private memory will return garbage. Pulling the rug out from under KVM reads won't fail as spectacularly as writes (at least not right away), but they'll still fail. I'm actually ok reading garbage if the guest screws up, but KVM needs consistent semantics.
Good news is that per-gfn tracking is probably overkill anyways. As mentioned above, user access don't need extra magic, they either fail or they don't.
For kvm_vcpu_map(), one thought would be to add a "short-term" map variant that is not allowed to be retained across VM-Entry, and then use e.g. SRCU to block PSC requests until there are no consumers.
Quoted 3 lines
arch/x86/kvm/x86.c +3
-0+if (kvm_x86_ops.write_page_begin) + kvm_x86_ops.write_page_begin (kvm, slot, gfn); +}