[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[PATCH v8 60/65] x86/hvm: map only its own CPU's stack in a cpu-stack vCPU's page-tables



With per-CPU stacks every pCPU runs on its stack at PCPU_STACK_VIRT(),
and every root page-table maps every pCPU's stack there, through the
idle domain's stack sub-area.  A vCPU of a vCPU-PT domain has page
tables of its own down to its per-domain L3, which is loaded on one
pCPU at a time, so it can map less: the stack of the pCPU it runs on,
and no other.

Give each pCPU an L2 and an L1 for the stack sub-area which map its own
stack alone, built with the stack as the pCPU comes up
(cpu_stack_map(); domain heap pages, never freed).  A vCPU of a
cpu_stack domain has, in the stack sub-area of its own per-domain L3,
the L2 of the pCPU it last ran on (v->arch.stack_cpu); the entry is
empty until the vCPU first runs.  When the vCPU is about to run on
another pCPU, context_switch() points the entry at that pCPU's L2,
through one helper, vcpu_set_stack_cpu(), which maps the L3
transiently, writes the entry and unmaps.  Nothing is written while a
vCPU stays on its pCPU, including a return from idle while that pCPU
still holds its state.

The store comes after the FLUSH_VCPU_STATE catch-up and before
local_irq_disable() in context_switch().  Why that window is safe:

 - schedule() drops the scheduler lock before sched_context_switch()
   calls context_switch(), but next was marked running under it, so no
   other pCPU can pick next meanwhile.  An interrupt returning to Xen
   does not run softirqs, so schedule() does not nest here.

 - A vCPU's page-tables are loaded only on the pCPU holding its state:
   running it, or keeping it lazily after a switch to idle, and that is
   the pCPU it last ran on.  If another pCPU holds next's state,
   context_switch() has just had it give it up (FLUSH_VCPU_STATE, which
   waits for the switch to idle's page-tables).  This pCPU holds it only
   if next last ran here, and then nothing is written.  So next's
   page-tables are loaded nowhere while the entry changes.

 - Interrupts are still on, and current is still prev, so
   map_domain_page() may complete this pCPU's own lazy switch to idle,
   as it does elsewhere.  Inside __context_switch(), with interrupts off
   and current already next, it would re-enter __context_switch().  The
   mapping comes from the mapcache of whichever vCPU's page-tables are
   loaded, or from the full directmap.

 - Common code does per-migration work at the same point already:
   vcpu_move_irqs() in sched_context_switch().

No TLB flush is needed.  Every page-table which maps PCPU_STACK_VIRT(N)
maps pCPU N's stack there, and stacks are never freed in this mode, so a
stale translation could map more than next's page-tables do, never
anything else.  And none survives: the stack mappings are not global,
and every pCPU which ran on next's page-tables has since loaded another
root through switch_cr3_cr4(), as this pCPU now loads next's, which
leaves no non-global translation of the previous root usable by the
time it returns, with or without PCIDs.  Within switch_cr3_cr4(), when
PCIDE goes from 1 to 0, the flush is the CR4 write after the CR3 write:
in between, for a few instructions with interrupts off, plus any NMI
or #MC handler that runs there, translations tagged with the incoming
PCID remain usable.

Checks: before write_ptbase() loads a cpu_stack vCPU's page-tables,
the vCPU's stack_cpu must name this pCPU, in every build, as
page-tables mapping another pCPU's stack would leave this one without a
stack at the CR3 write, with nothing able to report it; once they are
loaded, debug builds check that the entry in use, read through the
linear page-table, names this pCPU's L2; and at bring-up, debug builds
walk each pCPU's L2 and check that it maps the 8 pages of its own stack
and nothing else.

The vCPU's page-tables still reach every stack through the directmap
while stacks are xenheap pages, which the sparse directmap view keeps
too.  PV domains, HVM domains without vCPU-PT and the idle domain keep
mapping every pCPU's stack.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: George Dunlap <gwd@xxxxxxxxxxxxxx>
---
Changes in v8:
- New in this version.

Changes since previously posted version ("x86: adventures in Address Space 
Isolation", v2):
- New: replaces the update in "x86/mm: switch to a per-CPU mapped stack
  when using ASI", which emptied and rewrote the incoming vCPU's stack
  mappings at every switch, with interrupts off.  The mapping now
  changes only when a vCPU moves to another pCPU.
---
 xen/arch/x86/domain.c             |  12 ++
 xen/arch/x86/include/asm/config.h |   4 +-
 xen/arch/x86/include/asm/domain.h |  12 ++
 xen/arch/x86/include/asm/smp.h    |  12 +-
 xen/arch/x86/mm.c                 | 197 ++++++++++++++++++++++++++++--
 xen/arch/x86/setup.c              |   4 +-
 xen/arch/x86/smpboot.c            |   4 +-
 xen/arch/x86/spec_ctrl.c          |   5 +
 8 files changed, 232 insertions(+), 18 deletions(-)

diff --git a/xen/arch/x86/domain.c b/xen/arch/x86/domain.c
index d1bb40fba4..8ca6018118 100644
--- a/xen/arch/x86/domain.c
+++ b/xen/arch/x86/domain.c
@@ -2331,6 +2331,18 @@ void noreturn context_switch(struct vcpu *prev, struct 
vcpu *next)
         ASSERT(!vcpu_cpu_dirty(next));
     }
 
+    /*
+     * The page-tables of a cpu_stack vCPU map the stack of the CPU it last
+     * ran on, and no other: if that is not this CPU, they need this CPU's
+     * stack before they are loaded.  They are loaded only on a CPU holding
+     * next's state, which is the CPU next last ran on: if that is another
+     * CPU, the flush above has just made it give the state up.  So next's
+     * page-tables are loaded nowhere while vcpu_set_stack_cpu() edits them,
+     * with interrupts still on, as the transient mapping it takes may need.
+     */
+    if ( nextd->arch.asi.cpu_stack && next->arch.stack_cpu != cpu )
+        vcpu_set_stack_cpu(next);
+
     _update_runstate_area(prev);
     vpmu_switch_from(prev);
     np2m_schedule(NP2M_SCHEDLE_OUT);
diff --git a/xen/arch/x86/include/asm/config.h 
b/xen/arch/x86/include/asm/config.h
index 079dde1340..061a6e9ca0 100644
--- a/xen/arch/x86/include/asm/config.h
+++ b/xen/arch/x86/include/asm/config.h
@@ -338,7 +338,9 @@ extern unsigned long xen_phys_start;
  * Per-CPU stacks.  The fifth per-domain-mapping sub-area: when in use, each
  * CPU runs on its stack at PCPU_STACK_VIRT(cpu), in every root page-table it
  * loads.  The page-tables behind the sub-area are the idle domain's, mapping
- * every CPU's stack, which every other per-domain area shares by reference.
+ * every CPU's stack, which every other per-domain area shares by reference,
+ * except that of a cpu_stack vCPU: it refers to the page-tables of the CPU
+ * the vCPU last ran on, which map that CPU's stack alone.
  */
 #define PCPU_STACK_SLOT          4
 #define PCPU_STACK_VIRT_START    PERDOMAIN_VIRT_SLOT(PCPU_STACK_SLOT)
diff --git a/xen/arch/x86/include/asm/domain.h 
b/xen/arch/x86/include/asm/domain.h
index 68764f8d39..ef60cdda11 100644
--- a/xen/arch/x86/include/asm/domain.h
+++ b/xen/arch/x86/include/asm/domain.h
@@ -495,6 +495,12 @@ struct arch_domain
         /* Give each vCPU its own per-domain area (HVM only). */
         bool vcpu_pt:1;
 
+        /*
+         * Give each vCPU (vcpu_pt) page-tables which map, at
+         * PCPU_STACK_VIRT(), the stack of the CPU it runs on, and no other.
+         */
+        bool cpu_stack:1;
+
         /* The domain's root page-tables carry the sparse directmap view. */
         bool sparse_dmap:1;
     } asi;
@@ -726,6 +732,12 @@ struct arch_vcpu
     /* Per-vCPU L3 for the per-domain slot; NULL in a non-vCPU-PT domain. */
     struct page_info *pervcpu_l3_pg;
 
+    /*
+     * With d->arch.asi.cpu_stack, the CPU whose stack pervcpu_l3_pg maps,
+     * which the vCPU last ran on, or NR_CPUS before it first runs.
+     */
+    unsigned int stack_cpu;
+
     struct {
         bool next_interrupt_enabled;
     } monitor;
diff --git a/xen/arch/x86/include/asm/smp.h b/xen/arch/x86/include/asm/smp.h
index 6836076076..d8195923f7 100644
--- a/xen/arch/x86/include/asm/smp.h
+++ b/xen/arch/x86/include/asm/smp.h
@@ -90,12 +90,18 @@ void *cpu_alloc_stack(unsigned int cpu);
 /* Give the idle domain the per-domain area mapping every CPU's stack. */
 void cpu_stack_init(void);
 
-/* Map @cpu's stack at PCPU_STACK_VIRT(@cpu) in the idle domain's area. */
-void cpu_stack_map(unsigned int cpu);
+/*
+ * Map @cpu's stack at PCPU_STACK_VIRT(@cpu): in the idle domain's area, and in
+ * page-tables of @cpu's own, which map that stack alone.
+ */
+int cpu_stack_map(unsigned int cpu);
 
 struct vcpu;
 /* Set up the per-CPU stack sub-area of a non-idle vCPU's per-domain area. */
-void vcpu_stack_mappings_init(const struct vcpu *v);
+void vcpu_stack_mappings_init(struct vcpu *v);
+
+/* Map this CPU's stack, and no other, in a cpu_stack vCPU's page-tables. */
+void vcpu_set_stack_cpu(struct vcpu *v);
 
 #endif /* !__ASSEMBLER__ */
 
diff --git a/xen/arch/x86/mm.c b/xen/arch/x86/mm.c
index 4a79e8af3a..ff119c6134 100644
--- a/xen/arch/x86/mm.c
+++ b/xen/arch/x86/mm.c
@@ -562,6 +562,13 @@ void make_cr3(struct vcpu *v, mfn_t mfn)
     }
 }
 
+/*
+ * Per CPU, an L2 for the per-CPU stack sub-area, with one L1, mapping that
+ * CPU's stack and nothing else (cpu_stack_map()).  Allocated when the CPU
+ * first comes up, and never freed: per-vCPU L3s refer to it.
+ */
+static struct page_info *cpu_stack_l2[NR_CPUS];
+
 void write_ptbase(struct vcpu *v)
 {
     const struct domain *d = v->domain;
@@ -571,6 +578,13 @@ void write_ptbase(struct vcpu *v)
     new_cr4 = (is_pv_domain(d) && !is_idle_domain(d))
               ? pv_make_cr4(v) : mmu_cr4_features;
 
+    /*
+     * A cpu_stack vCPU's page-tables map the stack of the CPU it last ran on
+     * alone: loaded on another CPU, they would leave it without a stack at
+     * the CR3 write, with nothing able to report it.
+     */
+    BUG_ON(d->arch.asi.cpu_stack && v->arch.stack_cpu != smp_processor_id());
+
     if ( is_pv_domain(d) && d->arch.pv.xpti )
     {
         cpu_info->root_pgt_changed = true;
@@ -588,6 +602,12 @@ void write_ptbase(struct vcpu *v)
         switch_cr3_cr4(v, v->arch.cr3, new_cr4);
         cpu_info->pv_cr3 = 0;
     }
+
+    /* Loaded: check the entry in use, through the linear page-table. */
+    ASSERT(!d->arch.asi.cpu_stack ||
+           mfn_eq(l3e_get_mfn(__linear_l3_table[
+                                  l3_linear_offset(PCPU_STACK_VIRT_START)]),
+                  page_to_mfn(cpu_stack_l2[smp_processor_id()])));
 }
 
 /*
@@ -6721,38 +6741,155 @@ void __init cpu_stack_init(void)
     efi_update_l4_pgtable(slot, l4e);
 }
 
+/* Not global: page tables map the sub-area differently. */
+static unsigned int stack_page_flags(unsigned int i)
+{
+    return is_shstk_slot(i) ? __PAGE_HYPERVISOR_SHSTK : __PAGE_HYPERVISOR_RW;
+}
+
+/*
+ * Walk the stack page-tables under @l2pg, the L2 of a per-CPU stack sub-area.
+ * Returns the number of pages mapped as cpu_stack_map() maps them, page i of
+ * CPU c's stack at PCPU_STACK_VIRT(c) + i * PAGE_SIZE with the flags of
+ * stack_page_flags(i), for c == @cpu, or for any CPU if @cpu is NR_CPUS.
+ * *@other counts the pages mapped otherwise.
+ */
+static unsigned int stack_l2_walk(const struct page_info *l2pg,
+                                  unsigned int cpu, unsigned int *other)
+{
+    const l2_pgentry_t *l2tab = __map_domain_page(l2pg);
+    unsigned int i, j, n = 0;
+
+    *other = 0;
+
+    for ( i = 0; i < L2_PAGETABLE_ENTRIES; i++ )
+    {
+        const l1_pgentry_t *l1tab;
+
+        if ( !(l2e_get_flags(l2tab[i]) & _PAGE_PRESENT) )
+            continue;
+
+        if ( l2e_get_flags(l2tab[i]) & _PAGE_PSE )
+        {
+            *other += L1_PAGETABLE_ENTRIES;
+            continue;
+        }
+
+        l1tab = map_l1t_from_l2e(l2tab[i]);
+
+        for ( j = 0; j < L1_PAGETABLE_ENTRIES; j++ )
+        {
+            unsigned long idx = ((unsigned long)i << PAGETABLE_ORDER) + j;
+            unsigned long c = idx >> STACK_ORDER;
+            unsigned int pg = (unsigned int)idx & ((1U << STACK_ORDER) - 1);
+
+            if ( !(l1e_get_flags(l1tab[j]) & _PAGE_PRESENT) )
+                continue;
+
+            if ( (cpu == NR_CPUS || c == cpu) && c < nr_cpu_ids &&
+                 stack_pg[c] &&
+                 mfn_eq(l1e_get_mfn(l1tab[j]),
+                        mfn_add(page_to_mfn(stack_pg[c]), pg)) &&
+                 l1e_get_flags(l1tab[j]) == stack_page_flags(pg) )
+                n++;
+            else
+                (*other)++;
+        }
+
+        unmap_domain_page(l1tab);
+    }
+
+    unmap_domain_page(l2tab);
+
+    return n;
+}
+
 /*
  * Map @cpu's stack at PCPU_STACK_VIRT(@cpu) in the idle domain's per-domain
- * area, and so in every root page-table sharing its stack sub-area.
+ * area, and so in every root page-table sharing its stack sub-area; and in
+ * @cpu's own stack L2, which the per-vCPU L3s of cpu_stack vCPUs running on
+ * @cpu refer to.  A CPU coming back keeps its stack: the entries are written
+ * again with the same values.
  */
-void cpu_stack_map(unsigned int cpu)
+int cpu_stack_map(unsigned int cpu)
 {
+    unsigned long va;
+    nodeid_t node;
+    unsigned int memflags;
     mfn_t mfn;
+    l2_pgentry_t *l2tab;
+    l1_pgentry_t *l1tab;
     unsigned int i;
 
     ASSERT(cpu_stack_enabled);
     BUG_ON(cpu >= nr_cpu_ids || !stack_pg[cpu]);
 
+    va = PCPU_STACK_VIRT(cpu);
+    node = cpu_to_node(cpu);
+    memflags = node != NUMA_NO_NODE ? MEMF_node(node) : 0;
     mfn = page_to_mfn(stack_pg[cpu]);
 
     for ( i = 0; i < (1U << STACK_ORDER); i++ )
     {
         mfn_t m = mfn_add(mfn, i);
 
-        populate_perdomain_mapping(idle_vcpu[0],
-                                   PCPU_STACK_VIRT(cpu) + i * PAGE_SIZE,
-                                   &m, 1,
-                                   is_shstk_slot(i) ? __PAGE_HYPERVISOR_SHSTK
-                                                    : __PAGE_HYPERVISOR_RW);
+        populate_perdomain_mapping(idle_vcpu[0], va + i * PAGE_SIZE, &m, 1,
+                                   stack_page_flags(i));
+    }
+
+    if ( !cpu_stack_l2[cpu] )
+    {
+        struct page_info *l2pg = alloc_domheap_page(NULL, memflags);
+        struct page_info *l1pg = alloc_domheap_page(NULL, memflags);
+
+        if ( !l2pg || !l1pg )
+        {
+            if ( l2pg )
+                free_domheap_page(l2pg);
+            if ( l1pg )
+                free_domheap_page(l1pg);
+            return -ENOMEM;
+        }
+
+        clear_domain_page(page_to_mfn(l2pg));
+        clear_domain_page(page_to_mfn(l1pg));
+
+        l2tab = __map_domain_page(l2pg);
+        l2tab[l2_table_offset(va)] =
+            l2e_from_page(l1pg, __PAGE_HYPERVISOR_RW);
+        unmap_domain_page(l2tab);
+
+        cpu_stack_l2[cpu] = l2pg;
+    }
+
+    l2tab = __map_domain_page(cpu_stack_l2[cpu]);
+    l1tab = map_l1t_from_l2e(l2tab[l2_table_offset(va)]);
+    for ( i = 0; i < (1U << STACK_ORDER); i++ )
+        l1e_write(&l1tab[l1_table_offset(va + i * PAGE_SIZE)],
+                  l1e_from_mfn(mfn_add(mfn, i), stack_page_flags(i)));
+    unmap_domain_page(l1tab);
+    unmap_domain_page(l2tab);
+
+    if ( IS_ENABLED(CONFIG_DEBUG) )
+    {
+        unsigned int other;
+
+        /* @cpu's own stack L2 maps @cpu's 8 stack pages, and no others. */
+        BUG_ON(stack_l2_walk(cpu_stack_l2[cpu], cpu, &other) !=
+               (1U << STACK_ORDER) || other);
     }
+
+    return 0;
 }
 
 /*
  * Every other per-domain L3, a domain's or a vCPU's, shares the idle domain's
- * stack sub-area by reference, so that it maps every CPU's stack too.
+ * stack sub-area by reference, so that it maps every CPU's stack too, except
+ * that of a vCPU of a cpu_stack domain: it maps the stack of the CPU the vCPU
+ * runs on alone, from when the vCPU first runs (vcpu_set_stack_cpu()).
  * @v's per-domain L3 exists.
  */
-void vcpu_stack_mappings_init(const struct vcpu *v)
+void vcpu_stack_mappings_init(struct vcpu *v)
 {
     struct page_info *idle_l3pg = idle_vcpu[0]->domain->arch.perdomain_l3_pg;
     l3_pgentry_t *l3tab;
@@ -6760,6 +6897,12 @@ void vcpu_stack_mappings_init(const struct vcpu *v)
     ASSERT(cpu_stack_enabled && !is_idle_vcpu(v));
     BUG_ON(!idle_l3pg);
 
+    if ( v->domain->arch.asi.cpu_stack )
+    {
+        v->arch.stack_cpu = NR_CPUS;
+        return;
+    }
+
     l3tab = __map_domain_page(perdomain_l3(v));
     if ( !(l3e_get_flags(l3tab[PCPU_STACK_SLOT]) & _PAGE_PRESENT) )
     {
@@ -6771,6 +6914,38 @@ void vcpu_stack_mappings_init(const struct vcpu *v)
     unmap_domain_page(l3tab);
 }
 
+/*
+ * Map the stack of this CPU, and no other CPU's, in the page-tables of @v, a
+ * vCPU of a cpu_stack domain about to run here, having last run on another
+ * CPU or never: point the per-CPU stack sub-area of @v's own per-domain L3 at
+ * this CPU's stack L2.  The one helper which writes the entry.  No CPU may
+ * have @v's page-tables loaded meanwhile.
+ *
+ * No TLB flush is needed: every page-table which maps PCPU_STACK_VIRT(c) maps
+ * CPU c's stack there, and no stack is freed while per-CPU stacks are in use,
+ * so a stale translation could map more than @v's page-tables do, never
+ * anything else; and the stack mappings are not global, so switch_cr3_cr4(),
+ * on the CPU @v left as on this one, leaves none usable.
+ */
+void vcpu_set_stack_cpu(struct vcpu *v)
+{
+    unsigned int cpu = smp_processor_id();
+    l3_pgentry_t *l3tab;
+
+    ASSERT(v->domain->arch.asi.cpu_stack);
+    ASSERT(local_irq_is_enabled());
+    ASSERT(v != current && v->is_running);
+    BUG_ON(!cpu_stack_l2[cpu]);
+    BUG_ON(vcpu_cpu_dirty(v));
+
+    l3tab = __map_domain_page(v->arch.pervcpu_l3_pg);
+    l3e_write(&l3tab[PCPU_STACK_SLOT],
+              l3e_from_page(cpu_stack_l2[cpu], __PAGE_HYPERVISOR_RW));
+    unmap_domain_page(l3tab);
+
+    v->arch.stack_cpu = cpu;
+}
+
 /*
  * Take @nr slots of @v's state window, from @idx, out of the per-domain
  * area, before the caller frees the pages behind them: the pages are the
@@ -6827,7 +7002,9 @@ static void free_perdomain_l3(struct page_info *l3pg)
     {
         /*
          * The per-CPU stack sub-area holds page-tables the area does not
-         * own: the idle domain's, shared by reference.
+         * own: the idle domain's, shared by reference, or, in the L3 of a
+         * cpu_stack vCPU, the stack L2 of the CPU it last ran on
+         * (cpu_stack_l2[], never freed).
          */
         if ( i == PCPU_STACK_SLOT )
             continue;
diff --git a/xen/arch/x86/setup.c b/xen/arch/x86/setup.c
index e2d7b46cf1..f760498c89 100644
--- a/xen/arch/x86/setup.c
+++ b/xen/arch/x86/setup.c
@@ -2140,8 +2140,8 @@ void asmlinkage __init noreturn __start_xen(void)
     bsp_stack = cpu_alloc_stack(0); /* Needs to know IDT vs FRED */
     if ( !bsp_stack )
         panic("No memory for BSP stack\n");
-    if ( cpu_stack_enabled )
-        cpu_stack_map(0);
+    if ( cpu_stack_enabled && cpu_stack_map(0) )
+        panic("No memory for the BSP's stack mappings\n");
 
     /*
      * NB: when running as a PV shim VCPUOP_up/down is wired to the shim
diff --git a/xen/arch/x86/smpboot.c b/xen/arch/x86/smpboot.c
index 2943d56a13..bff09931ab 100644
--- a/xen/arch/x86/smpboot.c
+++ b/xen/arch/x86/smpboot.c
@@ -1095,8 +1095,8 @@ static int cpu_smpboot_alloc(unsigned int cpu)
          (stack_base[cpu] = cpu_alloc_stack(cpu)) == NULL )
             goto out;
 
-    if ( cpu_stack_enabled )
-        cpu_stack_map(cpu);
+    if ( cpu_stack_enabled && cpu_stack_map(cpu) )
+        goto out;
 
     info = get_cpu_info_from_stack((unsigned long)stack_base[cpu]);
     memset(info, 0, sizeof(*info));
diff --git a/xen/arch/x86/spec_ctrl.c b/xen/arch/x86/spec_ctrl.c
index c306776374..eb8da9ec28 100644
--- a/xen/arch/x86/spec_ctrl.c
+++ b/xen/arch/x86/spec_ctrl.c
@@ -2121,6 +2121,11 @@ void spec_ctrl_init_domain(struct domain *d)
     d->arch.asi.vcpu_pt = !pv && (is_hardware_domain(d) ? opt_vcpu_pt_hwdom
                                                         : opt_vcpu_pt_hvm);
 
+    /* Per-CPU stacks need the vCPU's own per-domain area (vcpu_pt). */
+    d->arch.asi.cpu_stack = cpu_stack_enabled && d->arch.asi.vcpu_pt &&
+                            (is_hardware_domain(d) ? opt_pvh_cpu_stack_hwdom
+                                                   : opt_cpu_stack_hvm);
+
     /*
      * The sparse directmap view needs a mapcache: PV domains all have one,
      * HVM domains through per-vCPU page-tables.  A PV domain using XPTI
-- 
2.56.0




 


Rackspace

Lists.xenproject.org is hosted with RackSpace, monitoring our
servers 24x7x365 and backed by RackSpace's Fanatical Support®.