Skip to contentSkip to conversation

X86/eager-fpu: Switch to eager fpu save/restore

PATCH In review Fouad Hilly 2 participants 8 messages Mar 4, 2024 – Mar 5, 2024

lore
Share & tools
lore
#0 lore raw

cover X86/eager-fpu: Switch to eager fpu save/restore

X86 Xen will only eagerly switch FPU context in the scheduler. Xen itslef won't set CR0.TS other than for the purpose of servicing a PV guset.

---
CC: Jan Beulich <[email protected]>
CC: Andrew Cooper <[email protected]>
CC: "Roger Pau Monné" <[email protected]>
CC: Wei Liu <[email protected]>
CC: George Dunlap <[email protected]>
CC: Julien Grall <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Paul Durrant <[email protected]>
CC: Jun Nakajima <[email protected]>
CC: Kevin Tian <[email protected]>

Wei Liu (3):
x86: i387.c cleanup
x86: introduce xstate_zero
x86: switch to eager fpu save / restore

 xen/arch/x86/cpu/common.c                    |   3 -
 xen/arch/x86/domain.c                        |  10 +-
 xen/arch/x86/domctl.c                        |   4 +-
 xen/arch/x86/hvm/emulate.c                   |  38 +----
 xen/arch/x86/hvm/hvm.c                       |   8 +-
 xen/arch/x86/hvm/svm/nestedsvm.c             |  62 +------
 xen/arch/x86/hvm/svm/svm.c                   |  81 +--------
 xen/arch/x86/hvm/svm/vmcb.c                  |   4 +-
 xen/arch/x86/hvm/vlapic.c                    |   4 -
 xen/arch/x86/hvm/vmx/vmcs.c                  |   8 +-
 xen/arch/x86/hvm/vmx/vmx.c                   |  70 +-------
 xen/arch/x86/hvm/vmx/vvmx.c                  |  15 +-
 xen/arch/x86/i387.c                          | 170 +++++--------------
 xen/arch/x86/include/asm/domain.h            |   3 -
 xen/arch/x86/include/asm/hvm/svm/nestedsvm.h |   3 -
 xen/arch/x86/include/asm/hvm/vmx/vmcs.h      |   2 -
 xen/arch/x86/include/asm/i387.h              |   3 +-
 xen/arch/x86/include/asm/xstate.h            |  18 +-
 xen/arch/x86/pv/misc-hypercalls.c            |   3 +-
 xen/arch/x86/traps.c                         |  18 +-
 xen/arch/x86/xstate.c                        |  65 ++++---
 xen/common/domain.c                          |   2 -
 xen/common/efi/runtime.c                     |   9 +-
 xen/include/xen/sched.h                      |   4 -
 24 files changed, 108 insertions(+), 499 deletions(-)
Signature · 1 line
2.42.0
#1 lore raw

PATCH 1/3 x86: i387.c cleanup

From: Wei Liu <[email protected]>

No functional change

---
CC: Jan Beulich <[email protected]>
CC: Andrew Cooper <[email protected]>
CC: "Roger Pau Monné" <[email protected]>
CC: Wei Liu <[email protected]>

---
 xen/arch/x86/i387.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
xen/arch/x86/i387.c +3 -3
index d824f2bb5294..7a4297cc921e 100644
@@ -26,7 +26,7 @@ static inline void fpu_xrstor(struct vcpu *v, uint64_t mask)
 
     ASSERT(v->arch.xsave_area);
     /*
-     * XCR0 normally represents what guest OS set. In case of Xen itself, 
+     * XCR0 normally represents what guest OS set. In case of Xen itself,
      * we set the accumulated feature mask before doing save/restore.
      */
     ok = set_xcr0(v->arch.xcr0_accum | XSTATE_FP_SSE);
@@ -36,7 +36,7 @@ static inline void fpu_xrstor(struct vcpu *v, uint64_t mask)
     ASSERT(ok);
 }
 
-/* Restor x87 FPU, MMX, SSE and SSE2 state */
+/* Restore x87 FPU, MMX, SSE and SSE2 state */
 static inline void fpu_fxrstor(struct vcpu *v)
 {
     const typeof(v->arch.xsave_area->fpu_sse) *fpu_ctxt = v->arch.fpu_ctxt;
@@ -307,7 +307,7 @@ void save_fpu_enable(void)
 int vcpu_init_fpu(struct vcpu *v)
 {
     int rc;
-    
+
     v->arch.fully_eager_fpu = opt_eager_fpu;
 
     if ( (rc = xstate_alloc_save_area(v)) != 0 )
Signature · 1 line
2.42.0
Acked-by on v1 1/3
#2 lore raw

Re: [PATCH 1/3] x86: i387.c cleanup

Quoted 3 lines · Fouad Hilly

From: Wei Liu <[email protected]>

No functional change

I don't think that's what's relevant to mention here. Saying that it's trailing blanks and spelling which are taken care of would have clarified what's to expect before even looking at the changes. I may decide to take the liberty of adding a sentence to this effect while committing ...

Quoted 2 lines

Jan

#3 lore raw

PATCH 2/3 x86: introduce xstate_zero

In reply to Fouad Hilly

From: Wei Liu <[email protected]>

Factor out xrstor__ and introduce xstate_zero, which zeros all the state components specified in the mask.

---
CC: Jan Beulich <[email protected]>
CC: Andrew Cooper <[email protected]>
CC: "Roger Pau Monné" <[email protected]>
CC: Wei Liu <[email protected]>

---
 xen/arch/x86/include/asm/xstate.h |  1 +
 xen/arch/x86/xstate.c             | 39 +++++++++++++++++++++++++------
 2 files changed, 33 insertions(+), 7 deletions(-)
xen/arch/x86/include/asm/xstate.h +1 -0
index c08c267884f0..bd767d9cd714 100644
@@ -94,6 +94,7 @@ uint64_t get_msr_xss(void);
 uint64_t read_bndcfgu(void);
 void xsave(struct vcpu *v, uint64_t mask);
 void xrstor(struct vcpu *v, uint64_t mask);
+void xstate_zero(uint64_t mask);
 void xstate_set_init(uint64_t mask);
 bool xsave_enabled(const struct vcpu *v);
 int __must_check validate_xstate(const struct domain *d,
xen/arch/x86/xstate.c +32 -7
index cf94761d0542..92a65bd8d52c 100644
@@ -368,11 +368,12 @@ void xsave(struct vcpu *v, uint64_t mask)
         ptr->fpu_sse.x[FPU_WORD_SIZE_OFFSET] = fip_width;
 }
 
-void xrstor(struct vcpu *v, uint64_t mask)
+/* True -> no error, false -> failed */
+static bool xrstor__(struct xsave_struct *ptr, uint64_t xcr0_accum,
+                     uint64_t mask)
 {
     uint32_t hmask = mask >> 32;
     uint32_t lmask = mask;
-    struct xsave_struct *ptr = v->arch.xsave_area;
     unsigned int faults, prev_faults;
 
     /*
@@ -412,7 +413,7 @@ void xrstor(struct vcpu *v, uint64_t mask)
                          [ptr] "D" (ptr) )
 
 #define XRSTOR(pfx) \
-        if ( v->arch.xcr0_accum & XSTATE_XSAVES_ONLY ) \
+        if ( xcr0_accum & XSTATE_XSAVES_ONLY ) \
         { \
             if ( unlikely(!(ptr->xsave_hdr.xcomp_bv & \
                             XSTATE_COMPACTION_ENABLED)) ) \
@@ -461,7 +462,7 @@ void xrstor(struct vcpu *v, uint64_t mask)
                   ((mask & X86_XCR0_YMM) &&
                    !(ptr->xsave_hdr.xcomp_bv & XSTATE_COMPACTION_ENABLED))) )
                 ptr->fpu_sse.mxcsr &= mxcsr_mask;
-            if ( v->arch.xcr0_accum & XSTATE_XSAVES_ONLY )
+            if ( xcr0_accum & XSTATE_XSAVES_ONLY )
             {
                 ptr->xsave_hdr.xcomp_bv &= this_cpu(xcr0) | this_cpu(xss);
                 ptr->xsave_hdr.xstate_bv &= ptr->xsave_hdr.xcomp_bv;
@@ -478,14 +479,35 @@ void xrstor(struct vcpu *v, uint64_t mask)
         case 2: /* Stage 2: Reset all state. */
             ptr->fpu_sse.mxcsr = MXCSR_DEFAULT;
             ptr->xsave_hdr.xstate_bv = 0;
-            ptr->xsave_hdr.xcomp_bv = v->arch.xcr0_accum & XSTATE_XSAVES_ONLY
+            ptr->xsave_hdr.xcomp_bv = xcr0_accum & XSTATE_XSAVES_ONLY
                                       ? XSTATE_COMPACTION_ENABLED : 0;
             continue;
         }
 
-        domain_crash(current->domain);
-        return;
+        return false;
     }
+
+    return true;
+}
+
+void xrstor(struct vcpu *v, uint64_t mask)
+{
+    if ( !xrstor__(v->arch.xsave_area, v->arch.xcr0_accum, mask) )
+        domain_crash(current->domain);
+}
+
+void xstate_zero(uint64_t mask)
+{
+    bool ok;
+    struct xsave_struct tmp;
+
+    tmp.fpu_sse.mxcsr = MXCSR_DEFAULT;
+    tmp.xsave_hdr.xstate_bv = 0;
+    tmp.xsave_hdr.xcomp_bv = 0;
+    memset(tmp.xsave_hdr.reserved, 0, sizeof(tmp.xsave_hdr.reserved));
+
+    ok = xrstor__(&tmp, mask, mask);
+    ASSERT(ok);
 }
 
 bool xsave_enabled(const struct vcpu *v)
@@ -731,6 +753,9 @@ int handle_xsetbv(u32 index, u64 new_bv)
     if ( (new_bv & ~xcr0_max) || !valid_xcr0(new_bv) )
         return -EINVAL;
 
+    /* Zero state components before writing new XCR0 */
+    xstate_zero(get_xcr0());
+
     /* By this point, new_bv really should be accepted by hardware. */
     if ( unlikely(!set_xcr0(new_bv)) )
     {
Signature · 1 line
2.42.0
#4 lore raw

Re: [PATCH 2/3] x86: introduce xstate_zero

xen/arch/x86/xstate.c void xrstor(struct vcpu *v, uint64_t mask) · line 504

Quoted 6 lines · Fouad Hilly
xen/arch/x86/xstate.c +6 -0
+void xstate_zero(uint64_t mask)
+{
+    bool ok;
+    struct xsave_struct tmp;
+
+    tmp.fpu_sse.mxcsr = MXCSR_DEFAULT;

This is a clear indication that the function name is wrong. Perhaps it is "reset" that was meant?

xen/arch/x86/xstate.c void xrstor(struct vcpu *v, uint64_t mask) · line 509

Quoted 5 lines
xen/arch/x86/xstate.c +5 -0
+    tmp.xsave_hdr.xstate_bv = 0;
+    tmp.xsave_hdr.xcomp_bv = 0;
+    memset(tmp.xsave_hdr.reserved, 0, sizeof(tmp.xsave_hdr.reserved));
+
+    ok = xrstor__(&tmp, mask, mask);

There's a lot of "tmp" that is left uninitialized, which would introduce a leak of (stack) data. I think "tmp" instead wants to have an initializer (consisting of just the explicit setting of MXCSR, leaving everything else to be default, i.e. zero-initialized).

xen/arch/x86/xstate.c int handle_xsetbv(u32 index, u64 new_bv) · line 757

Quoted 10 lines
xen/arch/x86/xstate.c +3 -0
+    ASSERT(ok);
 }
 
 bool xsave_enabled(const struct vcpu *v)
@@ -731,6 +753,9 @@ int handle_xsetbv(u32 index, u64 new_bv)
     if ( (new_bv & ~xcr0_max) || !valid_xcr0(new_bv) )
         return -EINVAL;
 
+    /* Zero state components before writing new XCR0 */
+    xstate_zero(get_xcr0());

This change isn't explained in the description, doesn't fit the subject (i.e. mechanical and functional change likely want splitting), and is imo wrong: Why would XSETBV gain this kind of side effect, when processed (emulated) in Xen? What I can see may want clearing are state components which were never enabled before by a vCPU. That would then need doing after writing the new XCR0 value, though. And it looks like that's already in place - is there something wrong with that code?

Or is this about clearing in hardware state components about to be turned off? If so, it would again need to be only the delta of components that's reset here, and their state would need saving first. Upon re-enabling of a component, that state would then need to be available for restoring. This need for saving of state would then also explain why what's presently named xstate_zero() can't very well use the vCPU's ->arch.xsave_area, but needs to have a (relatively big) on-stack variable instead.

Jan

#5 lore raw

PATCH 3/3 x86: switch to eager fpu save / restore

In reply to Fouad Hilly

From: Wei Liu <[email protected]>

Previously FPU is lazily switched. Due to the fact that a malicious guest can speculatively read the not yet switched out register states, we need to eagerly switch FPU states when a domain is scheduled to run.

In the new world, Xen will eagerly switch FPU context in the scheduler. Xen itself won't set CR0.TS other than for the purpose of servicing a PV guest.

The following things are done:

1. Xen will only set and clear CR0.TS on behalf of a PV guest. Any #NM received in Xen should only be delivered to the running PV guest.

2. Xen no longer causes vmexit for #NM for HVM guests when nested HVM is not in use.

3. When nested HVM is in use, Xen needs to trap #NM if specified by the L1 hypervisor, but all #NM handling is left to L1 hypervisor to deal with.

4. Xen saves and restores FPU states wherever it needs to. The following places are modified:
1. Scheduling in and out a guest;
2. Calling EFI runtime service;
3. ACPI reset;
4. x86 insn emulator fpu insn emulation.

5. Treat FPU as always initialised. Adjust following components:
1. HVM vcpu context save / load code;
2. arch_{get,set}_info_guest;
3. VLAPIC code.

6. Delete lazy FPU handling code.

Strip XCR0 and IA32_XSS manipulation from __context_switch. We need to be able to zero out previously used state components. Push everything into fpu_xrstor as that's the most suitable place.

Tested on AMD with PKU disabled and Intel, no performance degradation.

---
CC: Jan Beulich <[email protected]>
CC: Andrew Cooper <[email protected]>
CC: "Roger Pau Monné" <[email protected]>
CC: Wei Liu <[email protected]>
CC: George Dunlap <[email protected]>
CC: Julien Grall <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Paul Durrant <[email protected]>
CC: Jun Nakajima <[email protected]>
CC: Kevin Tian <[email protected]>

---
 xen/arch/x86/cpu/common.c                    |   3 -
 xen/arch/x86/domain.c                        |  10 +-
 xen/arch/x86/domctl.c                        |   4 +-
 xen/arch/x86/hvm/emulate.c                   |  38 +----
 xen/arch/x86/hvm/hvm.c                       |   8 +-
 xen/arch/x86/hvm/svm/nestedsvm.c             |  62 +------
 xen/arch/x86/hvm/svm/svm.c                   |  81 +--------
 xen/arch/x86/hvm/svm/vmcb.c                  |   4 +-
 xen/arch/x86/hvm/vlapic.c                    |   4 -
 xen/arch/x86/hvm/vmx/vmcs.c                  |   8 +-
 xen/arch/x86/hvm/vmx/vmx.c                   |  70 +-------
 xen/arch/x86/hvm/vmx/vvmx.c                  |  15 +-
 xen/arch/x86/i387.c                          | 164 ++++---------------
 xen/arch/x86/include/asm/domain.h            |   3 -
 xen/arch/x86/include/asm/hvm/svm/nestedsvm.h |   3 -
 xen/arch/x86/include/asm/hvm/vmx/vmcs.h      |   2 -
 xen/arch/x86/include/asm/i387.h              |   3 +-
 xen/arch/x86/include/asm/xstate.h            |  17 +-
 xen/arch/x86/pv/misc-hypercalls.c            |   3 +-
 xen/arch/x86/traps.c                         |  18 +-
 xen/arch/x86/xstate.c                        |  26 ---
 xen/common/domain.c                          |   2 -
 xen/common/efi/runtime.c                     |   9 +-
 xen/include/xen/sched.h                      |   4 -
 24 files changed, 72 insertions(+), 489 deletions(-)
xen/arch/x86/cpu/common.c +0 -3
index 28d7f34c4dbe..9ea748f959af 100644
@@ -967,9 +967,6 @@ void cpu_init(void)
 	/* Install correct page table. */
 	write_ptbase(current);
 
-	/* Ensure FPU gets initialised for each domain. */
-	stts();
-
 	/* Reset debug registers: */
 	write_debugreg(0, 0);
 	write_debugreg(1, 0);
xen/arch/x86/domain.c +1 -9
index bda853e3c92b..742d69dd93bb 100644
@@ -1996,15 +1996,7 @@ static void __context_switch(void)
     if ( !is_idle_domain(nd) )
     {
         memcpy(stack_regs, &n->arch.user_regs, CTXT_SWITCH_STACK_BYTES);
-        if ( cpu_has_xsave )
-        {
-            if ( !set_xcr0(n->arch.xcr0 ?: XSTATE_FP_SSE) )
-                BUG();
-
-            if ( cpu_has_xsaves && is_hvm_vcpu(n) )
-                set_msr_xss(n->arch.msrs->xss.raw);
-        }
-        vcpu_restore_fpu_nonlazy(n, false);
+        vcpu_restore_fpu(n);
         nd->arch.ctxt_switch->to(n);
     }
 
xen/arch/x86/domctl.c +1 -3
index 9a72d57333e9..d838427feb52 100644
@@ -967,7 +967,6 @@ long arch_do_domctl(
 
                 v->arch.xcr0 = _xcr0;
                 v->arch.xcr0_accum = _xcr0_accum;
-                v->arch.nonlazy_xstate_used = _xcr0_accum & XSTATE_NONLAZY;
                 compress_xsave_states(v, _xsave_area,
                                       evc->size - PV_XSAVE_HDR_SIZE);
 
@@ -1347,8 +1346,7 @@ void arch_get_info_guest(struct vcpu *v, vcpu_guest_context_u c)
         c(flags = v->arch.pv.vgc_flags & ~(VGCF_i387_valid|VGCF_in_kernel));
     else
         c(flags = 0);
-    if ( v->fpu_initialised )
-        c(flags |= VGCF_i387_valid);
+    c(flags |= VGCF_i387_valid);
     if ( !(v->pause_flags & VPF_down) )
         c(flags |= VGCF_online);
     if ( !compat )
xen/arch/x86/hvm/emulate.c +4 -34
index ab1bc516839a..8a1720008454 100644
@@ -2361,9 +2361,7 @@ static int cf_check hvmemul_get_fpu(
 {
     struct vcpu *curr = current;
 
-    if ( !curr->fpu_dirtied )
-        alternative_vcall(hvm_funcs.fpu_dirty_intercept);
-    else if ( type == X86EMUL_FPU_fpu )
+    if ( type == X86EMUL_FPU_fpu )
     {
         const typeof(curr->arch.xsave_area->fpu_sse) *fpu_ctxt =
             curr->arch.fpu_ctxt;
@@ -2372,16 +2370,8 @@ static int cf_check hvmemul_get_fpu(
          * Latch current register state so that we can back out changes
          * if needed (namely when a memory write fails after register state
          * has already been updated).
-         * NB: We don't really need the "enable" part of the called function
-         * (->fpu_dirtied set implies CR0.TS clear), but the additional
-         * overhead should be low enough to not warrant introduction of yet
-         * another slightly different function. However, we need to undo the
-         * ->fpu_dirtied clearing the function does as well as the possible
-         * masking of all exceptions by FNSTENV.)
          */
-        save_fpu_enable();
-        curr->fpu_initialised = true;
-        curr->fpu_dirtied = true;
+        vcpu_save_fpu(curr);
         if ( (fpu_ctxt->fcw & 0x3f) != 0x3f )
         {
             uint16_t fcw;
@@ -2415,12 +2405,8 @@ static void cf_check hvmemul_put_fpu(
          * Latch current register state so that we can replace FIP/FDP/FOP
          * (which have values resulting from our own invocation of the FPU
          * instruction during emulation).
-         * NB: See also the comment in hvmemul_get_fpu(); we don't need to
-         * set ->fpu_dirtied here as it is going to be cleared below, and
-         * we also don't need to reload FCW as we're forcing full state to
-         * be reloaded anyway.
          */
-        save_fpu_enable();
+        vcpu_save_fpu(curr);
 
         if ( boot_cpu_has(X86_FEATURE_FDP_EXCP_ONLY) &&
              !(fpu_ctxt->fsw & ~fpu_ctxt->fcw & 0x003f) )
@@ -2465,23 +2451,7 @@ static void cf_check hvmemul_put_fpu(
     }
 
     if ( backout == X86EMUL_FPU_fpu )
-    {
-        /*
-         * To back out changes to the register file
-         * - in fully eager mode, restore original state immediately,
-         * - in lazy mode, simply adjust state such that upon next FPU insn
-         *   use by the guest we'll reload the state saved (or freshly loaded)
-         *   by hvmemul_get_fpu().
-         */
-        if ( curr->arch.fully_eager_fpu )
-            vcpu_restore_fpu_nonlazy(curr, false);
-        else
-        {
-            curr->fpu_dirtied = false;
-            stts();
-            alternative_vcall(hvm_funcs.fpu_leave, curr);
-        }
-    }
+        vcpu_restore_fpu(curr);
 }
 
 static int cf_check hvmemul_tlb_op(
xen/arch/x86/hvm/hvm.c +2 -6
index c75959588c0e..e532e2a2d6a0 100644
@@ -899,11 +899,8 @@ static int cf_check hvm_save_cpu_ctxt(struct vcpu *v, hvm_domain_context_t *h)
     ctxt.ldtr_base = seg.base;
     ctxt.ldtr_arbytes = seg.attr;
 
-    if ( v->fpu_initialised )
-    {
-        memcpy(ctxt.fpu_regs, v->arch.fpu_ctxt, sizeof(ctxt.fpu_regs));
-        ctxt.flags = XEN_X86_FPU_INITIALISED;
-    }
+    memcpy(ctxt.fpu_regs, v->arch.fpu_ctxt, sizeof(ctxt.fpu_regs));
+    ctxt.flags = XEN_X86_FPU_INITIALISED;
 
     return hvm_save_entry(CPU, v->vcpu_id, h, &ctxt);
 }
@@ -1342,7 +1339,6 @@ static int cf_check hvm_load_cpu_xsave_states(
 
     v->arch.xcr0 = ctxt->xcr0;
     v->arch.xcr0_accum = ctxt->xcr0_accum;
-    v->arch.nonlazy_xstate_used = ctxt->xcr0_accum & XSTATE_NONLAZY;
     compress_xsave_states(v, &ctxt->save_area,
                           size - offsetof(struct hvm_hw_cpu_xsave, save_area));
 
xen/arch/x86/hvm/svm/nestedsvm.c +1 -61

105 lines not on this page · raw message

xen/arch/x86/hvm/svm/svm.c +2 -79

133 lines not on this page · raw message

xen/arch/x86/hvm/svm/vmcb.c +1 -3
index 282fe7cdbe39..bf568d256f5e 100644
@@ -127,9 +127,7 @@ static int construct_vmcb(struct vcpu *v)
 
     paging_update_paging_modes(v);
 
-    vmcb->_exception_intercepts =
-        HVM_TRAP_MASK |
-        (v->arch.fully_eager_fpu ? 0 : (1U << X86_EXC_NM));
+    vmcb->_exception_intercepts = HVM_TRAP_MASK;
 
     if ( paging_mode_hap(v->domain) )
     {
xen/arch/x86/hvm/vlapic.c +0 -4
index dcbcf4a1feb5..2551260acd4d 100644
@@ -263,7 +263,6 @@ static void vlapic_init_sipi_one(struct vcpu *target, uint32_t icr)
     switch ( icr & APIC_DM_MASK )
     {
     case APIC_DM_INIT: {
-        bool fpu_initialised;
         int rc;
 
         /* No work on INIT de-assert for P4-type APIC. */
@@ -275,11 +274,8 @@ static void vlapic_init_sipi_one(struct vcpu *target, uint32_t icr)
             break;
         hvm_vcpu_down(target);
         domain_lock(target->domain);
-        /* Reset necessary VCPU state. This does not include FPU state. */
-        fpu_initialised = target->fpu_initialised;
         rc = vcpu_reset(target);
         ASSERT(!rc);
-        target->fpu_initialised = fpu_initialised;
         vlapic_do_init(vcpu_vlapic(target));
         domain_unlock(target->domain);
         break;
xen/arch/x86/hvm/vmx/vmcs.c +2 -6
index 6b4f004a3d21..25bee5e5c404 100644
@@ -1242,10 +1242,7 @@ static int construct_vmcs(struct vcpu *v)
     __vmwrite(HOST_TR_SELECTOR, TSS_SELECTOR);
 
     /* Host control registers. */
-    v->arch.hvm.vmx.host_cr0 = read_cr0() & ~X86_CR0_TS;
-    if ( !v->arch.fully_eager_fpu )
-        v->arch.hvm.vmx.host_cr0 |= X86_CR0_TS;
-    __vmwrite(HOST_CR0, v->arch.hvm.vmx.host_cr0);
+    __vmwrite(HOST_CR0, read_cr0());
     __vmwrite(HOST_CR4, mmu_cr4_features);
     if ( cpu_has_vmx_efer )
         __vmwrite(HOST_EFER, read_efer());
@@ -1325,8 +1322,7 @@ static int construct_vmcs(struct vcpu *v)
     __vmwrite(VMCS_LINK_POINTER, ~0UL);
 
     v->arch.hvm.vmx.exception_bitmap = HVM_TRAP_MASK
-              | (paging_mode_hap(d) ? 0 : (1U << X86_EXC_PF))
-              | (v->arch.fully_eager_fpu ? 0 : (1U << X86_EXC_NM));
+              | (paging_mode_hap(d) ? 0 : (1U << X86_EXC_PF));
 
     if ( cpu_has_vmx_notify_vm_exiting )
         __vmwrite(NOTIFY_WINDOW, vm_notify_window);
xen/arch/x86/hvm/vmx/vmx.c +1 -69

118 lines not on this page · raw message

xen/arch/x86/hvm/vmx/vvmx.c +2 -13
index ece0aa243a73..497592969dfc 100644
@@ -1236,9 +1236,6 @@ static void virtual_vmentry(struct cpu_user_regs *regs)
     regs->rsp = get_vvmcs(v, GUEST_RSP);
     regs->rflags = get_vvmcs(v, GUEST_RFLAGS);
 
-    /* updating host cr0 to sync TS bit */
-    __vmwrite(HOST_CR0, v->arch.hvm.vmx.host_cr0);
-
     /* Setup virtual ETP for L2 guest*/
     if ( nestedhvm_paging_mode_hap(v) )
         /* This will setup the initial np2m for the nested vCPU */
@@ -1466,9 +1463,6 @@ static void virtual_vmexit(struct cpu_user_regs *regs)
     /* VM exit clears all bits except bit 1 */
     regs->rflags = X86_EFLAGS_MBS;
 
-    /* updating host cr0 to sync TS bit */
-    __vmwrite(HOST_CR0, v->arch.hvm.vmx.host_cr0);
-
     if ( cpu_has_vmx_virtual_intr_delivery )
         nvmx_update_apicv(v);
 
@@ -2454,19 +2448,14 @@ int nvmx_n2_vmexit_handler(struct cpu_user_regs *regs,
         __vmread(VM_EXIT_INTR_INFO, &intr_info);
         vector = intr_info & INTR_INFO_VECTOR_MASK;
         /*
-         * decided by L0 and L1 exception bitmap, if the vetor is set by
-         * both, L0 has priority on #PF and #NM, L1 has priority on others
+         * decided by L0 and L1 exception bitmap, if the vector is set by
+         * both, L0 has priority on #PF, L1 has priority on others
          */
         if ( vector == X86_EXC_PF )
         {
             if ( paging_mode_hap(v->domain) )
                 nvcpu->nv_vmexit_pending = 1;
         }
-        else if ( vector == X86_EXC_NM )
-        {
-            if ( v->fpu_dirtied )
-                nvcpu->nv_vmexit_pending = 1;
-        }
         else if ( (intr_info & valid_mask) == valid_mask )
         {
             exec_bitmap = get_vvmcs(v, EXCEPTION_BITMAP);
xen/arch/x86/i387.c +35 -129

213 lines not on this page · raw message

xen/arch/x86/include/asm/domain.h +0 -3
index 622d22bef255..396e9998d04f 100644
@@ -654,9 +654,6 @@ struct arch_vcpu
      * it explicitly enables it via xcr0.
      */
     uint64_t xcr0_accum;
-    /* This variable determines whether nonlazy extended state has been used,
-     * and thus should be saved/restored. */
-    bool nonlazy_xstate_used;
 
     /* Restore all FPU state (lazy and non-lazy state) on context switch? */
     bool fully_eager_fpu;
xen/arch/x86/include/asm/hvm/svm/nestedsvm.h +0 -3
index 406fc082b107..2f84546d6b3d 100644
@@ -40,9 +40,6 @@ struct nestedsvm {
     /* Shadow io permission map */
     unsigned long *ns_iomap;
 
-    uint64_t ns_cr0; /* Cached guest_cr[0] of l1 guest while l2 guest runs.
-                      * Needed to handle FPU context switching */
-
     /* Cache guest cr3/host cr3 the guest sets up for the l2 guest.
      * Used by Shadow-on-Shadow and Nested-on-Nested.
      * ns_vmcb_guestcr3: in l2 guest physical address space and points to
xen/arch/x86/include/asm/hvm/vmx/vmcs.h +0 -2
index a7dd2eeffcad..d84195c0426f 100644
@@ -141,8 +141,6 @@ struct vmx_vcpu {
     DECLARE_BITMAP(eoi_exit_bitmap, X86_NR_VECTORS);
     struct pi_desc       pi_desc;
 
-    unsigned long        host_cr0;
-
     /* Do we need to tolerate a spurious EPT_MISCONFIG VM exit? */
     bool                 ept_spurious_misconfig;
 
xen/arch/x86/include/asm/i387.h +1 -2
index a783549db991..bba5dfe3951a 100644
@@ -27,8 +27,7 @@ struct ix87_env {
     uint16_t fds, _res6;
 };
 
-void vcpu_restore_fpu_nonlazy(struct vcpu *v, bool need_stts);
-void vcpu_restore_fpu_lazy(struct vcpu *v);
+void vcpu_restore_fpu(struct vcpu *v);
 void vcpu_save_fpu(struct vcpu *v);
 void save_fpu_enable(void);
 
xen/arch/x86/include/asm/xstate.h +2 -15
index bd767d9cd714..eed40c94efea 100644
@@ -32,11 +32,10 @@ extern uint32_t mxcsr_mask;
 #define XSTATE_FP_SSE  (X86_XCR0_FP | X86_XCR0_SSE)
 #define XCNTXT_MASK    (X86_XCR0_FP | X86_XCR0_SSE | X86_XCR0_YMM | \
                         X86_XCR0_OPMASK | X86_XCR0_ZMM | X86_XCR0_HI_ZMM | \
-                        XSTATE_NONLAZY)
+                        X86_XCR0_LWP | X86_XCR0_BNDREGS | X86_XCR0_BNDCSR | \
+                        X86_XCR0_PKRU)
 
 #define XSTATE_ALL     (~(1ULL << 63))
-#define XSTATE_NONLAZY (X86_XCR0_BNDREGS | X86_XCR0_BNDCSR | X86_XCR0_PKRU)
-#define XSTATE_LAZY    (XSTATE_ALL & ~XSTATE_NONLAZY)
 #define XSTATE_XSAVES_ONLY         0
 #define XSTATE_COMPACTION_ENABLED  (1ULL << 63)
 
@@ -121,18 +120,6 @@ static inline uint64_t xgetbv(unsigned int index)
     return lo | ((uint64_t)hi << 32);
 }
 
-static inline bool xstate_all(const struct vcpu *v)
-{
-    /*
-     * XSTATE_FP_SSE may be excluded, because the offsets of XSTATE_FP_SSE
-     * (in the legacy region of xsave area) are fixed, so saving
-     * XSTATE_FP_SSE will not cause overwriting problem with XSAVES/XSAVEC.
-     */
-    return (v->arch.xsave_area->xsave_hdr.xcomp_bv &
-            XSTATE_COMPACTION_ENABLED) &&
-           (v->arch.xcr0_accum & XSTATE_LAZY & ~XSTATE_FP_SSE);
-}
-
 static inline bool __nonnull(1)
 xsave_area_compressed(const struct xsave_struct *xsave_area)
 {
xen/arch/x86/pv/misc-hypercalls.c +1 -2
index b529f00ea127..dd783e34b117 100644
@@ -40,8 +40,7 @@ long do_fpu_taskswitch(int set)
     else
     {
         v->arch.pv.ctrlreg[0] &= ~X86_CR0_TS;
-        if ( v->fpu_dirtied )
-            clts();
+        clts();
     }
 
     return 0;
xen/arch/x86/traps.c +10 -8
index d554c9d41edd..448a4073f589 100644
@@ -1891,15 +1891,17 @@ void asmlinkage do_device_not_available(struct cpu_user_regs *regs)
     }
 
 #ifdef CONFIG_PV
-    vcpu_restore_fpu_lazy(curr);
+    BUG_ON(!(curr->arch.pv.ctrlreg[0] & X86_CR0_TS));
 
-    if ( curr->arch.pv.ctrlreg[0] & X86_CR0_TS )
-    {
-        pv_inject_hw_exception(X86_EXC_NM, X86_EVENT_NO_EC);
-        curr->arch.pv.ctrlreg[0] &= ~X86_CR0_TS;
-    }
-    else
-        TRACE_0D(TRC_PV_MATH_STATE_RESTORE);
+    /*
+     * PV ABI QUIRK: Classic Xen kernels (2.6.18 and SLES 11 SP4's
+     * 3.0) rely on Xen to clear TS. PVOPS kernels (3.0, 3.16 and 4.15
+     * are checked) always clear TS themselves.
+     */
+    clts();
+
+    pv_inject_hw_exception(X86_EXC_NM, X86_EVENT_NO_EC);
+    curr->arch.pv.ctrlreg[0] &= ~X86_CR0_TS;
 #else
     ASSERT_UNREACHABLE();
 #endif
xen/arch/x86/xstate.c +0 -26
index 92a65bd8d52c..19de2d570220 100644
@@ -731,7 +731,6 @@ int handle_xsetbv(u32 index, u64 new_bv)
 {
     struct vcpu *curr = current;
     uint64_t xcr0_max = cpu_policy_xcr0_max(curr->domain->arch.cpuid);
-    u64 mask;
 
     if ( index != XCR_XFEATURE_ENABLED_MASK )
         return -EOPNOTSUPP;
@@ -766,34 +765,9 @@ int handle_xsetbv(u32 index, u64 new_bv)
         return -EFAULT;
     }
 
-    mask = new_bv & ~curr->arch.xcr0_accum;
     curr->arch.xcr0 = new_bv;
     curr->arch.xcr0_accum |= new_bv;
 
-    if ( new_bv & XSTATE_NONLAZY )
-        curr->arch.nonlazy_xstate_used = 1;
-
-    mask &= curr->fpu_dirtied ? ~XSTATE_FP_SSE : XSTATE_NONLAZY;
-    if ( mask )
-    {
-        unsigned long cr0 = read_cr0();
-
-        clts();
-        if ( curr->fpu_dirtied )
-            asm ( "stmxcsr %0" : "=m" (curr->arch.xsave_area->fpu_sse.mxcsr) );
-        else if ( xstate_all(curr) )
-        {
-            /* See the comment in i387.c:vcpu_restore_fpu_eager(). */
-            mask |= XSTATE_LAZY;
-            curr->fpu_initialised = 1;
-            curr->fpu_dirtied = 1;
-            cr0 &= ~X86_CR0_TS;
-        }
-        xrstor(curr, mask);
-        if ( cr0 & X86_CR0_TS )
-            write_cr0(cr0);
-    }
-
     return 0;
 }
 
xen/common/domain.c +0 -2
index f6f557499660..450a7cf1814a 100644
@@ -1488,8 +1488,6 @@ int vcpu_reset(struct vcpu *v)
     clear_bit(v->vcpu_id, d->poll_mask);
     v->poll_evtchn = 0;
 
-    v->fpu_initialised = 0;
-    v->fpu_dirtied     = 0;
     v->is_initialised  = 0;
     if ( v->affinity_broken & VCPU_AFFINITY_OVERRIDE )
         vcpu_temporary_affinity(v, NR_CPUS, VCPU_AFFINITY_OVERRIDE);
xen/common/efi/runtime.c +6 -3
index d952c3ba785e..273c03d676f8 100644
@@ -85,12 +85,14 @@ struct efi_rs_state efi_rs_enter(void)
     static const u16 fcw = FCW_DEFAULT;
     static const u32 mxcsr = MXCSR_DEFAULT;
     struct efi_rs_state state = { .cr3 = 0 };
+    struct vcpu *curr = current;
 
     if ( mfn_eq(efi_l4_mfn, INVALID_MFN) )
         return state;
 
     state.cr3 = read_cr3();
-    save_fpu_enable();
+    if ( !is_idle_vcpu(curr) )
+        vcpu_save_fpu(curr);
     asm volatile ( "fnclex; fldcw %0" :: "m" (fcw) );
     asm volatile ( "ldmxcsr %0" :: "m" (mxcsr) );
 
@@ -101,7 +103,7 @@ struct efi_rs_state efi_rs_enter(void)
     /* prevent fixup_page_fault() from doing anything */
     irq_enter();
 
-    if ( is_pv_vcpu(current) && !is_idle_vcpu(current) )
+    if ( is_pv_vcpu(curr) && !is_idle_vcpu(curr) )
     {
         struct desc_ptr gdt_desc = {
             .limit = LAST_RESERVED_GDT_BYTE,
@@ -153,7 +155,8 @@ void efi_rs_leave(struct efi_rs_state *state)
     irq_exit();
     efi_rs_on_cpu = NR_CPUS;
     spin_unlock(&efi_rs_lock);
-    vcpu_restore_fpu_nonlazy(curr, true);
+    if ( !is_idle_vcpu(curr) )
+        vcpu_restore_fpu(curr);
 }
 
 bool efi_rs_using_pgtables(void)
xen/include/xen/sched.h +0 -4
index 37f5922f3206..1da52e77dcdf 100644
@@ -206,10 +206,6 @@ struct vcpu
     struct guest_area runstate_guest_area;
     unsigned int     new_state;
 
-    /* Has the FPU been initialised? */
-    bool             fpu_initialised;
-    /* Has the FPU been used since it was last saved? */
-    bool             fpu_dirtied;
     /* Initialization completed for this VCPU? */
     bool             is_initialised;
     /* Currently running on a CPU? */
Signature · 1 line
2.42.0
#6 lore raw

Re: [PATCH 3/3] x86: switch to eager fpu save / restore

Quoted 6 lines · Fouad Hilly

From: Wei Liu <[email protected]>

Previously FPU is lazily switched. Due to the fact that a malicious guest can speculatively read the not yet switched out register states, we need to eagerly switch FPU states when a domain is scheduled to run.

The speculation aspect is already covered as of XSA-267, and hence imo cannot be used as a justification here.

Quoted 23 lines

In the new world, Xen will eagerly switch FPU context in the scheduler. Xen itself won't set CR0.TS other than for the purpose of servicing a PV guest.

The following things are done:

1. Xen will only set and clear CR0.TS on behalf of a PV guest. Any #NM received in Xen should only be delivered to the running PV guest.

2. Xen no longer causes vmexit for #NM for HVM guests when nested HVM is not in use.

3. When nested HVM is in use, Xen needs to trap #NM if specified by the L1 hypervisor, but all #NM handling is left to L1 hypervisor to deal with.

4. Xen saves and restores FPU states wherever it needs to. The following places are modified:
1. Scheduling in and out a guest;
2. Calling EFI runtime service;
3. ACPI reset;
4. x86 insn emulator fpu insn emulation.

Quoted 6 lines

5. Treat FPU as always initialised. Adjust following components:
1. HVM vcpu context save / load code;
2. arch_{get,set}_info_guest;
3. VLAPIC code.

6. Delete lazy FPU handling code.

This wants splitting up. I'm actually puzzled that step 6 does not include purging of e.g. opt_eager_fpu. Converting that to "always true" would seem to be the one first step with a functional change. All further steps would be removal of then-dead code.

Quoted 5 lines

Strip XCR0 and IA32_XSS manipulation from __context_switch. We need to be able to zero out previously used state components. Push everything into fpu_xrstor as that's the most suitable place.

Tested on AMD with PKU disabled and Intel, no performance degradation.

I dare to at least question whether this is going to hold once we support one of the huge state components (AMX patches have been pending for years).

Jan

#7 lore raw
In reply to Fouad Hilly
Quoted 7 lines · Fouad Hilly

X86 Xen will only eagerly switch FPU context in the scheduler. Xen itslef won't set CR0.TS other than for the purpose of servicing a PV guset.

Throughout replying to the series I got back "undeliverable" responses for Wei's old address at Citrix (noticed only now when I looked at what has accumulated again in my inbox in the meantime). Can you please avoid having dead addresses in patch submissions?

Jan