On 12/24/2024 5:23 PM, Borislav Petkov wrote: > On Wed, Dec 18, 2024 at 10:50:07AM +0530, Nikunj A. Dadhania wrote: >> With the condition inside the function, even tough the MSR is not >> valid in this configuration, I am getting value 0. Is this behavior >> acceptable ? > > The whole untested diff, should DTRT this time: I have tested the diff and ES_UNSUPPORTED causes unexpected termination of SNP guest(without SecureTSC). $ sudo wrmsr 0x10 0 KVM: unknown exit reason 24 EAX=00000000 EBX=00000000 ECX=00000000 EDX=00a00f11 ESI=00000000 EDI=00000000 EBP=00000000 ESP=00000000 EIP=0000fff0 EFL=00000002 [-------] CPL=0 II=0 A20=1 SMM=0 HLT=0 ... $ sudo wrmsr 0xc0010134 0 KVM: unknown exit reason 24 EAX=00000000 EBX=00000000 ECX=00000000 EDX=00a00f11 ESI=00000000 EDI=00000000 EBP=00000000 ESP=00000000 ... IMO, the below change appropriately handles all the conditions well and does not affect SNP guests without SecureTSC. diff --git a/arch/x86/coco/sev/core.c b/arch/x86/coco/sev/core.c index 84e4e64decf7..a8977c68695b 100644 --- a/arch/x86/coco/sev/core.c +++ b/arch/x86/coco/sev/core.c @@ -1428,6 +1428,40 @@ static enum es_result __vc_handle_msr_caa(struct pt_regs *regs, bool write) return ES_OK; } +/* + * TSC related accesses should not exit to the hypervisor when a guest is + * executing with SecureTSC enabled, so special handling is required for + * accesses of MSR_IA32_TSC and MSR_AMD64_GUEST_TSC_FREQ: + * + * Writes: Writing to MSR_IA32_TSC can cause subsequent reads + * of the TSC to return undefined values, so ignore all + * writes. + * Reads: Reads of MSR_IA32_TSC should return the current TSC + * value, use the value returned by RDTSC. + */ +static enum es_result __vc_handle_msr_tsc(struct pt_regs *regs, bool write) +{ + u64 tsc; + + /* + * GUEST_TSC_FREQ should not be intercepted when Secure TSC is + * enabled. Terminate the SNP guest when the interception is enabled. + */ + if (regs->cx == MSR_AMD64_GUEST_TSC_FREQ) + return ES_VMM_ERROR; + + if (write) { + WARN_ONCE(1, "TSC MSR writes are verboten!\n"); + return ES_OK; + } + + tsc = rdtsc_ordered(); + regs->ax = lower_32_bits(tsc); + regs->dx = upper_32_bits(tsc); + + return ES_OK; +} + static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt) { struct pt_regs *regs = ctxt->regs; @@ -1437,8 +1471,16 @@ static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt) /* Is it a WRMSR? */ write = ctxt->insn.opcode.bytes[1] == 0x30; - if (regs->cx == MSR_SVSM_CAA) + switch (regs->cx) { + case MSR_SVSM_CAA: return __vc_handle_msr_caa(regs, write); + case MSR_IA32_TSC: + case MSR_AMD64_GUEST_TSC_FREQ: + if (sev_status & MSR_AMD64_SNP_SECURE_TSC) + return __vc_handle_msr_tsc(regs, write); + default: + break; + } ghcb_set_rcx(ghcb, regs->cx); if (write) {