Re: [PATCH v15 04/13] x86/sev: Change TSC MSR behavior for Secure TSC enabled guests

Nikunj A. Dadhania
2024-12-10T05:02:34Z

On 12/9/2024 9:27 PM, Borislav Petkov wrote:
> On Tue, Dec 03, 2024 at 02:30:36PM +0530, Nikunj A Dadhania wrote:
>> Secure TSC enabled guests should not write to MSR_IA32_TSC(10H) register as
>> the subsequent TSC value reads are undefined.
>
> What does that mean exactly?

That is the warning from the APM: 15.36.18 Secure TSC

"Guests that run with Secure TSC enabled are not expected to perform writes to
the TSC MSR (10h). If such a write occurs, subsequent TSC values read are
undefined."

What I make out of it is: if a write is performed to the TSC MSR, subsequent
reads of TSC is not reliable/trusted.

That was the reason to ignore such writes in the #VC handler.

>
> I'd prefer if we issued a WARN_ONCE() there on the write to catch any
> offenders.

Do you also want to terminate the offending guest?

ES_UNSUPPORTED return will do that.

>
> *NO ONE* should be writing the TSC MSR but that's a different story.
>
> IOW, something like this ontop of yours?
>
> ---
>
> diff --git a/arch/x86/coco/sev/core.c b/arch/x86/coco/sev/core.c
> index c22cb2ea4b99..050170eb28e6 100644
> --- a/arch/x86/coco/sev/core.c
> +++ b/arch/x86/coco/sev/core.c
> @@ -1443,9 +1443,15 @@ static enum es_result __vc_handle_msr_tsc(struct pt_regs *regs, bool write)
> {
> u64 tsc;
>
> - if (write)
> - return ES_OK;
> + if (!(sev_status & MSR_AMD64_SNP_SECURE_TSC))
> + goto read_tsc;

This is changing the behavior for SEV-ES and SNP guests(non SECURE_TSC), TSC MSR
reads are converted to RDTSC. This is a good optimization. But just wanted to
bring up the subtle impact.

> +
> + if (write) {
> + WARN_ONCE(1, "TSC MSR writes are verboten!\n");
> + return ES_UNSUPPORTED;

Sure, we can add a WARN_ONCE().

> + }
>
> +read_tsc:
> tsc = rdtsc_ordered();
> regs->ax = lower_32_bits(tsc);
> regs->dx = upper_32_bits(tsc);
> @@ -1462,11 +1468,14 @@ 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) {

Yes, I was thinking about a switch, as there will be more such instances when we
enable newer features.

> + case MSR_SVSM_CAA:
> return __vc_handle_msr_caa(regs, write);
> -
> - if (regs->cx == MSR_IA32_TSC && (sev_status & MSR_AMD64_SNP_SECURE_TSC))
> + case MSR_IA32_TSC:
> return __vc_handle_msr_tsc(regs, write);
> + default:
> + break;
> + }
>
> ghcb_set_rcx(ghcb, regs->cx);
> if (write) {
>

Regards,
Nikunj