Skip to contentSkip to conversation

x86: adventures in Address Space Isolation

PATCH Superseded Roger Pau Monne 4 participants 64 messages Jul 26, 2024 – Sep 27, 2024

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover x86: adventures in Address Space Isolation

Hello,

The aim of this series is to introduce the functionality required to create linear mappings visible to a single pCPU.

Doing so requires having a per-CPU root page-table (L4), and hence requires changes to the HVM monitor tables and shadowing the guest selected L4 on PV guests. As follow ups (and partially to ensure the per-CPU mappings work fine) the CPU stacks are switched to use per-CPU mappings, so that remote stack contents are not by default mapped on all page-tables (note: for this to be true the directmap entries for the stack pages would need to be removed also).

Patches before patch 12 are either small fixes or preparatory non-functional changes in order to accommodate the rest of the series.

Patch 12 introduces a new 'asi' spec-ctrl option, that's used to enable Address Space Isolation.

Patches 13-15 and 20 introduce logic to use per-CPU L4 on HVM and PV guests.

Patches 16-18 add support for creating per-CPU mappings to the existing page-table management functions, map_pages_to_xen() and related functions. Patch 19 introduce helpers for creating per-CPU mappings using a fixmap interface.

Finally patches 21-22 add support for mapping the CPU stack in a per-CPU fixmap region, and zeroing the stacks on guest context switch.

I've been testing the patches quite a lot using XenRT, and so far they seem to not cause regressions (either with spec-ctrl=asi or without it), but XenRT no longer tests shadow paging or 32bit PV guests.

This proposal is also missing an interface similar to map_domain_page() in order to create per-CPU mappings that don't use a fixmap entry. I thought however that the current content was fair enough for a first posting, and that I would like to get feedback on this before building further functionality on top of it.

Note that none of the logic introduced in the series removes entries for the directmap, so evne when creating the per-CPU mappings the underlying physical addresses are fully accessible when using it's linear direct map entries.

I also haven't done any benchmarking. Doesn't seem to cripple performance up to the point that XenRT jobs would timeout before finishing, that the only objective reference I can provide at the moment.

It's likely to still have some rough edges, handle with care.

Thanks, Roger.

Roger Pau Monne (22):
x86/mm: drop l{1,2,3,4}e_write_atomic()
x86/mm: rename l{1,2,3,4}e_read_atomic()
x86/dom0: only disable SMAP for the PV dom0 build
x86/mm: ensure L4 idle_pg_table is not modified past boot x86/mm: make virt_to_xen_l1e() static
x86/mm: introduce a local domain variable to write_ptbase() x86/spec-ctrl: initialize per-domain XPTI in spec_ctrl_init_domain() x86/mm: avoid passing a domain parameter to L4 init function x86/pv: untie issuing FLUSH_ROOT_PGTBL from XPTI
x86/mm: move FLUSH_ROOT_PGTBL handling before TLB flush x86/mm: split setup of the per-domain slot on context switch x86/spec-ctrl: introduce Address Space Isolation command line option x86/hvm: use a per-pCPU monitor table in HAP mode x86/hvm: use a per-pCPU monitor table in shadow mode x86/idle: allow using a per-pCPU L4
x86/mm: introduce a per-CPU L3 table for the per-domain slot x86/mm: introduce support to populate a per-CPU page-table region x86/mm: allow modifying per-CPU entries of remote page-tables x86/mm: introduce a per-CPU fixmap area
x86/pv: allow using a unique per-pCPU root page table (L4) x86/mm: switch to a per-CPU mapped stack when using ASI x86/mm: zero stack on stack switch or reset

 docs/misc/xen-command-line.pandoc      |  15 +-
 xen/arch/x86/boot/x86_64.S             |  11 +
 xen/arch/x86/domain.c                  |  75 +++-
 xen/arch/x86/domain_page.c             |   2 +-
 xen/arch/x86/flushtlb.c                |  18 +-
 xen/arch/x86/hvm/hvm.c                 |  67 ++++
 xen/arch/x86/hvm/svm/svm.c             |   5 +
 xen/arch/x86/hvm/vmx/vmcs.c            |   1 +
 xen/arch/x86/hvm/vmx/vmx.c             |   4 +
 xen/arch/x86/include/asm/config.h      |   4 +
 xen/arch/x86/include/asm/current.h     |  38 +-
 xen/arch/x86/include/asm/domain.h      |   7 +
 xen/arch/x86/include/asm/fixmap.h      |  50 +++
 xen/arch/x86/include/asm/flushtlb.h    |   3 +-
 xen/arch/x86/include/asm/hap.h         |   1 -
 xen/arch/x86/include/asm/hvm/hvm.h     |   8 +
 xen/arch/x86/include/asm/hvm/vcpu.h    |   6 +-
 xen/arch/x86/include/asm/mm.h          |  34 +-
 xen/arch/x86/include/asm/page.h        |  37 +-
 xen/arch/x86/include/asm/paging.h      |  18 +
 xen/arch/x86/include/asm/pv/mm.h       |   8 +
 xen/arch/x86/include/asm/setup.h       |   1 +
 xen/arch/x86/include/asm/smp.h         |  12 +
 xen/arch/x86/include/asm/spec_ctrl.h   |   2 +
 xen/arch/x86/include/asm/x86_64/page.h |   4 -
 xen/arch/x86/mm.c                      | 484 ++++++++++++++++++++-----
 xen/arch/x86/mm/hap/hap.c              |  74 ----
 xen/arch/x86/mm/paging.c               |   4 +-
 xen/arch/x86/mm/shadow/common.c        |  42 +--
 xen/arch/x86/mm/shadow/hvm.c           |  64 ++--
 xen/arch/x86/mm/shadow/multi.c         |  73 ++--
 xen/arch/x86/mm/shadow/private.h       |   4 +-
 xen/arch/x86/pv/dom0_build.c           |  16 +-
 xen/arch/x86/pv/domain.c               |  28 +-
 xen/arch/x86/pv/mm.c                   |  52 +++
 xen/arch/x86/setup.c                   |  55 +--
 xen/arch/x86/smp.c                     |  29 ++
 xen/arch/x86/smpboot.c                 |  78 +++-
 xen/arch/x86/spec_ctrl.c               |  78 +++-
 xen/arch/x86/traps.c                   |  14 +-
 xen/common/efi/runtime.c               |  12 +
 xen/common/smp.c                       |  10 +
 xen/include/xen/smp.h                  |   5 +
 43 files changed, 1198 insertions(+), 355 deletions(-)
Signature · 1 line
2.45.2
#1 lore raw

PATCH 1/22 x86/mm: drop l{1,2,3,4}e_write_atomic()

The l{1,2,3,4}e_write_atomic() and non _atomic suffixed helpers share the same implementation, so it seems pointless and possibly confusing to have both.

Remove the l{1,2,3,4}e_write_atomic() helpers and switch it's user to l{1,2,3,4}e_write(), as that's also atomic. While there also remove pte_write{,_atomic}() and just use write_atomic() in the wrappers.

No functional change intended.

---
 xen/arch/x86/include/asm/page.h        | 21 +++-----------
 xen/arch/x86/include/asm/x86_64/page.h |  2 --
 xen/arch/x86/mm.c                      | 39 +++++++++++---------------
 3 files changed, 20 insertions(+), 42 deletions(-)
xen/arch/x86/include/asm/page.h +4 -17
index 350d1fb1100f..3d20ee507a33 100644
@@ -26,27 +26,14 @@
     l4e_from_intpte(pte_read_atomic(&l4e_get_intpte(*(l4ep))))
 
 /* Write a pte atomically to memory. */
-#define l1e_write_atomic(l1ep, l1e) \
-    pte_write_atomic(&l1e_get_intpte(*(l1ep)), l1e_get_intpte(l1e))
-#define l2e_write_atomic(l2ep, l2e) \
-    pte_write_atomic(&l2e_get_intpte(*(l2ep)), l2e_get_intpte(l2e))
-#define l3e_write_atomic(l3ep, l3e) \
-    pte_write_atomic(&l3e_get_intpte(*(l3ep)), l3e_get_intpte(l3e))
-#define l4e_write_atomic(l4ep, l4e) \
-    pte_write_atomic(&l4e_get_intpte(*(l4ep)), l4e_get_intpte(l4e))
-
-/*
- * Write a pte safely but non-atomically to memory.
- * The PTE may become temporarily not-present during the update.
- */
 #define l1e_write(l1ep, l1e) \
-    pte_write(&l1e_get_intpte(*(l1ep)), l1e_get_intpte(l1e))
+    write_atomic(&l1e_get_intpte(*(l1ep)), l1e_get_intpte(l1e))
 #define l2e_write(l2ep, l2e) \
-    pte_write(&l2e_get_intpte(*(l2ep)), l2e_get_intpte(l2e))
+    write_atomic(&l2e_get_intpte(*(l2ep)), l2e_get_intpte(l2e))
 #define l3e_write(l3ep, l3e) \
-    pte_write(&l3e_get_intpte(*(l3ep)), l3e_get_intpte(l3e))
+    write_atomic(&l3e_get_intpte(*(l3ep)), l3e_get_intpte(l3e))
 #define l4e_write(l4ep, l4e) \
-    pte_write(&l4e_get_intpte(*(l4ep)), l4e_get_intpte(l4e))
+    write_atomic(&l4e_get_intpte(*(l4ep)), l4e_get_intpte(l4e))
 
 /* Get direct integer representation of a pte's contents (intpte_t). */
 #define l1e_get_intpte(x)          ((x).l1)
xen/arch/x86/include/asm/x86_64/page.h +0 -2
index 19ca64d79223..03fcce61c052 100644
@@ -70,8 +70,6 @@ typedef l4_pgentry_t root_pgentry_t;
 #endif /* !__ASSEMBLY__ */
 
 #define pte_read_atomic(ptep)       read_atomic(ptep)
-#define pte_write_atomic(ptep, pte) write_atomic(ptep, pte)
-#define pte_write(ptep, pte)        write_atomic(ptep, pte)
 
 /* Given a virtual address, get an entry offset into a linear page table. */
 #define l1_linear_offset(_a) (((_a) & VADDR_MASK) >> L1_PAGETABLE_SHIFT)
xen/arch/x86/mm.c +16 -23
index 95795567f2a5..fab2de5fae27 100644
@@ -5253,7 +5253,7 @@ int map_pages_to_xen(
              !(flags & (_PAGE_PAT | MAP_SMALL_PAGES)) )
         {
             /* 1GB-page mapping. */
-            l3e_write_atomic(pl3e, l3e_from_mfn(mfn, l1f_to_lNf(flags)));
+            l3e_write(pl3e, l3e_from_mfn(mfn, l1f_to_lNf(flags)));
 
             if ( (l3e_get_flags(ol3e) & _PAGE_PRESENT) )
             {
@@ -5353,8 +5353,7 @@ int map_pages_to_xen(
             if ( (l3e_get_flags(*pl3e) & _PAGE_PRESENT) &&
                  (l3e_get_flags(*pl3e) & _PAGE_PSE) )
             {
-                l3e_write_atomic(pl3e,
-                                 l3e_from_mfn(l2mfn, __PAGE_HYPERVISOR));
+                l3e_write(pl3e, l3e_from_mfn(l2mfn, __PAGE_HYPERVISOR));
                 l2mfn = INVALID_MFN;
             }
             if ( locking )
@@ -5375,7 +5374,7 @@ int map_pages_to_xen(
         {
             /* Super-page mapping. */
             ol2e = *pl2e;
-            l2e_write_atomic(pl2e, l2e_from_mfn(mfn, l1f_to_lNf(flags)));
+            l2e_write(pl2e, l2e_from_mfn(mfn, l1f_to_lNf(flags)));
 
             if ( (l2e_get_flags(ol2e) & _PAGE_PRESENT) )
             {
@@ -5457,8 +5456,7 @@ int map_pages_to_xen(
                 if ( (l2e_get_flags(*pl2e) & _PAGE_PRESENT) &&
                      (l2e_get_flags(*pl2e) & _PAGE_PSE) )
                 {
-                    l2e_write_atomic(pl2e, l2e_from_mfn(l1mfn,
-                                                        __PAGE_HYPERVISOR));
+                    l2e_write(pl2e, l2e_from_mfn(l1mfn, __PAGE_HYPERVISOR));
                     l1mfn = INVALID_MFN;
                 }
                 if ( locking )
@@ -5471,7 +5469,7 @@ int map_pages_to_xen(
             if ( !pl1e )
                 pl1e = map_l1t_from_l2e(*pl2e) + l1_table_offset(virt);
             ol1e  = *pl1e;
-            l1e_write_atomic(pl1e, l1e_from_mfn(mfn, flags));
+            l1e_write(pl1e, l1e_from_mfn(mfn, flags));
             UNMAP_DOMAIN_PAGE(pl1e);
             if ( (l1e_get_flags(ol1e) & _PAGE_PRESENT) )
             {
@@ -5524,8 +5522,7 @@ int map_pages_to_xen(
                 UNMAP_DOMAIN_PAGE(l1t);
                 if ( i == L1_PAGETABLE_ENTRIES )
                 {
-                    l2e_write_atomic(pl2e, l2e_from_pfn(base_mfn,
-                                                        l1f_to_lNf(flags)));
+                    l2e_write(pl2e, l2e_from_pfn(base_mfn, l1f_to_lNf(flags)));
                     if ( locking )
                         spin_unlock(&map_pgdir_lock);
                     flush_area(virt - PAGE_SIZE,
@@ -5574,8 +5571,7 @@ int map_pages_to_xen(
             UNMAP_DOMAIN_PAGE(l2t);
             if ( i == L2_PAGETABLE_ENTRIES )
             {
-                l3e_write_atomic(pl3e, l3e_from_pfn(base_mfn,
-                                                    l1f_to_lNf(flags)));
+                l3e_write(pl3e, l3e_from_pfn(base_mfn, l1f_to_lNf(flags)));
                 if ( locking )
                     spin_unlock(&map_pgdir_lock);
                 flush_area(virt - PAGE_SIZE,
@@ -5674,7 +5670,7 @@ int modify_xen_mappings(unsigned long s, unsigned long e, unsigned int nf)
                     : l3e_from_pfn(l3e_get_pfn(*pl3e),
                                    (l3e_get_flags(*pl3e) & ~FLAGS_MASK) | nf);
 
-                l3e_write_atomic(pl3e, nl3e);
+                l3e_write(pl3e, nl3e);
                 v += 1UL << L3_PAGETABLE_SHIFT;
                 continue;
             }
@@ -5696,8 +5692,7 @@ int modify_xen_mappings(unsigned long s, unsigned long e, unsigned int nf)
             if ( (l3e_get_flags(*pl3e) & _PAGE_PRESENT) &&
                  (l3e_get_flags(*pl3e) & _PAGE_PSE) )
             {
-                l3e_write_atomic(pl3e,
-                                 l3e_from_mfn(l2mfn, __PAGE_HYPERVISOR));
+                l3e_write(pl3e, l3e_from_mfn(l2mfn, __PAGE_HYPERVISOR));
                 l2mfn = INVALID_MFN;
             }
             if ( locking )
@@ -5732,7 +5727,7 @@ int modify_xen_mappings(unsigned long s, unsigned long e, unsigned int nf)
                     : l2e_from_pfn(l2e_get_pfn(*pl2e),
                                    (l2e_get_flags(*pl2e) & ~FLAGS_MASK) | nf);
 
-                l2e_write_atomic(pl2e, nl2e);
+                l2e_write(pl2e, nl2e);
                 v += 1UL << L2_PAGETABLE_SHIFT;
             }
             else
@@ -5755,8 +5750,7 @@ int modify_xen_mappings(unsigned long s, unsigned long e, unsigned int nf)
                 if ( (l2e_get_flags(*pl2e) & _PAGE_PRESENT) &&
                      (l2e_get_flags(*pl2e) & _PAGE_PSE) )
                 {
-                    l2e_write_atomic(pl2e, l2e_from_mfn(l1mfn,
-                                                        __PAGE_HYPERVISOR));
+                    l2e_write(pl2e, l2e_from_mfn(l1mfn, __PAGE_HYPERVISOR));
                     l1mfn = INVALID_MFN;
                 }
                 if ( locking )
@@ -5785,7 +5779,7 @@ int modify_xen_mappings(unsigned long s, unsigned long e, unsigned int nf)
                 : l1e_from_pfn(l1e_get_pfn(*pl1e),
                                (l1e_get_flags(*pl1e) & ~FLAGS_MASK) | nf);
 
-            l1e_write_atomic(pl1e, nl1e);
+            l1e_write(pl1e, nl1e);
             UNMAP_DOMAIN_PAGE(pl1e);
             v += PAGE_SIZE;
 
@@ -5824,7 +5818,7 @@ int modify_xen_mappings(unsigned long s, unsigned long e, unsigned int nf)
             if ( i == L1_PAGETABLE_ENTRIES )
             {
                 /* Empty: zap the L2E and free the L1 page. */
-                l2e_write_atomic(pl2e, l2e_empty());
+                l2e_write(pl2e, l2e_empty());
                 if ( locking )
                     spin_unlock(&map_pgdir_lock);
                 flush_area(NULL, FLUSH_TLB_GLOBAL); /* flush before free */
@@ -5868,7 +5862,7 @@ int modify_xen_mappings(unsigned long s, unsigned long e, unsigned int nf)
             if ( i == L2_PAGETABLE_ENTRIES )
             {
                 /* Empty: zap the L3E and free the L2 page. */
-                l3e_write_atomic(pl3e, l3e_empty());
+                l3e_write(pl3e, l3e_empty());
                 if ( locking )
                     spin_unlock(&map_pgdir_lock);
                 flush_area(NULL, FLUSH_TLB_GLOBAL); /* flush before free */
@@ -5940,7 +5934,7 @@ void init_or_livepatch modify_xen_mappings_lite(
         {
             ASSERT(IS_ALIGNED(v, 1UL << L2_PAGETABLE_SHIFT));
 
-            l2e_write_atomic(pl2e, l2e_from_intpte((l2e.l2 & ~fm) | flags));
+            l2e_write(pl2e, l2e_from_intpte((l2e.l2 & ~fm) | flags));
 
             v += 1UL << L2_PAGETABLE_SHIFT;
             continue;
@@ -5958,8 +5952,7 @@ void init_or_livepatch modify_xen_mappings_lite(
 
                 ASSERT(l1f & _PAGE_PRESENT);
 
-                l1e_write_atomic(pl1e,
-                                 l1e_from_intpte((l1e.l1 & ~fm) | flags));
+                l1e_write(pl1e, l1e_from_intpte((l1e.l1 & ~fm) | flags));
 
                 v += 1UL << L1_PAGETABLE_SHIFT;
 
Signature · 1 line
2.45.2
Reviewed-by on v1 1/22
#2 lore raw

Re: [PATCH 01/22] x86/mm: drop l{1,2,3,4}e_write_atomic()

Quoted 10 lines · Roger Pau Monne

The l{1,2,3,4}e_write_atomic() and non _atomic suffixed helpers share the same implementation, so it seems pointless and possibly confusing to have both.

Remove the l{1,2,3,4}e_write_atomic() helpers and switch it's user to l{1,2,3,4}e_write(), as that's also atomic. While there also remove pte_write{,_atomic}() and just use write_atomic() in the wrappers.

No functional change intended.

In the description, can we perhaps mention the historical aspect of why these were there (and separate)? Happy to add a sentence when committing, as long as you agree.

Jan

#3 lore raw

Re: [PATCH 01/22] x86/mm: drop l{1,2,3,4}e_write_atomic()

Quoted 10 lines · Jan Beulich
Quoted 9 lines · Roger Pau Monne

The l{1,2,3,4}e_write_atomic() and non _atomic suffixed helpers share the same implementation, so it seems pointless and possibly confusing to have both.

Remove the l{1,2,3,4}e_write_atomic() helpers and switch it's user to l{1,2,3,4}e_write(), as that's also atomic. While there also remove pte_write{,_atomic}() and just use write_atomic() in the wrappers.

No functional change intended.

Quoted 7 lines
Quoted 1 line

In the description, can we perhaps mention the historical aspect of why these were there (and separate)? Happy to add a sentence when committing, as long as you agree.

Sure:

"x86 32bit mode used to have a non-atomic PTE write that would split the write in two halves, but with Xen only supporting x86 64bit that's no longer present."

Would be fine? Possibly added after the first paragraph IMO.

Thanks, Roger.

#4 lore raw

PATCH 2/22 x86/mm: rename l{1,2,3,4}e_read_atomic()

In reply to Roger Pau Monne

There's no l{1,2,3,4}e_read() implementation, so drop the _atomic suffix from the read helpers. This allows unifying the naming with the write helpers, which are also atomic but don't have the suffix already: l{1,2,3,4}e_write().

No functional change intended.

---
 xen/arch/x86/include/asm/page.h        | 16 ++++++++--------
 xen/arch/x86/include/asm/x86_64/page.h |  2 --
 xen/arch/x86/mm.c                      | 12 ++++++------
 xen/arch/x86/traps.c                   |  8 ++++----
 4 files changed, 18 insertions(+), 20 deletions(-)
xen/arch/x86/include/asm/page.h +8 -8
index 3d20ee507a33..e48571de9332 100644
@@ -16,14 +16,14 @@
 #include <asm/x86_64/page.h>
 
 /* Read a pte atomically from memory. */
-#define l1e_read_atomic(l1ep) \
-    l1e_from_intpte(pte_read_atomic(&l1e_get_intpte(*(l1ep))))
-#define l2e_read_atomic(l2ep) \
-    l2e_from_intpte(pte_read_atomic(&l2e_get_intpte(*(l2ep))))
-#define l3e_read_atomic(l3ep) \
-    l3e_from_intpte(pte_read_atomic(&l3e_get_intpte(*(l3ep))))
-#define l4e_read_atomic(l4ep) \
-    l4e_from_intpte(pte_read_atomic(&l4e_get_intpte(*(l4ep))))
+#define l1e_read(l1ep) \
+    l1e_from_intpte(read_atomic(&l1e_get_intpte(*(l1ep))))
+#define l2e_read(l2ep) \
+    l2e_from_intpte(read_atomic(&l2e_get_intpte(*(l2ep))))
+#define l3e_read(l3ep) \
+    l3e_from_intpte(read_atomic(&l3e_get_intpte(*(l3ep))))
+#define l4e_read(l4ep) \
+    l4e_from_intpte(read_atomic(&l4e_get_intpte(*(l4ep))))
 
 /* Write a pte atomically to memory. */
 #define l1e_write(l1ep, l1e) \
xen/arch/x86/include/asm/x86_64/page.h +0 -2
index 03fcce61c052..465a70731214 100644
@@ -69,8 +69,6 @@ typedef l4_pgentry_t root_pgentry_t;
 
 #endif /* !__ASSEMBLY__ */
 
-#define pte_read_atomic(ptep)       read_atomic(ptep)
-
 /* Given a virtual address, get an entry offset into a linear page table. */
 #define l1_linear_offset(_a) (((_a) & VADDR_MASK) >> L1_PAGETABLE_SHIFT)
 #define l2_linear_offset(_a) (((_a) & VADDR_MASK) >> L2_PAGETABLE_SHIFT)
xen/arch/x86/mm.c +6 -6
index fab2de5fae27..6ffacab341ad 100644
@@ -2147,7 +2147,7 @@ static int mod_l1_entry(l1_pgentry_t *pl1e, l1_pgentry_t nl1e,
                         struct vcpu *pt_vcpu, struct domain *pg_dom)
 {
     bool preserve_ad = (cmd == MMU_PT_UPDATE_PRESERVE_AD);
-    l1_pgentry_t ol1e = l1e_read_atomic(pl1e);
+    l1_pgentry_t ol1e = l1e_read(pl1e);
     struct domain *pt_dom = pt_vcpu->domain;
     int rc = 0;
 
@@ -2270,7 +2270,7 @@ static int mod_l2_entry(l2_pgentry_t *pl2e,
         return -EPERM;
     }
 
-    ol2e = l2e_read_atomic(pl2e);
+    ol2e = l2e_read(pl2e);
 
     if ( l2e_get_flags(nl2e) & _PAGE_PRESENT )
     {
@@ -2332,7 +2332,7 @@ static int mod_l3_entry(l3_pgentry_t *pl3e,
     if ( pgentry_ptr_to_slot(pl3e) >= 3 && is_pv_32bit_domain(d) )
         return -EINVAL;
 
-    ol3e = l3e_read_atomic(pl3e);
+    ol3e = l3e_read(pl3e);
 
     if ( l3e_get_flags(nl3e) & _PAGE_PRESENT )
     {
@@ -2394,7 +2394,7 @@ static int mod_l4_entry(l4_pgentry_t *pl4e,
         return -EINVAL;
     }
 
-    ol4e = l4e_read_atomic(pl4e);
+    ol4e = l4e_read(pl4e);
 
     if ( l4e_get_flags(nl4e) & _PAGE_PRESENT )
     {
@@ -5925,7 +5925,7 @@ void init_or_livepatch modify_xen_mappings_lite(
     while ( v < e )
     {
         l2_pgentry_t *pl2e = &l2_xenmap[l2_table_offset(v)];
-        l2_pgentry_t l2e = l2e_read_atomic(pl2e);
+        l2_pgentry_t l2e = l2e_read(pl2e);
         unsigned int l2f = l2e_get_flags(l2e);
 
         ASSERT(l2f & _PAGE_PRESENT);
@@ -5947,7 +5947,7 @@ void init_or_livepatch modify_xen_mappings_lite(
             while ( v < e )
             {
                 l1_pgentry_t *pl1e = &pl1t[l1_table_offset(v)];
-                l1_pgentry_t l1e = l1e_read_atomic(pl1e);
+                l1_pgentry_t l1e = l1e_read(pl1e);
                 unsigned int l1f = l1e_get_flags(l1e);
 
                 ASSERT(l1f & _PAGE_PRESENT);
xen/arch/x86/traps.c +4 -4
index ee91fc56b125..b4fb95917023 100644
@@ -1450,7 +1450,7 @@ static enum pf_type __page_fault_type(unsigned long addr,
     mfn = cr3 >> PAGE_SHIFT;
 
     l4t = map_domain_page(_mfn(mfn));
-    l4e = l4e_read_atomic(&l4t[l4_table_offset(addr)]);
+    l4e = l4e_read(&l4t[l4_table_offset(addr)]);
     mfn = l4e_get_pfn(l4e);
     unmap_domain_page(l4t);
     if ( ((l4e_get_flags(l4e) & required_flags) != required_flags) ||
@@ -1459,7 +1459,7 @@ static enum pf_type __page_fault_type(unsigned long addr,
     page_user &= l4e_get_flags(l4e);
 
     l3t  = map_domain_page(_mfn(mfn));
-    l3e = l3e_read_atomic(&l3t[l3_table_offset(addr)]);
+    l3e = l3e_read(&l3t[l3_table_offset(addr)]);
     mfn = l3e_get_pfn(l3e);
     unmap_domain_page(l3t);
     if ( ((l3e_get_flags(l3e) & required_flags) != required_flags) ||
@@ -1470,7 +1470,7 @@ static enum pf_type __page_fault_type(unsigned long addr,
         goto leaf;
 
     l2t = map_domain_page(_mfn(mfn));
-    l2e = l2e_read_atomic(&l2t[l2_table_offset(addr)]);
+    l2e = l2e_read(&l2t[l2_table_offset(addr)]);
     mfn = l2e_get_pfn(l2e);
     unmap_domain_page(l2t);
     if ( ((l2e_get_flags(l2e) & required_flags) != required_flags) ||
@@ -1481,7 +1481,7 @@ static enum pf_type __page_fault_type(unsigned long addr,
         goto leaf;
 
     l1t = map_domain_page(_mfn(mfn));
-    l1e = l1e_read_atomic(&l1t[l1_table_offset(addr)]);
+    l1e = l1e_read(&l1t[l1_table_offset(addr)]);
     mfn = l1e_get_pfn(l1e);
     unmap_domain_page(l1t);
     if ( ((l1e_get_flags(l1e) & required_flags) != required_flags) ||
Signature · 1 line
2.45.2
Reviewed-by on v1 2/22
#5 lore raw

Re: [PATCH 02/22] x86/mm: rename l{1,2,3,4}e_read_atomic()

Quoted 7 lines · Roger Pau Monne

There's no l{1,2,3,4}e_read() implementation, so drop the _atomic suffix from the read helpers. This allows unifying the naming with the write helpers, which are also atomic but don't have the suffix already: l{1,2,3,4}e_write().

No functional change intended.

#6 lore raw

PATCH 3/22 x86/dom0: only disable SMAP for the PV dom0 build

In reply to Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

---
 xen/arch/x86/pv/dom0_build.c | 13 ++++++++++---
 xen/arch/x86/setup.c         | 17 -----------------
 2 files changed, 10 insertions(+), 20 deletions(-)
xen/arch/x86/pv/dom0_build.c +10 -3
index d8043fa58a27..41772dbe80bf 100644
@@ -370,6 +370,7 @@ int __init dom0_construct_pv(struct domain *d,
     unsigned long alloc_epfn;
     unsigned long initrd_pfn = -1, initrd_mfn = 0;
     unsigned long count;
+    unsigned long cr4;
     struct page_info *page = NULL;
     unsigned int flush_flags = 0;
     start_info_t *si;
@@ -814,8 +815,14 @@ int __init dom0_construct_pv(struct domain *d,
     /* Set up CR3 value for switch_cr3_cr4(). */
     update_cr3(v);
 
+    /*
+     * Temporarily clear SMAP in CR4 to allow user-accesses when running with
+     * the dom0 page-tables.  Cache the value of CR4 so it can be restored.
+     */
+    cr4 = read_cr4();
+
     /* We run on dom0's page tables for the final part of the build process. */
-    switch_cr3_cr4(cr3_pa(v->arch.cr3), read_cr4());
+    switch_cr3_cr4(cr3_pa(v->arch.cr3), cr4 & ~X86_CR4_SMAP);
     mapcache_override_current(v);
 
     /* Copy the OS image and free temporary buffer. */
@@ -836,7 +843,7 @@ int __init dom0_construct_pv(struct domain *d,
              (parms.virt_hypercall >= v_end) )
         {
             mapcache_override_current(NULL);
-            switch_cr3_cr4(current->arch.cr3, read_cr4());
+            switch_cr3_cr4(current->arch.cr3, cr4);
             printk("Invalid HYPERCALL_PAGE field in ELF notes.\n");
             return -EINVAL;
         }
@@ -978,7 +985,7 @@ int __init dom0_construct_pv(struct domain *d,
 
     /* Return to idle domain's page tables. */
     mapcache_override_current(NULL);
-    switch_cr3_cr4(current->arch.cr3, read_cr4());
+    switch_cr3_cr4(current->arch.cr3, cr4);
 
     update_domain_wallclock_time(d);
 
xen/arch/x86/setup.c +0 -17
index eee20bb1753c..bc387d96b519 100644
@@ -955,26 +955,9 @@ static struct domain *__init create_dom0(const module_t *image,
         }
     }
 
-    /*
-     * Temporarily clear SMAP in CR4 to allow user-accesses in construct_dom0().
-     * This saves a large number of corner cases interactions with
-     * copy_from_user().
-     */
-    if ( cpu_has_smap )
-    {
-        cr4_pv32_mask &= ~X86_CR4_SMAP;
-        write_cr4(read_cr4() & ~X86_CR4_SMAP);
-    }
-
     if ( construct_dom0(d, image, headroom, initrd, cmdline) != 0 )
         panic("Could not construct domain 0\n");
 
-    if ( cpu_has_smap )
-    {
-        write_cr4(read_cr4() | X86_CR4_SMAP);
-        cr4_pv32_mask |= X86_CR4_SMAP;
-    }
-
     return d;
 }
 
Signature · 1 line
2.45.2
#7 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 2 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

This should be reworded as:

"The PVH dom0 builder doesn't build guest page-tables, because PVH is started in 32bit protected mode, hence has no need to run with SMAP disabled."

Thanks, Roger.

Reviewed-by on v1 3/22
#8 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

In reply to Roger Pau Monne
Quoted 9 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

I'm okay-ish with that being dropped, but iirc the goal was to keep the variable in sync with CPU state.

Quoted 1 line
#9 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 4 lines · Jan Beulich
Quoted 3 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Quoted 8 lines
Quoted 6 lines

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

I'm okay-ish with that being dropped, but iirc the goal was to keep the variable in sync with CPU state.

Removing SMAP from cr4_pv32_mask is necessary.

Otherwise IST vectors will reactive SMAP behind the back of the dombuilder.

This will probably only manifest in practice in a CONFIG_PV32=y build, and with a poorly timed NMI.

~Andrew

#10 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 11 lines · Andrew Cooper
Quoted 10 lines · Jan Beulich
Quoted 9 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

Quoted 8 lines
Quoted 2 lines

I'm okay-ish with that being dropped, but iirc the goal was to keep the variable in sync with CPU state.

Removing SMAP from cr4_pv32_mask is necessary.

Otherwise IST vectors will reactive SMAP behind the back of the dombuilder.

This will probably only manifest in practice in a CONFIG_PV32=y build,

Sorry, I'm possibly missing some context here. When running the dom0 builder we switch to the guest page-tables, but not to the guest vCPU, (iow: current == idle) and hence the context is always the Xen context.

Why would the return path of the IST use cr4_pv32_mask when the context in which the IST happened was the Xen one, and the current vCPU is the idle one (a 64bit PV guest from Xen's PoV).

My understanding is that cr4_pv32_mask should only be used when the current context is running a 32bit PV vCPU.

Thanks, Roger.

#11 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 16 lines · Roger Pau Monné
Quoted 15 lines · Andrew Cooper
Quoted 4 lines · Jan Beulich
Quoted 3 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Quoted 8 lines
Quoted 6 lines

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

I'm okay-ish with that being dropped, but iirc the goal was to keep the variable in sync with CPU state.

Removing SMAP from cr4_pv32_mask is necessary.

Quoted 7 lines
Quoted 3 lines

Otherwise IST vectors will reactive SMAP behind the back of the dombuilder.

This will probably only manifest in practice in a CONFIG_PV32=y build,

Sorry, I'm possibly missing some context here. When running the dom0 builder we switch to the guest page-tables, but not to the guest vCPU, (iow: current == idle) and hence the context is always the Xen context.

Correct.

Quoted 6 lines

Why would the return path of the IST use cr4_pv32_mask when the context in which the IST happened was the Xen one, and the current vCPU is the idle one (a 64bit PV guest from Xen's PoV).

My understanding is that cr4_pv32_mask should only be used when the current context is running a 32bit PV vCPU.

This logic is evil to follow, because you need to look at both cr4_pv32_mask and XEN_CR4_PV32_BITS to see both halves of it.

Notice how cr4_pv32_restore() only ever OR's cr4_pv32_mask into %cr4?

CR4_PV32_RESTORE is called from every entry path which *might* have come from a 32bit PV guest, and it always results in Xen having SMEP/SMAP active (as applicable).  This includes NMI.

The change is only undone in compat_restore_all_guest(), where XEN_CR4_PV32_BITS is cleared from %cr4 iff returning to Ring1/2.  This is logic cunningly disguised in the use of the Parity flag.

Because the NMI handler does reactive SMEP/SMAP (based on the value in cr4_pv32_mask), and returning to Xen does not pass through compat_restore_all_guest(), taking an NMI in the middle of of the dombuilder will reactive SMAP behind your back.

~Andrew

#12 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 48 lines · Andrew Cooper
Quoted 16 lines · Roger Pau Monné
Quoted 15 lines · Andrew Cooper
Quoted 4 lines · Jan Beulich
Quoted 3 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Quoted 8 lines
Quoted 6 lines

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

I'm okay-ish with that being dropped, but iirc the goal was to keep the variable in sync with CPU state.

Removing SMAP from cr4_pv32_mask is necessary.

Quoted 7 lines
Quoted 3 lines

Otherwise IST vectors will reactive SMAP behind the back of the dombuilder.

This will probably only manifest in practice in a CONFIG_PV32=y build,

Sorry, I'm possibly missing some context here. When running the dom0 builder we switch to the guest page-tables, but not to the guest vCPU, (iow: current == idle) and hence the context is always the Xen context.

Correct.

Quoted 6 lines

Why would the return path of the IST use cr4_pv32_mask when the context in which the IST happened was the Xen one, and the current vCPU is the idle one (a 64bit PV guest from Xen's PoV).

My understanding is that cr4_pv32_mask should only be used when the current context is running a 32bit PV vCPU.

This logic is evil to follow, because you need to look at both cr4_pv32_mask and XEN_CR4_PV32_BITS to see both halves of it.

Notice how cr4_pv32_restore() only ever OR's cr4_pv32_mask into %cr4?

CR4_PV32_RESTORE is called from every entry path which *might* have come from a 32bit PV guest, and it always results in Xen having SMEP/SMAP active (as applicable).  This includes NMI.

The change is only undone in compat_restore_all_guest(), where XEN_CR4_PV32_BITS is cleared from %cr4 iff returning to Ring1/2.  This is logic cunningly disguised in the use of the Parity flag.

Quoted 4 lines

Because the NMI handler does reactive SMEP/SMAP (based on the value in cr4_pv32_mask), and returning to Xen does not pass through compat_restore_all_guest(), taking an NMI in the middle of of the dombuilder will reactive SMAP behind your back.

After further conversations with Andrew we believe the current disabling of X86_CR4_SMAP in %cr4 during dom0 build is not safe.

Regardless of whether cr4_pv32_mask is properly adjusted return to Xen context from interrupt would be done with SMAP enabled if X86_FEATURE_XEN_SMAP is set.

I will send a new patch that uses stac/clac in order to disable SMAP (if required) around the dom0 builder code that switches to the guest page-tables.

Thanks, Roger.

#13 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 51 lines · Roger Pau Monné
Quoted 46 lines · Andrew Cooper
Quoted 16 lines · Roger Pau Monné
Quoted 15 lines · Andrew Cooper
Quoted 4 lines · Jan Beulich
Quoted 3 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Quoted 8 lines
Quoted 6 lines

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

I'm okay-ish with that being dropped, but iirc the goal was to keep the variable in sync with CPU state.

Removing SMAP from cr4_pv32_mask is necessary.

Quoted 7 lines
Quoted 3 lines

Otherwise IST vectors will reactive SMAP behind the back of the dombuilder.

This will probably only manifest in practice in a CONFIG_PV32=y build,

Sorry, I'm possibly missing some context here. When running the dom0 builder we switch to the guest page-tables, but not to the guest vCPU, (iow: current == idle) and hence the context is always the Xen context.

Correct.

Quoted 6 lines

Why would the return path of the IST use cr4_pv32_mask when the context in which the IST happened was the Xen one, and the current vCPU is the idle one (a 64bit PV guest from Xen's PoV).

My understanding is that cr4_pv32_mask should only be used when the current context is running a 32bit PV vCPU.

This logic is evil to follow, because you need to look at both cr4_pv32_mask and XEN_CR4_PV32_BITS to see both halves of it.

Notice how cr4_pv32_restore() only ever OR's cr4_pv32_mask into %cr4?

CR4_PV32_RESTORE is called from every entry path which *might* have come from a 32bit PV guest, and it always results in Xen having SMEP/SMAP active (as applicable).  This includes NMI.

The change is only undone in compat_restore_all_guest(), where XEN_CR4_PV32_BITS is cleared from %cr4 iff returning to Ring1/2.  This is logic cunningly disguised in the use of the Parity flag.

Quoted 4 lines

Because the NMI handler does reactive SMEP/SMAP (based on the value in cr4_pv32_mask), and returning to Xen does not pass through compat_restore_all_guest(), taking an NMI in the middle of of the dombuilder will reactive SMAP behind your back.

Quoted 6 lines

After further conversations with Andrew we believe the current disabling of X86_CR4_SMAP in %cr4 during dom0 build is not safe.

Regardless of whether cr4_pv32_mask is properly adjusted return to Xen context from interrupt would be done with SMAP enabled if X86_FEATURE_XEN_SMAP is set.

Sorry - that's not what I intended to convey.

The logic prior to this patch is safe.  SMAP is cleared from cr4_pv32_mask before clearing CR4.SMAP, and reinstated in the opposite order.  Therefore, an NMI hitting the region won't reactivate SMAP because it's not (instantaniously) set in cr4_pv32_mask.

Arguably it wants some barrier()'s for clarity, and an explanation of why this works.

The problem your patch has is that by not clearing SMAP from cr4_pv32_mask, it becomes unsafe iff an NMI/#MC/#DB hits the region.

Quoted 3 lines

I will send a new patch that uses stac/clac in order to disable SMAP (if required) around the dom0 builder code that switches to the guest page-tables.

Either way - this is a much cleaner solution.

~Andrew

#14 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 59 lines · Andrew Cooper
Quoted 51 lines · Roger Pau Monné
Quoted 46 lines · Andrew Cooper
Quoted 16 lines · Roger Pau Monné
Quoted 15 lines · Andrew Cooper
Quoted 4 lines · Jan Beulich
Quoted 3 lines · Roger Pau Monne

The PVH dom0 builder doesn't switch page tables and has no need to run with SMAP disabled.

Quoted 8 lines
Quoted 6 lines

Put the SMAP disabling close to the code region where it's necessary, as it then becomes obvious why switch_cr3_cr4() is required instead of write_ptbase().

Note removing SMAP from cr4_pv32_mask is not required, as we never jump into guest context, and hence updating the value of cr4_pv32_mask is not relevant.

I'm okay-ish with that being dropped, but iirc the goal was to keep the variable in sync with CPU state.

Removing SMAP from cr4_pv32_mask is necessary.

Quoted 7 lines
Quoted 3 lines

Otherwise IST vectors will reactive SMAP behind the back of the dombuilder.

This will probably only manifest in practice in a CONFIG_PV32=y build,

Sorry, I'm possibly missing some context here. When running the dom0 builder we switch to the guest page-tables, but not to the guest vCPU, (iow: current == idle) and hence the context is always the Xen context.

Correct.

Quoted 6 lines

Why would the return path of the IST use cr4_pv32_mask when the context in which the IST happened was the Xen one, and the current vCPU is the idle one (a 64bit PV guest from Xen's PoV).

My understanding is that cr4_pv32_mask should only be used when the current context is running a 32bit PV vCPU.

This logic is evil to follow, because you need to look at both cr4_pv32_mask and XEN_CR4_PV32_BITS to see both halves of it.

Notice how cr4_pv32_restore() only ever OR's cr4_pv32_mask into %cr4?

CR4_PV32_RESTORE is called from every entry path which *might* have come from a 32bit PV guest, and it always results in Xen having SMEP/SMAP active (as applicable).  This includes NMI.

The change is only undone in compat_restore_all_guest(), where XEN_CR4_PV32_BITS is cleared from %cr4 iff returning to Ring1/2.  This is logic cunningly disguised in the use of the Parity flag.

Quoted 4 lines

Because the NMI handler does reactive SMEP/SMAP (based on the value in cr4_pv32_mask), and returning to Xen does not pass through compat_restore_all_guest(), taking an NMI in the middle of of the dombuilder will reactive SMAP behind your back.

Quoted 6 lines

After further conversations with Andrew we believe the current disabling of X86_CR4_SMAP in %cr4 during dom0 build is not safe.

Regardless of whether cr4_pv32_mask is properly adjusted return to Xen context from interrupt would be done with SMAP enabled if X86_FEATURE_XEN_SMAP is set.

Quoted 6 lines

Sorry - that's not what I intended to convey.

The logic prior to this patch is safe.  SMAP is cleared from cr4_pv32_mask before clearing CR4.SMAP, and reinstated in the opposite order.  Therefore, an NMI hitting the region won't reactivate SMAP because it's not (instantaniously) set in cr4_pv32_mask.

My bad, I was getting confused with the clac instructions in the event entry points.

I think with my proposed change we would also hit the BUG in cr4_pv32_restore on debug builds if Xen got an interrupt in the middle of the SMAP disabled dom0 build region if SMEP is enabled, as cr4_pv32_mask would differ from the current %cr4 value (not all bits intended would be actually set).

Quoted 5 lines

Arguably it wants some barrier()'s for clarity, and an explanation of why this works.

The problem your patch has is that by not clearing SMAP from cr4_pv32_mask, it becomes unsafe iff an NMI/#MC/#DB hits the region.

Won't such issue also affect common_interrupt, and hence not be limited to NMI/#MC/#DB only?

Regards, Roger.

#15 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

In reply to Roger Pau Monne
Quoted 18 lines · Roger Pau Monne
xen/arch/x86/setup.c +0 -10
index eee20bb1753c..bc387d96b519 100644
@@ -955,26 +955,9 @@ static struct domain *__init create_dom0(const module_t *image,
         }
     }
 
-    /*
-     * Temporarily clear SMAP in CR4 to allow user-accesses in construct_dom0().
-     * This saves a large number of corner cases interactions with
-     * copy_from_user().
-     */
-    if ( cpu_has_smap )
-    {
-        cr4_pv32_mask &= ~X86_CR4_SMAP;
-        write_cr4(read_cr4() & ~X86_CR4_SMAP);
-    }

xen/arch/x86/setup.c static struct domain *__init create_dom0(const module_t *image, · line 977

Quoted 10 lines
xen/arch/x86/setup.c +0 -7
-
     if ( construct_dom0(d, image, headroom, initrd, cmdline) != 0 )
         panic("Could not construct domain 0\n");
 
-    if ( cpu_has_smap )
-    {
-        write_cr4(read_cr4() | X86_CR4_SMAP);
-        cr4_pv32_mask |= X86_CR4_SMAP;
-    }
-

Hang on.  Isn't this (preexistingly) broken given the distinction between cpu_has_smap and X86_FEATURE_XEN_SMAP ?

I'm very tempted to use this as a justification to remove opt_smap.

~Andrew

#16 lore raw

Re: [PATCH 03/22] x86/dom0: only disable SMAP for the PV dom0 build

Quoted 23 lines · Andrew Cooper
Quoted 22 lines · Roger Pau Monne
xen/arch/x86/setup.c +0 -11
index eee20bb1753c..bc387d96b519 100644
@@ -955,26 +955,9 @@ static struct domain *__init create_dom0(const module_t *image,
         }
     }
 
-    /*
-     * Temporarily clear SMAP in CR4 to allow user-accesses in construct_dom0().
-     * This saves a large number of corner cases interactions with
-     * copy_from_user().
-     */
-    if ( cpu_has_smap )
-    {
-        cr4_pv32_mask &= ~X86_CR4_SMAP;
-        write_cr4(read_cr4() & ~X86_CR4_SMAP);
-    }
-
     if ( construct_dom0(d, image, headroom, initrd, cmdline) != 0 )
         panic("Could not construct domain 0\n");
 
Quoted 9 lines

xen/arch/x86/setup.c static struct domain *__init create_dom0(const module_t *image, · line 977

Quoted 6 lines
xen/arch/x86/setup.c +0 -6
-    if ( cpu_has_smap )
-    {
-        write_cr4(read_cr4() | X86_CR4_SMAP);
-        cr4_pv32_mask |= X86_CR4_SMAP;
-    }
-

Hang on.  Isn't this (preexistingly) broken given the distinction between cpu_has_smap and X86_FEATURE_XEN_SMAP ?

I see, looks like Xen will unconditionally enable SMAP if the user has requested SMP for HVM only. Forcefully disabling SMAP for both PV and HVM will result in the CPUID bit getting cleared, and hence cpu_has_smap == false.

Quoted 1 line

I'm very tempted to use this as a justification to remove opt_smap.

Oh, so my change fixes that bug by caching the previous cr4 instead of using cpu_has_smap.

It seems like opt_smap is useful for the PV shim, as it caused some unnecessary performance degradation on AMD hardware due to AMD not allowing to selectively trap accesses to CR4, so on pvshim mode it gets disabled:

b05ec9263e56 x86/sm{e, a}p: do not enable SMEP/SMAP in PV shim by default on AMD

Thanks, Roger.

#17 lore raw

PATCH 4/22 x86/mm: ensure L4 idle_pg_table is not modified past boot

In reply to Roger Pau Monne

The idle_pg_table L4 is cloned to create all the other L4 Xen uses, and hence it shouldn't be modified once further L4 are created.

---
 xen/arch/x86/mm.c | 6 ++++++
 1 file changed, 6 insertions(+)
xen/arch/x86/mm.c +6 -0
index 6ffacab341ad..01380fd82c9d 100644
@@ -5023,6 +5023,12 @@ static l3_pgentry_t *virt_to_xen_l3e(unsigned long v)
         mfn_t l3mfn;
         l3_pgentry_t *l3t = alloc_mapped_pagetable(&l3mfn);
 
+        /*
+         * dom0 is build at smp_boot, at which point we already create new L4s
+         * based on idle_pg_table.
+         */
+        BUG_ON(system_state >= SYS_STATE_smp_boot);
+
         if ( !l3t )
             return NULL;
         UNMAP_DOMAIN_PAGE(l3t);
Signature · 1 line
2.45.2
#18 lore raw

Re: [PATCH 04/22] x86/mm: ensure L4 idle_pg_table is not modified past boot

Quoted 2 lines · Roger Pau Monne

The idle_pg_table L4 is cloned to create all the other L4 Xen uses, and hence it shouldn't be modified once further L4 are created.

Yes, but the window between moving into SYS_STATE_smp_boot and Dom0 having its initial page tables created is quite large. If the justification was relative to AP bringup, that may be all fine. But when related to cloning, I think that would then truly want keying to there being any non-system domain(s).

xen/arch/x86/mm.c static l3_pgentry_t *virt_to_xen_l3e(unsigned long v) · line 5030

Quoted 11 lines
xen/arch/x86/mm.c +5 -0
@@ -5023,6 +5023,12 @@ static l3_pgentry_t *virt_to_xen_l3e(unsigned long v)
         mfn_t l3mfn;
         l3_pgentry_t *l3t = alloc_mapped_pagetable(&l3mfn);
 
+        /*
+         * dom0 is build at smp_boot, at which point we already create new L4s
+         * based on idle_pg_table.
+         */
+        BUG_ON(system_state >= SYS_STATE_smp_boot);

Which effectively means most of this function could become __init (e.g. by moving into a helper). We'd then hit the BUG_ON() prior to init_done() destroying the .init.* mappings, and we'd simply #PF afterwards. That's not so much for the space savings in .text, but to document the limited lifetime of the (helper) function directly in its function head.

I further wonder whether in such a case the enclosing if() wouldn't want to gain unlikely() at the same time.

Jan

#19 lore raw

Re: [PATCH 04/22] x86/mm: ensure L4 idle_pg_table is not modified past boot

Quoted 9 lines · Jan Beulich
Quoted 2 lines · Roger Pau Monne

The idle_pg_table L4 is cloned to create all the other L4 Xen uses, and hence it shouldn't be modified once further L4 are created.

Yes, but the window between moving into SYS_STATE_smp_boot and Dom0 having its initial page tables created is quite large. If the justification was relative to AP bringup, that may be all fine. But when related to cloning, I think that would then truly want keying to there being any non-system domain(s).

Further changes in this series will add a per-CPU idle page table, and hence we need to ensure that by the time APs are started the BSP L4 idle page directory is not changed, as otherwise the copies in the APs would get out of sync.

The idle system domain is indeed tied to the idle page talbes, but the idle vCPU0 (the BSP) directly uses idle_pg_table (no copying), and hence it's fine to allow modifications of the L4 idle page table directory up to when APs are started (those will indeed make copies of the idle L4.

Quoted 6 lines
Quoted 6 lines
xen/arch/x86/mm.c +0 -0
@@ -5023,6 +5023,12 @@ static l3_pgentry_t *virt_to_xen_l3e(unsigned long v)
         mfn_t l3mfn;
         l3_pgentry_t *l3t = alloc_mapped_pagetable(&l3mfn);
 
Quoted 11 lines

xen/arch/x86/mm.c static l3_pgentry_t *virt_to_xen_l3e(unsigned long v) · line 5030

Quoted 5 lines
xen/arch/x86/mm.c +5 -0
+        /*
+         * dom0 is build at smp_boot, at which point we already create new L4s
+         * based on idle_pg_table.
+         */
+        BUG_ON(system_state >= SYS_STATE_smp_boot);

Which effectively means most of this function could become __init (e.g. by moving into a helper). We'd then hit the BUG_ON() prior to init_done() destroying the .init.* mappings, and we'd simply #PF afterwards. That's not so much for the space savings in .text, but to document the limited lifetime of the (helper) function directly in its function head.

IMO the BUG_ON() is clearer to debug, but I won't mind splitting the logic inside the if body into a separate helper.

Quoted 2 lines

I further wonder whether in such a case the enclosing if() wouldn't want to gain unlikely() at the same time.

Yes, I can certainly add that.

Thanks, Roger.

#20 lore raw

Re: [PATCH 04/22] x86/mm: ensure L4 idle_pg_table is not modified past boot

Quoted 16 lines · Roger Pau Monné
Quoted 9 lines · Jan Beulich
Quoted 2 lines · Roger Pau Monne

The idle_pg_table L4 is cloned to create all the other L4 Xen uses, and hence it shouldn't be modified once further L4 are created.

Yes, but the window between moving into SYS_STATE_smp_boot and Dom0 having its initial page tables created is quite large. If the justification was relative to AP bringup, that may be all fine. But when related to cloning, I think that would then truly want keying to there being any non-system domain(s).

Further changes in this series will add a per-CPU idle page table, and hence we need to ensure that by the time APs are started the BSP L4 idle page directory is not changed, as otherwise the copies in the APs would get out of sync.

Quoted 5 lines

The idle system domain is indeed tied to the idle page talbes, but the idle vCPU0 (the BSP) directly uses idle_pg_table (no copying), and hence it's fine to allow modifications of the L4 idle page table directory up to when APs are started (those will indeed make copies of the idle L4.

Which may want at least mentioning in the description then. I take it that ...

Quoted 10 lines
Quoted 10 lines

xen/arch/x86/mm.c static l3_pgentry_t *virt_to_xen_l3e(unsigned long v) · line 5029

Quoted 10 lines
xen/arch/x86/mm.c +4 -0
@@ -5023,6 +5023,12 @@ static l3_pgentry_t *virt_to_xen_l3e(unsigned long v)
         mfn_t l3mfn;
         l3_pgentry_t *l3t = alloc_mapped_pagetable(&l3mfn);
 
+        /*
+         * dom0 is build at smp_boot, at which point we already create new L4s
+         * based on idle_pg_table.
+         */

... this comment is then refined by the later patches you refer to?

Quoted 9 lines
Quoted 7 lines

xen/arch/x86/mm.c static l3_pgentry_t *virt_to_xen_l3e(unsigned long v) · line 5030

Quoted 1 line
xen/arch/x86/mm.c +1 -0
+        BUG_ON(system_state >= SYS_STATE_smp_boot);

Which effectively means most of this function could become __init (e.g. by moving into a helper). We'd then hit the BUG_ON() prior to init_done() destroying the .init.* mappings, and we'd simply #PF afterwards. That's not so much for the space savings in .text, but to document the limited lifetime of the (helper) function directly in its function head.

IMO the BUG_ON() is clearer to debug,

Fair point - it's indeed a balance between two possible goals. I guess ...

Quoted 2 lines

but I won't mind splitting the
logic inside the if body into a separate helper.

... simply keep it as you have it.

Jan

#21 lore raw

Re: [PATCH 04/22] x86/mm: ensure L4 idle_pg_table is not modified past boot

Quoted 32 lines · Jan Beulich
Quoted 16 lines · Roger Pau Monné
Quoted 9 lines · Jan Beulich
Quoted 2 lines · Roger Pau Monne

The idle_pg_table L4 is cloned to create all the other L4 Xen uses, and hence it shouldn't be modified once further L4 are created.

Yes, but the window between moving into SYS_STATE_smp_boot and Dom0 having its initial page tables created is quite large. If the justification was relative to AP bringup, that may be all fine. But when related to cloning, I think that would then truly want keying to there being any non-system domain(s).

Further changes in this series will add a per-CPU idle page table, and hence we need to ensure that by the time APs are started the BSP L4 idle page directory is not changed, as otherwise the copies in the APs would get out of sync.

Quoted 5 lines

The idle system domain is indeed tied to the idle page talbes, but the idle vCPU0 (the BSP) directly uses idle_pg_table (no copying), and hence it's fine to allow modifications of the L4 idle page table directory up to when APs are started (those will indeed make copies of the idle L4.

Which may want at least mentioning in the description then. I take it that ...

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
xen/arch/x86/mm.c +0 -0
@@ -5023,6 +5023,12 @@ static l3_pgentry_t *virt_to_xen_l3e(unsigned long v)
         mfn_t l3mfn;
         l3_pgentry_t *l3t = alloc_mapped_pagetable(&l3mfn);
 
Quoted 6 lines
Quoted 4 lines
Quoted 4 lines

xen/arch/x86/mm.c static l3_pgentry_t *virt_to_xen_l3e(unsigned long v) · line 5029

Quoted 4 lines
xen/arch/x86/mm.c +4 -0
+        /*
+         * dom0 is build at smp_boot, at which point we already create new L4s
+         * based on idle_pg_table.
+         */

... this comment is then refined by the later patches you refer to?

Hm, I would have to double check, not sure I've updated it once the idle_pg_table is cloned for AP bringup.

Will expand commit message and update the comment here if not done already by later patches.

Thanks, Roger.

#22 lore raw

PATCH 5/22 x86/mm: make virt_to_xen_l1e() static

In reply to Roger Pau Monne

There are no callers outside the translation unit where it's defined, so make the function static.

No functional change intended.

---
 xen/arch/x86/include/asm/mm.h | 2 --
 xen/arch/x86/mm.c             | 2 +-
 2 files changed, 1 insertion(+), 3 deletions(-)
xen/arch/x86/include/asm/mm.h +0 -2
index 98b66edaca5e..b3853ae734fa 100644
@@ -567,8 +567,6 @@ mfn_t alloc_xen_pagetable(void);
 void free_xen_pagetable(mfn_t mfn);
 void *alloc_mapped_pagetable(mfn_t *pmfn);
 
-l1_pgentry_t *virt_to_xen_l1e(unsigned long v);
-
 int __sync_local_execstate(void);
 
 /* Arch-specific portion of memory_op hypercall. */
xen/arch/x86/mm.c +1 -1
index 01380fd82c9d..ca3d116b0e05 100644
@@ -5087,7 +5087,7 @@ static l2_pgentry_t *virt_to_xen_l2e(unsigned long v)
     return map_l2t_from_l3e(l3e) + l2_table_offset(v);
 }
 
-l1_pgentry_t *virt_to_xen_l1e(unsigned long v)
+static l1_pgentry_t *virt_to_xen_l1e(unsigned long v)
 {
     l2_pgentry_t *pl2e, l2e;
 
Signature · 1 line
2.45.2
#24 lore raw

PATCH 6/22 x86/mm: introduce a local domain variable to write_ptbase()

In reply to Roger Pau Monne

This reduces the repeated accessing of v->domain.

No functional change intended.

---
 xen/arch/x86/mm.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
xen/arch/x86/mm.c +3 -2
index ca3d116b0e05..a792a300a866 100644
@@ -517,13 +517,14 @@ void make_cr3(struct vcpu *v, mfn_t mfn)
 
 void write_ptbase(struct vcpu *v)
 {
+    const struct domain *d = v->domain;
     struct cpu_info *cpu_info = get_cpu_info();
     unsigned long new_cr4;
 
-    new_cr4 = (is_pv_vcpu(v) && !is_idle_vcpu(v))
+    new_cr4 = (is_pv_domain(d) && !is_idle_domain(d))
               ? pv_make_cr4(v) : mmu_cr4_features;
 
-    if ( is_pv_vcpu(v) && v->domain->arch.pv.xpti )
+    if ( is_pv_domain(d) && d->arch.pv.xpti )
     {
         cpu_info->root_pgt_changed = true;
         cpu_info->pv_cr3 = __pa(this_cpu(root_pgt));
Signature · 1 line
2.45.2
#26 lore raw

PATCH 7/22 x86/spec-ctrl: initialize per-domain XPTI in spec_ctrl_init_domain()

In reply to Roger Pau Monne

XPTI being a speculation mitigation feels better to be initialized in spec_ctrl_init_domain().

No functional change intended, although the call to spec_ctrl_init_domain() in arch_domain_create() needs to be moved ahead of pv_domain_initialise() for d->->arch.pv.xpti to be correctly set.

Move it ahead of most of the initialization functions, since spec_ctrl_init_domain() doesn't depend on any member in the struct domain being set.

---
 xen/arch/x86/domain.c    | 4 ++--
 xen/arch/x86/pv/domain.c | 2 --
 xen/arch/x86/spec_ctrl.c | 4 ++++
 3 files changed, 6 insertions(+), 4 deletions(-)
xen/arch/x86/domain.c +2 -2
index ccadfe0c9e70..3d3c14dbb5ae 100644
@@ -842,6 +842,8 @@ int arch_domain_create(struct domain *d,
         is_pv_domain(d) ? __HYPERVISOR_COMPAT_VIRT_START : ~0u;
 #endif
 
+    spec_ctrl_init_domain(d);
+
     if ( (rc = paging_domain_init(d)) != 0 )
         goto fail;
     paging_initialised = true;
@@ -908,8 +910,6 @@ int arch_domain_create(struct domain *d,
 
     d->arch.msr_relaxed = config->arch.misc_flags & XEN_X86_MSR_RELAXED;
 
-    spec_ctrl_init_domain(d);
-
     return 0;
 
  fail:
xen/arch/x86/pv/domain.c +0 -2
index 2a445bb17b99..86b74fb372d5 100644
@@ -383,8 +383,6 @@ int pv_domain_initialise(struct domain *d)
 
     d->arch.ctxt_switch = &pv_csw;
 
-    d->arch.pv.xpti = is_hardware_domain(d) ? opt_xpti_hwdom : opt_xpti_domu;
-
     if ( !is_pv_32bit_domain(d) && use_invpcid && cpu_has_pcid )
         switch ( ACCESS_ONCE(opt_pcid) )
         {
xen/arch/x86/spec_ctrl.c +4 -0
index 40f6ae017010..5dc7a17b9354 100644
@@ -1769,6 +1769,10 @@ void spec_ctrl_init_domain(struct domain *d)
         (ibpb   ? SCF_entry_ibpb   : 0) |
         (bhb    ? SCF_entry_bhb    : 0) |
         0;
+
+    if ( pv )
+        d->arch.pv.xpti = is_hardware_domain(d) ? opt_xpti_hwdom
+                                                : opt_xpti_domu;
 }
 
 void __init init_speculation_mitigations(void)
Signature · 1 line
2.45.2
Reviewed-by on v1 7/22
#27 lore raw

Re: [PATCH 07/22] x86/spec-ctrl: initialize per-domain XPTI in spec_ctrl_init_domain()

Quoted 7 lines · Roger Pau Monne

XPTI being a speculation mitigation feels better to be initialized in spec_ctrl_init_domain().

No functional change intended, although the call to spec_ctrl_init_domain() in arch_domain_create() needs to be moved ahead of pv_domain_initialise() for d->->arch.pv.xpti to be correctly set.

Quoted 5 lines

Move it ahead of most of the initialization functions, since spec_ctrl_init_domain() doesn't depend on any member in the struct domain being set.

#28 lore raw

PATCH 8/22 x86/mm: avoid passing a domain parameter to L4 init function

In reply to Roger Pau Monne

In preparation for the function being called from contexts where no domain is present.

No functional change intended.

---
 xen/arch/x86/include/asm/mm.h  |  4 +++-
 xen/arch/x86/mm.c              | 24 +++++++++++++-----------
 xen/arch/x86/mm/hap/hap.c      |  3 ++-
 xen/arch/x86/mm/shadow/hvm.c   |  3 ++-
 xen/arch/x86/mm/shadow/multi.c |  7 +++++--
 xen/arch/x86/pv/dom0_build.c   |  3 ++-
 xen/arch/x86/pv/domain.c       |  3 ++-
 7 files changed, 29 insertions(+), 18 deletions(-)
xen/arch/x86/include/asm/mm.h +3 -1
index b3853ae734fa..076e7009dc99 100644
@@ -375,7 +375,9 @@ int devalidate_page(struct page_info *page, unsigned long type,
 
 void init_xen_pae_l2_slots(l2_pgentry_t *l2t, const struct domain *d);
 void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
-                       const struct domain *d, mfn_t sl4mfn, bool ro_mpt);
+                       mfn_t sl4mfn, const struct page_info *perdomain_l3,
+                       bool ro_mpt, bool maybe_compat, bool short_directmap);
+
 bool fill_ro_mpt(mfn_t mfn);
 void zap_ro_mpt(mfn_t mfn);
 
xen/arch/x86/mm.c +13 -11
index a792a300a866..c01b6712143e 100644
@@ -1645,14 +1645,9 @@ static int promote_l3_table(struct page_info *page)
  * extended directmap.
  */
 void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
-                       const struct domain *d, mfn_t sl4mfn, bool ro_mpt)
+                       mfn_t sl4mfn, const struct page_info *perdomain_l3,
+                       bool ro_mpt, bool maybe_compat, bool short_directmap)
 {
-    /*
-     * PV vcpus need a shortened directmap.  HVM and Idle vcpus get the full
-     * directmap.
-     */
-    bool short_directmap = !paging_mode_external(d);
-
     /* Slot 256: RO M2P (if applicable). */
     l4t[l4_table_offset(RO_MPT_VIRT_START)] =
         ro_mpt ? idle_pg_table[l4_table_offset(RO_MPT_VIRT_START)]
@@ -1673,13 +1668,14 @@ void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
         l4e_from_mfn(sl4mfn, __PAGE_HYPERVISOR_RW);
 
     /* Slot 260: Per-domain mappings. */
-    l4t[l4_table_offset(PERDOMAIN_VIRT_START)] =
-        l4e_from_page(d->arch.perdomain_l3_pg, __PAGE_HYPERVISOR_RW);
+    if ( perdomain_l3 )
+        l4t[l4_table_offset(PERDOMAIN_VIRT_START)] =
+            l4e_from_page(perdomain_l3, __PAGE_HYPERVISOR_RW);
 
     /* Slot 4: Per-domain mappings mirror. */
     BUILD_BUG_ON(IS_ENABLED(CONFIG_PV32) &&
                  !l4_table_offset(PERDOMAIN_ALT_VIRT_START));
-    if ( !is_pv_64bit_domain(d) )
+    if ( perdomain_l3 && maybe_compat )
         l4t[l4_table_offset(PERDOMAIN_ALT_VIRT_START)] =
             l4t[l4_table_offset(PERDOMAIN_VIRT_START)];
 
@@ -1710,6 +1706,10 @@ void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
     else
 #endif
     {
+        /*
+         * PV vcpus need a shortened directmap.  HVM and Idle vcpus get the full
+         * directmap.
+         */
         unsigned int slots = (short_directmap
                               ? ROOT_PAGETABLE_PV_XEN_SLOTS
                               : ROOT_PAGETABLE_XEN_SLOTS);
@@ -1830,7 +1830,9 @@ static int promote_l4_table(struct page_info *page)
     if ( !rc )
     {
         init_xen_l4_slots(pl4e, l4mfn,
-                          d, INVALID_MFN, VM_ASSIST(d, m2p_strict));
+                          INVALID_MFN, d->arch.perdomain_l3_pg,
+                          VM_ASSIST(d, m2p_strict), !is_pv_64bit_domain(d),
+                          true);
         atomic_inc(&d->arch.pv.nr_l4_pages);
     }
     unmap_domain_page(pl4e);
xen/arch/x86/mm/hap/hap.c +2 -1
index d2011fde2462..c8514ca0e917 100644
@@ -402,7 +402,8 @@ static mfn_t hap_make_monitor_table(struct vcpu *v)
     m4mfn = page_to_mfn(pg);
     l4e = map_domain_page(m4mfn);
 
-    init_xen_l4_slots(l4e, m4mfn, d, INVALID_MFN, false);
+    init_xen_l4_slots(l4e, m4mfn, INVALID_MFN, d->arch.perdomain_l3_pg,
+                      false, true, false);
     unmap_domain_page(l4e);
 
     return m4mfn;
xen/arch/x86/mm/shadow/hvm.c +2 -1
index c16f3b3adf32..93922a71e511 100644
@@ -758,7 +758,8 @@ mfn_t sh_make_monitor_table(const struct vcpu *v, unsigned int shadow_levels)
      * shadow-linear mapping will either be inserted below when creating
      * lower level monitor tables, or later in sh_update_cr3().
      */
-    init_xen_l4_slots(l4e, m4mfn, d, INVALID_MFN, false);
+    init_xen_l4_slots(l4e, m4mfn, INVALID_MFN, d->arch.perdomain_l3_pg,
+                      false, true, false);
 
     if ( shadow_levels < 4 )
     {
xen/arch/x86/mm/shadow/multi.c +5 -2
index 376f6823cd44..0def0c073ca8 100644
@@ -973,8 +973,11 @@ sh_make_shadow(struct vcpu *v, mfn_t gmfn, u32 shadow_type)
 
             BUILD_BUG_ON(sizeof(l4_pgentry_t) != sizeof(shadow_l4e_t));
 
-            init_xen_l4_slots(l4t, gmfn, d, smfn, (!is_pv_32bit_domain(d) &&
-                                                   VM_ASSIST(d, m2p_strict)));
+            init_xen_l4_slots(l4t, gmfn, smfn,
+                              d->arch.perdomain_l3_pg,
+                              (!is_pv_32bit_domain(d) &&
+                               VM_ASSIST(d, m2p_strict)),
+                              !is_pv_64bit_domain(d), true);
             unmap_domain_page(l4t);
         }
         break;
xen/arch/x86/pv/dom0_build.c +2 -1
index 41772dbe80bf..6a6689f402bb 100644
@@ -711,7 +711,8 @@ int __init dom0_construct_pv(struct domain *d,
         l4start = l4tab = __va(mpt_alloc); mpt_alloc += PAGE_SIZE;
         clear_page(l4tab);
         init_xen_l4_slots(l4tab, _mfn(virt_to_mfn(l4start)),
-                          d, INVALID_MFN, true);
+                          INVALID_MFN, d->arch.perdomain_l3_pg,
+                          true, !is_pv_64bit_domain(d), true);
         v->arch.guest_table = pagetable_from_paddr(__pa(l4start));
     }
     else
xen/arch/x86/pv/domain.c +2 -1
index 86b74fb372d5..6ff71f14a2f2 100644
@@ -124,7 +124,8 @@ static int setup_compat_l4(struct vcpu *v)
     mfn = page_to_mfn(pg);
     l4tab = map_domain_page(mfn);
     clear_page(l4tab);
-    init_xen_l4_slots(l4tab, mfn, v->domain, INVALID_MFN, false);
+    init_xen_l4_slots(l4tab, mfn, INVALID_MFN, v->domain->arch.perdomain_l3_pg,
+                      false, true, true);
     unmap_domain_page(l4tab);
 
     /* This page needs to look like a pagetable so that it can be shadowed */
Signature · 1 line
2.45.2
#29 lore raw

Re: [PATCH 08/22] x86/mm: avoid passing a domain parameter to L4 init function

Quoted 21 lines · Roger Pau Monne

In preparation for the function being called from contexts where no domain is present.

No functional change intended.

---
 xen/arch/x86/include/asm/mm.h  |  4 +++-
 xen/arch/x86/mm.c              | 24 +++++++++++++-----------
 xen/arch/x86/mm/hap/hap.c      |  3 ++-
 xen/arch/x86/mm/shadow/hvm.c   |  3 ++-
 xen/arch/x86/mm/shadow/multi.c |  7 +++++--
 xen/arch/x86/pv/dom0_build.c   |  3 ++-
 xen/arch/x86/pv/domain.c       |  3 ++-
 7 files changed, 29 insertions(+), 18 deletions(-)
xen/arch/x86/include/asm/mm.h +0 -0
index b3853ae734fa..076e7009dc99 100644

xen/arch/x86/include/asm/mm.h int devalidate_page(struct page_info *page, unsigned long type, · line 380

Quoted 7 lines
xen/arch/x86/include/asm/mm.h +3 -1
@@ -375,7 +375,9 @@ int devalidate_page(struct page_info *page, unsigned long type,
 
 void init_xen_pae_l2_slots(l2_pgentry_t *l2t, const struct domain *d);
 void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
-                       const struct domain *d, mfn_t sl4mfn, bool ro_mpt);
+                       mfn_t sl4mfn, const struct page_info *perdomain_l3,
+                       bool ro_mpt, bool maybe_compat, bool short_directmap);
+

The comment currently in the .c file should probably be here instead, and updated for the new arguments. That said, I'm skeptical 3 booleans is something desirable. It induces a lot of complexity at the call sites (which of the 8 forms of init_xen_l4_slots() do I need here?) and a lot of cognitive overload.

I can't propose a solution because I'm still wrapping my head around how the layout (esp. compat layout) fits together. Maybe the booleans can be mapped to an enum? It would also help interpret the callsites as it'd no longer be a sequence of contextless booleans, but a readable identifier.

Quoted 69 lines
xen/arch/x86/include/asm/mm.h +0 -0
 bool fill_ro_mpt(mfn_t mfn);
 void zap_ro_mpt(mfn_t mfn);
 
xen/arch/x86/mm.c +13 -11
index a792a300a866..c01b6712143e 100644
@@ -1645,14 +1645,9 @@ static int promote_l3_table(struct page_info *page)
  * extended directmap.
  */
 void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
-                       const struct domain *d, mfn_t sl4mfn, bool ro_mpt)
+                       mfn_t sl4mfn, const struct page_info *perdomain_l3,
+                       bool ro_mpt, bool maybe_compat, bool short_directmap)
 {
-    /*
-     * PV vcpus need a shortened directmap.  HVM and Idle vcpus get the full
-     * directmap.
-     */
-    bool short_directmap = !paging_mode_external(d);
-
     /* Slot 256: RO M2P (if applicable). */
     l4t[l4_table_offset(RO_MPT_VIRT_START)] =
         ro_mpt ? idle_pg_table[l4_table_offset(RO_MPT_VIRT_START)]
@@ -1673,13 +1668,14 @@ void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
         l4e_from_mfn(sl4mfn, __PAGE_HYPERVISOR_RW);
 
     /* Slot 260: Per-domain mappings. */
-    l4t[l4_table_offset(PERDOMAIN_VIRT_START)] =
-        l4e_from_page(d->arch.perdomain_l3_pg, __PAGE_HYPERVISOR_RW);
+    if ( perdomain_l3 )
+        l4t[l4_table_offset(PERDOMAIN_VIRT_START)] =
+            l4e_from_page(perdomain_l3, __PAGE_HYPERVISOR_RW);
 
     /* Slot 4: Per-domain mappings mirror. */
     BUILD_BUG_ON(IS_ENABLED(CONFIG_PV32) &&
                  !l4_table_offset(PERDOMAIN_ALT_VIRT_START));
-    if ( !is_pv_64bit_domain(d) )
+    if ( perdomain_l3 && maybe_compat )
         l4t[l4_table_offset(PERDOMAIN_ALT_VIRT_START)] =
             l4t[l4_table_offset(PERDOMAIN_VIRT_START)];
 
@@ -1710,6 +1706,10 @@ void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
     else
 #endif
     {
+        /*
+         * PV vcpus need a shortened directmap.  HVM and Idle vcpus get the full
+         * directmap.
+         */
         unsigned int slots = (short_directmap
                               ? ROOT_PAGETABLE_PV_XEN_SLOTS
                               : ROOT_PAGETABLE_XEN_SLOTS);
@@ -1830,7 +1830,9 @@ static int promote_l4_table(struct page_info *page)
     if ( !rc )
     {
         init_xen_l4_slots(pl4e, l4mfn,
-                          d, INVALID_MFN, VM_ASSIST(d, m2p_strict));
+                          INVALID_MFN, d->arch.perdomain_l3_pg,
+                          VM_ASSIST(d, m2p_strict), !is_pv_64bit_domain(d),
+                          true);
         atomic_inc(&d->arch.pv.nr_l4_pages);
     }
     unmap_domain_page(pl4e);
xen/arch/x86/mm/hap/hap.c +0 -0
index d2011fde2462..c8514ca0e917 100644

xen/arch/x86/mm/hap/hap.c static mfn_t hap_make_monitor_table(struct vcpu *v) · line 406

Quoted 6 lines
xen/arch/x86/mm/hap/hap.c +2 -1
@@ -402,7 +402,8 @@ static mfn_t hap_make_monitor_table(struct vcpu *v)
     m4mfn = page_to_mfn(pg);
     l4e = map_domain_page(m4mfn);
 
-    init_xen_l4_slots(l4e, m4mfn, d, INVALID_MFN, false);
+    init_xen_l4_slots(l4e, m4mfn, INVALID_MFN, d->arch.perdomain_l3_pg,
+                      false, true, false);

Out of ignorance: why is the compat area mapped on HVM monitor PTs? I thought those were used exclusively in hypervisor context, and would hence always have the 512 slots available.

Quoted 63 lines
xen/arch/x86/mm/hap/hap.c +0 -0
     unmap_domain_page(l4e);
 
     return m4mfn;
xen/arch/x86/mm/shadow/hvm.c +2 -1
index c16f3b3adf32..93922a71e511 100644
@@ -758,7 +758,8 @@ mfn_t sh_make_monitor_table(const struct vcpu *v, unsigned int shadow_levels)
      * shadow-linear mapping will either be inserted below when creating
      * lower level monitor tables, or later in sh_update_cr3().
      */
-    init_xen_l4_slots(l4e, m4mfn, d, INVALID_MFN, false);
+    init_xen_l4_slots(l4e, m4mfn, INVALID_MFN, d->arch.perdomain_l3_pg,
+                      false, true, false);
 
     if ( shadow_levels < 4 )
     {
xen/arch/x86/mm/shadow/multi.c +5 -2
index 376f6823cd44..0def0c073ca8 100644
@@ -973,8 +973,11 @@ sh_make_shadow(struct vcpu *v, mfn_t gmfn, u32 shadow_type)
 
             BUILD_BUG_ON(sizeof(l4_pgentry_t) != sizeof(shadow_l4e_t));
 
-            init_xen_l4_slots(l4t, gmfn, d, smfn, (!is_pv_32bit_domain(d) &&
-                                                   VM_ASSIST(d, m2p_strict)));
+            init_xen_l4_slots(l4t, gmfn, smfn,
+                              d->arch.perdomain_l3_pg,
+                              (!is_pv_32bit_domain(d) &&
+                               VM_ASSIST(d, m2p_strict)),
+                              !is_pv_64bit_domain(d), true);
             unmap_domain_page(l4t);
         }
         break;
xen/arch/x86/pv/dom0_build.c +2 -1
index 41772dbe80bf..6a6689f402bb 100644
@@ -711,7 +711,8 @@ int __init dom0_construct_pv(struct domain *d,
         l4start = l4tab = __va(mpt_alloc); mpt_alloc += PAGE_SIZE;
         clear_page(l4tab);
         init_xen_l4_slots(l4tab, _mfn(virt_to_mfn(l4start)),
-                          d, INVALID_MFN, true);
+                          INVALID_MFN, d->arch.perdomain_l3_pg,
+                          true, !is_pv_64bit_domain(d), true);
         v->arch.guest_table = pagetable_from_paddr(__pa(l4start));
     }
     else
xen/arch/x86/pv/domain.c +2 -1
index 86b74fb372d5..6ff71f14a2f2 100644
@@ -124,7 +124,8 @@ static int setup_compat_l4(struct vcpu *v)
     mfn = page_to_mfn(pg);
     l4tab = map_domain_page(mfn);
     clear_page(l4tab);
-    init_xen_l4_slots(l4tab, mfn, v->domain, INVALID_MFN, false);
+    init_xen_l4_slots(l4tab, mfn, INVALID_MFN, v->domain->arch.perdomain_l3_pg,
+                      false, true, true);
     unmap_domain_page(l4tab);
 
     /* This page needs to look like a pagetable so that it can be shadowed */
#30 lore raw

Re: [PATCH 08/22] x86/mm: avoid passing a domain parameter to L4 init function

Quoted 7 lines · Alejandro Vallejo
Quoted 6 lines · Roger Pau Monne
xen/arch/x86/mm/hap/hap.c +0 -0
@@ -402,7 +402,8 @@ static mfn_t hap_make_monitor_table(struct vcpu *v)
     m4mfn = page_to_mfn(pg);
     l4e = map_domain_page(m4mfn);
 
Quoted 7 lines

xen/arch/x86/mm/hap/hap.c static mfn_t hap_make_monitor_table(struct vcpu *v) · line 406

Quoted 3 lines
xen/arch/x86/mm/hap/hap.c +2 -1
-    init_xen_l4_slots(l4e, m4mfn, d, INVALID_MFN, false);
+    init_xen_l4_slots(l4e, m4mfn, INVALID_MFN, d->arch.perdomain_l3_pg,
+                      false, true, false);

Out of ignorance: why is the compat area mapped on HVM monitor PTs? I thought those were used exclusively in hypervisor context, and would hence always have the 512 slots available.

"compat area" is perhaps a misleading term. If you look at the function itself, it's PERDOMAIN_ALT_VIRT_START that is mapped in that case. Which underlies the compat-arg-xlat area, which both 32-bit PV and all HVM guests need, the latter as they can, at any time, switch to 32-bit mode.

Jan

#31 lore raw

Re: [PATCH 08/22] x86/mm: avoid passing a domain parameter to L4 init function

In reply to Alejandro Vallejo
Quoted 35 lines · Alejandro Vallejo
Quoted 21 lines · Roger Pau Monne

In preparation for the function being called from contexts where no domain is present.

No functional change intended.

---
 xen/arch/x86/include/asm/mm.h  |  4 +++-
 xen/arch/x86/mm.c              | 24 +++++++++++++-----------
 xen/arch/x86/mm/hap/hap.c      |  3 ++-
 xen/arch/x86/mm/shadow/hvm.c   |  3 ++-
 xen/arch/x86/mm/shadow/multi.c |  7 +++++--
 xen/arch/x86/pv/dom0_build.c   |  3 ++-
 xen/arch/x86/pv/domain.c       |  3 ++-
 7 files changed, 29 insertions(+), 18 deletions(-)
xen/arch/x86/include/asm/mm.h +0 -0
index b3853ae734fa..076e7009dc99 100644

xen/arch/x86/include/asm/mm.h int devalidate_page(struct page_info *page, unsigned long type, · line 380

Quoted 7 lines
xen/arch/x86/include/asm/mm.h +3 -1
@@ -375,7 +375,9 @@ int devalidate_page(struct page_info *page, unsigned long type,
 
 void init_xen_pae_l2_slots(l2_pgentry_t *l2t, const struct domain *d);
 void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
-                       const struct domain *d, mfn_t sl4mfn, bool ro_mpt);
+                       mfn_t sl4mfn, const struct page_info *perdomain_l3,
+                       bool ro_mpt, bool maybe_compat, bool short_directmap);
+

The comment currently in the .c file should probably be here instead, and updated for the new arguments. That said, I'm skeptical 3 booleans is something desirable. It induces a lot of complexity at the call sites (which of the 8 forms of init_xen_l4_slots() do I need here?) and a lot of cognitive overload.

Quoted 4 lines

I can't propose a solution because I'm still wrapping my head around how the layout (esp. compat layout) fits together. Maybe the booleans can be mapped to an enum? It would also help interpret the callsites as it'd no longer be a sequence of contextless booleans, but a readable identifier.

We have the following possible combinations:

RO MPT COMPAT XLAT SHORT DMAP

PV64        ?         N             Y
PV32        N         Y             Y
HVM         N         Y             N

So we would need:

enum l4_domain_type {
    PV64,
    PV64_RO_MPT,
    PV32,
    HVM
};

I can see about replacing those last 3 booleans with the proposed enum.

Thanks, Roger.

#32 lore raw

Re: [PATCH 08/22] x86/mm: avoid passing a domain parameter to L4 init function

In reply to Roger Pau Monne
Quoted 7 lines · Roger Pau Monne
xen/arch/x86/mm.c +1 -2
@@ -1673,13 +1668,14 @@ void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn,
         l4e_from_mfn(sl4mfn, __PAGE_HYPERVISOR_RW);
 
     /* Slot 260: Per-domain mappings. */
-    l4t[l4_table_offset(PERDOMAIN_VIRT_START)] =
-        l4e_from_page(d->arch.perdomain_l3_pg, __PAGE_HYPERVISOR_RW);
+    if ( perdomain_l3 )

xen/arch/x86/mm.c void init_xen_l4_slots(l4_pgentry_t *l4t, mfn_t l4mfn, · line 1680

Quoted 10 lines
xen/arch/x86/mm.c +3 -1
+        l4t[l4_table_offset(PERDOMAIN_VIRT_START)] =
+            l4e_from_page(perdomain_l3, __PAGE_HYPERVISOR_RW);
 
     /* Slot 4: Per-domain mappings mirror. */
     BUILD_BUG_ON(IS_ENABLED(CONFIG_PV32) &&
                  !l4_table_offset(PERDOMAIN_ALT_VIRT_START));
-    if ( !is_pv_64bit_domain(d) )
+    if ( perdomain_l3 && maybe_compat )
         l4t[l4_table_offset(PERDOMAIN_ALT_VIRT_START)] =
             l4t[l4_table_offset(PERDOMAIN_VIRT_START)];

I think it would be nice if the description could clarify why we need checks of perdomain_l3 twice here. I assume going forward you want to be able to pass in NULL. Therefore, if the conditionals are required, I think it would make sense to have just one, enclosing both (related) writes.

Jan

#33 lore raw

PATCH 9/22 x86/pv: untie issuing FLUSH_ROOT_PGTBL from XPTI

In reply to Roger Pau Monne

The current logic gates issuing flush TLB requests with the FLUSH_ROOT_PGTBL flag to XPTI being enabled.

In preparation for FLUSH_ROOT_PGTBL also being needed when not using XPTI, untie it from the xpti domain boolean and instead introduce a new flush_root_pt field.

No functional change intended, as flush_root_pt == xpti.

---
 xen/arch/x86/include/asm/domain.h   | 2 ++
 xen/arch/x86/include/asm/flushtlb.h | 2 +-
 xen/arch/x86/mm.c                   | 2 +-
 xen/arch/x86/pv/domain.c            | 2 ++
 4 files changed, 6 insertions(+), 2 deletions(-)
xen/arch/x86/include/asm/domain.h +2 -0
index f5daeb182baa..9dd2e047f4de 100644
@@ -283,6 +283,8 @@ struct pv_domain
     bool pcid;
     /* Mitigate L1TF with shadow/crashing? */
     bool check_l1tf;
+    /* Issue FLUSH_ROOT_PGTBL for root page-table changes. */
+    bool flush_root_pt;
 
     /* map_domain_page() mapping cache. */
     struct mapcache_domain mapcache;
xen/arch/x86/include/asm/flushtlb.h +1 -1
index bb0ad58db49b..1b98d03decdc 100644
@@ -177,7 +177,7 @@ void flush_area_mask(const cpumask_t *mask, const void *va,
 
 #define flush_root_pgtbl_domain(d)                                       \
 {                                                                        \
-    if ( is_pv_domain(d) && (d)->arch.pv.xpti )                          \
+    if ( is_pv_domain(d) && (d)->arch.pv.flush_root_pt )                 \
         flush_mask((d)->dirty_cpumask, FLUSH_ROOT_PGTBL);                \
 }
 
xen/arch/x86/mm.c +1 -1
index c01b6712143e..a1ac7bdc5b44 100644
@@ -4167,7 +4167,7 @@ long do_mmu_update(
                                       cmd == MMU_PT_UPDATE_PRESERVE_AD, v);
                     if ( !rc )
                         flush_linear_pt = true;
-                    if ( !rc && pt_owner->arch.pv.xpti )
+                    if ( !rc && pt_owner->arch.pv.flush_root_pt )
                     {
                         bool local_in_use = false;
 
xen/arch/x86/pv/domain.c +2 -0
index 6ff71f14a2f2..46ee10a8a4c2 100644
@@ -384,6 +384,8 @@ int pv_domain_initialise(struct domain *d)
 
     d->arch.ctxt_switch = &pv_csw;
 
+    d->arch.pv.flush_root_pt = d->arch.pv.xpti;
+
     if ( !is_pv_32bit_domain(d) && use_invpcid && cpu_has_pcid )
         switch ( ACCESS_ONCE(opt_pcid) )
         {
Signature · 1 line
2.45.2
#34 lore raw

PATCH 10/22 x86/mm: move FLUSH_ROOT_PGTBL handling before TLB flush

In reply to Roger Pau Monne

Move the handling of FLUSH_ROOT_PGTBL in flush_area_local() ahead of the logic that does the TLB flushing, in preparation for further changes requiring the TLB flush to be strictly done after having handled FLUSH_ROOT_PGTBL.

No functional change intended.

---
 xen/arch/x86/flushtlb.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
xen/arch/x86/flushtlb.c +3 -3
index 18748b2bc805..fd5ed16ffb57 100644
@@ -191,6 +191,9 @@ unsigned int flush_area_local(const void *va, unsigned int flags)
 {
     unsigned int order = (flags - 1) & FLUSH_ORDER_MASK;
 
+    if ( flags & FLUSH_ROOT_PGTBL )
+        get_cpu_info()->root_pgt_changed = true;
+
     if ( flags & (FLUSH_TLB|FLUSH_TLB_GLOBAL) )
     {
         if ( order == 0 )
@@ -254,9 +257,6 @@ unsigned int flush_area_local(const void *va, unsigned int flags)
         }
     }
 
-    if ( flags & FLUSH_ROOT_PGTBL )
-        get_cpu_info()->root_pgt_changed = true;
-
     return flags;
 }
 
Signature · 1 line
2.45.2
#35 lore raw

PATCH 11/22 x86/mm: split setup of the per-domain slot on context switch

In reply to Roger Pau Monne

It's currently only used for XPTI. Move the code to a separate helper in preparation for it gaining more logic.

While there switch to using l4e_write(): in the current context the L4 is not active when modified, but that could change.

No functional change intended.

---
 xen/arch/x86/domain.c         | 4 +---
 xen/arch/x86/include/asm/mm.h | 3 +++
 xen/arch/x86/mm.c             | 7 +++++++
 3 files changed, 11 insertions(+), 3 deletions(-)
xen/arch/x86/domain.c +1 -3
index 3d3c14dbb5ae..9cfcf0dc63f3 100644
@@ -1918,9 +1918,7 @@ void cf_check paravirt_ctxt_switch_to(struct vcpu *v)
     root_pgentry_t *root_pgt = this_cpu(root_pgt);
 
     if ( root_pgt )
-        root_pgt[root_table_offset(PERDOMAIN_VIRT_START)] =
-            l4e_from_page(v->domain->arch.perdomain_l3_pg,
-                          __PAGE_HYPERVISOR_RW);
+        setup_perdomain_slot(v, root_pgt);
 
     if ( unlikely(v->arch.dr7 & DR7_ACTIVE_MASK) )
         activate_debugregs(v);
xen/arch/x86/include/asm/mm.h +3 -0
index 076e7009dc99..2c309f7b1444 100644
@@ -630,4 +630,7 @@ static inline bool arch_mfns_in_directmap(unsigned long mfn, unsigned long nr)
     return (mfn + nr) <= (virt_to_mfn(eva - 1) + 1);
 }
 
+/* Setup the per-domain slot in the root page table pointer. */
+void setup_perdomain_slot(const struct vcpu *v, root_pgentry_t *root_pgt);
+
 #endif /* __ASM_X86_MM_H__ */
xen/arch/x86/mm.c +7 -0
index a1ac7bdc5b44..35e929057d21 100644
@@ -6362,6 +6362,13 @@ unsigned long get_upper_mfn_bound(void)
     return min(max_mfn, 1UL << (paddr_bits - PAGE_SHIFT)) - 1;
 }
 
+void setup_perdomain_slot(const struct vcpu *v, root_pgentry_t *root_pgt)
+{
+    l4e_write(&root_pgt[root_table_offset(PERDOMAIN_VIRT_START)],
+              l4e_from_page(v->domain->arch.perdomain_l3_pg,
+                            __PAGE_HYPERVISOR_RW));
+}
+
 static void __init __maybe_unused build_assertions(void)
 {
     /*
Signature · 1 line
2.45.2
#36 lore raw

PATCH 12/22 x86/spec-ctrl: introduce Address Space Isolation command line option

In reply to Roger Pau Monne

No functional change, as the option is not used.

Introduced new so newly added functionality is keyed on the option being enabled, even if the feature is non-functional.

---
 docs/misc/xen-command-line.pandoc    | 15 ++++--
 xen/arch/x86/include/asm/domain.h    |  3 ++
 xen/arch/x86/include/asm/spec_ctrl.h |  2 +
 xen/arch/x86/spec_ctrl.c             | 74 +++++++++++++++++++++++++---
 4 files changed, 81 insertions(+), 13 deletions(-)
docs/misc/xen-command-line.pandoc +10 -5
index 98a45211556b..0ddc330428d9 100644
@@ -2387,7 +2387,7 @@ By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`).
 
 ### spec-ctrl (x86)
 > `= List of [ <bool>, xen=<bool>, {pv,hvm}=<bool>,
->              {msr-sc,rsb,verw,{ibpb,bhb}-entry}=<bool>|{pv,hvm}=<bool>,
+>              {msr-sc,rsb,verw,{ibpb,bhb}-entry,asi}=<bool>|{pv,hvm}=<bool>,
 >              bti-thunk=retpoline|lfence|jmp,bhb-seq=short|tsx|long,
 >              {ibrs,ibpb,ssbd,psfd,
 >              eager-fpu,l1d-flush,branch-harden,srb-lock,
@@ -2414,10 +2414,10 @@ in place for guests to use.
 
 Use of a positive boolean value for either of these options is invalid.
 
-The `pv=`, `hvm=`, `msr-sc=`, `rsb=`, `verw=`, `ibpb-entry=` and `bhb-entry=`
-options offer fine grained control over the primitives by Xen.  These impact
-Xen's ability to protect itself, and/or Xen's ability to virtualise support
-for guests to use.
+The `pv=`, `hvm=`, `msr-sc=`, `rsb=`, `verw=`, `ibpb-entry=`, `bhb-entry=` and
+`asi=` options offer fine grained control over the primitives by Xen.  These
+impact Xen's ability to protect itself, and/or Xen's ability to virtualise
+support for guests to use.
 
 * `pv=` and `hvm=` offer control over all suboptions for PV and HVM guests
   respectively.
@@ -2449,6 +2449,11 @@ for guests to use.
   is not available (see `bhi-dis-s`).  The choice of scrubbing sequence can be
   selected using the `bhb-seq=` option.  If it is necessary to protect dom0
   too, boot with `spec-ctrl=bhb-entry`.
+* `asi=` offers control over whether the hypervisor will engage in Address
+  Space Isolation, by not having sensitive information mapped in the VMM
+  page-tables.  Not having sensitive information on the page-tables avoids
+  having to perform some mitigations for speculative attacks when
+  context-switching to the hypervisor.
 
 If Xen was compiled with `CONFIG_INDIRECT_THUNK` support, `bti-thunk=` can be
 used to select which of the thunks gets patched into the
xen/arch/x86/include/asm/domain.h +3 -0
index 9dd2e047f4de..8c366be8c75f 100644
@@ -458,6 +458,9 @@ struct arch_domain
     /* Don't unconditionally inject #GP for unhandled MSRs. */
     bool msr_relaxed;
 
+    /* Run the guest without sensitive information in the VMM page-tables. */
+    bool asi;
+
     /* Emulated devices enabled bitmap. */
     uint32_t emulation_flags;
 } __cacheline_aligned;
xen/arch/x86/include/asm/spec_ctrl.h +2 -0
index 72347ef2b959..39963c004312 100644
@@ -88,6 +88,8 @@ extern uint8_t default_scf;
 
 extern int8_t opt_xpti_hwdom, opt_xpti_domu;
 
+extern int8_t opt_asi_pv, opt_asi_hwdom, opt_asi_hvm;
+
 extern bool cpu_has_bug_l1tf;
 extern int8_t opt_pv_l1tf_hwdom, opt_pv_l1tf_domu;
 
xen/arch/x86/spec_ctrl.c +66 -8

157 lines not on this page · raw message

Signature · 1 line
2.45.2
#37 lore raw

Re: [PATCH 12/22] x86/spec-ctrl: introduce Address Space Isolation command line option

docs/misc/xen-command-line.pandoc By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`). · line 2390

Quoted 8 lines · Roger Pau Monne
docs/misc/xen-command-line.pandoc +1 -1
@@ -2387,7 +2387,7 @@ By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`).
 
 ### spec-ctrl (x86)
 > `= List of [ <bool>, xen=<bool>, {pv,hvm}=<bool>,
->              {msr-sc,rsb,verw,{ibpb,bhb}-entry}=<bool>|{pv,hvm}=<bool>,
+>              {msr-sc,rsb,verw,{ibpb,bhb}-entry,asi}=<bool>|{pv,hvm}=<bool>,

Is it really appropriate to hide this underneath an x86-only option? Even of other architectures won't support it right away, they surely will want to down the road? In which case making as much of this common right away is probably the best we can do. This goes along with the question whether, like e.g. "xpti", this should be a top-level option.

docs/misc/xen-command-line.pandoc in place for guests to use. · line 2418

Quoted 10 lines
docs/misc/xen-command-line.pandoc +2 -4
@@ -2414,10 +2414,10 @@ in place for guests to use.
 
 Use of a positive boolean value for either of these options is invalid.
 
-The `pv=`, `hvm=`, `msr-sc=`, `rsb=`, `verw=`, `ibpb-entry=` and `bhb-entry=`
-options offer fine grained control over the primitives by Xen.  These impact
-Xen's ability to protect itself, and/or Xen's ability to virtualise support
-for guests to use.
+The `pv=`, `hvm=`, `msr-sc=`, `rsb=`, `verw=`, `ibpb-entry=`, `bhb-entry=` and
+`asi=` options offer fine grained control over the primitives by Xen.  These

Here, ahead of "by Xen", it looks like "used" was missing. Maybe a good opportunity to add it?

docs/misc/xen-command-line.pandoc for guests to use. · line 2456

Quoted 9 lines
docs/misc/xen-command-line.pandoc +5 -0
@@ -2449,6 +2449,11 @@ for guests to use.
   is not available (see `bhi-dis-s`).  The choice of scrubbing sequence can be
   selected using the `bhb-seq=` option.  If it is necessary to protect dom0
   too, boot with `spec-ctrl=bhb-entry`.
+* `asi=` offers control over whether the hypervisor will engage in Address
+  Space Isolation, by not having sensitive information mapped in the VMM
+  page-tables.  Not having sensitive information on the page-tables avoids
+  having to perform some mitigations for speculative attacks when
+  context-switching to the hypervisor.

Is "not having" and ...

xen/arch/x86/include/asm/domain.h struct arch_domain · line 462

Quoted 8 lines
xen/arch/x86/include/asm/domain.h +2 -0
@@ -458,6 +458,9 @@ struct arch_domain
     /* Don't unconditionally inject #GP for unhandled MSRs. */
     bool msr_relaxed;
 
+    /* Run the guest without sensitive information in the VMM page-tables. */
+    bool asi;

... "without" really going to be fully true? Wouldn't we better say "as little as possible" or alike?

xen/arch/x86/include/asm/domain.h static int __init cf_check parse_spec_ctrl(const char *s) · line 157

Quoted 11 lines
xen/arch/x86/include/asm/domain.h +4 -0
@@ -143,6 +148,10 @@ static int __init cf_check parse_spec_ctrl(const char *s)
             opt_unpriv_mmio = false;
             opt_gds_mit = 0;
             opt_div_scrub = 0;
+
+            opt_asi_pv = 0;
+            opt_asi_hwdom = 0;
+            opt_asi_hvm = 0;
         }
         else if ( val > 0 )
             rc = -EINVAL;

I'm frequently in trouble when deciding where the split between "=no" and "=xen" should be. opt_xpti_* are cleared ahead of the disable_common label; considering the similarity I wonder whether the same should be true for ASI (as this is also or even mainly about protecting guests from one another), or whether the XPTI placement is actually wrong.

xen/arch/x86/include/asm/domain.h int8_t __ro_after_init opt_xpti_domu = -1; · line 414

Quoted 6 lines
xen/arch/x86/include/asm/domain.h +2 -0
@@ -378,6 +410,13 @@ int8_t __ro_after_init opt_xpti_domu = -1;
 
 static __init void xpti_init_default(void)
 {
+    ASSERT(opt_asi_pv >= 0 && opt_asi_hwdom >= 0);
+    if ( (opt_xpti_hwdom == 1 || opt_xpti_domu == 1) && opt_asi_pv == 1 )

There is a separate opt_asi_hwdom which isn't used here, but only ...

Quoted 9 lines
xen/arch/x86/include/asm/domain.h +5 -0
+    {
+        printk(XENLOG_ERR
+               "XPTI is incompatible with Address Space Isolation - disabling ASI\n");
+        opt_asi_pv = 0;
+    }
     if ( (boot_cpu_data.x86_vendor & (X86_VENDOR_AMD | X86_VENDOR_HYGON)) ||
          cpu_has_rdcl_no )
     {

xen/arch/x86/include/asm/domain.h static __init void xpti_init_default(void) · line 434

Quoted 9 lines
xen/arch/x86/include/asm/domain.h +2 -2
@@ -389,9 +428,9 @@ static __init void xpti_init_default(void)
     else
     {
         if ( opt_xpti_hwdom < 0 )
-            opt_xpti_hwdom = 1;
+            opt_xpti_hwdom = !opt_asi_hwdom;
         if ( opt_xpti_domu < 0 )
-            opt_xpti_domu = 1;
+            opt_xpti_domu = !opt_asi_pv;
     }

... here?

It would further seem desirable to me if opt_asi_hwdom had its default set later, when we know the kind of Dom0, such that it could be defaulted to what opt_asi_{hvm,pv} are set to. This, however, wouldn't be compatible with the use here. Perhaps the invocation of xpti_init_default() would need deferring, too.

Quoted 19 lines
xen/arch/x86/include/asm/domain.h +4 -3
@@ -643,22 +683,24 @@ static void __init print_details(enum ind_thunk thunk)
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_hvm                              ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_HVM)  ? " IBPB-entry"    : "",
-           opt_bhb_entry_hvm                         ? " BHB-entry"     : "");
+           opt_bhb_entry_hvm                         ? " BHB-entry"     : "",
+           opt_asi_hvm                               ? " ASI"           : "");
 
 #endif
 #ifdef CONFIG_PV
-    printk("  Support for PV VMs:%s%s%s%s%s%s%s\n",
+    printk("  Support for PV VMs:%s%s%s%s%s%s%s%s\n",
            (boot_cpu_has(X86_FEATURE_SC_MSR_PV) ||
             boot_cpu_has(X86_FEATURE_SC_RSB_PV) ||
             boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV) ||
-            opt_bhb_entry_pv ||
+            opt_bhb_entry_pv || opt_asi_pv ||
             opt_eager_fpu || opt_verw_pv)            ? ""               : " None",
            boot_cpu_has(X86_FEATURE_SC_MSR_PV)       ? " MSR_SPEC_CTRL" : "",

xen/arch/x86/include/asm/domain.h static void __init print_details(enum ind_thunk thunk) · line 706

Quoted 10 lines
xen/arch/x86/include/asm/domain.h +2 -1
            boot_cpu_has(X86_FEATURE_SC_RSB_PV)       ? " RSB"           : "",
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_pv                               ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV)   ? " IBPB-entry"    : "",
-           opt_bhb_entry_pv                          ? " BHB-entry"     : "");
+           opt_bhb_entry_pv                          ? " BHB-entry"     : "",
+           opt_asi_pv                                ? " ASI"           : "");
 
     printk("  XPTI (64-bit PV only): Dom0 %s, DomU %s (with%s PCID)\n",
            opt_xpti_hwdom ? "enabled" : "disabled",

Should this printk() perhaps be suppressed when ASI is in use?

Jan

#38 lore raw

Re: [PATCH 12/22] x86/spec-ctrl: introduce Address Space Isolation command line option

Quoted 5 lines · Jan Beulich
Quoted 4 lines · Roger Pau Monne
docs/misc/xen-command-line.pandoc +0 -0
@@ -2387,7 +2387,7 @@ By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`).
 
Quoted 10 lines

docs/misc/xen-command-line.pandoc By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`). · line 2390

Quoted 4 lines
docs/misc/xen-command-line.pandoc +1 -1
 ### spec-ctrl (x86)
 > `= List of [ <bool>, xen=<bool>, {pv,hvm}=<bool>,
->              {msr-sc,rsb,verw,{ibpb,bhb}-entry}=<bool>|{pv,hvm}=<bool>,
+>              {msr-sc,rsb,verw,{ibpb,bhb}-entry,asi}=<bool>|{pv,hvm}=<bool>,

Is it really appropriate to hide this underneath an x86-only option? Even of other architectures won't support it right away, they surely will want to down the road? In which case making as much of this common right away is probably the best we can do. This goes along with the question whether, like e.g. "xpti", this should be a top-level option.

I think it's better placed in spec-ctrl as it's a speculation mitigation. I can see your point about sharing with other arches, maybe when that's needed we can introduce a generic parser of spec-ctrl options?

It might end up needing slightly different processing for arches different than x86, as for x86 it should be possible to enable the option only for PV or HVM domains, while for other arches this might make no sense for not having PV support.

Quoted 4 lines
Quoted 4 lines
docs/misc/xen-command-line.pandoc +0 -0
@@ -2414,10 +2414,10 @@ in place for guests to use.
 
 Use of a positive boolean value for either of these options is invalid.
 
Quoted 9 lines

docs/misc/xen-command-line.pandoc in place for guests to use. · line 2418

Quoted 6 lines
docs/misc/xen-command-line.pandoc +2 -4
-The `pv=`, `hvm=`, `msr-sc=`, `rsb=`, `verw=`, `ibpb-entry=` and `bhb-entry=`
-options offer fine grained control over the primitives by Xen.  These impact
-Xen's ability to protect itself, and/or Xen's ability to virtualise support
-for guests to use.
+The `pv=`, `hvm=`, `msr-sc=`, `rsb=`, `verw=`, `ibpb-entry=`, `bhb-entry=` and
+`asi=` options offer fine grained control over the primitives by Xen.  These

Here, ahead of "by Xen", it looks like "used" was missing. Maybe a good opportunity to add it?

Oh, yes.

Quoted 18 lines

docs/misc/xen-command-line.pandoc for guests to use. · line 2456

Quoted 9 lines
docs/misc/xen-command-line.pandoc +5 -0
@@ -2449,6 +2449,11 @@ for guests to use.
   is not available (see `bhi-dis-s`).  The choice of scrubbing sequence can be
   selected using the `bhb-seq=` option.  If it is necessary to protect dom0
   too, boot with `spec-ctrl=bhb-entry`.
+* `asi=` offers control over whether the hypervisor will engage in Address
+  Space Isolation, by not having sensitive information mapped in the VMM
+  page-tables.  Not having sensitive information on the page-tables avoids
+  having to perform some mitigations for speculative attacks when
+  context-switching to the hypervisor.

Is "not having" and ...

Quoted 6 lines
xen/arch/x86/include/asm/domain.h +0 -0
@@ -458,6 +458,9 @@ struct arch_domain
     /* Don't unconditionally inject #GP for unhandled MSRs. */
     bool msr_relaxed;
 
Quoted 5 lines

xen/arch/x86/include/asm/domain.h struct arch_domain · line 462

Quoted 2 lines
xen/arch/x86/include/asm/domain.h +2 -0
+    /* Run the guest without sensitive information in the VMM page-tables. */
+    bool asi;

... "without" really going to be fully true? Wouldn't we better say "as little as possible" or alike?

Maybe better use:

"...by not having sensitive information permanently mapped..."

And a similar adjustment to the comment?

The key point is that we would only map sensitive information transiently IMO.

Quoted 9 lines
Quoted 9 lines
xen/arch/x86/include/asm/domain.h +4 -0
@@ -143,6 +148,10 @@ static int __init cf_check parse_spec_ctrl(const char *s)
             opt_unpriv_mmio = false;
             opt_gds_mit = 0;
             opt_div_scrub = 0;
+
+            opt_asi_pv = 0;
+            opt_asi_hwdom = 0;
+            opt_asi_hvm = 0;
         }
Quoted 8 lines

xen/arch/x86/include/asm/domain.h static int __init cf_check parse_spec_ctrl(const char *s) · line 157

Quoted 2 lines
xen/arch/x86/include/asm/domain.h +0 -0
         else if ( val > 0 )
             rc = -EINVAL;

I'm frequently in trouble when deciding where the split between "=no" and "=xen" should be. opt_xpti_* are cleared ahead of the disable_common label; considering the similarity I wonder whether the same should be true for ASI (as this is also or even mainly about protecting guests from one another), or whether the XPTI placement is actually wrong.

Hm, that's a difficult one. ASI is a Xen implemented mitigation, so it should be turned off when spec-ctrl=no-xen is used according to the description of the option:

"spec-ctrl=no-xen can be used to turn off all of Xen’s mitigations"

OTOH, there's no "virtualisation support in place for guests to use" when no-xen is used.

I have to admin the description for that option is not obviously clear to me, so

Quoted 8 lines

xen/arch/x86/include/asm/domain.h int8_t __ro_after_init opt_xpti_domu = -1; · line 414

Quoted 6 lines
xen/arch/x86/include/asm/domain.h +2 -0
@@ -378,6 +410,13 @@ int8_t __ro_after_init opt_xpti_domu = -1;
 
 static __init void xpti_init_default(void)
 {
+    ASSERT(opt_asi_pv >= 0 && opt_asi_hwdom >= 0);
+    if ( (opt_xpti_hwdom == 1 || opt_xpti_domu == 1) && opt_asi_pv == 1 )

There is a separate opt_asi_hwdom which isn't used here, but only ...

opt_asi_pv (and opt_asi_hvm) must be set for opt_asi_hwdom to also be set. XPTI is sligtly different, in that XPTI could be set only for the hwdom by using xpti=dom0.

Quoted 21 lines
Quoted 9 lines
xen/arch/x86/include/asm/domain.h +5 -0
+    {
+        printk(XENLOG_ERR
+               "XPTI is incompatible with Address Space Isolation - disabling ASI\n");
+        opt_asi_pv = 0;
+    }
     if ( (boot_cpu_data.x86_vendor & (X86_VENDOR_AMD | X86_VENDOR_HYGON)) ||
          cpu_has_rdcl_no )
     {

xen/arch/x86/include/asm/domain.h static __init void xpti_init_default(void) · line 434

Quoted 9 lines
xen/arch/x86/include/asm/domain.h +2 -2
@@ -389,9 +428,9 @@ static __init void xpti_init_default(void)
     else
     {
         if ( opt_xpti_hwdom < 0 )
-            opt_xpti_hwdom = 1;
+            opt_xpti_hwdom = !opt_asi_hwdom;
         if ( opt_xpti_domu < 0 )
-            opt_xpti_domu = 1;
+            opt_xpti_domu = !opt_asi_pv;
     }

... here?

Quoted 5 lines

It would further seem desirable to me if opt_asi_hwdom had its default set later, when we know the kind of Dom0, such that it could be defaulted to what opt_asi_{hvm,pv} are set to. This, however, wouldn't be compatible with the use here. Perhaps the invocation of xpti_init_default() would need deferring, too.

Given the current parsing logic, opt_asi_hwdom will only be set when both opt_asi_{hvm,pv} are set. Setting spec-ctrl=asi={pv,hvm} will only enable ASI for the domUs of the selected mode.

Hence deferring won't make any practical difference, as having opt_asi_hwdom enabled implies having ASI enabled for all domain types.

I think the most common case is either having ASI enabled everywhere, or having ASI enabled only for domUs and the speculation mitigations also disabled for the hw domain.

Quoted 27 lines
Quoted 27 lines
xen/arch/x86/include/asm/domain.h +6 -4
@@ -643,22 +683,24 @@ static void __init print_details(enum ind_thunk thunk)
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_hvm                              ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_HVM)  ? " IBPB-entry"    : "",
-           opt_bhb_entry_hvm                         ? " BHB-entry"     : "");
+           opt_bhb_entry_hvm                         ? " BHB-entry"     : "",
+           opt_asi_hvm                               ? " ASI"           : "");
 
 #endif
 #ifdef CONFIG_PV
-    printk("  Support for PV VMs:%s%s%s%s%s%s%s\n",
+    printk("  Support for PV VMs:%s%s%s%s%s%s%s%s\n",
            (boot_cpu_has(X86_FEATURE_SC_MSR_PV) ||
             boot_cpu_has(X86_FEATURE_SC_RSB_PV) ||
             boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV) ||
-            opt_bhb_entry_pv ||
+            opt_bhb_entry_pv || opt_asi_pv ||
             opt_eager_fpu || opt_verw_pv)            ? ""               : " None",
            boot_cpu_has(X86_FEATURE_SC_MSR_PV)       ? " MSR_SPEC_CTRL" : "",
            boot_cpu_has(X86_FEATURE_SC_RSB_PV)       ? " RSB"           : "",
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_pv                               ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV)   ? " IBPB-entry"    : "",
-           opt_bhb_entry_pv                          ? " BHB-entry"     : "");
+           opt_bhb_entry_pv                          ? " BHB-entry"     : "",
+           opt_asi_pv                                ? " ASI"           : "");
 
Quoted 4 lines

xen/arch/x86/include/asm/domain.h static void __init print_details(enum ind_thunk thunk) · line 706

Quoted 2 lines
xen/arch/x86/include/asm/domain.h +0 -0
     printk("  XPTI (64-bit PV only): Dom0 %s, DomU %s (with%s PCID)\n",
            opt_xpti_hwdom ? "enabled" : "disabled",

Should this printk() perhaps be suppressed when ASI is in use?

Maybe, I found it useful during development to ensure the logic was correct, but I guess it's not of much use for plain users. I will make the printing conditional to ASI not being uniformly enabled.

Maybe it would be useful to unify XPTI printing with the rest of mitigations listed in the "Support for PV VMs:" line? Albeit that would drop the signaling of opt_xpti_hwdom.

Thanks, Roger.

#39 lore raw

Re: [PATCH 12/22] x86/spec-ctrl: introduce Address Space Isolation command line option

Quoted 17 lines · Roger Pau Monné
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Roger Pau Monne
docs/misc/xen-command-line.pandoc +0 -0
@@ -2387,7 +2387,7 @@ By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`).
 
Quoted 10 lines

docs/misc/xen-command-line.pandoc By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`). · line 2390

Quoted 4 lines
docs/misc/xen-command-line.pandoc +1 -1
 ### spec-ctrl (x86)
 > `= List of [ <bool>, xen=<bool>, {pv,hvm}=<bool>,
->              {msr-sc,rsb,verw,{ibpb,bhb}-entry}=<bool>|{pv,hvm}=<bool>,
+>              {msr-sc,rsb,verw,{ibpb,bhb}-entry,asi}=<bool>|{pv,hvm}=<bool>,

Is it really appropriate to hide this underneath an x86-only option? Even of other architectures won't support it right away, they surely will want to down the road? In which case making as much of this common right away is probably the best we can do. This goes along with the question whether, like e.g. "xpti", this should be a top-level option.

Quoted 2 lines

I think it's better placed in spec-ctrl as it's a speculation mitigation.

As is XPTI.

Quoted 3 lines

I can see your point about sharing with other arches,
maybe when that's needed we can introduce a generic parser of spec-ctrl options?

Not sure how much could be generalized there.

Quoted 24 lines
Quoted 18 lines

docs/misc/xen-command-line.pandoc for guests to use. · line 2456

Quoted 9 lines
docs/misc/xen-command-line.pandoc +5 -0
@@ -2449,6 +2449,11 @@ for guests to use.
   is not available (see `bhi-dis-s`).  The choice of scrubbing sequence can be
   selected using the `bhb-seq=` option.  If it is necessary to protect dom0
   too, boot with `spec-ctrl=bhb-entry`.
+* `asi=` offers control over whether the hypervisor will engage in Address
+  Space Isolation, by not having sensitive information mapped in the VMM
+  page-tables.  Not having sensitive information on the page-tables avoids
+  having to perform some mitigations for speculative attacks when
+  context-switching to the hypervisor.

Is "not having" and ...

Quoted 6 lines
xen/arch/x86/include/asm/domain.h +0 -0
@@ -458,6 +458,9 @@ struct arch_domain
     /* Don't unconditionally inject #GP for unhandled MSRs. */
     bool msr_relaxed;
 
Quoted 5 lines

xen/arch/x86/include/asm/domain.h struct arch_domain · line 462

Quoted 2 lines
xen/arch/x86/include/asm/domain.h +2 -0
+    /* Run the guest without sensitive information in the VMM page-tables. */
+    bool asi;

... "without" really going to be fully true? Wouldn't we better say "as little as possible" or alike?

Quoted 5 lines

Maybe better use:

"...by not having sensitive information permanently mapped..."

And a similar adjustment to the comment?

Yes, that's better.

Quoted 18 lines
Quoted 9 lines
Quoted 9 lines
xen/arch/x86/include/asm/domain.h +4 -0
@@ -143,6 +148,10 @@ static int __init cf_check parse_spec_ctrl(const char *s)
             opt_unpriv_mmio = false;
             opt_gds_mit = 0;
             opt_div_scrub = 0;
+
+            opt_asi_pv = 0;
+            opt_asi_hwdom = 0;
+            opt_asi_hvm = 0;
         }
Quoted 8 lines

xen/arch/x86/include/asm/domain.h static int __init cf_check parse_spec_ctrl(const char *s) · line 157

Quoted 2 lines
xen/arch/x86/include/asm/domain.h +0 -0
         else if ( val > 0 )
             rc = -EINVAL;

I'm frequently in trouble when deciding where the split between "=no" and "=xen" should be. opt_xpti_* are cleared ahead of the disable_common label; considering the similarity I wonder whether the same should be true for ASI (as this is also or even mainly about protecting guests from one another), or whether the XPTI placement is actually wrong.

Quoted 5 lines

Hm, that's a difficult one. ASI is a Xen implemented mitigation, so it should be turned off when spec-ctrl=no-xen is used according to the description of the option:

"spec-ctrl=no-xen can be used to turn off all of Xen’s mitigations"

Meaning (aiui) mitigations to protect Xen itself.

Quoted 9 lines
Quoted 8 lines

xen/arch/x86/include/asm/domain.h int8_t __ro_after_init opt_xpti_domu = -1; · line 414

Quoted 6 lines
xen/arch/x86/include/asm/domain.h +2 -0
@@ -378,6 +410,13 @@ int8_t __ro_after_init opt_xpti_domu = -1;
 
 static __init void xpti_init_default(void)
 {
+    ASSERT(opt_asi_pv >= 0 && opt_asi_hwdom >= 0);
+    if ( (opt_xpti_hwdom == 1 || opt_xpti_domu == 1) && opt_asi_pv == 1 )

There is a separate opt_asi_hwdom which isn't used here, but only ...

Quoted 3 lines

opt_asi_pv (and opt_asi_hvm) must be set for opt_asi_hwdom to also be set. XPTI is sligtly different, in that XPTI could be set only for the hwdom by using xpti=dom0.

Hmm, I didn't even notice this oddity (as it feels to me) in parsing. From the doc provided it wouldn't occur to me that e.g. "asi=pv" won't affect a PV Dom0. That's (iirc) specifically why "xpti=" has a "hwdom" sub-option.

Quoted 19 lines
Quoted 13 lines

xen/arch/x86/include/asm/domain.h static __init void xpti_init_default(void) · line 434

Quoted 10 lines
xen/arch/x86/include/asm/domain.h +2 -2
@@ -389,9 +428,9 @@ static __init void xpti_init_default(void)
     else
     {
         if ( opt_xpti_hwdom < 0 )
-            opt_xpti_hwdom = 1;
+            opt_xpti_hwdom = !opt_asi_hwdom;
         if ( opt_xpti_domu < 0 )
-            opt_xpti_domu = 1;
+            opt_xpti_domu = !opt_asi_pv;
     }

... here?

Quoted 5 lines

It would further seem desirable to me if opt_asi_hwdom had its default set later, when we know the kind of Dom0, such that it could be defaulted to what opt_asi_{hvm,pv} are set to. This, however, wouldn't be compatible with the use here. Perhaps the invocation of xpti_init_default() would need deferring, too.

Quoted 7 lines

Given the current parsing logic, opt_asi_hwdom will only be set when both opt_asi_{hvm,pv} are set. Setting spec-ctrl=asi={pv,hvm} will only enable ASI for the domUs of the selected mode.

Hence deferring won't make any practical difference, as having opt_asi_hwdom enabled implies having ASI enabled for all domain types.

Right, another effect of me not having paid enough attention to that parsing detail.

Quoted 32 lines
Quoted 27 lines
Quoted 27 lines
xen/arch/x86/include/asm/domain.h +6 -4
@@ -643,22 +683,24 @@ static void __init print_details(enum ind_thunk thunk)
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_hvm                              ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_HVM)  ? " IBPB-entry"    : "",
-           opt_bhb_entry_hvm                         ? " BHB-entry"     : "");
+           opt_bhb_entry_hvm                         ? " BHB-entry"     : "",
+           opt_asi_hvm                               ? " ASI"           : "");
 
 #endif
 #ifdef CONFIG_PV
-    printk("  Support for PV VMs:%s%s%s%s%s%s%s\n",
+    printk("  Support for PV VMs:%s%s%s%s%s%s%s%s\n",
            (boot_cpu_has(X86_FEATURE_SC_MSR_PV) ||
             boot_cpu_has(X86_FEATURE_SC_RSB_PV) ||
             boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV) ||
-            opt_bhb_entry_pv ||
+            opt_bhb_entry_pv || opt_asi_pv ||
             opt_eager_fpu || opt_verw_pv)            ? ""               : " None",
            boot_cpu_has(X86_FEATURE_SC_MSR_PV)       ? " MSR_SPEC_CTRL" : "",
            boot_cpu_has(X86_FEATURE_SC_RSB_PV)       ? " RSB"           : "",
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_pv                               ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV)   ? " IBPB-entry"    : "",
-           opt_bhb_entry_pv                          ? " BHB-entry"     : "");
+           opt_bhb_entry_pv                          ? " BHB-entry"     : "",
+           opt_asi_pv                                ? " ASI"           : "");
 
Quoted 4 lines

xen/arch/x86/include/asm/domain.h static void __init print_details(enum ind_thunk thunk) · line 706

Quoted 2 lines
xen/arch/x86/include/asm/domain.h +0 -0
     printk("  XPTI (64-bit PV only): Dom0 %s, DomU %s (with%s PCID)\n",
            opt_xpti_hwdom ? "enabled" : "disabled",

Should this printk() perhaps be suppressed when ASI is in use?

Quoted 7 lines

Maybe, I found it useful during development to ensure the logic was correct, but I guess it's not of much use for plain users. I will make the printing conditional to ASI not being uniformly enabled.

Maybe it would be useful to unify XPTI printing with the rest of mitigations listed in the "Support for PV VMs:" line? Albeit that would drop the signaling of opt_xpti_hwdom.

Which is why I wouldn't want to "unify" it.

Jan

#40 lore raw

Re: [PATCH 12/22] x86/spec-ctrl: introduce Address Space Isolation command line option

Quoted 18 lines · Jan Beulich
Quoted 17 lines · Roger Pau Monné
Quoted 15 lines · Jan Beulich

docs/misc/xen-command-line.pandoc By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`). · line 2390

Quoted 8 lines · Roger Pau Monne
docs/misc/xen-command-line.pandoc +1 -1
@@ -2387,7 +2387,7 @@ By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`).
 
 ### spec-ctrl (x86)
 > `= List of [ <bool>, xen=<bool>, {pv,hvm}=<bool>,
->              {msr-sc,rsb,verw,{ibpb,bhb}-entry}=<bool>|{pv,hvm}=<bool>,
+>              {msr-sc,rsb,verw,{ibpb,bhb}-entry,asi}=<bool>|{pv,hvm}=<bool>,

Is it really appropriate to hide this underneath an x86-only option? Even of other architectures won't support it right away, they surely will want to down the road? In which case making as much of this common right away is probably the best we can do. This goes along with the question whether, like e.g. "xpti", this should be a top-level option.

Quoted 4 lines
Quoted 2 lines

I think it's better placed in spec-ctrl as it's a speculation mitigation.

As is XPTI.

But XPTI predates the introduction of spec-ctrl option, I assumed that's why xpti is not part of spec-ctrl.

Quoted 5 lines
Quoted 3 lines

I can see your point about sharing with other arches,
maybe when that's needed we can introduce a generic parser of spec-ctrl options?

Not sure how much could be generalized there.

Oh, so your point was not about sharing the parsing code, but sharing the command line documentation about it, sorry, I missed that.

Along the lines of:

asi= boolean | { pv, hvm, hwdom }

Or similar?

Even then sub-options would likely be different between architectures.

Quoted 18 lines
Quoted 18 lines
Quoted 17 lines

docs/misc/xen-command-line.pandoc static int __init cf_check parse_spec_ctrl(const char *s) · line 157

Quoted 11 lines
docs/misc/xen-command-line.pandoc +4 -0
@@ -143,6 +148,10 @@ static int __init cf_check parse_spec_ctrl(const char *s)
             opt_unpriv_mmio = false;
             opt_gds_mit = 0;
             opt_div_scrub = 0;
+
+            opt_asi_pv = 0;
+            opt_asi_hwdom = 0;
+            opt_asi_hvm = 0;
         }
         else if ( val > 0 )
             rc = -EINVAL;

I'm frequently in trouble when deciding where the split between "=no" and "=xen" should be. opt_xpti_* are cleared ahead of the disable_common label; considering the similarity I wonder whether the same should be true for ASI (as this is also or even mainly about protecting guests from one another), or whether the XPTI placement is actually wrong.

Quoted 7 lines
Quoted 5 lines

Hm, that's a difficult one. ASI is a Xen implemented mitigation, so it should be turned off when spec-ctrl=no-xen is used according to the description of the option:

"spec-ctrl=no-xen can be used to turn off all of Xen’s mitigations"

Meaning (aiui) mitigations to protect Xen itself.

So that would speculation attacks that take place in Xen context, which is what ASI would protect against?

I don't have a strong opinion, but I also have a hard time seeing what should no-xen disable.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

docs/misc/xen-command-line.pandoc int8_t __ro_after_init opt_xpti_domu = -1; · line 414

Quoted 6 lines
docs/misc/xen-command-line.pandoc +2 -0
@@ -378,6 +410,13 @@ int8_t __ro_after_init opt_xpti_domu = -1;
 
 static __init void xpti_init_default(void)
 {
+    ASSERT(opt_asi_pv >= 0 && opt_asi_hwdom >= 0);
+    if ( (opt_xpti_hwdom == 1 || opt_xpti_domu == 1) && opt_asi_pv == 1 )

There is a separate opt_asi_hwdom which isn't used here, but only ...

Quoted 8 lines
Quoted 3 lines

opt_asi_pv (and opt_asi_hvm) must be set for opt_asi_hwdom to also be set. XPTI is sligtly different, in that XPTI could be set only for the hwdom by using xpti=dom0.

Hmm, I didn't even notice this oddity (as it feels to me) in parsing. From the doc provided it wouldn't occur to me that e.g. "asi=pv" won't affect a PV Dom0. That's (iirc) specifically why "xpti=" has a "hwdom" sub-option.

It seems to be like that for all spec-ctrl options, see bhb-entry for example.

Quoted 36 lines
Quoted 36 lines
Quoted 27 lines
Quoted 27 lines
docs/misc/xen-command-line.pandoc +6 -4
@@ -643,22 +683,24 @@ static void __init print_details(enum ind_thunk thunk)
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_hvm                              ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_HVM)  ? " IBPB-entry"    : "",
-           opt_bhb_entry_hvm                         ? " BHB-entry"     : "");
+           opt_bhb_entry_hvm                         ? " BHB-entry"     : "",
+           opt_asi_hvm                               ? " ASI"           : "");
 
 #endif
 #ifdef CONFIG_PV
-    printk("  Support for PV VMs:%s%s%s%s%s%s%s\n",
+    printk("  Support for PV VMs:%s%s%s%s%s%s%s%s\n",
            (boot_cpu_has(X86_FEATURE_SC_MSR_PV) ||
             boot_cpu_has(X86_FEATURE_SC_RSB_PV) ||
             boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV) ||
-            opt_bhb_entry_pv ||
+            opt_bhb_entry_pv || opt_asi_pv ||
             opt_eager_fpu || opt_verw_pv)            ? ""               : " None",
            boot_cpu_has(X86_FEATURE_SC_MSR_PV)       ? " MSR_SPEC_CTRL" : "",
            boot_cpu_has(X86_FEATURE_SC_RSB_PV)       ? " RSB"           : "",
            opt_eager_fpu                             ? " EAGER_FPU"     : "",
            opt_verw_pv                               ? " VERW"          : "",
            boot_cpu_has(X86_FEATURE_IBPB_ENTRY_PV)   ? " IBPB-entry"    : "",
-           opt_bhb_entry_pv                          ? " BHB-entry"     : "");
+           opt_bhb_entry_pv                          ? " BHB-entry"     : "",
+           opt_asi_pv                                ? " ASI"           : "");
 
Quoted 4 lines

docs/misc/xen-command-line.pandoc static void __init print_details(enum ind_thunk thunk) · line 706

Quoted 2 lines
docs/misc/xen-command-line.pandoc +0 -0
     printk("  XPTI (64-bit PV only): Dom0 %s, DomU %s (with%s PCID)\n",
            opt_xpti_hwdom ? "enabled" : "disabled",

Should this printk() perhaps be suppressed when ASI is in use?

Maybe, I found it useful during development to ensure the logic was correct, but I guess it's not of much use for plain users. I will make the printing conditional to ASI not being uniformly enabled.

Quoted 5 lines
Quoted 3 lines

Maybe it would be useful to unify XPTI printing with the rest of mitigations listed in the "Support for PV VMs:" line? Albeit that would drop the signaling of opt_xpti_hwdom.

Which is why I wouldn't want to "unify" it.

Right I will avoid printing the line if ASI is uniformly enabled.

Thanks, Roger.

#41 lore raw

Re: [PATCH 12/22] x86/spec-ctrl: introduce Address Space Isolation command line option

Quoted 27 lines · Roger Pau Monné
Quoted 18 lines · Jan Beulich
Quoted 17 lines · Roger Pau Monné
Quoted 15 lines · Jan Beulich

docs/misc/xen-command-line.pandoc By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`). · line 2390

Quoted 8 lines · Roger Pau Monne
docs/misc/xen-command-line.pandoc +1 -1
@@ -2387,7 +2387,7 @@ By default SSBD will be mitigated at runtime (i.e `ssbd=runtime`).
 
 ### spec-ctrl (x86)
 > `= List of [ <bool>, xen=<bool>, {pv,hvm}=<bool>,
->              {msr-sc,rsb,verw,{ibpb,bhb}-entry}=<bool>|{pv,hvm}=<bool>,
+>              {msr-sc,rsb,verw,{ibpb,bhb}-entry,asi}=<bool>|{pv,hvm}=<bool>,

Is it really appropriate to hide this underneath an x86-only option? Even of other architectures won't support it right away, they surely will want to down the road? In which case making as much of this common right away is probably the best we can do. This goes along with the question whether, like e.g. "xpti", this should be a top-level option.

Quoted 4 lines
Quoted 2 lines

I think it's better placed in spec-ctrl as it's a speculation mitigation.

As is XPTI.

But XPTI predates the introduction of spec-ctrl option, I assumed that's why xpti is not part of spec-ctrl.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

I can see your point about sharing with other arches,
maybe when that's needed we can introduce a generic parser of spec-ctrl options?

Not sure how much could be generalized there.

Oh, so your point was not about sharing the parsing code, but sharing the command line documentation about it, sorry, I missed that.

My point was really to share as much as possible, if this was a top-level option. Of course ...

Quoted 7 lines

Along the lines of:

asi= boolean | { pv, hvm, hwdom }

Or similar?

Even then sub-options would likely be different between architectures.

... the sub-options wouldn't all be generalizable.

Quoted 24 lines
Quoted 24 lines
Quoted 23 lines
Quoted 9 lines
Quoted 9 lines
docs/misc/xen-command-line.pandoc +4 -0
@@ -143,6 +148,10 @@ static int __init cf_check parse_spec_ctrl(const char *s)
             opt_unpriv_mmio = false;
             opt_gds_mit = 0;
             opt_div_scrub = 0;
+
+            opt_asi_pv = 0;
+            opt_asi_hwdom = 0;
+            opt_asi_hvm = 0;
         }
Quoted 8 lines

docs/misc/xen-command-line.pandoc static int __init cf_check parse_spec_ctrl(const char *s) · line 157

Quoted 2 lines
docs/misc/xen-command-line.pandoc +0 -0
         else if ( val > 0 )
             rc = -EINVAL;

I'm frequently in trouble when deciding where the split between "=no" and "=xen" should be. opt_xpti_* are cleared ahead of the disable_common label; considering the similarity I wonder whether the same should be true for ASI (as this is also or even mainly about protecting guests from one another), or whether the XPTI placement is actually wrong.

Hm, that's a difficult one. ASI is a Xen implemented mitigation, so it should be turned off when spec-ctrl=no-xen is used according to the description of the option:

"spec-ctrl=no-xen can be used to turn off all of Xen’s mitigations"

Quoted 7 lines
Quoted 1 line

Meaning (aiui) mitigations to protect Xen itself.

So that would speculation attacks that take place in Xen context, which is what ASI would protect against?

I don't have a strong opinion, but I also have a hard time seeing what should no-xen disable.

I wonder whether Andrew knows of a clear way of expressing where that line is intended to be drawn.

Quoted 13 lines
Quoted 13 lines
Quoted 12 lines
Quoted 8 lines

docs/misc/xen-command-line.pandoc int8_t __ro_after_init opt_xpti_domu = -1; · line 414

Quoted 6 lines
docs/misc/xen-command-line.pandoc +2 -0
@@ -378,6 +410,13 @@ int8_t __ro_after_init opt_xpti_domu = -1;
 
 static __init void xpti_init_default(void)
 {
+    ASSERT(opt_asi_pv >= 0 && opt_asi_hwdom >= 0);
+    if ( (opt_xpti_hwdom == 1 || opt_xpti_domu == 1) && opt_asi_pv == 1 )

There is a separate opt_asi_hwdom which isn't used here, but only ...

opt_asi_pv (and opt_asi_hvm) must be set for opt_asi_hwdom to also be set. XPTI is sligtly different, in that XPTI could be set only for the hwdom by using xpti=dom0.

Quoted 7 lines
Quoted 4 lines

Hmm, I didn't even notice this oddity (as it feels to me) in parsing. From the doc provided it wouldn't occur to me that e.g. "asi=pv" won't affect a PV Dom0. That's (iirc) specifically why "xpti=" has a "hwdom" sub-option.

It seems to be like that for all spec-ctrl options, see bhb-entry for example.

Hmm, indeed.

Jan

#42 lore raw

PATCH 13/22 x86/hvm: use a per-pCPU monitor table in HAP mode

In reply to Roger Pau Monne

Instead of allocating a monitor table for each vCPU when running in HVM HAP mode, use a per-pCPU monitor table, which gets the per-domain slot updated on guest context switch.

This limits the amount of memory used for HVM HAP monitor tables to the amount of active pCPUs, rather than to the number of vCPUs. It also simplifies vCPU allocation and teardown, since the monitor table handling is removed from there.

Note the switch to using a per-CPU monitor table is done regardless of whether Address Space Isolation is enabled or not. Partly for the memory usage reduction, and also because it allows to simplify the VM tear down path by not having to cleanup the per-vCPU monitor tables.

---
Note the monitor table is not made static because uses outside of the file where it's defined will be added by further patches.

---
 xen/arch/x86/hvm/hvm.c             | 60 ++++++++++++++++++++++++
 xen/arch/x86/hvm/svm/svm.c         |  5 ++
 xen/arch/x86/hvm/vmx/vmcs.c        |  1 +
 xen/arch/x86/hvm/vmx/vmx.c         |  4 ++
 xen/arch/x86/include/asm/hap.h     |  1 -
 xen/arch/x86/include/asm/hvm/hvm.h |  8 ++++
 xen/arch/x86/mm.c                  |  8 ++++
 xen/arch/x86/mm/hap/hap.c          | 75 ------------------------------
 xen/arch/x86/mm/paging.c           |  4 +-
 9 files changed, 87 insertions(+), 79 deletions(-)
xen/arch/x86/hvm/hvm.c +60 -0
index 7f4b627b1f5f..3f771bc65677 100644
@@ -104,6 +104,54 @@ static const char __initconst warning_hvm_fep[] =
 static bool __initdata opt_altp2m_enabled;
 boolean_param("altp2m", opt_altp2m_enabled);
 
+DEFINE_PER_CPU(root_pgentry_t *, monitor_pgt);
+
+static int allocate_cpu_monitor_table(unsigned int cpu)
+{
+    root_pgentry_t *pgt = alloc_xenheap_page();
+
+    if ( !pgt )
+        return -ENOMEM;
+
+    clear_page(pgt);
+
+    init_xen_l4_slots(pgt, _mfn(virt_to_mfn(pgt)), INVALID_MFN, NULL,
+                      false, true, false);
+
+    ASSERT(!per_cpu(monitor_pgt, cpu));
+    per_cpu(monitor_pgt, cpu) = pgt;
+
+    return 0;
+}
+
+static void free_cpu_monitor_table(unsigned int cpu)
+{
+    root_pgentry_t *pgt = per_cpu(monitor_pgt, cpu);
+
+    if ( !pgt )
+        return;
+
+    per_cpu(monitor_pgt, cpu) = NULL;
+    free_xenheap_page(pgt);
+}
+
+void hvm_set_cpu_monitor_table(struct vcpu *v)
+{
+    root_pgentry_t *pgt = this_cpu(monitor_pgt);
+
+    ASSERT(pgt);
+
+    setup_perdomain_slot(v, pgt);
+
+    make_cr3(v, _mfn(virt_to_mfn(pgt)));
+}
+
+void hvm_clear_cpu_monitor_table(struct vcpu *v)
+{
+    /* Poison %cr3, it will be updated when the vCPU is scheduled. */
+    make_cr3(v, INVALID_MFN);
+}
+
 static int cf_check cpu_callback(
     struct notifier_block *nfb, unsigned long action, void *hcpu)
 {
@@ -113,6 +161,9 @@ static int cf_check cpu_callback(
     switch ( action )
     {
     case CPU_UP_PREPARE:
+        rc = allocate_cpu_monitor_table(cpu);
+        if ( rc )
+            break;
         rc = alternative_call(hvm_funcs.cpu_up_prepare, cpu);
         break;
     case CPU_DYING:
@@ -121,6 +172,7 @@ static int cf_check cpu_callback(
     case CPU_UP_CANCELED:
     case CPU_DEAD:
         alternative_vcall(hvm_funcs.cpu_dead, cpu);
+        free_cpu_monitor_table(cpu);
         break;
     default:
         break;
@@ -154,6 +206,7 @@ static bool __init hap_supported(struct hvm_function_table *fns)
 static int __init cf_check hvm_enable(void)
 {
     const struct hvm_function_table *fns = NULL;
+    int rc;
 
     if ( cpu_has_vmx )
         fns = start_vmx();
@@ -205,6 +258,13 @@ static int __init cf_check hvm_enable(void)
 
     register_cpu_notifier(&cpu_nfb);
 
+    rc = allocate_cpu_monitor_table(0);
+    if ( rc )
+    {
+        printk(XENLOG_ERR "Error %d setting up HVM monitor page tables\n", rc);
+        return rc;
+    }
+
     return 0;
 }
 presmp_initcall(hvm_enable);
xen/arch/x86/hvm/svm/svm.c +5 -0
index 988250dbc154..a3fc033c0100 100644
@@ -902,6 +902,8 @@ static void cf_check svm_ctxt_switch_from(struct vcpu *v)
     if ( unlikely((read_efer() & EFER_SVME) == 0) )
         return;
 
+    hvm_clear_cpu_monitor_table(v);
+
     if ( !v->arch.fully_eager_fpu )
         svm_fpu_leave(v);
 
@@ -957,6 +959,8 @@ static void cf_check svm_ctxt_switch_to(struct vcpu *v)
         ASSERT(v->domain->arch.cpuid->extd.virt_ssbd);
         amd_set_legacy_ssbd(true);
     }
+
+    hvm_set_cpu_monitor_table(v);
 }
 
 static void noreturn cf_check svm_do_resume(void)
@@ -990,6 +994,7 @@ static void noreturn cf_check svm_do_resume(void)
         hvm_migrate_pirqs(v);
         /* Migrating to another ASID domain.  Request a new ASID. */
         hvm_asid_flush_vcpu(v);
+        hvm_update_host_cr3(v);
     }
 
     if ( !vcpu_guestmode && !vlapic_hw_disabled(vlapic) )
xen/arch/x86/hvm/vmx/vmcs.c +1 -0
index 9b6dc51f36ab..5d67c8157825 100644
@@ -1957,6 +1957,7 @@ void cf_check vmx_do_resume(void)
         v->arch.hvm.vmx.hostenv_migrated = 1;
 
         hvm_asid_flush_vcpu(v);
+        hvm_update_host_cr3(v);
     }
 
     debug_state = v->domain->debugger_attached
xen/arch/x86/hvm/vmx/vmx.c +4 -0
index cbe91c679807..5863c57b2d4a 100644
@@ -1153,6 +1153,8 @@ static void cf_check vmx_ctxt_switch_from(struct vcpu *v)
     if ( unlikely(!this_cpu(vmxon)) )
         return;
 
+    hvm_clear_cpu_monitor_table(v);
+
     if ( !v->is_running )
     {
         /*
@@ -1182,6 +1184,8 @@ static void cf_check vmx_ctxt_switch_to(struct vcpu *v)
 
     if ( v->domain->arch.hvm.pi_ops.flags & PI_CSW_TO )
         vmx_pi_switch_to(v);
+
+    hvm_set_cpu_monitor_table(v);
 }
 
 
xen/arch/x86/include/asm/hap.h +0 -1
index f01ce73fb4f3..ae6760bc2bf5 100644
@@ -24,7 +24,6 @@ int   hap_domctl(struct domain *d, struct xen_domctl_shadow_op *sc,
                  XEN_GUEST_HANDLE_PARAM(xen_domctl_t) u_domctl);
 int   hap_enable(struct domain *d, u32 mode);
 void  hap_final_teardown(struct domain *d);
-void  hap_vcpu_teardown(struct vcpu *v);
 void  hap_teardown(struct domain *d, bool *preempted);
 void  hap_vcpu_init(struct vcpu *v);
 int   hap_track_dirty_vram(struct domain *d,
xen/arch/x86/include/asm/hvm/hvm.h +8 -0
index 1c01e22c8e62..6d9a1ae04feb 100644
@@ -550,6 +550,14 @@ static inline void hvm_invlpg(struct vcpu *v, unsigned long linear)
                        (1U << X86_EXC_AC) | \
                        (1U << X86_EXC_MC))
 
+/*
+ * Setup the per-domain slots of the per-cpu monitor table and update the vCPU
+ * cr3 to use it.
+ */
+DECLARE_PER_CPU(root_pgentry_t *, monitor_pgt);
+void hvm_set_cpu_monitor_table(struct vcpu *v);
+void hvm_clear_cpu_monitor_table(struct vcpu *v);
+
 /* Called in boot/resume paths.  Must cope with no HVM support. */
 static inline int hvm_cpu_up(void)
 {
xen/arch/x86/mm.c +8 -0
index 35e929057d21..7f2666adaef4 100644
@@ -6367,6 +6367,14 @@ void setup_perdomain_slot(const struct vcpu *v, root_pgentry_t *root_pgt)
     l4e_write(&root_pgt[root_table_offset(PERDOMAIN_VIRT_START)],
               l4e_from_page(v->domain->arch.perdomain_l3_pg,
                             __PAGE_HYPERVISOR_RW));
+
+    if ( !is_pv_64bit_vcpu(v) )
+        /*
+         * HVM guests always have the compatibility L4 per-domain area because
+         * bitness is not know, and can change at runtime.
+         */
+        l4e_write(&root_pgt[root_table_offset(PERDOMAIN_ALT_VIRT_START)],
+                  root_pgt[root_table_offset(PERDOMAIN_VIRT_START)]);
 }
 
 static void __init __maybe_unused build_assertions(void)
xen/arch/x86/mm/hap/hap.c +0 -75

102 lines not on this page · raw message

xen/arch/x86/mm/paging.c +1 -3
index bca320fffabf..8ba105b5cb0c 100644
@@ -794,9 +794,7 @@ long do_paging_domctl_cont(
 
 void paging_vcpu_teardown(struct vcpu *v)
 {
-    if ( hap_enabled(v->domain) )
-        hap_vcpu_teardown(v);
-    else
+    if ( !hap_enabled(v->domain) )
         shadow_vcpu_teardown(v);
 }
 
Signature · 1 line
2.45.2
#43 lore raw

Re: [PATCH 13/22] x86/hvm: use a per-pCPU monitor table in HAP mode

Quoted 10 lines · Roger Pau Monne

Instead of allocating a monitor table for each vCPU when running in HVM HAP mode, use a per-pCPU monitor table, which gets the per-domain slot updated on guest context switch.

This limits the amount of memory used for HVM HAP monitor tables to the amount of active pCPUs, rather than to the number of vCPUs. It also simplifies vCPU allocation and teardown, since the monitor table handling is removed from there.

Note the switch to using a per-CPU monitor table is done regardless of whether

s/per-CPU/per-pCPU/

Quoted 25 lines

Address Space Isolation is enabled or not. Partly for the memory usage reduction, and also because it allows to simplify the VM tear down path by not having to cleanup the per-vCPU monitor tables.

---
Note the monitor table is not made static because uses outside of the file where it's defined will be added by further patches.

---
 xen/arch/x86/hvm/hvm.c             | 60 ++++++++++++++++++++++++
 xen/arch/x86/hvm/svm/svm.c         |  5 ++
 xen/arch/x86/hvm/vmx/vmcs.c        |  1 +
 xen/arch/x86/hvm/vmx/vmx.c         |  4 ++
 xen/arch/x86/include/asm/hap.h     |  1 -
 xen/arch/x86/include/asm/hvm/hvm.h |  8 ++++
 xen/arch/x86/mm.c                  |  8 ++++
 xen/arch/x86/mm/hap/hap.c          | 75 ------------------------------
 xen/arch/x86/mm/paging.c           |  4 +-
 9 files changed, 87 insertions(+), 79 deletions(-)
xen/arch/x86/hvm/hvm.c +0 -0
index 7f4b627b1f5f..3f771bc65677 100644

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 109

Quoted 6 lines
xen/arch/x86/hvm/hvm.c +3 -0
@@ -104,6 +104,54 @@ static const char __initconst warning_hvm_fep[] =
 static bool __initdata opt_altp2m_enabled;
 boolean_param("altp2m", opt_altp2m_enabled);
 
+DEFINE_PER_CPU(root_pgentry_t *, monitor_pgt);
+
+static int allocate_cpu_monitor_table(unsigned int cpu)

To avoid ambiguity, could we call these *_pcpu_*() instead?

Quoted 25 lines
xen/arch/x86/hvm/hvm.c +25 -0
+{
+    root_pgentry_t *pgt = alloc_xenheap_page();
+
+    if ( !pgt )
+        return -ENOMEM;
+
+    clear_page(pgt);
+
+    init_xen_l4_slots(pgt, _mfn(virt_to_mfn(pgt)), INVALID_MFN, NULL,
+                      false, true, false);
+
+    ASSERT(!per_cpu(monitor_pgt, cpu));
+    per_cpu(monitor_pgt, cpu) = pgt;
+
+    return 0;
+}
+
+static void free_cpu_monitor_table(unsigned int cpu)
+{
+    root_pgentry_t *pgt = per_cpu(monitor_pgt, cpu);
+
+    if ( !pgt )
+        return;
+
+    per_cpu(monitor_pgt, cpu) = NULL;

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 144

Quoted 10 lines
xen/arch/x86/hvm/hvm.c +10 -0
+    free_xenheap_page(pgt);
+}
+
+void hvm_set_cpu_monitor_table(struct vcpu *v)
+{
+    root_pgentry_t *pgt = this_cpu(monitor_pgt);
+
+    ASSERT(pgt);
+
+    setup_perdomain_slot(v, pgt);

Why not modify them as part of write_ptbase() instead? As it stands, it appears to be modifying the PTEs of what may very well be our current PT, which makes the perdomain slot be in a $DEITY-knows-what state until the next flush (presumably the write to cr3 in write_ptbase()?; assuming no PCIDs).

Setting the slot up right before the cr3 change should reduce the potential for misuse.

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 152

Quoted 8 lines
xen/arch/x86/hvm/hvm.c +8 -0
+
+    make_cr3(v, _mfn(virt_to_mfn(pgt)));
+}
+
+void hvm_clear_cpu_monitor_table(struct vcpu *v)
+{
+    /* Poison %cr3, it will be updated when the vCPU is scheduled. */
+    make_cr3(v, INVALID_MFN);

I think this would benefit from more exposition in the comment. If I'm getting this right, after descheduling this vCPU we can't assume it'll be rescheduled on the same pCPU, and if it's not it'll end up using a different monitor table. This poison value is meant to highlight forgetting to set cr3 in the "ctxt_switch_to()" path.

All of that can be deduced from what you wrote and sufficient headscratching but seeing how this is invoked from the context switch path it's not incredibly clear wether you meant the perdomain slot would be updated by the next vCPU or what I stated in the previous paragraph.

Assuming it is as I mentioned, maybe hvm_forget_cpu_monitor_table() would convey what it does better? i.e: the vCPU forgets/unbinds the monitor table from its internal state.

Cheers,
Alejandro

#44 lore raw

Re: [PATCH 13/22] x86/hvm: use a per-pCPU monitor table in HAP mode

Quoted 5 lines · Alejandro Vallejo
Quoted 4 lines · Roger Pau Monne

Instead of allocating a monitor table for each vCPU when running in HVM HAP mode, use a per-pCPU monitor table, which gets the per-domain slot updated on guest context switch.

Quoted 8 lines
Quoted 6 lines

This limits the amount of memory used for HVM HAP monitor tables to the amount of active pCPUs, rather than to the number of vCPUs. It also simplifies vCPU allocation and teardown, since the monitor table handling is removed from there.

Note the switch to using a per-CPU monitor table is done regardless of whether

s/per-CPU/per-pCPU/

While this adjustment is probably fine (albeit I wouldn't insist), ...

Quoted 11 lines

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 109

Quoted 9 lines
xen/arch/x86/hvm/hvm.c +3 -0
@@ -104,6 +104,54 @@ static const char __initconst warning_hvm_fep[] =
 static bool __initdata opt_altp2m_enabled;
 boolean_param("altp2m", opt_altp2m_enabled);
 
+DEFINE_PER_CPU(root_pgentry_t *, monitor_pgt);
+
+static int allocate_cpu_monitor_table(unsigned int cpu)

To avoid ambiguity, could we call these *_pcpu_*() instead?

... I can spot only very few functions with "pcpu" in their names, and I think we're also pretty clear in distinguishing vcpu from cpu. Therefore I'd rather not see any p-s added to function names.

Jan

#45 lore raw

Re: [PATCH 13/22] x86/hvm: use a per-pCPU monitor table in HAP mode

In reply to Alejandro Vallejo
Quoted 112 lines · Alejandro Vallejo
Quoted 10 lines · Roger Pau Monne

Instead of allocating a monitor table for each vCPU when running in HVM HAP mode, use a per-pCPU monitor table, which gets the per-domain slot updated on guest context switch.

This limits the amount of memory used for HVM HAP monitor tables to the amount of active pCPUs, rather than to the number of vCPUs. It also simplifies vCPU allocation and teardown, since the monitor table handling is removed from there.

Note the switch to using a per-CPU monitor table is done regardless of whether

s/per-CPU/per-pCPU/

Quoted 25 lines

Address Space Isolation is enabled or not. Partly for the memory usage reduction, and also because it allows to simplify the VM tear down path by not having to cleanup the per-vCPU monitor tables.

---
Note the monitor table is not made static because uses outside of the file where it's defined will be added by further patches.

---
 xen/arch/x86/hvm/hvm.c             | 60 ++++++++++++++++++++++++
 xen/arch/x86/hvm/svm/svm.c         |  5 ++
 xen/arch/x86/hvm/vmx/vmcs.c        |  1 +
 xen/arch/x86/hvm/vmx/vmx.c         |  4 ++
 xen/arch/x86/include/asm/hap.h     |  1 -
 xen/arch/x86/include/asm/hvm/hvm.h |  8 ++++
 xen/arch/x86/mm.c                  |  8 ++++
 xen/arch/x86/mm/hap/hap.c          | 75 ------------------------------
 xen/arch/x86/mm/paging.c           |  4 +-
 9 files changed, 87 insertions(+), 79 deletions(-)
xen/arch/x86/hvm/hvm.c +0 -0
index 7f4b627b1f5f..3f771bc65677 100644

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 109

Quoted 6 lines
xen/arch/x86/hvm/hvm.c +3 -0
@@ -104,6 +104,54 @@ static const char __initconst warning_hvm_fep[] =
 static bool __initdata opt_altp2m_enabled;
 boolean_param("altp2m", opt_altp2m_enabled);
 
+DEFINE_PER_CPU(root_pgentry_t *, monitor_pgt);
+
+static int allocate_cpu_monitor_table(unsigned int cpu)

To avoid ambiguity, could we call these *_pcpu_*() instead?

Quoted 25 lines
xen/arch/x86/hvm/hvm.c +25 -0
+{
+    root_pgentry_t *pgt = alloc_xenheap_page();
+
+    if ( !pgt )
+        return -ENOMEM;
+
+    clear_page(pgt);
+
+    init_xen_l4_slots(pgt, _mfn(virt_to_mfn(pgt)), INVALID_MFN, NULL,
+                      false, true, false);
+
+    ASSERT(!per_cpu(monitor_pgt, cpu));
+    per_cpu(monitor_pgt, cpu) = pgt;
+
+    return 0;
+}
+
+static void free_cpu_monitor_table(unsigned int cpu)
+{
+    root_pgentry_t *pgt = per_cpu(monitor_pgt, cpu);
+
+    if ( !pgt )
+        return;
+
+    per_cpu(monitor_pgt, cpu) = NULL;

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 144

Quoted 10 lines
xen/arch/x86/hvm/hvm.c +10 -0
+    free_xenheap_page(pgt);
+}
+
+void hvm_set_cpu_monitor_table(struct vcpu *v)
+{
+    root_pgentry_t *pgt = this_cpu(monitor_pgt);
+
+    ASSERT(pgt);
+
+    setup_perdomain_slot(v, pgt);

Why not modify them as part of write_ptbase() instead? As it stands, it appears to be modifying the PTEs of what may very well be our current PT, which makes the perdomain slot be in a $DEITY-knows-what state until the next flush (presumably the write to cr3 in write_ptbase()?; assuming no PCIDs).

Setting the slot up right before the cr3 change should reduce the potential for misuse.

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 152

Quoted 8 lines
xen/arch/x86/hvm/hvm.c +8 -0
+
+    make_cr3(v, _mfn(virt_to_mfn(pgt)));
+}
+
+void hvm_clear_cpu_monitor_table(struct vcpu *v)
+{
+    /* Poison %cr3, it will be updated when the vCPU is scheduled. */
+    make_cr3(v, INVALID_MFN);

I think this would benefit from more exposition in the comment. If I'm getting this right, after descheduling this vCPU we can't assume it'll be rescheduled on the same pCPU, and if it's not it'll end up using a different monitor table. This poison value is meant to highlight forgetting to set cr3 in the "ctxt_switch_to()" path.

All of that can be deduced from what you wrote and sufficient headscratching but seeing how this is invoked from the context switch path it's not incredibly clear wether you meant the perdomain slot would be updated by the next vCPU or what I stated in the previous paragraph.

Quoted 6 lines

Assuming it is as I mentioned, maybe hvm_forget_cpu_monitor_table() would convey what it does better? i.e: the vCPU forgets/unbinds the monitor table from its internal state.

Cheers,
Alejandro

After playing with the code for a while I'm becoming increasingly convinced that we don't want to tie hvm_clear_cpu_monitor_table() to the ctx_switch_to handlers at all. In __context_switch() we would ideally like to delay restoring the state until after said state is available in the page tables (i.e: after write_ptbase()).

With that division we can do saves and restores with far less headaches as we can assume that the pcpu fixmap always contains the relevant data.

Cheers,
Alejandro

#46 lore raw

Re: [PATCH 13/22] x86/hvm: use a per-pCPU monitor table in HAP mode

In reply to Alejandro Vallejo
Quoted 5 lines · Alejandro Vallejo
Quoted 4 lines · Roger Pau Monne

Instead of allocating a monitor table for each vCPU when running in HVM HAP mode, use a per-pCPU monitor table, which gets the per-domain slot updated on guest context switch.

Quoted 8 lines
Quoted 6 lines

This limits the amount of memory used for HVM HAP monitor tables to the amount of active pCPUs, rather than to the number of vCPUs. It also simplifies vCPU allocation and teardown, since the monitor table handling is removed from there.

Note the switch to using a per-CPU monitor table is done regardless of whether

s/per-CPU/per-pCPU/

Sorry, I might not has been as consistent as I wanted with using pCPU everywhere.

Quoted 28 lines
Quoted 28 lines

Address Space Isolation is enabled or not. Partly for the memory usage reduction, and also because it allows to simplify the VM tear down path by not having to cleanup the per-vCPU monitor tables.

---
Note the monitor table is not made static because uses outside of the file where it's defined will be added by further patches.

---
 xen/arch/x86/hvm/hvm.c             | 60 ++++++++++++++++++++++++
 xen/arch/x86/hvm/svm/svm.c         |  5 ++
 xen/arch/x86/hvm/vmx/vmcs.c        |  1 +
 xen/arch/x86/hvm/vmx/vmx.c         |  4 ++
 xen/arch/x86/include/asm/hap.h     |  1 -
 xen/arch/x86/include/asm/hvm/hvm.h |  8 ++++
 xen/arch/x86/mm.c                  |  8 ++++
 xen/arch/x86/mm/hap/hap.c          | 75 ------------------------------
 xen/arch/x86/mm/paging.c           |  4 +-
 9 files changed, 87 insertions(+), 79 deletions(-)
xen/arch/x86/hvm/hvm.c +0 -0
index 7f4b627b1f5f..3f771bc65677 100644
@@ -104,6 +104,54 @@ static const char __initconst warning_hvm_fep[] =
 static bool __initdata opt_altp2m_enabled;
 boolean_param("altp2m", opt_altp2m_enabled);
 
Quoted 5 lines

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 109

Quoted 3 lines
xen/arch/x86/hvm/hvm.c +3 -0
+DEFINE_PER_CPU(root_pgentry_t *, monitor_pgt);
+
+static int allocate_cpu_monitor_table(unsigned int cpu)

To avoid ambiguity, could we call these *_pcpu_*() instead?

As replied by Jan, plain 'cpu' is physical CPU on hypervisor code function names usually. '_pcpu_' here would IMO imply per-CPU, which it also is, but likely doesn't need spelling in the function name.

Quoted 41 lines
Quoted 25 lines
xen/arch/x86/hvm/hvm.c +25 -0
+{
+    root_pgentry_t *pgt = alloc_xenheap_page();
+
+    if ( !pgt )
+        return -ENOMEM;
+
+    clear_page(pgt);
+
+    init_xen_l4_slots(pgt, _mfn(virt_to_mfn(pgt)), INVALID_MFN, NULL,
+                      false, true, false);
+
+    ASSERT(!per_cpu(monitor_pgt, cpu));
+    per_cpu(monitor_pgt, cpu) = pgt;
+
+    return 0;
+}
+
+static void free_cpu_monitor_table(unsigned int cpu)
+{
+    root_pgentry_t *pgt = per_cpu(monitor_pgt, cpu);
+
+    if ( !pgt )
+        return;
+
+    per_cpu(monitor_pgt, cpu) = NULL;

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 144

Quoted 10 lines
xen/arch/x86/hvm/hvm.c +10 -0
+    free_xenheap_page(pgt);
+}
+
+void hvm_set_cpu_monitor_table(struct vcpu *v)
+{
+    root_pgentry_t *pgt = this_cpu(monitor_pgt);
+
+    ASSERT(pgt);
+
+    setup_perdomain_slot(v, pgt);

Why not modify them as part of write_ptbase() instead? As it stands, it appears to be modifying the PTEs of what may very well be our current PT, which makes the perdomain slot be in a $DEITY-knows-what state until the next flush (presumably the write to cr3 in write_ptbase()?; assuming no PCIDs).

Quoted 2 lines

Setting the slot up right before the cr3 change should reduce the potential for misuse.

The reasoning for doing it here it that the per-domain slot only needs setting on context switch. In the PV case write_ptbase() will be called each time the guest switches %cr3, but setting the per-domain slot is not required for each call if the vCPU hasn't changed.

Let me see if I can arrange for the current contents of setup_perdomain_slot() to be merged into write_ptbase(). Note setup_perdomain_slot() started as a wrapper to extract XPTI specific code from paravirt_ctxt_switch_to().

Quoted 6 lines
Quoted 6 lines
xen/arch/x86/hvm/hvm.c +6 -0
+
+    make_cr3(v, _mfn(virt_to_mfn(pgt)));
+}
+
+void hvm_clear_cpu_monitor_table(struct vcpu *v)
+{
Quoted 8 lines

xen/arch/x86/hvm/hvm.c static const char __initconst warning_hvm_fep[] = · line 152

Quoted 2 lines
xen/arch/x86/hvm/hvm.c +2 -0
+    /* Poison %cr3, it will be updated when the vCPU is scheduled. */
+    make_cr3(v, INVALID_MFN);

I think this would benefit from more exposition in the comment. If I'm getting this right, after descheduling this vCPU we can't assume it'll be rescheduled on the same pCPU, and if it's not it'll end up using a different monitor table. This poison value is meant to highlight forgetting to set cr3 in the "ctxt_switch_to()" path.

Indeed, we would like to avoid running on a different pCPU while still using the monitor page-tables from whatever pCPU the vCPU previously had been running.

Quoted 4 lines

All of that can be deduced from what you wrote and sufficient headscratching but seeing how this is invoked from the context switch path it's not incredibly clear wether you meant the perdomain slot would be updated by the next vCPU or what I stated in the previous paragraph.

No, it's just about not leaving stale values in the vcpu struct.

Quoted 3 lines

Assuming it is as I mentioned, maybe hvm_forget_cpu_monitor_table() would convey what it does better? i.e: the vCPU forgets/unbinds the monitor table from its internal state.

Right, I assumed that 'clear' already conveyed the concept of unbinding from a pCPU. If I use unbind, then I guess I should also use 'bind' for what I currently call 'set'.

Thanks, Roger.

#47 lore raw

PATCH 14/22 x86/hvm: use a per-pCPU monitor table in shadow mode

In reply to Roger Pau Monne

Instead of allocating a monitor table for each vCPU when running in HVM shadow mode, use a per-pCPU monitor table, which gets the per-domain slot updated on guest context switch.

---
I've tested this manually, but XenServer builds disable shadow support, so it possibly hasn't been given the same level of testing as the rest of the changes.

---
 xen/arch/x86/hvm/hvm.c              |  7 +++
 xen/arch/x86/include/asm/hvm/vcpu.h |  6 ++-
 xen/arch/x86/include/asm/paging.h   | 18 ++++++++
 xen/arch/x86/mm.c                   |  6 +++
 xen/arch/x86/mm/shadow/common.c     | 42 +++++++-----------
 xen/arch/x86/mm/shadow/hvm.c        | 65 ++++++++++++----------------
 xen/arch/x86/mm/shadow/multi.c      | 66 ++++++++++++++++++-----------
 xen/arch/x86/mm/shadow/private.h    |  4 +-
 8 files changed, 120 insertions(+), 94 deletions(-)
xen/arch/x86/hvm/hvm.c +7 -0
index 3f771bc65677..419d78a79c51 100644
@@ -141,6 +141,7 @@ void hvm_set_cpu_monitor_table(struct vcpu *v)
 
     ASSERT(pgt);
 
+    paging_set_cpu_monitor_table(v);
     setup_perdomain_slot(v, pgt);
 
     make_cr3(v, _mfn(virt_to_mfn(pgt)));
@@ -150,6 +151,8 @@ void hvm_clear_cpu_monitor_table(struct vcpu *v)
 {
     /* Poison %cr3, it will be updated when the vCPU is scheduled. */
     make_cr3(v, INVALID_MFN);
+
+    paging_clear_cpu_monitor_table(v);
 }
 
 static int cf_check cpu_callback(
@@ -1645,6 +1648,10 @@ int hvm_vcpu_initialise(struct vcpu *v)
     int rc;
     struct domain *d = v->domain;
 
+#ifdef CONFIG_SHADOW_PAGING
+    v->arch.hvm.shadow_linear_l3 = INVALID_MFN;
+#endif
+
     hvm_asid_flush_vcpu(v);
 
     spin_lock_init(&v->arch.hvm.tm_lock);
xen/arch/x86/include/asm/hvm/vcpu.h +4 -2
index 64c7a6fedea9..f7faaaa21521 100644
@@ -149,8 +149,10 @@ struct hvm_vcpu {
         uint16_t p2midx;
     } fast_single_step;
 
-    /* (MFN) hypervisor page table */
-    pagetable_t         monitor_table;
+#ifdef CONFIG_SHADOW_PAGING
+    /* Reference to the linear L3 page table. */
+    mfn_t shadow_linear_l3;
+#endif
 
     struct hvm_vcpu_asid n1asid;
 
xen/arch/x86/include/asm/paging.h +18 -0
index 8a2a0af40874..c1e188bcd3c0 100644
@@ -117,6 +117,8 @@ struct paging_mode {
                                             unsigned long cr3,
                                             paddr_t ga, uint32_t *pfec,
                                             unsigned int *page_order);
+    void          (*set_cpu_monitor_table  )(struct vcpu *v);
+    void          (*clear_cpu_monitor_table)(struct vcpu *v);
 #endif
     pagetable_t   (*update_cr3            )(struct vcpu *v, bool noflush);
 
@@ -288,6 +290,22 @@ static inline bool paging_flush_tlb(const unsigned long *vcpu_bitmap)
     return current->domain->arch.paging.flush_tlb(vcpu_bitmap);
 }
 
+static inline void paging_set_cpu_monitor_table(struct vcpu *v)
+{
+    const struct paging_mode *mode = paging_get_hostmode(v);
+
+    if ( mode->set_cpu_monitor_table )
+        mode->set_cpu_monitor_table(v);
+}
+
+static inline void paging_clear_cpu_monitor_table(struct vcpu *v)
+{
+    const struct paging_mode *mode = paging_get_hostmode(v);
+
+    if ( mode->clear_cpu_monitor_table )
+        mode->clear_cpu_monitor_table(v);
+}
+
 #endif /* CONFIG_HVM */
 
 /* Update all the things that are derived from the guest's CR3.
xen/arch/x86/mm.c +6 -0
index 7f2666adaef4..13aa15f4db22 100644
@@ -534,6 +534,12 @@ void write_ptbase(struct vcpu *v)
     }
     else
     {
+        ASSERT(!is_hvm_domain(d) || !d->arch.asi
+#ifdef CONFIG_HVM
+               || mfn_eq(maddr_to_mfn(v->arch.cr3),
+                         virt_to_mfn(this_cpu(monitor_pgt)))
+#endif
+               );
         /* Make sure to clear use_pv_cr3 and xen_cr3 before pv_cr3. */
         cpu_info->use_pv_cr3 = false;
         cpu_info->xen_cr3 = 0;
xen/arch/x86/mm/shadow/common.c +16 -26

80 lines not on this page · raw message

xen/arch/x86/mm/shadow/hvm.c +26 -39

108 lines not on this page · raw message

xen/arch/x86/mm/shadow/multi.c +41 -25

103 lines not on this page · raw message

xen/arch/x86/mm/shadow/private.h +2 -2
index a5fc3a7676eb..6743aeefe12e 100644
@@ -420,8 +420,8 @@ void shadow_unhook_mappings(struct domain *d, mfn_t smfn, int user_only);
  * sh_{make,destroy}_monitor_table() depend only on the number of shadow
  * levels.
  */
-mfn_t sh_make_monitor_table(const struct vcpu *v, unsigned int shadow_levels);
-void sh_destroy_monitor_table(const struct vcpu *v, mfn_t mmfn,
+int sh_update_monitor_table(struct vcpu *v, unsigned int shadow_levels);
+void sh_destroy_monitor_table(const struct vcpu *v, mfn_t m3mfn,
                               unsigned int shadow_levels);
 
 /* VRAM dirty tracking helpers. */
Signature · 1 line
2.45.2
#48 lore raw

PATCH 15/22 x86/idle: allow using a per-pCPU L4

In reply to Roger Pau Monne

Introduce support for possibly using a different L4 across the idle vCPUs.

This change only introduces support for loading a per-pPCU idle L4, but even with the per-CPU idle page-table enabled it should still be a clone of idle_pg_table, hence no functional change expected.

Note the idle L4 is not changed after Xen has reached the SYS_STATE_smp_boot state, hence there are no need to synchronize the contents of the L4 once the CPUs are started.

Using a per-CPU idle page-table is not strictly required for the Address Space Isolation work, as idle page tables are never used when running guests. However it simplifies memory management of the per-CPU mappings, as creating per-CPU mappings only require using the idle page-table of the CPU where the mappings should be created.

---
 xen/arch/x86/boot/x86_64.S       | 11 +++++++++++
 xen/arch/x86/domain.c            | 20 +++++++++++++++++++-
 xen/arch/x86/domain_page.c       |  2 +-
 xen/arch/x86/include/asm/setup.h |  1 +
 xen/arch/x86/setup.c             |  3 +++
 xen/arch/x86/smpboot.c           |  7 +++++++
 6 files changed, 42 insertions(+), 2 deletions(-)
xen/arch/x86/boot/x86_64.S +11 -0
index 04bb62ae8680..af7854820185 100644
@@ -15,6 +15,17 @@ ENTRY(__high_start)
         mov     $XEN_MINIMAL_CR4,%rcx
         mov     %rcx,%cr4
 
+        /*
+         * Possibly switch to the per-CPU idle page-tables. Note we cannot
+         * switch earlier as the per-CPU page-tables might be above 4G, and
+         * hence need to load them from 64bit code.
+         */
+        mov     ap_cr3(%rip), %rax
+        test    %rax, %rax
+        jz      .L_skip_cr3
+        mov     %rax, %cr3
+.L_skip_cr3:
+
         mov     stack_start(%rip),%rsp
 
         /* Reset EFLAGS (subsumes CLI and CLD). */
xen/arch/x86/domain.c +19 -1
index 9cfcf0dc63f3..b62c4311da6c 100644
@@ -555,6 +555,7 @@ void arch_vcpu_regs_init(struct vcpu *v)
 int arch_vcpu_create(struct vcpu *v)
 {
     struct domain *d = v->domain;
+    root_pgentry_t *pgt = NULL;
     int rc;
 
     v->arch.flags = TF_kernel_mode;
@@ -589,7 +590,23 @@ int arch_vcpu_create(struct vcpu *v)
     else
     {
         /* Idle domain */
-        v->arch.cr3 = __pa(idle_pg_table);
+        if ( (opt_asi_pv || opt_asi_hvm) && v->vcpu_id )
+        {
+            pgt = alloc_xenheap_page();
+
+            /*
+             * For the idle vCPU 0 (the BSP idle vCPU) use idle_pg_table
+             * directly, there's no need to create yet another copy.
+             */
+            rc = -ENOMEM;
+            if ( !pgt )
+                goto fail;
+
+            copy_page(pgt, idle_pg_table);
+            v->arch.cr3 = __pa(pgt);
+        }
+        else
+            v->arch.cr3 = __pa(idle_pg_table);
         rc = 0;
         v->arch.msrs = ZERO_BLOCK_PTR; /* Catch stray misuses */
     }
@@ -611,6 +628,7 @@ int arch_vcpu_create(struct vcpu *v)
     vcpu_destroy_fpu(v);
     xfree(v->arch.msrs);
     v->arch.msrs = NULL;
+    free_xenheap_page(pgt);
 
     return rc;
 }
xen/arch/x86/domain_page.c +1 -1
index eac5e3304fb8..99b78af90fd3 100644
@@ -51,7 +51,7 @@ static inline struct vcpu *mapcache_current_vcpu(void)
         if ( (v = idle_vcpu[smp_processor_id()]) == current )
             sync_local_execstate();
         /* We must now be running on the idle page table. */
-        ASSERT(cr3_pa(read_cr3()) == __pa(idle_pg_table));
+        ASSERT(cr3_pa(read_cr3()) == cr3_pa(v->arch.cr3));
     }
 
     return v;
xen/arch/x86/include/asm/setup.h +1 -0
index d75589178b91..a8452fce8f05 100644
@@ -14,6 +14,7 @@ extern unsigned long xenheap_initial_phys_start;
 extern uint64_t boot_tsc_stamp;
 
 extern void *stack_start;
+extern unsigned long ap_cr3;
 
 void early_cpu_init(bool verbose);
 void early_time_init(void);
xen/arch/x86/setup.c +3 -0
index bc387d96b519..c5a13b30daf4 100644
@@ -158,6 +158,9 @@ char asmlinkage __section(".init.bss.stack_aligned") __aligned(STACK_SIZE)
 /* Used by the BSP/AP paths to find the higher half stack mapping to use. */
 void *stack_start = cpu0_stack + STACK_SIZE - sizeof(struct cpu_info);
 
+/* cr3 value for the AP to load on boot. */
+unsigned long ap_cr3;
+
 /* Used by the boot asm to stash the relocated multiboot info pointer. */
 unsigned int asmlinkage __initdata multiboot_ptr;
 
xen/arch/x86/smpboot.c +7 -0
index 8aa621533f3d..e07add36b1b6 100644
@@ -581,6 +581,13 @@ static int do_boot_cpu(int apicid, int cpu)
 
     stack_start = stack_base[cpu] + STACK_SIZE - sizeof(struct cpu_info);
 
+    /*
+     * If per-CPU idle root page table has been allocated, switch to it as
+     * part of the AP bringup trampoline.
+     */
+    ap_cr3 = idle_vcpu[cpu]->arch.cr3 != __pa(idle_pg_table) ?
+             idle_vcpu[cpu]->arch.cr3 : 0;
+
     /* This grunge runs the startup process for the targeted processor. */
 
     set_cpu_state(CPU_STATE_INIT);
Signature · 1 line
2.45.2
#49 lore raw

Re: [PATCH 15/22] x86/idle: allow using a per-pCPU L4

Quoted 15 lines · Roger Pau Monne
xen/arch/x86/domain.c +1 -0
index 9cfcf0dc63f3..b62c4311da6c 100644
@@ -555,6 +555,7 @@ void arch_vcpu_regs_init(struct vcpu *v)
 int arch_vcpu_create(struct vcpu *v)
 {
     struct domain *d = v->domain;
+    root_pgentry_t *pgt = NULL;
     int rc;
 
     v->arch.flags = TF_kernel_mode;
@@ -589,7 +590,23 @@ int arch_vcpu_create(struct vcpu *v)
     else
     {

xen/arch/x86/domain.c int arch_vcpu_create(struct vcpu *v) · line 600

Quoted 10 lines
xen/arch/x86/domain.c +8 -1
         /* Idle domain */
-        v->arch.cr3 = __pa(idle_pg_table);
+        if ( (opt_asi_pv || opt_asi_hvm) && v->vcpu_id )
+        {
+            pgt = alloc_xenheap_page();
+
+            /*
+             * For the idle vCPU 0 (the BSP idle vCPU) use idle_pg_table
+             * directly, there's no need to create yet another copy.
+             */

Shouldn't this comment be in the else branch instead? Or reworded to refer to non-0 vCPUs.

xen/arch/x86/domain.c int arch_vcpu_create(struct vcpu *v) · line 601

Quoted 1 line
xen/arch/x86/domain.c +1 -0
+            rc = -ENOMEM;

While it's true rc is overriden later, I feel uneasy leaving it with -ENOMEM after the check. Could we have it immediately before "goto fail"?

Quoted 12 lines
xen/arch/x86/domain.c +8 -0
+            if ( !pgt )
+                goto fail;
+
+            copy_page(pgt, idle_pg_table);
+            v->arch.cr3 = __pa(pgt);
+        }
+        else
+            v->arch.cr3 = __pa(idle_pg_table);
         rc = 0;
         v->arch.msrs = ZERO_BLOCK_PTR; /* Catch stray misuses */
     }

xen/arch/x86/domain.c int arch_vcpu_create(struct vcpu *v) · line 634

Quoted 7 lines
xen/arch/x86/domain.c +1 -0
@@ -611,6 +628,7 @@ int arch_vcpu_create(struct vcpu *v)
     vcpu_destroy_fpu(v);
     xfree(v->arch.msrs);
     v->arch.msrs = NULL;
+    free_xenheap_page(pgt);
 
     return rc;
 }

I guess the idle domain has a forever lifetime and its vCPUs are kept around forever too, right?; otherwise we'd need extra logic in the the vcpu_destroy() to free the page table copies should they exist too.

Cheers,
Alejandro

#50 lore raw

Re: [PATCH 15/22] x86/idle: allow using a per-pCPU L4

Quoted 21 lines · Alejandro Vallejo
Quoted 20 lines · Roger Pau Monne
xen/arch/x86/domain.c +4 -1
index 9cfcf0dc63f3..b62c4311da6c 100644
@@ -555,6 +555,7 @@ void arch_vcpu_regs_init(struct vcpu *v)
 int arch_vcpu_create(struct vcpu *v)
 {
     struct domain *d = v->domain;
+    root_pgentry_t *pgt = NULL;
     int rc;
 
     v->arch.flags = TF_kernel_mode;
@@ -589,7 +590,23 @@ int arch_vcpu_create(struct vcpu *v)
     else
     {
         /* Idle domain */
-        v->arch.cr3 = __pa(idle_pg_table);
+        if ( (opt_asi_pv || opt_asi_hvm) && v->vcpu_id )
+        {
+            pgt = alloc_xenheap_page();
Quoted 8 lines

xen/arch/x86/domain.c int arch_vcpu_create(struct vcpu *v) · line 600

Quoted 5 lines
xen/arch/x86/domain.c +5 -0
+
+            /*
+             * For the idle vCPU 0 (the BSP idle vCPU) use idle_pg_table
+             * directly, there's no need to create yet another copy.
+             */

Shouldn't this comment be in the else branch instead? Or reworded to refer to non-0 vCPUs.

Sure, moved to the else branch.

Quoted 4 lines

xen/arch/x86/domain.c int arch_vcpu_create(struct vcpu *v) · line 601

Quoted 1 line
xen/arch/x86/domain.c +1 -0
+            rc = -ENOMEM;

While it's true rc is overriden later, I feel uneasy leaving it with -ENOMEM after the check. Could we have it immediately before "goto fail"?

I have to admit I found this coding style weird at first, but it's used all over Xen. I don't mind setting rc ahead of the goto, AFAICT the only benefit of the current style is that we can avoid the braces around the if code block for it being a single statement.

Quoted 17 lines
Quoted 17 lines
xen/arch/x86/domain.c +9 -0
+            if ( !pgt )
+                goto fail;
+
+            copy_page(pgt, idle_pg_table);
+            v->arch.cr3 = __pa(pgt);
+        }
+        else
+            v->arch.cr3 = __pa(idle_pg_table);
         rc = 0;
         v->arch.msrs = ZERO_BLOCK_PTR; /* Catch stray misuses */
     }
@@ -611,6 +628,7 @@ int arch_vcpu_create(struct vcpu *v)
     vcpu_destroy_fpu(v);
     xfree(v->arch.msrs);
     v->arch.msrs = NULL;
+    free_xenheap_page(pgt);
 
Quoted 6 lines

xen/arch/x86/domain.c int arch_vcpu_create(struct vcpu *v) · line 634

Quoted 2 lines
xen/arch/x86/domain.c +0 -0
     return rc;
 }

I guess the idle domain has a forever lifetime and its vCPUs are kept around forever too, right?; otherwise we'd need extra logic in the the vcpu_destroy() to free the page table copies should they exist too.

Indeed, vcpus are only destroyed when destroying domains, and system domains are never destroyed.

Thanks, Roger.

#51 lore raw

PATCH 16/22 x86/mm: introduce a per-CPU L3 table for the per-domain slot

In reply to Roger Pau Monne

So far L4 slot 260 has always been per-domain, in other words: all vCPUs of a domain share the same L3 entry. Currently only 3 slots are used in that L3 table, which leaves plenty of room.

Introduce a per-CPU L3 that's used the the domain has Address Space Isolation enabled. Such per-CPU L3 gets currently populated using the same L3 entries present on the per-domain L3 (d->arch.perdomain_l3_pg).

No functional change expected, as the per-CPU L3 is always a copy of the contents of d->arch.perdomain_l3_pg.

Note that all the per-domain L3 entries are populated at domain create, and hence there's no need to sync the state of the per-CPU L3 as the domain won't yet be running when the L3 is modified.

---
 xen/arch/x86/include/asm/domain.h |  2 +
 xen/arch/x86/include/asm/mm.h     |  4 ++
 xen/arch/x86/mm.c                 | 80 +++++++++++++++++++++++++++++--
 xen/arch/x86/setup.c              |  8 ++++
 xen/arch/x86/smpboot.c            |  4 ++
 5 files changed, 95 insertions(+), 3 deletions(-)
xen/arch/x86/include/asm/domain.h +2 -0
index 8c366be8c75f..7620a352b9e3 100644
@@ -313,6 +313,8 @@ struct arch_domain
 {
     struct page_info *perdomain_l3_pg;
 
+    struct page_info *perdomain_l2_pgs[PERDOMAIN_SLOTS];
+
 #ifdef CONFIG_PV32
     unsigned int hv_compat_vstart;
 #endif
xen/arch/x86/include/asm/mm.h +4 -0
index 2c309f7b1444..34407fb0af06 100644
@@ -633,4 +633,8 @@ static inline bool arch_mfns_in_directmap(unsigned long mfn, unsigned long nr)
 /* Setup the per-domain slot in the root page table pointer. */
 void setup_perdomain_slot(const struct vcpu *v, root_pgentry_t *root_pgt);
 
+/* Allocate a per-CPU local L3 table to use in the per-domain slot. */
+int allocate_perdomain_local_l3(unsigned int cpu);
+void free_perdomain_local_l3(unsigned int cpu);
+
 #endif /* __ASM_X86_MM_H__ */
xen/arch/x86/mm.c +77 -3

94 lines not on this page · raw message

xen/arch/x86/setup.c +8 -0
index c5a13b30daf4..5bf81b81b46f 100644
@@ -1961,6 +1961,14 @@ void asmlinkage __init noreturn __start_xen(unsigned long mbi_p)
 
     alternative_branches();
 
+    /*
+     * Setup the local per-domain L3 for the BSP also, so it matches the state
+     * of the APs.
+     */
+    ret = allocate_perdomain_local_l3(0);
+    if ( ret )
+        panic("Error %d setting up local per-domain L3\n", ret);
+
     /*
      * NB: when running as a PV shim VCPUOP_up/down is wired to the shim
      * physical cpu_add/remove functions, so launch the guest with only
xen/arch/x86/smpboot.c +4 -0
index e07add36b1b6..40cc14799252 100644
@@ -986,6 +986,7 @@ static void cpu_smpboot_free(unsigned int cpu, bool remove)
     }
 
     cleanup_cpu_root_pgt(cpu);
+    free_perdomain_local_l3(cpu);
 
     if ( per_cpu(stubs.addr, cpu) )
     {
@@ -1100,6 +1101,9 @@ static int cpu_smpboot_alloc(unsigned int cpu)
     per_cpu(stubs.addr, cpu) = stub_page + STUB_BUF_CPU_OFFS(cpu);
 
     rc = setup_cpu_root_pgt(cpu);
+    if ( rc )
+        goto out;
+    rc = allocate_perdomain_local_l3(cpu);
     if ( rc )
         goto out;
     rc = -ENOMEM;
Signature · 1 line
2.45.2
#52 lore raw

Re: [PATCH 16/22] x86/mm: introduce a per-CPU L3 table for the per-domain slot

Quoted 8 lines · Roger Pau Monne

So far L4 slot 260 has always been per-domain, in other words: all vCPUs of a domain share the same L3 entry. Currently only 3 slots are used in that L3 table, which leaves plenty of room.

Introduce a per-CPU L3 that's used the the domain has Address Space Isolation enabled. Such per-CPU L3 gets currently populated using the same L3 entries present on the per-domain L3 (d->arch.perdomain_l3_pg).

Quoted 8 lines

No functional change expected, as the per-CPU L3 is always a copy of the contents of d->arch.perdomain_l3_pg.

Note that all the per-domain L3 entries are populated at domain create, and hence there's no need to sync the state of the per-CPU L3 as the domain won't yet be running when the L3 is modified.

Still scratching my head with the details on this, but in general I'm utterly confused whenever I read per-CPU in the series because it's not obvious which CPU (p or v) I should be thinking about. A general change that would help a lot is to replace every instance of per-CPU with per-vCPU or per-pCPU as needed.

Cheers,
Alejandro

#53 lore raw

Re: [PATCH 16/22] x86/mm: introduce a per-CPU L3 table for the per-domain slot

Quoted 16 lines · Alejandro Vallejo
Quoted 15 lines · Roger Pau Monne

So far L4 slot 260 has always been per-domain, in other words: all vCPUs of a domain share the same L3 entry. Currently only 3 slots are used in that L3 table, which leaves plenty of room.

Introduce a per-CPU L3 that's used the the domain has Address Space Isolation enabled. Such per-CPU L3 gets currently populated using the same L3 entries present on the per-domain L3 (d->arch.perdomain_l3_pg).

No functional change expected, as the per-CPU L3 is always a copy of the contents of d->arch.perdomain_l3_pg.

Note that all the per-domain L3 entries are populated at domain create, and hence there's no need to sync the state of the per-CPU L3 as the domain won't yet be running when the L3 is modified.

Quoted 6 lines
Quoted 1 line

Still scratching my head with the details on this, but in general I'm utterly confused whenever I read per-CPU in the series because it's not obvious which CPU (p or v) I should be thinking about. A general change that would help a lot is to replace every instance of per-CPU with per-vCPU or per-pCPU as needed.

per-CPU is always per-pCPU, as CPU without any prefix should always refer to a physical CPU. I think it's only recently that we have started using pCPU vs vCPU, in the past it always was CPU vs vCPU.

I will attempt to be better at explicitly using pCPU instead of CPU in the commit messages, sorry.

Thanks, Roger.

#54 lore raw

PATCH 17/22 x86/mm: introduce support to populate a per-CPU page-table region

In reply to Roger Pau Monne

Add logic in map_pages_to_xen() and modify_xen_mappings() so that TLB flushes are only performed locally when dealing with entries in the per-CPU area of the page-tables.

No functional change intended, as there are no callers added that create or modify per-CPU mappings, nor is the per-CPU area still properly setup in the page-tables yet.

Note that the removed flush_area() ended up calling flush_area_mask() through the flush_area_all() alias.

---
 xen/arch/x86/include/asm/config.h   |  4 ++
 xen/arch/x86/include/asm/flushtlb.h |  1 -
 xen/arch/x86/mm.c                   | 64 +++++++++++++++++++----------
 3 files changed, 47 insertions(+), 22 deletions(-)
xen/arch/x86/include/asm/config.h +4 -0
index 2a260a2581fd..c24d735a0cee 100644
@@ -204,6 +204,10 @@ extern unsigned char boot_edid_info[128];
 #define PERDOMAIN_SLOTS         3
 #define PERDOMAIN_VIRT_SLOT(s)  (PERDOMAIN_VIRT_START + (s) * \
                                  (PERDOMAIN_SLOT_MBYTES << 20))
+#define PERCPU_VIRT_START       PERDOMAIN_VIRT_SLOT(PERDOMAIN_SLOTS)
+#define PERCPU_SLOTS            1
+#define PERCPU_VIRT_SLOT(s)     (PERCPU_VIRT_START + (s) * \
+                                 (PERDOMAIN_SLOT_MBYTES << 20))
 /* Slot 4: mirror of per-domain mappings (for compat xlat area accesses). */
 #define PERDOMAIN_ALT_VIRT_START PML4_ADDR(4)
 /* Slot 261: machine-to-phys conversion table (256GB). */
xen/arch/x86/include/asm/flushtlb.h +0 -1
index 1b98d03decdc..affe944d1a5b 100644
@@ -146,7 +146,6 @@ void flush_area_mask(const cpumask_t *mask, const void *va,
 #define flush_mask(mask, flags) flush_area_mask(mask, NULL, flags)
 
 /* Flush all CPUs' TLBs/caches */
-#define flush_area_all(va, flags) flush_area_mask(&cpu_online_map, va, flags)
 #define flush_all(flags) flush_mask(&cpu_online_map, flags)
 
 /* Flush local TLBs */
xen/arch/x86/mm.c +43 -21

174 lines not on this page · raw message

Signature · 1 line
2.45.2
#55 lore raw

PATCH 18/22 x86/mm: allow modifying per-CPU entries of remote page-tables

In reply to Roger Pau Monne

Add support for modifying the per-CPU page-tables entries of remote CPUs, this will be required in order to setup the page-tables of CPUs before bringing them up. A restriction is added so that remote page-tables can only be modified as long as the remote CPU is not yet online.

Non functional change, as there's no user introduced that modifies remote page-tables.

---
Can be merged with previous patch?

---
 xen/arch/x86/include/asm/mm.h | 15 ++++++++++
 xen/arch/x86/mm.c             | 55 ++++++++++++++++++++++++++---------
 2 files changed, 56 insertions(+), 14 deletions(-)
xen/arch/x86/include/asm/mm.h +15 -0
index 34407fb0af06..f883468b1a7c 100644
@@ -637,4 +637,19 @@ void setup_perdomain_slot(const struct vcpu *v, root_pgentry_t *root_pgt);
 int allocate_perdomain_local_l3(unsigned int cpu);
 void free_perdomain_local_l3(unsigned int cpu);
 
+/* Specify the CPU idle root page-table to use for modifications. */
+int map_pages_to_xen_cpu(
+    unsigned long virt,
+    mfn_t mfn,
+    unsigned long nr_mfns,
+    unsigned int flags,
+    unsigned int cpu);
+int modify_xen_mappings_cpu(unsigned long s, unsigned long e, unsigned int nf,
+                            unsigned int cpu);
+static inline int destroy_xen_mappings_cpu(unsigned long s, unsigned long e,
+                                           unsigned int cpu)
+{
+    return modify_xen_mappings_cpu(s, e, _PAGE_NONE, cpu);
+}
+
 #endif /* __ASM_X86_MM_H__ */
xen/arch/x86/mm.c +41 -14

148 lines not on this page · raw message

Signature · 1 line
2.45.2
#56 lore raw

PATCH 19/22 x86/mm: introduce a per-CPU fixmap area

In reply to Roger Pau Monne

Introduce the logic to manage a per-CPU fixmap area. This includes adding a new set of headers that are capable of creating mappings in the per-CPU page-table regions by making use of the map_pages_to_xen_cpu().

This per-CPU fixmap area is currently set to use one L3 slot: 1GiB of linear address space.

---
 xen/arch/x86/include/asm/fixmap.h | 44 +++++++++++++++++++++++++++++++
 xen/arch/x86/mm.c                 | 16 ++++++++++-
 2 files changed, 59 insertions(+), 1 deletion(-)
xen/arch/x86/include/asm/fixmap.h +44 -0
index 516ec3fa6c95..a456c65072d8 100644
@@ -118,6 +118,50 @@ extern void __set_fixmap_x(
 #define __fix_x_to_virt(x) (FIXADDR_X_TOP - ((x) << PAGE_SHIFT))
 #define fix_x_to_virt(x)   ((void *)__fix_x_to_virt(x))
 
+/* per-CPU fixmap area. */
+enum percpu_fixed_addresses {
+    __end_of_percpu_fixed_addresses
+};
+
+#define PERCPU_FIXADDR_SIZE (__end_of_percpu_fixed_addresses << PAGE_SHIFT)
+#define PERCPU_FIXADDR PERCPU_VIRT_SLOT(0)
+
+static inline void *percpu_fix_to_virt(enum percpu_fixed_addresses idx)
+{
+    BUG_ON(idx >=__end_of_percpu_fixed_addresses);
+    return (void *)PERCPU_FIXADDR + (idx << PAGE_SHIFT);
+}
+
+static inline void percpu_set_fixmap_remote(
+    unsigned int cpu, enum percpu_fixed_addresses idx, mfn_t mfn,
+    unsigned long flags)
+{
+    map_pages_to_xen_cpu((unsigned long)percpu_fix_to_virt(idx), mfn, 1, flags,
+                         cpu);
+}
+
+static inline void percpu_clear_fixmap_remote(
+    unsigned int cpu, enum percpu_fixed_addresses idx)
+{
+    /*
+     * Use map_pages_to_xen_cpu() instead of destroy_xen_mappings_cpu() to
+     * avoid tearing down the intermediate page-tables if empty.
+     */
+    map_pages_to_xen_cpu((unsigned long)percpu_fix_to_virt(idx), INVALID_MFN, 1,
+                         0, cpu);
+}
+
+static inline void percpu_set_fixmap(enum percpu_fixed_addresses idx, mfn_t mfn,
+                                     unsigned long flags)
+{
+    percpu_set_fixmap_remote(smp_processor_id(), idx, mfn, flags);
+}
+
+static inline void percpu_clear_fixmap(enum percpu_fixed_addresses idx)
+{
+    percpu_clear_fixmap_remote(smp_processor_id(), idx);
+}
+
 #endif /* __ASSEMBLY__ */
 
 #endif
xen/arch/x86/mm.c +15 -1
index faf2d42745d1..937089d203cc 100644
@@ -6467,7 +6467,17 @@ int allocate_perdomain_local_l3(unsigned int cpu)
 
     per_cpu(local_l3, cpu) = l3;
 
-    return 0;
+    /*
+     * Pre-allocate the page-table structures for the per-cpu fixmap.  Some of
+     * the per-cpu fixmap calls might happen in contexts where memory
+     * allocation is not possible.
+     *
+     * Only one L3 slot is currently reserved for the per-CPU fixmap.
+     */
+    BUILD_BUG_ON(PERCPU_FIXADDR_SIZE > (1 << L3_PAGETABLE_SHIFT));
+    return map_pages_to_xen_cpu(PERCPU_VIRT_START, INVALID_MFN,
+                                PFN_DOWN(PERCPU_FIXADDR_SIZE), MAP_SMALL_PAGES,
+                                cpu);
 }
 
 void free_perdomain_local_l3(unsigned int cpu)
@@ -6478,6 +6488,10 @@ void free_perdomain_local_l3(unsigned int cpu)
         return;
 
     per_cpu(local_l3, cpu) = NULL;
+
+    destroy_xen_mappings_cpu(PERCPU_VIRT_START,
+                             PERCPU_VIRT_START + PERCPU_FIXADDR_SIZE, cpu);
+
     free_xenheap_page(l3);
 }
 
Signature · 1 line
2.45.2
#57 lore raw

PATCH 20/22 x86/pv: allow using a unique per-pCPU root page table (L4)

In reply to Roger Pau Monne

When running PV guests it's possible for the guest to use the same root page table (L4) for all vCPUs, which in turn will result in Xen also using the same root page table on all pCPUs that are running any domain vCPU.

When using XPTI Xen switches to a per-CPU shadow L4 when running in guest context, switching to the fully populated L4 when in Xen context.

Take advantage of this existing shadowing and force the usage of a per-CPU L4 that shadows the guest selected L4 when Address Space Isolation is requested for PV guests.

The mapping of the guest L4 is done with a per-CPU fixmap entry, that however requires that the currently loaded L4 has the per-CPU slot setup. In order to ensure this switch to the shadow per-CPU L4 with just the Xen slots populated, and then map the guest L4 and copy the contents of the guest controlled slots.

---
 xen/arch/x86/domain.c              | 37 +++++++++++++++++++++
 xen/arch/x86/flushtlb.c            |  9 ++++++
 xen/arch/x86/include/asm/current.h | 15 ++++++---
 xen/arch/x86/include/asm/fixmap.h  |  1 +
 xen/arch/x86/include/asm/pv/mm.h   |  8 +++++
 xen/arch/x86/mm.c                  | 47 +++++++++++++++++++++++++++
 xen/arch/x86/pv/domain.c           | 25 ++++++++++++--
 xen/arch/x86/pv/mm.c               | 52 ++++++++++++++++++++++++++++++
 xen/arch/x86/smpboot.c             | 20 +++++++++++-
 9 files changed, 207 insertions(+), 7 deletions(-)
xen/arch/x86/domain.c +37 -0
index b62c4311da6c..94a42ef29cd1 100644
@@ -45,6 +45,7 @@
 #include <asm/io.h>
 #include <asm/processor.h>
 #include <asm/desc.h>
+#include <asm/fixmap.h>
 #include <asm/i387.h>
 #include <asm/xstate.h>
 #include <asm/cpuidle.h>
@@ -2110,11 +2111,47 @@ void context_switch(struct vcpu *prev, struct vcpu *next)
 
     local_irq_disable();
 
+    if ( is_pv_domain(prevd) && prevd->arch.asi )
+    {
+        /*
+         * Don't leak the L4 shadow mapping in the per-CPU area.  Can't be done
+         * in paravirt_ctxt_switch_from() because the lazy idle vCPU context
+         * switch would otherwise enter an infinite loop in
+         * mapcache_current_vcpu() with sync_local_execstate().
+         *
+         * Note clearing the fixmpa must strictly be done ahead of changing the
+         * current vCPU and with interrupts disabled, so there's no window
+         * where current->domain->arch.asi == true and PCPU_FIX_PV_L4SHADOW is
+         * not mapped.
+         */
+        percpu_clear_fixmap(PCPU_FIX_PV_L4SHADOW);
+        get_cpu_info()->root_pgt_changed = false;
+    }
+
     set_current(next);
 
     if ( (per_cpu(curr_vcpu, cpu) == next) ||
          (is_idle_domain(nextd) && cpu_online(cpu)) )
     {
+        if ( is_pv_domain(nextd) && nextd->arch.asi )
+        {
+            /* Signal the fixmap entry must be mapped. */
+            get_cpu_info()->new_cr3 = true;
+            if ( get_cpu_info()->root_pgt_changed )
+            {
+                /*
+                 * Map and update the shadow L4 in case we received any
+                 * FLUSH_ROOT_PGTBL request while running on the idle vCPU.
+                 *
+                 * Do it before enabling interrupts so that no flush IPI can be
+                 * delivered without having PCPU_FIX_PV_L4SHADOW correctly
+                 * mapped.
+                 */
+                pv_update_shadow_l4(next, true);
+                get_cpu_info()->root_pgt_changed = false;
+            }
+        }
+
         local_irq_enable();
     }
     else
xen/arch/x86/flushtlb.c +9 -0
index fd5ed16ffb57..b85ce232abbb 100644
@@ -17,6 +17,7 @@
 #include <asm/nops.h>
 #include <asm/page.h>
 #include <asm/pv/domain.h>
+#include <asm/pv/mm.h>
 #include <asm/spec_ctrl.h>
 
 /* Debug builds: Wrap frequently to stress-test the wrap logic. */
@@ -192,7 +193,15 @@ unsigned int flush_area_local(const void *va, unsigned int flags)
     unsigned int order = (flags - 1) & FLUSH_ORDER_MASK;
 
     if ( flags & FLUSH_ROOT_PGTBL )
+    {
+        const struct vcpu *curr = current;
+        const struct domain *curr_d = curr->domain;
+
         get_cpu_info()->root_pgt_changed = true;
+        if ( is_pv_domain(curr_d) && curr_d->arch.asi )
+            /* Update the shadow root page-table ahead of doing TLB flush. */
+            pv_update_shadow_l4(curr, false);
+    }
 
     if ( flags & (FLUSH_TLB|FLUSH_TLB_GLOBAL) )
     {
xen/arch/x86/include/asm/current.h +11 -4
index bcec328c9875..6a021607a1a9 100644
@@ -60,10 +60,14 @@ struct cpu_info {
     uint8_t      scf; /* SCF_* */
 
     /*
-     * The following field controls copying of the L4 page table of 64-bit
-     * PV guests to the per-cpu root page table on entering the guest context.
-     * If set the L4 page table is being copied to the root page table and
-     * the field will be reset.
+     * For XPTI the following field controls copying of the L4 page table of
+     * 64-bit PV guests to the per-cpu root page table on entering the guest
+     * context.  If set the L4 page table is being copied to the root page
+     * table and the field will be reset.
+     *
+     * For ASI the field is used to acknowledge whether a FLUSH_ROOT_PGTBL
+     * request has been received when running the idle vCPU on PV guest
+     * page-tables (a lazy context switch to the idle vCPU).
      */
     bool         root_pgt_changed;
 
@@ -74,6 +78,9 @@ struct cpu_info {
      */
     bool         use_pv_cr3;
 
+    /* For ASI: per-CPU fixmap of guest L4 is possibly out of sync. */
+    bool         new_cr3;
+
     /* get_stack_bottom() must be 16-byte aligned */
 };
 
xen/arch/x86/include/asm/fixmap.h +1 -0
index a456c65072d8..bc68a98568ae 100644
@@ -120,6 +120,7 @@ extern void __set_fixmap_x(
 
 /* per-CPU fixmap area. */
 enum percpu_fixed_addresses {
+    PCPU_FIX_PV_L4SHADOW,
     __end_of_percpu_fixed_addresses
 };
 
xen/arch/x86/include/asm/pv/mm.h +8 -0
index 182764542c1f..a7c74898fce0 100644
@@ -23,6 +23,9 @@ bool pv_destroy_ldt(struct vcpu *v);
 
 int validate_segdesc_page(struct page_info *page);
 
+void pv_clear_l4_guest_entries(root_pgentry_t *root_pgt);
+void pv_update_shadow_l4(const struct vcpu *v, bool flush);
+
 #else
 
 #include <xen/errno.h>
@@ -44,6 +47,11 @@ static inline bool pv_map_ldt_shadow_page(unsigned int off) { return false; }
 static inline bool pv_destroy_ldt(struct vcpu *v)
 { ASSERT_UNREACHABLE(); return false; }
 
+static inline void pv_clear_l4_guest_entries(root_pgentry_t *root_pgt)
+{ ASSERT_UNREACHABLE(); }
+static inline void pv_update_shadow_l4(const struct vcpu *v, bool flush)
+{ ASSERT_UNREACHABLE(); }
+
 #endif
 
 #endif /* __X86_PV_MM_H__ */
xen/arch/x86/mm.c +47 -0

65 lines not on this page · raw message

xen/arch/x86/pv/domain.c +23 -2
index 46ee10a8a4c2..80bf2bf934dd 100644
@@ -15,6 +15,7 @@
 #include <asm/invpcid.h>
 #include <asm/spec_ctrl.h>
 #include <asm/pv/domain.h>
+#include <asm/pv/mm.h>
 #include <asm/shadow.h>
 
 #ifdef CONFIG_PV32
@@ -384,7 +385,7 @@ int pv_domain_initialise(struct domain *d)
 
     d->arch.ctxt_switch = &pv_csw;
 
-    d->arch.pv.flush_root_pt = d->arch.pv.xpti;
+    d->arch.pv.flush_root_pt = d->arch.pv.xpti || d->arch.asi;
 
     if ( !is_pv_32bit_domain(d) && use_invpcid && cpu_has_pcid )
         switch ( ACCESS_ONCE(opt_pcid) )
@@ -446,7 +447,27 @@ static void _toggle_guest_pt(struct vcpu *v)
      * to release). Switch to the idle page tables in such an event; the
      * guest will have been crashed already.
      */
-    cr3 = v->arch.cr3;
+    if ( v->domain->arch.asi )
+    {
+        /*
+         * _toggle_guest_pt() might switch between user and kernel page tables,
+         * but doesn't use write_ptbase(), and hence needs an explicit call to
+         * sync the shadow L4.
+         */
+        cr3 = __pa(this_cpu(root_pgt));
+        if ( v->domain->arch.pv.pcid )
+            cr3 |= get_pcid_bits(v, false);
+        /*
+         * Ensure the current root page table is already the shadow L4, as
+         * guest user/kernel switches can only happen once the guest is
+         * running.
+         */
+        ASSERT(read_cr3() == cr3);
+        pv_update_shadow_l4(v, false);
+    }
+    else
+        cr3 = v->arch.cr3;
+
     if ( shadow_mode_enabled(v->domain) )
     {
         cr3 &= ~X86_CR3_NOFLUSH;
xen/arch/x86/pv/mm.c +52 -0

64 lines not on this page · raw message

xen/arch/x86/smpboot.c +19 -1
index 40cc14799252..d9841ed3b663 100644
@@ -829,7 +829,7 @@ int setup_cpu_root_pgt(unsigned int cpu)
     unsigned int off;
     int rc;
 
-    if ( !opt_xpti_hwdom && !opt_xpti_domu )
+    if ( !opt_xpti_hwdom && !opt_xpti_domu && !opt_asi_pv )
         return 0;
 
     rpt = alloc_xenheap_page();
@@ -839,6 +839,18 @@ int setup_cpu_root_pgt(unsigned int cpu)
     clear_page(rpt);
     per_cpu(root_pgt, cpu) = rpt;
 
+    if ( opt_asi_pv )
+    {
+        /*
+         * Populate the Xen slots, the guest ones will be copied from the guest
+         * root page-table.
+         */
+        init_xen_l4_slots(rpt, _mfn(virt_to_mfn(rpt)), INVALID_MFN, NULL,
+                          false, false, true);
+
+        return 0;
+    }
+
     rpt[root_table_offset(RO_MPT_VIRT_START)] =
         idle_pg_table[root_table_offset(RO_MPT_VIRT_START)];
     /* SH_LINEAR_PT inserted together with guest mappings. */
@@ -892,6 +904,12 @@ static void cleanup_cpu_root_pgt(unsigned int cpu)
 
     per_cpu(root_pgt, cpu) = NULL;
 
+    if ( opt_asi_pv )
+    {
+        free_xenheap_page(rpt);
+        return;
+    }
+
     for ( r = root_table_offset(DIRECTMAP_VIRT_START);
           r < root_table_offset(HYPERVISOR_VIRT_END); ++r )
     {
Signature · 1 line
2.45.2
#58 lore raw

PATCH 21/22 x86/mm: switch to a per-CPU mapped stack when using ASI

In reply to Roger Pau Monne

When using ASI the CPU stack is mapped using a range of fixmap entries in the per-CPU region. This ensures the stack is only accessible by the current CPU.

Note however there's further work required in order to allocate the stack from domheap instead of xenheap, and ensure the stack is not part of the direct map.

For domains not running with ASI enabled all the CPU stacks are mapped in the per-domain L3, so that the stack is always at the same linear address, regardless of whether ASI is enabled or not for the domain.

When calling UEFI runtime methods the current per-domain slot needs to be added to the EFI L4, so that the stack is available in UEFI.

Finally, some users of callfunc IPIs pass parameters from the stack, so when handling a callfunc IPI the stack of the caller CPU is mapped into the address space of the CPU handling the IPI. This needs further work to use a bounce buffer in order to avoid having to map remote CPU stacks.

---
There's also further work required in order to avoid mapping remote stack when handling callfunc IPIs.

---
 xen/arch/x86/domain.c              |  12 +++
 xen/arch/x86/include/asm/current.h |   5 ++
 xen/arch/x86/include/asm/fixmap.h  |   5 ++
 xen/arch/x86/include/asm/mm.h      |   6 +-
 xen/arch/x86/include/asm/smp.h     |  12 +++
 xen/arch/x86/mm.c                  | 125 +++++++++++++++++++++++++++--
 xen/arch/x86/setup.c               |  27 +++++--
 xen/arch/x86/smp.c                 |  29 +++++++
 xen/arch/x86/smpboot.c             |  47 ++++++++++-
 xen/arch/x86/traps.c               |   6 +-
 xen/common/efi/runtime.c           |  12 +++
 xen/common/smp.c                   |  10 +++
 xen/include/xen/smp.h              |   5 ++
 13 files changed, 281 insertions(+), 20 deletions(-)
xen/arch/x86/domain.c +12 -0
index 94a42ef29cd1..d00ba415877f 100644
@@ -929,6 +929,18 @@ int arch_domain_create(struct domain *d,
 
     d->arch.msr_relaxed = config->arch.misc_flags & XEN_X86_MSR_RELAXED;
 
+    if ( !d->arch.asi && (opt_asi_hvm || opt_asi_pv ) )
+    {
+        /*
+         * This domain is not using ASI, but other domains on the system
+         * possibly are, hence the CPU stacks are on the per-CPU page-table
+         * region.  Add an L3 entry that has all the stacks mapped.
+         */
+        rc = map_all_stacks(d);
+        if ( rc )
+            goto fail;
+    }
+
     return 0;
 
  fail:
xen/arch/x86/include/asm/current.h +5 -0
index 6a021607a1a9..75b9a341f814 100644
@@ -24,6 +24,11 @@
  * 0 - IST Shadow Stacks (4x 1k, read-only)
  */
 
+static inline bool is_shstk_slot(unsigned int i)
+{
+    return (i == 0 || i == PRIMARY_SHSTK_SLOT);
+}
+
 /*
  * Identify which stack page the stack pointer is on.  Returns an index
  * as per the comment above.
xen/arch/x86/include/asm/fixmap.h +5 -0
index bc68a98568ae..d52c1886fcdd 100644
@@ -120,6 +120,11 @@ extern void __set_fixmap_x(
 
 /* per-CPU fixmap area. */
 enum percpu_fixed_addresses {
+    /* For alignment reasons the per-CPU stacks must come first. */
+    PCPU_STACK_START,
+    PCPU_STACK_END = PCPU_STACK_START + NR_CPUS * (1U << STACK_ORDER) - 1,
+#define PERCPU_STACK_IDX(c) (PCPU_STACK_START + (c) * (1U << STACK_ORDER))
+#define PERCPU_STACK_ADDR(c) percpu_fix_to_virt(PERCPU_STACK_IDX(c))
     PCPU_FIX_PV_L4SHADOW,
     __end_of_percpu_fixed_addresses
 };
xen/arch/x86/include/asm/mm.h +5 -1
index f883468b1a7c..b4f1e0399275 100644
@@ -521,7 +521,7 @@ extern struct rangeset *mmio_ro_ranges;
 #define compat_pfn_to_cr3(pfn) (((unsigned)(pfn) << 12) | ((unsigned)(pfn) >> 20))
 #define compat_cr3_to_pfn(cr3) (((unsigned)(cr3) >> 12) | ((unsigned)(cr3) << 20))
 
-void memguard_guard_stack(void *p);
+void memguard_guard_stack(void *p, unsigned int cpu);
 void memguard_unguard_stack(void *p);
 
 struct mmio_ro_emulate_ctxt {
@@ -652,4 +652,8 @@ static inline int destroy_xen_mappings_cpu(unsigned long s, unsigned long e,
     return modify_xen_mappings_cpu(s, e, _PAGE_NONE, cpu);
 }
 
+/* Setup a per-domain slot that maps all pCPU stacks. */
+int map_all_stacks(struct domain *d);
+int add_stack(const void *stack, unsigned int cpu);
+
 #endif /* __ASM_X86_MM_H__ */
xen/arch/x86/include/asm/smp.h +12 -0
index c8c79601343d..a17c609da4b6 100644
@@ -79,6 +79,18 @@ extern bool unaccounted_cpus;
 
 void *cpu_alloc_stack(unsigned int cpu);
 
+/*
+ * Setup the per-CPU area stack mappings.
+ *
+ * @dest_cpu:  CPU where the mappings are to appear.
+ * @stack_cpu: CPU whose stacks should be mapped.
+ */
+void cpu_set_stack_mappings(unsigned int dest_cpu, unsigned int stack_cpu);
+
+#define HAS_ARCH_SMP_CALLFUNC
+void arch_smp_pre_callfunc(unsigned int cpu);
+void arch_smp_post_callfunc(unsigned int cpu);
+
 #endif /* !__ASSEMBLY__ */
 
 #endif
xen/arch/x86/mm.c +117 -8

160 lines not on this page · raw message

xen/arch/x86/setup.c +20 -7
index 5bf81b81b46f..76f7d71b8c1c 100644
@@ -808,8 +808,6 @@ static void __init noreturn reinit_bsp_stack(void)
     /* Update SYSCALL trampolines */
     percpu_traps_init();
 
-    stack_base[0] = stack;
-
     rc = setup_cpu_root_pgt(0);
     if ( rc )
         panic("Error %d setting up PV root page table\n", rc);
@@ -1771,10 +1769,6 @@ void asmlinkage __init noreturn __start_xen(unsigned long mbi_p)
 
     system_state = SYS_STATE_boot;
 
-    bsp_stack = cpu_alloc_stack(0);
-    if ( !bsp_stack )
-        panic("No memory for BSP stack\n");
-
     console_init_ring();
     vesa_init();
 
@@ -1961,6 +1955,16 @@ void asmlinkage __init noreturn __start_xen(unsigned long mbi_p)
 
     alternative_branches();
 
+    /*
+     * Alloc the BSP stack closer to the point where the AP ones also get
+     * allocated - and after the speculation mitigations have been initialized.
+     * In order to set up the shadow stack token correctly Xen needs to know
+     * whether per-CPU mapped stacks are being used.
+     */
+    bsp_stack = cpu_alloc_stack(0);
+    if ( !bsp_stack )
+        panic("No memory for BSP stack\n");
+
     /*
      * Setup the local per-domain L3 for the BSP also, so it matches the state
      * of the APs.
@@ -2065,8 +2069,17 @@ void asmlinkage __init noreturn __start_xen(unsigned long mbi_p)
         info->last_spec_ctrl = default_xen_spec_ctrl;
     }
 
+    stack_base[0] = bsp_stack;
+
     /* Copy the cpu info block, and move onto the BSP stack. */
-    bsp_info = get_cpu_info_from_stack((unsigned long)bsp_stack);
+    if ( opt_asi_hvm || opt_asi_pv )
+    {
+        cpu_set_stack_mappings(0, 0);
+        bsp_info = get_cpu_info_from_stack((unsigned long)PERCPU_STACK_ADDR(0));
+    }
+    else
+        bsp_info = get_cpu_info_from_stack((unsigned long)bsp_stack);
+
     *bsp_info = *info;
 
     asm volatile ("mov %[stk], %%rsp; jmp %c[fn]" ::
xen/arch/x86/smp.c +29 -0
index 04c6a0572319..18a7196195cf 100644
@@ -22,6 +22,7 @@
 #include <asm/hardirq.h>
 #include <asm/hpet.h>
 #include <asm/setup.h>
+#include <asm/spec_ctrl.h>
 #include <irq_vectors.h>
 #include <mach_apic.h>
 
@@ -433,3 +434,31 @@ long cf_check cpu_down_helper(void *data)
         ret = cpu_down(cpu);
     return ret;
 }
+
+void arch_smp_pre_callfunc(unsigned int cpu)
+{
+    if ( (!opt_asi_pv && !opt_asi_hvm) || cpu == smp_processor_id() ||
+         (!current->domain->arch.asi && !is_idle_vcpu(current)) ||
+        /*
+         * CPU#0 still runs on the .init stack when the APs are started, don't
+         * attempt to map such stack.
+         */
+         (!cpu && system_state < SYS_STATE_active) )
+        return;
+
+    cpu_set_stack_mappings(smp_processor_id(), cpu);
+}
+
+void arch_smp_post_callfunc(unsigned int cpu)
+{
+    unsigned int i;
+
+    if ( (!opt_asi_pv && !opt_asi_hvm) || cpu == smp_processor_id() ||
+         (!current->domain->arch.asi && !is_idle_vcpu(current)) )
+        return;
+
+    for ( i = 0; i < (1U << STACK_ORDER); i++ )
+        percpu_clear_fixmap(PERCPU_STACK_IDX(cpu) + i);
+
+    flush_area_local(PERCPU_STACK_ADDR(cpu), FLUSH_ORDER(STACK_ORDER));
+}
xen/arch/x86/smpboot.c +45 -2

63 lines not on this page · raw message

xen/arch/x86/traps.c +4 -2
index b4fb95917023..28513c0e3d6a 100644
@@ -609,10 +609,12 @@ void show_stack_overflow(unsigned int cpu, const struct cpu_user_regs *regs)
     unsigned long esp = regs->rsp;
     unsigned long curr_stack_base = esp & ~(STACK_SIZE - 1);
     unsigned long esp_top, esp_bottom;
+    const void *stack = current->domain->arch.asi ? PERCPU_STACK_ADDR(cpu)
+                                                  : stack_base[cpu];
 
-    if ( _p(curr_stack_base) != stack_base[cpu] )
+    if ( _p(curr_stack_base) != stack )
         printk("Current stack base %p differs from expected %p\n",
-               _p(curr_stack_base), stack_base[cpu]);
+               _p(curr_stack_base), stack);
 
     esp_bottom = (esp | (STACK_SIZE - 1)) + 1;
     esp_top    = esp_bottom - PRIMARY_STACK_SIZE;
xen/common/efi/runtime.c +12 -0
index d952c3ba785e..3a8233ed62ac 100644
@@ -32,6 +32,7 @@ void efi_rs_leave(struct efi_rs_state *state);
 
 #ifndef CONFIG_ARM
 # include <asm/i387.h>
+# include <asm/spec_ctrl.h>
 # include <asm/xstate.h>
 # include <public/platform.h>
 #endif
@@ -85,6 +86,7 @@ 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 };
+    root_pgentry_t *efi_pgt, *idle_pgt;
 
     if ( mfn_eq(efi_l4_mfn, INVALID_MFN) )
         return state;
@@ -98,6 +100,16 @@ struct efi_rs_state efi_rs_enter(void)
 
     efi_rs_on_cpu = smp_processor_id();
 
+    if ( opt_asi_pv || opt_asi_hvm )
+    {
+        /* Insert the idle per-domain slot for the stack mapping. */
+        efi_pgt = map_domain_page(efi_l4_mfn);
+        idle_pgt = maddr_to_virt(idle_vcpu[efi_rs_on_cpu]->arch.cr3);
+        efi_pgt[root_table_offset(PERDOMAIN_VIRT_START)].l4 =
+            idle_pgt[root_table_offset(PERDOMAIN_VIRT_START)].l4;
+        unmap_domain_page(efi_pgt);
+    }
+
     /* prevent fixup_page_fault() from doing anything */
     irq_enter();
 
xen/common/smp.c +10 -0
index a011f541f1ea..04f5aede0d3d 100644
@@ -29,6 +29,7 @@ static struct call_data_struct {
     void (*func) (void *info);
     void *info;
     int wait;
+    unsigned int caller;
     cpumask_t selected;
 } call_data;
 
@@ -63,6 +64,7 @@ void on_selected_cpus(
     call_data.func = func;
     call_data.info = info;
     call_data.wait = wait;
+    call_data.caller = smp_processor_id();
 
     smp_send_call_function_mask(&call_data.selected);
 
@@ -82,6 +84,12 @@ void smp_call_function_interrupt(void)
     if ( !cpumask_test_cpu(cpu, &call_data.selected) )
         return;
 
+    /*
+     * TODO: use bounce buffers to pass callfunc data, so that when using ASI
+     * there's no need to map remote CPU stacks.
+     */
+    arch_smp_pre_callfunc(call_data.caller);
+
     irq_enter();
 
     if ( unlikely(!func) )
@@ -102,6 +110,8 @@ void smp_call_function_interrupt(void)
     }
 
     irq_exit();
+
+    arch_smp_post_callfunc(call_data.caller);
 }
 
 /*
xen/include/xen/smp.h +5 -0
index 2ca9ff1bfcc1..610c279ca24c 100644
@@ -76,4 +76,9 @@ extern void *stack_base[NR_CPUS];
 void initialize_cpu_data(unsigned int cpu);
 int setup_cpu_root_pgt(unsigned int cpu);
 
+#ifndef HAS_ARCH_SMP_CALLFUNC
+static inline void arch_smp_pre_callfunc(unsigned int cpu) {}
+static inline void arch_smp_post_callfunc(unsigned int cpu) {}
+#endif
+
 #endif /* __XEN_SMP_H__ */
Signature · 1 line
2.45.2
#59 lore raw

PATCH 22/22 x86/mm: zero stack on stack switch or reset

In reply to Roger Pau Monne

With the stack mapped on a per-CPU basis there's no risk of other CPUs being able to read the stack contents, but vCPUs running on the current pCPU could read stack rubble from operations of previous vCPUs.

The #DF stack is not zeroed because handling of #DF results in a panic.

---
 xen/arch/x86/include/asm/current.h | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
xen/arch/x86/include/asm/current.h +29 -1
index 75b9a341f814..02b4118b03ef 100644
@@ -177,6 +177,14 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 # define SHADOW_STACK_WORK ""
 #endif
 
+#define ZERO_STACK                                              \
+    "test %[stk_size], %[stk_size];"                            \
+    "jz .L_skip_zeroing.%=;"                                    \
+    "std;"                                                      \
+    "rep stosb;"                                                \
+    "cld;"                                                      \
+    ".L_skip_zeroing.%=:"
+
 #if __GNUC__ >= 9
 # define ssaj_has_attr_noreturn(fn) __builtin_has_attribute(fn, __noreturn__)
 #else
@@ -187,10 +195,24 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 #define switch_stack_and_jump(fn, instr, constr)                        \
     ({                                                                  \
         unsigned int tmp;                                               \
+        bool zero_stack = current->domain->arch.asi;                    \
         BUILD_BUG_ON(!ssaj_has_attr_noreturn(fn));                      \
+        ASSERT(IS_ALIGNED((unsigned long)guest_cpu_user_regs() -        \
+                          PRIMARY_STACK_SIZE +                          \
+                          sizeof(struct cpu_info), PAGE_SIZE));         \
+        if ( zero_stack )                                               \
+        {                                                               \
+            unsigned long stack_top = get_stack_bottom() &              \
+                                      ~(STACK_SIZE - 1);                \
+                                                                        \
+            clear_page((void *)stack_top + IST_MCE * PAGE_SIZE);        \
+            clear_page((void *)stack_top + IST_NMI * PAGE_SIZE);        \
+            clear_page((void *)stack_top + IST_DB  * PAGE_SIZE);        \
+        }                                                               \
         __asm__ __volatile__ (                                          \
             SHADOW_STACK_WORK                                           \
             "mov %[stk], %%rsp;"                                        \
+            ZERO_STACK                                                  \
             CHECK_FOR_LIVEPATCH_WORK                                    \
             instr "[fun]"                                               \
             : [val] "=&r" (tmp),                                        \
@@ -201,7 +223,13 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
               ((PRIMARY_SHSTK_SLOT + 1) * PAGE_SIZE - 8),               \
               [stack_mask] "i" (STACK_SIZE - 1),                        \
               _ASM_BUGFRAME_INFO(BUGFRAME_bug, __LINE__,                \
-                                 __FILE__, NULL)                        \
+                                 __FILE__, NULL),                       \
+              /* For stack zeroing. */                                  \
+              "D" ((void *)guest_cpu_user_regs() - 1),                  \
+              [stk_size] "c"                                            \
+              (zero_stack ? PRIMARY_STACK_SIZE - sizeof(struct cpu_info)\
+                          : 0),                                         \
+              "a" (0)                                                   \
             : "memory" );                                               \
         unreachable();                                                  \
     })
Signature · 1 line
2.45.2
#60 lore raw

Re: [PATCH 22/22] x86/mm: zero stack on stack switch or reset

Quoted 60 lines · Roger Pau Monne

With the stack mapped on a per-CPU basis there's no risk of other CPUs being able to read the stack contents, but vCPUs running on the current pCPU could read stack rubble from operations of previous vCPUs.

The #DF stack is not zeroed because handling of #DF results in a panic.

---
 xen/arch/x86/include/asm/current.h | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
xen/arch/x86/include/asm/current.h +22 -1
index 75b9a341f814..02b4118b03ef 100644
@@ -177,6 +177,14 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 # define SHADOW_STACK_WORK ""
 #endif
 
+#define ZERO_STACK                                              \
+    "test %[stk_size], %[stk_size];"                            \
+    "jz .L_skip_zeroing.%=;"                                    \
+    "std;"                                                      \
+    "rep stosb;"                                                \
+    "cld;"                                                      \
+    ".L_skip_zeroing.%=:"
+
 #if __GNUC__ >= 9
 # define ssaj_has_attr_noreturn(fn) __builtin_has_attribute(fn, __noreturn__)
 #else
@@ -187,10 +195,24 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 #define switch_stack_and_jump(fn, instr, constr)                        \
     ({                                                                  \
         unsigned int tmp;                                               \
+        bool zero_stack = current->domain->arch.asi;                    \
         BUILD_BUG_ON(!ssaj_has_attr_noreturn(fn));                      \
+        ASSERT(IS_ALIGNED((unsigned long)guest_cpu_user_regs() -        \
+                          PRIMARY_STACK_SIZE +                          \
+                          sizeof(struct cpu_info), PAGE_SIZE));         \
+        if ( zero_stack )                                               \
+        {                                                               \
+            unsigned long stack_top = get_stack_bottom() &              \
+                                      ~(STACK_SIZE - 1);                \
+                                                                        \
+            clear_page((void *)stack_top + IST_MCE * PAGE_SIZE);        \
+            clear_page((void *)stack_top + IST_NMI * PAGE_SIZE);        \
+            clear_page((void *)stack_top + IST_DB  * PAGE_SIZE);        \
+        }                                                               \
         __asm__ __volatile__ (                                          \
             SHADOW_STACK_WORK                                           \
             "mov %[stk], %%rsp;"                                        \
+            ZERO_STACK                                                  \
             CHECK_FOR_LIVEPATCH_WORK                                    \
             instr "[fun]"                                               \
             : [val] "=&r" (tmp),                                        \
@@ -201,7 +223,13 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
               ((PRIMARY_SHSTK_SLOT + 1) * PAGE_SIZE - 8),               \
               [stack_mask] "i" (STACK_SIZE - 1),                        \
               _ASM_BUGFRAME_INFO(BUGFRAME_bug, __LINE__,                \
-                                 __FILE__, NULL)                        \

xen/arch/x86/include/asm/current.h unsigned long get_stack_dump_bottom (unsigned long sp); · line 235

Quoted 10 lines
xen/arch/x86/include/asm/current.h +7 -0
+                                 __FILE__, NULL),                       \
+              /* For stack zeroing. */                                  \
+              "D" ((void *)guest_cpu_user_regs() - 1),                  \
+              [stk_size] "c"                                            \
+              (zero_stack ? PRIMARY_STACK_SIZE - sizeof(struct cpu_info)\
+                          : 0),                                         \
+              "a" (0)                                                   \
             : "memory" );                                               \
         unreachable();                                                  \
     })

This looks very expensive.

For starters, switch_stack_and_jump() is used twice in a typical context switch; once in the schedule tail, and again out of hvm_do_resume().

Furthermore, #MC happen never (to many many significant figures), #DB happens never for HVM guests (but does happen for PV), and NMIs are either ~never, or 2Hz which is far less often than the 30ms default timeslice.

So, the overwhelming majority of the time, those 3 calls to clear_page() will be re-zeroing blocks of zeroes.

This can probably be avoided by making use of ist_exit (held in %r12) to only zero an IST stack when leaving it.  This leaves the IRET frame able to be recovered, but with e.g. RFDS, you can do that irrespective, and it's not terribly sensitive.

What about shadow stacks?  You're not zeroing those, and while they're less sensitive than the data stack, there ought to be some reasoning about them.

~Andrew

#61 lore raw

Re: [PATCH 22/22] x86/mm: zero stack on stack switch or reset

Quoted 74 lines · Andrew Cooper
Quoted 60 lines · Roger Pau Monne

With the stack mapped on a per-CPU basis there's no risk of other CPUs being able to read the stack contents, but vCPUs running on the current pCPU could read stack rubble from operations of previous vCPUs.

The #DF stack is not zeroed because handling of #DF results in a panic.

---
 xen/arch/x86/include/asm/current.h | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
xen/arch/x86/include/asm/current.h +22 -1
index 75b9a341f814..02b4118b03ef 100644
@@ -177,6 +177,14 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 # define SHADOW_STACK_WORK ""
 #endif
 
+#define ZERO_STACK                                              \
+    "test %[stk_size], %[stk_size];"                            \
+    "jz .L_skip_zeroing.%=;"                                    \
+    "std;"                                                      \
+    "rep stosb;"                                                \
+    "cld;"                                                      \
+    ".L_skip_zeroing.%=:"
+
 #if __GNUC__ >= 9
 # define ssaj_has_attr_noreturn(fn) __builtin_has_attribute(fn, __noreturn__)
 #else
@@ -187,10 +195,24 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 #define switch_stack_and_jump(fn, instr, constr)                        \
     ({                                                                  \
         unsigned int tmp;                                               \
+        bool zero_stack = current->domain->arch.asi;                    \
         BUILD_BUG_ON(!ssaj_has_attr_noreturn(fn));                      \
+        ASSERT(IS_ALIGNED((unsigned long)guest_cpu_user_regs() -        \
+                          PRIMARY_STACK_SIZE +                          \
+                          sizeof(struct cpu_info), PAGE_SIZE));         \
+        if ( zero_stack )                                               \
+        {                                                               \
+            unsigned long stack_top = get_stack_bottom() &              \
+                                      ~(STACK_SIZE - 1);                \
+                                                                        \
+            clear_page((void *)stack_top + IST_MCE * PAGE_SIZE);        \
+            clear_page((void *)stack_top + IST_NMI * PAGE_SIZE);        \
+            clear_page((void *)stack_top + IST_DB  * PAGE_SIZE);        \
+        }                                                               \
         __asm__ __volatile__ (                                          \
             SHADOW_STACK_WORK                                           \
             "mov %[stk], %%rsp;"                                        \
+            ZERO_STACK                                                  \
             CHECK_FOR_LIVEPATCH_WORK                                    \
             instr "[fun]"                                               \
             : [val] "=&r" (tmp),                                        \
@@ -201,7 +223,13 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
               ((PRIMARY_SHSTK_SLOT + 1) * PAGE_SIZE - 8),               \
               [stack_mask] "i" (STACK_SIZE - 1),                        \
               _ASM_BUGFRAME_INFO(BUGFRAME_bug, __LINE__,                \
-                                 __FILE__, NULL)                        \

xen/arch/x86/include/asm/current.h unsigned long get_stack_dump_bottom (unsigned long sp); · line 235

Quoted 10 lines
xen/arch/x86/include/asm/current.h +7 -0
+                                 __FILE__, NULL),                       \
+              /* For stack zeroing. */                                  \
+              "D" ((void *)guest_cpu_user_regs() - 1),                  \
+              [stk_size] "c"                                            \
+              (zero_stack ? PRIMARY_STACK_SIZE - sizeof(struct cpu_info)\
+                          : 0),                                         \
+              "a" (0)                                                   \
             : "memory" );                                               \
         unreachable();                                                  \
     })

This looks very expensive.

Quoted 2 lines

For starters, switch_stack_and_jump() is used twice in a typical context switch; once in the schedule tail, and again out of hvm_do_resume().

Right, it's the reset_stack_and_call_ind() at the end of context switch and then the reset_stack_and_jump() in the HVM tail context switch handlers.

One option would be to only do the stack zeroing from the reset_stack_and_call_ind() call in context_switch().

I've got no idea how expensive this is, I might try to run some benchmarks to get some figures. I was planning on running two VMs with 1 vCPU each, both pinned to the same pCPU.

Quoted 6 lines

Furthermore, #MC happen never (to many many significant figures), #DB happens never for HVM guests (but does happen for PV), and NMIs are either ~never, or 2Hz which is far less often than the 30ms default timeslice.

Quoted 7 lines

So, the overwhelming majority of the time, those 3 calls to clear_page() will be re-zeroing blocks of zeroes.

This can probably be avoided by making use of ist_exit (held in %r12) to only zero an IST stack when leaving it.  This leaves the IRET frame able to be recovered, but with e.g. RFDS, you can do that irrespective, and it's not terribly sensitive.

I could look into that, TBH I was bordeline with clearing the IST stacks, as I wasn't convinced there could be anything sensitive there, but again couldn't convince myself there's nothing sensitive now, nor can be in the future.

Quoted 3 lines

What about shadow stacks?  You're not zeroing those, and while they're less sensitive than the data stack, there ought to be some reasoning about them.

I've assumed that shadow stacks only contained the expected return addresses, and hence won't be considered sensitive information, but maybe I was too lax.

An attacker could get execution traces of the previous vCPU, and that might be useful for some exploits?

Thanks, Roger.

#62 lore raw

Re: [PATCH 22/22] x86/mm: zero stack on stack switch or reset

In reply to Roger Pau Monne
Quoted 16 lines · Roger Pau Monne

With the stack mapped on a per-CPU basis there's no risk of other CPUs being able to read the stack contents, but vCPUs running on the current pCPU could read stack rubble from operations of previous vCPUs.

The #DF stack is not zeroed because handling of #DF results in a panic.

---
 xen/arch/x86/include/asm/current.h | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
xen/arch/x86/include/asm/current.h +0 -0
index 75b9a341f814..02b4118b03ef 100644

xen/arch/x86/include/asm/current.h unsigned long get_stack_dump_bottom (unsigned long sp); · line 185

Quoted 9 lines
xen/arch/x86/include/asm/current.h +6 -0
@@ -177,6 +177,14 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 # define SHADOW_STACK_WORK ""
 #endif
 
+#define ZERO_STACK                                              \
+    "test %[stk_size], %[stk_size];"                            \
+    "jz .L_skip_zeroing.%=;"                                    \
+    "std;"                                                      \
+    "rep stosb;"                                                \
+    "cld;"                                                      \

Is ERMS actually helping with backwards copies? I didn't think so, and hence it may be that REP STOSQ might be more efficient here?

Jan

#63 lore raw

Re: [PATCH 22/22] x86/mm: zero stack on stack switch or reset

Quoted 20 lines · Jan Beulich
Quoted 19 lines · Roger Pau Monne

With the stack mapped on a per-CPU basis there's no risk of other CPUs being able to read the stack contents, but vCPUs running on the current pCPU could read stack rubble from operations of previous vCPUs.

The #DF stack is not zeroed because handling of #DF results in a panic.

---
 xen/arch/x86/include/asm/current.h | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
xen/arch/x86/include/asm/current.h +0 -0
index 75b9a341f814..02b4118b03ef 100644
@@ -177,6 +177,14 @@ unsigned long get_stack_dump_bottom (unsigned long sp);
 # define SHADOW_STACK_WORK ""
 #endif
 
Quoted 9 lines

xen/arch/x86/include/asm/current.h unsigned long get_stack_dump_bottom (unsigned long sp); · line 185

Quoted 6 lines
xen/arch/x86/include/asm/current.h +6 -0
+#define ZERO_STACK                                              \
+    "test %[stk_size], %[stk_size];"                            \
+    "jz .L_skip_zeroing.%=;"                                    \
+    "std;"                                                      \
+    "rep stosb;"                                                \
+    "cld;"                                                      \

Is ERMS actually helping with backwards copies? I didn't think so, and hence it may be that REP STOSQ might be more efficient here?

Possibly, Intel optimization guide says:

"However, setting the DF to force REP MOVSB to copy bytes from high towards low addresses will experience significant performance degradation."

I will see what I can do.

Thanks, Roger.