Add AMD Secure Nested Paging (SEV-SNP) Hypervisor Support
Subsystems (12)
PATCH v5 35/45 KVM: SVM: Remove the long-lived GHCB host map
In reply to Brijesh SinghOn VMGEXIT, sev_handle_vmgexit() creates a host mapping for the GHCB GPA, and unmaps it just before VM-entry. This long-lived GHCB map is used by the VMGEXIT handler through accessors such as ghcb_{set_get}_xxx().
A long-lived GHCB map can cause issue when SEV-SNP is enabled. When SEV-SNP is enabled the mapped GPA needs to be protected against a page state change.
To eliminate the long-lived GHCB mapping, update the GHCB sync operations to explicitly map the GHCB before access and unmap it after access is complete. This requires that the setting of the GHCBs sw_exit_info_{1,2} fields be done during sev_es_sync_to_ghcb(), so create two new fields in the vcpu_svm struct to hold these values when required to be set outside of the GHCB mapping.
--- arch/x86/kvm/svm/sev.c | 129 ++++++++++++++++++++++++++--------------- arch/x86/kvm/svm/svm.c | 12 ++-- arch/x86/kvm/svm/svm.h | 24 +++++++- 3 files changed, 111 insertions(+), 54 deletions(-)
arch/x86/kvm/svm/sev.c +83 -46
@@ -2493,15 +2493,40 @@ void sev_free_vcpu(struct kvm_vcpu *vcpu)kfree (svm->ghcb_sa); } +static inline int svm_map_ghcb (struct vcpu_svm *svm,struct kvm_host_map *map) +{ +struct vmcb_control_area *control = &svm->vmcb->control; +u64 gfn =gpa_to_gfn (control->ghcb_gpa); + +if (kvm_vcpu_map (&svm->vcpu, gfn, map)) { +/* Unable to map GHCB from guest */ +pr_err ("error mapping GHCB GFN [%#llx] from guest\n" , gfn); +return -EFAULT ; + } + +return 0 ; +} + +static inline void svm_unmap_ghcb (struct vcpu_svm *svm,struct kvm_host_map *map) +{ +kvm_vcpu_unmap (&svm->vcpu, map, true); +} +static void dump_ghcb (struct vcpu_svm *svm) { -struct ghcb *ghcb = svm->ghcb; +struct kvm_host_map map;unsigned int nbits; +struct ghcb *ghcb; + +if (svm_map_ghcb (svm, &map)) +return ; + + ghcb = map.hva;/* Re-use the dump_invalid_vmcb module parameter */ if (!dump_invalid_vmcb) {pr_warn_ratelimited ("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n" ); -return ; + goto e_unmap; } nbits =sizeof (ghcb->save.valid_bitmap) *8 ;
@@ -2516,12 +2541,21 @@ static void dump_ghcb(struct vcpu_svm *svm)pr_err ("%-20s%016llx is_valid: %u\n" ,"sw_scratch" , ghcb->save.sw_scratch,ghcb_sw_scratch_is_valid (ghcb));pr_err ("%-20s%*pb\n" ,"valid_bitmap" , nbits, ghcb->save.valid_bitmap); + +e_unmap: +svm_unmap_ghcb (svm, &map); } -static void sev_es_sync_to_ghcb (struct vcpu_svm *svm) +static bool sev_es_sync_to_ghcb (struct vcpu_svm *svm) {struct kvm_vcpu *vcpu = &svm->vcpu; -struct ghcb *ghcb = svm->ghcb; +struct kvm_host_map map; +struct ghcb *ghcb; + +if (svm_map_ghcb (svm, &map)) +return false; + + ghcb = map.hva;/* * The GHCB protocol so far allows for the following data
@@ -2535,13 +2569,24 @@ static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)ghcb_set_rbx (ghcb, vcpu->arch.regs[VCPU_REGS_RBX ]);ghcb_set_rcx (ghcb, vcpu->arch.regs[VCPU_REGS_RCX ]);ghcb_set_rdx (ghcb, vcpu->arch.regs[VCPU_REGS_RDX ]); + +/* +* Copy the return values from the exit_info_{1,2}. +*/ +ghcb_set_sw_exit_info_1 (ghcb, svm->ghcb_sw_exit_info_1); +ghcb_set_sw_exit_info_2 (ghcb, svm->ghcb_sw_exit_info_2); + +trace_kvm_vmgexit_exit (svm->vcpu.vcpu_id, ghcb); + +svm_unmap_ghcb (svm, &map); + +return true; } -static void sev_es_sync_from_ghcb (struct vcpu_svm *svm) +static void sev_es_sync_from_ghcb (struct vcpu_svm *svm,struct ghcb *ghcb) {struct vmcb_control_area *control = &svm->vmcb->control;struct kvm_vcpu *vcpu = &svm->vcpu; -struct ghcb *ghcb = svm->ghcb;u64 exit_code;/*
@@ -2585,13 +2630,18 @@ static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)memset (ghcb->save.valid_bitmap,0 ,sizeof (ghcb->save.valid_bitmap)); } -static int sev_es_validate_vmgexit (struct vcpu_svm *svm) +static int sev_es_validate_vmgexit (struct vcpu_svm *svm,u64 *exit_code) { -struct kvm_vcpu *vcpu; +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm_host_map map;struct ghcb *ghcb; -u64 exit_code =0 ; - ghcb = svm->ghcb; +if (svm_map_ghcb (svm, &map)) +return -EFAULT ; + + ghcb = map.hva; + +trace_kvm_vmgexit_enter (vcpu->vcpu_id, ghcb);/* Only GHCB Usage code 0 is supported */ if (ghcb->ghcb_usage)
@@ -2601,7 +2651,7 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)* Retrieve the exit code now even though is may not be marked valid * as it could help with debugging. */ - exit_code =ghcb_get_sw_exit_code (ghcb); + *exit_code =ghcb_get_sw_exit_code (ghcb); if (!ghcb_sw_exit_code_is_valid(ghcb) || !ghcb_sw_exit_info_1_is_valid(ghcb) ||
@@ -2685,6 +2735,9 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm) goto vmgexit_err; } +sev_es_sync_from_ghcb (svm, ghcb); + +svm_unmap_ghcb (svm, &map);return 0 ; vmgexit_err:
@@ -2695,16 +2748,17 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm) ghcb->ghcb_usage); }else {vcpu_unimpl (vcpu,"vmgexit: exit reason %#llx is not valid\n" , - exit_code); + *exit_code);dump_ghcb (svm); } vcpu->run->exit_reason =KVM_EXIT_INTERNAL_ERROR ; vcpu->run->internal.suberror =KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON ; vcpu->run->internal.ndata =2 ; - vcpu->run->internal.data[0 ] = exit_code; + vcpu->run->internal.data[0 ] = *exit_code; vcpu->run->internal.data[1 ] = vcpu->arch.last_vmentry_cpu; +svm_unmap_ghcb (svm, &map);return -EINVAL ; }
@@ -2713,23 +2767,20 @@ 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) +if (!svm->ghcb_in_use)return ;/* Sync the scratch buffer area. */ if (svm->ghcb_sa_sync) {kvm_write_guest (svm->vcpu.kvm, -ghcb_get_sw_scratch (svm->ghcb), + svm->ghcb_sa_gpa, svm->ghcb_sa, svm->ghcb_sa_len); svm->ghcb_sa_sync = false; } -trace_kvm_vmgexit_exit (svm->vcpu.vcpu_id, svm->ghcb); -sev_es_sync_to_ghcb (svm); -kvm_vcpu_unmap (&svm->vcpu, &svm->ghcb_map, true); - svm->ghcb =NULL ; + svm->ghcb_in_use = false; }void pre_sev_run (struct vcpu_svm *svm,int cpu)
@@ -2961,7 +3012,6 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)struct vcpu_svm *svm =to_svm (vcpu);struct vmcb_control_area *control = &svm->vmcb->control;u64 ghcb_gpa, exit_code; -struct ghcb *ghcb;int ret;/* Validate the GHCB */
@@ -2974,27 +3024,14 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)return -EINVAL ; } -if (kvm_vcpu_map (vcpu, ghcb_gpa >>PAGE_SHIFT , &svm->ghcb_map)) { -/* Unable to map GHCB from guest */ -vcpu_unimpl (vcpu,"vmgexit: error mapping GHCB [%#llx] from guest\n" , - ghcb_gpa); -return -EINVAL ; - } - - svm->ghcb = svm->ghcb_map.hva; - ghcb = svm->ghcb_map.hva; - -trace_kvm_vmgexit_enter (vcpu->vcpu_id, ghcb); - - exit_code =ghcb_get_sw_exit_code (ghcb); - - ret =sev_es_validate_vmgexit (svm); + ret =sev_es_validate_vmgexit (svm, &exit_code);if (ret)return ret; -sev_es_sync_from_ghcb (svm); -ghcb_set_sw_exit_info_1 (ghcb,0 ); -ghcb_set_sw_exit_info_2 (ghcb,0 ); + svm->ghcb_in_use = true; + +svm_set_ghcb_sw_exit_info_1 (vcpu,0 ); +svm_set_ghcb_sw_exit_info_2 (vcpu,0 ); ret = -EINVAL ;switch (exit_code) {
@@ -3033,23 +3070,23 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)break ;case 1 :/* Get AP jump table address */ -ghcb_set_sw_exit_info_2 (ghcb, sev->ap_jump_table); +svm_set_ghcb_sw_exit_info_2 (vcpu, sev->ap_jump_table);break ;default :pr_err ("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n" , control->exit_info_1); -ghcb_set_sw_exit_info_1 (ghcb,1 ); -ghcb_set_sw_exit_info_2 (ghcb, -X86_TRAP_UD | -SVM_EVTINJ_TYPE_EXEPT | -SVM_EVTINJ_VALID ); +svm_set_ghcb_sw_exit_info_1 (vcpu,1 ); +svm_set_ghcb_sw_exit_info_2 (vcpu, +X86_TRAP_UD | +SVM_EVTINJ_TYPE_EXEPT | +SVM_EVTINJ_VALID ); } ret =1 ;break ; }case SVM_VMGEXIT_HV_FEATURES : { -ghcb_set_sw_exit_info_2 (ghcb,GHCB_HV_FT_SUPPORTED ); +svm_set_ghcb_sw_exit_info_2 (vcpu,GHCB_HV_FT_SUPPORTED ); ret =1 ;break ;
@@ -3171,7 +3208,7 @@ void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)* 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 ); +svm_set_ghcb_sw_exit_info_2 (vcpu,1 );break ;case AP_RESET_HOLD_MSR_PROTO :/*
arch/x86/kvm/svm/svm.c +6 -6
@@ -2786,14 +2786,14 @@ static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)static int svm_complete_emulated_msr (struct kvm_vcpu *vcpu,int err) {struct vcpu_svm *svm =to_svm (vcpu); -if (!err || !sev_es_guest (vcpu->kvm) ||WARN_ON_ONCE (!svm->ghcb)) +if (!err || !sev_es_guest (vcpu->kvm) ||WARN_ON_ONCE (!svm->ghcb_in_use))return kvm_complete_insn_gp (vcpu, err); -ghcb_set_sw_exit_info_1 (svm->ghcb,1 ); -ghcb_set_sw_exit_info_2 (svm->ghcb, -X86_TRAP_GP | -SVM_EVTINJ_TYPE_EXEPT | -SVM_EVTINJ_VALID ); +svm_set_ghcb_sw_exit_info_1 (vcpu,1 ); +svm_set_ghcb_sw_exit_info_2 (vcpu, +X86_TRAP_GP | +SVM_EVTINJ_TYPE_EXEPT | +SVM_EVTINJ_VALID );return 1 ; }
arch/x86/kvm/svm/svm.h +22 -2
@@ -191,8 +191,7 @@ struct vcpu_svm {/* SEV-ES support */ struct sev_es_save_area *vmsa; -struct ghcb *ghcb; -struct kvm_host_map ghcb_map; +bool ghcb_in_use;bool received_first_sipi;unsigned int ap_reset_hold_type;
@@ -204,6 +203,13 @@ struct vcpu_svm {bool ghcb_sa_sync;bool guest_state_loaded; + +/* +* SEV-ES support to hold the sw_exit_info return values to be +* sync'ed to the GHCB when mapped. +*/ +u64 ghcb_sw_exit_info_1; +u64 ghcb_sw_exit_info_2; };struct svm_cpu_data {
@@ -503,6 +509,20 @@ void nested_sync_control_from_vmcb02(struct vcpu_svm *svm);void nested_vmcb02_compute_g_pat (struct vcpu_svm *svm);void svm_switch_vmcb (struct vcpu_svm *svm,struct kvm_vmcb_info *target_vmcb); +static inline void svm_set_ghcb_sw_exit_info_1 (struct kvm_vcpu *vcpu,u64 val) +{ +struct vcpu_svm *svm =to_svm (vcpu); + + svm->ghcb_sw_exit_info_1 = val; +} + +static inline void svm_set_ghcb_sw_exit_info_2 (struct kvm_vcpu *vcpu,u64 val) +{ +struct vcpu_svm *svm =to_svm (vcpu); + + svm->ghcb_sw_exit_info_2 = val; +} +extern struct kvm_x86_nested_ops svm_nested_ops;/* avic.c */
Signature · 1 line
2.17.1
PATCH v5 36/45 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. 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 | 8 ++++++++ arch/x86/kvm/svm/sev.c | 27 +++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.h | 7 +++++++ 3 files changed, 42 insertions(+)
arch/x86/include/asm/sev-common.h +8 -0
@@ -59,6 +59,14 @@#define GHCB_MSR_AP_RESET_HOLD_RESULT_POS 12#define GHCB_MSR_AP_RESET_HOLD_RESULT_MASK GENMASK_ULL(51, 0) +/* Preferred GHCB GPA Request */ +#define GHCB_MSR_PREF_GPA_REQ 0x010 +#define GHCB_MSR_GPA_VALUE_POS 12 +#define GHCB_MSR_GPA_VALUE_MASK GENMASK_ULL(51, 0) + +#define GHCB_MSR_PREF_GPA_RESP 0x011 +#define GHCB_MSR_PREF_GPA_NONE 0xfffffffffffff +/* GHCB GPA Register */ #define GHCB_MSR_REG_GPA_REQ 0x012#define GHCB_MSR_REG_GPA_REQ_VAL (v) \
arch/x86/kvm/svm/sev.c +27 -0
@@ -2984,6 +2984,27 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_PREF_GPA_REQ : { +set_ghcb_msr_bits (svm,GHCB_MSR_PREF_GPA_NONE ,GHCB_MSR_GPA_VALUE_MASK , +GHCB_MSR_GPA_VALUE_POS ); +set_ghcb_msr_bits (svm,GHCB_MSR_PREF_GPA_RESP ,GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS ); +break ; + } +case GHCB_MSR_REG_GPA_REQ : { +u64 gfn; + + gfn =get_ghcb_msr_bits (svm,GHCB_MSR_GPA_VALUE_MASK , +GHCB_MSR_GPA_VALUE_POS ); + + svm->ghcb_registered_gpa =gfn_to_gpa (gfn); + +set_ghcb_msr_bits (svm, gfn,GHCB_MSR_GPA_VALUE_MASK , +GHCB_MSR_GPA_VALUE_POS ); +set_ghcb_msr_bits (svm,GHCB_MSR_REG_GPA_RESP ,GHCB_MSR_INFO_MASK , +GHCB_MSR_INFO_POS ); +break ; + }case GHCB_MSR_TERM_REQ : {u64 reason_set, reason_code;
@@ -3024,6 +3045,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 ; + } + ret =sev_es_validate_vmgexit (svm, &exit_code);if (ret)return ret;
arch/x86/kvm/svm/svm.h +7 -0
@@ -210,6 +210,8 @@ struct vcpu_svm {*/ u64 ghcb_sw_exit_info_1;u64 ghcb_sw_exit_info_2; + +u64 ghcb_registered_gpa; };struct svm_cpu_data {
@@ -266,6 +268,11 @@ static inline bool sev_snp_guest(struct kvm *kvm)return sev_es_guest (kvm) && sev->snp_active; } +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
PATCH v5 37/45 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, lookup the page in the NPT 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 NPT and RMP for the page. If the page is not mapped in the NPT, 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 | 9 ++ arch/x86/kvm/svm/sev.c | 197 ++++++++++++++++++++++++++++++ arch/x86/kvm/trace.h | 34 ++++++ arch/x86/kvm/x86.c | 1 + 4 files changed, 241 insertions(+)
arch/x86/include/asm/sev-common.h +9 -0
@@ -89,6 +89,10 @@ enum psc_op { };#define GHCB_MSR_PSC_REQ 0x014 +#define GHCB_MSR_PSC_GFN_POS 12 +#define GHCB_MSR_PSC_GFN_MASK GENMASK_ULL(39, 0) +#define GHCB_MSR_PSC_OP_POS 52 +#define GHCB_MSR_PSC_OP_MASK 0xf#define GHCB_MSR_PSC_REQ_GFN (gfn, op) \/* GHCBData[55:52] */ \ (((u64)((op) & 0xf) << 52) | \
@@ -98,6 +102,11 @@ enum psc_op { GHCB_MSR_PSC_REQ)#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_ERROR 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) \/* GHCBData[63:32] */ \ (((u64)(val) & GENMASK_ULL(63, 32)) >> 32)
arch/x86/kvm/svm/sev.c +197 -0
215 lines not on this page · raw message
arch/x86/kvm/trace.h +34 -0
@@ -7,6 +7,7 @@#include <asm/svm.h> #include <asm/clocksource.h> #include <asm/pvclock-abi.h> +#include <asm/sev-common.h> #undef TRACE_SYSTEM#define TRACE_SYSTEM kvm
@@ -1711,6 +1712,39 @@ TRACE_EVENT(kvm_vmgexit_msr_protocol_exit, __entry->vcpu_id, __entry->ghcb_gpa, __entry->result) ); +/* +* Tracepoint for the SEV-SNP page state change processing +*/ +#define psc_operation \ + {SNP_PAGE_STATE_PRIVATE, "private"}, \ + {SNP_PAGE_STATE_SHARED, "shared"} \ + +TRACE_EVENT (kvm_snp_psc, + TP_PROTO(unsigned int vcpu_id, u64 pfn, u64 gpa, u8 op, int level), +TP_ARGS (vcpu_id, pfn, gpa, op, level), + +TP_STRUCT__entry ( + __field(int, vcpu_id) + __field(u64, pfn) + __field(u64, gpa) + __field(u8, op) +__field (int, level) + ), + +TP_fast_assign ( + __entry->vcpu_id = vcpu_id; + __entry->pfn = pfn; + __entry->gpa = gpa; + __entry->op = op; + __entry->level = level; + ), + +TP_printk ("vcpu %u, pfn %llx, gpa %llx, op %s, level %d" , + __entry->vcpu_id, __entry->pfn, __entry->gpa, +__print_symbolic (__entry->op, psc_operation), + __entry->level) +); +#endif /* _TRACE_KVM_H */ #undef TRACE_INCLUDE_PATH
arch/x86/kvm/x86.c +1 -0
@@ -12371,3 +12371,4 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_vmgexit_exit);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_vmgexit_msr_protocol_enter);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_vmgexit_msr_protocol_exit); +EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_snp_psc);
Signature · 1 line
2.17.1
Re: [PATCH Part2 v5 37/45] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 69 lines · * Brijesh Singh ([email protected]) wrote:
SEV-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, lookup the page in the NPT 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 NPT and RMP for the page. If the page is not mapped in the NPT, then create a fault such that it gets mapped before we change the page state in the RMP entry.
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/sev-common.h | 9 ++ arch/x86/kvm/svm/sev.c | 197 ++++++++++++++++++++++++++++++ arch/x86/kvm/trace.h | 34 ++++++ arch/x86/kvm/x86.c | 1 + 4 files changed, 241 insertions(+)arch/x86/include/asm/sev-common.h +9
-0@@ -89,6 +89,10 @@ enum psc_op { };#define GHCB_MSR_PSC_REQ 0x014 +#define GHCB_MSR_PSC_GFN_POS 12 +#define GHCB_MSR_PSC_GFN_MASK GENMASK_ULL(39, 0) +#define GHCB_MSR_PSC_OP_POS 52 +#define GHCB_MSR_PSC_OP_MASK 0xf#define GHCB_MSR_PSC_REQ_GFN (gfn, op) \/* GHCBData[55:52] */ \ (((u64)((op) & 0xf) << 52) | \@@ -98,6 +102,11 @@ enum psc_op { GHCB_MSR_PSC_REQ)#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_ERROR 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) \/* GHCBData[63:32] */ \ (((u64)(val) & GENMASK_ULL(63, 32)) >> 32)arch/x86/kvm/svm/sev.c +9
-0@@ -31,6 +31,7 @@#include "svm_ops.h" #include "cpuid.h" #include "trace.h" +#include "mmu.h" #define __ex (x) __kvm_handle_fault_on_reboot(x)@@ -2905,6 +2906,181 @@ static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) svm->vmcb->control.ghcb_gpa = value; } +static int snp_rmptable_psmash (struct kvm *kvm,kvm_pfn_t pfn) +{ + pfn = pfn & ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); + +return psmash (pfn); +} + +static int snp_make_page_shared (struct kvm *kvm,gpa_t gpa,kvm_pfn_t pfn,int level)
....
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3028
Quoted 3 lines
arch/x86/kvm/svm/sev.c +3
-0+ +/* +* Mark the userspace range unmerable before adding the pages
^^^^^^^^^ typo
Quoted 25 lines
arch/x86/kvm/svm/sev.c +25
-0+* in the RMP table. +*/ +mmap_write_lock (kvm->mm); + rc =snp_mark_unmergable (kvm, hva,page_level_size (level)); +mmap_write_unlock (kvm->mm); +if (rc) +return -EINVAL ; + } + +write_lock (&kvm->mmu_lock); + + rc =kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &npt_level); +if (!rc) { +/* +* This may happen if another vCPU unmapped the page +* before we acquire the lock. Retry the PSC. +*/ +write_unlock (&kvm->mmu_lock); +return 0 ; + } + +/* +* Adjust the level so that we don't go higher than the backing +* page level. +*/
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3063
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ level =min_t (size_t, level, npt_level); + +trace_kvm_snp_psc (vcpu->vcpu_id, pfn, gpa, op, level); + +switch (op) { +case SNP_PAGE_STATE_SHARED : + rc =snp_make_page_shared (kvm, gpa, pfn, level); +break ; +case SNP_PAGE_STATE_PRIVATE : + rc =rmp_make_private (pfn, gpa, level, sev->asid, false);
Minor nit; it seems a shame that snp_make_page_shared and rmp_make_private both take gpa, pfn, level - in different orders.
Dave
Quoted 116 lines
arch/x86/kvm/svm/sev.c +41
-0+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); +return rc; + } + + gpa = gpa +page_level_size (level); + } + +return 0 ; +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;@@ -3005,6 +3181,27 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) GHCB_MSR_INFO_POS);break ; } +case GHCB_MSR_PSC_REQ : { +gfn_t gfn; +int ret; +enum psc_op 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_page_state_change (vcpu, op,gfn_to_gpa (gfn),PG_LEVEL_4K ); + +if (ret) +set_ghcb_msr_bits (svm,GHCB_MSR_PSC_ERROR , +GHCB_MSR_PSC_ERROR_MASK ,GHCB_MSR_PSC_ERROR_POS ); +else +set_ghcb_msr_bits (svm,0 , +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;arch/x86/kvm/trace.h +34
-0@@ -7,6 +7,7 @@#include <asm/svm.h> #include <asm/clocksource.h> #include <asm/pvclock-abi.h> +#include <asm/sev-common.h> #undef TRACE_SYSTEM#define TRACE_SYSTEM kvm@@ -1711,6 +1712,39 @@ TRACE_EVENT(kvm_vmgexit_msr_protocol_exit, __entry->vcpu_id, __entry->ghcb_gpa, __entry->result) ); +/* +* Tracepoint for the SEV-SNP page state change processing +*/ +#define psc_operation \ + {SNP_PAGE_STATE_PRIVATE, "private"}, \ + {SNP_PAGE_STATE_SHARED, "shared"} \ + +TRACE_EVENT (kvm_snp_psc, + TP_PROTO(unsigned int vcpu_id, u64 pfn, u64 gpa, u8 op, int level), +TP_ARGS (vcpu_id, pfn, gpa, op, level), + +TP_STRUCT__entry ( + __field(int, vcpu_id) + __field(u64, pfn) + __field(u64, gpa) + __field(u8, op) +__field (int, level) + ), + +TP_fast_assign ( + __entry->vcpu_id = vcpu_id; + __entry->pfn = pfn; + __entry->gpa = gpa; + __entry->op = op; + __entry->level = level; + ), + +TP_printk ("vcpu %u, pfn %llx, gpa %llx, op %s, level %d" , + __entry->vcpu_id, __entry->pfn, __entry->gpa, +__print_symbolic (__entry->op, psc_operation), + __entry->level) +); +#endif /* _TRACE_KVM_H */ #undef TRACE_INCLUDE_PATHarch/x86/kvm/x86.c +1
-0@@ -12371,3 +12371,4 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_vmgexit_exit);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_vmgexit_msr_protocol_enter);EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_vmgexit_msr_protocol_exit); +EXPORT_TRACEPOINT_SYMBOL_GPL (kvm_snp_psc);Signature · 1 line
2.17.1
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
Sean Christopherson
maintainerRe: [PATCH Part2 v5 37/45] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
In reply to Brijesh SinghQuoted 51 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +36
-0@@ -31,6 +31,7 @@#include "svm_ops.h" #include "cpuid.h" #include "trace.h" +#include "mmu.h" #define __ex (x) __kvm_handle_fault_on_reboot(x)@@ -2905,6 +2906,181 @@ static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) svm->vmcb->control.ghcb_gpa = value; } +static int snp_rmptable_psmash (struct kvm *kvm,kvm_pfn_t pfn) +{ + pfn = pfn & ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); + +return psmash (pfn); +} + +static int snp_make_page_shared (struct kvm *kvm,gpa_t gpa,kvm_pfn_t pfn,int level) +{ +int rc, rmp_level; + + rc =snp_lookup_rmpentry (pfn, &rmp_level); +if (rc <0 ) +return -EINVAL ; + +/* If page is not assigned then do nothing */ +if (!rc) +return 0 ; + +/* +* Is the page part of an existing 2MB RMP entry ? Split the 2MB into +* multiple of 4K-page before making the memory shared. +*/ +if (level ==PG_LEVEL_4K && rmp_level ==PG_LEVEL_2M ) { + rc =snp_rmptable_psmash (kvm, pfn); +if (rc) +return rc; + } + +return rmp_make_shared (pfn, level); +} + +static int snp_check_and_build_npt (struct kvm_vcpu *vcpu,gpa_t gpa,int level) +{ +struct kvm *kvm = vcpu->kvm;
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2953
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+int rc, npt_level; +kvm_pfn_t pfn; + +/* +* Get the pfn and level for the gpa from the nested page table. +* +* If the tdp walk fails, then its safe to say that there is no +* valid mapping for this gpa. Create a fault to build the map. +*/ +write_lock (&kvm->mmu_lock);
SEV (or any vendor code for that matter) should not be taking mmu_lock. All of KVM has somewhat fungible borders between the various components, but IMO this crosses firmly into "this belongs in the MMU" territory.
For example, I highly doubt this actually need to take mmu_lock for write. More below.
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2955
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+ rc =kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &npt_level); +write_unlock (&kvm->mmu_lock);
What's the point of this walk? As soon as mmu_lock is dropped, all bets are off. At best this is a strong hint. It doesn't hurt anything per se, it's just a waste of cycles.
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2957
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+if (!rc) { + pfn =kvm_mmu_map_tdp_page (vcpu, gpa,PFERR_USER_MASK , level);
Same here.
Quoted 18 lines
arch/x86/kvm/svm/sev.c +18
-0+if (is_error_noslot_pfn (pfn)) +return -EINVAL ; + } + +return 0 ; +} + +static int snp_gpa_to_hva (struct kvm *kvm,gpa_t gpa,hva_t *hva) +{ +struct kvm_memory_slot *slot; +gfn_t gfn =gpa_to_gfn (gpa); +int idx; + + idx =srcu_read_lock (&kvm->srcu); + slot =gfn_to_memslot (kvm, gfn); +if (!slot) { +srcu_read_unlock (&kvm->srcu, idx); +return -EINVAL ;
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2985
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ } + +/* +* Note, using the __gfn_to_hva_memslot() is not solely for performance, +* it's also necessary to avoid the "writable" check in __gfn_to_hva_many(), +* which will always fail on read-only memslots due to gfn_to_hva() assuming +* writes. +*/ + *hva =__gfn_to_hva_memslot (slot, gfn); +srcu_read_unlock (&kvm->srcu, idx);
*hva is effectively invalidated the instance kvm->srcu is unlocked, e.g. a pending memslot update can complete immediately after and delete/move the backing memslot.
Quoted 27 lines
arch/x86/kvm/svm/sev.c +27
-0+ +return 0 ; +} + +static int __snp_handle_page_state_change (struct kvm_vcpu *vcpu,enum psc_op op,gpa_t gpa, +int level) +{ +struct kvm_sev_info *sev = &to_kvm_svm (vcpu->kvm)->sev_info; +struct kvm *kvm = vcpu->kvm; +int rc, npt_level; +kvm_pfn_t pfn; +gpa_t gpa_end; + + gpa_end = gpa +page_level_size (level); + +while (gpa < gpa_end) { +/* +* If the gpa is not present in the NPT then build the NPT. +*/ + rc =snp_check_and_build_npt (vcpu, gpa, level); +if (rc) +return -EINVAL ; + +if (op ==SNP_PAGE_STATE_PRIVATE ) { +hva_t hva; + +if (snp_gpa_to_hva (kvm, gpa, &hva))
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3022
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+return -EINVAL ; + +/* +* Verify that the hva range is registered. This enforcement is +* required to avoid the cases where a page is marked private +* in the RMP table but never gets cleanup during the VM +* termination path. +*/ +mutex_lock (&kvm->lock); + rc =is_hva_registered (kvm, hva,page_level_size (level));
This will get a false negative if a hva+size spans two contiguous regions.
Also, storing a boolean return in a variable that is an int _and_ was already used for the kernel's standard
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3023
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+mutex_unlock (&kvm->lock);
This is also subject to races, e.g. userspace unregisters the hva immediately after this check, before KVM makes whatever conversion it makes below.
A linear walk through a list to find a range is also a bad idea, e.g. pathological worst case scenario is that userspace has created tens of thousands of individual regions. There is no restriction on the number of regions, just the number of pages that can be pinned.
I dislike the svm_(un)register_enc_region() scheme in general, but at least for SEV and SEV-ES the code is isolated, e.g. KVM is little more than a dump pipe to let userspace pin pages. I would like to go the opposite direction and work towards eliminating regions_list (or at least making it optional), not build more stuff on top.
The more I look at this, the more strongly I feel that private <=> shared conversions belong in the MMU, and that KVM's SPTEs should be the single source of truth for shared vs. private. E.g. add a SPTE_TDP_PRIVATE_MASK in the software available bits. I believe the only hiccup is the snafu where not zapping _all_ SPTEs on memslot deletion breaks QEMU+VFIO+GPU, i.e. KVM would lose its canonical info on unrelated memslot deletion.
But that is a solvable problem. Ideally the bug, wherever it is, would be root caused and fixed. I believe Peter (and Marc?) is going to work on reproducing the bug.
If we are unable to root cause and fix the bug, I think a viable workaround would be to clear the hardware present bit in unrelated SPTEs, but keep the SPTEs themselves. The idea mostly the same as the ZAPPED_PRIVATE concept from the initial TDX RFC. MMU notifier invalidations, memslot removal, RMP restoration, etc... would all continue to work since the SPTEs is still there, and KVM's page fault handler could audit any "blocked" SPTE when it's refaulted (I'm pretty sure it'd be impossible for the PFN to change, since any PFN change would require a memslot update or mmu_notifier invalidation).
The downside to that approach is that it would require walking all SPTEs to do a memslot deletion, i.e. we'd lose the "fast zap" behavior. If that's a performance issue, the behavior could be opt-in (but not for SNP/TDX).
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3033
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+if (!rc) +return -EINVAL ; + +/* +* Mark the userspace range unmerable before adding the pages +* in the RMP table. +*/ +mmap_write_lock (kvm->mm); + rc =snp_mark_unmergable (kvm, hva,page_level_size (level)); +mmap_write_unlock (kvm->mm);
As mentioned in an earlier patch, this simply cannot work.
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3040
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+if (rc) +return -EINVAL ; + } + +write_lock (&kvm->mmu_lock); + + rc =kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &npt_level);
Same comment about the bool into int. Though in this case I'd say have kvm_mmu_get_tdp_walk() return 0/-errno, not a bool. Boolean returns for helpers without "is_", "test_", etc... are generally confusing.
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3047
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+if (!rc) { +/* +* This may happen if another vCPU unmapped the page +* before we acquire the lock. Retry the PSC. +*/ +write_unlock (&kvm->mmu_lock); +return 0 ;
How will the caller (guest?) know to retry the PSC if KVM returns "success"?
Quoted 9 lines
arch/x86/kvm/svm/sev.c +9
-0+ } + +/* +* Adjust the level so that we don't go higher than the backing +* page level. +*/ + level =min_t (size_t, level, npt_level); + +trace_kvm_snp_psc (vcpu->vcpu_id, pfn, gpa, op, level);
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3066
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ +switch (op) { +case SNP_PAGE_STATE_SHARED : + rc =snp_make_page_shared (kvm, gpa, pfn, level); +break ; +case SNP_PAGE_STATE_PRIVATE : + rc =rmp_make_private (pfn, gpa, level, sev->asid, false); +break ; +default : + rc = -EINVAL ;
Not that it really matters, because I don't think the MADV_* approach is viable, but this neglects to undo snp_mark_unmergable() on failure.
Quoted 20 lines
arch/x86/kvm/svm/sev.c +17
-0+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); +return rc; + } + + gpa = gpa +page_level_size (level); + } + +return 0 ; +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;
Sean Christopherson
maintainerRe: [PATCH Part2 v5 37/45] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 9 lines · Sean Christopherson
If we are unable to root cause and fix the bug, I think a viable workaround would be to clear the hardware present bit in unrelated SPTEs, but keep the SPTEs themselves. The idea mostly the same as the
ZAPPED_PRIVATEconcept from the initial TDX RFC. MMU notifier invalidations, memslot removal, RMP restoration, etc... would all continue to work since the SPTEs is still there, and KVM's page fault handler could audit any "blocked" SPTE when it's refaulted (I'm pretty sure it'd be impossible for the PFN to change, since any PFN change would require a memslot update ormmu_notifierinvalidation).
Quoted 3 lines
The downside to that approach is that it would require walking all SPTEs to do a memslot deletion, i.e. we'd lose the "fast zap" behavior. If that's a performance issue, the behavior could be opt-in (but not for SNP/TDX).
Another option if we introduce private memslots is to preserve private memslots on unrelated deletions. The argument being that (a) private memslots are a new feature so there's no prior uABI to break, and (b) if not zapping private memslot SPTEs in response to the guest remapping a BAR somehow breaks GPU pass-through, then the bug is all but guaranteed to be somewhere besides KVM's memslot logic.
Re: [PATCH Part2 v5 37/45] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
In reply to Sean ChristophersonQuoted 66 lines · Sean Christopherson
Quoted 51 lines · Brijesh Singh
arch/x86/kvm/svm/sev.c +36
-0@@ -31,6 +31,7 @@#include "svm_ops.h" #include "cpuid.h" #include "trace.h" +#include "mmu.h" #define __ex (x) __kvm_handle_fault_on_reboot(x)@@ -2905,6 +2906,181 @@ static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) svm->vmcb->control.ghcb_gpa = value; } +static int snp_rmptable_psmash (struct kvm *kvm,kvm_pfn_t pfn) +{ + pfn = pfn & ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); + +return psmash (pfn); +} + +static int snp_make_page_shared (struct kvm *kvm,gpa_t gpa,kvm_pfn_t pfn,int level) +{ +int rc, rmp_level; + + rc =snp_lookup_rmpentry (pfn, &rmp_level); +if (rc <0 ) +return -EINVAL ; + +/* If page is not assigned then do nothing */ +if (!rc) +return 0 ; + +/* +* Is the page part of an existing 2MB RMP entry ? Split the 2MB into +* multiple of 4K-page before making the memory shared. +*/ +if (level ==PG_LEVEL_4K && rmp_level ==PG_LEVEL_2M ) { + rc =snp_rmptable_psmash (kvm, pfn); +if (rc) +return rc; + } + +return rmp_make_shared (pfn, level); +} + +static int snp_check_and_build_npt (struct kvm_vcpu *vcpu,gpa_t gpa,int level) +{ +struct kvm *kvm = vcpu->kvm;arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2953
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+int rc, npt_level; +kvm_pfn_t pfn; + +/* +* Get the pfn and level for the gpa from the nested page table. +* +* If the tdp walk fails, then its safe to say that there is no +* valid mapping for this gpa. Create a fault to build the map. +*/ +write_lock (&kvm->mmu_lock);SEV (or any vendor code for that matter) should not be taking
mmu_lock. All of KVM has somewhat fungible borders between the various components, but IMO this crosses firmly into "this belongs in the MMU" territory.
Quoted 8 lines
For example, I highly doubt this actually need to take
mmu_lockfor write. More below.arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2955
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+ rc =kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &npt_level); +write_unlock (&kvm->mmu_lock);What's the point of this walk? As soon as
mmu_lockis dropped, all bets are off. At best this is a strong hint. It doesn't hurt anything per se, it's just a waste of cycles.
I can avoid the walk because the kvm_mmu_map_tdp_page() will return a pfn if the NPT is already built.
Quoted 26 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2957
Quoted 2 lines
arch/x86/kvm/svm/sev.c +2
-0+if (!rc) { + pfn =kvm_mmu_map_tdp_page (vcpu, gpa,PFERR_USER_MASK , level);Same here.
Quoted 22 lines
arch/x86/kvm/svm/sev.c +22
-0+if (is_error_noslot_pfn (pfn)) +return -EINVAL ; + } + +return 0 ; +} + +static int snp_gpa_to_hva (struct kvm *kvm,gpa_t gpa,hva_t *hva) +{ +struct kvm_memory_slot *slot; +gfn_t gfn =gpa_to_gfn (gpa); +int idx; + + idx =srcu_read_lock (&kvm->srcu); + slot =gfn_to_memslot (kvm, gfn); +if (!slot) { +srcu_read_unlock (&kvm->srcu, idx); +return -EINVAL ; + } + +/* +* Note, using the __gfn_to_hva_memslot() is not solely for performance,
Quoted 8 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 2985
Quoted 6 lines
arch/x86/kvm/svm/sev.c +6
-0+* it's also necessary to avoid the "writable" check in __gfn_to_hva_many(), +* which will always fail on read-only memslots due to gfn_to_hva() assuming +* writes. +*/ + *hva =__gfn_to_hva_memslot (slot, gfn); +srcu_read_unlock (&kvm->srcu, idx);*hva is effectively invalidated the instance
kvm->srcuis unlocked, e.g. a pending memslot update can complete immediately after and delete/move the backing memslot.
Fair point, I can rework to do all the hva related updates while we keep the kvm->srcu. More on this below.
Quoted 51 lines
Quoted 27 lines
arch/x86/kvm/svm/sev.c +27
-0+ +return 0 ; +} + +static int __snp_handle_page_state_change (struct kvm_vcpu *vcpu,enum psc_op op,gpa_t gpa, +int level) +{ +struct kvm_sev_info *sev = &to_kvm_svm (vcpu->kvm)->sev_info; +struct kvm *kvm = vcpu->kvm; +int rc, npt_level; +kvm_pfn_t pfn; +gpa_t gpa_end; + + gpa_end = gpa +page_level_size (level); + +while (gpa < gpa_end) { +/* +* If the gpa is not present in the NPT then build the NPT. +*/ + rc =snp_check_and_build_npt (vcpu, gpa, level); +if (rc) +return -EINVAL ; + +if (op ==SNP_PAGE_STATE_PRIVATE ) { +hva_t hva; + +if (snp_gpa_to_hva (kvm, gpa, &hva))arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3022
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+return -EINVAL ; + +/* +* Verify that the hva range is registered. This enforcement is +* required to avoid the cases where a page is marked private +* in the RMP table but never gets cleanup during the VM +* termination path. +*/ +mutex_lock (&kvm->lock); + rc =is_hva_registered (kvm, hva,page_level_size (level));This will get a false negative if a hva+size spans two contiguous regions.
Also, storing a boolean return in a variable that is an int _and_ was already used for the kernel's standard
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3023
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+mutex_unlock (&kvm->lock);This is also subject to races, e.g. userspace unregisters the hva immediately after this check, before KVM makes whatever conversion it makes below.
A linear walk through a list to find a range is also a bad idea, e.g. pathological worst case scenario is that userspace has created tens of thousands of individual regions. There is no restriction on the number of regions, just the number of pages that can be pinned.
Quoted 5 lines
I dislike the svm_(un)register_enc_region() scheme in general, but at least for SEV and SEV-ES the code is isolated, e.g. KVM is little more than a dump pipe to let userspace pin pages. I would like to go the opposite direction and work towards eliminating
regions_list(or at least making it optional), not build more stuff on top.
If we don't nuke the page from the direct map and region_list removed then we no longer need to have all the above complexity in the PSC. PSC can be as simple as 1) map the page in NPF and 2) update the RMP table.
Quoted 10 lines
The more I look at this, the more strongly I feel that private <=> shared conversions belong in the MMU, and that KVM's SPTEs should be the single source of truth for shared vs. private. E.g. add a
SPTE_TDP_PRIVATE_MASKin the software available bits. I believe the only hiccup is the snafu where not zapping _all_ SPTEs on memslot deletion breaks QEMU+VFIO+GPU, i.e. KVM would lose its canonical info on unrelated memslot deletion.But that is a solvable problem. Ideally the bug, wherever it is, would be root caused and fixed. I believe Peter (and Marc?) is going to work on reproducing the bug.
We have been also setting up VM with Qemu + VFIO + GPU usecase to repro the bug on AMD HW and so far we no luck in reproducing it. Will continue stressing the system to recreate it. Lets hope that Peter (and Marc) can easily recreate on Intel HW so that we can work towards fixing it.
Quoted 14 lines
If we are unable to root cause and fix the bug, I think a viable workaround would be to clear the hardware present bit in unrelated SPTEs, but keep the SPTEs themselves. The idea mostly the same as the
ZAPPED_PRIVATEconcept from the initial TDX RFC. MMU notifier invalidations, memslot removal, RMP restoration, etc... would all continue to work since the SPTEs is still there, and KVM's page fault handler could audit any "blocked" SPTE when it's refaulted (I'm pretty sure it'd be impossible for the PFN to change, since any PFN change would require a memslot update ormmu_notifierinvalidation).The downside to that approach is that it would require walking all SPTEs to do a memslot deletion, i.e. we'd lose the "fast zap" behavior. If that's a performance issue, the behavior could be opt-in (but not for SNP/TDX).
Quoted 11 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3033
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+if (!rc) +return -EINVAL ; + +/* +* Mark the userspace range unmerable before adding the pages +* in the RMP table. +*/ +mmap_write_lock (kvm->mm); + rc =snp_mark_unmergable (kvm, hva,page_level_size (level)); +mmap_write_unlock (kvm->mm);As mentioned in an earlier patch, this simply cannot work.
As discussed in the previous patches, will drop the support for nuking the page from direct map; this will keep ksm happy and no need to mark vma unmergable.
Quoted 12 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3040
Quoted 8 lines
arch/x86/kvm/svm/sev.c +7
-0+if (rc) +return -EINVAL ; + } + +write_lock (&kvm->mmu_lock); + + rc =kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &npt_level);Same comment about the bool into int. Though in this case I'd say have
kvm_mmu_get_tdp_walk()return 0/-errno, not a bool. Boolean returns for helpers without "is_", "test_", etc... are generally confusing.
Quoted 8 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3047
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+if (!rc) { +/* +* This may happen if another vCPU unmapped the page +* before we acquire the lock. Retry the PSC. +*/ +write_unlock (&kvm->mmu_lock); +return 0 ;How will the caller (guest?) know to retry the PSC if KVM returns "success"?
If a guest is adhering to the GHCB spec then it will see that hypervisor has not processed all the entry and it should retry the PSC.
Quoted 42 lines
Quoted 9 lines
arch/x86/kvm/svm/sev.c +9
-0+ } + +/* +* Adjust the level so that we don't go higher than the backing +* page level. +*/ + level =min_t (size_t, level, npt_level); + +trace_kvm_snp_psc (vcpu->vcpu_id, pfn, gpa, op, level);arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3066
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ +switch (op) { +case SNP_PAGE_STATE_SHARED : + rc =snp_make_page_shared (kvm, gpa, pfn, level); +break ; +case SNP_PAGE_STATE_PRIVATE : + rc =rmp_make_private (pfn, gpa, level, sev->asid, false); +break ; +default : + rc = -EINVAL ;Not that it really matters, because I don't think the MADV_* approach is viable, but this neglects to undo
snp_mark_unmergable()on failure.Quoted 20 lines
arch/x86/kvm/svm/sev.c +17
-0+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); +return rc; + } + + gpa = gpa +page_level_size (level); + } + +return 0 ; +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;
Sean Christopherson
maintainerRe: [PATCH Part2 v5 37/45] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 7 lines · Brijesh Singh
Quoted 7 lines
The more I look at this, the more strongly I feel that private <=> shared conversions belong in the MMU, and that KVM's SPTEs should be the single source of truth for shared vs. private. E.g. add a
SPTE_TDP_PRIVATE_MASKin the software available bits. I believe the only hiccup is the snafu where not zapping _all_ SPTEs on memslot deletion breaks QEMU+VFIO+GPU, i.e. KVM would lose its canonical info on unrelated memslot deletion.
Quoted 7 lines
Quoted 3 lines
But that is a solvable problem. Ideally the bug, wherever it is, would be root caused and fixed. I believe Peter (and Marc?) is going to work on reproducing the bug.
We have been also setting up VM with Qemu + VFIO + GPU usecase to repro the bug on AMD HW and so far we no luck in reproducing it. Will continue stressing the system to recreate it. Lets hope that Peter (and Marc) can easily recreate on Intel HW so that we can work towards fixing it.
Are you trying on a modern kernel? If so, double check that nx_huge_pages is off, turning that on caused the bug to disappear. It should be off for AMD systems, but it's worth checking.
Quoted 11 lines
Quoted 8 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3047
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+if (!rc) { +/* +* This may happen if another vCPU unmapped the page +* before we acquire the lock. Retry the PSC. +*/ +write_unlock (&kvm->mmu_lock); +return 0 ;How will the caller (guest?) know to retry the PSC if KVM returns "success"?
If a guest is adhering to the GHCB spec then it will see that hypervisor has not processed all the entry and it should retry the PSC.
But AFAICT that information isn't passed to the guest. Even in this single-page MSR-based case, the caller will say "all good" on a return of 0.
The "full" path is more obvious, as the caller clearly continues to process entries unless there's an actual failure.
+ for (; cur <= end; cur++) {
+ entry = &info->entries[cur]; + 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;
+ }
+
+ rc = __snp_handle_page_state_change(vcpu, op, gpa, level);
+ if (rc)
+ goto out;
+ }
Re: [PATCH Part2 v5 37/45] KVM: SVM: Add support to handle MSR based Page State Change VMGEXIT
Quoted 11 lines · Sean Christopherson
Quoted 10 lines · Brijesh Singh
Quoted 10 lines
The more I look at this, the more strongly I feel that private <=> shared conversions belong in the MMU, and that KVM's SPTEs should be the single source of truth for shared vs. private. E.g. add a
SPTE_TDP_PRIVATE_MASKin the software available bits. I believe the only hiccup is the snafu where not zapping _all_ SPTEs on memslot deletion breaks QEMU+VFIO+GPU, i.e. KVM would lose its canonical info on unrelated memslot deletion.But that is a solvable problem. Ideally the bug, wherever it is, would be root caused and fixed. I believe Peter (and Marc?) is going to work on reproducing the bug.
Quoted 7 lines
Quoted 4 lines
We have been also setting up VM with Qemu + VFIO + GPU usecase to repro the bug on AMD HW and so far we no luck in reproducing it. Will continue stressing the system to recreate it. Lets hope that Peter (and Marc) can easily recreate on Intel HW so that we can work towards fixing it.
Are you trying on a modern kernel? If so, double check that
nx_huge_pagesis off, turning that on caused the bug to disappear. It should be off for AMD systems, but it's worth checking.
Yes, this is a recent kernel. I will double check the nx_huge_pages is off.
Quoted 22 lines
Quoted 10 lines
Quoted 8 lines
arch/x86/kvm/svm/sev.c static void set_ghcb_msr(struct vcpu_svm *svm, u64 value) · line 3047
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7
-0+if (!rc) { +/* +* This may happen if another vCPU unmapped the page +* before we acquire the lock. Retry the PSC. +*/ +write_unlock (&kvm->mmu_lock); +return 0 ;How will the caller (guest?) know to retry the PSC if KVM returns "success"?
If a guest is adhering to the GHCB spec then it will see that hypervisor has not processed all the entry and it should retry the PSC.
But AFAICT that information isn't passed to the guest. Even in this single-page MSR-based case, the caller will say "all good" on a return of 0.
The "full" path is more obvious, as the caller clearly continues to process entries unless there's an actual failure.
(quoted diff) +5
-0+ for (; cur <= end; cur++) { + entry = &info->entries[cur]; + gpa = gfn_to_gpa(entry->gfn); + level = RMP_TO_X86_PG_LEVEL(entry->pagesize); + op = entry->operation;
Review
Quoted 10 lines
(quoted diff) +10
-0+ + if (!IS_ALIGNED(gpa, page_level_size(level))) { + rc = PSC_INVALID_ENTRY; + goto out; + } + + rc = __snp_handle_page_state_change(vcpu, op, gpa, level); + if (rc) + goto out; + }
Please see the guest kernel patch #19 [1]. In spec there is no special code for the retry. The guest will look at the PSC hdr to determine how many entries were processed by the hypervisor (in this particular case a 0). And at time the guest can do whatever it wants. In the case of Linux guest, we retry the PSC.
[1]
https://lore.kernel.org/linux-mm/[email protected]/
thanks
PATCH v5 38/45 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 version 2.
--- arch/x86/include/asm/sev-common.h | 7 +++ arch/x86/kvm/svm/sev.c | 82 +++++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 5 deletions(-)
arch/x86/include/asm/sev-common.h +7 -0
@@ -126,6 +126,13 @@ enum psc_op {/* 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 psc_hdr {u16 cur_entry;u16 end_entry;
arch/x86/kvm/svm/sev.c +77 -5
130 lines not on this page · raw message
Signature · 1 line
2.17.1
Re: [PATCH Part2 v5 38/45] KVM: SVM: Add support to handle Page State Change VMGEXIT
Quoted 92 lines · * Brijesh Singh ([email protected]) wrote:
SEV-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 version 2.
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/sev-common.h | 7 +++ arch/x86/kvm/svm/sev.c | 82 +++++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 5 deletions(-)arch/x86/include/asm/sev-common.h +7
-0@@ -126,6 +126,13 @@ enum psc_op {/* 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 psc_hdr {u16 cur_entry;u16 end_entry;arch/x86/kvm/svm/sev.c +10
-5@@ -2731,6 +2731,7 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm, u64 *exit_code)case SVM_VMGEXIT_AP_JUMP_TABLE :case SVM_VMGEXIT_UNSUPPORTED_EVENT :case SVM_VMGEXIT_HV_FEATURES : +case SVM_VMGEXIT_PSC :break ;default : goto vmgexit_err;@@ -3004,13 +3005,13 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op,*/ rc =snp_check_and_build_npt (vcpu, gpa, level);if (rc) -return -EINVAL ; +return PSC_UNDEF_ERR ;if (op ==SNP_PAGE_STATE_PRIVATE ) {hva_t hva;if (snp_gpa_to_hva (kvm, gpa, &hva)) -return -EINVAL ; +return PSC_UNDEF_ERR ;/* * Verify that the hva range is registered. This enforcement is @@ -3022,7 +3023,7 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op, rc =is_hva_registered (kvm, hva,page_level_size (level));mutex_unlock (&kvm->lock);if (!rc) -return -EINVAL ; +return PSC_UNDEF_ERR ;/* * Mark the userspace range unmerable before adding the pages @@ -3032,7 +3033,7 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op, rc =snp_mark_unmergable (kvm, hva,page_level_size (level));mmap_write_unlock (kvm->mm);if (rc) -return -EINVAL ; +return PSC_UNDEF_ERR ; }write_lock (&kvm->mmu_lock);@@ -3062,8 +3063,11 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op,case SNP_PAGE_STATE_PRIVATE : rc =rmp_make_private (pfn, gpa, level, sev->asid, false);break ; +case SNP_PAGE_STATE_PSMASH : +case SNP_PAGE_STATE_UNSMASH : +/* TODO: Add support to handle it */ default : - rc = -EINVAL ; + rc =PSC_INVALID_ENTRY ;break ; }@@ -3081,6 +3085,65 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op,return 0 ; } +static inline unsigned long map_to_psc_vmgexit_code (int rc)
arch/x86/kvm/svm/sev.c static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op, · line 3098
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+{ +switch (rc) { +case PSC_INVALID_HDR : +return ((1ul <<32 ) |1 ); +case PSC_INVALID_ENTRY : +return ((1ul <<32 ) |2 ); +case RMPUPDATE_FAIL_OVERLAP : +return ((3ul <<32 ) |2 ); +default :return (4ul <<32 ); + }
Are these the values defined in 56421 section 4.1.6 ?
If so, that says:
SW_EXITINFO2[63:32] == 0x00000100
The hypervisor encountered some other error situation and was not able to complete the request identified by page_state_change_header.cur_entry. It is left to the guest to decide how to proceed in this situation.
so it looks like the default should be 0x100 rather than 4?
(It's a shame they're all magical constants, it would be nice if the standard have them names)
Dave
Quoted 71 lines
arch/x86/kvm/svm/sev.c +57
-0+} + +static unsigned long snp_handle_page_state_change (struct vcpu_svm *svm) +{ +struct kvm_vcpu *vcpu = &svm->vcpu; +int level, op, rc =PSC_UNDEF_ERR ; +struct snp_psc_desc *info; +struct psc_entry *entry; +u16 cur, end; +gpa_t gpa; + +if (!sev_snp_guest (vcpu->kvm)) +return PSC_INVALID_HDR ; + +if (!setup_vmgexit_scratch (svm, true,sizeof (*info))) { +pr_err ("vmgexit: scratch area is not setup.\n" ); +return PSC_INVALID_HDR ; + } + + info = (struct snp_psc_desc *)svm->ghcb_sa; + cur = info->hdr.cur_entry; + end = info->hdr.end_entry; + +if (cur >=VMGEXIT_PSC_MAX_ENTRY || + end >=VMGEXIT_PSC_MAX_ENTRY || cur > end) +return PSC_INVALID_ENTRY ; + +for (; cur <= end; cur++) { + entry = &info->entries[cur]; + 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; + } + + rc =__snp_handle_page_state_change (vcpu, op, gpa, level); +if (rc) + goto out; + } + +out: + info->hdr.cur_entry = cur; +return rc ?map_to_psc_vmgexit_code (rc) :0 ; +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;@@ -3315,6 +3378,15 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu) ret =1 ;break ; } +case SVM_VMGEXIT_PSC : { +unsigned long rc; + + ret =1 ; + + rc =snp_handle_page_state_change (svm); +svm_set_ghcb_sw_exit_info_2 (vcpu, rc); +break ; + }case SVM_VMGEXIT_UNSUPPORTED_EVENT : vcpu_unimpl(vcpu, "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",Signature · 1 line
2.17.1
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
Re: [PATCH Part2 v5 38/45] KVM: SVM: Add support to handle Page State Change VMGEXIT
Quoted 110 lines · Dr. David Alan Gilbert
Quoted 92 lines · * Brijesh Singh ([email protected]) wrote:
SEV-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 version 2.
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/include/asm/sev-common.h | 7 +++ arch/x86/kvm/svm/sev.c | 82 +++++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 5 deletions(-)arch/x86/include/asm/sev-common.h +7
-0@@ -126,6 +126,13 @@ enum psc_op {/* 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 psc_hdr {u16 cur_entry;u16 end_entry;arch/x86/kvm/svm/sev.c +10
-5@@ -2731,6 +2731,7 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm, u64 *exit_code)case SVM_VMGEXIT_AP_JUMP_TABLE :case SVM_VMGEXIT_UNSUPPORTED_EVENT :case SVM_VMGEXIT_HV_FEATURES : +case SVM_VMGEXIT_PSC :break ;default : goto vmgexit_err;@@ -3004,13 +3005,13 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op,*/ rc =snp_check_and_build_npt (vcpu, gpa, level);if (rc) -return -EINVAL ; +return PSC_UNDEF_ERR ;if (op ==SNP_PAGE_STATE_PRIVATE ) {hva_t hva;if (snp_gpa_to_hva (kvm, gpa, &hva)) -return -EINVAL ; +return PSC_UNDEF_ERR ;/* * Verify that the hva range is registered. This enforcement is @@ -3022,7 +3023,7 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op, rc =is_hva_registered (kvm, hva,page_level_size (level));mutex_unlock (&kvm->lock);if (!rc) -return -EINVAL ; +return PSC_UNDEF_ERR ;/* * Mark the userspace range unmerable before adding the pages @@ -3032,7 +3033,7 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op, rc =snp_mark_unmergable (kvm, hva,page_level_size (level));mmap_write_unlock (kvm->mm);if (rc) -return -EINVAL ; +return PSC_UNDEF_ERR ; }write_lock (&kvm->mmu_lock);@@ -3062,8 +3063,11 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op,case SNP_PAGE_STATE_PRIVATE : rc =rmp_make_private (pfn, gpa, level, sev->asid, false);break ; +case SNP_PAGE_STATE_PSMASH : +case SNP_PAGE_STATE_UNSMASH : +/* TODO: Add support to handle it */ default : - rc = -EINVAL ; + rc =PSC_INVALID_ENTRY ;break ; }@@ -3081,6 +3085,65 @@ static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op,return 0 ; } +static inline unsigned long map_to_psc_vmgexit_code (int rc)arch/x86/kvm/svm/sev.c static int __snp_handle_page_state_change(struct kvm_vcpu *vcpu, enum psc_op op, · line 3098
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+{ +switch (rc) { +case PSC_INVALID_HDR : +return ((1ul <<32 ) |1 ); +case PSC_INVALID_ENTRY : +return ((1ul <<32 ) |2 ); +case RMPUPDATE_FAIL_OVERLAP : +return ((3ul <<32 ) |2 ); +default :return (4ul <<32 ); + }Are these the values defined in 56421 section 4.1.6 ?
If so, that says:
SW_EXITINFO2[63:32] ==0x00000100
The hypervisor encountered some other error situation and was not able to complete the request identified by page_state_change_header.cur_entry. It is left to the guest to decide how to proceed in this situation.
Quoted 1 line
so it looks like the default should be
0x100rather than 4?
Ah good catch, it should be 0x100. I will fix it.
Quoted 2 lines
(It's a shame they're all magical constants, it would be nice if the standard have them names)
In early RFC's I had a macros to build the error code but based on feedback's went with this function with open coded values.
thanks
PATCH v5 39/45 KVM: SVM: Introduce ops for the post gfn map and unmap
In reply to Brijesh SinghWhen 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 #PF.
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
--- arch/x86/include/asm/kvm-x86-ops.h | 2 + arch/x86/include/asm/kvm_host.h | 4 ++ arch/x86/kvm/svm/sev.c | 69 +++++++++++++++++++++----- arch/x86/kvm/svm/svm.c | 4 ++ arch/x86/kvm/svm/svm.h | 8 +++ arch/x86/kvm/x86.c | 78 +++++++++++++++++++++++++++--- 6 files changed, 146 insertions(+), 19 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
@@ -124,6 +124,8 @@ KVM_X86_OP(msr_filter_changed) KVM_X86_OP_NULL(complete_emulated_msr) KVM_X86_OP(alloc_apic_backing_page) KVM_X86_OP_NULL(rmp_page_level_adjust) +KVM_X86_OP(post_map_gfn) +KVM_X86_OP(post_unmap_gfn) #undef KVM_X86_OP#undef KVM_X86_OP_NULL
arch/x86/include/asm/kvm_host.h +4 -0
@@ -1463,7 +1463,11 @@ struct kvm_x86_ops {void (*vcpu_deliver_sipi_vector)(struct kvm_vcpu *vcpu,u8 vector);void *(*alloc_apic_backing_page)(struct kvm_vcpu *vcpu); +void (*rmp_page_level_adjust)(struct kvm *kvm,kvm_pfn_t pfn,int *level); + +int (*post_map_gfn)(struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token); +void (*post_unmap_gfn)(struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int token); };struct kvm_x86_nested_ops {
arch/x86/kvm/svm/sev.c +58 -11
154 lines not on this page · raw message
arch/x86/kvm/svm/svm.c +4 -0
@@ -4679,7 +4679,11 @@ 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, + .rmp_page_level_adjust = sev_rmp_page_level_adjust, + + .post_map_gfn = sev_post_map_gfn, + .post_unmap_gfn = sev_post_unmap_gfn, };static struct kvm_x86_init_ops svm_init_ops__initdata = {
arch/x86/kvm/svm/svm.h +8 -0
@@ -76,16 +76,22 @@ 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 */ +unsigned long pages_locked;/* Number of pages locked */ struct list_head regions_list;/* List of registered regions */ +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 */ +u64 snp_init_flags;void *snp_context;/* SNP guest context page */ +struct srcu_struct psc_srcu; };struct kvm_svm {
@@ -618,6 +624,8 @@ 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);void sev_rmp_page_level_adjust (struct kvm *kvm,kvm_pfn_t pfn,int *level); +int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token); +void sev_post_unmap_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int token);/* vmenter.S */
arch/x86/kvm/x86.c +70 -8
138 lines not on this page · raw message
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 8 lines · Brijesh Singh
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 #PF.
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The synchronize_srcu_expedited() in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ the synchronize_srcu_expedited() call.
This also doesn't handle kvm_{read,write}_guest_cached().
I can't help but note that the private memslots idea[*] would handle this gracefully, e.g. the memslot lookup would fail, and any change in private memslots would invalidate the cache due to a generation mismatch.
KSM is another mess that would Just Work.
I'm not saying that SNP should be blocked on support for unmapping guest private memory, but I do think we should strongly consider focusing on that effort rather than trying to fix things piecemeal throughout KVM. I don't think it's too absurd to say that it might actually be faster overall. And I 100% think that having a cohesive design and uABI for SNP and TDX would be hugely beneficial to KVM.
[*] https://lkml.kernel.org/r/[email protected]
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3635
Quoted 11 lines
arch/x86/kvm/svm/sev.c +11
-0+int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token) +{ +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +int level; + +if (!sev_snp_guest (kvm)) +return 0 ; + + *token =srcu_read_lock (&sev->psc_srcu); + +/* If pfn is not added as private then fail */
This comment and the pr_err() are backwards, and confused the heck out of me. snp_lookup_rmpentry() returns '1' if the pfn is assigned, a.k.a. private. That means this code throws an error if the page is private, i.e. requires the page to be shared. Which makes sense given the use cases, it's just incredibly confusing.
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3636
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+if (snp_lookup_rmpentry (pfn, &level) ==1 ) {
Any reason not to provide e.g. rmp_is_shared() and rmp_is_private() so that callers don't have to care as much about the return values? The -errno/0/1 semantics are all but guarantee to bite us in the rear at some point.
Actually, peeking at other patches, I think it already has. This usage in __unregister_enc_region_locked() is wrong:
/*
* 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 (!snp_lookup_rmpentry(pfn, &level)) <-- attempts make_shared() on non-existent entry
continue;
cond_resched();
if (level > PG_LEVEL_4K)
pfn &= ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1);
host_rmp_make_shared(pfn, level, true);
}
}Quoted 19 lines
arch/x86/kvm/svm/sev.c +7
-0+srcu_read_unlock (&sev->psc_srcu, *token); +pr_err_ratelimited ("failed to map private gfn 0x%llx pfn 0x%llx\n" , gfn, pfn); +return -EBUSY ; + } + +return 0 ; +}static struct kvm_x86_init_ops svm_init_ops__initdata = {arch/x86/kvm/svm/svm.h +1
-0@@ -76,16 +76,22 @@ 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 */
arch/x86/kvm/svm/svm.h struct kvm_sev_info { · line 91
Quoted 10 lines
arch/x86/kvm/svm/svm.h +4
-0int fd;/* SEV device fd */ +unsigned long pages_locked;/* Number of pages locked */ struct list_head regions_list;/* List of registered regions */ +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 */ +
Unrelated whitespace changes.
Quoted 4 lines
arch/x86/kvm/svm/svm.h +1
-0u64 snp_init_flags;void *snp_context;/* SNP guest context page */ +struct srcu_struct psc_srcu; };
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 9 lines · Sean Christopherson
Quoted 8 lines · Brijesh Singh
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 #PF.
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
Quoted 6 lines
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.This also doesn't handle kvm_{read,write}_guest_cached().
Hmm, I thought the kvm_{read_write}_guest_cached() uses the copy_{to,from}_user(). Writing to the private will cause a #PF and will fail the copy_to_user(). Am I missing something?
Quoted 15 lines
I can't help but note that the private memslots idea[*] would handle this gracefully, e.g. the memslot lookup would fail, and any change in private memslots would invalidate the cache due to a generation mismatch.
KSM is another mess that would Just Work.
I'm not saying that SNP should be blocked on support for unmapping guest private memory, but I do think we should strongly consider focusing on that effort rather than trying to fix things piecemeal throughout KVM. I don't think it's too absurd to say that it might actually be faster overall. And I 100% think that having a cohesive design and uABI for SNP and TDX would be hugely beneficial to KVM.
Quoted 16 lines
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3635
Quoted 11 lines
arch/x86/kvm/svm/sev.c +11
-0+int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token) +{ +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +int level; + +if (!sev_snp_guest (kvm)) +return 0 ; + + *token =srcu_read_lock (&sev->psc_srcu); + +/* If pfn is not added as private then fail */ This comment and the
pr_err()are backwards, and confused the heck out of me.snp_lookup_rmpentry()returns '1' if the pfn is assigned, a.k.a. private. That means this code throws an error if the page is private, i.e. requires the page to be shared. Which makes sense given the use cases, it's just incredibly confusing.
Actually I followed your recommendation from the previous feedback that snp_lookup_rmpentry() should return 1 for the assigned page, 0 for the shared and -negative for invalid. I can clarify it here again.
Quoted 5 lines
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3636
Quoted 2 lines
arch/x86/kvm/svm/sev.c +1
-0+if (snp_lookup_rmpentry (pfn, &level) ==1 ) {Any reason not to provide e.g.
rmp_is_shared()andrmp_is_private()so that callers don't have to care as much about the return values? The -errno/0/1 semantics are all but guarantee to bite us in the rear at some point.
If we look at the previous series, I had a macro rmp_is_assigned() for exactly the same purpose but the feedback was to drop those macros and return the state indirectly through the snp_lookup_rmpentry(). I can certainly add a helper rmp_is_{shared,private}() if it makes code more readable.
Quoted 59 lines
Actually, peeking at other patches, I think it already has. This usage in
__unregister_enc_region_locked()is wrong:/* * 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 (!snp_lookup_rmpentry(pfn, &level)) <-- attempts make_shared() on non-existent entry continue; cond_resched(); if (level > PG_LEVEL_4K) pfn &= ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1); host_rmp_make_shared(pfn, level, true); } }Quoted 19 lines
arch/x86/kvm/svm/sev.c +7
-0+srcu_read_unlock (&sev->psc_srcu, *token); +pr_err_ratelimited ("failed to map private gfn 0x%llx pfn 0x%llx\n" , gfn, pfn); +return -EBUSY ; + } + +return 0 ; +}static struct kvm_x86_init_ops svm_init_ops__initdata = {arch/x86/kvm/svm/svm.h +1
-0@@ -76,16 +76,22 @@ 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 */ arch/x86/kvm/svm/svm.h struct kvm_sev_info { · line 91
Quoted 10 lines
arch/x86/kvm/svm/svm.h +4
-0int fd;/* SEV device fd */ +unsigned long pages_locked;/* Number of pages locked */ struct list_head regions_list;/* List of registered regions */ +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 */ +Unrelated whitespace changes.
Quoted 4 lines
arch/x86/kvm/svm/svm.h +1
-0u64 snp_init_flags;void *snp_context;/* SNP guest context page */ +struct srcu_struct psc_srcu; };
Sean Christopherson
maintainerRe: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 16 lines · Brijesh Singh
Quoted 14 lines · Sean Christopherson
Quoted 8 lines · Brijesh Singh
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 #PF.
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.
Quoted 5 lines
Quoted 1 line
This also doesn't handle kvm_{read,write}_guest_cached().
Hmm, I thought the kvm_{read_write}_guest_cached() uses the copy_{to,from}_user(). Writing to the private will cause a #PF and will fail the
copy_to_user(). Am I missing something?
Doh, right you are. I was thinking they cached the kmap, but it's just the gpa->hva that gets cached.
Quoted 39 lines
Quoted 14 lines
I can't help but note that the private memslots idea[*] would handle this gracefully, e.g. the memslot lookup would fail, and any change in private memslots would invalidate the cache due to a generation mismatch.
KSM is another mess that would Just Work.
I'm not saying that SNP should be blocked on support for unmapping guest private memory, but I do think we should strongly consider focusing on that effort rather than trying to fix things piecemeal throughout KVM. I don't think it's too absurd to say that it might actually be faster overall. And I 100% think that having a cohesive design and uABI for SNP and TDX would be hugely beneficial to KVM.
Quoted 16 lines
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3635
Quoted 11 lines
arch/x86/kvm/svm/sev.c +11
-0+int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token) +{ +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +int level; + +if (!sev_snp_guest (kvm)) +return 0 ; + + *token =srcu_read_lock (&sev->psc_srcu); + +/* If pfn is not added as private then fail */ This comment and the
pr_err()are backwards, and confused the heck out of me.snp_lookup_rmpentry()returns '1' if the pfn is assigned, a.k.a. private. That means this code throws an error if the page is private, i.e. requires the page to be shared. Which makes sense given the use cases, it's just incredibly confusing.Actually I followed your recommendation from the previous feedback that
snp_lookup_rmpentry()should return 1 for the assigned page, 0 for the shared and -negative for invalid. I can clarify it here again.Quoted 4 lines
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3636
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+if (snp_lookup_rmpentry (pfn, &level) ==1 ) {Any reason not to provide e.g.
rmp_is_shared()andrmp_is_private()so that callers don't have to care as much about the return values? The -errno/0/1 semantics are all but guarantee to bite us in the rear at some point.
Quoted 5 lines
If we look at the previous series, I had a macro
rmp_is_assigned()for exactly the same purpose but the feedback was to drop those macros and return the state indirectly through thesnp_lookup_rmpentry(). I can certainly add a helper rmp_is_{shared,private}() if it makes code more readable.
Ah rats. Bad communication on my side. I didn't intended to have non-RMP code directly consume snp_lookup_rmpentry() for simple checks. The goal behind the helper was to bury "struct rmpentry" so that it wasn't visible to the kernel at large. I.e. my objection was that rmp_assigned() was looking directly at a non-architectural struct.
My full thought for snp_lookup_rmpentry() was that it _could_ be consumed directly without exposing "struct rmpentry", but that simple, common use cases would provide wrappers, e.g.
static inline snp_is_rmp_private(...)
{
return snp_lookup_rmpentry(...) == 1;
}static inline snp_is_rmp_shared(...)
{
return snp_lookup_rmpentry(...) < 1;
}Side topic, what do you think about s/assigned/private for the "public" APIs, as suggested/implied above? I actually like the terminology when talking specifically about the RMP, but it doesn't fit the abstractions that tend to be used when talking about these things in other contexts, e.g. in KVM.
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 77 lines · Sean Christopherson
Quoted 15 lines · Brijesh Singh
Quoted 14 lines · Sean Christopherson
Quoted 8 lines · Brijesh Singh
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 #PF.
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.Quoted 4 lines
Quoted 1 line
This also doesn't handle kvm_{read,write}_guest_cached().
Hmm, I thought the kvm_{read_write}_guest_cached() uses the copy_{to,from}_user(). Writing to the private will cause a #PF and will fail the
copy_to_user(). Am I missing something?Doh, right you are. I was thinking they cached the kmap, but it's just the
gpa->hvathat gets cached.Quoted 38 lines
Quoted 14 lines
I can't help but note that the private memslots idea[*] would handle this gracefully, e.g. the memslot lookup would fail, and any change in private memslots would invalidate the cache due to a generation mismatch.
KSM is another mess that would Just Work.
I'm not saying that SNP should be blocked on support for unmapping guest private memory, but I do think we should strongly consider focusing on that effort rather than trying to fix things piecemeal throughout KVM. I don't think it's too absurd to say that it might actually be faster overall. And I 100% think that having a cohesive design and uABI for SNP and TDX would be hugely beneficial to KVM.
Quoted 16 lines
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3635
Quoted 11 lines
arch/x86/kvm/svm/sev.c +11
-0+int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token) +{ +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info; +int level; + +if (!sev_snp_guest (kvm)) +return 0 ; + + *token =srcu_read_lock (&sev->psc_srcu); + +/* If pfn is not added as private then fail */ This comment and the
pr_err()are backwards, and confused the heck out of me.snp_lookup_rmpentry()returns '1' if the pfn is assigned, a.k.a. private. That means this code throws an error if the page is private, i.e. requires the page to be shared. Which makes sense given the use cases, it's just incredibly confusing.Actually I followed your recommendation from the previous feedback that
snp_lookup_rmpentry()should return 1 for the assigned page, 0 for the shared and -negative for invalid. I can clarify it here again.Quoted 4 lines
arch/x86/kvm/svm/sev.c void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level) · line 3636
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+if (snp_lookup_rmpentry (pfn, &level) ==1 ) {Any reason not to provide e.g.
rmp_is_shared()andrmp_is_private()so that callers don't have to care as much about the return values? The -errno/0/1 semantics are all but guarantee to bite us in the rear at some point.Quoted 5 lines
If we look at the previous series, I had a macro
rmp_is_assigned()for exactly the same purpose but the feedback was to drop those macros and return the state indirectly through thesnp_lookup_rmpentry(). I can certainly add a helper rmp_is_{shared,private}() if it makes code more readable.Ah rats. Bad communication on my side. I didn't intended to have non-RMP code directly consume
snp_lookup_rmpentry()for simple checks. The goal behind the helper was to bury "struct rmpentry" so that it wasn't visible to the kernel at large. I.e. my objection was thatrmp_assigned()was looking directly at a non-architectural struct.My full thought for
snp_lookup_rmpentry()was that it _could_ be consumed directly without exposing "struct rmpentry", but that simple, common use cases would provide wrappers, e.g.static inline
snp_is_rmp_private(...)
Quoted 8 lines
{ return snp_lookup_rmpentry(...) == 1; }static inline
snp_is_rmp_shared(...){ return snp_lookup_rmpentry(...) < 1; }
Yep, that what I was going to do for the helper.
Quoted 5 lines
Side topic, what do you think about s/assigned/private for the "public" APIs, as suggested/implied above? I actually like the terminology when talking specifically about the RMP, but it doesn't fit the abstractions that tend to be used when talking about these things in other contexts, e.g. in KVM.
I can float the idea to see if docs folks is okay with the changes but generally speaking we all have been referring the assigned == private in the Linux SNP support patch.
thanks
Sean Christopherson
maintainerRe: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 10 lines · Brijesh Singh
Quoted 4 lines · Sean Christopherson
Side topic, what do you think about s/assigned/private for the "public" APIs, as suggested/implied above? I actually like the terminology when talking specifically about the RMP, but it doesn't fit the abstractions that tend to be used when talking about these things in other contexts, e.g. in KVM.
I can float the idea to see if docs folks is okay with the changes but generally speaking we all have been referring the assigned == private in the Linux SNP support patch.
Oh, I wasn't suggesting anything remotely close to an "official" change, it was purely a suggestion for the host-side patches. It might even be unique to this one helper.
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Brijesh Singh
Quoted 4 lines · Sean Christopherson
Side topic, what do you think about s/assigned/private for the "public" APIs, as suggested/implied above? I actually like the terminology when talking specifically about the RMP, but it doesn't fit the abstractions that tend to be used when talking about these things in other contexts, e.g. in KVM.
Quoted 6 lines
Quoted 3 lines
I can float the idea to see if docs folks is okay with the changes but generally speaking we all have been referring the assigned == private in the Linux SNP support patch.
Oh, I wasn't suggesting anything remotely close to an "official" change, it was purely a suggestion for the host-side patches. It might even be unique to this one helper.
Ah, sure I am good with calling a private in the helper.
-Brijesh
Sean Christopherson
maintainerRe: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
In reply to Sean ChristophersonQuoted 6 lines · Sean Christopherson
Quoted 5 lines · Brijesh Singh
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 #PF.
Quoted 8 lines
Quoted 3 lines
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.
Argh, another goof on my part. Rereading prior feedback, I see that I loosely suggested SRCU as a possible solution. That was a bad, bad suggestion. I think (hope) I made it offhand without really thinking it through. SRCU can't work in this case, because the whole premise of Read-Copy-Update is that there can be multiple copies of the data. That simply can't be true for the RMP as hardware operates on a single table.
In the future, please don't hesitate to push back on and/or question suggestions, especially those that are made without concrete examples, i.e. are likely off the cuff. My goal isn't to set you up for failure :-/
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 21 lines · Sean Christopherson
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Brijesh Singh
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 #PF.
Quoted 7 lines
Quoted 3 lines
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.Argh, another goof on my part. Rereading prior feedback, I see that I loosely suggested SRCU as a possible solution. That was a bad, bad suggestion. I think (hope) I made it offhand without really thinking it through. SRCU can't work in this case, because the whole premise of Read-Copy-Update is that there can be multiple copies of the data. That simply can't be true for the RMP as hardware operates on a single table.
Quoted 3 lines
In the future, please don't hesitate to push back on and/or question suggestions, especially those that are made without concrete examples, i.e. are likely off the cuff. My goal isn't to set you up for failure :-/
What do you think about going back to my initial proposal of per-gfn tracking [1] ? We can limit the changes to just for the kvm_vcpu_map() and let the copy_to_user() take a fault and return an error (if it attempt to write to guest private). If PSC happen while lock is held then simplify return and let the guest retry PSC.
Sean Christopherson
maintainerRe: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 27 lines · Brijesh Singh
Quoted 21 lines · Sean Christopherson
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Brijesh Singh
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 #PF.
Quoted 7 lines
Quoted 3 lines
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.Argh, another goof on my part. Rereading prior feedback, I see that I loosely suggested SRCU as a possible solution. That was a bad, bad suggestion. I think (hope) I made it offhand without really thinking it through. SRCU can't work in this case, because the whole premise of Read-Copy-Update is that there can be multiple copies of the data. That simply can't be true for the RMP as hardware operates on a single table.
Quoted 3 lines
In the future, please don't hesitate to push back on and/or question suggestions, especially those that are made without concrete examples, i.e. are likely off the cuff. My goal isn't to set you up for failure :-/
Quoted 5 lines
What do you think about going back to my initial proposal of per-gfn tracking [1] ? We can limit the changes to just for the
kvm_vcpu_map()and let thecopy_to_user()take a fault and return an error (if it attempt to write to guest private). If PSC happen while lock is held then simplify return and let the guest retry PSC.
That approach is also broken as it doesn't hold a lock when updating host_write_track, e.g. the count can be corrupted if writers collide, and nothing blocks writers on in-progress readers.
I'm not opposed to a scheme that blocks PSC while KVM is reading, but I don't want to spend time iterating on the KVM case until consensus has been reached on how exactly RMP updates will be handled, and in general how the kernel will manage guest private memory.
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 34 lines · Sean Christopherson
Quoted 27 lines · Brijesh Singh
Quoted 21 lines · Sean Christopherson
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Brijesh Singh
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 #PF.
Quoted 7 lines
Quoted 3 lines
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.Argh, another goof on my part. Rereading prior feedback, I see that I loosely suggested SRCU as a possible solution. That was a bad, bad suggestion. I think (hope) I made it offhand without really thinking it through. SRCU can't work in this case, because the whole premise of Read-Copy-Update is that there can be multiple copies of the data. That simply can't be true for the RMP as hardware operates on a single table.
Quoted 3 lines
In the future, please don't hesitate to push back on and/or question suggestions, especially those that are made without concrete examples, i.e. are likely off the cuff. My goal isn't to set you up for failure :-/
Quoted 5 lines
What do you think about going back to my initial proposal of per-gfn tracking [1] ? We can limit the changes to just for the
kvm_vcpu_map()and let thecopy_to_user()take a fault and return an error (if it attempt to write to guest private). If PSC happen while lock is held then simplify return and let the guest retry PSC.
Quoted 8 lines
That approach is also broken as it doesn't hold a lock when updating
host_write_track, e.g. the count can be corrupted if writers collide, and nothing blocks writers on in-progress readers.I'm not opposed to a scheme that blocks PSC while KVM is reading, but I don't want to spend time iterating on the KVM case until consensus has been reached on how exactly RMP updates will be handled, and in general how the kernel will manage guest private memory.
Hi Sean,
(Sorry in advance for the long read, but it touches on a couple inter-tangled topics that I think are important for this series.)
While we do still remain committed to working with community toward implementing a UPM solution, we would still like to have a 'complete' solution in the meantime, if at the very least to use as a basis for building out other parts of the stack, or for enabling early adopters downstream doing the same.
Toward that end, there are a couple areas that need to be addressed, (and remain unaddressed with v6, since we were planning to leverage UPM to handle them and so left them as open TODOs at the time):
1) this issue of guarding against shared->private conversions for pages that are in-use by kernel
2) how to deal with unmapping/splitting the direct map
(These 2 things end up being fairly tightly coupled, which is why I'm trying to cover them both in this email. Will explain more in a bit)
You mentioned elsewhere how 1) would be nicely addressed with UPM, since the conversion would only point the guest to an entirely new page, while leaving the shared page intact (at least until the normal notifiers do their thing in response to any subsequent discard operations from userspace). If the guest breaks because it doesn't see the write, that's okay, because it's not supposed to be switching in-use shared pages to private while they are being used. (though the pKVM folks did note in v7 of private memslot patches that they actually use the same physical page for both shared/private, so I'm not sure if that approach will still stack up in that context, if it ends up being needed there)
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):
- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will see the validated bit was cleared, and get a #VC where it can terminate accordingly
- if this was a bug (or maliciousness) on the part of the guest, then the behavior is unexpected anyway, and it will be made aware this by the same mechanism
We've done some testing with this approach and it seems to hold up, but since we also need the handler to deal with the !PRESENT case (because of the current approach of nuking directmap entry for private pages), there's a situation that can't be easily resolved with this approach:
# CASE1: recoverable
THREAD 1 THREAD 2
- #PF(!PRESENT) - #PF(!PRESENT)
- restore directmap
- RMPUPDATE(shared)
- not private? okay to retry since maybe it was fixed up already
# CASE2: unrecoverable
THREAD 1
- broken kernel breaks directmap/init-mm, not related to SEV
- #PF(!PRESENT)
- not private? we should oops, since retrying might cause a loop
The reason we can't distinguish between recoverable/unrecoverable is because the kernel #PF handling here needs to happen for both !PRESENT and for RMP violations. This is due to how we unmap from directmap as part of shared->private conversion.
So we have to take the pessimistic approach due to CASE2, which means that if CASE1 pops up, we'll still have a case where guest can cause a crash/loop.
That where 2) comes into play. If we go back to the original approach (as of v4) of simply splitting the directmap when we do shared->private conversions, then we can limit the #PF handling to only have to deal with cases where there's an RMP violation and X86_PF_RMP is set, which makes it safe to retry to handle spurious cases like case #1.
AIUI, this is still sort of an open question, but you noted how nuking the directmap without any formalized interface for letting the kernel know about it could be problematic down the road, which also sounds like the sort of thing more suited for having UPM address at a more general level, since there are similar requirements for TDX as well.
AIUI there are 2 main arguments against splitting the directmap:
a) we can't easily rebuild it atm
b) things like KSM might still tries to access private pages
But unmapping also suffers from a), since we still end up splitting the directmap unless we remove pages in blocks of 2M. But nothing prevents a guest from switching a single 4K page to private, in which case we are forced to split. That would be normal behavior on the part of the guest for setting up GHCB pages/etc, so we still end up splitting the directmap over time.
And for b), as you noted, this is already something that SEV/SEV-ES need to deal with, and at least in the case of SNP guest things are a bit better since:
- if some kernel thread tried to write to private memory, they would notice if some errant kernel thread tried to write to guest memory, since #PF handler with flip the page and unset the validated bit on that memory.
- for reads, they will get ciphertext, which isn't any worse than reading unencrypted guest memory for anything outside of KVM that specifically knows what it is expecting to read there (KSM being one exception, since it'll waste cycles cmp'ing ciphertext, but there's no way to make it work anyway, and we would be fine with requiring it to be disabled if that is a concern)
So that's sort of the context for why we're considering these 2 changes. Any input on these is welcome, but at the very least wanted to provide our rationale for past reviewers.
Thanks!
-Mike
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 146 lines · Michael Roth
Quoted 34 lines · Sean Christopherson
Quoted 27 lines · Brijesh Singh
Quoted 21 lines · Sean Christopherson
Quoted 6 lines · Sean Christopherson
Quoted 5 lines · Brijesh Singh
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 #PF.
Quoted 7 lines
Quoted 3 lines
To avoid the RMP violation, add post_{map,unmap}_gfn() ops that can be used to verify that its safe to map a given guest page. Use the SRCU to protect against the page state change for existing mapped pages.
SRCU isn't protecting anything. The
synchronize_srcu_expedited()in the PSC code forces it to wait for existing maps to go away, but it doesn't prevent new maps from being created while the actual RMP updates are in-flight. Most telling is that the RMP updates happen _after_ thesynchronize_srcu_expedited()call.Argh, another goof on my part. Rereading prior feedback, I see that I loosely suggested SRCU as a possible solution. That was a bad, bad suggestion. I think (hope) I made it offhand without really thinking it through. SRCU can't work in this case, because the whole premise of Read-Copy-Update is that there can be multiple copies of the data. That simply can't be true for the RMP as hardware operates on a single table.
Quoted 3 lines
In the future, please don't hesitate to push back on and/or question suggestions, especially those that are made without concrete examples, i.e. are likely off the cuff. My goal isn't to set you up for failure :-/
Quoted 5 lines
What do you think about going back to my initial proposal of per-gfn tracking [1] ? We can limit the changes to just for the
kvm_vcpu_map()and let thecopy_to_user()take a fault and return an error (if it attempt to write to guest private). If PSC happen while lock is held then simplify return and let the guest retry PSC.Quoted 8 lines
That approach is also broken as it doesn't hold a lock when updating
host_write_track, e.g. the count can be corrupted if writers collide, and nothing blocks writers on in-progress readers.I'm not opposed to a scheme that blocks PSC while KVM is reading, but I don't want to spend time iterating on the KVM case until consensus has been reached on how exactly RMP updates will be handled, and in general how the kernel will manage guest private memory.
Hi Sean,
(Sorry in advance for the long read, but it touches on a couple inter-tangled topics that I think are important for this series.)
While we do still remain committed to working with community toward implementing a UPM solution, we would still like to have a 'complete' solution in the meantime, if at the very least to use as a basis for building out other parts of the stack, or for enabling early adopters downstream doing the same.
Toward that end, there are a couple areas that need to be addressed, (and remain unaddressed with v6, since we were planning to leverage UPM to handle them and so left them as open TODOs at the time):
1) this issue of guarding against
shared->privateconversions for pages that are in-use by kernel
2) how to deal with unmapping/splitting the direct map(These 2 things end up being fairly tightly coupled, which is why I'm trying to cover them both in this email. Will explain more in a bit)
You mentioned elsewhere how 1) would be nicely addressed with UPM, since the conversion would only point the guest to an entirely new page, while leaving the shared page intact (at least until the normal notifiers do their thing in response to any subsequent discard operations from userspace). If the guest breaks because it doesn't see the write, that's okay, because it's not supposed to be switching in-use shared pages to private while they are being used. (though the pKVM folks did note in v7 of private memslot patches that they actually use the same physical page for both shared/private, so I'm not sure if that approach will still stack up in that context, if it ends up being needed there)
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):
- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will see the validated bit was cleared, and get a #VC where it can terminate accordingly
- if this was a bug (or maliciousness) on the part of the guest, then the behavior is unexpected anyway, and it will be made aware this by the same mechanismWe've done some testing with this approach and it seems to hold up, but since we also need the handler to deal with the !PRESENT case (because of the current approach of nuking directmap entry for private pages), there's a situation that can't be easily resolved with this approach:
# CASE1: recoverable
THREAD 1 THREAD 2
- #PF(!PRESENT) - #PF(!PRESENT)
- restore directmap
- RMPUPDATE(shared)
- not private? okay to retry since maybe it was fixed up already# CASE2: unrecoverable
THREAD 1
- broken kernel breaks directmap/init-mm, not related to SEV
- #PF(!PRESENT)
- not private? we should oops, since retrying might cause a loopThe reason we can't distinguish between recoverable/unrecoverable is because the kernel #PF handling here needs to happen for both !PRESENT and for RMP violations. This is due to how we unmap from directmap as part of
shared->privateconversion.So we have to take the pessimistic approach due to CASE2, which means that if CASE1 pops up, we'll still have a case where guest can cause a crash/loop.
That where 2) comes into play. If we go back to the original approach (as of v4) of simply splitting the directmap when we do
shared->privateconversions, then we can limit the #PF handling to only have to deal with cases where there's an RMP violation andX86_PF_RMPis set, which makes it safe to retry to handle spurious cases like case #1.AIUI, this is still sort of an open question, but you noted how nuking the directmap without any formalized interface for letting the kernel know about it could be problematic down the road, which also sounds like the sort of thing more suited for having UPM address at a more general level, since there are similar requirements for TDX as well.
AIUI there are 2 main arguments against splitting the directmap:
a) we can't easily rebuild it atm
b) things like KSM might still tries to access private pages
Quoted 6 lines
But unmapping also suffers from a), since we still end up splitting the directmap unless we remove pages in blocks of 2M. But nothing prevents a guest from switching a single 4K page to private, in which case we are forced to split. That would be normal behavior on the part of the guest for setting up GHCB pages/etc, so we still end up splitting the directmap over time.
One more thing to note here, is with the splitting approach, we also have the option of doing all the splitting when the region is registered via KVM_MEMORY_ENCRYPT_REG_REGION. If unsplitting becomes possible in the future, we could then handle that in KVM_MEMORY_ENCRYPT_UNREG_REGION all at once which, where we'd have a bit more flexibility for going about that.
-Mike
Quoted 24 lines
And for b), as you noted, this is already something that SEV/SEV-ES need to deal with, and at least in the case of SNP guest things are a bit better since:
- if some kernel thread tried to write to private memory, they would notice if some errant kernel thread tried to write to guest memory, since #PF handler with flip the page and unset the validated bit on that memory.
- for reads, they will get ciphertext, which isn't any worse than reading unencrypted guest memory for anything outside of KVM that specifically knows what it is expecting to read there (KSM being one exception, since it'll waste cycles cmp'ing ciphertext, but there's no way to make it work anyway, and we would be fine with requiring it to be disabled if that is a concern)
So that's sort of the context for why we're considering these 2 changes. Any input on these is welcome, but at the very least wanted to provide our rationale for past reviewers.
Thanks!
-Mike
Sean Christopherson
maintainerRe: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
In reply to Michael RothQuoted 10 lines · Michael Roth
On Fri, Oct 15, 2021 at 05:16:28PM +0000, Sean Christopherson wrote:
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):
Quoted 7 lines
- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will see
As discussed off-list, attempting to fix up RMP violations in the host #PF handler is not a viable approach. There was also extensive discussion on-list a while back:
https://lore.kernel.org/all/[email protected]
Quoted 6 lines
AIUI, this is still sort of an open question, but you noted how nuking the directmap without any formalized interface for letting the kernel know about it could be problematic down the road, which also sounds like the sort of thing more suited for having UPM address at a more general level, since there are similar requirements for TDX as well.
Quoted 6 lines
AIUI there are 2 main arguments against splitting the directmap:
a) we can't easily rebuild it atm
b) things like KSM might still tries to access private pagesBut unmapping also suffers from a), since we still end up splitting the directmap unless we remove pages in blocks of 2M.
But for UPM, it's easy to rebuild the direct map since there will be an explicit, kernel controlled point where the "inaccesible" memfd releases the private page.
Quoted 4 lines
But nothing prevents a guest from switching a single 4K page to private, in which case we are forced to split. That would be normal behavior on the part of the guest for setting up GHCB pages/etc, so we still end up splitting the directmap over time.
The host actually isn't _forced_ to split with UPM. One option would be to refuse to split the direct map and instead force userspace to eat the 2mb allocation even though it only wants to map a single 4kb chunk into the guest. I don't know that that's a _good_ option, but it is an option.
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 20 lines · Sean Christopherson
Quoted 10 lines · Michael Roth
On Fri, Oct 15, 2021 at 05:16:28PM +0000, Sean Christopherson wrote:
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):Quoted 7 lines
- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will see
Quoted 4 lines
As discussed off-list, attempting to fix up RMP violations in the host #PF handler is not a viable approach. There was also extensive discussion on-list a while back:
I mentioned this during Mike's talk at the micro-conference: For pages mapped in by the kernel can we disallow them to be converted to private? Note, userspace accesses are already handled by UPM.
In pseudo-code, I'm thinking something like this:
kmap_helper() {
// And all other interfaces where the kernel can map a GPA // into the kernel page tables mapped_into_kernel_mem_set[hpa] = true;
}
kunmap_helper() {
// And all other interfaces where the kernel can unmap a GPA // into the kernel page tables mapped_into_kernel_mem_set[hpa] = false;
// Except it's not this simple because we probably need ref counting // for multiple mappings. Sigh. But you get the idea.
}
rmpupdate_helper() {
if (conversion = SHARED_TO_PRIVATE && mapped_into_kernel_mem_set[hpa])
return -EINVAL; // Or whatever the appropriate error code here is.
}
Sean Christopherson
maintainerRe: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 21 lines · Marc Orr
Quoted 20 lines · Sean Christopherson
Quoted 17 lines · Michael Roth
On Fri, Oct 15, 2021 at 05:16:28PM +0000, Sean Christopherson wrote:
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will see
Quoted 8 lines
Quoted 4 lines
As discussed off-list, attempting to fix up RMP violations in the host #PF handler is not a viable approach. There was also extensive discussion on-list a while back:
I mentioned this during Mike's talk at the micro-conference: For pages mapped in by the kernel can we disallow them to be converted to private?
In theory, yes. Do we want to do something like this? No. kmap() does something vaguely similar for 32-bit PAE/PSE kernels, but that's a lot of complexity and overhead to take on. And this issue goes far beyond a kmap(); when the kernel gup()s a page, the kernel expects the pfn to be available, no exceptions (pun intended).
Quoted 1 line
Note, userspace accesses are already handled by UPM.
I'm confused by the UPM comment. Isn't the gist of this thread about the ability to merge SNP _without_ UPM? Or am I out in left field?
Quoted 8 lines
In pseudo-code, I'm thinking something like this:
kmap_helper(){
// And all other interfaces where the kernel can map a GPA // into the kernel page tables mapped_into_kernel_mem_set[hpa] = true;
}
Quoted 7 lines
kunmap_helper(){
// And all other interfaces where the kernel can unmap a GPA // into the kernel page tables mapped_into_kernel_mem_set[hpa] = false;// Except it's not this simple because we probably need ref counting // for multiple mappings. Sigh. But you get the idea.
A few issues off the top of my head:
- It's not just refcounting, there would also likely need to be locking to guarantee sane behavior.
- kmap() isn't allowed to fail and RMPUPDATE isn't strictly guaranteed to succeed, which is problematic if the kernel attempts to kmap() a page that's already private, especially for kmap_atomic(), which isn't allowed to sleep.
- Not all kernel code is well behaved and bounces through kmap(); undoubtedly some of the 1200+ users of page_address() will be problematic.
$ git grep page_address | wc -l
1267
- It's not sufficient for TDX. Merging something this complicated when we know we still need UPM would be irresponsible from a maintenance perspective.
- KVM would need to support two separate APIs for SNP, which I very much don't want to do.
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 37 lines · Sean Christopherson
Quoted 21 lines · Marc Orr
Quoted 20 lines · Sean Christopherson
Quoted 17 lines · Michael Roth
On Fri, Oct 15, 2021 at 05:16:28PM +0000, Sean Christopherson wrote:
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will seeQuoted 8 lines
Quoted 4 lines
As discussed off-list, attempting to fix up RMP violations in the host #PF handler is not a viable approach. There was also extensive discussion on-list a while back:
I mentioned this during Mike's talk at the micro-conference: For pages mapped in by the kernel can we disallow them to be converted to private?
In theory, yes. Do we want to do something like this? No.
kmap()does something vaguely similar for 32-bit PAE/PSE kernels, but that's a lot of complexity and overhead to take on. And this issue goes far beyond akmap(); when the kernel gup()s a page, the kernel expects the pfn to be available, no exceptions (pun intended).
Quoted 4 lines
Quoted 1 line
Note, userspace accesses are already handled by UPM.
I'm confused by the UPM comment. Isn't the gist of this thread about the ability to merge SNP _without_ UPM? Or am I out in left field?
I think that was the overall gist: yes. But it's not what I was trying to comment on :-).
HOWEVER, thinking about this more: I was confused when I wrote out my last reply. I had thought that the issue that Michael brought up applied even with UPM. That is, I was thinking it was still possibly for a guest to maliciously convert a page to private mapped in by the kernel and assumed to be shared.
But I now realize that is not what will actually happen. To be concrete, let's assume the GHCB page. What will happen is:
- KVM has GHCB page mapped in. GHCB is always assumed to be shared. So far so good.
- Malicious guest converts GHCB page to private (e.g., via Page State Change request)
- Guest exits to KVM
- KVM exits to userspace VMM
- Userspace VM allocates page in private FD.
Now, what happens here depends on how UPM works. If we allow double allocation then our host kernel is safe. However, now we have the "double allocation problem".
If on the other hand, we deallocate the page in the shared FD, the host kernel can segfault. And now we actually do have essentially the same problem Michael was describing that we have without UPM. Because we'll end up in fault.c in the kernel context and likely panic the host.
I hope I got this right this time. Sorry for the confusion on my last reply.
Quoted 26 lines
Quoted 8 lines
In pseudo-code, I'm thinking something like this:
kmap_helper(){
// And all other interfaces where the kernel can map a GPA // into the kernel page tables mapped_into_kernel_mem_set[hpa] = true;
}Quoted 7 lines
kunmap_helper(){
// And all other interfaces where the kernel can unmap a GPA // into the kernel page tables mapped_into_kernel_mem_set[hpa] = false;// Except it's not this simple because we probably need ref counting // for multiple mappings. Sigh. But you get the idea.
A few issues off the top of my head:
- It's not just refcounting, there would also likely need to be locking to guarantee sane behavior.
-kmap()isn't allowed to fail and RMPUPDATE isn't strictly guaranteed to succeed, which is problematic if the kernel attempts tokmap()a page that's already private, especially forkmap_atomic(), which isn't allowed to sleep.
- Not all kernel code is well behaved and bounces throughkmap(); undoubtedly some of the 1200+ users ofpage_address()will be problematic.
Quoted 6 lines
$ git grep
page_address| wc -l
1267
- It's not sufficient for TDX. Merging something this complicated when we know we still need UPM would be irresponsible from a maintenance perspective.
- KVM would need to support two separate APIs for SNP, which I very much don't want to do.
Ack on merging without UPM. I wasn't trying to chime in on merging before/after UPM. See my other comment above. Sorry for the confusion. Ack on other concerns about "enlightening kmap" as well. I agree.
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
Quoted 67 lines · Marc Orr
Quoted 37 lines · Sean Christopherson
Quoted 21 lines · Marc Orr
Quoted 20 lines · Sean Christopherson
Quoted 17 lines · Michael Roth
On Fri, Oct 15, 2021 at 05:16:28PM +0000, Sean Christopherson wrote:
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will seeQuoted 8 lines
Quoted 4 lines
As discussed off-list, attempting to fix up RMP violations in the host #PF handler is not a viable approach. There was also extensive discussion on-list a while back:
I mentioned this during Mike's talk at the micro-conference: For pages mapped in by the kernel can we disallow them to be converted to private?
In theory, yes. Do we want to do something like this? No.
kmap()does something vaguely similar for 32-bit PAE/PSE kernels, but that's a lot of complexity and overhead to take on. And this issue goes far beyond akmap(); when the kernel gup()s a page, the kernel expects the pfn to be available, no exceptions (pun intended).Quoted 4 lines
Quoted 1 line
Note, userspace accesses are already handled by UPM.
I'm confused by the UPM comment. Isn't the gist of this thread about the ability to merge SNP _without_ UPM? Or am I out in left field?
I think that was the overall gist: yes. But it's not what I was trying to comment on :-).
HOWEVER, thinking about this more: I was confused when I wrote out my last reply. I had thought that the issue that Michael brought up applied even with UPM. That is, I was thinking it was still possibly for a guest to maliciously convert a page to private mapped in by the kernel and assumed to be shared.
But I now realize that is not what will actually happen. To be concrete, let's assume the GHCB page. What will happen is:
- KVM has GHCB page mapped in. GHCB is always assumed to be shared. So far so good.
- Malicious guest converts GHCB page to private (e.g., via Page State Change request)
- Guest exits to KVM
- KVM exits to userspace VMM
- Userspace VM allocates page in private FD.Now, what happens here depends on how UPM works. If we allow double allocation then our host kernel is safe. However, now we have the "double allocation problem".
Quoted 5 lines
If on the other hand, we deallocate the page in the shared FD, the host kernel can segfault. And now we actually do have essentially the same problem Michael was describing that we have without UPM. Because we'll end up in
fault.cin the kernel context and likely panic the host.
Thinking about this even more... Even if we deallocate in the userspace VMM's shared FD, the kernel has its own page tables -- right? So maybe we are actually 100% OK under UPM then regardless of the userspace VMM's policy around managing the private and shared FDs.
Re: [PATCH Part2 v5 39/45] KVM: SVM: Introduce ops for the post gfn map and unmap
In reply to Sean ChristophersonQuoted 11 lines · Sean Christopherson
Quoted 10 lines · Michael Roth
On Fri, Oct 15, 2021 at 05:16:28PM +0000, Sean Christopherson wrote:
So in the context of this interim solution, we're trying to look for a solution that's simple enough that it can be used reliably, without introducing too much additional complexity into KVM. There is one approach that seems to fit that bill, that Brijesh attempted in an earlier version of this series (I'm not sure what exactly was the catalyst to changing the approach, as I wasn't really in the loop at the time, but AIUI there weren't any showstoppers there, but please correct me if I'm missing anything):
Quoted 7 lines
Quoted 7 lines
- if the host is writing to a page that it thinks is supposed to be shared, and the guest switches it to private, we get an RMP fault (actually, we will get a !PRESENT fault, since as of v5 we now remove the mapping from the directmap as part of conversion)
- in the host #PF handler, if we see that the page is marked private in the RMP table, simply switch it back to shared
- if this was a bug on the part of the host, then the guest will see
Hi Sean,
Thanks for the input here and at KVM Forum.
Quoted 5 lines
As discussed off-list, attempting to fix up RMP violations in the host #PF handler is not a viable approach. There was also extensive discussion on-list a while back:
I think that was likely the only hope for a non-UPM approach, as anything else would require a good bit of infrastructure in KVM and elsewhere to avoid that situation occuring to begin with, and it probably would not be worth the effort outside the context of a general/platform-independent solution like UPM. I was hoping it would be possible to work through Andy's concerns, but the concerns you and Paolo raised of potential surprise #PFs in other parts of the kernel are something I'm less optimistic about, so I agree UPM is probably the right place to focus efforts.
Quoted 11 lines
Quoted 11 lines
AIUI, this is still sort of an open question, but you noted how nuking the directmap without any formalized interface for letting the kernel know about it could be problematic down the road, which also sounds like the sort of thing more suited for having UPM address at a more general level, since there are similar requirements for TDX as well.
AIUI there are 2 main arguments against splitting the directmap:
a) we can't easily rebuild it atm
b) things like KSM might still tries to access private pages
Quoted 5 lines
Quoted 2 lines
But unmapping also suffers from a), since we still end up splitting the directmap unless we remove pages in blocks of 2M.
But for UPM, it's easy to rebuild the direct map since there will be an explicit, kernel controlled point where the "inaccesible" memfd releases the private page.
I was thinking it would be possible to do something similar by doing page splitting/restore in bulk as part of MEM_ENCRYPT_{REG,UNREG}_REGION, but yes UPM also allows for a convenient point in time to split/unsplit.
Quoted 10 lines
Quoted 5 lines
But nothing prevents a guest from switching a single 4K page to private, in which case we are forced to split. That would be normal behavior on the part of the guest for setting up GHCB pages/etc, so we still end up splitting the directmap over time.
The host actually isn't _forced_ to split with UPM. One option would be to refuse to split the direct map and instead force userspace to eat the 2mb allocation even though it only wants to map a single 4kb chunk into the guest. I don't know that that's a _good_ option, but it is an option.
That does seem like a reasonable option. Maybe it also opens up a path for hugetlbfs support of sorts. In practice I wouldn't expect too many of those pages to be wasted, worst case would be 2MB per shared page in the guest... I suppose that could add up for GHCB pages and whatnot if there are lots of vCPUs, but at that point you're likely dealing with large guests with enough memory to spare. Could be another pain point regarding calculating appropriate memory limits for userspace though.
Thanks!
-Mike
PATCH v5 40/45 KVM: x86: Export the kvm_zap_gfn_range() for the SNP use
In reply to Brijesh SinghWhile resolving the RMP page fault, we may run into cases where the page level between the RMP entry and TDP does not match and the 2M RMP entry must be split into 4K RMP entries. Or a 2M TDP page need to be broken into multiple of 4K pages.
To keep the RMP and TDP page level in sync, we will zap the gfn range after splitting the pages in the RMP entry. The zap should force the TDP to gets rebuilt with the new page level.
--- arch/x86/include/asm/kvm_host.h | 2 ++ arch/x86/kvm/mmu.h | 2 -- arch/x86/kvm/mmu/mmu.c | 1 + 3 files changed, 3 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
@@ -1561,6 +1561,8 @@ void kvm_mmu_zap_all(struct kvm *kvm);void kvm_mmu_invalidate_mmio_sptes (struct kvm *kvm,u64 gen);unsigned long kvm_mmu_calculate_default_mmu_pages (struct kvm *kvm);void kvm_mmu_change_mmu_pages (struct kvm *kvm,unsigned long kvm_nr_mmu_pages); +void kvm_zap_gfn_range (struct kvm *kvm,gfn_t gfn_start,gfn_t gfn_end); +int load_pdptrs (struct kvm_vcpu *vcpu,struct kvm_mmu *mmu,unsigned long cr3);
arch/x86/kvm/mmu.h +0 -2
@@ -228,8 +228,6 @@ static inline u8 permission_fault(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,return -(u32 )fault & errcode; } -void kvm_zap_gfn_range (struct kvm *kvm,gfn_t gfn_start,gfn_t gfn_end); -int kvm_arch_write_log_dirty (struct kvm_vcpu *vcpu);int kvm_mmu_post_init_vm (struct kvm *kvm);
arch/x86/kvm/mmu/mmu.c +1 -0
@@ -5748,6 +5748,7 @@ static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,return need_tlb_flush; } +EXPORT_SYMBOL_GPL (kvm_zap_gfn_range);void kvm_mmu_zap_collapsible_sptes (struct kvm *kvm,const struct kvm_memory_slot *memslot)
Signature · 1 line
2.17.1
PATCH v5 41/45 KVM: SVM: Add support to handle the RMP nested page fault
In reply to Brijesh SinghWhen SEV-SNP is enabled in the guest, the hardware places restrictions on all memory accesses based on the contents of the RMP table. When hardware encounters RMP check failure caused by the guest memory access it raises the #NPF. The error code contains additional information on the access type. See the APM volume 2 for additional information.
--- arch/x86/kvm/svm/sev.c | 76 ++++++++++++++++++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 14 +++++--- arch/x86/kvm/svm/svm.h | 1 + 3 files changed, 87 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +76 -0
@@ -3651,3 +3651,79 @@ void sev_post_unmap_gfn(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int token)srcu_read_unlock (&sev->psc_srcu, token); } + +void handle_rmp_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u64 error_code) +{ +int rmp_level, npt_level, rc, assigned; +struct kvm *kvm = vcpu->kvm; +gfn_t gfn =gpa_to_gfn (gpa); +bool need_psc = false; +enum psc_op psc_op; +kvm_pfn_t pfn; +bool private; + +write_lock (&kvm->mmu_lock); + +if (unlikely (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &npt_level))) + goto unlock; + + assigned =snp_lookup_rmpentry (pfn, &rmp_level); +if (unlikely (assigned <0 )) + goto unlock; + + private = !!(error_code &PFERR_GUEST_ENC_MASK ); + +/* +* If the fault was due to size mismatch, or NPT and RMP page level's +* are not in sync, then use PSMASH to split the RMP entry into 4K. +*/ +if ((error_code &PFERR_GUEST_SIZEM_MASK ) || + (npt_level ==PG_LEVEL_4K && rmp_level ==PG_LEVEL_2M && private)) { + rc =snp_rmptable_psmash (kvm, pfn); +if (rc) +pr_err_ratelimited ("psmash failed, gpa 0x%llx pfn 0x%llx rc %d\n" , + gpa, pfn, rc); + goto out; + } + +/* +* If it's a private access, and the page is not assigned in the +* RMP table, create a new private RMP entry. This can happen if +* guest did not use the PSC VMGEXIT to transition the page state +* before the access. +*/ +if (!assigned && private) { + need_psc =1 ; + psc_op =SNP_PAGE_STATE_PRIVATE ; + goto out; + } + +/* +* If it's a shared access, but the page is private in the RMP table +* then make the page shared in the RMP table. This can happen if +* the guest did not use the PSC VMGEXIT to transition the page +* state before the access. +*/ +if (assigned && !private) { + need_psc =1 ; + psc_op =SNP_PAGE_STATE_SHARED ; + } + +out: +write_unlock (&kvm->mmu_lock); + +if (need_psc) + rc =__snp_handle_page_state_change (vcpu, psc_op, gpa,PG_LEVEL_4K ); + +/* +* The fault handler has updated the RMP pagesize, zap the existing +* rmaps for large entry ranges so that nested page table gets rebuilt +* with the updated RMP pagesize. +*/ + gfn =gpa_to_gfn (gpa) & ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); +kvm_zap_gfn_range (kvm, gfn, gfn +PTRS_PER_PMD ); +return ; + +unlock: +write_unlock (&kvm->mmu_lock); +}
arch/x86/kvm/svm/svm.c +10 -4
@@ -1933,15 +1933,21 @@ static int pf_interception(struct kvm_vcpu *vcpu)static int npf_interception (struct kvm_vcpu *vcpu) {struct vcpu_svm *svm =to_svm (vcpu); +int rc;u64 fault_address = svm->vmcb->control.exit_info_2;u64 error_code = svm->vmcb->control.exit_info_1;trace_kvm_page_fault (fault_address, error_code); -return kvm_mmu_page_fault (vcpu, fault_address, error_code, -static_cpu_has (X86_FEATURE_DECODEASSISTS ) ? - svm->vmcb->control.insn_bytes :NULL , - svm->vmcb->control.insn_len); + rc =kvm_mmu_page_fault (vcpu, fault_address, error_code, +static_cpu_has (X86_FEATURE_DECODEASSISTS ) ? + svm->vmcb->control.insn_bytes :NULL , + svm->vmcb->control.insn_len); + +if (error_code &PFERR_GUEST_RMP_MASK ) +handle_rmp_page_fault (vcpu, fault_address, error_code); + +return rc; }static int db_interception (struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +1 -0
@@ -626,6 +626,7 @@ struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);void sev_rmp_page_level_adjust (struct kvm *kvm,kvm_pfn_t pfn,int *level);int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token);void sev_post_unmap_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int token); +void handle_rmp_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u64 error_code);/* vmenter.S */
Signature · 1 line
2.17.1
Re: [PATCH Part2 v5 41/45] KVM: SVM: Add support to handle the RMP nested page fault
Quoted 74 lines · * Brijesh Singh ([email protected]) wrote:
When SEV-SNP is enabled in the guest, the hardware places restrictions on all memory accesses based on the contents of the RMP table. When hardware encounters RMP check failure caused by the guest memory access it raises the #NPF. The error code contains additional information on the access type. See the APM volume 2 for additional information.
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/kvm/svm/sev.c | 76 ++++++++++++++++++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 14 +++++--- arch/x86/kvm/svm/svm.h | 1 + 3 files changed, 87 insertions(+), 4 deletions(-)arch/x86/kvm/svm/sev.c +53
-0@@ -3651,3 +3651,79 @@ void sev_post_unmap_gfn(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int token)srcu_read_unlock (&sev->psc_srcu, token); } + +void handle_rmp_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u64 error_code) +{ +int rmp_level, npt_level, rc, assigned; +struct kvm *kvm = vcpu->kvm; +gfn_t gfn =gpa_to_gfn (gpa); +bool need_psc = false; +enum psc_op psc_op; +kvm_pfn_t pfn; +bool private; + +write_lock (&kvm->mmu_lock); + +if (unlikely (!kvm_mmu_get_tdp_walk (vcpu, gpa, &pfn, &npt_level))) + goto unlock; + + assigned =snp_lookup_rmpentry (pfn, &rmp_level); +if (unlikely (assigned <0 )) + goto unlock; + + private = !!(error_code &PFERR_GUEST_ENC_MASK ); + +/* +* If the fault was due to size mismatch, or NPT and RMP page level's +* are not in sync, then use PSMASH to split the RMP entry into 4K. +*/ +if ((error_code &PFERR_GUEST_SIZEM_MASK ) || + (npt_level ==PG_LEVEL_4K && rmp_level ==PG_LEVEL_2M && private)) { + rc =snp_rmptable_psmash (kvm, pfn); +if (rc) +pr_err_ratelimited ("psmash failed, gpa 0x%llx pfn 0x%llx rc %d\n" , + gpa, pfn, rc); + goto out; + } + +/* +* If it's a private access, and the page is not assigned in the +* RMP table, create a new private RMP entry. This can happen if +* guest did not use the PSC VMGEXIT to transition the page state +* before the access. +*/ +if (!assigned && private) { + need_psc =1 ; + psc_op =SNP_PAGE_STATE_PRIVATE ; + goto out; + } + +/* +* If it's a shared access, but the page is private in the RMP table +* then make the page shared in the RMP table. This can happen if +* the guest did not use the PSC VMGEXIT to transition the page +* state before the access. +*/
arch/x86/kvm/svm/sev.c void sev_post_unmap_gfn(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int token) · line 3716
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+if (assigned && !private) { + need_psc =1 ; + psc_op =SNP_PAGE_STATE_SHARED ; + } + +out: +write_unlock (&kvm->mmu_lock); + +if (need_psc) + rc =__snp_handle_page_state_change (vcpu, psc_op, gpa,PG_LEVEL_4K );
That 'rc' never goes anywhere - should it?
Quoted 24 lines
arch/x86/kvm/svm/sev.c +12
-0+/* +* The fault handler has updated the RMP pagesize, zap the existing +* rmaps for large entry ranges so that nested page table gets rebuilt +* with the updated RMP pagesize. +*/ + gfn =gpa_to_gfn (gpa) & ~(KVM_PAGES_PER_HPAGE (PG_LEVEL_2M ) -1 ); +kvm_zap_gfn_range (kvm, gfn, gfn +PTRS_PER_PMD ); +return ; + +unlock: +write_unlock (&kvm->mmu_lock); +}arch/x86/kvm/svm/svm.c +1
-0@@ -1933,15 +1933,21 @@ static int pf_interception(struct kvm_vcpu *vcpu)static int npf_interception (struct kvm_vcpu *vcpu) {struct vcpu_svm *svm =to_svm (vcpu); +int rc;u64 fault_address = svm->vmcb->control.exit_info_2;u64 error_code = svm->vmcb->control.exit_info_1;
arch/x86/kvm/svm/svm.c static int pf_interception(struct kvm_vcpu *vcpu) · line 1945
Quoted 10 lines
arch/x86/kvm/svm/svm.c +4
-4trace_kvm_page_fault (fault_address, error_code); -return kvm_mmu_page_fault (vcpu, fault_address, error_code, -static_cpu_has (X86_FEATURE_DECODEASSISTS ) ? - svm->vmcb->control.insn_bytes :NULL , - svm->vmcb->control.insn_len); + rc =kvm_mmu_page_fault (vcpu, fault_address, error_code, +static_cpu_has (X86_FEATURE_DECODEASSISTS ) ? + svm->vmcb->control.insn_bytes :NULL , + svm->vmcb->control.insn_len);
If kvm_mmu_page_fault failed, (rc!=0) do you still want to call your handler?
Dave
Quoted 23 lines
arch/x86/kvm/svm/svm.c +4
-0+if (error_code &PFERR_GUEST_RMP_MASK ) +handle_rmp_page_fault (vcpu, fault_address, error_code); + +return rc; }static int db_interception (struct kvm_vcpu *vcpu)arch/x86/kvm/svm/svm.h +1
-0@@ -626,6 +626,7 @@ struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);void sev_rmp_page_level_adjust (struct kvm *kvm,kvm_pfn_t pfn,int *level);int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token);void sev_post_unmap_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int token); +void handle_rmp_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u64 error_code);/* vmenter.S */ Signature · 1 line
2.17.1
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
Sean Christopherson
maintainerRe: [PATCH Part2 v5 41/45] KVM: SVM: Add support to handle the RMP nested page fault
In reply to Brijesh SinghQuoted 18 lines · Brijesh Singh
When SEV-SNP is enabled in the guest, the hardware places restrictions on all memory accesses based on the contents of the RMP table. When hardware encounters RMP check failure caused by the guest memory access it raises the #NPF. The error code contains additional information on the access type. See the APM volume 2 for additional information.
Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/kvm/svm/sev.c | 76 ++++++++++++++++++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 14 +++++--- arch/x86/kvm/svm/svm.h | 1 + 3 files changed, 87 insertions(+), 4 deletions(-)arch/x86/kvm/svm/sev.c +0
-0
arch/x86/kvm/svm/sev.c void sev_post_unmap_gfn(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int token) · line 3657
Quoted 7 lines
arch/x86/kvm/svm/sev.c +4
-0@@ -3651,3 +3651,79 @@ void sev_post_unmap_gfn(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int token)srcu_read_unlock (&sev->psc_srcu, token); } + +void handle_rmp_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u64 error_code) +{ +int rmp_level, npt_level, rc, assigned;
Really silly nit: can you use 'r' or 'ret' instead of 'rc'? Outside of the emulator, which should never be the gold standard for code ;-), 'rc' isn't used in x86 KVM.
Quoted 14 lines
arch/x86/kvm/svm/svm.c +1
-0@@ -1933,15 +1933,21 @@ static int pf_interception(struct kvm_vcpu *vcpu)static int npf_interception (struct kvm_vcpu *vcpu) {struct vcpu_svm *svm =to_svm (vcpu); +int rc;u64 fault_address = svm->vmcb->control.exit_info_2;u64 error_code = svm->vmcb->control.exit_info_1;trace_kvm_page_fault (fault_address, error_code);
arch/x86/kvm/svm/svm.c static int pf_interception(struct kvm_vcpu *vcpu) · line 1947
Quoted 10 lines
arch/x86/kvm/svm/svm.c +6
-4-return kvm_mmu_page_fault (vcpu, fault_address, error_code, -static_cpu_has (X86_FEATURE_DECODEASSISTS ) ? - svm->vmcb->control.insn_bytes :NULL , - svm->vmcb->control.insn_len); + rc =kvm_mmu_page_fault (vcpu, fault_address, error_code, +static_cpu_has (X86_FEATURE_DECODEASSISTS ) ? + svm->vmcb->control.insn_bytes :NULL , + svm->vmcb->control.insn_len); + +if (error_code &PFERR_GUEST_RMP_MASK )
Don't think it will matter in the end, but shouldn't this consult 'rc' before diving into RMP handling?
arch/x86/kvm/svm/svm.c static int pf_interception(struct kvm_vcpu *vcpu) · line 1948
Quoted 1 line
arch/x86/kvm/svm/svm.c +1
-0+handle_rmp_page_fault (vcpu, fault_address, error_code);
Similar to my comments on the PSC patches, I think this is backwards. The MMU should provide the control logic to convert between private and shared, and vendor code should only get involved when there are side effects from the conversion.
Once I've made a dent in my review backlog, I'll fiddle with this and some of the other MMU interactions, and hopefully come up with a workable sketch for the MMU stuff. Yell at me if you haven't gotten an update by Wednesday or so.
PATCH v5 42/45 KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event
In reply to Brijesh SinghVersion 2 of GHCB specification added the support for two SNP Guest Request Message NAE events. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the SNP_GUEST_REQUEST API define in the SEV-SNP firmware specification.
The SNP_EXT_GUEST_REQUEST is similar to SNP_GUEST_REQUEST with the difference of an additional certificate blob that can be passed through the SNP_SET_CONFIG ioctl defined in the CCP driver. The CCP driver provides snp_guest_ext_guest_request() that is used by the KVM to get both the report and certificate data at once.
--- arch/x86/kvm/svm/sev.c | 197 +++++++++++++++++++++++++++++++++++++++-- arch/x86/kvm/svm/svm.h | 2 + 2 files changed, 193 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/sev.c +191 -6
@@ -19,6 +19,7 @@#include <linux/trace_events.h> #include <linux/sev.h> #include <linux/ksm.h> +#include <linux/sev-guest.h> #include <asm/fpu/internal.h> #include <asm/pkru.h>
@@ -338,6 +339,7 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)init_srcu_struct (&sev->psc_srcu); ret =sev_snp_init (&argp->error); +mutex_init (&sev->guest_req_lock); }else { ret =sev_platform_init (&argp->error); }
@@ -1602,23 +1604,39 @@ static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)static void *snp_context_create (struct kvm *kvm,struct kvm_sev_cmd *argp) { +void *context =NULL , *certs_data =NULL , *resp_page =NULL ; +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info;struct sev_data_snp_gctx_create data = {}; -void *context;int rc; +/* Allocate memory used for the certs data in SNP guest request */ + certs_data =kmalloc (SEV_FW_BLOB_MAX_SIZE ,GFP_KERNEL_ACCOUNT ); +if (!certs_data) +return NULL ; +/* Allocate memory for context page */ context =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT );if (!context) -return NULL ; + goto e_free; + +/* Allocate a firmware buffer used during the guest command handling. */ + resp_page =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT ); +if (!resp_page) + goto e_free; 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 ; - } +if (rc) + goto e_free; + + sev->snp_certs_data = certs_data;return context; + +e_free: +snp_free_firmware_page (context); +kfree (certs_data); +return NULL ; }static int snp_bind_asid (struct kvm *kvm,int *error)
@@ -2248,6 +2266,8 @@ static int snp_decommission_context(struct kvm *kvm)snp_free_firmware_page (sev->snp_context); sev->snp_context =NULL ; +kfree (sev->snp_certs_data); +return 0 ; }
@@ -2746,6 +2766,8 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm, u64 *exit_code)case SVM_VMGEXIT_UNSUPPORTED_EVENT :case SVM_VMGEXIT_HV_FEATURES :case SVM_VMGEXIT_PSC : +case SVM_VMGEXIT_GUEST_REQUEST : +case SVM_VMGEXIT_EXT_GUEST_REQUEST :break ;default : goto vmgexit_err;
@@ -3161,6 +3183,155 @@ static unsigned long snp_handle_page_state_change(struct vcpu_svm *svm)return rc ?map_to_psc_vmgexit_code (rc) :0 ; } +static unsigned long snp_setup_guest_buf (struct vcpu_svm *svm, +struct sev_data_snp_guest_request *data, +gpa_t req_gpa,gpa_t resp_gpa) +{ +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +kvm_pfn_t req_pfn, resp_pfn; +struct kvm_sev_info *sev; + + sev = &to_kvm_svm (kvm)->sev_info; + +if (!IS_ALIGNED (req_gpa,PAGE_SIZE ) || !IS_ALIGNED (resp_gpa,PAGE_SIZE )) +return SEV_RET_INVALID_PARAM ; + + req_pfn =gfn_to_pfn (kvm,gpa_to_gfn (req_gpa)); +if (is_error_noslot_pfn (req_pfn)) +return SEV_RET_INVALID_ADDRESS ; + + resp_pfn =gfn_to_pfn (kvm,gpa_to_gfn (resp_gpa)); +if (is_error_noslot_pfn (resp_pfn)) +return SEV_RET_INVALID_ADDRESS ; + +if (rmp_make_private (resp_pfn,0 ,PG_LEVEL_4K ,0 , true)) +return SEV_RET_INVALID_ADDRESS ; + + data->gctx_paddr =__psp_pa (sev->snp_context); + data->req_paddr =__sme_set (req_pfn <<PAGE_SHIFT ); + data->res_paddr =__sme_set (resp_pfn <<PAGE_SHIFT ); + +return 0 ; +} + +static void snp_cleanup_guest_buf (struct sev_data_snp_guest_request *data,unsigned long *rc) +{ +u64 pfn =__sme_clr (data->res_paddr) >>PAGE_SHIFT ; +int ret; + + ret =snp_page_reclaim (pfn); +if (ret) + *rc =SEV_RET_INVALID_ADDRESS ; + + ret =rmp_make_shared (pfn,PG_LEVEL_4K ); +if (ret) + *rc =SEV_RET_INVALID_ADDRESS ; +} + +static void snp_handle_guest_request (struct vcpu_svm *svm,gpa_t req_gpa,gpa_t resp_gpa) +{ +struct sev_data_snp_guest_request data = {0 }; +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +struct kvm_sev_info *sev; +unsigned long rc; +int err; + +if (!sev_snp_guest (vcpu->kvm)) { + rc =SEV_RET_INVALID_GUEST ; + goto e_fail; + } + + sev = &to_kvm_svm (kvm)->sev_info; + +mutex_lock (&sev->guest_req_lock); + + rc =snp_setup_guest_buf (svm, &data, req_gpa, resp_gpa); +if (rc) + goto unlock; + + rc =sev_issue_cmd (kvm,SEV_CMD_SNP_GUEST_REQUEST , &data, &err); +if (rc) +/* use the firmware error code */ + rc = err; + +snp_cleanup_guest_buf (&data, &rc); + +unlock: +mutex_unlock (&sev->guest_req_lock); + +e_fail: +svm_set_ghcb_sw_exit_info_2 (vcpu, rc); +} + +static void snp_handle_ext_guest_request (struct vcpu_svm *svm,gpa_t req_gpa,gpa_t resp_gpa) +{ +struct sev_data_snp_guest_request req = {0 }; +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +unsigned long data_npages; +struct kvm_sev_info *sev; +unsigned long rc, err; +u64 data_gpa; + +if (!sev_snp_guest (vcpu->kvm)) { + rc =SEV_RET_INVALID_GUEST ; + goto e_fail; + } + + sev = &to_kvm_svm (kvm)->sev_info; + + data_gpa = vcpu->arch.regs[VCPU_REGS_RAX ]; + data_npages = vcpu->arch.regs[VCPU_REGS_RBX ]; + +if (!IS_ALIGNED (data_gpa,PAGE_SIZE )) { + rc =SEV_RET_INVALID_ADDRESS ; + goto e_fail; + } + +/* Verify that requested blob will fit in certificate buffer */ +if ((data_npages <<PAGE_SHIFT ) >SEV_FW_BLOB_MAX_SIZE ) { + rc =SEV_RET_INVALID_PARAM ; + goto e_fail; + } + +mutex_lock (&sev->guest_req_lock); + + rc =snp_setup_guest_buf (svm, &req, req_gpa, resp_gpa); +if (rc) + goto unlock; + + rc =snp_guest_ext_guest_request (&req, (unsigned long )sev->snp_certs_data, + &data_npages, &err); +if (rc) { +/* +* If buffer length is small then return the expected +* length in rbx. +*/ +if (err ==SNP_GUEST_REQ_INVALID_LEN ) + vcpu->arch.regs[VCPU_REGS_RBX ] = data_npages; + +/* pass the firmware error code */ + rc = err; + goto cleanup; + } + +/* Copy the certificate blob in the guest memory */ +if (data_npages && +kvm_write_guest (kvm, data_gpa, sev->snp_certs_data, data_npages <<PAGE_SHIFT )) + rc =SEV_RET_INVALID_ADDRESS ; + +cleanup: +snp_cleanup_guest_buf (&req, &rc); + +unlock: +mutex_unlock (&sev->guest_req_lock); + +e_fail: +svm_set_ghcb_sw_exit_info_2 (vcpu, rc); +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;
@@ -3404,6 +3575,20 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)svm_set_ghcb_sw_exit_info_2 (vcpu, rc);break ; } +case SVM_VMGEXIT_GUEST_REQUEST : { +snp_handle_guest_request (svm, control->exit_info_1, control->exit_info_2); + + ret =1 ; +break ; + } +case SVM_VMGEXIT_EXT_GUEST_REQUEST : { +snp_handle_ext_guest_request (svm, + control->exit_info_1, + control->exit_info_2); + + 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 -0
@@ -92,6 +92,8 @@ struct kvm_sev_info {u64 snp_init_flags;void *snp_context;/* SNP guest context page */ struct srcu_struct psc_srcu; +void *snp_certs_data; +struct mutex guest_req_lock; };struct kvm_svm {
Signature · 1 line
2.17.1
Re: [PATCH Part2 v5 42/45] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event
Quoted 266 lines · Brijesh Singh
Version 2 of GHCB specification added the support for two SNP Guest Request Message NAE events. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the
SNP_GUEST_REQUESTAPI define in the SEV-SNP firmware specification.The
SNP_EXT_GUEST_REQUESTis similar toSNP_GUEST_REQUESTwith the difference of an additional certificate blob that can be passed through theSNP_SET_CONFIGioctl defined in the CCP driver. The CCP driver providessnp_guest_ext_guest_request()that is used by the KVM to get both the report and certificate data at once.Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/kvm/svm/sev.c | 197 +++++++++++++++++++++++++++++++++++++++-- arch/x86/kvm/svm/svm.h | 2 + 2 files changed, 193 insertions(+), 6 deletions(-)arch/x86/kvm/svm/sev.c +181
-6@@ -19,6 +19,7 @@#include <linux/trace_events.h> #include <linux/sev.h> #include <linux/ksm.h> +#include <linux/sev-guest.h> #include <asm/fpu/internal.h> #include <asm/pkru.h> @@ -338,6 +339,7 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)init_srcu_struct (&sev->psc_srcu); ret =sev_snp_init (&argp->error); +mutex_init (&sev->guest_req_lock); }else { ret =sev_platform_init (&argp->error); }@@ -1602,23 +1604,39 @@ static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)static void *snp_context_create (struct kvm *kvm,struct kvm_sev_cmd *argp) { +void *context =NULL , *certs_data =NULL , *resp_page =NULL ; +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info;struct sev_data_snp_gctx_create data = {}; -void *context;int rc; +/* Allocate memory used for the certs data in SNP guest request */ + certs_data =kmalloc (SEV_FW_BLOB_MAX_SIZE ,GFP_KERNEL_ACCOUNT ); +if (!certs_data) +return NULL ; +/* Allocate memory for context page */ context =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT );if (!context) -return NULL ; + goto e_free; + +/* Allocate a firmware buffer used during the guest command handling. */ + resp_page =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT ); +if (!resp_page) + goto e_free; 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 ; - } +if (rc) + goto e_free; + + sev->snp_certs_data = certs_data;return context; + +e_free: +snp_free_firmware_page (context); +kfree (certs_data); +return NULL ; }static int snp_bind_asid (struct kvm *kvm,int *error)@@ -2248,6 +2266,8 @@ static int snp_decommission_context(struct kvm *kvm)snp_free_firmware_page (sev->snp_context); sev->snp_context =NULL ; +kfree (sev->snp_certs_data); +return 0 ; }@@ -2746,6 +2766,8 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm, u64 *exit_code)case SVM_VMGEXIT_UNSUPPORTED_EVENT :case SVM_VMGEXIT_HV_FEATURES :case SVM_VMGEXIT_PSC : +case SVM_VMGEXIT_GUEST_REQUEST : +case SVM_VMGEXIT_EXT_GUEST_REQUEST :break ;default : goto vmgexit_err;@@ -3161,6 +3183,155 @@ static unsigned long snp_handle_page_state_change(struct vcpu_svm *svm)return rc ?map_to_psc_vmgexit_code (rc) :0 ; } +static unsigned long snp_setup_guest_buf (struct vcpu_svm *svm, +struct sev_data_snp_guest_request *data, +gpa_t req_gpa,gpa_t resp_gpa) +{ +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +kvm_pfn_t req_pfn, resp_pfn; +struct kvm_sev_info *sev; + + sev = &to_kvm_svm (kvm)->sev_info; + +if (!IS_ALIGNED (req_gpa,PAGE_SIZE ) || !IS_ALIGNED (resp_gpa,PAGE_SIZE )) +return SEV_RET_INVALID_PARAM ; + + req_pfn =gfn_to_pfn (kvm,gpa_to_gfn (req_gpa)); +if (is_error_noslot_pfn (req_pfn)) +return SEV_RET_INVALID_ADDRESS ; + + resp_pfn =gfn_to_pfn (kvm,gpa_to_gfn (resp_gpa)); +if (is_error_noslot_pfn (resp_pfn)) +return SEV_RET_INVALID_ADDRESS ; + +if (rmp_make_private (resp_pfn,0 ,PG_LEVEL_4K ,0 , true)) +return SEV_RET_INVALID_ADDRESS ; + + data->gctx_paddr =__psp_pa (sev->snp_context); + data->req_paddr =__sme_set (req_pfn <<PAGE_SHIFT ); + data->res_paddr =__sme_set (resp_pfn <<PAGE_SHIFT ); + +return 0 ; +} + +static void snp_cleanup_guest_buf (struct sev_data_snp_guest_request *data,unsigned long *rc) +{ +u64 pfn =__sme_clr (data->res_paddr) >>PAGE_SHIFT ; +int ret; + + ret =snp_page_reclaim (pfn); +if (ret) + *rc =SEV_RET_INVALID_ADDRESS ; + + ret =rmp_make_shared (pfn,PG_LEVEL_4K ); +if (ret) + *rc =SEV_RET_INVALID_ADDRESS ; +} + +static void snp_handle_guest_request (struct vcpu_svm *svm,gpa_t req_gpa,gpa_t resp_gpa) +{ +struct sev_data_snp_guest_request data = {0 }; +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +struct kvm_sev_info *sev; +unsigned long rc; +int err; + +if (!sev_snp_guest (vcpu->kvm)) { + rc =SEV_RET_INVALID_GUEST ; + goto e_fail; + } + + sev = &to_kvm_svm (kvm)->sev_info; + +mutex_lock (&sev->guest_req_lock); + + rc =snp_setup_guest_buf (svm, &data, req_gpa, resp_gpa); +if (rc) + goto unlock; + + rc =sev_issue_cmd (kvm,SEV_CMD_SNP_GUEST_REQUEST , &data, &err); +if (rc) +/* use the firmware error code */ + rc = err; + +snp_cleanup_guest_buf (&data, &rc); + +unlock: +mutex_unlock (&sev->guest_req_lock); + +e_fail: +svm_set_ghcb_sw_exit_info_2 (vcpu, rc); +} + +static void snp_handle_ext_guest_request (struct vcpu_svm *svm,gpa_t req_gpa,gpa_t resp_gpa) +{ +struct sev_data_snp_guest_request req = {0 }; +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +unsigned long data_npages; +struct kvm_sev_info *sev; +unsigned long rc, err; +u64 data_gpa; + +if (!sev_snp_guest (vcpu->kvm)) { + rc =SEV_RET_INVALID_GUEST ; + goto e_fail; + } + + sev = &to_kvm_svm (kvm)->sev_info; + + data_gpa = vcpu->arch.regs[VCPU_REGS_RAX ]; + data_npages = vcpu->arch.regs[VCPU_REGS_RBX ]; + +if (!IS_ALIGNED (data_gpa,PAGE_SIZE )) { + rc =SEV_RET_INVALID_ADDRESS ; + goto e_fail; + } + +/* Verify that requested blob will fit in certificate buffer */ +if ((data_npages <<PAGE_SHIFT ) >SEV_FW_BLOB_MAX_SIZE ) { + rc =SEV_RET_INVALID_PARAM ; + goto e_fail; + } + +mutex_lock (&sev->guest_req_lock); + + rc =snp_setup_guest_buf (svm, &req, req_gpa, resp_gpa); +if (rc) + goto unlock; + + rc =snp_guest_ext_guest_request (&req, (unsigned long )sev->snp_certs_data, + &data_npages, &err); +if (rc) { +/* +* If buffer length is small then return the expected +* length in rbx. +*/ +if (err ==SNP_GUEST_REQ_INVALID_LEN ) + vcpu->arch.regs[VCPU_REGS_RBX ] = data_npages; + +/* pass the firmware error code */ + rc = err; + goto cleanup; + } + +/* Copy the certificate blob in the guest memory */ +if (data_npages && +kvm_write_guest (kvm, data_gpa, sev->snp_certs_data, data_npages <<PAGE_SHIFT )) + rc =SEV_RET_INVALID_ADDRESS ; + +cleanup: +snp_cleanup_guest_buf (&req, &rc); + +unlock: +mutex_unlock (&sev->guest_req_lock); + +e_fail: +svm_set_ghcb_sw_exit_info_2 (vcpu, rc); +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;@@ -3404,6 +3575,20 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)svm_set_ghcb_sw_exit_info_2 (vcpu, rc);break ; } +case SVM_VMGEXIT_GUEST_REQUEST : { +snp_handle_guest_request (svm, control->exit_info_1, control->exit_info_2); + + ret =1 ;
arch/x86/kvm/svm/sev.c int sev_handle_vmgexit(struct kvm_vcpu *vcpu) · line 3591
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+break ; + } +case SVM_VMGEXIT_EXT_GUEST_REQUEST : { +snp_handle_ext_guest_request (svm, + control->exit_info_1, + control->exit_info_2); + + ret =1 ; +break ; + }
Don't we need some sort of rate limiting here? Since the PSP is a shared resource that the host needs access to as well as other guests it seems a little dangerous to let the guest spam this interface.
Quoted 19 lines
arch/x86/kvm/svm/sev.c +0
-0case 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@@ -92,6 +92,8 @@ struct kvm_sev_info {u64 snp_init_flags;void *snp_context;/* SNP guest context page */ struct srcu_struct psc_srcu; +void *snp_certs_data; +struct mutex guest_req_lock; };struct kvm_svm { --2.17.1
Re: [PATCH Part2 v5 42/45] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event
In reply to Brijesh SinghQuoted 217 lines · Brijesh Singh
Version 2 of GHCB specification added the support for two SNP Guest Request Message NAE events. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the
SNP_GUEST_REQUESTAPI define in the SEV-SNP firmware specification.The
SNP_EXT_GUEST_REQUESTis similar toSNP_GUEST_REQUESTwith the difference of an additional certificate blob that can be passed through theSNP_SET_CONFIGioctl defined in the CCP driver. The CCP driver providessnp_guest_ext_guest_request()that is used by the KVM to get both the report and certificate data at once.Signed-off-by Brijesh Singh <[email protected]>--- arch/x86/kvm/svm/sev.c | 197 +++++++++++++++++++++++++++++++++++++++-- arch/x86/kvm/svm/svm.h | 2 + 2 files changed, 193 insertions(+), 6 deletions(-)arch/x86/kvm/svm/sev.c +139
-6@@ -19,6 +19,7 @@#include <linux/trace_events.h> #include <linux/sev.h> #include <linux/ksm.h> +#include <linux/sev-guest.h> #include <asm/fpu/internal.h> #include <asm/pkru.h> @@ -338,6 +339,7 @@ static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)init_srcu_struct (&sev->psc_srcu); ret =sev_snp_init (&argp->error); +mutex_init (&sev->guest_req_lock); }else { ret =sev_platform_init (&argp->error); }@@ -1602,23 +1604,39 @@ static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)static void *snp_context_create (struct kvm *kvm,struct kvm_sev_cmd *argp) { +void *context =NULL , *certs_data =NULL , *resp_page =NULL ; +struct kvm_sev_info *sev = &to_kvm_svm (kvm)->sev_info;struct sev_data_snp_gctx_create data = {}; -void *context;int rc; +/* Allocate memory used for the certs data in SNP guest request */ + certs_data =kmalloc (SEV_FW_BLOB_MAX_SIZE ,GFP_KERNEL_ACCOUNT ); +if (!certs_data) +return NULL ; +/* Allocate memory for context page */ context =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT );if (!context) -return NULL ; + goto e_free; + +/* Allocate a firmware buffer used during the guest command handling. */ + resp_page =snp_alloc_firmware_page (GFP_KERNEL_ACCOUNT ); +if (!resp_page) + goto e_free; 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 ; - } +if (rc) + goto e_free; + + sev->snp_certs_data = certs_data;return context; + +e_free: +snp_free_firmware_page (context); +kfree (certs_data); +return NULL ; }static int snp_bind_asid (struct kvm *kvm,int *error)@@ -2248,6 +2266,8 @@ static int snp_decommission_context(struct kvm *kvm)snp_free_firmware_page (sev->snp_context); sev->snp_context =NULL ; +kfree (sev->snp_certs_data); +return 0 ; }@@ -2746,6 +2766,8 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm, u64 *exit_code)case SVM_VMGEXIT_UNSUPPORTED_EVENT :case SVM_VMGEXIT_HV_FEATURES :case SVM_VMGEXIT_PSC : +case SVM_VMGEXIT_GUEST_REQUEST : +case SVM_VMGEXIT_EXT_GUEST_REQUEST :break ;default : goto vmgexit_err;@@ -3161,6 +3183,155 @@ static unsigned long snp_handle_page_state_change(struct vcpu_svm *svm)return rc ?map_to_psc_vmgexit_code (rc) :0 ; } +static unsigned long snp_setup_guest_buf (struct vcpu_svm *svm, +struct sev_data_snp_guest_request *data, +gpa_t req_gpa,gpa_t resp_gpa) +{ +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +kvm_pfn_t req_pfn, resp_pfn; +struct kvm_sev_info *sev; + + sev = &to_kvm_svm (kvm)->sev_info; + +if (!IS_ALIGNED (req_gpa,PAGE_SIZE ) || !IS_ALIGNED (resp_gpa,PAGE_SIZE )) +return SEV_RET_INVALID_PARAM ; + + req_pfn =gfn_to_pfn (kvm,gpa_to_gfn (req_gpa)); +if (is_error_noslot_pfn (req_pfn)) +return SEV_RET_INVALID_ADDRESS ; + + resp_pfn =gfn_to_pfn (kvm,gpa_to_gfn (resp_gpa)); +if (is_error_noslot_pfn (resp_pfn)) +return SEV_RET_INVALID_ADDRESS ; + +if (rmp_make_private (resp_pfn,0 ,PG_LEVEL_4K ,0 , true)) +return SEV_RET_INVALID_ADDRESS ; + + data->gctx_paddr =__psp_pa (sev->snp_context); + data->req_paddr =__sme_set (req_pfn <<PAGE_SHIFT ); + data->res_paddr =__sme_set (resp_pfn <<PAGE_SHIFT ); + +return 0 ; +} + +static void snp_cleanup_guest_buf (struct sev_data_snp_guest_request *data,unsigned long *rc) +{ +u64 pfn =__sme_clr (data->res_paddr) >>PAGE_SHIFT ; +int ret; + + ret =snp_page_reclaim (pfn); +if (ret) + *rc =SEV_RET_INVALID_ADDRESS ; + + ret =rmp_make_shared (pfn,PG_LEVEL_4K ); +if (ret) + *rc =SEV_RET_INVALID_ADDRESS ; +} + +static void snp_handle_guest_request (struct vcpu_svm *svm,gpa_t req_gpa,gpa_t resp_gpa) +{ +struct sev_data_snp_guest_request data = {0 }; +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +struct kvm_sev_info *sev; +unsigned long rc; +int err; + +if (!sev_snp_guest (vcpu->kvm)) { + rc =SEV_RET_INVALID_GUEST ; + goto e_fail; + } + + sev = &to_kvm_svm (kvm)->sev_info; + +mutex_lock (&sev->guest_req_lock); + + rc =snp_setup_guest_buf (svm, &data, req_gpa, resp_gpa); +if (rc) + goto unlock; + + rc =sev_issue_cmd (kvm,SEV_CMD_SNP_GUEST_REQUEST , &data, &err); +if (rc) +/* use the firmware error code */ + rc = err; + +snp_cleanup_guest_buf (&data, &rc); + +unlock: +mutex_unlock (&sev->guest_req_lock); + +e_fail: +svm_set_ghcb_sw_exit_info_2 (vcpu, rc); +} + +static void snp_handle_ext_guest_request (struct vcpu_svm *svm,gpa_t req_gpa,gpa_t resp_gpa) +{ +struct sev_data_snp_guest_request req = {0 }; +struct kvm_vcpu *vcpu = &svm->vcpu; +struct kvm *kvm = vcpu->kvm; +unsigned long data_npages; +struct kvm_sev_info *sev; +unsigned long rc, err; +u64 data_gpa; + +if (!sev_snp_guest (vcpu->kvm)) { + rc =SEV_RET_INVALID_GUEST ; + goto e_fail; + } + + sev = &to_kvm_svm (kvm)->sev_info; + + data_gpa = vcpu->arch.regs[VCPU_REGS_RAX ]; + data_npages = vcpu->arch.regs[VCPU_REGS_RBX ]; + +if (!IS_ALIGNED (data_gpa,PAGE_SIZE )) { + rc =SEV_RET_INVALID_ADDRESS ; + goto e_fail; + } + +/* Verify that requested blob will fit in certificate buffer */ +if ((data_npages <<PAGE_SHIFT ) >SEV_FW_BLOB_MAX_SIZE ) { + rc =SEV_RET_INVALID_PARAM ; + goto e_fail;
arch/x86/kvm/svm/sev.c static unsigned long snp_handle_page_state_change(struct vcpu_svm *svm) · line 3306
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+ } + +mutex_lock (&sev->guest_req_lock); + + rc =snp_setup_guest_buf (svm, &req, req_gpa, resp_gpa); +if (rc) + goto unlock; + + rc =snp_guest_ext_guest_request (&req, (unsigned long )sev->snp_certs_data, + &data_npages, &err);
What's the point of caching the certs from the sev_device in the sev_info struct if the snp_guest_ext_guest_request() function always seems to re-copy the certs back into |sev->snp_certs_data| on every call? I am probably missing something.
Quoted 68 lines
arch/x86/kvm/svm/sev.c +42
-0+if (rc) { +/* +* If buffer length is small then return the expected +* length in rbx. +*/ +if (err ==SNP_GUEST_REQ_INVALID_LEN ) + vcpu->arch.regs[VCPU_REGS_RBX ] = data_npages; + +/* pass the firmware error code */ + rc = err; + goto cleanup; + } + +/* Copy the certificate blob in the guest memory */ +if (data_npages && +kvm_write_guest (kvm, data_gpa, sev->snp_certs_data, data_npages <<PAGE_SHIFT )) + rc =SEV_RET_INVALID_ADDRESS ; + +cleanup: +snp_cleanup_guest_buf (&req, &rc); + +unlock: +mutex_unlock (&sev->guest_req_lock); + +e_fail: +svm_set_ghcb_sw_exit_info_2 (vcpu, rc); +} +static int sev_handle_vmgexit_msr_protocol (struct vcpu_svm *svm) {struct vmcb_control_area *control = &svm->vmcb->control;@@ -3404,6 +3575,20 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)svm_set_ghcb_sw_exit_info_2 (vcpu, rc);break ; } +case SVM_VMGEXIT_GUEST_REQUEST : { +snp_handle_guest_request (svm, control->exit_info_1, control->exit_info_2); + + ret =1 ; +break ; + } +case SVM_VMGEXIT_EXT_GUEST_REQUEST : { +snp_handle_ext_guest_request (svm, + control->exit_info_1, + control->exit_info_2); + + 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@@ -92,6 +92,8 @@ struct kvm_sev_info {u64 snp_init_flags;void *snp_context;/* SNP guest context page */ struct srcu_struct psc_srcu; +void *snp_certs_data; +struct mutex guest_req_lock; };struct kvm_svm { --2.17.1
PATCH v5 43/45 KVM: SVM: Use a VMSA physical address variable for populating VMCB
In reply to Brijesh SinghFrom: Tom Lendacky <[email protected]>
In preparation to support SEV-SNP AP Creation, use a variable that holds the VMSA physical address rather than converting the virtual address. This will allow SEV-SNP AP Creation to set the new physical address that will be used should the vCPU reset path be taken.
--- arch/x86/kvm/svm/sev.c | 5 ++--- arch/x86/kvm/svm/svm.c | 9 ++++++++- arch/x86/kvm/svm/svm.h | 1 + 3 files changed, 11 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +2 -3
@@ -3619,10 +3619,9 @@ void sev_es_init_vmcb(struct vcpu_svm *svm)/* * An SEV-ES guest requires a VMSA area that is a separate from the -* VMCB page. Do not include the encryption mask on the VMSA physical -* address since hardware will access it using the guest key. +* VMCB page. */ - svm->vmcb->control.vmsa_pa =__pa (svm->vmsa); + svm->vmcb->control.vmsa_pa = svm->vmsa_pa;/* Can't intercept CR register access, HV can't modify CR registers */ svm_clr_intercept (svm,INTERCEPT_CR0_READ );
arch/x86/kvm/svm/svm.c +8 -1
@@ -1409,9 +1409,16 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu) svm->vmcb01.ptr =page_address (vmcb01_page); svm->vmcb01.pa =__sme_set (page_to_pfn (vmcb01_page) <<PAGE_SHIFT ); -if (vmsa_page) +if (vmsa_page) { svm->vmsa =page_address (vmsa_page); +/* +* Do not include the encryption mask on the VMSA physical +* address since hardware will access it using the guest key. +*/ + svm->vmsa_pa =__pa (svm->vmsa); + } + svm->guest_state_loaded = false;svm_switch_vmcb (svm, &svm->vmcb01);
arch/x86/kvm/svm/svm.h +1 -0
@@ -199,6 +199,7 @@ struct vcpu_svm {/* SEV-ES support */ struct sev_es_save_area *vmsa; +hpa_t vmsa_pa;bool ghcb_in_use;bool received_first_sipi;unsigned int ap_reset_hold_type;
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 v5 43/45] KVM: SVM: Use a VMSA physical address variable for populating VMCB
Quoted 6 lines · Brijesh Singh
From: Tom Lendacky <[email protected]>
In preparation to support SEV-SNP AP Creation, use a variable that holds the VMSA physical address rather than converting the virtual address. This will allow SEV-SNP AP Creation to set the new physical address that will be used should the vCPU reset path be taken.
The use of "variable" in the changelog and shortlog is really confusing. I read them multiple times and still didn't fully understand the change until I sussed out that the change is to track the PA in vcpu_svm separately from vcpu_svm.vmsa.
It's somewhat of a moot point though, because I think this can and should be simplified.
In the SEV-ES case, svm->vmcb->control.vmsa_pa is always __pa(svm->vmsa). And in the SNP case, svm->vmcb->control.vmsa_pa defaults to __pa(svm->vmsa), but is not changed on INIT. Rather than do this crazy 3-way dance, simply don't write svm->vmcb->control.vmsa_pa on INIT. Then SNP can change it at will without having an unnecessary and confusing field.
arch/x86/kvm/svm/sev.c +7 -7
@@ -2593,13 +2593,6 @@ void sev_es_init_vmcb(struct vcpu_svm *svm) svm->vmcb->control.nested_ctl |=SVM_NESTED_CTL_SEV_ES_ENABLE ; svm->vmcb->control.virt_ext |=LBR_CTL_ENABLE_MASK ; -/* -* An SEV-ES guest requires a VMSA area that is a separate from the -* VMCB page. Do not include the encryption mask on the VMSA physical -* address since hardware will access it using the guest key. -*/ - svm->vmcb->control.vmsa_pa =__pa (svm->vmsa); -/* Can't intercept CR register access, HV can't modify CR registers */ svm_clr_intercept (svm,INTERCEPT_CR0_READ );svm_clr_intercept (svm,INTERCEPT_CR4_READ );
@@ -2633,6 +2626,13 @@ void sev_es_init_vmcb(struct vcpu_svm *svm)void sev_es_vcpu_reset (struct vcpu_svm *svm) { +/* +* An SEV-ES guest requires a VMSA area that is a separate from the +* VMCB page. Do not include the encryption mask on the VMSA physical +* address since hardware will access it using the guest key. +*/ + svm->vmcb->control.vmsa_pa =__pa (svm->vmsa); +/* * Set the GHCB MSR value as per the GHCB specification when emulating * vCPU RESET for an SEV-ES guest.
Quoted 1 line
Signed-off-by Tom Lendacky <[email protected]>
This needs your SoB.
PATCH v5 44/45 KVM: SVM: Support SEV-SNP AP Creation NAE event
In reply to Brijesh SinghFrom: Tom Lendacky <[email protected]>
Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.
A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.
For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.
For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.
For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.
The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.
--- arch/x86/include/asm/kvm-x86-ops.h | 1 + arch/x86/include/asm/kvm_host.h | 3 + arch/x86/include/asm/svm.h | 7 +- arch/x86/kvm/svm/sev.c | 211 +++++++++++++++++++++++++++++ arch/x86/kvm/svm/svm.c | 6 +- arch/x86/kvm/svm/svm.h | 9 ++ arch/x86/kvm/x86.c | 13 +- 7 files changed, 247 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
@@ -126,6 +126,7 @@ KVM_X86_OP(alloc_apic_backing_page) KVM_X86_OP_NULL(rmp_page_level_adjust) KVM_X86_OP(post_map_gfn) KVM_X86_OP(post_unmap_gfn) +KVM_X86_OP(update_protected_guest_state)#undef KVM_X86_OP#undef KVM_X86_OP_NULL
arch/x86/include/asm/kvm_host.h +3 -0
@@ -91,6 +91,7 @@#define KVM_REQ_MSR_FILTER_CHANGED KVM_ARCH_REQ(29)#define KVM_REQ_UPDATE_CPU_DIRTY_LOGGING \ KVM_ARCH_REQ_FLAGS(30, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP) +#define KVM_REQ_UPDATE_PROTECTED_GUEST_STATE KVM_ARCH_REQ(31)#define CR0_RESERVED_BITS \ (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
@@ -1468,6 +1469,8 @@ struct kvm_x86_ops {int (*post_map_gfn)(struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token);void (*post_unmap_gfn)(struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int token); + +int (*update_protected_guest_state)(struct kvm_vcpu *vcpu); };struct kvm_x86_nested_ops {
arch/x86/include/asm/svm.h +6 -1
@@ -218,7 +218,12 @@ struct __attribute__ ((__packed__)) vmcb_control_area {#define SVM_NESTED_CTL_SEV_ENABLE BIT(1)#define SVM_NESTED_CTL_SEV_ES_ENABLE BIT(2) -#define SVM_SEV_FEAT_SNP_ACTIVE BIT(0) +#define SVM_SEV_FEAT_SNP_ACTIVE BIT(0) +#define SVM_SEV_FEAT_RESTRICTED_INJECTION BIT(3) +#define SVM_SEV_FEAT_ALTERNATE_INJECTION BIT(4) +#define SVM_SEV_FEAT_INT_INJ_MODES \ + (SVM_SEV_FEAT_RESTRICTED_INJECTION | \ + SVM_SEV_FEAT_ALTERNATE_INJECTION)struct vmcb_seg {u16 selector;
arch/x86/kvm/svm/sev.c +211 -0
247 lines not on this page · raw message
arch/x86/kvm/svm/svm.c +5 -1
@@ -1336,7 +1336,9 @@ static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) svm->spec_ctrl =0 ; svm->virt_spec_ctrl =0 ; -if (!init_event) { +if (init_event) { +sev_snp_init_protected_guest_state (vcpu); + }else { vcpu->arch.apic_base =APIC_DEFAULT_PHYS_BASE |MSR_IA32_APICBASE_ENABLE ;if (kvm_vcpu_is_reset_bsp (vcpu))
@@ -4697,6 +4699,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = { .post_map_gfn = sev_post_map_gfn, .post_unmap_gfn = sev_post_unmap_gfn, + + .update_protected_guest_state = sev_snp_update_protected_guest_state, };static struct kvm_x86_init_ops svm_init_ops__initdata = {
arch/x86/kvm/svm/svm.h +9 -0
@@ -94,6 +94,8 @@ struct kvm_sev_info {struct srcu_struct psc_srcu;void *snp_certs_data;struct mutex guest_req_lock; + +u64 sev_features;/* Features set at VMSA creation */ };struct kvm_svm {
@@ -221,6 +223,11 @@ struct vcpu_svm {u64 ghcb_sw_exit_info_2;u64 ghcb_registered_gpa; + +struct mutex snp_vmsa_mutex; +gpa_t snp_vmsa_gpa; +kvm_pfn_t snp_vmsa_pfn; +bool snp_vmsa_update_on_init;/* SEV-SNP AP Creation on INIT-SIPI */ };struct svm_cpu_data {
@@ -630,6 +637,8 @@ void sev_rmp_page_level_adjust(struct kvm *kvm, kvm_pfn_t pfn, int *level);int sev_post_map_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int *token);void sev_post_unmap_gfn (struct kvm *kvm,gfn_t gfn,kvm_pfn_t pfn,int token);void handle_rmp_page_fault (struct kvm_vcpu *vcpu,gpa_t gpa,u64 error_code); +void sev_snp_init_protected_guest_state (struct kvm_vcpu *vcpu); +int sev_snp_update_protected_guest_state (struct kvm_vcpu *vcpu);/* vmenter.S */
arch/x86/kvm/x86.c +12 -1
@@ -9576,6 +9576,16 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)if (kvm_check_request (KVM_REQ_UPDATE_CPU_DIRTY_LOGGING , vcpu))static_call (kvm_x86_update_cpu_dirty_logging)(vcpu); + +if (kvm_check_request (KVM_REQ_UPDATE_PROTECTED_GUEST_STATE , vcpu)) { + r =static_call (kvm_x86_update_protected_guest_state)(vcpu); +if (!r) { + vcpu->run->exit_reason =KVM_EXIT_INTERNAL_ERROR ; + goto out; + }else if (vcpu->arch.mp_state !=KVM_MP_STATE_RUNNABLE ) { + goto out; + } + } } if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
@@ -11656,7 +11666,8 @@ static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)if (!list_empty_careful (&vcpu->async_pf.done))return true; -if (kvm_apic_has_events (vcpu)) +if (kvm_apic_has_events (vcpu) || +kvm_test_request (KVM_REQ_UPDATE_PROTECTED_GUEST_STATE , vcpu))return true;if (vcpu->arch.pv.pv_unhalted)
Signature · 1 line
2.17.1
Sean Christopherson
maintainerRe: [PATCH Part2 v5 44/45] KVM: SVM: Support SEV-SNP AP Creation NAE event
Quoted 26 lines · Brijesh Singh
From: Tom Lendacky <[email protected]>
Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.
A new event,
KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, theKVM_REQ_UPDATE_PROTECTED_GUEST_STATEevent is added to the vCPU and then the vCPU is kicked.For
CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, theKVM_REQ_UPDATE_PROTECTED_GUEST_STATEevent is added to vCPU and then the vCPU is kicked.
Quoted 10 lines
The
KVM_REQ_UPDATE_PROTECTED_GUEST_STATEevent handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to theKVM_MP_STATE_UNINITIALIZEDstate, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set toKVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left asKVM_MP_STATE_UNINITIALIZEDto prevent it from being run.
LOL, this part of the GHCB is debatable, though I guess it does say "may"...
Using VMGEXIT SW_EXITCODE 0x8000_0013, an SEV-SNP guest can create or update the vCPU state of an AP, which may allow for a simpler and more secure method of
^^^^^^^
booting an AP.
arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3363
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+if (VALID_PAGE (svm->snp_vmsa_pfn)) {
KVM's VMSA page should be freed on a successful "switch", because AFAICT it's incorrect for KVM to ever go back to the original VMSA.
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+/* +* The snp_vmsa_pfn fields holds the hypervisor physical address +* of the about to be replaced VMSA which will no longer be used +* or referenced, so un-pin it. +*/
arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3378
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+kvm_release_pfn_dirty (svm->snp_vmsa_pfn); + svm->snp_vmsa_pfn =INVALID_PAGE ; + } + +if (VALID_PAGE (svm->snp_vmsa_gpa)) { +/* +* The VMSA is referenced by the hypervisor physical address, +* so retrieve the PFN and pin it. +*/ + pfn =gfn_to_pfn (vcpu->kvm,gpa_to_gfn (svm->snp_vmsa_gpa));
Oh yay, a gfn. That means that the page is subject to memslot movement. I don't think the code will break per se, but it's a wrinkle that's not handled.
I'm also pretty sure the page will effectively be leaked, I don't see a
kvm_release_pfn_dirty(svm->snp_vmsa_pfn);
in vCPU teardown.
Furthermore, letting the guest specify the page would open up to exploits of the erratum where a spurious RMP violation is signaled if an in-use page, a.k.a. VMSA page, is 2mb aligned. That also means the _guest_ needs to be somehow be aware of the erratum.
And digging through the guest patches, this gives the guest _full_ control over the VMSA contents. That is bonkers. At _best_ it gives the guest the ability to fuzz VMRUN ucode by stuffing garbage into the VMSA.
Honestly, why should KVM even support guest-provided VMSAs? It's far, far simpler to handle this fully in the guest with a BIOS<=>kernel mailbox; see the MP wakeup protocol being added for TDX. That would allow improving the security for SEV-ES as well, though I'm guessing no one actually cares about that in practice.
IIUC, the use case for VMPLs is that VMPL0 would be fully trusted by both the host and guest, i.e. attacks via the VMSA are out-of-scope. That is very much not the case here.
Re: [PATCH Part2 v5 44/45] KVM: SVM: Support SEV-SNP AP Creation NAE event
Quoted 68 lines · Sean Christopherson
Quoted 26 lines · Brijesh Singh
From: Tom Lendacky <[email protected]>
Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to alter the register state of the APs on their own. This allows the guest a way of simulating INIT-SIPI.
A new event,
KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, theKVM_REQ_UPDATE_PROTECTED_GUEST_STATEevent is added to the vCPU and then the vCPU is kicked.For
CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, theKVM_REQ_UPDATE_PROTECTED_GUEST_STATEevent is added to vCPU and then the vCPU is kicked.Quoted 10 lines
The
KVM_REQ_UPDATE_PROTECTED_GUEST_STATEevent handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to theKVM_MP_STATE_UNINITIALIZEDstate, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set toKVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left asKVM_MP_STATE_UNINITIALIZEDto prevent it from being run.LOL, this part of the GHCB is debatable, though I guess it does say "may"...
Using VMGEXIT
SW_EXITCODE0x8000_0013, an SEV-SNP guest can create or update the vCPU state of an AP, which may allow for a simpler and more secure method of^^^^^^^booting an AP.
arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3363
Quoted 1 line
arch/x86/kvm/svm/sev.c +1
-0+if (VALID_PAGE (svm->snp_vmsa_pfn)) {KVM's VMSA page should be freed on a successful "switch", because AFAICT it's incorrect for KVM to ever go back to the original VMSA.
Quoted 5 lines
arch/x86/kvm/svm/sev.c +5
-0+/* +* The snp_vmsa_pfn fields holds the hypervisor physical address +* of the about to be replaced VMSA which will no longer be used +* or referenced, so un-pin it. +*/ arch/x86/kvm/svm/sev.c static void snp_handle_ext_guest_request(struct vcpu_svm *svm, gpa_t req_gpa, gp · line 3378
Quoted 10 lines
arch/x86/kvm/svm/sev.c +10
-0+kvm_release_pfn_dirty (svm->snp_vmsa_pfn); + svm->snp_vmsa_pfn =INVALID_PAGE ; + } + +if (VALID_PAGE (svm->snp_vmsa_gpa)) { +/* +* The VMSA is referenced by the hypervisor physical address, +* so retrieve the PFN and pin it. +*/ + pfn =gfn_to_pfn (vcpu->kvm,gpa_to_gfn (svm->snp_vmsa_gpa));Oh yay, a gfn. That means that the page is subject to memslot movement. I don't think the code will break per se, but it's a wrinkle that's not handled.
I'm also pretty sure the page will effectively be leaked, I don't see a
Quoted 8 lines
kvm_release_pfn_dirty(svm->snp_vmsa_pfn);in vCPU teardown.
Furthermore, letting the guest specify the page would open up to exploits of the erratum where a spurious RMP violation is signaled if an in-use page, a.k.a. VMSA page, is 2mb aligned. That also means the _guest_ needs to be somehow be aware of the erratum.
Good point Sean, a guest could exploit the IN_USE erratum in this case. We need to somehow communicate this to guest so that it does not allocate the VMSA at 2MB boundary. It would be nice if GHCB spec can add a requirement that VMSA should not be a 2MB aligned. I will see what we can do to address this.
Quoted 3 lines
And digging through the guest patches, this gives the guest _full_ control over the VMSA contents. That is bonkers. At _best_ it gives the guest the ability to fuzz VMRUN ucode by stuffing garbage into the VMSA.
If guest puts garbage in VMSA then VMRUN will fail. I am sure ucode is doing all kind of sanity checks to ensure that VMSA does not contain invalid value before the run.
Quoted 7 lines
Honestly, why should KVM even support guest-provided VMSAs? It's far, far simpler to handle this fully in the guest with a BIOS<=>kernel mailbox; see the MP wakeup protocol being added for TDX. That would allow improving the security for SEV-ES as well, though I'm guessing no one actually cares about that in practice. IIUC, the use case for VMPLs is that VMPL0 would be fully trusted by both the host and guest, i.e. attacks via the VMSA are out-of-scope. That is very much not the case here.
Sean Christopherson
maintainerRe: [PATCH Part2 v5 44/45] KVM: SVM: Support SEV-SNP AP Creation NAE event
Quoted 9 lines · Brijesh Singh
Quoted 3 lines · Sean Christopherson
And digging through the guest patches, this gives the guest _full_ control over the VMSA contents. That is bonkers. At _best_ it gives the guest the ability to fuzz VMRUN ucode by stuffing garbage into the VMSA.
If guest puts garbage in VMSA then VMRUN will fail. I am sure ucode is doing all kind of sanity checks to ensure that VMSA does not contain invalid value before the run.
Oh, I'm well aware of the number of sanity checks that are in VM-Enter ucode, and that's precisely why I'm of the opinion that letting the guest fuzz VMRUN is a non-trivial security risk for the host. I know of at least at least two VMX bugs (one erratum that I could find, one that must have been fixed with a ucode patch?) where ucode failed to detect invalid state. Those were "benign" in that they caused a missed VM-Fail but didn't corrupt CPU state, but it's not a stretch to imagine a ucode bug that leads to corruption of CPU state and a system crash.
The sheer number of checks involved, combined with the fact that there likely hasn't been much fuzzing of VM-Enter outside of the hardware vendor's own validation, means I'm not exactly brimming with confidence that VMRUN's ucode is perfect.
I fully acknowledge that the host kernel obviously "trusts" CPU ucode to a great extent. My point here is that the design exposes the host to unnecessary risk.
PATCH v5 45/45 KVM: SVM: Add module parameter to enable the SEV-SNP
In reply to Brijesh SinghAdd a module parameter than can be used to enable or disable the SEV-SNP feature. Now that KVM contains the support for the SNP set the GHCB hypervisor feature flag to indicate that SNP is supported.
--- arch/x86/kvm/svm/sev.c | 7 ++++--- arch/x86/kvm/svm/svm.h | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +4 -3
@@ -59,14 +59,15 @@ 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#endif /* CONFIG_KVM_AMD_SEV */ -/* enable/disable SEV-SNP support */ -static bool sev_snp_enabled; -#define AP_RESET_HOLD_NONE 0#define AP_RESET_HOLD_NAE_EVENT 1#define AP_RESET_HOLD_MSR_PROTO 2
arch/x86/kvm/svm/svm.h +1 -1
@@ -608,7 +608,7 @@ void svm_vcpu_unblocking(struct kvm_vcpu *vcpu);#define GHCB_VERSION_MAX 2ULL#define GHCB_VERSION_MIN 1ULL -#define GHCB_HV_FT_SUPPORTED 0 +#define GHCB_HV_FT_SUPPORTED (GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION)extern unsigned int max_sev_asid;
Signature · 1 line
2.17.1
Hi Brijesh,,
One high level discussion I'd like to have on these SNP KVM patches.
In these patches (V5) if a host userspace process writes a guest private page a SIGBUS is issued to that process. If the kernel writes a guest private page then the kernel panics due to the unhandled RMP fault page fault. This is an issue because not all writes into guest memory may come from a bug in the host. For instance a malicious or even buggy guest could easily point the host to writing a private page during the emulation of many virtual devices (virtio, NVMe, etc). For example if a well behaved guests behavior is to: start up a driver, select some pages to share with the guest, ask the host to convert them to shared, then use those pages for virtual device DMA, if a buggy guest forget the step to request the pages be converted to shared its easy to see how the host could rightfully write to private memory. I think we can better guarantee host reliability when running SNP guests without changing SNP’s security properties.
Here is an alternative to the current approach: On RMP violation (host or userspace) the page fault handler converts the page from private to shared to allow the write to continue. This pulls from s390’s error handling which does exactly this. See ‘arch_make_page_accessible()’. Additionally it adds less complexity to the SNP kernel patches, and requires no new ABI.
In the current (V5) KVM implementation if a userspace process generates an RMP violation (writes to guest private memory) the process receives a SIGBUS. At first glance, it would appear that user-space shouldn’t write to private memory. However, guaranteeing this in a generic fashion requires locking the RMP entries (via locks external to the RMP). Otherwise, a user-space process emulating a guest device IO may be vulnerable to having the guest memory (maliciously or by guest bug) converted to private while user-space emulation is happening. This results in a well behaved userspace process receiving a SIGBUS.
This proposal allows buggy and malicious guests to run under SNP without jeopardizing the reliability / safety of host processes. This is very important to a cloud service provider (CSP) since it’s common to have host wide daemons that write/read all guests, i.e. a single process could manage the networking for all VMs on the host. Crashing that singleton process kills networking for all VMs on the system.
This proposal also allows for minimal changes to the kexec flow and kdump. The new kexec kernel can simply update private pages to shared as it encounters them during their boot. This avoids needing to propagate the RMP state from kernel to kernel. Of course this doesn’t preserve any running VMs but is still useful for kdump crash dumps or quicker rekerneling for development with kexec.
This proposal does cause guest memory corruption for some bugs but one of SEV-SNP’s goals extended from SEV-ES’s goals is for guest’s to be able to detect when its memory has been corrupted / replayed by the host. So SNP already has features for allowing guests to detect this kind of memory corruption. Additionally this is very similar to a page of memory generating a machine check because of 2-bit memory corruption. In other words SNP guests must be enlightened and ready for these kinds of errors.
For an SNP guest running under this proposal the flow would look like this:
* Host gets a #PF because its trying to write to a private page.
* Host #PF handler updates the page to shared.
* Write continues normally.
* Guest accesses memory (r/w).
* Guest gets a #VC error because the page is not PVALIDATED
* Guest is now in control. Guest can terminate because its memory has been corrupted. Guest could try and continue to log the error to its owner.
A similar approach was introduced in the SNP patches V1 and V2 for kernel page fault handling. The pushback around this convert to shared approach was largely focused around the idea that the kernel has all the information about which pages are shared vs private so it should be able to check shared status before write to pages. After V2 the patches were updated to not have a kernel page fault handler for RMP violations (other than dumping state during a panic). The current patches protect the host with new post_{map,unmap}_gfn() function that checks if a page is shared before mapping it, then locks the page shared until unmapped. Given the discussions on ‘[Part2,v5,39/45] KVM:
SVM: Introduce ops for the post gfn map and unmap’ building a solution to do this is non trivial and adds new overheads to KVM. Additionally the current solution is local to the kernel. So a new ABI just now be created to allow the userspace VMM to access the kernel-side locks for this to work generically for the whole host. This is more complicated than this proposal and adding more lock holders seems like it could reduce performance further.
There are a couple corner cases with this approach. Under SNP guests can request their memory be changed into a VMSA. This VMSA page cannot be changed to shared while the vCPU associated with it is running. So KVM + the #PF handler will need something to kick vCPUs from running. Joerg believes that a possible fix for this could be a new MMU notifier in the kernel, then on the #PF we can go through the rmp and execute this vCPU kick callback.
Another corner case is the RMPUPDATE instruction is not guaranteed to succeed on first iteration. As noted above if the page is a VMSA it cannot be updated while the vCPU is running. Another issue is if the guest is running a RMPADJUST on a page it cannot be RMPUPDATED at that time. There is a lock for each RMP Entry so there is a race for these instructions. The vCPU kicking can solve this issue to be kicking all guest vCPUs which removes the chance for the race.
Since this proposal probably results in SNP guests terminating due to a page unexpectedly needing PVALIDATE. The approach could be simplified to just the KVM killing the guest. I think it's nicer to users to instead of unilaterally killing the guest allowing the unvalidated #VC exception to allow users to collect some additional debug information and any additional clean up work they would like to perform.
Thanks
Peter
Quoted 192 lines · Brijesh Singh
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 requestThe 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 interrupt security and migration and those feature will be added after the base support.
The series is based on the commit:
SNP part1 commit and
fa7a549d321a(kvm/next, next) KVM: x86: accept userspace interrupt only if no event is injectedTODO:
* Add support for command to ratelimit the guest message request.Changes since v4:
* Move the RMP entry definition to x86 specific header file.
* Move the dump RMP entry function to SEV specific file.
* UseBIT_ULLwhile defining the #PF bit fields.
* Add helper function to check the IOMMU support for SEV-SNP feature.
* Add helper functions for the page state transition.
* Map and unmap the pages from the direct map after page is added or removed in RMP table.
* Enforce the minimum SEV-SNP firmware version.
* Extend theLAUNCH_UPDATEto accept thebase_gfnand remove the logic to calculate the gfn from the hva.
* Add a check inLAUNCH_UPDATEto ensure that all the pages are shared before calling the PSP.
* Mark the memory failure when failing to remove the page from the RMP table or clearing the immutable bit.
* Exclude the encrypted hva range from the KSM.
* Remove the gfn tracking during thekvm_gfn_map()and use SRCU to syncronize the PSC and gfn mapping.
* Allow PSC on the registered hva range only.
* Add support for the Preferred GPA VMGEXIT.
* Simplify the PSC handling routines.
* Use thestatic_call()for the newly addedkvm_x86_ops.
* Remove the long-lived GHCB map.
* Move the snp enable module parameter to the end of the file.
* Remove thekvm_x86_opfor the RMP fault handling. Call the fault handler directly from the #NPF interception.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 theSNP_INITcommand 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 inarch/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 handleGUEST_REQUESTNAE event for attestation.
* Rename RMP table lookup helper.
* Drop typedef from rmpentry struct definition.
* Drop SNP static key and usecpu_feature_enabled()to check whether SEV-SNP is active.
* Multiple cleanup/fixes to address Boris review feedback.Brijesh Singh (40):
x86/cpufeatures: Add SEV-SNP CPU feature
iommu/amd: Introduce function to check SEV-SNP support 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: Invalid pages from direct map when adding it to RMP table x86/traps: Define RMP violation #PF error code
x86/fault: Add support to handle the RMP fault for user address x86/fault: Add support to dump RMP entry on fault
crypto: ccp: shutdown SEV firmware on kexec
crypto:ccp: Define the SEV-SNP commands
crypto: ccp: Add support to initialize the AMD-SP for SEV-SNP 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 theSNP_PLATFORM_STATUScommand
crypto: ccp: Add the SNP_{SET,GET}_EXT_CONFIG command
crypto: ccp: Provide APIs to query extended attestation report
KVM: SVM: Provide the Hypervisor Feature support VMGEXIT
KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
KVM: SVM: Add initial SEV-SNP support
KVM: SVM: AddKVM_SNP_INITcommand
KVM: SVM: AddKVM_SEV_SNP_LAUNCH_STARTcommand
KVM: SVM: AddKVM_SEV_SNP_LAUNCH_UPDATEcommand
KVM: SVM: Mark the private vma unmerable for SEV-SNP guests
KVM: SVM: AddKVM_SEV_SNP_LAUNCH_FINISHcommand
KVM: X86: Keep the NPT and RMP page level in sync
KVM: x86: Introducekvm_mmu_get_tdp_walk()for SEV-SNP use
KVM: x86: Define RMP page fault error bits for #NPF
KVM: x86: Update page-fault trace to log full 64-bit error code
KVM: SVM: Do not use long-lived GHCB map while setting scratch area
KVM: SVM: Remove the long-lived GHCB host map
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: SVM: Introduce ops for the post gfn map and unmap
KVM: x86: Export thekvm_zap_gfn_range()for the SNP use
KVM: SVM: Add support to handle the RMP nested page fault
KVM: SVM: Provide support forSNP_GUEST_REQUESTNAE event
KVM: SVM: Add module parameter to enable the SEV-SNPSean Christopherson (2):
KVM: x86/mmu: Move 'pfn' variable to caller ofdirect_page_fault()
KVM: x86/mmu: Introducekvm_mmu_map_tdp_page()for use by TDX and SNPTom 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 eventDocumentation/virt/coco/sevguest.rst | 55 + .../virt/kvm/amd-memory-encryption.rst | 102 + arch/x86/include/asm/cpufeatures.h | 1 + arch/x86/include/asm/disabled-features.h | 8 +- arch/x86/include/asm/kvm-x86-ops.h | 5 + arch/x86/include/asm/kvm_host.h | 20 + arch/x86/include/asm/msr-index.h | 6 + arch/x86/include/asm/sev-common.h | 28 + arch/x86/include/asm/sev.h | 45 + arch/x86/include/asm/svm.h | 7 + arch/x86/include/asm/trap_pf.h | 18 +- arch/x86/kernel/cpu/amd.c | 3 +- arch/x86/kernel/sev.c | 361 ++++ arch/x86/kvm/lapic.c | 5 +- arch/x86/kvm/mmu.h | 7 +- arch/x86/kvm/mmu/mmu.c | 84 +- arch/x86/kvm/svm/sev.c | 1676 ++++++++++++++++- arch/x86/kvm/svm/svm.c | 62 +- arch/x86/kvm/svm/svm.h | 74 +- arch/x86/kvm/trace.h | 40 +- arch/x86/kvm/x86.c | 92 +- arch/x86/mm/fault.c | 84 +- drivers/crypto/ccp/sev-dev.c | 924 ++++++++- drivers/crypto/ccp/sev-dev.h | 17 + drivers/crypto/ccp/sp-pci.c | 12 + drivers/iommu/amd/init.c | 30 + include/linux/iommu.h | 9 + include/linux/mm.h | 6 +- include/linux/psp-sev.h | 346 ++++ include/linux/sev.h | 32 + include/uapi/linux/kvm.h | 56 + include/uapi/linux/psp-sev.h | 60 + mm/memory.c | 13 + tools/arch/x86/include/asm/cpufeatures.h | 1 + 34 files changed, 4088 insertions(+), 201 deletions(-) create mode 100644 include/linux/sev.h--
2.17.1
On 11/12/21 7:43 AM, Peter Gonda wrote:
...
Quoted 6 lines
Here is an alternative to the current approach: On RMP violation (host or userspace) the page fault handler converts the page from private to shared to allow the write to continue. This pulls from s390’s error handling which does exactly this. See ‘arch_make_page_accessible()’. Additionally it adds less complexity to the SNP kernel patches, and requires no new ABI.
I think it's important to very carefully describe where these RMP page faults can occur within the kernel. They can obvious occur on things like:
copy_to_user(&user_buf, &kernel_buf, len);
That's not a big deal. Those can obviously handle page faults. We know exactly the instruction on which the fault can occur and we handle it gracefully.
*But*, these are harder:
get_user_pages(addr, len, &pages); spin_lock(&lock); ptr = kmap_atomic(pages[0]); *ptr = foo; // #PF here kunmap_atomic(ptr); spin_unlock(&lock); put_page(pages[0]);
In this case, the place where the fault happens are not especially well bounded. It can be in compiler-generated code. It can happen on any random instruction in there.
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Quoted 9 lines
This proposal does cause guest memory corruption for some bugs but one of SEV-SNP’s goals extended from SEV-ES’s goals is for guest’s to be able to detect when its memory has been corrupted / replayed by the host. So SNP already has features for allowing guests to detect this kind of memory corruption. Additionally this is very similar to a page of memory generating a machine check because of 2-bit memory corruption. In other words SNP guests must be enlightened and ready for these kinds of errors.
Quoted 9 lines
For an SNP guest running under this proposal the flow would look like this:
* Host gets a #PF because its trying to write to a private page.
* Host #PF handler updates the page to shared.
* Write continues normally.
* Guest accesses memory (r/w).
* Guest gets a #VC error because the page is not PVALIDATED
* Guest is now in control. Guest can terminate because its memory has been corrupted. Guest could try and continue to log the error to its owner.
This sounds like a _possible_ opportunity for the guest to do some extra handling. It's also quite possible that this #VC happens in a place that the guest can't handle.
Quoted 9 lines
A similar approach was introduced in the SNP patches V1 and V2 for kernel page fault handling. The pushback around this convert to shared approach was largely focused around the idea that the kernel has all the information about which pages are shared vs private so it should be able to check shared status before write to pages. After V2 the patches were updated to not have a kernel page fault handler for RMP violations (other than dumping state during a panic). The current patches protect the host with new post_{map,unmap}_gfn() function that checks if a page is shared before mapping it, then locks the page
Quoted 8 lines
shared until unmapped. Given the discussions on ‘[Part2,v5,39/45] KVM:
SVM: Introduce ops for the post gfn map and unmap’ building a solution to do this is non trivial and adds new overheads to KVM. Additionally the current solution is local to the kernel. So a new ABI just now be created to allow the userspace VMM to access the kernel-side locks for this to work generically for the whole host. This is more complicated than this proposal and adding more lock holders seems like it could reduce performance further.
The locking is complicated. But, I think it is necessary. Once the kernel can map private memory, it can access it in random spots. It's hard to make random kernel code recoverable from faults.
Borislav Petkov
maintainerQuoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
So I'm currently under the impression that random host->guest accesses should not happen if not previously agreed upon by both.
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Quoted 3 lines
This sounds like a _possible_ opportunity for the guest to do some extra handling. It's also quite possible that this #VC happens in a place that the guest can't handle.
How? It'll get a #VC when it first touches that page.
I'd say the #VC handler should be able to deal with it...
Thx.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteSean Christopherson
maintainerQuoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.
Key word "should".
Quoted 7 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Quoted 4 lines · Peter Gonda
Here is an alternative to the current approach: On RMP violation (host or userspace) the page fault handler converts the page from private to shared to allow the write to continue. This pulls from s390’s error handling which does exactly this. See ‘arch_make_page_accessible()’.
Ah, after further reading, s390 does _not_ do implicit private=>shared conversions.
s390's arch_make_page_accessible() is somewhat similar, but it is not a direct comparison. IIUC, it exports and integrity protects the data and thus preserves the guest's data in an encrypted form, e.g. so that it can be swapped to disk. And if the host corrupts the data, attempting to convert it back to secure on a subsequent guest access will fail.
The host kernel's handling of the "convert to secure" failures doesn't appear to be all that robust, e.g. it looks like there are multiple paths where the error is dropped on the floor and the guest is resumed , but IMO soft hanging the guest is still better than inducing a fault in the guest, and far better than potentially coercing the guest into reading corrupted memory ("spurious" PVALIDATE). And s390's behavior is fixable since it's purely a host error handling problem.
To truly make a page shared, s390 requires the guest to call into the ultravisor to make a page shared. And on the host side, the host can pin a page as shared to prevent the guest from unsharing it while the host is accessing it as a shared page.
So, inducing #VC is similar in the sense that a malicious s390 can also DoS itself, but is quite different in that (AFAICT) s390 does not create an attack surface where a malicious or buggy host userspace can induce faults in the guest, or worst case in SNP, exploit a buggy guest into accepting and accessing corrupted data.
It's also different in that s390 doesn't implicitly convert between shared and private. Functionally, it doesn't really change the end result because a buggy host that writes guest private memory will DoS the guest (by inducing a #VC or corrupting exported data), but at least for s390 there's a sane, legitimate use case for accessing guest private memory (swap and maybe migration?), whereas for SNP, IMO implicitly converting to shared on a host access is straight up wrong.
Quoted 2 lines
Additionally it adds less complexity to the SNP kernel patches, and requires no new ABI.
I disagree, this would require "new" ABI in the sense that it commits KVM to supporting SNP without requiring userspace to initiate any and all conversions between shared and private. Which in my mind is the big elephant in the room:
do we want to require new KVM (and kernel?) ABI to allow/force userspace to explicitly declare guest private memory for TDX _and_ SNP, or just TDX?
Borislav Petkov
maintainerQuoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
What do you suggest instead?
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteSean Christopherson
maintainerQuoted 4 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
What do you suggest instead?
Let userspace decide what is mapped shared and what is mapped private. The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.
This is the direction KVM TDX support is headed, though it's obviously still a WIP.
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.
Borislav Petkov
maintainerQuoted 1 line · Sean Christopherson
Let userspace decide what is mapped shared and what is mapped private.
With "userspace", you mean the *host* userspace?
Quoted 11 lines
The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
That SIGSEGV is generated by the host kernel, I presume, after it checks whether the memory belongs to the guest?
Quoted 1 line
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
Quoted 1 line
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.
Yah, that's the easy one.
Quoted 7 lines
This is the direction KVM TDX support is headed, though it's obviously still a WIP.
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.
I like the explicit nature of this but devil's in the detail and I'm no virt guy...
Quoted 6 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.
Yah, the #MC thing sounds like someone didn't think things through. ;-\
Thx.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteQuoted 18 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Let userspace decide what is mapped shared and what is mapped private.
With "userspace", you mean the *host* userspace?
Quoted 11 lines
The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
Quoted 8 lines
That SIGSEGV is generated by the host kernel, I presume, after it checks whether the memory belongs to the guest?
Quoted 1 line
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Quoted 7 lines
Quoted 2 lines
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.
Yah, that's the easy one.
Quoted 2 lines
This is the direction KVM TDX support is headed, though it's obviously still a WIP.
Quoted 8 lines
Quoted 5 lines
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.I like the explicit nature of this but devil's in the detail and I'm no virt guy...
This seems like a reasonable approach that can help with the issue of terminating the entity behaving poorly. Could this feature be an improvement that comes later? This improvement could be gated behind a per VM KVM CAP, a kvm module param, or insert other solution here, to not blind side userspace with this change?
Quoted 9 lines
Quoted 7 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.Yah, the #MC thing sounds like someone didn't think things through. ;-\
Yes #MC in TDX seems much harder to deal with than the #PF for SNP. I'd propose TDX keeps the host kernel safe bug not have that solution block SNP. As suggested above I like the idea but it seems like it can come as a future improvement to SNP support.
Quoted 8 lines
Thx.
--
Regards/Gruss,
Boris.
Andy Lutomirski
maintainerQuoted 66 lines · Peter Gonda
Quoted 18 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Let userspace decide what is mapped shared and what is mapped private.
With "userspace", you mean the *host* userspace?
Quoted 11 lines
The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
Quoted 8 lines
That SIGSEGV is generated by the host kernel, I presume, after it checks whether the memory belongs to the guest?
Quoted 1 line
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Quoted 7 lines
Quoted 2 lines
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.
Yah, that's the easy one.
Quoted 2 lines
This is the direction KVM TDX support is headed, though it's obviously still a WIP.
Quoted 8 lines
Quoted 5 lines
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.I like the explicit nature of this but devil's in the detail and I'm no virt guy...
This seems like a reasonable approach that can help with the issue of terminating the entity behaving poorly. Could this feature be an improvement that comes later? This improvement could be gated behind a per VM KVM CAP, a kvm module param, or insert other solution here, to not blind side userspace with this change?
Quoted 8 lines
Quoted 7 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.
Quoted 7 lines
Quoted 1 line
Yah, the #MC thing sounds like someone didn't think things through. ;-\
Yes #MC in TDX seems much harder to deal with than the #PF for SNP. I'd propose TDX keeps the host kernel safe bug not have that solution block SNP. As suggested above I like the idea but it seems like it can come as a future improvement to SNP support.
Can you clarify what type of host bug you're talking about here? We're talking about the host kernel reading or writing guest private memory through the direct map or kmap, right? It seems to me that the way this happens is:
struct page *guest_page = (get and refcount a guest page);
...
guest switches the page to private;
...
read or write the page via direct map or kmap.
This naively *looks* like something a malicious or buggy guest could induce the host kernel to do. But I think that, if this actually occurs, it's an example of a much more severe host bug. In particular, there is nothing special about the guest switching a page to private -- the guest or QEMU could just as easily have freed (hotunplugged) a shared guest page or ballooned it or swapped it or otherwise deallocated it. And, if the host touches a page/pfn that the guest has freed, this is UAF, is a huge security hole if the guest has any degree of control, and needs to kill the host kernel if detected.
Now we can kind of sweep it under the rug by saying that changing a page from shared to private isn't really freeing the page -- it's just modifying the usage of the page. But to me that sounds like saying "reusing a former user memory page as a pagetable isn't *really* freeing it if the kernel kept a pointer around the whole time and the page allocator wasn't involved".
So let's please just consider these mode transitions to be equivalent to actually freeing the page at least from a locking perspective, and then the way to prevent these bugs and the correct action to take if they occur is clear.
(On TDX, changing a page shared/private state is very much like freeing and reallocating -- they're in different page tables and, in principle anyway, there is no actual relationship between a shared page and a supposedly matching private page except that some bits of the GPA happen to match. The hardware the TD module fully support both being mapped at once at the same "address", at least according to the specs I've read.)
--Andy
Borislav Petkov
maintainerQuoted 7 lines · Andy Lutomirski
Can you clarify what type of host bug you're talking about here? We're talking about the host kernel reading or writing guest private memory through the direct map or kmap, right? It seems to me that the way this happens is:
struct page
*guest_page= (get and refcount a guest page);
Quoted 7 lines
...
guest switches the page to private;
...
read or write the page via direct map or kmap.
Maybe I don't understand your example properly but on this access here, the page is not gonna be validated anymore in the RMP table, i.e., on the next access, the guest will get a #VC.
Or are you talking about a case where the host gets a reference to a guest page and the guest - in the meantime - PVALIDATEs that page and thus converts it into a private page?
So that case is simple: if the guest really deliberately gave that page to the host to do stuff to it and it converted it to private in the meantime, guest dies.
That's why it would make sense to have explicit consensus between guest and host which pages get shared. Everything else is not going to be allowed and the entity at fault pays the consequences.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteQuoted 76 lines · Andy Lutomirski
Quoted 66 lines · Peter Gonda
Quoted 18 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Let userspace decide what is mapped shared and what is mapped private.
With "userspace", you mean the *host* userspace?
Quoted 11 lines
The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
Quoted 8 lines
That SIGSEGV is generated by the host kernel, I presume, after it checks whether the memory belongs to the guest?
Quoted 1 line
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Quoted 7 lines
Quoted 2 lines
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.
Yah, that's the easy one.
Quoted 2 lines
This is the direction KVM TDX support is headed, though it's obviously still a WIP.
Quoted 8 lines
Quoted 5 lines
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.I like the explicit nature of this but devil's in the detail and I'm no virt guy...
This seems like a reasonable approach that can help with the issue of terminating the entity behaving poorly. Could this feature be an improvement that comes later? This improvement could be gated behind a per VM KVM CAP, a kvm module param, or insert other solution here, to not blind side userspace with this change?
Quoted 8 lines
Quoted 7 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.Quoted 7 lines
Quoted 1 line
Yah, the #MC thing sounds like someone didn't think things through. ;-\
Yes #MC in TDX seems much harder to deal with than the #PF for SNP. I'd propose TDX keeps the host kernel safe bug not have that solution block SNP. As suggested above I like the idea but it seems like it can come as a future improvement to SNP support.
Quoted 4 lines
Can you clarify what type of host bug you're talking about here? We're talking about the host kernel reading or writing guest private memory through the direct map or kmap, right? It seems to me that the way this happens is:
An example bug I am discussing looks like this:
* Guest wants to use virt device on some shared memory.
* Guest forgets to ask host to RMPUPDATE page to shared state (hypervisor owned)
* Guest points virt device at pages
* Virt device writes to page, since they are still private guest userspace causes RMP fault #PF.
This seems like a trivial attack malicious guests could do.
Quoted 22 lines
struct page
*guest_page= (get and refcount a guest page);...
guest switches the page to private;
...
read or write the page via direct map or kmap.
This naively *looks* like something a malicious or buggy guest could induce the host kernel to do. But I think that, if this actually occurs, it's an example of a much more severe host bug. In particular, there is nothing special about the guest switching a page to private -- the guest or QEMU could just as easily have freed (hotunplugged) a shared guest page or ballooned it or swapped it or otherwise deallocated it. And, if the host touches a page/pfn that the guest has freed, this is UAF, is a huge security hole if the guest has any degree of control, and needs to kill the host kernel if detected.
Quoted 6 lines
Now we can kind of sweep it under the rug by saying that changing a page from shared to private isn't really freeing the page -- it's just modifying the usage of the page. But to me that sounds like saying "reusing a former user memory page as a pagetable isn't *really* freeing it if the kernel kept a pointer around the whole time and the page allocator wasn't involved".
This is different from the QEMU hotunplug because in that case QEMU is aware of the memory change. Currently QEMU (userspace) is completely unaware of which pages are shared and which are private. So how does userspace know the memory has been "freed"?
Quoted 14 lines
So let's please just consider these mode transitions to be equivalent to actually freeing the page at least from a locking perspective, and then the way to prevent these bugs and the correct action to take if they occur is clear.
(On TDX, changing a page shared/private state is very much like freeing and reallocating -- they're in different page tables and, in principle anyway, there is no actual relationship between a shared page and a supposedly matching private page except that some bits of the GPA happen to match. The hardware the TD module fully support both being mapped at once at the same "address", at least according to the specs I've read.)
--Andy
Sean Christopherson
maintainerQuoted 6 lines · Peter Gonda
Quoted 5 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Let userspace decide what is mapped shared and what is mapped private.
With "userspace", you mean the *host* userspace?
Yep.
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
Quoted 4 lines
Quoted 4 lines
Quoted 1 line
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
That SIGSEGV is generated by the host kernel, I presume, after it checks whether the memory belongs to the guest?
Yep.
Quoted 6 lines
Quoted 5 lines
Quoted 1 line
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
Quoted 7 lines
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Plenty of examples. kvm_spurious_fault() is the obvious one. Any NULL pointer deref will lead to a BUG, etc... And it's not just KVM, e.g. it's possible, if unlikely, for the core kernel to run into guest private memory (e.g. if the kernel botches an RMP change), and if that happens there's no guarantee that the kernel can recover.
I fully agree that ideally KVM would have a better sense of self-preservation, but IMO that's an orthogonal discussion.
Quoted 12 lines
Quoted 11 lines
Quoted 3 lines
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Quoted 8 lines
Plenty of examples.
kvm_spurious_fault()is the obvious one. Any NULL pointer deref will lead to a BUG, etc... And it's not just KVM, e.g. it's possible, if unlikely, for the core kernel to run into guest private memory (e.g. if the kernel botches an RMP change), and if that happens there's no guarantee that the kernel can recover.I fully agree that ideally KVM would have a better sense of self-preservation, but IMO that's an orthogonal discussion.
I don't think we should treat the possibility of crashing the host with live VMs nonchalantly. It's a big deal. Doing so has big implications on the probability that any cloud vendor wil bee able to deploy this code to production. And aren't cloud vendors one of the main use cases for all of this confidential compute stuff? I'm honestly surprised that so many people are OK with crashing the host.
Sean Christopherson
maintainerQuoted 21 lines · Marc Orr
Quoted 12 lines
Quoted 11 lines
Quoted 3 lines
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Quoted 8 lines
Plenty of examples.
kvm_spurious_fault()is the obvious one. Any NULL pointer deref will lead to a BUG, etc... And it's not just KVM, e.g. it's possible, if unlikely, for the core kernel to run into guest private memory (e.g. if the kernel botches an RMP change), and if that happens there's no guarantee that the kernel can recover.I fully agree that ideally KVM would have a better sense of self-preservation, but IMO that's an orthogonal discussion.
Quoted 6 lines
I don't think we should treat the possibility of crashing the host with live VMs nonchalantly. It's a big deal. Doing so has big implications on the probability that any cloud vendor wil bee able to deploy this code to production. And aren't cloud vendors one of the main use cases for all of this confidential compute stuff? I'm honestly surprised that so many people are OK with crashing the host.
I'm not treating it nonchalantly, merely acknowledging that (a) some flavors of kernel bugs (or hardware issues!) are inherently fatal to the system, and (b) crashing the host may be preferable to continuing on in certain cases, e.g. if continuing on has a high probablity of corrupting guest data.
Quoted 30 lines · Sean Christopherson
Quoted 21 lines · Marc Orr
Quoted 12 lines
Quoted 11 lines
Quoted 3 lines
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Quoted 8 lines
Plenty of examples.
kvm_spurious_fault()is the obvious one. Any NULL pointer deref will lead to a BUG, etc... And it's not just KVM, e.g. it's possible, if unlikely, for the core kernel to run into guest private memory (e.g. if the kernel botches an RMP change), and if that happens there's no guarantee that the kernel can recover.I fully agree that ideally KVM would have a better sense of self-preservation, but IMO that's an orthogonal discussion.
Quoted 6 lines
I don't think we should treat the possibility of crashing the host with live VMs nonchalantly. It's a big deal. Doing so has big implications on the probability that any cloud vendor wil bee able to deploy this code to production. And aren't cloud vendors one of the main use cases for all of this confidential compute stuff? I'm honestly surprised that so many people are OK with crashing the host.
Quoted 4 lines
I'm not treating it nonchalantly, merely acknowledging that (a) some flavors of kernel bugs (or hardware issues!) are inherently fatal to the system, and (b) crashing the host may be preferable to continuing on in certain cases, e.g. if continuing on has a high probablity of corrupting guest data.
I disagree. Crashing the host -- and _ALL_ of its VMs (including non-confidential VMs) -- is not preferable to crashing a single SNP VM. Especially when that SNP VM is guaranteed to detect the memory corruption and react accordingly.
Sean Christopherson
maintainerQuoted 31 lines · Marc Orr
Quoted 30 lines · Sean Christopherson
Quoted 27 lines · Marc Orr
Quoted 12 lines
Quoted 11 lines
Quoted 3 lines
If *it* is the host kernel, then you probably shouldn't do that - otherwise you just killed the host kernel on which all those guests are running.
I agree, it seems better to terminate the single guest with an issue. Rather than killing the host (and therefore all guests). So I'd suggest even in this case we do the 'convert to shared' approach or just outright terminate the guest.
Are there already examples in KVM of a KVM bug in servicing a VM's request results in a BUG/panic/oops? That seems not ideal ever.
Quoted 8 lines
Plenty of examples.
kvm_spurious_fault()is the obvious one. Any NULL pointer deref will lead to a BUG, etc... And it's not just KVM, e.g. it's possible, if unlikely, for the core kernel to run into guest private memory (e.g. if the kernel botches an RMP change), and if that happens there's no guarantee that the kernel can recover.I fully agree that ideally KVM would have a better sense of self-preservation, but IMO that's an orthogonal discussion.
I don't think we should treat the possibility of crashing the host with live VMs nonchalantly. It's a big deal. Doing so has big implications on the probability that any cloud vendor wil bee able to deploy this code to production. And aren't cloud vendors one of the main use cases for all of this confidential compute stuff? I'm honestly surprised that so many people are OK with crashing the host.
Quoted 8 lines
Quoted 4 lines
I'm not treating it nonchalantly, merely acknowledging that (a) some flavors of kernel bugs (or hardware issues!) are inherently fatal to the system, and (b) crashing the host may be preferable to continuing on in certain cases, e.g. if continuing on has a high probablity of corrupting guest data.
I disagree. Crashing the host -- and _ALL_ of its VMs (including non-confidential VMs) -- is not preferable to crashing a single SNP VM.
We're in violent agreement. I fully agree that, when allowed by the architecture, injecting an error into the guest is preferable to killing the VM, which is in turn preferable to crashing the host.
What I'm saying is that there are classes of bugs where injecting an error is not allowed/feasible, and where killing an individual VM is not correct/feasible.
The canonical example of this escalating behavior is an uncorrectable ECC #MC. If the bad page is guest memory and the guest vCPU model supports MCA, then userspace can inject an #MC into the guest so that the guest can take action and hopefully not simply die. If the bad page is in the guest but the guest doesn't support #MC injection, the guest effectively gets killed. And if the #MC is in host kernel memory that can't be offlined, e.g. hits the IDT, then the whole system comes crashing down.
Quoted 2 lines
Especially when that SNP VM is guaranteed to detect the memory corruption and react accordingly.
For the record, we can make no such guarantees about the SNP VM. Yes, the VM _should_ do the right thing when handed a #VC, but bugs happen, otherwise we wouldn't be having this discussion.
Quoted 4 lines · Sean Christopherson
I'm not treating it nonchalantly, merely acknowledging that (a) some flavors of kernel bugs (or hardware issues!) are inherently fatal to the system, and (b) crashing the host may be preferable to continuing on in certain cases, e.g. if continuing on has a high probablity of corrupting guest data.
The problem here is that for SNP host-side RMP faults it will often not be clear at fault-time if it was caused by wrong guest or host behavior.
I agree with Marc that crashing the host is not the right thing to do in this situation. Instead debug data should be collected to do further post-mortem analysis.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Sean Christopherson
maintainerQuoted 6 lines · Joerg Roedel
Quoted 4 lines · Sean Christopherson
I'm not treating it nonchalantly, merely acknowledging that (a) some flavors of kernel bugs (or hardware issues!) are inherently fatal to the system, and (b) crashing the host may be preferable to continuing on in certain cases, e.g. if continuing on has a high probablity of corrupting guest data.
Quoted 6 lines
The problem here is that for SNP host-side RMP faults it will often not be clear at fault-time if it was caused by wrong guest or host behavior.
I agree with Marc that crashing the host is not the right thing to do in this situation. Instead debug data should be collected to do further post-mortem analysis.
Again, I am not saying that any RMP #PF violation is an immediate, "crash the host". It should be handled exactly like any other #PF due to permission violation. The only wrinkle added by the RMP is that the #PF can be due to permissions on the GPA itself, but even that is not unique, e.g. see the proposed KVM XO support that will hopefully still land someday.
If the guest violates the current permissions, it (indirectly) gets a #VC. If host userspace violates permissions, it gets SIGSEGV. If the host kernel violates permissions, then it reacts to the #PF in whatever way it can. What I am saying is that in some cases, there is _zero_ chance of recovery in the host and so crashing
the entire system is inevitable. E.g. if the host kernel hits an RMP #PF when
vectoring a #GP because the IDT lookup somehow triggers an RMP violation, then the host is going into triple fault shutdown.
Quoted 29 lines · Sean Christopherson
Quoted 4 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
What do you suggest instead?
Let userspace decide what is mapped shared and what is mapped private. The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.This is the direction KVM TDX support is headed, though it's obviously still a WIP.
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.
Quoted 6 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.
In this proposal, consider a guest driver instructing a device to DMA write a 1 GB memory buffer. A well-behaved guest driver will ensure that the entire 1 GB is marked shared. But what about a malicious or buggy guest? Let's assume a bad guest driver instructs the device to write guest private memory.
So now, the virtual device, which might be implemented as some host side process, needs to (1) check and lock all 4k constituent RMP entries (so they're not converted to private while the DMA write is taking palce), (2) write the 1 GB buffer, and (3) unlock all 4 k constituent RMP entries? If I'm understanding this correctly, then the synchronization will be prohibitively expensive.
Quoted 6 lines · Marc Orr
In this proposal, consider a guest driver instructing a device to DMA write a 1 GB memory buffer. A well-behaved guest driver will ensure that the entire 1 GB is marked shared. But what about a malicious or buggy guest? Let's assume a bad guest driver instructs the device to write guest private memory.
Quoted 6 lines
So now, the virtual device, which might be implemented as some host side process, needs to (1) check and lock all 4k constituent RMP entries (so they're not converted to private while the DMA write is taking palce), (2) write the 1 GB buffer, and (3) unlock all 4 k constituent RMP entries? If I'm understanding this correctly, then the synchronization will be prohibitively expensive.
Are you taking about a 1GB *mapping* here? As in, something us using a 1GB page table entry to map the 1GB memory buffer? That was the only case where I knew we needed coordination between neighbor RMP entries and host memory accesses.
That 1GB problem _should_ be impossible. I thought we settled on disabling hugetlbfs and fracturing the whole of the direct map down to 4k.
Quoted 15 lines · Dave Hansen
Quoted 6 lines · Marc Orr
In this proposal, consider a guest driver instructing a device to DMA write a 1 GB memory buffer. A well-behaved guest driver will ensure that the entire 1 GB is marked shared. But what about a malicious or buggy guest? Let's assume a bad guest driver instructs the device to write guest private memory.
Quoted 6 lines
So now, the virtual device, which might be implemented as some host side process, needs to (1) check and lock all 4k constituent RMP entries (so they're not converted to private while the DMA write is taking palce), (2) write the 1 GB buffer, and (3) unlock all 4 k constituent RMP entries? If I'm understanding this correctly, then the synchronization will be prohibitively expensive.
Quoted 7 lines
Are you taking about a 1GB *mapping* here? As in, something us using a 1GB page table entry to map the 1GB memory buffer? That was the only case where I knew we needed coordination between neighbor RMP entries and host memory accesses.
That 1GB problem _should_ be impossible. I thought we settled on disabling hugetlbfs and fracturing the whole of the direct map down to 4k.
No. I was trying to give an example where a host-side process is virtualizing a DMA write over a large buffer that consists of a lot of 4k or 2MB RMP entries. I picked 1 GB as an arbitrary example.
Andy Lutomirski
maintainerQuoted 43 lines · Marc Orr
Quoted 29 lines · Sean Christopherson
Quoted 4 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
What do you suggest instead?
Let userspace decide what is mapped shared and what is mapped private. The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.This is the direction KVM TDX support is headed, though it's obviously still a WIP.
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.Quoted 6 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.In this proposal, consider a guest driver instructing a device to DMA write a 1 GB memory buffer. A well-behaved guest driver will ensure that the entire 1 GB is marked shared. But what about a malicious or buggy guest? Let's assume a bad guest driver instructs the device to write guest private memory.
Quoted 6 lines
So now, the virtual device, which might be implemented as some host side process, needs to (1) check and lock all 4k constituent RMP entries (so they're not converted to private while the DMA write is taking palce), (2) write the 1 GB buffer, and (3) unlock all 4 k constituent RMP entries? If I'm understanding this correctly, then the synchronization will be prohibitively expensive.
Let's consider a very very similar scenario: consider a guest driver setting up a 1 GB DMA buffer. The virtual device, implemented as host process, needs to (1) map (and thus lock *or* be prepared for faults) in 1GB / 4k pages of guest memory (so they're not *freed* while the DMA write is taking place), (2) write the buffer, and (3) unlock all the pages. Or it can lock them at setup time and keep them locked for a long time if that's appropriate.
Sure, the locking is expensive, but it's nonnegotiable. The RMP issue is just a special case of the more general issue that the host MUST NOT ACCESS GUEST MEMORY AFTER IT'S FREED.
--Andy
Quoted 54 lines · Andy Lutomirski
Quoted 43 lines · Marc Orr
Quoted 29 lines · Sean Christopherson
Quoted 4 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
What do you suggest instead?
Let userspace decide what is mapped shared and what is mapped private. The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.This is the direction KVM TDX support is headed, though it's obviously still a WIP.
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.Quoted 6 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.In this proposal, consider a guest driver instructing a device to DMA write a 1 GB memory buffer. A well-behaved guest driver will ensure that the entire 1 GB is marked shared. But what about a malicious or buggy guest? Let's assume a bad guest driver instructs the device to write guest private memory.
Quoted 6 lines
So now, the virtual device, which might be implemented as some host side process, needs to (1) check and lock all 4k constituent RMP entries (so they're not converted to private while the DMA write is taking palce), (2) write the 1 GB buffer, and (3) unlock all 4 k constituent RMP entries? If I'm understanding this correctly, then the synchronization will be prohibitively expensive.
Quoted 3 lines
Let's consider a very very similar scenario: consider a guest driver setting up a 1 GB DMA buffer. The virtual device, implemented as host process, needs to (1) map (and thus lock *or* be prepared for faults) in 1GB / 4k pages of guest memory (so they're not *freed* while the DMA write is taking place), (2) write the buffer, and (3) unlock all the pages. Or it can lock them at setup time and keep them locked for a long time if that's appropriate.
Sure, the locking is expensive, but it's nonnegotiable. The RMP issue is just a special case of the more general issue that the host MUST NOT ACCESS GUEST MEMORY AFTER IT'S FREED.
Good point.
Quoted 56 lines · Marc Orr
Quoted 54 lines · Andy Lutomirski
Quoted 49 lines · Marc Orr
Quoted 29 lines · Sean Christopherson
Quoted 4 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
What do you suggest instead?
Let userspace decide what is mapped shared and what is mapped private. The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.This is the direction KVM TDX support is headed, though it's obviously still a WIP.
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.Quoted 6 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.In this proposal, consider a guest driver instructing a device to DMA write a 1 GB memory buffer. A well-behaved guest driver will ensure that the entire 1 GB is marked shared. But what about a malicious or buggy guest? Let's assume a bad guest driver instructs the device to write guest private memory.
So now, the virtual device, which might be implemented as some host side process, needs to (1) check and lock all 4k constituent RMP entries (so they're not converted to private while the DMA write is taking palce), (2) write the 1 GB buffer, and (3) unlock all 4 k constituent RMP entries? If I'm understanding this correctly, then the synchronization will be prohibitively expensive.
Quoted 5 lines
Quoted 3 lines
Let's consider a very very similar scenario: consider a guest driver setting up a 1 GB DMA buffer. The virtual device, implemented as host process, needs to (1) map (and thus lock *or* be prepared for faults) in 1GB / 4k pages of guest memory (so they're not *freed* while the DMA write is taking place), (2) write the buffer, and (3) unlock all the pages. Or it can lock them at setup time and keep them locked for a long time if that's appropriate.
Sure, the locking is expensive, but it's nonnegotiable. The RMP issue is just a special case of the more general issue that the host MUST NOT ACCESS GUEST MEMORY AFTER IT'S FREED.
Good point.
Thanks for the responses Andy.
Having a way for userspace to lock pages as shared was an idea I just proposed the simplest solution to start the conversation. So what we could do here is change map to error if the selected region has private pages, if the region is mapped we can then lock the pages shared. Now processes mapping guest memory that are well behaved can be safe from RMP violations. That seems like a reasonable solution for allowing userspace to know if guest memory is accessible or not. Or do you have other ideas to meet your other comment:
Quoted 4 lines
SEV-SNP, TDX, and any reasonable software solution all require that the host know which pages are private and which pages are shared. Sure, the old SEV-ES Linux host implementation was very simple, but it's nasty and fundamentally can't support migration.
Sean Christopherson
maintainerQuoted 15 lines · Peter Gonda
Quoted 14 lines · Marc Orr
Quoted 11 lines · Andy Lutomirski
Let's consider a very very similar scenario: consider a guest driver setting up a 1 GB DMA buffer. The virtual device, implemented as host process, needs to (1) map (and thus lock *or* be prepared for faults) in 1GB / 4k pages of guest memory (so they're not *freed* while the DMA write is taking place), (2) write the buffer, and (3) unlock all the pages. Or it can lock them at setup time and keep them locked for a long time if that's appropriate.
Sure, the locking is expensive, but it's nonnegotiable. The RMP issue is just a special case of the more general issue that the host MUST NOT ACCESS GUEST MEMORY AFTER IT'S FREED.
Quoted 6 lines
Quoted 1 line
Good point.
Thanks for the responses Andy.
Having a way for userspace to lock pages as shared was an idea I just proposed the simplest solution to start the conversation.
Assuming you meant that to read:
Having a way for userspace to lock pages as shared is an alternative idea; I just proposed the simplest solution to start the conversation.
The unmapping[*] guest private memory proposal is essentially that, a way for userspace to "lock" the state of a page by requiring all conversions to be initiated by userspace and by providing APIs to associate a pfn 1:1 with a KVM instance, i.e. lock a pfn to a guest.
Andy's DMA example brings up a very good point though. If the shared and private variants of a given GPA are _not_ required to point at a single PFN, which is the case in the current unmapping proposal, userspace doesn't need to do any additional juggling to track guest conversions across multiple processes.
Any process that's accessing guest (shared!) memory simply does its locking as normal, which as Andy pointed out, is needed for correctness today. If the guest requests a conversion from shared=>private without first ensuring the gfn is unused (by a host "device"), the host will side will continue accessing the old, shared memory, which it locked, while the guest will be doing who knows what. And if the guest provides a GPA that isn't mapped shared in the VMM's address space, it's conceptually no different than if the guest provided a completely bogus GPA, which again needs to be handled today.
In other words, if done properly, differentiating private from shared shouldn't be a heavy lift for host userspace.
[*] Actually unmapping memory may not be strictly necessary for SNP because a
#PF(RMP) is likely just as good as a #PF(!PRESENT) when both are treated as fatal, but the rest of the proposal that allows KVM to understand the stage of a page and exit to userspace accordingly applies.
Quoted 47 lines · Sean Christopherson
Quoted 15 lines · Peter Gonda
Quoted 14 lines · Marc Orr
Quoted 11 lines · Andy Lutomirski
Let's consider a very very similar scenario: consider a guest driver setting up a 1 GB DMA buffer. The virtual device, implemented as host process, needs to (1) map (and thus lock *or* be prepared for faults) in 1GB / 4k pages of guest memory (so they're not *freed* while the DMA write is taking place), (2) write the buffer, and (3) unlock all the pages. Or it can lock them at setup time and keep them locked for a long time if that's appropriate.
Sure, the locking is expensive, but it's nonnegotiable. The RMP issue is just a special case of the more general issue that the host MUST NOT ACCESS GUEST MEMORY AFTER IT'S FREED.
Quoted 6 lines
Quoted 1 line
Good point.
Thanks for the responses Andy.
Having a way for userspace to lock pages as shared was an idea I just proposed the simplest solution to start the conversation.
Assuming you meant that to read:
Having a way for userspace to lock pages as shared is an alternative idea; I just proposed the simplest solution to start the conversation.
The unmapping[*] guest private memory proposal is essentially that, a way for userspace to "lock" the state of a page by requiring all conversions to be initiated by userspace and by providing APIs to associate a pfn 1:1 with a KVM instance, i.e. lock a pfn to a guest.
Andy's DMA example brings up a very good point though. If the shared and private variants of a given GPA are _not_ required to point at a single PFN, which is the case in the current unmapping proposal, userspace doesn't need to do any additional juggling to track guest conversions across multiple processes.
Any process that's accessing guest (shared!) memory simply does its locking as normal, which as Andy pointed out, is needed for correctness today. If the guest requests a conversion from shared=>private without first ensuring the gfn is unused (by a host "device"), the host will side will continue accessing the old, shared memory, which it locked, while the guest will be doing who knows what. And if the guest provides a GPA that isn't mapped shared in the VMM's address space, it's conceptually no different than if the guest provided a completely bogus GPA, which again needs to be handled today.
Quoted 7 lines
In other words, if done properly, differentiating private from shared shouldn't be a heavy lift for host userspace.
[*] Actually unmapping memory may not be strictly necessary for SNP because a
#PF(RMP) is likely just as good as a #PF(!PRESENT) when both are treated as fatal, but the rest of the proposal that allows KVM to understand the stage of a page and exit to userspace accordingly applies.
Thanks for this explanation. When you write "while the guest will be doing who knows what":
Isn't that a large weakness of this proposal? To me, it seems better for debuggability to corrupt the private memory (i.e., convert the page to shared) so the guest can detect the issue via a PVALIDATE failure.
The main issue I see with corrupting the guest memory is that we may not know whether the host is at fault or the guest. Though, we can probably in many cases be sure it's the host, if the pid associated with the page fault is NOT a process associated with virtualization. But if it is a process associated with virtualization, we legitimately might not know. (I think if the pid is the kernel itself, it's probably a host-side bug, but I'm still not confident on this; for example, the guest might be able to coerce KVM's built-in emulator to write guest private memory.)
Sean Christopherson
maintainerQuoted 36 lines · Marc Orr
Quoted 27 lines · Sean Christopherson
Quoted 2 lines · Peter Gonda
Having a way for userspace to lock pages as shared was an idea I just proposed the simplest solution to start the conversation.
Assuming you meant that to read:
Having a way for userspace to lock pages as shared is an alternative idea; I just proposed the simplest solution to start the conversation.
The unmapping[*] guest private memory proposal is essentially that, a way for userspace to "lock" the state of a page by requiring all conversions to be initiated by userspace and by providing APIs to associate a pfn 1:1 with a KVM instance, i.e. lock a pfn to a guest.
Andy's DMA example brings up a very good point though. If the shared and private variants of a given GPA are _not_ required to point at a single PFN, which is the case in the current unmapping proposal, userspace doesn't need to do any additional juggling to track guest conversions across multiple processes.
Any process that's accessing guest (shared!) memory simply does its locking as normal, which as Andy pointed out, is needed for correctness today. If the guest requests a conversion from shared=>private without first ensuring the gfn is unused (by a host "device"), the host will side will continue accessing the old, shared memory, which it locked, while the guest will be doing who knows what. And if the guest provides a GPA that isn't mapped shared in the VMM's address space, it's conceptually no different than if the guest provided a completely bogus GPA, which again needs to be handled today.
Quoted 7 lines
In other words, if done properly, differentiating private from shared shouldn't be a heavy lift for host userspace.
[*] Actually unmapping memory may not be strictly necessary for SNP because a
#PF(RMP) is likely just as good as a #PF(!PRESENT) when both are treated as fatal, but the rest of the proposal that allows KVM to understand the stage of a page and exit to userspace accordingly applies.
Quoted 7 lines
Thanks for this explanation. When you write "while the guest will be doing who knows what":
Isn't that a large weakness of this proposal? To me, it seems better for debuggability to corrupt the private memory (i.e., convert the page to shared) so the guest can detect the issue via a PVALIDATE failure.
The behavior is no different than it is today for regular VMs.
Quoted 2 lines
The main issue I see with corrupting the guest memory is that we may not know whether the host is at fault or the guest.
Yes, one issue is that bugs in the host will result in downstream errors in the guest, as opposed to immediate, synchronous detection in the guest. IMO that is a significant flaw.
Another issue is that the host kernel, which despite being "untrusted", absolutely should be acting in the best interests of the guest. Allowing userspace to inject #VC, e.g. to attempt to attack the guest by triggering a spurious PVALIDATE, means the kernel is failing miserably on that front.
Quoted 41 lines · Sean Christopherson
Quoted 39 lines · Marc Orr
Quoted 27 lines · Sean Christopherson
Quoted 2 lines · Peter Gonda
Having a way for userspace to lock pages as shared was an idea I just proposed the simplest solution to start the conversation.
Assuming you meant that to read:
Having a way for userspace to lock pages as shared is an alternative idea; I just proposed the simplest solution to start the conversation.
The unmapping[*] guest private memory proposal is essentially that, a way for userspace to "lock" the state of a page by requiring all conversions to be initiated by userspace and by providing APIs to associate a pfn 1:1 with a KVM instance, i.e. lock a pfn to a guest.
Andy's DMA example brings up a very good point though. If the shared and private variants of a given GPA are _not_ required to point at a single PFN, which is the case in the current unmapping proposal, userspace doesn't need to do any additional juggling to track guest conversions across multiple processes.
Any process that's accessing guest (shared!) memory simply does its locking as normal, which as Andy pointed out, is needed for correctness today. If the guest requests a conversion from shared=>private without first ensuring the gfn is unused (by a host "device"), the host will side will continue accessing the old, shared memory, which it locked, while the guest will be doing who knows what. And if the guest provides a GPA that isn't mapped shared in the VMM's address space, it's conceptually no different than if the guest provided a completely bogus GPA, which again needs to be handled today.
Quoted 7 lines
In other words, if done properly, differentiating private from shared shouldn't be a heavy lift for host userspace.
[*] Actually unmapping memory may not be strictly necessary for SNP because a
#PF(RMP) is likely just as good as a #PF(!PRESENT) when both are treated as fatal, but the rest of the proposal that allows KVM to understand the stage of a page and exit to userspace accordingly applies.Thanks for this explanation. When you write "while the guest will be doing who knows what":
Quoted 6 lines
Quoted 4 lines
Isn't that a large weakness of this proposal? To me, it seems better for debuggability to corrupt the private memory (i.e., convert the page to shared) so the guest can detect the issue via a PVALIDATE failure.
The behavior is no different than it is today for regular VMs.
Isn't this counter to the sketch you laid out earlier where you wrote:
--- QUOTE START ---
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.
--- QUOTE END ---
Here, the guest does not get killed. Which seems hard to debug.
Quoted 6 lines
Quoted 2 lines
The main issue I see with corrupting the guest memory is that we may not know whether the host is at fault or the guest.
Yes, one issue is that bugs in the host will result in downstream errors in the guest, as opposed to immediate, synchronous detection in the guest. IMO that is a significant flaw.
Nobody wants bugs in the host. Once we've hit one -- and we will -- we're in a bad situation. The question is how will we handle these bugs. I'm arguing that we should design the system to be as robust as possible.
I agree that immediate, synchronous detection in the guest is ideal. But at what cost? Is it worth killing _ALL_ VMs on the system? That's what we're doing when we crash host-wide processes, or even worse, the kernel itself.
The reality is that guests must be able to detect writes to their private memory long after they have occurred. Both SNP and TDX are designed this way! For SNP the guest gets a PVALIDATE failure when it reads the corrupted memory. For TDX, my understanding is that the hardware fails to verify an HMAC over a page when it's read by the guest.
The argument I'm making is that the success of confidential VMs -- in both SNP and TDX -- depends on the guest being able to detect that its private memory has been corrupted in a delayed and asynchronous fashion. We should be leveraging this fact to make the entire system more robust and reliable.
Quoted 4 lines
Another issue is that the host kernel, which despite being "untrusted", absolutely should be acting in the best interests of the guest. Allowing userspace to inject #VC, e.g. to attempt to attack the guest by triggering a spurious PVALIDATE, means the kernel is failing miserably on that front.
The host is acting in the best interests of the guest. That's why we're having this debate :-). No-one here is trying to write host code to sabotage the guest. Quite the opposite.
But what happens when we mess up? That's what this conversation is really about.
If allowing userspace to inject #VC into the guest means that the host can continue to serve other guests, that seems like a win. The alternative, to blow up the host, essentially expands the blast radius from a single guest to all guests.
Also, these attacks go both ways. As we already discussed, the guest may try to trick the host into writing its own private memory. Yes, the entire idea to literally make that impossible is a good one -- in theory. But it's also very complicated. And what happens if we get that wrong? Now our entire host is at risk from a single guest.
Leveraging the system-wide design of SNP and TDX -- where a detecting writes to private memory asynchronously is table stakes -- increases the reliability of the entire system. And, as Peter mentioned earlier on, we can always incorporate any future work to make writing private memory impossible into SNP, on top of the code to convert the shared page to private. This way, we get reliability in depth, and minimize the odds of crashing the host -- and its VMs.
Sean Christopherson
maintainerQuoted 5 lines · Marc Orr
Quoted 1 line · Sean Christopherson
The behavior is no different than it is today for regular VMs.
Isn't this counter to the sketch you laid out earlier where you wrote:
Quoted 7 lines
--- QUOTE START ---
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.
--- QUOTE END ---Here, the guest does not get killed. Which seems hard to debug.
No, it does contradict that statement.
If the guest requests a conversion from shared=>private without first ensuring the gfn is unused (by a host "device"), the host will side will continue accessing the old, shared memory, which it locked, while the guest will be doing who knows what.
In this case, the guest will have converted a GPA from shared=>private, i.e. changed the effective GFN for a e.g. a shared queue, without informing host userspace that the GFN, and thus the associated HVA in the host, has changed. For TDX that is literally the same bug as the guest changing the GFN without informing the host, as the SHARED bit is just an address bit with some extra meaning piled on top. For SNP, it's slightly different because the C-bit isn't strictly required to be an address bit, but for all intents and purposes it's the same type of bug.
I phrased it "guest will be doing who knows what" because from a host userspace perspective, it can't know what the guest behavior will be, and more importantly, it doesn't care because (a) the guest is buggy and (b) the host itself is _not_ in danger.
Yes, those types of bugs suck to debug. But they really should be few and far between. The only reason I called out this specific scenario was to note that host userspace doesn't need to take extra steps to guard against bogus shared=>private conversions, because host userspace already needs to have such guards in place. In prior (offline?) conversations, we had assumed that host userspace would need to propagate the shared vs. private status to any and all processes that map guest memory, i.e. would require substantial enabling, but that assumption was wrong.
Quoted 4 lines
If allowing userspace to inject #VC into the guest means that the host can continue to serve other guests, that seems like a win. The alternative, to blow up the host, essentially expands the blast radius from a single guest to all guests.
As mentioned in other threads of this conversation, when I say "host crashes", I am specifically talking about scenarios where it is simply not possible for the host kernel to recover, e.g. an RMP #PF violation on the IDT.
Setting that aside, injecting a #VC into the guest is not in anyway necessary for a buggy host userspace to terminate a single guest, host userspace can simply stop running that specific guest.
Quoted 4 lines · Sean Christopherson
Another issue is that the host kernel, which despite being "untrusted", absolutely should be acting in the best interests of the guest. Allowing userspace to inject #VC, e.g. to attempt to attack the guest by triggering a spurious PVALIDATE, means the kernel is failing miserably on that front.
Well, no. The kernel is only a part of the hypervisor, KVM userspace is another. It is possible today for the userspace part(s) to interact in bad ways with the guest and trick or kill it. Allowing user-space to cause a #VC in the guest is no different from that.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Quoted 4 lines · Sean Christopherson
Quoted 3 lines · Borislav Petkov
Quoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
In the automatic change proposal, both the the host and a guest bug will cause a guest to get the #VC and then the guest can decide whether it wants to proceed or terminate. If it chooses to move, it can poison the page and log it for future examination.
Quoted 12 lines
Quoted 1 line
What do you suggest instead?
Let userspace decide what is mapped shared and what is mapped private. The kernel and KVM provide the APIs/infrastructure to do the actual conversions in a thread-safe fashion and also to enforce the current state, but userspace is the control plane.
It would require non-trivial changes in userspace if there are multiple processes accessing guest memory, e.g. Peter's networking daemon example, but it _is_ fully solvable. The exit to userspace means all three components (guest, kernel, and userspace) have full knowledge of what is shared and what is private. There is zero ambiguity:
Quoted 6 lines
- if userspace accesses guest private memory, it gets SIGSEGV or whatever.
- if kernel accesses guest private memory, it does BUG/panic/oops[*]
- if guest accesses memory with the incorrect C/SHARED-bit, it gets killed.This is the direction KVM TDX support is headed, though it's obviously still a WIP.
Just curious, in this approach, how do you propose handling the host kexec/kdump? If a kexec/kdump occurs while the VM is still active, the new kernel will encounter the #PF (RMP violation) because some pages are still marked 'private' in the RMP table.
Quoted 6 lines
And ideally, to avoid implicit conversions at any level, hardware vendors' ABIs define that:
a) All convertible memory, i.e. RAM, starts as private.
b) Conversions between private and shared must be done via explicit hypercall.
Quoted 7 lines
Without (b), userspace and thus KVM have to treat guest accesses to the incorrect type as implicit conversions.
[*] Sadly, fully preventing kernel access to guest private is not possible with
TDX, especially if the direct map is left intact. But maybe in the future TDX will signal a fault instead of poisoning memory and leaving a #MC mine.
thanks
Sean Christopherson
maintainerQuoted 9 lines · Brijesh Singh
Quoted 2 lines · Sean Christopherson
This is the direction KVM TDX support is headed, though it's obviously still a WIP.
Just curious, in this approach, how do you propose handling the host kexec/kdump? If a kexec/kdump occurs while the VM is still active, the new kernel will encounter the #PF (RMP violation) because some pages are still marked 'private' in the RMP table.
There are two basic options: a) eagerly purge the RMP or b) lazily fixup the RMP on #PF. Either approach can be made to work. I'm not opposed to fixing up the RMP on #PF in the kexec/kdump case, I'm opposed to blindly updating the RMP on _all_ RMP #PFs, i.e. the kernel should modify the RMP if and only if it knows that doing so is correct. E.g. a naive lazy-fixup solution would be to track which pages have been sanitized and adjust the RMP on #PF to a page that hasn't yet been sanitized.
Quoted 11 lines · Sean Christopherson
Quoted 9 lines · Brijesh Singh
Quoted 2 lines · Sean Christopherson
This is the direction KVM TDX support is headed, though it's obviously still a WIP.
Just curious, in this approach, how do you propose handling the host kexec/kdump? If a kexec/kdump occurs while the VM is still active, the new kernel will encounter the #PF (RMP violation) because some pages are still marked 'private' in the RMP table.
Quoted 7 lines
There are two basic options: a) eagerly purge the RMP or b) lazily fixup the RMP on #PF. Either approach can be made to work. I'm not opposed to fixing up the RMP on #PF in the kexec/kdump case, I'm opposed to blindly updating the RMP on _all_ RMP #PFs, i.e. the kernel should modify the RMP if and only if it knows that doing so is correct. E.g. a naive lazy-fixup solution would be to track which pages have been sanitized and adjust the RMP on #PF to a page that hasn't yet been sanitized.
Yap, I think option #a will require the current kernel to iterate through the entire memory and make it shared before booting the kexec kernel. It may bring another ask to track the guest private/shared on the host to minimize the iterations.
thanks
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
I want to push back on "inducing a fault in the guest because of _host_ bug is wrong.". The guest is _required_ to be robust against the host maliciously (or accidentally) writing its memory. SNP security depends on the guest detecting such writes. Therefore, why is leveraging this system property that the guest will detect when its private memory has been written wrong? Especially when its orders or magnitudes simpler than the alternative to have everything in the system -- kernel, user-space, and guest -- all coordinate to agree what's private and what's shared. Such a complex approach is likely to bring a lot of bugs, vulnerabilities, and limitations on future design into the picture.
Andy Lutomirski
maintainerQuoted 13 lines · Marc Orr
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
I want to push back on "inducing a fault in the guest because of _host_ bug is wrong.". The guest is _required_ to be robust against the host maliciously (or accidentally) writing its memory. SNP security depends on the guest detecting such writes. Therefore, why is leveraging this system property that the guest will detect when its private memory has been written wrong?
Quoted 7 lines
Especially when its orders or
magnitudes simpler than the alternative to have everything in the system -- kernel, user-space, and guest -- all coordinate to agree what's private and what's shared. Such a complex approach is likely to bring a lot of bugs, vulnerabilities, and limitations on future design into the picture.
SEV-SNP, TDX, and any reasonable software solution all require that the host know which pages are private and which pages are shared. Sure, the old SEV-ES Linux host implementation was very simple, but it's nasty and fundamentally can't support migration.
Borislav Petkov
maintainerQuoted 4 lines · Andy Lutomirski
SEV-SNP, TDX, and any reasonable software solution all require that the host know which pages are private and which pages are shared. Sure, the old SEV-ES Linux host implementation was very simple, but it's nasty and fundamentally can't support migration.
Right, so at least SNP guests need to track which pages have been already PVALIDATEd by them so that they don't validate them again. So if we track that somewhere in struct page or wherever, that same bit can be used to state, page is private or shared.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteQuoted 17 lines · * Sean Christopherson ([email protected]) wrote:
Quoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.Key word "should".
Quoted 5 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Would it necessarily have been a host bug? A guest telling the host a bad GPA to DMA into would trigger this wouldn't it?
Still; I wonder if it's best to kill the guest - maybe it's best for the host to kill the guest and leave behind diagnostics of what happened; for someone debugging the crash, it's going to be less useful to know that page X was wrongly accessed (which is what the guest would see), and more useful to know that it was the kernel's vhost-... driver that accessed it.
Dave
Quoted 47 lines · Peter Gonda
Quoted 4 lines
Here is an alternative to the current approach: On RMP violation (host or userspace) the page fault handler converts the page from private to shared to allow the write to continue. This pulls from s390’s error handling which does exactly this. See ‘arch_make_page_accessible()’.
Ah, after further reading, s390 does _not_ do implicit private=>shared conversions.
s390's
arch_make_page_accessible()is somewhat similar, but it is not a direct comparison. IIUC, it exports and integrity protects the data and thus preserves the guest's data in an encrypted form, e.g. so that it can be swapped to disk. And if the host corrupts the data, attempting to convert it back to secure on a subsequent guest access will fail.The host kernel's handling of the "convert to secure" failures doesn't appear to be all that robust, e.g. it looks like there are multiple paths where the error is dropped on the floor and the guest is resumed , but IMO soft hanging the guest is still better than inducing a fault in the guest, and far better than potentially coercing the guest into reading corrupted memory ("spurious" PVALIDATE). And s390's behavior is fixable since it's purely a host error handling problem.
To truly make a page shared, s390 requires the guest to call into the ultravisor to make a page shared. And on the host side, the host can pin a page as shared to prevent the guest from unsharing it while the host is accessing it as a shared page.
So, inducing #VC is similar in the sense that a malicious s390 can also DoS itself, but is quite different in that (AFAICT) s390 does not create an attack surface where a malicious or buggy host userspace can induce faults in the guest, or worst case in SNP, exploit a buggy guest into accepting and accessing corrupted data.
It's also different in that s390 doesn't implicitly convert between shared and private. Functionally, it doesn't really change the end result because a buggy host that writes guest private memory will DoS the guest (by inducing a #VC or corrupting exported data), but at least for s390 there's a sane, legitimate use case for accessing guest private memory (swap and maybe migration?), whereas for SNP, IMO implicitly converting to shared on a host access is straight up wrong.
Quoted 2 lines
Additionally it adds less complexity to the SNP kernel patches, and requires no new ABI.
I disagree, this would require "new" ABI in the sense that it commits KVM to supporting SNP without requiring userspace to initiate any and all conversions between shared and private. Which in my mind is the big elephant in the room:
do we want to require new KVM (and kernel?) ABI to allow/force userspace to explicitly declare guest private memory for TDX _and_ SNP, or just TDX?
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
Quoted 6 lines · Dr. David Alan Gilbert
Still; I wonder if it's best to kill the guest - maybe it's best for the host to kill the guest and leave behind diagnostics of what happened; for someone debugging the crash, it's going to be less useful to know that page X was wrongly accessed (which is what the guest would see), and more useful to know that it was the kernel's vhost-... driver that accessed it.
I is best to let the guest #VC on the page when this happens. If it happened because of a guest bug all necessary debugging data is in the guest and only the guest owner can obtain it.
Then the guest owner can do a kdump on this unexpected #VC and collect the data to debug the issue. With just killing the guest from the host side this data would be lost.
Regards,
Joerg
Quoted 8 lines · * Joerg Roedel ([email protected]) wrote:
Quoted 6 lines · Dr. David Alan Gilbert
Still; I wonder if it's best to kill the guest - maybe it's best for the host to kill the guest and leave behind diagnostics of what happened; for someone debugging the crash, it's going to be less useful to know that page X was wrongly accessed (which is what the guest would see), and more useful to know that it was the kernel's vhost-... driver that accessed it.
Quoted 7 lines
I is best to let the guest #VC on the page when this happens. If it happened because of a guest bug all necessary debugging data is in the guest and only the guest owner can obtain it.
Then the guest owner can do a kdump on this unexpected #VC and collect the data to debug the issue. With just killing the guest from the host side this data would be lost.
How would you debug an unexpected access by the host kernel using a guests kdump?
Dave
Quoted 4 lines
Regards,
Joerg
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
Quoted 2 lines · Dr. David Alan Gilbert
How would you debug an unexpected access by the host kernel using a guests kdump?
The host needs to log the access in some way (trace-event, pr_err) with relevant information.
And with the guest-side kdump you can rule out that it was a guest bug which triggered the access. And you learn what the guest was trying to do when it triggered the access. This also helps finding the issue on the host side (if it is a host-side issue).
(Guest and host owner need to work together for debugging, of course).
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Quoted 6 lines · * Joerg Roedel ([email protected]) wrote:
Quoted 2 lines · Dr. David Alan Gilbert
How would you debug an unexpected access by the host kernel using a guests kdump?
The host needs to log the access in some way (trace-event,
pr_err) with relevant information.
Yeh OK that makes sense if the host-owner could then enable some type of debugging based on that event for the unfortunate guest owner.
Quoted 6 lines
And with the guest-side kdump you can rule out that it was a guest bug which triggered the access. And you learn what the guest was trying to do when it triggered the access. This also helps finding the issue on the host side (if it is a host-side issue).
(Guest and host owner need to work together for debugging, of course).
Yeh.
Dave
Quoted 14 lines
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
Sean Christopherson
maintainerQuoted 18 lines · Dr. David Alan Gilbert
Quoted 17 lines · * Sean Christopherson ([email protected]) wrote:
Quoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.Key word "should".
Quoted 5 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Would it necessarily have been a host bug? A guest telling the host a bad GPA to DMA into would trigger this wouldn't it?
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
Quoted 28 lines · Sean Christopherson
Quoted 18 lines · Dr. David Alan Gilbert
Quoted 17 lines · * Sean Christopherson ([email protected]) wrote:
Quoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.Key word "should".
Quoted 5 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Would it necessarily have been a host bug? A guest telling the host a bad GPA to DMA into would trigger this wouldn't it?
Quoted 7 lines
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
"If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up."
^^^
Again, I'm flabbergasted that you are arguing that it's OK for a guest to exploit a host bug to take down host-side processes or the host itself, either of which could bring down all other VMs on the machine.
I'm going to repeat -- this is not OK! Period.
Again, if the community wants to layer some orchestration scheme between host userspace, host kernel, and guest, on top of the code to inject the #VC into the guest, that's fine. This proposal is not stopping that. In fact, the two approaches are completely orthogonal and compatible.
But so far I have heard zero reasons why injecting a #VC into the guest is wrong. Other than just stating that it's wrong.
Again, the guest must be able to detect buggy and malicious host-side writes to private memory. Or else "confidential computing" doesn't work. Assuming that's not true is not a valid argument to dismiss injecting a #VC exception into the guest.
Sean Christopherson
maintainer+arm64 KVM folks
Quoted 46 lines · Marc Orr
Quoted 28 lines · Sean Christopherson
Quoted 18 lines · Dr. David Alan Gilbert
Quoted 17 lines · * Sean Christopherson ([email protected]) wrote:
Quoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.Key word "should".
Quoted 5 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Would it necessarily have been a host bug? A guest telling the host a bad GPA to DMA into would trigger this wouldn't it?
Quoted 7 lines
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
"If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up."
^^^
Again, I'm flabbergasted that you are arguing that it's OK for a guest to exploit a host bug to take down host-side processes or the host itself, either of which could bring down all other VMs on the machine.
Quoted 1 line
I'm going to repeat -- this is not OK! Period.
Huh? At which point did I suggest it's ok to ship software with bugs? Of course it's not ok to introduce host bugs that let the guest crash the host (or host processes). But _if_ someone does ship buggy host software, it's not like we can wave a magic wand and stop the guest from exploiting the bug. That's why they're such a big deal.
Yes, in this case a very specific flavor of host userspace bug could be morphed into a guest exception, but as mentioned ad nauseum, _if_ host userspace has bug where it does not properly validate a GPA=>HVA, then any such bug exists and is exploitable today irrespective of SNP.
Quoted 8 lines
Again, if the community wants to layer some orchestration scheme between host userspace, host kernel, and guest, on top of the code to inject the #VC into the guest, that's fine. This proposal is not stopping that. In fact, the two approaches are completely orthogonal and compatible.
But so far I have heard zero reasons why injecting a #VC into the guest is wrong. Other than just stating that it's wrong.
It creates a new attack surface, e.g. if the guest mishandles the #VC and does PVALIDATE on memory that it previously accepted, then userspace can attack the guest by accessing guest private memory to coerce the guest into consuming corrupted data.
Quoted 3 lines
Again, the guest must be able to detect buggy and malicious host-side writes to private memory. Or else "confidential computing" doesn't work.
That assertion assumes the host _hypervisor_ is untrusted, which does not hold true for all use cases. The Cc'd arm64 folks are working on a protected VM model where the host kernel at large is untrusted, but the "hypervisor" (KVM plus a few other bits), is still trusted by the guest. Because the hypervisor is trusted, the guest doesn't need to be hardened against event injection attacks from the host.
Note, SNP already has a similar concept in it's VMPLs. VMPL3 runs a confidential VM that is not hardened in any way, and fully trusts VMPL0 to not inject bogus faults.
And along the lines of arm64's pKVM, I would very much like to get KVM to a point where it can remove host userspace from the guest's TCB without relying on hardware. Anything that can be in hardware absolutely can be done in the kernel, and likely can be done with significantly less performance overhead. Confidential computing is not a binary thing where the only valid use case is removing the host kernel from the TCB and trusting only hardware. There are undoubtedly use cases where trusting the host kernel but not host userspace brings tangible value, but the overhead of TDX/SNP to get the host kernel out of the TCB is the wrong tradeoff for performance vs. security.
Quoted 2 lines
Assuming that's not true is not a valid argument to dismiss injecting a #VC exception into the guest.
Quoted 58 lines · Sean Christopherson
+arm64 KVM folks
Quoted 46 lines · Marc Orr
Quoted 28 lines · Sean Christopherson
Quoted 18 lines · Dr. David Alan Gilbert
Quoted 17 lines · * Sean Christopherson ([email protected]) wrote:
Quoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.Key word "should".
Quoted 5 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Would it necessarily have been a host bug? A guest telling the host a bad GPA to DMA into would trigger this wouldn't it?
Quoted 7 lines
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
"If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up."
^^^
Again, I'm flabbergasted that you are arguing that it's OK for a guest to exploit a host bug to take down host-side processes or the host itself, either of which could bring down all other VMs on the machine.Quoted 1 line
I'm going to repeat -- this is not OK! Period.
Huh? At which point did I suggest it's ok to ship software with bugs? Of course it's not ok to introduce host bugs that let the guest crash the host (or host processes). But _if_ someone does ship buggy host software, it's not like we can wave a magic wand and stop the guest from exploiting the bug. That's why they're such a big deal.
Quoted 4 lines
Yes, in this case a very specific flavor of host userspace bug could be morphed into a guest exception, but as mentioned ad nauseum, _if_ host userspace has bug where it does not properly validate a GPA=>HVA, then any such bug exists and is exploitable today irrespective of SNP.
If I'm understanding you correctly, you're saying that we will never get into the host's page fault handler due to an RMP violation if we implement the unmapping guest private memory proposal (without bugs).
However, bugs do happen. And the host-side page fault handler will have code to react to an RMP violation (even if it's supposedly impossible to hit). I'm saying that the host-side page fault handler should NOT handle an RMP violation by killing host-side processes or the kernel itself. This is detrimental to host reliability.
There are two ways to handle this. (1) Convert the private page causing the RMP violation to shared, (2) Kill the guest.
Converting the private page to shared is a good solution in SNP's threat model. And overall, it's better for debuggability than immediately terminating the guest.
Quoted 6 lines
Quoted 6 lines
Again, if the community wants to layer some orchestration scheme between host userspace, host kernel, and guest, on top of the code to inject the #VC into the guest, that's fine. This proposal is not stopping that. In fact, the two approaches are completely orthogonal and compatible.
Quoted 7 lines
Quoted 2 lines
But so far I have heard zero reasons why injecting a #VC into the guest is wrong. Other than just stating that it's wrong.
It creates a new attack surface, e.g. if the guest mishandles the #VC and does PVALIDATE on memory that it previously accepted, then userspace can attack the guest by accessing guest private memory to coerce the guest into consuming corrupted data.
We should handle RMP violations as best possible from within the host-side page fault handler, independent of the proposal to unmap private guest memory for all CVM architectures. Otherwise, if someone figures out how to trigger an RMP violation by writing guest private memory (despite unmapping guest private memory's goal to make this impossible), the attack surface has now increased. Because now we're either killing host processes or the kernel. Which is worse than killing the single guest.
Second, I don't think it's correct to say that the host-side implementation changes the attack surface. The guest must already be hardened against host-side bugs and attacks. From the guest's perspective, the attack surface is the same. Also, unmapping private guest memory is going to require coordination across host userspace, host kernel, and guest. That's a lot of code. And typically more code means more attack surface. That being said, if all that code is implemented perfectly, you might be right, that unmapping guest private memory makes it harder for the host to attack the guest. But I think it's a moot point. Because in the end, converting the page from private to shared is entirely reasonable to solve this problem for SNP, and we should be doing it irregardless, even if we do get unmapping private memory working on SNP.
Andy Lutomirski
maintainerQuoted 68 lines · Marc Orr
Quoted 58 lines · Sean Christopherson
+arm64 KVM folks
Quoted 46 lines · Marc Orr
Quoted 28 lines · Sean Christopherson
Quoted 18 lines · Dr. David Alan Gilbert
Quoted 17 lines · * Sean Christopherson ([email protected]) wrote:
Quoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.Key word "should".
Quoted 5 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Would it necessarily have been a host bug? A guest telling the host a bad GPA to DMA into would trigger this wouldn't it?
Quoted 7 lines
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
"If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up."
^^^
Again, I'm flabbergasted that you are arguing that it's OK for a guest to exploit a host bug to take down host-side processes or the host itself, either of which could bring down all other VMs on the machine.Quoted 1 line
I'm going to repeat -- this is not OK! Period.
Huh? At which point did I suggest it's ok to ship software with bugs? Of course it's not ok to introduce host bugs that let the guest crash the host (or host processes). But _if_ someone does ship buggy host software, it's not like we can wave a magic wand and stop the guest from exploiting the bug. That's why they're such a big deal.
Quoted 4 lines
Yes, in this case a very specific flavor of host userspace bug could be morphed into a guest exception, but as mentioned ad nauseum, _if_ host userspace has bug where it does not properly validate a GPA=>HVA, then any such bug exists and is exploitable today irrespective of SNP.
If I'm understanding you correctly, you're saying that we will never get into the host's page fault handler due to an RMP violation if we implement the unmapping guest private memory proposal (without bugs).
Quoted 8 lines
However, bugs do happen. And the host-side page fault handler will have code to react to an RMP violation (even if it's supposedly impossible to hit). I'm saying that the host-side page fault handler should NOT handle an RMP violation by killing host-side processes or the kernel itself. This is detrimental to host reliability.
There are two ways to handle this. (1) Convert the private page causing the RMP violation to shared, (2) Kill the guest.
It’s time to put on my maintainer hat. This is solidly in my territory, and NAK. A kernel privilege fault, from who-knows-what context (interrupts off? NMI? locks held?) that gets an RMP violation with no exception handler is *not* going to blindly write the RMP and retry. It’s not going to send flush IPIs or call into KVM to “fix” things. Just the locking issues alone are probably showstopping, even ignoring the security and sanity issues.
You are welcome to submit patches to make the panic_on_oops=0 case as robust as practical, and you are welcome to keep running other VMs after we die() and taint the kernel, but that is strictly best effort and is a bad idea in a highly security sensitive environment.
And that goes for everyone else here too. If you all have a brilliant idea to lazily fix RMP faults (and the actual semantics are reasonable) and you want my NAK to go away, I want to see a crystal clear explanation of what you plan to put in fault.c, how the locking is supposed to work, and how you bound retries such that the system will reliably OOPS if something goes wrong instead of retrying forever or deadlocking.
Otherwise can we please get on with designing a reasonable model for guest-private memory please?
Quoted 7 lines · Andy Lutomirski
It’s time to put on my maintainer hat. This is solidly in my territory, and NAK. A kernel privilege fault, from who-knows-what context (interrupts off? NMI? locks held?) that gets an RMP violation with no exception handler is *not* going to blindly write the RMP and retry. It’s not going to send flush IPIs or call into KVM to “fix” things. Just the locking issues alone are probably showstopping, even ignoring the security and sanity issues.
RMP faults are expected from two contexts:
* User-space
* KVM running in task context
The only situation where RMP faults could happen outside of these contexts is when running a kexec'ed kernel, which was launched while SNP guests were still running (that needs to be taken care of as well).
And from the locking side, which lock does the #PF handler need to take? Processors supporting SNP also have hardware support for flushing remote TLBs, so locks taken in the flush path are not strictly required.
Calling into KVM is another story and needs some more thought, I agree with that.
Quoted 2 lines
Otherwise can we please get on with designing a reasonable model for guest-private memory please?
It is fine to unmap guest-private memory from the host kernel, even if it is not required by SNP. TDX need to do that because of the #MC thing that happens otherwise, but that is also just a way to emulate an RMP-like fault with TDX.
But as Marc already pointed out, the kernel needs a plan B when an RMP happens anyway due to some bug.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Sean Christopherson
maintainerQuoted 2 lines · Joerg Roedel
But as Marc already pointed out, the kernel needs a plan B when an RMP happens anyway due to some bug.
I don't see why unexpected RMP #PF is a special snowflake that needs a different plan than literally every other type of unexpected #PF in the kernel.
Quoted 7 lines · Sean Christopherson
Quoted 2 lines · Joerg Roedel
But as Marc already pointed out, the kernel needs a plan B when an RMP happens anyway due to some bug.
I don't see why unexpected RMP #PF is a special snowflake that needs a different plan than literally every other type of unexpected #PF in the kernel.
When I started this thread I was not trying to say we *need* to do something different for RMP faults, but that we *could* improve host reliability by doing something. Since it is possible to special case an RMP fault and prevent a panic I thought it was with discussing.
Quoted 4 lines · Sean Christopherson
It creates a new attack surface, e.g. if the guest mishandles the #VC and does PVALIDATE on memory that it previously accepted, then userspace can attack the guest by accessing guest private memory to coerce the guest into consuming corrupted data.
If a guest can be tricked into a double PVALIDATE or otherwise misbehaves on a #VC exception, then it is a guest bug and needs to be fixed there.
It is a core requirement to the #VC handler that it can not be tricked that way.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Andy Lutomirski
maintainerQuoted 46 lines · Marc Orr
Quoted 28 lines · Sean Christopherson
Quoted 18 lines · Dr. David Alan Gilbert
Quoted 17 lines · * Sean Christopherson ([email protected]) wrote:
Quoted 3 lines · Borislav Petkov
Quoted 2 lines · Dave Hansen
Or, is there some mechanism that prevent guest-private memory from being accessed in random host kernel code?
Or random host userspace code...
Quoted 2 lines
So I'm currently under the impression that random
host->guestaccesses should not happen if not previously agreed upon by both.Key word "should".
Quoted 5 lines
Because, as explained on IRC, if host touches a private guest page, whatever the host does to that page, the next time the guest runs, it'll get a #VC where it will see that that page doesn't belong to it anymore and then, out of paranoia, it will simply terminate to protect itself.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
So cloud providers should have an interest to prevent such random stray accesses if they wanna have guests. :)
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
Would it necessarily have been a host bug? A guest telling the host a bad GPA to DMA into would trigger this wouldn't it?
Quoted 7 lines
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
"If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up."
^^^
Again, I'm flabbergasted that you are arguing that it's OK for a guest to exploit a host bug to take down host-side processes or the host itself, either of which could bring down all other VMs on the machine.
Quoted 1 line
I'm going to repeat -- this is not OK! Period.
I don’t understand the point you’re trying to make. If the host _kernel_has a bug that allows a guest to trigger invalid host memory access, this is bad. We want to know about it and fix it, abcs the security folks want to minimize the chance that such a bug exists.
If host _userspace_ such a bug, the kernel should not crash if it’s exploited.
Quoted 7 lines · Sean Christopherson
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
The thing is that the usual checking mechanisms can't be applied to guest-private pages. For user-space the GPA is valid if it fits into the guest memory layout user-space set up before. But whether a page is shared or private is the guests business. And without an expensive reporting/query mechanism user-space doesn't have the information to do the check.
A mechanism to lock pages to shared is also needed, and that creates the next problems:
* Who can release the lock, only the process which created it or anyone who has the memory mapped?
* What happens when a process has locked guest regions and then dies with SIGSEGV, will its locks on guest memory be released stay around forever?
And this is only what comes to mind immediatly, I sure there are more problematic details in such an interface.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Sean Christopherson
maintainerQuoted 9 lines · Joerg Roedel
Quoted 7 lines · Sean Christopherson
No, because as Andy pointed out, host userspace must already guard against a bad GPA, i.e. this is just a variant of the guest telling the host to DMA to a GPA that is completely bogus. The shared vs. private behavior just means that when host userspace is doing a GPA=>HVA lookup, it needs to incorporate the "shared" state of the GPA. If the host goes and DMAs into the completely wrong HVA=>PFN, then that is a host bug; that the bug happened to be exploited by a buggy/malicious guest doesn't change the fact that the host messed up.
Quoted 4 lines
The thing is that the usual checking mechanisms can't be applied to guest-private pages. For user-space the GPA is valid if it fits into the guest memory layout user-space set up before. But whether a page is shared or private is the guests business.
And that's where we fundamentally disagree. Whether a page is shared or private is very much the host's business. The guest can _ask_ to convert a page, but the host ultimately owns the state of a page. Even in this proposed auto-convert approach, the host has final say over the state of the page.
The main difference between auto-converting in the #PF handler and an unmapping approach is that, as you note below, the latter requires an explicit action from host userspace. But again, the host kernel has final say over the state of any given page.
Quoted 2 lines
And without an expensive reporting/query mechanism user-space doesn't have the information to do the check.
The cost of exiting to userspace isn't all that expensive relative to the cost of the RMP update itself, e.g. IIRC updating the RMP is several thousand cycles. TDX will have a similar cost to modify S-EPT entries.
Actually updating the backing store (see below) might be relatively expensive, but I highly doubt it will be orders of magnitude slower than updating the RMP, or that it will have a meaningful impact on guest performance.
Quoted 2 lines
A mechanism to lock pages to shared is also needed, and that creates the next problems:
The most recent proposal for unmapping guest private memory doesn't require new locking at the page level. The high level idea is to treat shared and private variations of GPAs as two unrelated addresses from a host memory management perspective. They are only a "single" address in the context of KVM's MMU, i.e. the NPT for SNP.
For shared pages, no new locking is required as the PFN associated with a VMA will not be freed until all mappings go away. Any access after all mappings/references have been dropped is a nothing more than a use-after-free bug, and the guilty party is punished accordingly.
For private pages, the proposed idea is to require that all guest private memory be backed by an elightened backing store, e.g. the initial RFC enhances memfd and shmem to support sealing the file as guest-only:
: The new seal is only allowed if there's no pre-existing pages in the fd : and there's no existing mapping of the file. After the seal is set, no : read/write/mmap from userspace is allowed.
It is KVM's responsibility to ensure it doesn't map a shared PFN into a private GPA and vice versa, and that TDP entries are unmapped appropriately, e.g. when userspace punches a hole in the backing store, but that can all be done using existing locks, e.g. KVM's mmu_lock. No new locking mechanisms are required.
Quoted 9 lines
* Who can release the lock, only the process which created it or anyone who has the memory mapped?
* What happens when a process has locked guest regions and then dies with SIGSEGV, will its locks on guest memory be released stay around forever?
And this is only what comes to mind immediatly, I sure there are more problematic details in such an interface.
Please read through this proposal/RFC, more eyeballs would certainly be welcome.
Quoted 1 line · Sean Christopherson
Yes, but IMO inducing a fault in the guest because of _host_ bug is wrong.
And what is the plan with handling this host bug? Can it be handled in a way that keeps the guest running?
IMO the best way to handle this is to do it the way Peter proposed:
* Convert the page from private to shared on host write access and log this event on the host side (e.g. via a trace event)
* The guest will notice what happened and can decide on its own what to do, either poison the page or panic with doing a kdump that can be used for bug analysis by guest and host owner
At the time the fault happens we can not reliably find the reason. It can be a host bug, a guest bug (or attack), or whatnot. So the best that can be done is collecting debug data without impacting other guests.
This also saves lots of code for avoiding these faults when the outcome would be the same: A dead VM.
Quoted 5 lines
I disagree, this would require "new" ABI in the sense that it commits KVM to supporting SNP without requiring userspace to initiate any and all conversions between shared and private. Which in my mind is the big elephant in the room:
do we want to require new KVM (and kernel?) ABI to allow/force userspace to explicitly declare guest private memory for TDX _and_ SNP, or just TDX?
No, not for SNP. User-space has no say in what guest memory is private and shared, that should fundamentally be the guests decision. The host has no idea about the guests workload and how much shared memory it needs. It might be that the guest temporarily needs to share more memory. I see no reason to cut this flexibility out for SNP guests.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Hi Peter,
Quoted 37 lines · Peter Gonda
Hi Brijesh,,
One high level discussion I'd like to have on these SNP KVM patches.
In these patches (V5) if a host userspace process writes a guest private page a SIGBUS is issued to that process. If the kernel writes a guest private page then the kernel panics due to the unhandled RMP fault page fault. This is an issue because not all writes into guest memory may come from a bug in the host. For instance a malicious or even buggy guest could easily point the host to writing a private page during the emulation of many virtual devices (virtio, NVMe, etc). For example if a well behaved guests behavior is to: start up a driver, select some pages to share with the guest, ask the host to convert them to shared, then use those pages for virtual device DMA, if a buggy guest forget the step to request the pages be converted to shared its easy to see how the host could rightfully write to private memory. I think we can better guarantee host reliability when running SNP guests without changing SNP’s security properties.
Here is an alternative to the current approach: On RMP violation (host or userspace) the page fault handler converts the page from private to shared to allow the write to continue. This pulls from s390’s error handling which does exactly this. See ‘arch_make_page_accessible()’. Additionally it adds less complexity to the SNP kernel patches, and requires no new ABI.
In the current (V5) KVM implementation if a userspace process generates an RMP violation (writes to guest private memory) the process receives a SIGBUS. At first glance, it would appear that user-space shouldn’t write to private memory. However, guaranteeing this in a generic fashion requires locking the RMP entries (via locks external to the RMP). Otherwise, a user-space process emulating a guest device IO may be vulnerable to having the guest memory (maliciously or by guest bug) converted to private while user-space emulation is happening. This results in a well behaved userspace process receiving a SIGBUS.
Quoted 7 lines
This proposal allows buggy and malicious guests to run under SNP without jeopardizing the reliability / safety of host processes. This is very important to a cloud service provider (CSP) since it’s common to have host wide daemons that write/read all guests, i.e. a single process could manage the networking for all VMs on the host. Crashing that singleton process kills networking for all VMs on the system.
Thank you for starting the thread; based on the discussion, I am keeping the current implementation as-is and *not* going with the auto conversion from private to shared. To summarize what we are doing in the current SNP series:
- If userspace accesses guest private memory, it gets SIGBUS.
- If kernel accesses[*] guest private memory, it does panic.
[*] Kernel consults the RMP table for the page ownership before the access. If the page is shared, then it uses the locking mechanism to ensure that a guest will not be able to change the page ownership while kernel has it mapped.
thanks
Quoted 264 lines
This proposal also allows for minimal changes to the kexec flow and kdump. The new kexec kernel can simply update private pages to shared as it encounters them during their boot. This avoids needing to propagate the RMP state from kernel to kernel. Of course this doesn’t preserve any running VMs but is still useful for kdump crash dumps or quicker rekerneling for development with kexec.
This proposal does cause guest memory corruption for some bugs but one of SEV-SNP’s goals extended from SEV-ES’s goals is for guest’s to be able to detect when its memory has been corrupted / replayed by the host. So SNP already has features for allowing guests to detect this kind of memory corruption. Additionally this is very similar to a page of memory generating a machine check because of 2-bit memory corruption. In other words SNP guests must be enlightened and ready for these kinds of errors.
For an SNP guest running under this proposal the flow would look like this:
* Host gets a #PF because its trying to write to a private page.
* Host #PF handler updates the page to shared.
* Write continues normally.
* Guest accesses memory (r/w).
* Guest gets a #VC error because the page is not PVALIDATED
* Guest is now in control. Guest can terminate because its memory has been corrupted. Guest could try and continue to log the error to its owner.A similar approach was introduced in the SNP patches V1 and V2 for kernel page fault handling. The pushback around this convert to shared approach was largely focused around the idea that the kernel has all the information about which pages are shared vs private so it should be able to check shared status before write to pages. After V2 the patches were updated to not have a kernel page fault handler for RMP violations (other than dumping state during a panic). The current patches protect the host with new post_{map,unmap}_gfn() function that checks if a page is shared before mapping it, then locks the page shared until unmapped. Given the discussions on ‘[Part2,v5,39/45] KVM:
SVM: Introduce ops for the post gfn map and unmap’ building a solution to do this is non trivial and adds new overheads to KVM. Additionally the current solution is local to the kernel. So a new ABI just now be created to allow the userspace VMM to access the kernel-side locks for this to work generically for the whole host. This is more complicated than this proposal and adding more lock holders seems like it could reduce performance further.There are a couple corner cases with this approach. Under SNP guests can request their memory be changed into a VMSA. This VMSA page cannot be changed to shared while the vCPU associated with it is running. So KVM + the #PF handler will need something to kick vCPUs from running. Joerg believes that a possible fix for this could be a new MMU notifier in the kernel, then on the #PF we can go through the rmp and execute this vCPU kick callback.
Another corner case is the RMPUPDATE instruction is not guaranteed to succeed on first iteration. As noted above if the page is a VMSA it cannot be updated while the vCPU is running. Another issue is if the guest is running a RMPADJUST on a page it cannot be RMPUPDATED at that time. There is a lock for each RMP Entry so there is a race for these instructions. The vCPU kicking can solve this issue to be kicking all guest vCPUs which removes the chance for the race.
Since this proposal probably results in SNP guests terminating due to a page unexpectedly needing PVALIDATE. The approach could be simplified to just the KVM killing the guest. I think it's nicer to users to instead of unilaterally killing the guest allowing the unvalidated #VC exception to allow users to collect some additional debug information and any additional clean up work they would like to perform.
Thanks
PeterQuoted 192 lines · Brijesh Singh
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 requestThe 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 interrupt security and migration and those feature will be added after the base support.
The series is based on the commit:
SNP part1 commit and
fa7a549d321a(kvm/next, next) KVM: x86: accept userspace interrupt only if no event is injectedTODO:
* Add support for command to ratelimit the guest message request.Changes since v4:
* Move the RMP entry definition to x86 specific header file.
* Move the dump RMP entry function to SEV specific file.
* UseBIT_ULLwhile defining the #PF bit fields.
* Add helper function to check the IOMMU support for SEV-SNP feature.
* Add helper functions for the page state transition.
* Map and unmap the pages from the direct map after page is added or removed in RMP table.
* Enforce the minimum SEV-SNP firmware version.
* Extend theLAUNCH_UPDATEto accept thebase_gfnand remove the logic to calculate the gfn from the hva.
* Add a check inLAUNCH_UPDATEto ensure that all the pages are shared before calling the PSP.
* Mark the memory failure when failing to remove the page from the RMP table or clearing the immutable bit.
* Exclude the encrypted hva range from the KSM.
* Remove the gfn tracking during thekvm_gfn_map()and use SRCU to syncronize the PSC and gfn mapping.
* Allow PSC on the registered hva range only.
* Add support for the Preferred GPA VMGEXIT.
* Simplify the PSC handling routines.
* Use thestatic_call()for the newly addedkvm_x86_ops.
* Remove the long-lived GHCB map.
* Move the snp enable module parameter to the end of the file.
* Remove thekvm_x86_opfor the RMP fault handling. Call the fault handler directly from the #NPF interception.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 theSNP_INITcommand 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 inarch/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 handleGUEST_REQUESTNAE event for attestation.
* Rename RMP table lookup helper.
* Drop typedef from rmpentry struct definition.
* Drop SNP static key and usecpu_feature_enabled()to check whether SEV-SNP is active.
* Multiple cleanup/fixes to address Boris review feedback.Brijesh Singh (40):
x86/cpufeatures: Add SEV-SNP CPU feature
iommu/amd: Introduce function to check SEV-SNP support 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: Invalid pages from direct map when adding it to RMP table x86/traps: Define RMP violation #PF error code
x86/fault: Add support to handle the RMP fault for user address x86/fault: Add support to dump RMP entry on fault
crypto: ccp: shutdown SEV firmware on kexec
crypto:ccp: Define the SEV-SNP commands
crypto: ccp: Add support to initialize the AMD-SP for SEV-SNP 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 theSNP_PLATFORM_STATUScommand
crypto: ccp: Add the SNP_{SET,GET}_EXT_CONFIG command
crypto: ccp: Provide APIs to query extended attestation report
KVM: SVM: Provide the Hypervisor Feature support VMGEXIT
KVM: SVM: Make AVIC backing, VMSA and VMCB memory allocation SNP safe
KVM: SVM: Add initial SEV-SNP support
KVM: SVM: AddKVM_SNP_INITcommand
KVM: SVM: AddKVM_SEV_SNP_LAUNCH_STARTcommand
KVM: SVM: AddKVM_SEV_SNP_LAUNCH_UPDATEcommand
KVM: SVM: Mark the private vma unmerable for SEV-SNP guests
KVM: SVM: AddKVM_SEV_SNP_LAUNCH_FINISHcommand
KVM: X86: Keep the NPT and RMP page level in sync
KVM: x86: Introducekvm_mmu_get_tdp_walk()for SEV-SNP use
KVM: x86: Define RMP page fault error bits for #NPF
KVM: x86: Update page-fault trace to log full 64-bit error code
KVM: SVM: Do not use long-lived GHCB map while setting scratch area
KVM: SVM: Remove the long-lived GHCB host map
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: SVM: Introduce ops for the post gfn map and unmap
KVM: x86: Export thekvm_zap_gfn_range()for the SNP use
KVM: SVM: Add support to handle the RMP nested page fault
KVM: SVM: Provide support forSNP_GUEST_REQUESTNAE event
KVM: SVM: Add module parameter to enable the SEV-SNPSean Christopherson (2):
KVM: x86/mmu: Move 'pfn' variable to caller ofdirect_page_fault()
KVM: x86/mmu: Introducekvm_mmu_map_tdp_page()for use by TDX and SNPTom 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 eventDocumentation/virt/coco/sevguest.rst | 55 + .../virt/kvm/amd-memory-encryption.rst | 102 + arch/x86/include/asm/cpufeatures.h | 1 + arch/x86/include/asm/disabled-features.h | 8 +- arch/x86/include/asm/kvm-x86-ops.h | 5 + arch/x86/include/asm/kvm_host.h | 20 + arch/x86/include/asm/msr-index.h | 6 + arch/x86/include/asm/sev-common.h | 28 + arch/x86/include/asm/sev.h | 45 + arch/x86/include/asm/svm.h | 7 + arch/x86/include/asm/trap_pf.h | 18 +- arch/x86/kernel/cpu/amd.c | 3 +- arch/x86/kernel/sev.c | 361 ++++ arch/x86/kvm/lapic.c | 5 +- arch/x86/kvm/mmu.h | 7 +- arch/x86/kvm/mmu/mmu.c | 84 +- arch/x86/kvm/svm/sev.c | 1676 ++++++++++++++++- arch/x86/kvm/svm/svm.c | 62 +- arch/x86/kvm/svm/svm.h | 74 +- arch/x86/kvm/trace.h | 40 +- arch/x86/kvm/x86.c | 92 +- arch/x86/mm/fault.c | 84 +- drivers/crypto/ccp/sev-dev.c | 924 ++++++++- drivers/crypto/ccp/sev-dev.h | 17 + drivers/crypto/ccp/sp-pci.c | 12 + drivers/iommu/amd/init.c | 30 + include/linux/iommu.h | 9 + include/linux/mm.h | 6 +- include/linux/psp-sev.h | 346 ++++ include/linux/sev.h | 32 + include/uapi/linux/kvm.h | 56 + include/uapi/linux/psp-sev.h | 60 + mm/memory.c | 13 + tools/arch/x86/include/asm/cpufeatures.h | 1 + 34 files changed, 4088 insertions(+), 201 deletions(-)create mode 100644
include/linux/sev.h--
2.17.1
Quoted 47 lines · Brijesh Singh
Hi Peter,
Quoted 37 lines · Peter Gonda
Hi Brijesh,,
One high level discussion I'd like to have on these SNP KVM patches.
In these patches (V5) if a host userspace process writes a guest private page a SIGBUS is issued to that process. If the kernel writes a guest private page then the kernel panics due to the unhandled RMP fault page fault. This is an issue because not all writes into guest memory may come from a bug in the host. For instance a malicious or even buggy guest could easily point the host to writing a private page during the emulation of many virtual devices (virtio, NVMe, etc). For example if a well behaved guests behavior is to: start up a driver, select some pages to share with the guest, ask the host to convert them to shared, then use those pages for virtual device DMA, if a buggy guest forget the step to request the pages be converted to shared its easy to see how the host could rightfully write to private memory. I think we can better guarantee host reliability when running SNP guests without changing SNP’s security properties.
Here is an alternative to the current approach: On RMP violation (host or userspace) the page fault handler converts the page from private to shared to allow the write to continue. This pulls from s390’s error handling which does exactly this. See ‘arch_make_page_accessible()’. Additionally it adds less complexity to the SNP kernel patches, and requires no new ABI.
In the current (V5) KVM implementation if a userspace process generates an RMP violation (writes to guest private memory) the process receives a SIGBUS. At first glance, it would appear that user-space shouldn’t write to private memory. However, guaranteeing this in a generic fashion requires locking the RMP entries (via locks external to the RMP). Otherwise, a user-space process emulating a guest device IO may be vulnerable to having the guest memory (maliciously or by guest bug) converted to private while user-space emulation is happening. This results in a well behaved userspace process receiving a SIGBUS.
Quoted 7 lines
This proposal allows buggy and malicious guests to run under SNP without jeopardizing the reliability / safety of host processes. This is very important to a cloud service provider (CSP) since it’s common to have host wide daemons that write/read all guests, i.e. a single process could manage the networking for all VMs on the host. Crashing that singleton process kills networking for all VMs on the system.
Quoted 5 lines
Thank you for starting the thread; based on the discussion, I am keeping the current implementation as-is and *not* going with the auto conversion from private to shared. To summarize what we are doing in the current SNP series:
- If userspace accesses guest private memory, it gets SIGBUS.
So, is there anything protecting host userspace processes from malicious guests?
Quoted 8 lines
- If kernel accesses[*] guest private memory, it does panic.
[*] Kernel consults the RMP table for the page ownership before the access. If the page is shared, then it uses the locking mechanism to ensure that a guest will not be able to change the page ownership while kernel has it mapped.
thanks
Quoted 48 lines · Vlastimil Babka
Quoted 47 lines · Brijesh Singh
Hi Peter,
Quoted 44 lines · Peter Gonda
Hi Brijesh,,
One high level discussion I'd like to have on these SNP KVM patches.
In these patches (V5) if a host userspace process writes a guest private page a SIGBUS is issued to that process. If the kernel writes a guest private page then the kernel panics due to the unhandled RMP fault page fault. This is an issue because not all writes into guest memory may come from a bug in the host. For instance a malicious or even buggy guest could easily point the host to writing a private page during the emulation of many virtual devices (virtio, NVMe, etc). For example if a well behaved guests behavior is to: start up a driver, select some pages to share with the guest, ask the host to convert them to shared, then use those pages for virtual device DMA, if a buggy guest forget the step to request the pages be converted to shared its easy to see how the host could rightfully write to private memory. I think we can better guarantee host reliability when running SNP guests without changing SNP’s security properties.
Here is an alternative to the current approach: On RMP violation (host or userspace) the page fault handler converts the page from private to shared to allow the write to continue. This pulls from s390’s error handling which does exactly this. See ‘arch_make_page_accessible()’. Additionally it adds less complexity to the SNP kernel patches, and requires no new ABI.
In the current (V5) KVM implementation if a userspace process generates an RMP violation (writes to guest private memory) the process receives a SIGBUS. At first glance, it would appear that user-space shouldn’t write to private memory. However, guaranteeing this in a generic fashion requires locking the RMP entries (via locks external to the RMP). Otherwise, a user-space process emulating a guest device IO may be vulnerable to having the guest memory (maliciously or by guest bug) converted to private while user-space emulation is happening. This results in a well behaved userspace process receiving a SIGBUS.
This proposal allows buggy and malicious guests to run under SNP without jeopardizing the reliability / safety of host processes. This is very important to a cloud service provider (CSP) since it’s common to have host wide daemons that write/read all guests, i.e. a single process could manage the networking for all VMs on the host. Crashing that singleton process kills networking for all VMs on the system.
Quoted 8 lines
Quoted 5 lines
Thank you for starting the thread; based on the discussion, I am keeping the current implementation as-is and *not* going with the auto conversion from private to shared. To summarize what we are doing in the current SNP series:
- If userspace accesses guest private memory, it gets SIGBUS.
So, is there anything protecting host userspace processes from malicious guests?
Unfortunately, no.
In the future, we could look into Sean's suggestion to come with an ABI that userspace can use to lock the guest pages before the access and notify the caller of the access violation. It seems that TDX may need something similar, but I cannot tell for sure. This proposal seems good at the first glance but devil is in the detail; once implemented we also need to measure the performance implication of it.
Should we consider using SIGSEGV (SEGV_ACCERR) instead of SIGBUS? In other words, treating a guest's private pages as read-only and writing to them will generate a standard SIGSEGV.
thanks
Quoted 8 lines
Quoted 8 lines
- If kernel accesses[*] guest private memory, it does panic.
[*] Kernel consults the RMP table for the page ownership before the access. If the page is shared, then it uses the locking mechanism to ensure that a guest will not be able to change the page ownership while kernel has it mapped.
thanks
Quoted 7 lines · Brijesh Singh
Thank you for starting the thread; based on the discussion, I am keeping the current implementation as-is and *not* going with the auto conversion from private to shared. To summarize what we are doing in the current SNP series:
- If userspace accesses guest private memory, it gets SIGBUS.
- If kernel accesses[*] guest private memory, it does panic.
There's a subtlety here, though. There are really three *different* kinds of kernel accesses that matter:
1. Kernel bugs. Kernel goes off and touches some guest private memory when it didn't mean to. Say, it runs off the end of a slab page and runs into a guest page. panic() is expected here.
2. Kernel accesses guest private memory via a userspace mapping, in a place where it is known to be accessing userspace and is prepared to fault. copy_to_user() is the most straightforward example. Kernel must *not* panic(). Returning an error to the syscall is a good way to handle these (if in a syscall).
3. Kernel accesses guest private memory via a kernel mapping. This one is tricky. These probably *do* result in a panic() today, but ideally shouldn't.
Could you explicitly clarify what the current behavior is?
Quoted 6 lines · Dave Hansen
Quoted 5 lines · Brijesh Singh
Thank you for starting the thread; based on the discussion, I am keeping the current implementation as-is and *not* going with the auto conversion from private to shared. To summarize what we are doing in the current SNP series:
Quoted 7 lines
Quoted 2 lines
- If userspace accesses guest private memory, it gets SIGBUS.
- If kernel accesses[*] guest private memory, it does panic.There's a subtlety here, though. There are really three *different* kinds of kernel accesses that matter:
1. Kernel bugs. Kernel goes off and touches some guest private memory when it didn't mean to. Say, it runs off the end of a slab page and runs into a guest page.panic()is expected here.
In current implementation, a write to guest private will trigger a kernel panic().
Quoted 5 lines
2. Kernel accesses guest private memory via a userspace mapping, in a place where it is known to be accessing userspace and is prepared to fault.
copy_to_user()is the most straightforward example. Kernel must *not*panic(). Returning an error to the syscall is a good way to handle these (if in a syscall).
In the current implementation, the copy_to_user() on the guest private will fails with -EFAULT.
Quoted 3 lines
3. Kernel accesses guest private memory via a kernel mapping. This one is tricky. These probably *do* result in a
panic()today, but ideally shouldn't.
KVM has defined some helper functions to maps and unmap the guest pages. Those helper functions do the GPA to PFN lookup before calling the kmap(). Those helpers are enhanced such that it check the RMP table before the kmap() and acquire a lock to prevent a page state change until the kunmap() is called. So, in the current implementation, we should *not* see a panic() unless there is a KVM driver bug that didn't use the helper functions or a bug in the helper function itself.
Quoted 1 line
Could you explicitly clarify what the current behavior is?
Quoted 10 lines · Brijesh Singh
Quoted 3 lines
3. Kernel accesses guest private memory via a kernel mapping. This one is tricky. These probably *do* result in a
panic()today, but ideally shouldn't.KVM has defined some helper functions to maps and unmap the guest pages. Those helper functions do the GPA to PFN lookup before calling the
kmap(). Those helpers are enhanced such that it check the RMP table before thekmap()and acquire a lock to prevent a page state change until thekunmap()is called. So, in the current implementation, we should *not* see apanic()unless there is a KVM driver bug that didn't use the helper functions or a bug in the helper function itself.
I don't think this is really KVM specific.
Think of a remote process doing ptrace(PTRACE_POKEUSER) or pretty much any generic get_user_pages() instance. As long as the memory is mapped into the page tables, you're exposed to users that walk the page tables.
How do we, for example, prevent ptrace() from inducing a panic()?
Quoted 12 lines · Dave Hansen
Quoted 10 lines · Brijesh Singh
Quoted 3 lines
3. Kernel accesses guest private memory via a kernel mapping. This one is tricky. These probably *do* result in a
panic()today, but ideally shouldn't.KVM has defined some helper functions to maps and unmap the guest pages. Those helper functions do the GPA to PFN lookup before calling the
kmap(). Those helpers are enhanced such that it check the RMP table before thekmap()and acquire a lock to prevent a page state change until thekunmap()is called. So, in the current implementation, we should *not* see apanic()unless there is a KVM driver bug that didn't use the helper functions or a bug in the helper function itself.
Quoted 8 lines
I don't think this is really KVM specific.
Think of a remote process doing
ptrace(PTRACE_POKEUSER)or pretty much any genericget_user_pages()instance. As long as the memory is mapped into the page tables, you're exposed to users that walk the page tables.How do we, for example, prevent
ptrace()from inducing apanic()?
In the current approach, this access will induce a panic(). In general, supporting the ptrace() for the encrypted VM region is going to be difficult. The upcoming TDX work to unmap the guest memory region from the current process page table can easily extend for the SNP to cover the current limitations.
thanks
Sean Christopherson
maintainerQuoted 20 lines · Brijesh Singh
Quoted 18 lines · Dave Hansen
Quoted 10 lines · Brijesh Singh
Quoted 3 lines
3. Kernel accesses guest private memory via a kernel mapping. This one is tricky. These probably *do* result in a
panic()today, but ideally shouldn't.KVM has defined some helper functions to maps and unmap the guest pages. Those helper functions do the GPA to PFN lookup before calling the
kmap(). Those helpers are enhanced such that it check the RMP table before thekmap()and acquire a lock to prevent a page state change until thekunmap()is called. So, in the current implementation, we should *not* see apanic()unless there is a KVM driver bug that didn't use the helper functions or a bug in the helper function itself.I don't think this is really KVM specific.
Think of a remote process doing
ptrace(PTRACE_POKEUSER)or pretty much any genericget_user_pages()instance. As long as the memory is mapped into the page tables, you're exposed to users that walk the page tables.
Quoted 6 lines
Quoted 2 lines
How do we, for example, prevent
ptrace()from inducing apanic()?In the current approach, this access will induce a
panic(). In general, supporting theptrace()for the encrypted VM region is going to be difficult.
But ptrace() is just an example, any path in the kernel that accesses a gup'd page through a kernel mapping will explode if handed a guest private page.
Quoted 2 lines
The upcoming TDX work to unmap the guest memory region from the current process page table can easily extend for the SNP to cover the current limitations.
That represents an ABI change though. If KVM allows userspace to create SNP guests without any guarantees that userspace cannot coerce the kernel into accessing guest private memory, then we are stuck supporting that behavior even if KVM later gains the ability to provide such guarantees through new APIs.
If allowing this behavior was only a matter of the system admin opting into a dangerous configuration, I would probably be ok merging SNP with it buried behind EXPERT or something scarier, but this impacts KVM's ABI as well as kernel internals, e.g. the hooks in kvm_vcpu_map() and friends are unnecessary if KVM can differentiate between shared and private gfns in its memslots, as gfn_to_pfn() will either fail or point at memory that is guaranteed to be in the shared state.
Quoted 3 lines · Brijesh Singh
Quoted 1 line
How do we, for example, prevent
ptrace()from inducing apanic()?In the current approach, this access will induce a
panic().
That needs to get fixed before SEV-SNP is merged, IMNHO. This behavior would effectively mean that any userspace given access to create SNP guests would panic the kernel.
Quoted 2 lines
In general, supporting the
ptrace()for the encrypted VM region is going to be difficult.
By "supporting", do you mean doing something functional? I don't really care if ptrace() to guest private memory returns -EINVAL or whatever. The most important thing is not crashing the host.
Also, as Sean mentioned, this isn't really about ptrace() itself. It's really about ensuring that no kernel or devices accesses to guest private memory can induce bad behavior.
Quoted 3 lines
The upcoming TDX work to unmap the guest memory region from the current process page table can easily extend for the SNP to cover the current limitations.
My preference would be that we never have SEV-SNP code in the kernel that can panic() the host from guest userspace. If that means waiting until there's common guest unmapping infrastructure around, then I think we should wait.
Quoted 4 lines
My preference would be that we never have SEV-SNP code in the kernel that can
panic()the host from guest userspace. If that means waiting until there's common guest unmapping infrastructure around, then I think we should wait.
Perhaps I'm missing some context ... but guests must NEVER be allowed to panic the host.
-Tony
Borislav Petkov
maintainerQuoted 7 lines · Dave Hansen
By "supporting", do you mean doing something functional? I don't really care if
ptrace()to guest private memory returns-EINVALor whatever. The most important thing is not crashing the host.Also, as Sean mentioned, this isn't really about
ptrace()itself. It's really about ensuring that no kernel or devices accesses to guest private memory can induce bad behavior.
I keep repeating this suggestion of mine that we should treat guest-private pages as hw-poisoned pages which have experienced a uncorrectable error in the past.
mm already knows how to stay away from those.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteSean Christopherson
maintainerQuoted 9 lines · Borislav Petkov
Quoted 7 lines · Dave Hansen
By "supporting", do you mean doing something functional? I don't really care if
ptrace()to guest private memory returns-EINVALor whatever. The most important thing is not crashing the host.Also, as Sean mentioned, this isn't really about
ptrace()itself. It's really about ensuring that no kernel or devices accesses to guest private memory can induce bad behavior.
Quoted 5 lines
I keep repeating this suggestion of mine that we should treat guest-private pages as hw-poisoned pages which have experienced a uncorrectable error in the past.
mm already knows how to stay away from those.
Kirill posted a few RFCs that did exactly that. It's definitely a viable approach, but it's a bit of a dead end, e.g. doesn't help solve page migration, is limited to struct page, doesn't capture which KVM guest owns the memory, etc...
Borislav Petkov
maintainerQuoted 2 lines · Sean Christopherson
Kirill posted a few RFCs that did exactly that. It's definitely a viable approach, but it's a bit of a dead end,
One thing at a time...
Quoted 1 line
e.g. doesn't help solve page migration,
AFAICR, that needs a whole explicit and concerted effort with the migration helper - that was one of the approaches, at least, guest's explicit involvement, remote attestation and a bunch of other things...
Quoted 1 line
is limited to struct page
I'm no mm guy so maybe you can elaborate further.
Quoted 1 line
doesn't capture which KVM guest owns the memory, etc...
So I don't think we need this for the problem at hand. But from the sound of it, it probably is a good idea to be able to map the guest owner to the memory anyway.
Quoted 1 line
Right, there it is in the last patch.
Hmmkay, so we need some generic machinery which unmaps memory from the host kernel's pagetables so that it doesn't do any stray/unwanted accesses to it. I'd look in the direction of mm folks for what to do exactly, though.
Thx.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteQuoted 12 lines · Dave Hansen
Quoted 3 lines · Brijesh Singh
Quoted 1 line
How do we, for example, prevent
ptrace()from inducing apanic()?In the current approach, this access will induce a
panic().That needs to get fixed before SEV-SNP is merged, IMNHO. This behavior would effectively mean that any userspace given access to create SNP guests would panic the kernel.
Quoted 2 lines
In general, supporting the
ptrace()for the encrypted VM region is going to be difficult.
Quoted 7 lines
By "supporting", do you mean doing something functional? I don't really care if
ptrace()to guest private memory returns-EINVALor whatever. The most important thing is not crashing the host.Also, as Sean mentioned, this isn't really about
ptrace()itself. It's really about ensuring that no kernel or devices accesses to guest private memory can induce bad behavior.
Then we need gup to block any changes from shared to guest private? I assume there will be the usual issues of recognizing temporary elevated refcount vs long-term gup, etc.
Quoted 3 lines
Quoted 3 lines
The upcoming TDX work to unmap the guest memory region from the current process page table can easily extend for the SNP to cover the current limitations.
By "current process page table" you mean userspace page tables?
Quoted 5 lines
My preference would be that we never have SEV-SNP code in the kernel that can
panic()the host from guest userspace. If that means waiting until there's common guest unmapping infrastructure around, then I think we should wait.
Quoted 4 lines · Dave Hansen
My preference would be that we never have SEV-SNP code in the kernel that can
panic()the host from guest userspace. If that means waiting until there's common guest unmapping infrastructure around, then I think we should wait.
Can you elaborate how to crash host kernel from guest user-space? If I understood correctly it was about crashing host kernel from _host_ user-space.
I think the RMP-fault path in the page-fault handler needs to take the uaccess exception tables into account before actually causing a panic. This should solve most of the problems discussed here.
Maybe we also need the previously suggested copy_from/to_guest() interfaces.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Quoted 8 lines · Joerg Roedel
Quoted 4 lines · Dave Hansen
My preference would be that we never have SEV-SNP code in the kernel that can
panic()the host from guest userspace. If that means waiting until there's common guest unmapping infrastructure around, then I think we should wait.Can you elaborate how to crash host kernel from guest user-space? If I understood correctly it was about crashing host kernel from _host_ user-space.
Sorry, I misspoke there.
My concern is about crashing the host kernel. It appears that *host* userspace can do that quite easily by inducing the host kernel to access some guest private memory via a kernel mapping.
Quoted 3 lines
I think the RMP-fault path in the page-fault handler needs to take the uaccess exception tables into account before actually causing a panic. This should solve most of the problems discussed here.
That covers things like copy_from_user(). It does not account for things where kernel mappings are used, like where a get_user_pages()/kmap() is in play.
Quoted 10 lines · Dave Hansen
Quoted 8 lines · Joerg Roedel
Quoted 4 lines · Dave Hansen
My preference would be that we never have SEV-SNP code in the kernel that can
panic()the host from guest userspace. If that means waiting until there's common guest unmapping infrastructure around, then I think we should wait.Can you elaborate how to crash host kernel from guest user-space? If I understood correctly it was about crashing host kernel from _host_ user-space.
Quoted 5 lines
Sorry, I misspoke there.
My concern is about crashing the host kernel. It appears that *host* userspace can do that quite easily by inducing the host kernel to access some guest private memory via a kernel mapping.
I thought some of the scenarios discussed here also went along "guest (doesn't matter if userspace or kernel) shares a page with host, invokes some host kernel operation and in parallel makes the page private again".
Quoted 8 lines
Quoted 3 lines
I think the RMP-fault path in the page-fault handler needs to take the uaccess exception tables into account before actually causing a panic. This should solve most of the problems discussed here.
That covers things like
copy_from_user(). It does not account for things where kernel mappings are used, like where a get_user_pages()/kmap() is in play.
Quoted 3 lines · Dave Hansen
That covers things like
copy_from_user(). It does not account for things where kernel mappings are used, like where a get_user_pages()/kmap() is in play.
The kmap case is guarded by KVM code, which locks the page first so that the guest can't change the page state, then checks the page state, and if it is shared does the kmap and the access.
This should turn an RMP fault in the kernel which is not covered in the uaccess exception table into a fatal error.
Regards,
Signature · 10 lines
Jörg Rödel [email protected] SUSE Software Solutions Germany GmbH Maxfeldstr. 5 90409 Nürnberg Germany (HRB 36809, AG Nürnberg) Geschäftsführer: Ivo Totev
Quoted 8 lines · Joerg Roedel
Quoted 3 lines · Dave Hansen
That covers things like
copy_from_user(). It does not account for things where kernel mappings are used, like where a get_user_pages()/kmap() is in play.The kmap case is guarded by KVM code, which locks the page first so that the guest can't change the page state, then checks the page state, and if it is shared does the kmap and the access.
The KVM use-case is well covered in the series, but I believe Dave is highlighting what if the access happens outside of the KVM driver (such as a ptrace() or others).
One possible approach to fix this is to enlighten the kmap/unmap(). Basically, move the per page locking mechanism used by the KVM in the arch-specific code and have kmap/kunmap() call the arch hooks. The arch hooks will do this:
Before the map, check whether the page is added as a shared in the RMP table. If not shared, then error. Acquire a per-page map_lock.
Release the per-page map_lock on the kunmap().
The current patch set provides helpers to change the page from private to shared. Enhance the helpers to check for the per-page map_lock, if the map_lock is held then do not allow changing the page from shared to private.
Thoughts ?
Quoted 6 lines
This should turn an RMP fault in the kernel which is not covered in the uaccess exception table into a fatal error.
Regards,
Quoted 8 lines · Brijesh Singh
Quoted 5 lines · Joerg Roedel
Quoted 3 lines · Dave Hansen
That covers things like copy_from_user(). It does not account for things where kernel mappings are used, like where a get_user_pages()/kmap() is in play.
Quoted 8 lines
Quoted 3 lines
The kmap case is guarded by KVM code, which locks the page first so that the guest can't change the page state, then checks the page state, and if it is shared does the kmap and the access.
The KVM use-case is well covered in the series, but I believe Dave is highlighting what if the access happens outside of the KVM driver (such as a
ptrace()or others).
AFAIU ptrace() is a scenario where the userspace mapping is being gup-ped, not a kernel page being kmap()ed?
Quoted 5 lines
One possible approach to fix this is to enlighten the kmap/unmap(). Basically, move the per page locking mechanism used by the KVM in the arch-specific code and have kmap/kunmap() call the arch hooks. The arch hooks will do this:
Quoted 8 lines
Before the map, check whether the page is added as a shared in the RMP table. If not shared, then error.
Acquire a per-pagemap_lock.
Release the per-pagemap_lockon thekunmap().The current patch set provides helpers to change the page from private to shared. Enhance the helpers to check for the per-page
map_lock, if themap_lockis held then do not allow changing the page from shared to private.
That could work for the kmap() context.
What to do for the userspace context (host userspace)?
- shared->private transition - page has to be unmapped from all userspace, elevated refcount (gup() in progress) can block this unmap until it goes away - could be doable
- still, what to do if host userspace then tries to access the unmapped page? SIGSEGV instead of SIGBUS and it can recover?
Quoted 8 lines
Thoughts ?
Quoted 6 lines
This should turn an RMP fault in the kernel which is not covered in the uaccess exception table into a fatal error.
Regards,
Quoted 14 lines · Vlastimil Babka
Quoted 13 lines · Brijesh Singh
Quoted 8 lines · Joerg Roedel
Quoted 3 lines · Dave Hansen
That covers things like copy_from_user(). It does not account for things where kernel mappings are used, like where a get_user_pages()/kmap() is in play.
The kmap case is guarded by KVM code, which locks the page first so that the guest can't change the page state, then checks the page state, and if it is shared does the kmap and the access.
Quoted 7 lines
Quoted 3 lines
The KVM use-case is well covered in the series, but I believe Dave is highlighting what if the access happens outside of the KVM driver (such as a
ptrace()or others).AFAIU
ptrace()is a scenario where the userspace mapping is being gup-ped, not a kernel page being kmap()ed?
Yes that is correct.
Quoted 14 lines
Quoted 5 lines
One possible approach to fix this is to enlighten the kmap/unmap(). Basically, move the per page locking mechanism used by the KVM in the arch-specific code and have kmap/kunmap() call the arch hooks. The arch hooks will do this:
Quoted 8 lines
Before the map, check whether the page is added as a shared in the RMP table. If not shared, then error.
Acquire a per-pagemap_lock.
Release the per-pagemap_lockon thekunmap().The current patch set provides helpers to change the page from private to shared. Enhance the helpers to check for the per-page
map_lock, if themap_lockis held then do not allow changing the page from shared to private.
Quoted 5 lines
That could work for the
kmap()context.
What to do for the userspace context (host userspace)?
-shared->privatetransition - page has to be unmapped from all userspace, elevated refcount (gup()in progress) can block this unmap until it goes away - could be doable
An unmap of the page from all the userspace process during the page state transition will be great. If we can somehow store the state information in the 'struct page' then it can be later used to make better decision. I am not sure that relying on the elevated refcount is the correct approach. e.g in the case of encrypted guests, the HV may pin the page to prevent it from migration.
Thoughts on how you want to approach unmaping the page from userspace page table?
Quoted 3 lines
- still, what to do if host userspace then tries to access the unmapped page? SIGSEGV instead of SIGBUS and it can recover?
Yes, SIGSEGV makes sense to me.
Quoted 11 lines
Quoted 10 lines
Thoughts ?
Quoted 6 lines
This should turn an RMP fault in the kernel which is not covered in the uaccess exception table into a fatal error.
Regards,
Quoted 14 lines · Brijesh Singh
Quoted 6 lines
That could work for the
kmap()context.
What to do for the userspace context (host userspace)?
-shared->privatetransition - page has to be unmapped from all userspace, elevated refcount (gup()in progress) can block this unmap until it goes away - could be doableAn unmap of the page from all the userspace process during the page state transition will be great. If we can somehow store the state information in the 'struct page' then it can be later used to make better decision. I am not sure that relying on the elevated refcount is the correct approach. e.g in the case of encrypted guests, the HV may pin the page to prevent it from migration.
Quoted 2 lines
Thoughts on how you want to approach unmaping the page from userspace page table?
After giving it more thought and rereading the threads here it seems I thought it would be easier than it really is, and it would have to be something at least like Kirill's hwpoison based approach.
Quoted 5 lines
Quoted 3 lines
- still, what to do if host userspace then tries to access the unmapped page? SIGSEGV instead of SIGBUS and it can recover?
Yes, SIGSEGV makes sense to me.
OTOH the newer fd-based proposal also IIUC takes care of this part better - the host userspace controls the guest's shared->private conversion requests so it can't be tricked to access a page that's changed under it.
Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
Thoughts ?
Quoted 6 lines
This should turn an RMP fault in the kernel which is not covered in the uaccess exception table into a fatal error.
Regards,
Quoted 10 lines · Joerg Roedel
Quoted 3 lines · Dave Hansen
That covers things like
copy_from_user(). It does not account for things where kernel mappings are used, like where a get_user_pages()/kmap() is in play.The kmap case is guarded by KVM code, which locks the page first so that the guest can't change the page state, then checks the page state, and if it is shared does the kmap and the access.
This should turn an RMP fault in the kernel which is not covered in the uaccess exception table into a fatal error.
Let's say something does process_vm_readv() where the pid is a qemu process and it is writing to a guest private memory area. The syscall will eventually end up in process_vm_rw_single_vec() which does:
Quoted 3 lines
pinned_pages= pin_user_pages_remote(mm, pa,pinned_pages,
flags,process_pages, NULL, &locked);
...
Quoted 3 lines
rc = process_vm_rw_pages(process_pages,
start_offset, bytes, iter,vm_write);
and eventually in copy_page_from_iter():
Quoted 3 lines
void *kaddr = kmap_local_page(page);
size_t wanted = _copy_from_iter(kaddr + offset, bytes, i);
kunmap_local(kaddr);The kernel access to 'kaddr+offset' shouldn't fault. How does the KVM code thwart that kmap_local_page()?