Skip to contentSkip to conversation

HVM x86 enhancements to run Xen deprivileged mode operations

RFC In review Ben Catterall 7 participants 53 messages Aug 6, 2015 – Aug 20, 2015

lore
Share & tools
lore
#0 lore raw

cover HVM x86 enhancements to run Xen deprivileged mode operations

Hi all,

I have a working base for this and would appreciate feedback at this point to evaluate if it is moving in the right direction.

Many thanks in advance,
Ben

The aim of this work is to create a proof-of-concept to establish if it is feasible to move certain Xen operations into a deprivileged context to mitigate the impact of a bug or compromise in such areas. An example would be x86_emulate or virtual device emulation which is not done in QEMU for performance reasons.

This patch series contains the underlying support mechanisms for this mode, which include:
- Setting up the necessary monitor page table entries for the deprivileged code, data and stack regions.
- Moving into and out of this mode
- Handle system calls from this mode
- Trapping exceptions taken whilst in this mode

Performance testing
-------------------
Performance testing indicates that the overhead for this deprivileged mode is approximately 25%. This overhead is the cost of moving into deprivileged mode and then fully back out of deprivileged mode.

I performed 100000 writes to a single I/O port on an Intel 2.2GHz Xeon E5-2407 0 processor. This was done from a python script within the HVM guest using time.time() and running Debian Jessie. Each write was trapped to cause a vmexit and the time for each write was calculated. These experiments were repeated. Note that only the host and this HVM guest were running (both Debian Jessie) during the experiments.

20e-6 seconds was the average time for performing the write without the
deprivileged code running.
25e-6 seconds was the average time for performing the write with an entry and
exit from deprvileged mode.

Further Work
------------
- Support migration of vcpus between pcpus. This will likely be done by using a hard affinity to a pcpu and setting a 'migration pending' flag so that once we return from deprivileged mode and the stack has unwound, we can then migrate the vcpu.
- Prevent DoS attacks on migration: A counter is needed to prevent a spinning deprivileged mode from preventing migration. We could count the number of quanta which have passed since we failed to migrate, then migrate when it becomes too high.

- Add support for SVM and test on AMD processors.
- We need to get the host MSRs for AMD SVM mode.

#1 lore raw

RFC 1/4 HVM x86 deprivileged mode: Page allocation helper

This allocation function is used by the deprivileged mode initialisation code to allocate pages for the new page table mappings and page frames on the HAP page heap.

---
 xen/arch/x86/mm/hap/hap.c    | 23 +++++++++++++++++++++++
 xen/include/asm-x86/domain.h |  1 +
 xen/include/asm-x86/hap.h    |  5 +++++
 3 files changed, 29 insertions(+)
xen/arch/x86/mm/hap/hap.c +23 -0
index d375c4d..593cba7 100644
@@ -844,6 +844,29 @@ static const struct paging_mode hap_paging_long_mode = {
     .guest_levels           = 4
 };
 
+/************************************************/
+/*               HAP HVM functions              */
+/************************************************/
+struct page_info *hvm_alloc_page(struct domain *d)
+{
+    struct page_info *pg;
+
+    if( (pg = hap_alloc(d)) == NULL )
+    {
+        HAP_ERROR("HVM: Out of memory allocating HVM page\n");
+        domain_crash(d);
+        return NULL;
+    }
+
+    ASSERT(paging_locked_by_me(d));
+
+    /* Track our used pages */
+    page_list_add(pg, &d->arch.paging.hap.hvmlist);
+
+    return pg;
+}
+
+
 /*
  * Local variables:
  * mode: C
xen/include/asm-x86/domain.h +1 -0
index 0fce09e..c46a31a 100644
@@ -154,6 +154,7 @@ struct shadow_vcpu {
 /************************************************/
 struct hap_domain {
     struct page_list_head freelist;
+    struct page_list_head hvmlist;  /* HVM usermode page allocation */
     unsigned int      total_pages;  /* number of pages allocated */
     unsigned int      free_pages;   /* number of pages on freelists */
     unsigned int      p2m_pages;    /* number of pages allocates to p2m */
xen/include/asm-x86/hap.h +5 -0
index bd87481..0432eb5 100644
@@ -48,6 +48,11 @@ int   hap_track_dirty_vram(struct domain *d,
 extern const struct paging_mode *hap_paging_get_mode(struct vcpu *);
 void hap_set_alloc_for_pvh_dom0(struct domain *d, unsigned long num_pages);
 
+/************************************************/
+/*               hap HVM functions              */
+/************************************************/
+
+struct page_info *hvm_alloc_page(struct domain *d);
 #endif /* XEN_HAP_H */
 
 /*
Signature · 1 line
2.1.4
#9 lore raw

RFC 2/4 HVM x86 deprivileged mode: Create deprivileged page tables

In reply to Ben Catterall

The paging structure mappings for the deprivileged mode are added to the monitor page table for HVM guests. The entries are generated by walking the page tables and mapping in new pages. If a higher-level page table mapping exists, we attempt to traverse all the way down to a leaf page and add the page there. Access bits are flipped as needed.

The page entries are generated for deprivileged .text, .data and a stack. The data is copied from sections allocated by the linker. The mappings are setup in an unused portion of the Xen virtual address space. The pages are mapped in as user mode accessible, with NX bits set for the data and stack regions and the code region is set to be executable and read-only.

The needed pages are allocated on the HAP page heap and are deallocated when those heap pages are deallocated (on domain destruction).

---
 xen/arch/x86/hvm/Makefile          |   1 +
 xen/arch/x86/hvm/deprivileged.c    | 441 +++++++++++++++++++++++++++++++++++++
 xen/arch/x86/mm/hap/hap.c          |  10 +-
 xen/arch/x86/xen.lds.S             |  19 ++
 xen/include/asm-x86/config.h       |  10 +-
 xen/include/xen/hvm/deprivileged.h |  94 ++++++++
 6 files changed, 573 insertions(+), 2 deletions(-)
 create mode 100644 xen/arch/x86/hvm/deprivileged.c
 create mode 100644 xen/include/xen/hvm/deprivileged.h
xen/arch/x86/hvm/Makefile +1 -0
index 794e793..bd83ba3 100644
@@ -16,6 +16,7 @@ obj-y += pmtimer.o
 obj-y += quirks.o
 obj-y += rtc.o
 obj-y += save.o
+obj-y += deprivileged.o
 obj-y += stdvga.o
 obj-y += vioapic.o
 obj-y += viridian.o
xen/arch/x86/hvm/deprivileged.c new file +441 -0

441 lines not on this page · raw message

xen/arch/x86/mm/hap/hap.c +9 -1
index 593cba7..abc5113 100644
@@ -40,7 +40,8 @@
 #include <asm/domain.h>
 #include <xen/numa.h>
 #include <asm/hvm/nestedhvm.h>
-
+#include <xen/hvm/deprivileged.h>
+#include <asm/hvm/vmx/vmx.h>
 #include "private.h"
 
 /* Override macros from asm/page.h to make them work with mfn_t */
@@ -401,6 +402,9 @@ static void hap_install_xen_entries_in_l4(struct vcpu *v, mfn_t l4mfn)
            &idle_pg_table[ROOT_PAGETABLE_FIRST_XEN_SLOT],
            ROOT_PAGETABLE_XEN_SLOTS * sizeof(l4_pgentry_t));
 
+    /* Initialise the HVM deprivileged mode feature */
+    hvm_deprivileged_init(d, l4e);
+
     /* Install the per-domain mappings for this domain */
     l4e[l4_table_offset(PERDOMAIN_VIRT_START)] =
         l4e_from_pfn(mfn_x(page_to_mfn(d->arch.perdomain_l3_pg)),
@@ -439,6 +443,10 @@ static void hap_destroy_monitor_table(struct vcpu* v, mfn_t mmfn)
 
     /* Put the memory back in the pool */
     hap_free(d, mmfn);
+
+    /* Destroy the HVM tables */
+    ASSERT(paging_locked_by_me(d));
+    hvm_deprivileged_destroy(d);
 }
 
 /************************************************/
xen/arch/x86/xen.lds.S +19 -0
index 6553cff..0bfe0cf 100644
@@ -50,6 +50,25 @@ SECTIONS
        _etext = .;             /* End of text section */
   } :text = 0x9090
 
+  /* HVM deprivileged mode segments
+   * Used to map the ring3 static data and .text
+   */
+
+  . = ALIGN(PAGE_SIZE);
+  .hvm_deprivileged_text : {
+      __hvm_deprivileged_text_start = . ;
+      *(.hvm_deprivileged_enhancement.text)
+      __hvm_deprivileged_text_end = . ;
+  } : text
+
+  . = ALIGN(PAGE_SIZE);
+  .hvm_deprivileged_data : {
+      __hvm_deprivileged_data_start = . ;
+      *(.hvm_deprivileged_enhancement.data)
+      __hvm_deprivileged_data_end = . ;
+  } : text
+
+  . = ALIGN(PAGE_SIZE);
   .rodata : {
        /* Bug frames table */
        . = ALIGN(4);
xen/include/asm-x86/config.h +9 -1
index 3e9be83..302399d 100644
@@ -186,7 +186,7 @@ extern unsigned char boot_edid_info[128];
  *  0xffff880000000000 - 0xffffff7fffffffff [119.5TB,           PML4:272-510]
  *    HVM/idle: continuation of 1:1 mapping
  *  0xffffff8000000000 - 0xffffffffffffffff [512GB, 2^39 bytes  PML4:511]
- *    HVM/idle: unused
+ *    HVM: HVM deprivileged mode 
  *
  * Compatibility guest area layout:
  *  0x0000000000000000 - 0x00000000f57fffff [3928MB,            PML4:0]
@@ -280,6 +280,14 @@ extern unsigned char boot_edid_info[128];
 #endif
 #define DIRECTMAP_VIRT_END      (DIRECTMAP_VIRT_START + DIRECTMAP_SIZE)
 
+/* Slot 511: HVM deprivileged mode
+ * The virtual addresses where the .text, .data and stack should be
+ * placed.
+ */
+#define HVM_DEPRIVILEGED_TEXT_ADDR  (PML4_ADDR(511))
+#define HVM_DEPRIVILEGED_DATA_ADDR  (PML4_ADDR(511) + 0xa000000)
+#define HVM_DEPRIVILEGED_STACK_ADDR (PML4_ADDR(511) + 0xc000000)
+
 #ifndef __ASSEMBLY__
 
 /* This is not a fixed value, just a lower limit. */
xen/include/xen/hvm/deprivileged.h new file +94 -0

94 lines not on this page · raw message

Signature · 1 line
2.1.4
#13 lore raw

RFC 3/4 HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer. This allows us to restore the stack when we have finished the deprivileged mode operation, meaning we can continue execution from that point. This is similar to if a context switch had happened.

To exit deprivileged mode, we copy the stack back, replacing the current stack. We can then continue execution from where we left off, which will unwind the stack and free up resources. This method means that we do not need to change any other code paths and its invocation will be transparent to callers. This should allow the feature to be more easily deployed to different parts of Xen.

Note that this copy of the stack is per-vcpu but, it will contain per-pcpu data. Extra work is needed to properly migrate vcpus between pcpus.

The switch to and from deprivileged mode is performed using sysret and syscall respectively.

The return paths in entry.S have been edited so that, when we receive an interrupt whilst in deprivileged mode, we return into that mode correctly.

A hook on the syscall handler in entry.S has also been added which handles returning from user mode and will support deprivileged mode system calls when these are needed.

---
 xen/arch/x86/domain.c               |  12 +++
 xen/arch/x86/hvm/Makefile           |   1 +
 xen/arch/x86/hvm/deprivileged.c     | 103 ++++++++++++++++++
 xen/arch/x86/hvm/deprivileged_asm.S | 205 ++++++++++++++++++++++++++++++++++++
 xen/arch/x86/hvm/vmx/vmx.c          |   7 ++
 xen/arch/x86/x86_64/asm-offsets.c   |   5 +
 xen/arch/x86/x86_64/entry.S         |  35 ++++++
 xen/include/asm-x86/hvm/vmx/vmx.h   |   2 +
 xen/include/xen/hvm/deprivileged.h  |  38 +++++++
 xen/include/xen/sched.h             |  18 +++-
 10 files changed, 425 insertions(+), 1 deletion(-)
 create mode 100644 xen/arch/x86/hvm/deprivileged_asm.S
xen/arch/x86/domain.c +12 -0
index 045f6ff..a0e5e70 100644
@@ -62,6 +62,7 @@
 #include <xen/iommu.h>
 #include <compat/vcpu.h>
 #include <asm/psr.h>
+#include <xen/hvm/deprivileged.h>
 
 DEFINE_PER_CPU(struct vcpu *, curr_vcpu);
 DEFINE_PER_CPU(unsigned long, cr4);
@@ -446,6 +447,12 @@ int vcpu_initialise(struct vcpu *v)
     if ( has_hvm_container_domain(d) )
     {
         rc = hvm_vcpu_initialise(v);
+
+        /* Initialise HVM deprivileged mode */
+        printk("HVM initialising deprivileged mode ...");
+        hvm_deprivileged_prepare_vcpu(v);
+        printk("Done.\n");
+
         goto done;
     }
 
@@ -523,7 +530,12 @@ void vcpu_destroy(struct vcpu *v)
     vcpu_destroy_fpu(v);
 
     if ( has_hvm_container_vcpu(v) )
+    {
+        /* Destroy the deprivileged mode on this vcpu */
+        hvm_deprivileged_destroy_vcpu(v);
+
         hvm_vcpu_destroy(v);
+    }
     else
         xfree(v->arch.pv_vcpu.trap_ctxt);
 }
xen/arch/x86/hvm/Makefile +1 -0
index bd83ba3..6819886 100644
@@ -17,6 +17,7 @@ obj-y += quirks.o
 obj-y += rtc.o
 obj-y += save.o
 obj-y += deprivileged.o
+obj-y += deprivileged_asm.o
 obj-y += stdvga.o
 obj-y += vioapic.o
 obj-y += viridian.o
xen/arch/x86/hvm/deprivileged.c +103 -0

106 lines not on this page · raw message

xen/arch/x86/hvm/deprivileged_asm.S new file +205 -0

205 lines not on this page · raw message

xen/arch/x86/hvm/vmx/vmx.c +7 -0
index c32d863..595b0f2 100644
@@ -59,6 +59,8 @@
 #include <asm/event.h>
 #include <asm/monitor.h>
 #include <public/arch-x86/cpuid.h>
+#include <xen/hvm/deprivileged.h>
+
 
 static bool_t __initdata opt_force_ept;
 boolean_param("force-ept", opt_force_ept);
@@ -194,6 +196,10 @@ void vmx_save_host_msrs(void)
         set_bit(VMX_INDEX_MSR_ ## address, &host_msr_state->flags);     \
     } while ( 0 )
 
+struct vmx_msr_state *get_host_msr_state(void) {
+    return &this_cpu(host_msr_state);
+}
+
 static enum handler_return
 long_mode_do_msr_read(unsigned int msr, uint64_t *msr_content)
 {
@@ -272,6 +278,7 @@ long_mode_do_msr_write(unsigned int msr, uint64_t msr_content)
     case MSR_LSTAR:
         if ( !is_canonical_address(msr_content) )
             goto uncanonical_address;
+
         WRITE_MSR(LSTAR);
         break;
 
xen/arch/x86/x86_64/asm-offsets.c +5 -0
index 447c650..fd5de44 100644
@@ -115,6 +115,11 @@ void __dummy__(void)
     OFFSET(VCPU_nsvm_hap_enabled, struct vcpu, arch.hvm_vcpu.nvcpu.u.nsvm.ns_hap_enabled);
     BLANK();
 
+    OFFSET(VCPU_stack, struct vcpu, stack);
+    OFFSET(VCPU_rsp, struct vcpu, rsp);
+    OFFSET(VCPU_user_mode, struct vcpu, user_mode);
+    BLANK();
+
     OFFSET(DOMAIN_is_32bit_pv, struct domain, arch.is_32bit_pv);
     BLANK();
 
xen/arch/x86/x86_64/entry.S +35 -0
index 74677a2..fa9155c 100644
@@ -102,6 +102,15 @@ restore_all_xen:
         RESTORE_ALL adj=8
         iretq
 
+/* Returning from user mode */
+handle_hvm_user_mode:
+
+        call hvm_deprivileged_handle_user_mode
+
+        /* Go back into user mode */
+        cli
+        jmp  restore_all_guest
+
 /*
  * When entering SYSCALL from kernel mode:
  *  %rax                            = hypercall vector
@@ -131,6 +140,14 @@ ENTRY(lstar_enter)
         testb $TF_kernel_mode,VCPU_thread_flags(%rbx)
         jz    switch_to_kernel
 
+        /* Were we in Xen's ring 3?  */
+        push %rbx
+        GET_CURRENT(%rbx)
+        movq VCPU_user_mode(%rbx), %rbx
+        cmp  $1, %rbx
+        je   handle_hvm_user_mode
+        pop  %rbx
+
 /*hypercall:*/
         movq  %r10,%rcx
         cmpq  $NR_hypercalls,%rax
@@ -487,6 +504,13 @@ ENTRY(common_interrupt)
 /* No special register assumptions. */
 ENTRY(ret_from_intr)
         GET_CURRENT(%rbx)
+
+        /* If we are in Xen's user mode, return into it */
+        cmpq $1,VCPU_user_mode(%rbx)
+        cli
+        je    restore_all_guest
+        sti
+
         testb $3,UREGS_cs(%rsp)
         jz    restore_all_xen
         movq  VCPU_domain(%rbx),%rax
@@ -509,6 +533,14 @@ handle_exception_saved:
         GET_CURRENT(%rbx)
         PERFC_INCR(exceptions, %rax, %rbx)
         callq *(%rdx,%rax,8)
+
+        /* If we are in Xen's user mode, return into it */
+        /* TODO: Test this path */
+        cmpq  $1,VCPU_user_mode(%rbx)
+        cli
+        je    restore_all_guest
+        sti
+
         testb $3,UREGS_cs(%rsp)
         jz    restore_all_xen
         leaq  VCPU_trap_bounce(%rbx),%rdx
@@ -664,6 +696,9 @@ handle_ist_exception:
         movl  $EVENT_CHECK_VECTOR,%edi
         call  send_IPI_self
 1:      movq  VCPU_domain(%rbx),%rax
+        /* This also handles Xen ring3 return for us.
+         * So, there is no need to explicitly do a user mode check.
+         */
         cmpb  $0,DOMAIN_is_32bit_pv(%rax)
         je    restore_all_guest
         jmp   compat_restore_all_guest
xen/include/asm-x86/hvm/vmx/vmx.h +2 -0
index 3fbfa44..98e269e 100644
@@ -565,4 +565,6 @@ typedef struct {
     u16 eptp_index;
 } ve_info_t;
 
+struct vmx_msr_state *get_host_msr_state(void);
+
 #endif /* __ASM_X86_HVM_VMX_VMX_H__ */
xen/include/xen/hvm/deprivileged.h +38 -0
index 6cc803e..e42f39a 100644
@@ -68,6 +68,37 @@ int hvm_deprivileged_copy_l1(struct domain *d,
                              unsigned int l1_flags);
 
 
+/* Used to prepare each vcpu's data for user mode. Call for each HVM vcpu. */
+int hvm_deprivileged_prepare_vcpu(struct vcpu *vcpu);
+
+/* Destroy each vcpu's data for Xen user mode. Again, call for each vcpu. */
+void hvm_deprivileged_destroy_vcpu(struct vcpu *vcpu);
+
+/* Called to perform a user mode operation. */
+void hvm_deprivileged_user_mode(void);
+
+/* Called when the user mode operation has completed */
+void hvm_deprivileged_finish_user_mode(void);
+
+/* Called to move into and then out of user mode. Needed for accessing
+ * assembly features.
+ */
+void hvm_deprivileged_user_mode_asm(void);
+
+/* Called on the return path to return to the correct execution point */
+void hvm_deprivileged_finish_user_mode_asm(void);
+
+/* Handle any syscalls that the user mode makes */
+void hvm_deprivileged_handle_user_mode(void);
+
+/* The ring 3 code */
+void hvm_deprivileged_ring3(void);
+
+/* Call when inside a trap that should cause a domain crash if in user mode
+ * e.g. an invalid_op is trapped whilst in user mode.
+ */
+void hvm_deprivileged_check_trap(const char* func_name);
+
 /* The segments where the user mode .text and .data are stored */
 extern unsigned long int __hvm_deprivileged_text_start;
 extern unsigned long int __hvm_deprivileged_text_end;
@@ -91,4 +122,11 @@ extern unsigned long int __hvm_deprivileged_data_end;
 
 #define HVM_ERR_PG_ALLOC -1
 
+/* The user mode stack pointer.
++ * The stack grows down so set this to top of the stack region. Then,
++ * as this is 0-indexed, move into the stack, not just after it.
++ * Subtract 16 bytes for correct stack alignment.
++ */
+#define HVM_STACK_PTR (HVM_DEPRIVILEGED_STACK_ADDR + STACK_SIZE - 16)
+
 #endif
xen/include/xen/sched.h +17 -1
index 73d3bc8..180643e 100644
@@ -137,7 +137,7 @@ void evtchn_destroy_final(struct domain *d); /* from complete_domain_destroy */
 
 struct waitqueue_vcpu;
 
-struct vcpu 
+struct vcpu
 {
     int              vcpu_id;
 
@@ -158,6 +158,22 @@ struct vcpu
 
     void            *sched_priv;    /* scheduler-specific data */
 
+    /* HVM deprivileged mode state */
+    void *stack;             /* Location of stack to save data onto */
+    unsigned long rsp;       /* rsp of our stack to restore our data to */
+    unsigned long user_mode; /* Are we (possibly moving into) in user mode? */
+
+    /* The mstar of the processor that we are currently executing on.
+     *  we need to save this because Xen does lazy saving of these.
+     */
+    unsigned long int msr_lstar; /* lstar */
+    unsigned long int msr_star;
+
+    /* Debug info */
+    unsigned long int old_rsp;
+    unsigned long int old_processor;
+    unsigned long int old_msr_lstar;
+    unsigned long int old_msr_star;
     struct vcpu_runstate_info runstate;
 #ifndef CONFIG_COMPAT
 # define runstate_guest(v) ((v)->runstate_guest)
Signature · 1 line
2.1.4
#41 lore raw

RFC 4/4 HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Ben Catterall

Added trap handlers to catch exceptions such as a page fault, general protection fault, etc. These handlers will crash the domain as such exceptions would indicate that either there is a bug in deprivileged mode or it has been compromised by an attacker.

---
 xen/arch/x86/mm/hap/hap.c |  9 +++++++++
 xen/arch/x86/traps.c      | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 49 insertions(+), 1 deletion(-)
xen/arch/x86/mm/hap/hap.c +9 -0
index abc5113..43bde89 100644
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v, unsigned long va,
 {
     struct domain *d = v->domain;
 
+    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);
+        domain_crash_synchronous();
+    }
+
     HAP_ERROR("Intercepted a guest #PF (%u:%u) with HAP enabled.\n",
               d->domain_id, v->vcpu_id);
+
     domain_crash(d);
     return 0;
 }
xen/arch/x86/traps.c +40 -1

89 lines not on this page · raw message

Signature · 1 line
2.1.4
#2 lore raw

Re: [RFC 1/4] HVM x86 deprivileged mode: Page allocation helper

In reply to Ben Catterall
Quoted 5 lines · Ben Catterall

This allocation function is used by the deprivileged mode initialisation code to allocate pages for the new page table mappings and page frames on the HAP page heap.

This is fine for your test box, but isn't fine for systems out there without hardware EPT/NPT support. For older systems like that (or in certain specific workloads), shadow paging is used instead.

This feature is applicable to any HVM domain, which means that it shouldn't depend on HAP or shadow paging.

How much memory is allocated for the depriv area, and what exactly is allocated in total?

I expect it isn't very much, and would suggest using d->arch.paging.alloc_page() instead (which is the generic "get me some memory accounted against the domain" helper) which looks as if it should suffice.

Depending on exactly how much memory is needed, you might need to bump the default minimum shadow pool size.

~Andrew

#10 lore raw

Re: [RFC 2/4] HVM x86 deprivileged mode: Create deprivileged page tables

In reply to Ben Catterall
Quoted 32 lines · Ben Catterall

The paging structure mappings for the deprivileged mode are added to the monitor page table for HVM guests. The entries are generated by walking the page tables and mapping in new pages. If a higher-level page table mapping exists, we attempt to traverse all the way down to a leaf page and add the page there. Access bits are flipped as needed.

The page entries are generated for deprivileged .text, .data and a stack. The data is copied from sections allocated by the linker. The mappings are setup in an unused portion of the Xen virtual address space. The pages are mapped in as user mode accessible, with NX bits set for the data and stack regions and the code region is set to be executable and read-only.

The needed pages are allocated on the HAP page heap and are deallocated when those heap pages are deallocated (on domain destruction).

---
 xen/arch/x86/hvm/Makefile          |   1 +
 xen/arch/x86/hvm/deprivileged.c    | 441 +++++++++++++++++++++++++++++++++++++
 xen/arch/x86/mm/hap/hap.c          |  10 +-
 xen/arch/x86/xen.lds.S             |  19 ++
 xen/include/asm-x86/config.h       |  10 +-
 xen/include/xen/hvm/deprivileged.h |  94 ++++++++
 6 files changed, 573 insertions(+), 2 deletions(-)
 create mode 100644 xen/arch/x86/hvm/deprivileged.c
 create mode 100644 xen/include/xen/hvm/deprivileged.h
xen/arch/x86/hvm/Makefile +0 -0
index 794e793..bd83ba3 100644

xen/arch/x86/hvm/Makefile obj-y += pmtimer.o · line 19

Quoted 4 lines
xen/arch/x86/hvm/Makefile +1 -0
@@ -16,6 +16,7 @@ obj-y += pmtimer.o
 obj-y += quirks.o
 obj-y += rtc.o
 obj-y += save.o
+obj-y += deprivileged.o

We attempt to keep objects linked in alphabetical order, where possible.

Quoted 26 lines
xen/arch/x86/hvm/Makefile +0 -0
 obj-y += stdvga.o
 obj-y += vioapic.o
 obj-y += viridian.o
xen/arch/x86/hvm/deprivileged.c new file +17 -0
new file mode 100644
index 0000000..071d900
@@ -0,0 +1,441 @@
+/*
+ * HVM deprivileged mode to provide support for running operations in
+ * user mode from Xen
+ */
+#include <xen/lib.h>
+#include <xen/mm.h>
+#include <xen/domain_page.h>
+#include <xen/config.h>
+#include <xen/types.h>
+#include <xen/sched.h>
+#include <asm/paging.h>
+#include <xen/compiler.h>
+#include <asm/hap.h>
+#include <asm/paging.h>
+#include <asm-x86/page.h>
+#include <public/domctl.h>
+#include <xen/domain_page.h>

xen/arch/x86/hvm/deprivileged.c line 27

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c new file +10 -0
+#include <asm/hvm/vmx/vmx.h>
+#include <xen/hvm/deprivileged.h>
+
+void hvm_deprivileged_init(struct domain *d, l4_pgentry_t *l4e)
+{
+    int ret;
+    void *p;
+    unsigned long int size;
+
+    /* Copy the .text segment for deprivileged code */

Why do you need to copy the deprivileged text section at all? It is read only and completely common. All you should need to do is make userspace mappings to it where it resides in the Xen linked area.

i.e. this is an operation which should be performed once at startup, not once per domain. You will also reduce your memory overhead by doing this.

xen/arch/x86/hvm/deprivileged.c line 28

Quoted 1 line
xen/arch/x86/hvm/deprivileged.c new file +1 -0
+    size = (unsigned long int)&__hvm_deprivileged_text_end -

Don't bother qualifying unsigned long with a further "int". A plain "unsigned long" is the expected declaration.

Quoted 12 lines
xen/arch/x86/hvm/deprivileged.c new file +12 -0
+           (unsigned long int)&__hvm_deprivileged_text_start;
+
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long int)&__hvm_deprivileged_text_start,
+                              (unsigned long int)HVM_DEPRIVILEGED_TEXT_ADDR,
+                              size, 0 /* No write */);
+
+    if( ret )
+    {
+        printk("HVM: Error when initialising depriv .text. Code: %d", ret);
+        domain_crash(d);
+        return;

xen/arch/x86/hvm/deprivileged.c line 50

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c new file +10 -0
+    }
+
+    /* Copy the .data segment for ring3 code */
+    size = (unsigned long int)&__hvm_deprivileged_data_end -
+           (unsigned long int)&__hvm_deprivileged_data_start;
+
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long int)&__hvm_deprivileged_data_start,
+                              (unsigned long int)HVM_DEPRIVILEGED_DATA_ADDR,
+                              size, _PAGE_NX | _PAGE_RW);

What do you expect to end up in a data section like this?

xen/arch/x86/hvm/deprivileged.c line 59

Quoted 9 lines
xen/arch/x86/hvm/deprivileged.c new file +9 -0
+
+    if( ret )
+    {
+        printk("HVM: Error when initialising depriv .data. Code: %d", ret);
+        domain_crash(d);
+        return;
+    }
+
+    /* Setup the stack mappings.

Xen recommended style for multiline comments is

/*
* Setup ...

Quoted 4 lines
xen/arch/x86/hvm/deprivileged.c new file +4 -0
+     * This is a bit of a hack: by allocating a blank area
+     * we can reuse the hvm_deprivileged_copy_pages code.
+     * The stacks are actually allocated in the per-vcpu initialisation
+     * routine.

xen/arch/x86/hvm/deprivileged.c line 73

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c new file +10 -0
+     */
+    size = STACK_SIZE;
+
+    p = alloc_xenheap_pages(STACK_ORDER, 0);
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long int)p,
+                              (unsigned long int)HVM_DEPRIVILEGED_STACK_ADDR,
+                              size, _PAGE_NX | _PAGE_RW);
+
+    free_xenheap_pages(p, STACK_ORDER);

The userspace stacks really don't need to be this large. Xens primary stack, which runs all of this code normally, is limited at 2 pages, which is 1/4 of STACK_SIZE.

Quoted 9 lines
xen/arch/x86/hvm/deprivileged.c new file +9 -0
+
+    if( ret )
+    {
+        printk("HVM: Error when initialising depriv stack. Code: %d", ret);
+        domain_crash(d);
+        return;
+    }
+}
+

xen/arch/x86/hvm/deprivileged.c line 92

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c new file +10 -0
+void hvm_deprivileged_destroy(struct domain *d)
+{
+    struct page_info *pg = NULL;
+
+    /* Free up all the pages we allocated from the HAP HVM list */
+    while( (pg = page_list_remove_head(&d->arch.paging.hap.hvmlist)) )
+    {
+        d->arch.paging.hap.free_pages++;
+        page_list_add_tail(pg, &d->arch.paging.hap.freelist);
+    }

See c/s 0174da5b7 for why loops like this are bad in general. However, if you use the shadow pool, this should be able to disappear.

Quoted 18 lines
xen/arch/x86/hvm/deprivileged.c new file +18 -0
+}
+
+/* Create a copy of the data at the specified virtual address.
+ * When writing to the source, it will walk the page table hierarchy, creating
+ * new levels as needed.
+ *
+ * If we find a leaf entry in a page table (one which holds the
+ * mfn of a 4KB, 2MB, etc. page frame) which has already been
+ * mapped in, then we bail as we have a collision and this likely
+ * means a bug or the memory configuration has been changed.
+ *
+ * Pages have PAGE_USER, PAGE_GLOBAL (if supported) and PAGE_PRESENT set by
+ * default. The extra l1_flags are used for extra control e.g. PAGE_RW.
+ * The PAGE_RW flag will be enabled for all page structure entries
+ * above the leaf page if that leaf page has PAGE_RW set. This is needed to
+ * permit the writes on the leaf pages. See the Intel manual 3A section 4.6.
+ *
+ * TODO: We proceed down to L1 4KB pages and then map these in. We should

xen/arch/x86/hvm/deprivileged.c line 120

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c new file +10 -0
+ * stop the recursion on L3/L2 for a 1GB or 2MB page which would mean faster
+ * page access. When we stop would depend on size (e.g. use 2MB pages for a
+ * few MBs)
+ */
+int hvm_deprivileged_copy_pages(struct domain *d,
+                            l4_pgentry_t *l4t_base,
+                            unsigned long int src_start,
+                            unsigned long int dst_start,
+                            unsigned long int size,
+                            unsigned int l1_flags)

<large snip>

Does map_pages_to_xen() not do everything you need here? It certainly should be fine for the .text section, and will keep the idle and monitor tables up to date for you.

Either way, it would be useful to start early on with a description of what the new memory layout is expected to be, and which bits are global, which are per pcpu and which are per vcpu.

xen/arch/x86/mm/hap/hap.c line 44

Quoted 12 lines
xen/arch/x86/mm/hap/hap.c +2 -1
index 593cba7..abc5113 100644
@@ -40,7 +40,8 @@
 #include <asm/domain.h>
 #include <xen/numa.h>
 #include <asm/hvm/nestedhvm.h>
-
+#include <xen/hvm/deprivileged.h>
+#include <asm/hvm/vmx/vmx.h>

This looks like a spurious addition.

Quoted 153 lines
xen/arch/x86/mm/hap/hap.c +7 -0
 #include "private.h"
 
 /* Override macros from asm/page.h to make them work with mfn_t */
@@ -401,6 +402,9 @@ static void hap_install_xen_entries_in_l4(struct vcpu *v, mfn_t l4mfn)
            &idle_pg_table[ROOT_PAGETABLE_FIRST_XEN_SLOT],
            ROOT_PAGETABLE_XEN_SLOTS * sizeof(l4_pgentry_t));
 
+    /* Initialise the HVM deprivileged mode feature */
+    hvm_deprivileged_init(d, l4e);
+
     /* Install the per-domain mappings for this domain */
     l4e[l4_table_offset(PERDOMAIN_VIRT_START)] =
         l4e_from_pfn(mfn_x(page_to_mfn(d->arch.perdomain_l3_pg)),
@@ -439,6 +443,10 @@ static void hap_destroy_monitor_table(struct vcpu* v, mfn_t mmfn)
 
     /* Put the memory back in the pool */
     hap_free(d, mmfn);
+
+    /* Destroy the HVM tables */
+    ASSERT(paging_locked_by_me(d));
+    hvm_deprivileged_destroy(d);
 }
 
 /************************************************/
xen/arch/x86/xen.lds.S +19 -0
index 6553cff..0bfe0cf 100644
@@ -50,6 +50,25 @@ SECTIONS
        _etext = .;             /* End of text section */
   } :text = 0x9090
 
+  /* HVM deprivileged mode segments
+   * Used to map the ring3 static data and .text
+   */
+
+  . = ALIGN(PAGE_SIZE);
+  .hvm_deprivileged_text : {
+      __hvm_deprivileged_text_start = . ;
+      *(.hvm_deprivileged_enhancement.text)
+      __hvm_deprivileged_text_end = . ;
+  } : text
+
+  . = ALIGN(PAGE_SIZE);
+  .hvm_deprivileged_data : {
+      __hvm_deprivileged_data_start = . ;
+      *(.hvm_deprivileged_enhancement.data)
+      __hvm_deprivileged_data_end = . ;
+  } : text
+
+  . = ALIGN(PAGE_SIZE);
   .rodata : {
        /* Bug frames table */
        . = ALIGN(4);
xen/include/asm-x86/config.h +9 -1
index 3e9be83..302399d 100644
@@ -186,7 +186,7 @@ extern unsigned char boot_edid_info[128];
  *  0xffff880000000000 - 0xffffff7fffffffff [119.5TB,           PML4:272-510]
  *    HVM/idle: continuation of 1:1 mapping
  *  0xffffff8000000000 - 0xffffffffffffffff [512GB, 2^39 bytes  PML4:511]
- *    HVM/idle: unused
+ *    HVM: HVM deprivileged mode 
  *
  * Compatibility guest area layout:
  *  0x0000000000000000 - 0x00000000f57fffff [3928MB,            PML4:0]
@@ -280,6 +280,14 @@ extern unsigned char boot_edid_info[128];
 #endif
 #define DIRECTMAP_VIRT_END      (DIRECTMAP_VIRT_START + DIRECTMAP_SIZE)
 
+/* Slot 511: HVM deprivileged mode
+ * The virtual addresses where the .text, .data and stack should be
+ * placed.
+ */
+#define HVM_DEPRIVILEGED_TEXT_ADDR  (PML4_ADDR(511))
+#define HVM_DEPRIVILEGED_DATA_ADDR  (PML4_ADDR(511) + 0xa000000)
+#define HVM_DEPRIVILEGED_STACK_ADDR (PML4_ADDR(511) + 0xc000000)
+
 #ifndef __ASSEMBLY__
 
 /* This is not a fixed value, just a lower limit. */
xen/include/xen/hvm/deprivileged.h new file +65 -0
new file mode 100644
index 0000000..6cc803e
@@ -0,0 +1,94 @@
+#ifndef __X86_HVM_DEPRIVILEGED
+#define __X86_HVM_DEPRIVILEGED
+
+/* This is also included in the HVM deprivileged mode .S file */
+#ifndef __ASSEMBLY__
+
+#include <asm/page.h>
+#include <xen/lib.h>
+#include <xen/mm.h>
+#include <xen/domain_page.h>
+#include <xen/config.h>
+#include <xen/types.h>
+#include <xen/sched.h>
+#include <asm/paging.h>
+#include <asm/hap.h>
+#include <asm/paging.h>
+#include <asm-x86/page.h>
+#include <public/domctl.h>
+#include <xen/domain_page.h>
+
+/* Initialise the HVM deprivileged mode. This just sets up the general
+ * page mappings for .text and .data. It does not prepare each HVM vcpu's data
+ * or stack which needs to be done separately using
+ * hvm_deprivileged_prepare_vcpu.
+ */
+void hvm_deprivileged_init(struct domain *d, l4_pgentry_t *l4e);
+
+/* Free up the data used by the HVM deprivileged enhancements.
+ * This frees general page mappings. It does not destroy the per-vcpu
+ * data so hvm_deprivileged_destroy_vcpu also needs to be called for each vcpu.
+ * This method should be called after those per-vcpu destruction routines.
+ */
+void hvm_deprivileged_destroy(struct domain *d);
+
+/* Use create a copy of the data at the specified virtual address.
+ * When writing to the source, it will walk the page table hierarchy, creating
+ * new levels as needed, and then copy the data across.
+ */
+int hvm_deprivileged_copy_pages(struct domain *d,
+                                l4_pgentry_t *l4e_base,
+                                unsigned long int src_start,
+                                unsigned long int dst_start,
+                                unsigned long int size,
+                                unsigned int l1_flags);
+
+int hvm_deprivileged_copy_l3(struct domain *d,
+                             l3_pgentry_t *l1t_base,
+                             unsigned long int src_start,
+                             unsigned long int dst_start,
+                             unsigned long int size,
+                             unsigned int l1_flags);
+
+int hvm_deprivileged_copy_l2(struct domain *d,
+                             l2_pgentry_t *l1t_base,
+                             unsigned long int src_start,
+                             unsigned long int dst_start,
+                             unsigned long int size,
+                             unsigned int l1_flags);
+
+/* The left case of the copy. Will allocate the pages and actually copy the
+ * data.
+ */
+int hvm_deprivileged_copy_l1(struct domain *d,
+                             l1_pgentry_t *l1t_base,
+                             unsigned long int src_start,

xen/include/xen/hvm/deprivileged.h line 75

Quoted 10 lines
xen/include/xen/hvm/deprivileged.h new file +10 -0
+                             unsigned long int dst_start,
+                             unsigned long int size,
+                             unsigned int l1_flags);
+
+
+/* The segments where the user mode .text and .data are stored */
+extern unsigned long int __hvm_deprivileged_text_start;
+extern unsigned long int __hvm_deprivileged_text_end;
+extern unsigned long int __hvm_deprivileged_data_start;
+extern unsigned long int __hvm_deprivileged_data_end;

extern unsigned long __hvm_$foo[];

Will be a more useful type to work with, and harder to accidentally misuse.

Quoted 5 lines
xen/include/xen/hvm/deprivileged.h new file +5 -0
+
+#endif
+
+/* The sizes of the pages */
+#define HVM_1GB_PAGESIZE 0x40000000ul

xen/include/xen/hvm/deprivileged.h line 90

Quoted 10 lines
xen/include/xen/hvm/deprivileged.h new file +10 -0
+#define HVM_2MB_PAGESIZE 0x00200000ul
+#define HVM_4KB_PAGESIZE 0x00001000ul
+
+/* The size in bytes that a single L(1,2,3,4} entry covers.
+ * There are 512 (left shift by 9) entries in each page-structure.
+ */
+#define HVM_L4_PAGE_RANGE (HVM_1GB_PAGESIZE << 9)
+#define HVM_L3_PAGE_RANGE (HVM_2MB_PAGESIZE << 9)
+#define HVM_L2_PAGE_RANGE (HVM_4KB_PAGESIZE << 9)
+#define HVM_L1_PAGE_RANGE (HVM_4KB_PAGESIZE     )

Values like this should be straight from page.h rather than redefining here. if page.h is missing some, that is the correct place to add them.

~Andrew

Quoted 4 lines
xen/include/xen/hvm/deprivileged.h new file +4 -0
+
+#define HVM_ERR_PG_ALLOC -1
+
+#endif
#14 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Ben Catterall
Quoted 15 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer. This allows us to restore the stack when we have finished the deprivileged mode operation, meaning we can continue execution from that point. This is similar to if a context switch had happened.

To exit deprivileged mode, we copy the stack back, replacing the current stack. We can then continue execution from where we left off, which will unwind the stack and free up resources. This method means that we do not need to change any other code paths and its invocation will be transparent to callers. This should allow the feature to be more easily deployed to different parts of Xen.

Quoted 2 lines

Note that this copy of the stack is per-vcpu but, it will contain per-pcpu data. Extra work is needed to properly migrate vcpus between pcpus.

Under what circumstances do you see there being persistent state in the depriv area between calls, given that the calls are synchronous from VM actions?

Quoted 3 lines

The switch to and from deprivileged mode is performed using sysret and syscall respectively.

I suspect we need to borrow the SS attribute workaround from Linux to make this function reliably on AMD systems.

https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=61f01dd941ba9e06d2bf05994450ecc3d61b6b8b

Quoted 36 lines

The return paths in entry.S have been edited so that, when we receive an interrupt whilst in deprivileged mode, we return into that mode correctly.

A hook on the syscall handler in entry.S has also been added which handles returning from user mode and will support deprivileged mode system calls when these are needed.

---
 xen/arch/x86/domain.c               |  12 +++
 xen/arch/x86/hvm/Makefile           |   1 +
 xen/arch/x86/hvm/deprivileged.c     | 103 ++++++++++++++++++
 xen/arch/x86/hvm/deprivileged_asm.S | 205 ++++++++++++++++++++++++++++++++++++
 xen/arch/x86/hvm/vmx/vmx.c          |   7 ++
 xen/arch/x86/x86_64/asm-offsets.c   |   5 +
 xen/arch/x86/x86_64/entry.S         |  35 ++++++
 xen/include/asm-x86/hvm/vmx/vmx.h   |   2 +
 xen/include/xen/hvm/deprivileged.h  |  38 +++++++
 xen/include/xen/sched.h             |  18 +++-
 10 files changed, 425 insertions(+), 1 deletion(-)
 create mode 100644 xen/arch/x86/hvm/deprivileged_asm.S
xen/arch/x86/domain.c +1 -0
index 045f6ff..a0e5e70 100644
@@ -62,6 +62,7 @@
 #include <xen/iommu.h>
 #include <compat/vcpu.h>
 #include <asm/psr.h>
+#include <xen/hvm/deprivileged.h>
 
 DEFINE_PER_CPU(struct vcpu *, curr_vcpu);
 DEFINE_PER_CPU(unsigned long, cr4);

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

Quoted 6 lines
xen/arch/x86/domain.c +3 -0
@@ -446,6 +447,12 @@ int vcpu_initialise(struct vcpu *v)
     if ( has_hvm_container_domain(d) )
     {
         rc = hvm_vcpu_initialise(v);
+
+        /* Initialise HVM deprivileged mode */
+        printk("HVM initialising deprivileged mode ...");

All printk()s should have a XENLOG_$severity prefix.

Quoted 46 lines
xen/arch/x86/domain.c +8 -0
+        hvm_deprivileged_prepare_vcpu(v);
+        printk("Done.\n");
+
         goto done;
     }
 
@@ -523,7 +530,12 @@ void vcpu_destroy(struct vcpu *v)
     vcpu_destroy_fpu(v);
 
     if ( has_hvm_container_vcpu(v) )
+    {
+        /* Destroy the deprivileged mode on this vcpu */
+        hvm_deprivileged_destroy_vcpu(v);
+
         hvm_vcpu_destroy(v);
+    }
     else
         xfree(v->arch.pv_vcpu.trap_ctxt);
 }
xen/arch/x86/hvm/Makefile +1 -0
index bd83ba3..6819886 100644
@@ -17,6 +17,7 @@ obj-y += quirks.o
 obj-y += rtc.o
 obj-y += save.o
 obj-y += deprivileged.o
+obj-y += deprivileged_asm.o
 obj-y += stdvga.o
 obj-y += vioapic.o
 obj-y += viridian.o
xen/arch/x86/hvm/deprivileged.c +7 -0
index 071d900..979fc69 100644
@@ -439,3 +439,106 @@ int hvm_deprivileged_copy_l1(struct domain *d,
     }
     return 0;
 }
+
+/* Used to prepare each vcpus data for user mode. Call for each HVM vcpu.
+ */
+int hvm_deprivileged_prepare_vcpu(struct vcpu *vcpu)
+{
+    struct page_info *pg;
+

xen/arch/x86/hvm/deprivileged.c int hvm_deprivileged_copy_l1(struct domain *d, · line 458

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c +10 -0
+    /* TODO: clarify if this MEMF is correct */
+    /* Allocate 2^STACK_ORDER contiguous pages */
+    pg = alloc_domheap_pages(NULL, STACK_ORDER, MEMF_no_owner);
+    if( pg == NULL )
+    {
+        panic("HVM: Out of memory on per-vcpu deprivileged mode init.\n");
+        return -ENOMEM;
+    }
+
+    vcpu->stack = page_to_virt(pg);

Xen has two heaps, the xenheap and the domheap.

You may only construct pointers like this into the xenheap. The domheap is not guaranteed to have safe virtual mappings to. (This code only works because your test box isn't bigger than 5TB. Also there is a bug with xenheap allocations at the same point, but I need to fix that bug).

All access to domheap pages must strictly be within a map_domain_page()/unmap() region, which construct save temporary mappings.

Quoted 28 lines
xen/arch/x86/hvm/deprivileged.c +28 -0
+    vcpu->rsp = 0;
+    vcpu->user_mode = 0;
+
+    return 0;
+}
+
+/* Called on destroying each vcpu */
+void hvm_deprivileged_destroy_vcpu(struct vcpu *vcpu)
+{
+    free_domheap_pages(virt_to_page(vcpu->stack), STACK_ORDER);
+}
+
+/* Called to perform a user mode operation.
+ * Execution context is saved and then we move into user mode.
+ * This method is then jumped into to restore execution context after
+ * exiting user mode.
+ */
+void hvm_deprivileged_user_mode(void)
+{
+    struct vcpu *vcpu = get_current();
+    unsigned long int efer = read_efer();
+    register unsigned long sp asm("rsp");
+
+    ASSERT( vcpu->user_mode == 0 );
+    ASSERT( vcpu->stack != 0 );
+    ASSERT( vcpu->rsp == 0 );
+
+    /* Flip the SCE bit to allow sysret/call */

xen/arch/x86/hvm/deprivileged.c int hvm_deprivileged_copy_l1(struct domain *d, · line 496

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c +10 -0
+    write_efer(efer | EFER_SCE);
+
+    /* Save the msr lstar and star. Xen does lazy loading of these
+     * so we need to put the host values in and then restore the
+     * guest ones once we're done.
+     */
+    rdmsrl(MSR_LSTAR, vcpu->msr_lstar);
+    rdmsrl(MSR_STAR, vcpu->msr_star);
+    wrmsrl(MSR_LSTAR,get_host_msr_state()->msrs[VMX_INDEX_MSR_LSTAR]);
+    wrmsrl(MSR_STAR, get_host_msr_state()->msrs[VMX_INDEX_MSR_STAR]);

A partial context switch like this should be implemented as two new hvm_ops such as hvm_op.depriv_ctxt_switch_{to,from}()

This allows you to keep the common code clean of vendor specific code.

xen/arch/x86/hvm/deprivileged.c int hvm_deprivileged_copy_l1(struct domain *d, · line 504

Quoted 8 lines
xen/arch/x86/hvm/deprivileged.c +8 -0
+
+    /* The assembly routine to handle moving into/out of deprivileged mode */
+    hvm_deprivileged_user_mode_asm();
+
+    /* If our copy failed */
+    if( unlikely(vcpu->rsp == 0) )
+    {
+        gdprintk(XENLOG_ERR, "HVM: Stack too large in %s\n", __FUNCTION__);

__func__ please. It conforms to C99 whereas __FUNCTION__ is a gnuism.

Quoted 119 lines
xen/arch/x86/hvm/deprivileged.c +40 -0
+        domain_crash_synchronous();
+    }
+
+    /* Debug info */
+    vcpu->old_msr_lstar = get_host_msr_state()->msrs[VMX_INDEX_MSR_LSTAR];
+    vcpu->old_msr_star = get_host_msr_state()->msrs[VMX_INDEX_MSR_STAR];
+    vcpu->old_rsp = sp;
+    vcpu->old_processor = smp_processor_id();
+
+    /* Restore the efer and saved msr registers */
+    write_efer(efer);
+    wrmsrl(MSR_LSTAR, vcpu->msr_lstar);
+    wrmsrl(MSR_STAR, vcpu->msr_star);
+    vcpu->user_mode = 0;
+    vcpu->rsp = 0;
+}
+
+/* Called when the user mode operation has completed
+ * Perform C-level processing on return pathx
+ */
+void hvm_deprivileged_finish_user_mode(void)
+{
+    /* If we are not returning from user mode: bail */
+    ASSERT(get_current()->user_mode == 1);
+
+    hvm_deprivileged_finish_user_mode_asm();
+}
+
+void hvm_deprivileged_check_trap(const char* func_name)
+{
+    if( current->user_mode == 1 )
+    {
+        printk("HVM Deprivileged Mode: Trap whilst in user mode, %s\n",
+               func_name);
+        domain_crash_synchronous();
+    }
+}
+
+
+
xen/arch/x86/hvm/deprivileged_asm.S new file +73 -0
new file mode 100644
index 0000000..00a9e9c
@@ -0,0 +1,205 @@
+/*
+ * HVM security enhancements assembly code
+ */
+#include <xen/config.h>
+#include <xen/errno.h>
+#include <xen/softirq.h>
+#include <asm/asm_defns.h>
+#include <asm/apicdef.h>
+#include <asm/page.h>
+#include <public/xen.h>
+#include <irq_vectors.h>
+#include <xen/hvm/deprivileged.h>
+
+/* Handles entry into the deprivileged mode and returning from this
+ * mode. This requires copying the current Xen privileged stack across
+ * to a per-vcpu buffer as we need to be able to handle interrupts and
+ * exceptions whilst in this mode. Xen is non-preemptable so our
+ * privileged mode stack would  be clobbered if we did not save it.
+ *
+ * If we are entering deprivileged mode, then we use a sysret to get there.
+ * If we are returning from deprivileged mode, then we need to unwind the stack
+ * so we copy it back over the current stack so that we can return from the
+ * call path where we came in from.
+ *
+ * We're doing sort-of a long jump/set jump with copying to a stack to
+ * preserve it and allow returning code to continue executing from
+ * within this method.
+ */
+ENTRY(hvm_deprivileged_user_mode_asm)
+        /* Save our registers */
+        push   %rax
+        push   %rbx
+        push   %rcx
+        push   %rdx
+        push   %rsi
+        push   %rdi
+        push   %rbp
+        push   %r8
+        push   %r9
+        push   %r10
+        push   %r11
+        push   %r12
+        push   %r13
+        push   %r14
+        push   %r15
+        pushfq
+
+        /* Perform a near call to push rip onto the stack */
+        call   1f
+
+        /* Magic: Add to the stored rip the size of the code between
+         * label 1 and label 2. This allows  us to restart execution at label 2.
+         */
+1:      addq   $2f-1b, (%rsp)
+
+        GET_CURRENT(%r8)
+        xor    %rsi, %rsi
+
+        /* The following is equivalent to
+         * (get_cpu_info() + sizeof(struct cpu_info))
+         * This gets us to the top of the stack.
+         */
+        GET_STACK_BASE(%rcx)
+        addq   $STACK_SIZE, %rcx
+
+        movq   VCPU_stack(%r8), %rdi
+
+        /* We need copy the current stack across to our buffer
+         * Calculate the number of bytes to copy:
+         * (top of stack - current stack pointer)
+         * NOTE: We must not push any more data onto our stack after this point
+         * as it won't be saved.
+         */

xen/arch/x86/hvm/deprivileged_asm.S line 83

Quoted 10 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +10 -0
+        sub    %rsp, %rcx
+
+        /* If the stack is too big, we don't do the copy: handled by caller. */
+        cmpq   $STACK_SIZE, %rcx
+        ja     3f
+
+        mov    %rsp, %rsi
+/* USER MODE ENTRY POINT */
+2:
+        /* More magic: If we came here from preparing to go into user mode,

There is a very fine line between magic and gross hack ;)

I havn't quite decided which this is yet, but it certainly is neat, if rather opaque.

Quoted 14 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +14 -0
+         * then we copy our current stack to the buffer (the lines above
+         * have setup rsi, rdi and rcx to do this).
+         *
+         * If we came here from user mode, then we movsb to copy from
+         * our buffer into our current stack so that we can continue
+         * execution from the current code point, and return back to the guest
+         * via the path we came in. rsi, rdi and rcx have been setup by the
+         * de-privileged return path for this.
+         */
+        rep    movsb
+        mov    %rsp, %rsi
+
+        GET_CURRENT(%r8)
+        movq   VCPU_user_mode(%r8), %rdx

xen/arch/x86/hvm/deprivileged_asm.S line 107

Quoted 10 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +10 -0
+        movq   VCPU_rsp(%r8), %rax
+
+        /* If !user_mode  */
+        cmpq   $0, %rdx
+        jne    3f
+        cli
+
+        movabs $HVM_DEPRIVILEGED_TEXT_ADDR, %rcx /* RIP in user mode */
+
+        movq   $0x10200, %r11          /* RFLAGS user mode enable interrupts */

Please use $(X86_FLAGS_IF | X86_FLAGS_MBS) to be more clear which flags are being set.

Also, by enabling interrupts, you need some hook to short-circuit the scheduling softirq. As it currently stands, a timer interrupt interrupting depriv mode is liable to swap all your state out from under you.

xen/arch/x86/hvm/deprivileged_asm.S line 111

Quoted 4 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +4 -0
+        movq   $1, VCPU_user_mode(%r8) /* Now in user mode */
+        movq   %rsi, VCPU_rsp(%r8)     /* The rsp to restore to */
+
+        /* Stack ptr is set by user mode to avoid race conditions.

What race condition are you referring to?

xen/arch/x86/hvm/deprivileged_asm.S line 112

Quoted 1 line
xen/arch/x86/hvm/deprivileged_asm.S new file +1 -0
+         * See Intel manual 2 on the sysret instruction.

As a general rule, read both the Intel and the AMD manual for bits like this. sysret is one of the areas where implementations differ.

Quoted 118 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +93 -0
+         */
+        movq   $HVM_STACK_PTR, %rbx
+        sysretq                         /* Enter deprivileged mode */
+
+3:      GET_CURRENT(%r8)
+        movq   %rsi, VCPU_rsp(%r8)
+        pop    %rax    /* Pop off rip: used in a jump so still on stack */
+
+        /* Restore registers */
+        popfq
+        pop    %r15
+        pop    %r14
+        pop    %r13
+        pop    %r12
+        pop    %r11
+        pop    %r10
+        pop    %r9
+        pop    %r8
+        pop    %rbp
+        pop    %rdi
+        pop    %rsi
+        pop    %rdx
+        pop    %rcx
+        pop    %rbx
+        pop    %rax
+        ret
+
+/* Finished in user mode so return */
+ENTRY(hvm_deprivileged_finish_user_mode_asm)
+        /* The source is the copied stack in our buffer.
+         * The destination is our current stack.
+         *
+         * We need to:
+         * - Move the stack pointer to where it was before we entered
+         *   deprivileged mode.
+         * - Setup rsi, rdi and rcx as needed to perform the copy
+         * - Jump to the address held at the top of the stack which
+         *   is the user mode return address
+         */
+        cli
+        GET_CURRENT(%rbx)
+        movq   VCPU_stack(%rbx), %rsi
+        movq   VCPU_rsp(%rbx), %rdi
+
+        /* The return address that the near call pushed onto the
+         * buffer is pointed to by stack, so use that for rip.
+         */
+        movq   %rdi, %rsp
+
+        /* The following is equivalent to
+         * (get_cpu_info() + sizeof(struct cpu_info) - vcpu->rsp)
+         * This works out how many bytes we need to copy:
+         * (top of stack - bottom of stack)
+         */
+        GET_STACK_BASE(%rcx)
+        addq   $STACK_SIZE, %rcx
+        subq   %rdi, %rcx
+
+        /* Go to user mode return code */
+        jmp    *(%rsi)
+
+/* Entry point from the assembly syscall handlers */
+ENTRY(hvm_deprivileged_handle_user_mode)
+
+        /* Handle a user mode hypercall here */
+
+
+        /* We are finished in user mode */
+        call hvm_deprivileged_finish_user_mode
+
+        ret
+
+.section .hvm_deprivileged_enhancement.text,"ax"
+/* HVM deprivileged code */
+ENTRY(hvm_deprivileged_ring3)
+        /* sysret has loaded eip from rcx and rflags from r11.
+         * CS and SS have been loaded from the MSR for ring 3.
+         * We now need to  switch to the user mode stack
+         */
+        /* Setup usermode stack */
+        movabs $HVM_STACK_PTR, %rsp
+
+        /* Perform user mode processing */
+
+        mov $0xf, %rcx
+1: dec  %rcx
+        cmp $0, %rcx
+        jne 1b
+
+        /* Return to ring 0 */
+        syscall
+
+.previous
xen/arch/x86/hvm/vmx/vmx.c +6 -0
index c32d863..595b0f2 100644
@@ -59,6 +59,8 @@
 #include <asm/event.h>
 #include <asm/monitor.h>
 #include <public/arch-x86/cpuid.h>
+#include <xen/hvm/deprivileged.h>
+
 
 static bool_t __initdata opt_force_ept;
 boolean_param("force-ept", opt_force_ept);
@@ -194,6 +196,10 @@ void vmx_save_host_msrs(void)
         set_bit(VMX_INDEX_MSR_ ## address, &host_msr_state->flags);     \
     } while ( 0 )
 
+struct vmx_msr_state *get_host_msr_state(void) {
+    return &this_cpu(host_msr_state);
+}
+
 static enum handler_return
 long_mode_do_msr_read(unsigned int msr, uint64_t *msr_content)
 {

xen/arch/x86/hvm/vmx/vmx.c long_mode_do_msr_write(unsigned int msr, uint64_t msr_content) · line 281

Quoted 4 lines
xen/arch/x86/hvm/vmx/vmx.c +1 -0
@@ -272,6 +278,7 @@ long_mode_do_msr_write(unsigned int msr, uint64_t msr_content)
     case MSR_LSTAR:
         if ( !is_canonical_address(msr_content) )
             goto uncanonical_address;
+

Please avoid spurious changes like this.

Quoted 40 lines
xen/arch/x86/hvm/vmx/vmx.c +0 -0
         WRITE_MSR(LSTAR);
         break;
 
xen/arch/x86/x86_64/asm-offsets.c +5 -0
index 447c650..fd5de44 100644
@@ -115,6 +115,11 @@ void __dummy__(void)
     OFFSET(VCPU_nsvm_hap_enabled, struct vcpu, arch.hvm_vcpu.nvcpu.u.nsvm.ns_hap_enabled);
     BLANK();
 
+    OFFSET(VCPU_stack, struct vcpu, stack);
+    OFFSET(VCPU_rsp, struct vcpu, rsp);
+    OFFSET(VCPU_user_mode, struct vcpu, user_mode);
+    BLANK();
+
     OFFSET(DOMAIN_is_32bit_pv, struct domain, arch.is_32bit_pv);
     BLANK();
 
xen/arch/x86/x86_64/entry.S +9 -0
index 74677a2..fa9155c 100644
@@ -102,6 +102,15 @@ restore_all_xen:
         RESTORE_ALL adj=8
         iretq
 
+/* Returning from user mode */
+handle_hvm_user_mode:
+
+        call hvm_deprivileged_handle_user_mode
+
+        /* Go back into user mode */
+        cli
+        jmp  restore_all_guest
+
 /*
  * When entering SYSCALL from kernel mode:
  *  %rax                            = hypercall vector

xen/arch/x86/x86_64/entry.S ENTRY(lstar_enter) · line 149

Quoted 10 lines
xen/arch/x86/x86_64/entry.S +7 -0
@@ -131,6 +140,14 @@ ENTRY(lstar_enter)
         testb $TF_kernel_mode,VCPU_thread_flags(%rbx)
         jz    switch_to_kernel
 
+        /* Were we in Xen's ring 3?  */
+        push %rbx
+        GET_CURRENT(%rbx)
+        movq VCPU_user_mode(%rbx), %rbx
+        cmp  $1, %rbx
+        je   handle_hvm_user_mode
+        pop  %rbx

No need for the movq or rbx clobber. This entire block can be:

cmpb $1, VCPU_user_mode(%rbx)
je handle_hvm_user_mode

Similar to the $TF_kernel_mode check in context above.

Quoted 5 lines
xen/arch/x86/x86_64/entry.S +1 -0
+
 /*hypercall:*/
         movq  %r10,%rcx
         cmpq  $NR_hypercalls,%rax

xen/arch/x86/x86_64/entry.S ENTRY(common_interrupt) · line 513

Quoted 10 lines
xen/arch/x86/x86_64/entry.S +7 -0
@@ -487,6 +504,13 @@ ENTRY(common_interrupt)
 /* No special register assumptions. */
 ENTRY(ret_from_intr)
         GET_CURRENT(%rbx)
+
+        /* If we are in Xen's user mode, return into it */
+        cmpq $1,VCPU_user_mode(%rbx)
+        cli
+        je    restore_all_guest
+        sti
+

None of this should be necessary - the exception frame created by lstar_enter should cause ret_from_intr to do the correct thing.

Quoted 98 lines
xen/arch/x86/x86_64/entry.S +11 -0
         testb $3,UREGS_cs(%rsp)
         jz    restore_all_xen
         movq  VCPU_domain(%rbx),%rax
@@ -509,6 +533,14 @@ handle_exception_saved:
         GET_CURRENT(%rbx)
         PERFC_INCR(exceptions, %rax, %rbx)
         callq *(%rdx,%rax,8)
+
+        /* If we are in Xen's user mode, return into it */
+        /* TODO: Test this path */
+        cmpq  $1,VCPU_user_mode(%rbx)
+        cli
+        je    restore_all_guest
+        sti
+
         testb $3,UREGS_cs(%rsp)
         jz    restore_all_xen
         leaq  VCPU_trap_bounce(%rbx),%rdx
@@ -664,6 +696,9 @@ handle_ist_exception:
         movl  $EVENT_CHECK_VECTOR,%edi
         call  send_IPI_self
 1:      movq  VCPU_domain(%rbx),%rax
+        /* This also handles Xen ring3 return for us.
+         * So, there is no need to explicitly do a user mode check.
+         */
         cmpb  $0,DOMAIN_is_32bit_pv(%rax)
         je    restore_all_guest
         jmp   compat_restore_all_guest
xen/include/asm-x86/hvm/vmx/vmx.h +2 -0
index 3fbfa44..98e269e 100644
@@ -565,4 +565,6 @@ typedef struct {
     u16 eptp_index;
 } ve_info_t;
 
+struct vmx_msr_state *get_host_msr_state(void);
+
 #endif /* __ASM_X86_HVM_VMX_VMX_H__ */
xen/include/xen/hvm/deprivileged.h +38 -0
index 6cc803e..e42f39a 100644
@@ -68,6 +68,37 @@ int hvm_deprivileged_copy_l1(struct domain *d,
                              unsigned int l1_flags);
 
 
+/* Used to prepare each vcpu's data for user mode. Call for each HVM vcpu. */
+int hvm_deprivileged_prepare_vcpu(struct vcpu *vcpu);
+
+/* Destroy each vcpu's data for Xen user mode. Again, call for each vcpu. */
+void hvm_deprivileged_destroy_vcpu(struct vcpu *vcpu);
+
+/* Called to perform a user mode operation. */
+void hvm_deprivileged_user_mode(void);
+
+/* Called when the user mode operation has completed */
+void hvm_deprivileged_finish_user_mode(void);
+
+/* Called to move into and then out of user mode. Needed for accessing
+ * assembly features.
+ */
+void hvm_deprivileged_user_mode_asm(void);
+
+/* Called on the return path to return to the correct execution point */
+void hvm_deprivileged_finish_user_mode_asm(void);
+
+/* Handle any syscalls that the user mode makes */
+void hvm_deprivileged_handle_user_mode(void);
+
+/* The ring 3 code */
+void hvm_deprivileged_ring3(void);
+
+/* Call when inside a trap that should cause a domain crash if in user mode
+ * e.g. an invalid_op is trapped whilst in user mode.
+ */
+void hvm_deprivileged_check_trap(const char* func_name);
+
 /* The segments where the user mode .text and .data are stored */
 extern unsigned long int __hvm_deprivileged_text_start;
 extern unsigned long int __hvm_deprivileged_text_end;
@@ -91,4 +122,11 @@ extern unsigned long int __hvm_deprivileged_data_end;
 
 #define HVM_ERR_PG_ALLOC -1
 
+/* The user mode stack pointer.
++ * The stack grows down so set this to top of the stack region. Then,
++ * as this is 0-indexed, move into the stack, not just after it.
++ * Subtract 16 bytes for correct stack alignment.
++ */
+#define HVM_STACK_PTR (HVM_DEPRIVILEGED_STACK_ADDR + STACK_SIZE - 16)
+
 #endif
xen/include/xen/sched.h +0 -0
index 73d3bc8..180643e 100644

xen/include/xen/sched.h void evtchn_destroy_final(struct domain *d); /* from complete_domain_destroy */ · line 140

Quoted 5 lines
xen/include/xen/sched.h +1 -1
@@ -137,7 +137,7 @@ void evtchn_destroy_final(struct domain *d); /* from complete_domain_destroy */
 
 struct waitqueue_vcpu;
 
-struct vcpu 
+struct vcpu

Trailing whitespace is nasty, but we avoid inflating the patch by dropping whitespace on lines not touched by semantic changes.

Quoted 7 lines
xen/include/xen/sched.h +0 -0
 {
     int              vcpu_id;
 
@@ -158,6 +158,22 @@ struct vcpu
 
     void            *sched_priv;    /* scheduler-specific data */
 

xen/include/xen/sched.h struct vcpu · line 170

Quoted 10 lines
xen/include/xen/sched.h +10 -0
+    /* HVM deprivileged mode state */
+    void *stack;             /* Location of stack to save data onto */
+    unsigned long rsp;       /* rsp of our stack to restore our data to */
+    unsigned long user_mode; /* Are we (possibly moving into) in user mode? */
+
+    /* The mstar of the processor that we are currently executing on.
+     *  we need to save this because Xen does lazy saving of these.
+     */
+    unsigned long int msr_lstar; /* lstar */
+    unsigned long int msr_star;

There should be no need to store this like this. Follow what the current context switching code does.

~Andrew

Quoted 9 lines
xen/include/xen/sched.h +6 -0
+
+    /* Debug info */
+    unsigned long int old_rsp;
+    unsigned long int old_processor;
+    unsigned long int old_msr_lstar;
+    unsigned long int old_msr_star;
     struct vcpu_runstate_info runstate;
 #ifndef CONFIG_COMPAT
 # define runstate_guest(v) ((v)->runstate_guest)
#42 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Ben Catterall
Quoted 16 lines · Ben Catterall

Added trap handlers to catch exceptions such as a page fault, general protection fault, etc. These handlers will crash the domain as such exceptions would indicate that either there is a bug in deprivileged mode or it has been compromised by an attacker.

---
 xen/arch/x86/mm/hap/hap.c |  9 +++++++++
 xen/arch/x86/traps.c      | 41 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 49 insertions(+), 1 deletion(-)
xen/arch/x86/mm/hap/hap.c +0 -0
index abc5113..43bde89 100644

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 692

Quoted 8 lines
xen/arch/x86/mm/hap/hap.c +5 -0
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v, unsigned long va,
 {
     struct domain *d = v->domain;
 
+    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);

%pv is your friend. Like Linux, we have custom printk formats. In this case, passing 'v' as a parameter to %pv will cause d$Xv$Y to be printed. (The example below predates %pv being introduced).

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 693

Quoted 1 line
xen/arch/x86/mm/hap/hap.c +1 -0
+        domain_crash_synchronous();

No need for _synchronous() here. _synchronous() should only be used when you can't safely recover. It ends up spinning in a tight loop waiting for the next timer interrupt, is anything up to 30ms away.

~Andrew

Quoted 8 lines
xen/arch/x86/mm/hap/hap.c +3 -0
+    }
+
     HAP_ERROR("Intercepted a guest #PF (%u:%u) with HAP enabled.\n",
               d->domain_id, v->vcpu_id);
+
     domain_crash(d);
     return 0;
 }
#3 lore raw

Re: [RFC 1/4] HVM x86 deprivileged mode: Page allocation helper

In reply to Andrew Cooper
Quoted 10 lines · Andrew Cooper
Quoted 5 lines · Ben Catterall

This allocation function is used by the deprivileged mode initialisation code to allocate pages for the new page table mappings and page frames on the HAP page heap.

This is fine for your test box, but isn't fine for systems out there without hardware EPT/NPT support. For older systems like that (or in certain specific workloads), shadow paging is used instead.

Quoted 5 lines

This feature is applicable to any HVM domain, which means that it shouldn't depend on HAP or shadow paging.

How much memory is allocated for the depriv area, and what exactly is allocated in total?

So, per-vcpu:
- a user mode stack which, from your comments in [RFC 2/4], can be 2 pages
- local data (may or may not be needed, depends on the device) which will be around a page or two.

Text segment: as per your comments in RFC 2/4, this will be changed to be an alias so no extra memory.

Quoted 9 lines

I expect it isn't very much, and would suggest using d->arch.paging.alloc_page() instead (which is the generic "get me some memory accounted against the domain" helper) which looks as if it should suffice.

Depending on exactly how much memory is needed, you might need to bump the default minimum shadow pool size.

~Andrew

Ok, will do. That will also solve the EPT/NPT problem, thanks!

Ben

#43 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Andrew Cooper
Quoted 20 lines · Andrew Cooper
Quoted 19 lines · Ben Catterall

Added trap handlers to catch exceptions such as a page fault, general protection fault, etc. These handlers will crash the domain as such exceptions would indicate that either there is a bug in deprivileged mode or it has been compromised by an attacker.

---
  xen/arch/x86/mm/hap/hap.c |  9 +++++++++
  xen/arch/x86/traps.c      | 41 ++++++++++++++++++++++++++++++++++++++++-
  2 files changed, 49 insertions(+), 1 deletion(-)
xen/arch/x86/mm/hap/hap.c +0 -0
index abc5113..43bde89 100644
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v, unsigned long va,
  {
      struct domain *d = v->domain;
 
Quoted 8 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 692

Quoted 5 lines
xen/arch/x86/mm/hap/hap.c +5 -0
+    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);

%pv is your friend. Like Linux, we have custom printk formats. In this case, passing 'v' as a parameter to %pv will cause d$Xv$Y to be printed. (The example below predates %pv being introduced).

ok, will do. thanks!

Quoted 5 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 693

Quoted 2 lines
xen/arch/x86/mm/hap/hap.c +1 -0
+        domain_crash_synchronous();

No need for _synchronous() here. _synchronous() should only be used when you can't safely recover. It ends up spinning in a tight loop waiting for the next timer interrupt, is anything up to 30ms away.

I'm not sure if we can safely recover from this. This will only be triggered if there is a bug in depriv mode or if the mode has been compromised and an attacker has tried to access unavailable memory. From my understanding (am I missing something?): domain_crash effectively sets flags to tell the scheduler that it should be killed the next time the scheduler runs and then returns. In which case, if we don't do a synchronous crash, this return path would return back into the deprivileged mode, we would not have mapped in the page (as we shouldn't), and then we get another fault.

What do you think is the best way forward? Thanks!

Quoted 10 lines

~Andrew

Quoted 8 lines
xen/arch/x86/mm/hap/hap.c +3 -0
+    }
+
      HAP_ERROR("Intercepted a guest #PF (%u:%u) with HAP enabled.\n",
                d->domain_id, v->vcpu_id);
+
      domain_crash(d);
      return 0;
  }
#15 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Andrew Cooper
Quoted 16 lines · Andrew Cooper
Quoted 15 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer. This allows us to restore the stack when we have finished the deprivileged mode operation, meaning we can continue execution from that point. This is similar to if a context switch had happened.

To exit deprivileged mode, we copy the stack back, replacing the current stack. We can then continue execution from where we left off, which will unwind the stack and free up resources. This method means that we do not need to change any other code paths and its invocation will be transparent to callers. This should allow the feature to be more easily deployed to different parts of Xen.

Quoted 6 lines
Quoted 2 lines

Note that this copy of the stack is per-vcpu but, it will contain per-pcpu data. Extra work is needed to properly migrate vcpus between pcpus.

Under what circumstances do you see there being persistent state in the depriv area between calls, given that the calls are synchronous from VM actions?

I don't know if we can make these synchronous as we need a way to interrupt the vcpu if it's spinning for a long time. Otherwise an attacker could just spin in depriv and cause a DoS. With that in mind, the scheduler may decide to migrate the vcpu whilst it's in depriv mode which would mean this per-pcpu data is held in the stack copy which is then migrated to another pcpu incorrectly.

Quoted 11 lines
Quoted 4 lines

The switch to and from deprivileged mode is performed using sysret and syscall respectively.

I suspect we need to borrow the SS attribute workaround from Linux to make this function reliably on AMD systems.

https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=61f01dd941ba9e06d2bf05994450ecc3d61b6b8b

Ah! ok, I'll look into this. Thanks!

Quoted 33 lines
Quoted 33 lines

The return paths in entry.S have been edited so that, when we receive an interrupt whilst in deprivileged mode, we return into that mode correctly.

A hook on the syscall handler in entry.S has also been added which handles returning from user mode and will support deprivileged mode system calls when these are needed.

---
  xen/arch/x86/domain.c               |  12 +++
  xen/arch/x86/hvm/Makefile           |   1 +
  xen/arch/x86/hvm/deprivileged.c     | 103 ++++++++++++++++++
  xen/arch/x86/hvm/deprivileged_asm.S | 205 ++++++++++++++++++++++++++++++++++++
  xen/arch/x86/hvm/vmx/vmx.c          |   7 ++
  xen/arch/x86/x86_64/asm-offsets.c   |   5 +
  xen/arch/x86/x86_64/entry.S         |  35 ++++++
  xen/include/asm-x86/hvm/vmx/vmx.h   |   2 +
  xen/include/xen/hvm/deprivileged.h  |  38 +++++++
  xen/include/xen/sched.h             |  18 +++-
  10 files changed, 425 insertions(+), 1 deletion(-)

create mode 100644 xen/arch/x86/hvm/deprivileged_asm.S

xen/arch/x86/domain.c +1 -0
index 045f6ff..a0e5e70 100644
@@ -62,6 +62,7 @@
  #include <xen/iommu.h>
  #include <compat/vcpu.h>
  #include <asm/psr.h>
+#include <xen/hvm/deprivileged.h>
 
Quoted 12 lines

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

Quoted 9 lines
xen/arch/x86/domain.c +3 -0
  DEFINE_PER_CPU(struct vcpu *, curr_vcpu);
  DEFINE_PER_CPU(unsigned long, cr4);
@@ -446,6 +447,12 @@ int vcpu_initialise(struct vcpu *v)
      if ( has_hvm_container_domain(d) )
      {
          rc = hvm_vcpu_initialise(v);
+
+        /* Initialise HVM deprivileged mode */
+        printk("HVM initialising deprivileged mode ...");

All printk()s should have a XENLOG_$severity prefix.

will do.

Quoted 59 lines
Quoted 46 lines
xen/arch/x86/domain.c +8 -0
+        hvm_deprivileged_prepare_vcpu(v);
+        printk("Done.\n");
+
          goto done;
      }
 
@@ -523,7 +530,12 @@ void vcpu_destroy(struct vcpu *v)
      vcpu_destroy_fpu(v);
 
      if ( has_hvm_container_vcpu(v) )
+    {
+        /* Destroy the deprivileged mode on this vcpu */
+        hvm_deprivileged_destroy_vcpu(v);
+
          hvm_vcpu_destroy(v);
+    }
      else
          xfree(v->arch.pv_vcpu.trap_ctxt);
  }
xen/arch/x86/hvm/Makefile +1 -0
index bd83ba3..6819886 100644
@@ -17,6 +17,7 @@ obj-y += quirks.o
  obj-y += rtc.o
  obj-y += save.o
  obj-y += deprivileged.o
+obj-y += deprivileged_asm.o
  obj-y += stdvga.o
  obj-y += vioapic.o
  obj-y += viridian.o
xen/arch/x86/hvm/deprivileged.c +7 -0
index 071d900..979fc69 100644
@@ -439,3 +439,106 @@ int hvm_deprivileged_copy_l1(struct domain *d,
      }
      return 0;
  }
+
+/* Used to prepare each vcpus data for user mode. Call for each HVM vcpu.
+ */
+int hvm_deprivileged_prepare_vcpu(struct vcpu *vcpu)
+{
+    struct page_info *pg;
+

xen/arch/x86/hvm/deprivileged.c int hvm_deprivileged_copy_l1(struct domain *d, · line 458

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c +10 -0
+    /* TODO: clarify if this MEMF is correct */
+    /* Allocate 2^STACK_ORDER contiguous pages */
+    pg = alloc_domheap_pages(NULL, STACK_ORDER, MEMF_no_owner);
+    if( pg == NULL )
+    {
+        panic("HVM: Out of memory on per-vcpu deprivileged mode init.\n");
+        return -ENOMEM;
+    }
+
+    vcpu->stack = page_to_virt(pg);

Xen has two heaps, the xenheap and the domheap.

Quoted 8 lines

You may only construct pointers like this into the xenheap. The domheap is not guaranteed to have safe virtual mappings to. (This code only works because your test box isn't bigger than 5TB. Also there is a bug with xenheap allocations at the same point, but I need to fix that bug).

All access to domheap pages must strictly be within a map_domain_page()/unmap() region, which construct save temporary mappings.

ok, I'll add these.

Quoted 44 lines
Quoted 28 lines
xen/arch/x86/hvm/deprivileged.c +28 -0
+    vcpu->rsp = 0;
+    vcpu->user_mode = 0;
+
+    return 0;
+}
+
+/* Called on destroying each vcpu */
+void hvm_deprivileged_destroy_vcpu(struct vcpu *vcpu)
+{
+    free_domheap_pages(virt_to_page(vcpu->stack), STACK_ORDER);
+}
+
+/* Called to perform a user mode operation.
+ * Execution context is saved and then we move into user mode.
+ * This method is then jumped into to restore execution context after
+ * exiting user mode.
+ */
+void hvm_deprivileged_user_mode(void)
+{
+    struct vcpu *vcpu = get_current();
+    unsigned long int efer = read_efer();
+    register unsigned long sp asm("rsp");
+
+    ASSERT( vcpu->user_mode == 0 );
+    ASSERT( vcpu->stack != 0 );
+    ASSERT( vcpu->rsp == 0 );
+
+    /* Flip the SCE bit to allow sysret/call */

xen/arch/x86/hvm/deprivileged.c int hvm_deprivileged_copy_l1(struct domain *d, · line 496

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c +10 -0
+    write_efer(efer | EFER_SCE);
+
+    /* Save the msr lstar and star. Xen does lazy loading of these
+     * so we need to put the host values in and then restore the
+     * guest ones once we're done.
+     */
+    rdmsrl(MSR_LSTAR, vcpu->msr_lstar);
+    rdmsrl(MSR_STAR, vcpu->msr_star);
+    wrmsrl(MSR_LSTAR,get_host_msr_state()->msrs[VMX_INDEX_MSR_LSTAR]);
+    wrmsrl(MSR_STAR, get_host_msr_state()->msrs[VMX_INDEX_MSR_STAR]);

A partial context switch like this should be implemented as two new hvm_ops such as hvm_op.depriv_ctxt_switch_{to,from}()

This allows you to keep the common code clean of vendor specific code.

Quoted 11 lines

xen/arch/x86/hvm/deprivileged.c int hvm_deprivileged_copy_l1(struct domain *d, · line 504

Quoted 8 lines
xen/arch/x86/hvm/deprivileged.c +8 -0
+
+    /* The assembly routine to handle moving into/out of deprivileged mode */
+    hvm_deprivileged_user_mode_asm();
+
+    /* If our copy failed */
+    if( unlikely(vcpu->rsp == 0) )
+    {
+        gdprintk(XENLOG_ERR, "HVM: Stack too large in %s\n", __FUNCTION__);

__func__ please. It conforms to C99 whereas __FUNCTION__ is a gnuism.

got it.

Quoted 154 lines
Quoted 119 lines
xen/arch/x86/hvm/deprivileged.c +40 -0
+        domain_crash_synchronous();
+    }
+
+    /* Debug info */
+    vcpu->old_msr_lstar = get_host_msr_state()->msrs[VMX_INDEX_MSR_LSTAR];
+    vcpu->old_msr_star = get_host_msr_state()->msrs[VMX_INDEX_MSR_STAR];
+    vcpu->old_rsp = sp;
+    vcpu->old_processor = smp_processor_id();
+
+    /* Restore the efer and saved msr registers */
+    write_efer(efer);
+    wrmsrl(MSR_LSTAR, vcpu->msr_lstar);
+    wrmsrl(MSR_STAR, vcpu->msr_star);
+    vcpu->user_mode = 0;
+    vcpu->rsp = 0;
+}
+
+/* Called when the user mode operation has completed
+ * Perform C-level processing on return pathx
+ */
+void hvm_deprivileged_finish_user_mode(void)
+{
+    /* If we are not returning from user mode: bail */
+    ASSERT(get_current()->user_mode == 1);
+
+    hvm_deprivileged_finish_user_mode_asm();
+}
+
+void hvm_deprivileged_check_trap(const char* func_name)
+{
+    if( current->user_mode == 1 )
+    {
+        printk("HVM Deprivileged Mode: Trap whilst in user mode, %s\n",
+               func_name);
+        domain_crash_synchronous();
+    }
+}
+
+
+
xen/arch/x86/hvm/deprivileged_asm.S new file +73 -0
new file mode 100644
index 0000000..00a9e9c
@@ -0,0 +1,205 @@
+/*
+ * HVM security enhancements assembly code
+ */
+#include <xen/config.h>
+#include <xen/errno.h>
+#include <xen/softirq.h>
+#include <asm/asm_defns.h>
+#include <asm/apicdef.h>
+#include <asm/page.h>
+#include <public/xen.h>
+#include <irq_vectors.h>
+#include <xen/hvm/deprivileged.h>
+
+/* Handles entry into the deprivileged mode and returning from this
+ * mode. This requires copying the current Xen privileged stack across
+ * to a per-vcpu buffer as we need to be able to handle interrupts and
+ * exceptions whilst in this mode. Xen is non-preemptable so our
+ * privileged mode stack would  be clobbered if we did not save it.
+ *
+ * If we are entering deprivileged mode, then we use a sysret to get there.
+ * If we are returning from deprivileged mode, then we need to unwind the stack
+ * so we copy it back over the current stack so that we can return from the
+ * call path where we came in from.
+ *
+ * We're doing sort-of a long jump/set jump with copying to a stack to
+ * preserve it and allow returning code to continue executing from
+ * within this method.
+ */
+ENTRY(hvm_deprivileged_user_mode_asm)
+        /* Save our registers */
+        push   %rax
+        push   %rbx
+        push   %rcx
+        push   %rdx
+        push   %rsi
+        push   %rdi
+        push   %rbp
+        push   %r8
+        push   %r9
+        push   %r10
+        push   %r11
+        push   %r12
+        push   %r13
+        push   %r14
+        push   %r15
+        pushfq
+
+        /* Perform a near call to push rip onto the stack */
+        call   1f
+
+        /* Magic: Add to the stored rip the size of the code between
+         * label 1 and label 2. This allows  us to restart execution at label 2.
+         */
+1:      addq   $2f-1b, (%rsp)
+
+        GET_CURRENT(%r8)
+        xor    %rsi, %rsi
+
+        /* The following is equivalent to
+         * (get_cpu_info() + sizeof(struct cpu_info))
+         * This gets us to the top of the stack.
+         */
+        GET_STACK_BASE(%rcx)
+        addq   $STACK_SIZE, %rcx
+
+        movq   VCPU_stack(%r8), %rdi
+
+        /* We need copy the current stack across to our buffer
+         * Calculate the number of bytes to copy:
+         * (top of stack - current stack pointer)
+         * NOTE: We must not push any more data onto our stack after this point
+         * as it won't be saved.
+         */

xen/arch/x86/hvm/deprivileged_asm.S line 83

Quoted 10 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +10 -0
+        sub    %rsp, %rcx
+
+        /* If the stack is too big, we don't do the copy: handled by caller. */
+        cmpq   $STACK_SIZE, %rcx
+        ja     3f
+
+        mov    %rsp, %rsi
+/* USER MODE ENTRY POINT */
+2:
+        /* More magic: If we came here from preparing to go into user mode,

There is a very fine line between magic and gross hack ;)

I havn't quite decided which this is yet, but it certainly is neat, if rather opaque.

Quoted 19 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +19 -0
+         * then we copy our current stack to the buffer (the lines above
+         * have setup rsi, rdi and rcx to do this).
+         *
+         * If we came here from user mode, then we movsb to copy from
+         * our buffer into our current stack so that we can continue
+         * execution from the current code point, and return back to the guest
+         * via the path we came in. rsi, rdi and rcx have been setup by the
+         * de-privileged return path for this.
+         */
+        rep    movsb
+        mov    %rsp, %rsi
+
+        GET_CURRENT(%r8)
+        movq   VCPU_user_mode(%r8), %rdx
+        movq   VCPU_rsp(%r8), %rax
+
+        /* If !user_mode  */
+        cmpq   $0, %rdx
+        jne    3f
Quoted 9 lines

xen/arch/x86/hvm/deprivileged_asm.S line 107

Quoted 5 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +5 -0
+        cli
+
+        movabs $HVM_DEPRIVILEGED_TEXT_ADDR, %rcx /* RIP in user mode */
+
+        movq   $0x10200, %r11          /* RFLAGS user mode enable interrupts */

Please use $(X86_FLAGS_IF | X86_FLAGS_MBS) to be more clear which flags are being set.

will do.

Quoted 5 lines

Also, by enabling interrupts, you need some hook to short-circuit the scheduling softirq. As it currently stands, a timer interrupt interrupting depriv mode is liable to swap all your state out from under you.

We need interrupts to be enabled so that we can prevent a DoS from depriv by allowing the scheduler to decide to deschedule it. That's also why we needed some of the return path changes.

Quoted 122 lines

xen/arch/x86/hvm/deprivileged_asm.S line 111

Quoted 4 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +4 -0
+        movq   $1, VCPU_user_mode(%r8) /* Now in user mode */
+        movq   %rsi, VCPU_rsp(%r8)     /* The rsp to restore to */
+
+        /* Stack ptr is set by user mode to avoid race conditions.

What race condition are you referring to?

xen/arch/x86/hvm/deprivileged_asm.S line 112

Quoted 1 line
xen/arch/x86/hvm/deprivileged_asm.S new file +1 -0
+         * See Intel manual 2 on the sysret instruction.

As a general rule, read both the Intel and the AMD manual for bits like this. sysret is one of the areas where implementations differ.

Quoted 110 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +93 -0
+         */
+        movq   $HVM_STACK_PTR, %rbx
+        sysretq                         /* Enter deprivileged mode */
+
+3:      GET_CURRENT(%r8)
+        movq   %rsi, VCPU_rsp(%r8)
+        pop    %rax    /* Pop off rip: used in a jump so still on stack */
+
+        /* Restore registers */
+        popfq
+        pop    %r15
+        pop    %r14
+        pop    %r13
+        pop    %r12
+        pop    %r11
+        pop    %r10
+        pop    %r9
+        pop    %r8
+        pop    %rbp
+        pop    %rdi
+        pop    %rsi
+        pop    %rdx
+        pop    %rcx
+        pop    %rbx
+        pop    %rax
+        ret
+
+/* Finished in user mode so return */
+ENTRY(hvm_deprivileged_finish_user_mode_asm)
+        /* The source is the copied stack in our buffer.
+         * The destination is our current stack.
+         *
+         * We need to:
+         * - Move the stack pointer to where it was before we entered
+         *   deprivileged mode.
+         * - Setup rsi, rdi and rcx as needed to perform the copy
+         * - Jump to the address held at the top of the stack which
+         *   is the user mode return address
+         */
+        cli
+        GET_CURRENT(%rbx)
+        movq   VCPU_stack(%rbx), %rsi
+        movq   VCPU_rsp(%rbx), %rdi
+
+        /* The return address that the near call pushed onto the
+         * buffer is pointed to by stack, so use that for rip.
+         */
+        movq   %rdi, %rsp
+
+        /* The following is equivalent to
+         * (get_cpu_info() + sizeof(struct cpu_info) - vcpu->rsp)
+         * This works out how many bytes we need to copy:
+         * (top of stack - bottom of stack)
+         */
+        GET_STACK_BASE(%rcx)
+        addq   $STACK_SIZE, %rcx
+        subq   %rdi, %rcx
+
+        /* Go to user mode return code */
+        jmp    *(%rsi)
+
+/* Entry point from the assembly syscall handlers */
+ENTRY(hvm_deprivileged_handle_user_mode)
+
+        /* Handle a user mode hypercall here */
+
+
+        /* We are finished in user mode */
+        call hvm_deprivileged_finish_user_mode
+
+        ret
+
+.section .hvm_deprivileged_enhancement.text,"ax"
+/* HVM deprivileged code */
+ENTRY(hvm_deprivileged_ring3)
+        /* sysret has loaded eip from rcx and rflags from r11.
+         * CS and SS have been loaded from the MSR for ring 3.
+         * We now need to  switch to the user mode stack
+         */
+        /* Setup usermode stack */
+        movabs $HVM_STACK_PTR, %rsp
+
+        /* Perform user mode processing */
+
+        mov $0xf, %rcx
+1: dec  %rcx
+        cmp $0, %rcx
+        jne 1b
+
+        /* Return to ring 0 */
+        syscall
+
+.previous
xen/arch/x86/hvm/vmx/vmx.c +2 -0
index c32d863..595b0f2 100644
@@ -59,6 +59,8 @@
  #include <asm/event.h>
  #include <asm/monitor.h>
  #include <public/arch-x86/cpuid.h>
+#include <xen/hvm/deprivileged.h>
+
 
  static bool_t __initdata opt_force_ept;
  boolean_param("force-ept", opt_force_ept);
@@ -194,6 +196,10 @@ void vmx_save_host_msrs(void)
          set_bit(VMX_INDEX_MSR_ ## address, &host_msr_state->flags);     \
      } while ( 0 )
 
Quoted 15 lines

xen/arch/x86/hvm/vmx/vmx.c long_mode_do_msr_write(unsigned int msr, uint64_t msr_content) · line 281

Quoted 12 lines
xen/arch/x86/hvm/vmx/vmx.c +5 -0
+struct vmx_msr_state *get_host_msr_state(void) {
+    return &this_cpu(host_msr_state);
+}
+
  static enum handler_return
  long_mode_do_msr_read(unsigned int msr, uint64_t *msr_content)
  {
@@ -272,6 +278,7 @@ long_mode_do_msr_write(unsigned int msr, uint64_t msr_content)
      case MSR_LSTAR:
          if ( !is_canonical_address(msr_content) )
              goto uncanonical_address;
+

Please avoid spurious changes like this.

apologies.

Quoted 53 lines
Quoted 40 lines
xen/arch/x86/hvm/vmx/vmx.c +0 -0
          WRITE_MSR(LSTAR);
          break;
 
xen/arch/x86/x86_64/asm-offsets.c +5 -0
index 447c650..fd5de44 100644
@@ -115,6 +115,11 @@ void __dummy__(void)
      OFFSET(VCPU_nsvm_hap_enabled, struct vcpu, arch.hvm_vcpu.nvcpu.u.nsvm.ns_hap_enabled);
      BLANK();
 
+    OFFSET(VCPU_stack, struct vcpu, stack);
+    OFFSET(VCPU_rsp, struct vcpu, rsp);
+    OFFSET(VCPU_user_mode, struct vcpu, user_mode);
+    BLANK();
+
      OFFSET(DOMAIN_is_32bit_pv, struct domain, arch.is_32bit_pv);
      BLANK();
 
xen/arch/x86/x86_64/entry.S +9 -0
index 74677a2..fa9155c 100644
@@ -102,6 +102,15 @@ restore_all_xen:
          RESTORE_ALL adj=8
          iretq
 
+/* Returning from user mode */
+handle_hvm_user_mode:
+
+        call hvm_deprivileged_handle_user_mode
+
+        /* Go back into user mode */
+        cli
+        jmp  restore_all_guest
+
  /*
   * When entering SYSCALL from kernel mode:
   *  %rax                            = hypercall vector

xen/arch/x86/x86_64/entry.S ENTRY(lstar_enter) · line 149

Quoted 10 lines
xen/arch/x86/x86_64/entry.S +7 -0
@@ -131,6 +140,14 @@ ENTRY(lstar_enter)
          testb $TF_kernel_mode,VCPU_thread_flags(%rbx)
          jz    switch_to_kernel
 
+        /* Were we in Xen's ring 3?  */
+        push %rbx
+        GET_CURRENT(%rbx)
+        movq VCPU_user_mode(%rbx), %rbx
+        cmp  $1, %rbx
+        je   handle_hvm_user_mode
+        pop  %rbx

No need for the movq or rbx clobber. This entire block can be:

Quoted 5 lines

cmpb $1, VCPU_user_mode(%rbx)
je handle_hvm_user_mode

Similar to the $TF_kernel_mode check in context above.

got it. Thanks!

Quoted 12 lines
Quoted 12 lines
xen/arch/x86/x86_64/entry.S +3 -0
+
  /*hypercall:*/
          movq  %r10,%rcx
          cmpq  $NR_hypercalls,%rax
@@ -487,6 +504,13 @@ ENTRY(common_interrupt)
  /* No special register assumptions. */
  ENTRY(ret_from_intr)
          GET_CURRENT(%rbx)
+
+        /* If we are in Xen's user mode, return into it */
Quoted 9 lines

xen/arch/x86/x86_64/entry.S ENTRY(common_interrupt) · line 513

Quoted 5 lines
xen/arch/x86/x86_64/entry.S +5 -0
+        cmpq $1,VCPU_user_mode(%rbx)
+        cli
+        je    restore_all_guest
+        sti
+

None of this should be necessary - the exception frame created by lstar_enter should cause ret_from_intr to do the correct thing.

I think this is needed as we have interrupts enabled and so we can take interrupts from paths other than lstar_enter. This ensures that Xen doesn't treat our depriv mode as a PV guest which led to random page, general protection etc. faults.

Quoted 114 lines
Quoted 98 lines
xen/arch/x86/x86_64/entry.S +11 -0
          testb $3,UREGS_cs(%rsp)
          jz    restore_all_xen
          movq  VCPU_domain(%rbx),%rax
@@ -509,6 +533,14 @@ handle_exception_saved:
          GET_CURRENT(%rbx)
          PERFC_INCR(exceptions, %rax, %rbx)
          callq *(%rdx,%rax,8)
+
+        /* If we are in Xen's user mode, return into it */
+        /* TODO: Test this path */
+        cmpq  $1,VCPU_user_mode(%rbx)
+        cli
+        je    restore_all_guest
+        sti
+
          testb $3,UREGS_cs(%rsp)
          jz    restore_all_xen
          leaq  VCPU_trap_bounce(%rbx),%rdx
@@ -664,6 +696,9 @@ handle_ist_exception:
          movl  $EVENT_CHECK_VECTOR,%edi
          call  send_IPI_self
  1:      movq  VCPU_domain(%rbx),%rax
+        /* This also handles Xen ring3 return for us.
+         * So, there is no need to explicitly do a user mode check.
+         */
          cmpb  $0,DOMAIN_is_32bit_pv(%rax)
          je    restore_all_guest
          jmp   compat_restore_all_guest
xen/include/asm-x86/hvm/vmx/vmx.h +2 -0
index 3fbfa44..98e269e 100644
@@ -565,4 +565,6 @@ typedef struct {
      u16 eptp_index;
  } ve_info_t;
 
+struct vmx_msr_state *get_host_msr_state(void);
+
  #endif /* __ASM_X86_HVM_VMX_VMX_H__ */
xen/include/xen/hvm/deprivileged.h +38 -0
index 6cc803e..e42f39a 100644
@@ -68,6 +68,37 @@ int hvm_deprivileged_copy_l1(struct domain *d,
                               unsigned int l1_flags);
 
 
+/* Used to prepare each vcpu's data for user mode. Call for each HVM vcpu. */
+int hvm_deprivileged_prepare_vcpu(struct vcpu *vcpu);
+
+/* Destroy each vcpu's data for Xen user mode. Again, call for each vcpu. */
+void hvm_deprivileged_destroy_vcpu(struct vcpu *vcpu);
+
+/* Called to perform a user mode operation. */
+void hvm_deprivileged_user_mode(void);
+
+/* Called when the user mode operation has completed */
+void hvm_deprivileged_finish_user_mode(void);
+
+/* Called to move into and then out of user mode. Needed for accessing
+ * assembly features.
+ */
+void hvm_deprivileged_user_mode_asm(void);
+
+/* Called on the return path to return to the correct execution point */
+void hvm_deprivileged_finish_user_mode_asm(void);
+
+/* Handle any syscalls that the user mode makes */
+void hvm_deprivileged_handle_user_mode(void);
+
+/* The ring 3 code */
+void hvm_deprivileged_ring3(void);
+
+/* Call when inside a trap that should cause a domain crash if in user mode
+ * e.g. an invalid_op is trapped whilst in user mode.
+ */
+void hvm_deprivileged_check_trap(const char* func_name);
+
  /* The segments where the user mode .text and .data are stored */
  extern unsigned long int __hvm_deprivileged_text_start;
  extern unsigned long int __hvm_deprivileged_text_end;
@@ -91,4 +122,11 @@ extern unsigned long int __hvm_deprivileged_data_end;
 
  #define HVM_ERR_PG_ALLOC -1
 
+/* The user mode stack pointer.
++ * The stack grows down so set this to top of the stack region. Then,
++ * as this is 0-indexed, move into the stack, not just after it.
++ * Subtract 16 bytes for correct stack alignment.
++ */
+#define HVM_STACK_PTR (HVM_DEPRIVILEGED_STACK_ADDR + STACK_SIZE - 16)
+
  #endif
xen/include/xen/sched.h +0 -0
index 73d3bc8..180643e 100644

xen/include/xen/sched.h void evtchn_destroy_final(struct domain *d); /* from complete_domain_destroy */ · line 140

Quoted 5 lines
xen/include/xen/sched.h +1 -1
@@ -137,7 +137,7 @@ void evtchn_destroy_final(struct domain *d); /* from complete_domain_destroy */
 
  struct waitqueue_vcpu;
 
-struct vcpu
+struct vcpu

Trailing whitespace is nasty, but we avoid inflating the patch by dropping whitespace on lines not touched by semantic changes.

Quoted 7 lines
xen/include/xen/sched.h +0 -0
  {
      int              vcpu_id;
 
@@ -158,6 +158,22 @@ struct vcpu
 
      void            *sched_priv;    /* scheduler-specific data */
 
Quoted 14 lines

xen/include/xen/sched.h struct vcpu · line 170

Quoted 10 lines
xen/include/xen/sched.h +10 -0
+    /* HVM deprivileged mode state */
+    void *stack;             /* Location of stack to save data onto */
+    unsigned long rsp;       /* rsp of our stack to restore our data to */
+    unsigned long user_mode; /* Are we (possibly moving into) in user mode? */
+
+    /* The mstar of the processor that we are currently executing on.
+     *  we need to save this because Xen does lazy saving of these.
+     */
+    unsigned long int msr_lstar; /* lstar */
+    unsigned long int msr_star;

There should be no need to store this like this. Follow what the current context switching code does.

ok, I'll take a look.

Quoted 12 lines

~Andrew

Quoted 9 lines
xen/include/xen/sched.h +6 -0
+
+    /* Debug info */
+    unsigned long int old_rsp;
+    unsigned long int old_processor;
+    unsigned long int old_msr_lstar;
+    unsigned long int old_msr_star;
      struct vcpu_runstate_info runstate;
  #ifndef CONFIG_COMPAT
  # define runstate_guest(v) ((v)->runstate_guest)
#16 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 7 lines · Ben Catterall

I don't know if we can make these synchronous as we need a way to interrupt the vcpu if it's spinning for a long time. Otherwise an attacker could just spin in depriv and cause a DoS. With that in mind, the scheduler may decide to migrate the vcpu whilst it's in depriv mode which would mean this per-pcpu data is held in the stack copy which is then migrated to another pcpu incorrectly.

IMO, DoS attacks on depriv'd emulators aren't very interesting.

I think it is counter-productive to address this attack in this initial implementation at the expense (delays/complexity/etc.) of solving the key requirement of mitigating information leaks and privilege escalation attacks

David

#4 lore raw

Re: [RFC 1/4] HVM x86 deprivileged mode: Page allocation helper

In reply to Ben Catterall
Quoted 25 lines · Ben Catterall
Quoted 12 lines · Andrew Cooper
Quoted 7 lines · Ben Catterall

This allocation function is used by the deprivileged mode initialisation code
to allocate pages for the new page table mappings and page frames on the HAP
page heap.

This is fine for your test box, but isn't fine for systems out there without hardware EPT/NPT support. For older systems like that (or in certain specific workloads), shadow paging is used instead.

Quoted 5 lines

This feature is applicable to any HVM domain, which means that it shouldn't depend on HAP or shadow paging.

How much memory is allocated for the depriv area, and what exactly is allocated in total?

So, per-vcpu:
- a user mode stack which, from your comments in [RFC 2/4], can be 2 pages
- local data (may or may not be needed, depends on the device) which will be around
a page or two.

Quoted 3 lines

Text segment: as per your comments in RFC 2/4, this will be changed to be an alias
so no extra memory.

Plus pagetables for all of these.

The stack definitely doesn't need to be per-vcpu. per-pcpu is fine, and will reduce the overhead.

I still don't see why local data would be needed between calls into depriv code. Small enough data can live on the stack, and allowing data to persist across calls risks getting state out-of-sync with the device model under emulation.

(That is not to say that local data isn't needed. I just can't see a viable use for it at this stage.)

~Andrew

#44 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Ben Catterall
Quoted 52 lines · Ben Catterall
Quoted 15 lines · Andrew Cooper
Quoted 14 lines · Ben Catterall

Added trap handlers to catch exceptions such as a page fault, general protection fault, etc. These handlers will crash the domain as such exceptions
would indicate that either there is a bug in deprivileged mode or it has been
compromised by an attacker.

---
  xen/arch/x86/mm/hap/hap.c |  9 +++++++++
  xen/arch/x86/traps.c      | 41
++++++++++++++++++++++++++++++++++++++++-
  2 files changed, 49 insertions(+), 1 deletion(-)
Quoted 16 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, · line 692

Quoted 13 lines
xen/arch/x86/mm/hap/hap.c +4 -0
index abc5113..43bde89 100644
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v,
 unsigned long va,
  {
      struct domain *d = v->domain;
  +    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);

%pv is your friend. Like Linux, we have custom printk formats. In this case, passing 'v' as a parameter to %pv will cause d$Xv$Y to be printed. (The example below predates %pv being introduced).

ok, will do. thanks!

Quoted 5 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 693

Quoted 2 lines
xen/arch/x86/mm/hap/hap.c +1 -0
+        domain_crash_synchronous();

No need for _synchronous() here. _synchronous() should only be used when you can't safely recover. It ends up spinning in a tight loop waiting for the next timer interrupt, is anything up to 30ms away.

I'm not sure if we can safely recover from this. This will only be triggered if there is a bug in depriv mode
or if the mode has been compromised and an attacker has tried to access unavailable memory.
From my understanding (am I missing something?): domain_crash effectively sets flags to tell the scheduler that
it should be killed the next time the scheduler runs and then returns. In which case, if we don't do a
synchronous crash, this return path would return back into the deprivileged mode, we would not
have mapped in the page (as we shouldn't), and then we get another fault.

Quoted 2 lines

What do you think is the best way forward? Thanks!

Given that there is a use of domain_crash(d) in context below, it is clearly safe to use from here. (Although my general point about hap vs shadow code still applies, meaning that hap_page_fault() is not the correct function to hook like this.)

domain_crash() sets a flag, but exiting out from a fault handler heading back towards ring3 code should check for pending softirqs. However, because of the way you have hooked return-to-depriv, you might have broken this.

~Andrew

#11 lore raw

Re: [RFC 2/4] HVM x86 deprivileged mode: Create deprivileged page tables

In reply to Andrew Cooper
Quoted 28 lines · Andrew Cooper
Quoted 27 lines · Ben Catterall

The paging structure mappings for the deprivileged mode are added to the monitor page table for HVM guests. The entries are generated by walking the page tables and mapping in new pages. If a higher-level page table mapping exists, we attempt to traverse all the way down to a leaf page and add the page there. Access bits are flipped as needed.

The page entries are generated for deprivileged .text, .data and a stack. The data is copied from sections allocated by the linker. The mappings are setup in an unused portion of the Xen virtual address space. The pages are mapped in as user mode accessible, with NX bits set for the data and stack regions and the code region is set to be executable and read-only.

The needed pages are allocated on the HAP page heap and are deallocated when those heap pages are deallocated (on domain destruction).

---
  xen/arch/x86/hvm/Makefile          |   1 +
  xen/arch/x86/hvm/deprivileged.c    | 441 +++++++++++++++++++++++++++++++++++++
  xen/arch/x86/mm/hap/hap.c          |  10 +-
  xen/arch/x86/xen.lds.S             |  19 ++
  xen/include/asm-x86/config.h       |  10 +-
  xen/include/xen/hvm/deprivileged.h |  94 ++++++++
  6 files changed, 573 insertions(+), 2 deletions(-)

create mode 100644 xen/arch/x86/hvm/deprivileged.c create mode 100644 xen/include/xen/hvm/deprivileged.h

Quoted 12 lines

xen/arch/x86/hvm/Makefile obj-y += pmtimer.o · line 19

Quoted 9 lines
xen/arch/x86/hvm/Makefile +1 -0
index 794e793..bd83ba3 100644
@@ -16,6 +16,7 @@ obj-y += pmtimer.o
  obj-y += quirks.o
  obj-y += rtc.o
  obj-y += save.o
+obj-y += deprivileged.o

We attempt to keep objects linked in alphabetical order, where possible.

apologies

Quoted 32 lines
Quoted 32 lines
xen/arch/x86/hvm/Makefile +0 -0
  obj-y += stdvga.o
  obj-y += vioapic.o
  obj-y += viridian.o
xen/arch/x86/hvm/deprivileged.c new file +23 -0
new file mode 100644
index 0000000..071d900
@@ -0,0 +1,441 @@
+/*
+ * HVM deprivileged mode to provide support for running operations in
+ * user mode from Xen
+ */
+#include <xen/lib.h>
+#include <xen/mm.h>
+#include <xen/domain_page.h>
+#include <xen/config.h>
+#include <xen/types.h>
+#include <xen/sched.h>
+#include <asm/paging.h>
+#include <xen/compiler.h>
+#include <asm/hap.h>
+#include <asm/paging.h>
+#include <asm-x86/page.h>
+#include <public/domctl.h>
+#include <xen/domain_page.h>
+#include <asm/hvm/vmx/vmx.h>
+#include <xen/hvm/deprivileged.h>
+
+void hvm_deprivileged_init(struct domain *d, l4_pgentry_t *l4e)
+{
+    int ret;
Quoted 9 lines

xen/arch/x86/hvm/deprivileged.c line 27

Quoted 4 lines
xen/arch/x86/hvm/deprivileged.c new file +4 -0
+    void *p;
+    unsigned long int size;
+
+    /* Copy the .text segment for deprivileged code */

Why do you need to copy the deprivileged text section at all? It is read only and completely common. All you should need to do is make userspace mappings to it where it resides in the Xen linked area.

tbh: At the time, I was unsure if it could open a hole if, when Xen switched over to superpages, and the deprivileged code was not aligned on a 4KB page boundary, then mapping it in might prove problematic. Mainly as we'd map in some of Xen's ring 0 code by accident, which could prove useful to an attacker as they could then call this from userspace.

Though, now I've thought about it more, I can ensure in the linker that it's aligned properly and I think map_pages_to_xen() will do what I need.

Quoted 3 lines

i.e. this is an operation which should be performed once at startup, not once per domain. You will also reduce your memory overhead by doing this.

got it.

Quoted 4 lines

xen/arch/x86/hvm/deprivileged.c line 28

Quoted 1 line
xen/arch/x86/hvm/deprivileged.c new file +1 -0
+    size = (unsigned long int)&__hvm_deprivileged_text_end -

Don't bother qualifying unsigned long with a further "int". A plain "unsigned long" is the expected declaration.

understood.

Quoted 17 lines
Quoted 17 lines
xen/arch/x86/hvm/deprivileged.c new file +16 -0
+           (unsigned long int)&__hvm_deprivileged_text_start;
+
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long int)&__hvm_deprivileged_text_start,
+                              (unsigned long int)HVM_DEPRIVILEGED_TEXT_ADDR,
+                              size, 0 /* No write */);
+
+    if( ret )
+    {
+        printk("HVM: Error when initialising depriv .text. Code: %d", ret);
+        domain_crash(d);
+        return;
+    }
+
+    /* Copy the .data segment for ring3 code */
+    size = (unsigned long int)&__hvm_deprivileged_data_end -
Quoted 9 lines

xen/arch/x86/hvm/deprivileged.c line 50

Quoted 6 lines
xen/arch/x86/hvm/deprivileged.c new file +6 -0
+           (unsigned long int)&__hvm_deprivileged_data_start;
+
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long int)&__hvm_deprivileged_data_start,
+                              (unsigned long int)HVM_DEPRIVILEGED_DATA_ADDR,
+                              size, _PAGE_NX | _PAGE_RW);

What do you expect to end up in a data section like this?

It's for passing in configuration data at the start when we run the device (reduce the number of system calls needed) and for local data which the emulated devices may need. It can also be used to put the results of any system calls that the deprivileged code may call.

Quoted 12 lines

xen/arch/x86/hvm/deprivileged.c line 59

Quoted 9 lines
xen/arch/x86/hvm/deprivileged.c new file +9 -0
+
+    if( ret )
+    {
+        printk("HVM: Error when initialising depriv .data. Code: %d", ret);
+        domain_crash(d);
+        return;
+    }
+
+    /* Setup the stack mappings.

Xen recommended style for multiline comments is

Quoted 3 lines

/*
* Setup ...

apologies. I'll revise all of these.

Quoted 10 lines
Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c new file +10 -0
+     * This is a bit of a hack: by allocating a blank area
+     * we can reuse the hvm_deprivileged_copy_pages code.
+     * The stacks are actually allocated in the per-vcpu initialisation
+     * routine.
+     */
+    size = STACK_SIZE;
+
+    p = alloc_xenheap_pages(STACK_ORDER, 0);
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long int)p,
Quoted 9 lines

xen/arch/x86/hvm/deprivileged.c line 73

Quoted 4 lines
xen/arch/x86/hvm/deprivileged.c new file +4 -0
+                              (unsigned long int)HVM_DEPRIVILEGED_STACK_ADDR,
+                              size, _PAGE_NX | _PAGE_RW);
+
+    free_xenheap_pages(p, STACK_ORDER);

The userspace stacks really don't need to be this large. Xens primary stack, which runs all of this code normally, is limited at 2 pages, which is 1/4 of STACK_SIZE.

got it. will do.

Quoted 14 lines
Quoted 14 lines
xen/arch/x86/hvm/deprivileged.c new file +14 -0
+
+    if( ret )
+    {
+        printk("HVM: Error when initialising depriv stack. Code: %d", ret);
+        domain_crash(d);
+        return;
+    }
+}
+
+void hvm_deprivileged_destroy(struct domain *d)
+{
+    struct page_info *pg = NULL;
+
+    /* Free up all the pages we allocated from the HAP HVM list */
Quoted 9 lines

xen/arch/x86/hvm/deprivileged.c line 92

Quoted 5 lines
xen/arch/x86/hvm/deprivileged.c new file +5 -0
+    while( (pg = page_list_remove_head(&d->arch.paging.hap.hvmlist)) )
+    {
+        d->arch.paging.hap.free_pages++;
+        page_list_add_tail(pg, &d->arch.paging.hap.freelist);
+    }

See c/s 0174da5b7 for why loops like this are bad in general. However, if you use the shadow pool, this should be able to disappear.

I'll switch pools as you suggested.

Quoted 31 lines
Quoted 18 lines
xen/arch/x86/hvm/deprivileged.c new file +18 -0
+}
+
+/* Create a copy of the data at the specified virtual address.
+ * When writing to the source, it will walk the page table hierarchy, creating
+ * new levels as needed.
+ *
+ * If we find a leaf entry in a page table (one which holds the
+ * mfn of a 4KB, 2MB, etc. page frame) which has already been
+ * mapped in, then we bail as we have a collision and this likely
+ * means a bug or the memory configuration has been changed.
+ *
+ * Pages have PAGE_USER, PAGE_GLOBAL (if supported) and PAGE_PRESENT set by
+ * default. The extra l1_flags are used for extra control e.g. PAGE_RW.
+ * The PAGE_RW flag will be enabled for all page structure entries
+ * above the leaf page if that leaf page has PAGE_RW set. This is needed to
+ * permit the writes on the leaf pages. See the Intel manual 3A section 4.6.
+ *
+ * TODO: We proceed down to L1 4KB pages and then map these in. We should

xen/arch/x86/hvm/deprivileged.c line 120

Quoted 10 lines
xen/arch/x86/hvm/deprivileged.c new file +10 -0
+ * stop the recursion on L3/L2 for a 1GB or 2MB page which would mean faster
+ * page access. When we stop would depend on size (e.g. use 2MB pages for a
+ * few MBs)
+ */
+int hvm_deprivileged_copy_pages(struct domain *d,
+                            l4_pgentry_t *l4t_base,
+                            unsigned long int src_start,
+                            unsigned long int dst_start,
+                            unsigned long int size,
+                            unsigned int l1_flags)

<large snip>

Quoted 4 lines

Does map_pages_to_xen() not do everything you need here? It certainly should be fine for the .text section, and will keep the idle and monitor tables up to date for you.

As it updates the idle tables I haven't used it. From my understanding: those idle tables are also used by the PV guests when the guest is created as the idle table is copied from FIRST_XEN_SLOT up to the end of the table. In config.h, the region where I'm mapping in my new mode has been allocated for PV guest-defined usage. I can edit init_guest_l4_table so that it doesn't copy this last slot across. I don't know if this would have further repercussions.

What would you suggest? Thanks!

Quoted 4 lines

Either way, it would be useful to start early on with a description of what the new memory layout is expected to be, and which bits are global, which are per pcpu and which are per vcpu.

Ok, I'll add this to the comments. Briefly:

The .text mappings are global for all HVM vcpus.
The data mappings need to be per vcpu as each vcpu depriv mode has its own local data and configuration. The stack mappings need to be per vcpu for the same reason.

These are mapped into 0xffffff8000000000 which is currently unused for HVM guests.

I'll revise the global page bits as, after further consideration (and our discussion clarifying them), they are no longer needed.

Quoted 15 lines

xen/arch/x86/mm/hap/hap.c line 44

Quoted 12 lines
xen/arch/x86/mm/hap/hap.c +2 -1
index 593cba7..abc5113 100644
@@ -40,7 +40,8 @@
  #include <asm/domain.h>
  #include <xen/numa.h>
  #include <asm/hvm/nestedhvm.h>
-
+#include <xen/hvm/deprivileged.h>
+#include <asm/hvm/vmx/vmx.h>

This looks like a spurious addition.

apologies.

Quoted 166 lines
Quoted 153 lines
xen/arch/x86/mm/hap/hap.c +7 -0
  #include "private.h"
 
  /* Override macros from asm/page.h to make them work with mfn_t */
@@ -401,6 +402,9 @@ static void hap_install_xen_entries_in_l4(struct vcpu *v, mfn_t l4mfn)
             &idle_pg_table[ROOT_PAGETABLE_FIRST_XEN_SLOT],
             ROOT_PAGETABLE_XEN_SLOTS * sizeof(l4_pgentry_t));
 
+    /* Initialise the HVM deprivileged mode feature */
+    hvm_deprivileged_init(d, l4e);
+
      /* Install the per-domain mappings for this domain */
      l4e[l4_table_offset(PERDOMAIN_VIRT_START)] =
          l4e_from_pfn(mfn_x(page_to_mfn(d->arch.perdomain_l3_pg)),
@@ -439,6 +443,10 @@ static void hap_destroy_monitor_table(struct vcpu* v, mfn_t mmfn)
 
      /* Put the memory back in the pool */
      hap_free(d, mmfn);
+
+    /* Destroy the HVM tables */
+    ASSERT(paging_locked_by_me(d));
+    hvm_deprivileged_destroy(d);
  }
 
  /************************************************/
xen/arch/x86/xen.lds.S +19 -0
index 6553cff..0bfe0cf 100644
@@ -50,6 +50,25 @@ SECTIONS
         _etext = .;             /* End of text section */
    } :text = 0x9090
 
+  /* HVM deprivileged mode segments
+   * Used to map the ring3 static data and .text
+   */
+
+  . = ALIGN(PAGE_SIZE);
+  .hvm_deprivileged_text : {
+      __hvm_deprivileged_text_start = . ;
+      *(.hvm_deprivileged_enhancement.text)
+      __hvm_deprivileged_text_end = . ;
+  } : text
+
+  . = ALIGN(PAGE_SIZE);
+  .hvm_deprivileged_data : {
+      __hvm_deprivileged_data_start = . ;
+      *(.hvm_deprivileged_enhancement.data)
+      __hvm_deprivileged_data_end = . ;
+  } : text
+
+  . = ALIGN(PAGE_SIZE);
    .rodata : {
         /* Bug frames table */
         . = ALIGN(4);
xen/include/asm-x86/config.h +9 -1
index 3e9be83..302399d 100644
@@ -186,7 +186,7 @@ extern unsigned char boot_edid_info[128];
   *  0xffff880000000000 - 0xffffff7fffffffff [119.5TB,           PML4:272-510]
   *    HVM/idle: continuation of 1:1 mapping
   *  0xffffff8000000000 - 0xffffffffffffffff [512GB, 2^39 bytes  PML4:511]
- *    HVM/idle: unused
+ *    HVM: HVM deprivileged mode
   *
   * Compatibility guest area layout:
   *  0x0000000000000000 - 0x00000000f57fffff [3928MB,            PML4:0]
@@ -280,6 +280,14 @@ extern unsigned char boot_edid_info[128];
  #endif
  #define DIRECTMAP_VIRT_END      (DIRECTMAP_VIRT_START + DIRECTMAP_SIZE)
 
+/* Slot 511: HVM deprivileged mode
+ * The virtual addresses where the .text, .data and stack should be
+ * placed.
+ */
+#define HVM_DEPRIVILEGED_TEXT_ADDR  (PML4_ADDR(511))
+#define HVM_DEPRIVILEGED_DATA_ADDR  (PML4_ADDR(511) + 0xa000000)
+#define HVM_DEPRIVILEGED_STACK_ADDR (PML4_ADDR(511) + 0xc000000)
+
  #ifndef __ASSEMBLY__
 
  /* This is not a fixed value, just a lower limit. */
xen/include/xen/hvm/deprivileged.h new file +65 -0
new file mode 100644
index 0000000..6cc803e
@@ -0,0 +1,94 @@
+#ifndef __X86_HVM_DEPRIVILEGED
+#define __X86_HVM_DEPRIVILEGED
+
+/* This is also included in the HVM deprivileged mode .S file */
+#ifndef __ASSEMBLY__
+
+#include <asm/page.h>
+#include <xen/lib.h>
+#include <xen/mm.h>
+#include <xen/domain_page.h>
+#include <xen/config.h>
+#include <xen/types.h>
+#include <xen/sched.h>
+#include <asm/paging.h>
+#include <asm/hap.h>
+#include <asm/paging.h>
+#include <asm-x86/page.h>
+#include <public/domctl.h>
+#include <xen/domain_page.h>
+
+/* Initialise the HVM deprivileged mode. This just sets up the general
+ * page mappings for .text and .data. It does not prepare each HVM vcpu's data
+ * or stack which needs to be done separately using
+ * hvm_deprivileged_prepare_vcpu.
+ */
+void hvm_deprivileged_init(struct domain *d, l4_pgentry_t *l4e);
+
+/* Free up the data used by the HVM deprivileged enhancements.
+ * This frees general page mappings. It does not destroy the per-vcpu
+ * data so hvm_deprivileged_destroy_vcpu also needs to be called for each vcpu.
+ * This method should be called after those per-vcpu destruction routines.
+ */
+void hvm_deprivileged_destroy(struct domain *d);
+
+/* Use create a copy of the data at the specified virtual address.
+ * When writing to the source, it will walk the page table hierarchy, creating
+ * new levels as needed, and then copy the data across.
+ */
+int hvm_deprivileged_copy_pages(struct domain *d,
+                                l4_pgentry_t *l4e_base,
+                                unsigned long int src_start,
+                                unsigned long int dst_start,
+                                unsigned long int size,
+                                unsigned int l1_flags);
+
+int hvm_deprivileged_copy_l3(struct domain *d,
+                             l3_pgentry_t *l1t_base,
+                             unsigned long int src_start,
+                             unsigned long int dst_start,
+                             unsigned long int size,
+                             unsigned int l1_flags);
+
+int hvm_deprivileged_copy_l2(struct domain *d,
+                             l2_pgentry_t *l1t_base,
+                             unsigned long int src_start,
+                             unsigned long int dst_start,
+                             unsigned long int size,
+                             unsigned int l1_flags);
+
+/* The left case of the copy. Will allocate the pages and actually copy the
+ * data.
+ */
+int hvm_deprivileged_copy_l1(struct domain *d,
+                             l1_pgentry_t *l1t_base,
+                             unsigned long int src_start,

xen/include/xen/hvm/deprivileged.h line 75

Quoted 10 lines
xen/include/xen/hvm/deprivileged.h new file +10 -0
+                             unsigned long int dst_start,
+                             unsigned long int size,
+                             unsigned int l1_flags);
+
+
+/* The segments where the user mode .text and .data are stored */
+extern unsigned long int __hvm_deprivileged_text_start;
+extern unsigned long int __hvm_deprivileged_text_end;
+extern unsigned long int __hvm_deprivileged_data_start;
+extern unsigned long int __hvm_deprivileged_data_end;

extern unsigned long __hvm_$foo[];

Quoted 2 lines

Will be a more useful type to work with, and harder to accidentally misuse.

thanks, will do!

Quoted 10 lines
Quoted 10 lines
xen/include/xen/hvm/deprivileged.h new file +10 -0
+
+#endif
+
+/* The sizes of the pages */
+#define HVM_1GB_PAGESIZE 0x40000000ul
+#define HVM_2MB_PAGESIZE 0x00200000ul
+#define HVM_4KB_PAGESIZE 0x00001000ul
+
+/* The size in bytes that a single L(1,2,3,4} entry covers.
+ * There are 512 (left shift by 9) entries in each page-structure.
Quoted 9 lines

xen/include/xen/hvm/deprivileged.h line 90

Quoted 5 lines
xen/include/xen/hvm/deprivileged.h new file +5 -0
+ */
+#define HVM_L4_PAGE_RANGE (HVM_1GB_PAGESIZE << 9)
+#define HVM_L3_PAGE_RANGE (HVM_2MB_PAGESIZE << 9)
+#define HVM_L2_PAGE_RANGE (HVM_4KB_PAGESIZE << 9)
+#define HVM_L1_PAGE_RANGE (HVM_4KB_PAGESIZE     )

Values like this should be straight from page.h rather than redefining here. if page.h is missing some, that is the correct place to add them.

got it.

Quoted 7 lines

~Andrew

Quoted 4 lines
xen/include/xen/hvm/deprivileged.h new file +4 -0
+
+#define HVM_ERR_PG_ALLOC -1
+
+#endif
#45 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Andrew Cooper
Quoted 61 lines · Andrew Cooper
Quoted 52 lines · Ben Catterall
Quoted 15 lines · Andrew Cooper
Quoted 14 lines · Ben Catterall

Added trap handlers to catch exceptions such as a page fault, general protection fault, etc. These handlers will crash the domain as such exceptions
would indicate that either there is a bug in deprivileged mode or it has been
compromised by an attacker.

---
   xen/arch/x86/mm/hap/hap.c |  9 +++++++++
   xen/arch/x86/traps.c      | 41
++++++++++++++++++++++++++++++++++++++++-
   2 files changed, 49 insertions(+), 1 deletion(-)
Quoted 16 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, · line 692

Quoted 13 lines
xen/arch/x86/mm/hap/hap.c +4 -0
index abc5113..43bde89 100644
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v,
 unsigned long va,
   {
       struct domain *d = v->domain;
   +    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);

%pv is your friend. Like Linux, we have custom printk formats. In this case, passing 'v' as a parameter to %pv will cause d$Xv$Y to be printed. (The example below predates %pv being introduced).

ok, will do. thanks!

Quoted 5 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 693

Quoted 2 lines
xen/arch/x86/mm/hap/hap.c +1 -0
+        domain_crash_synchronous();

No need for _synchronous() here. _synchronous() should only be used when you can't safely recover. It ends up spinning in a tight loop waiting for the next timer interrupt, is anything up to 30ms away.

I'm not sure if we can safely recover from this. This will only be triggered if there is a bug in depriv mode
or if the mode has been compromised and an attacker has tried to access unavailable memory.
From my understanding (am I missing something?): domain_crash
effectively sets flags to tell the scheduler that
it should be killed the next time the scheduler runs and then returns. In which case, if we don't do a
synchronous crash, this return path would return back into the deprivileged mode, we would not
have mapped in the page (as we shouldn't), and then we get another fault.

Quoted 2 lines

What do you think is the best way forward? Thanks!

Given that there is a use of domain_crash(d) in context below, it is clearly safe to use from here. (Although my general point about hap vs shadow code still applies, meaning that hap_page_fault() is not the correct function to hook like this.)

Quoted 5 lines

domain_crash() sets a flag, but exiting out from a fault handler heading back towards ring3 code should check for pending softirqs. However, because of the way you have hooked return-to-depriv, you might have broken this.

Understood, I'll move the handler, make this change and examine the return path. Thanks!

Quoted 2 lines

~Andrew

#17 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Ben Catterall
Quoted 34 lines · Ben Catterall
Quoted 25 lines · Andrew Cooper
Quoted 24 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to
setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's
registers up to the current stack pointer. This allows us to restore the stack
when we have finished the deprivileged mode operation, meaning we can continue
execution from that point. This is similar to if a context switch had happened.

To exit deprivileged mode, we copy the stack back, replacing the current stack.
We can then continue execution from where we left off, which will unwind the
stack and free up resources. This method means that we do not need to change any other code paths and its invocation will be transparent to callers.
This should allow the feature to be more easily deployed to different parts
of Xen.

Quoted 7 lines
Quoted 3 lines

Note that this copy of the stack is per-vcpu but, it will contain per-pcpu data.
Extra work is needed to properly migrate vcpus between pcpus.

Under what circumstances do you see there being persistent state in the depriv area between calls, given that the calls are synchronous from VM actions?

Quoted 6 lines

I don't know if we can make these synchronous as we need a way to interrupt the vcpu if it's spinning for a long time. Otherwise an attacker could just spin in depriv and cause a DoS. With that in mind, the scheduler may decide to migrate the vcpu whilst it's in depriv mode which would mean this per-pcpu data is held in the stack copy which is then migrated to another pcpu incorrectly.

If the emulator spins for a sufficient time, it is fine to shoot the domain. This is a strict improvement on the current behaviour where a spinning emulator would shoot the host, via a watchdog timeout.

As said elsewhere, this kind of DoS is not a very interesting attack vector. State handling errors which cause Xen to change the wrong thing are far more interesting from a guests point of view.

http://xenbits.xen.org/xsa/advisory-123.html (full host compromise) or
http://xenbits.xen.org/xsa/advisory-108.html (read other guests data) are examples of kinds of interesting issues which could potentially be mitigated with this depriv infrastructure.

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

The switch to and from deprivileged mode is performed using sysret and syscall
respectively.

Quoted 8 lines
Quoted 7 lines

I suspect we need to borrow the SS attribute workaround from Linux to make this function reliably on AMD systems.

https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=61f01dd941ba9e06d2bf05994450ecc3d61b6b8b

Ah! ok, I'll look into this. Thanks!

Just be aware of it. Don't spend your time attempting to retrofit it to Xen. It is more work than it looks.

~Andrew

#12 lore raw

Re: [RFC 2/4] HVM x86 deprivileged mode: Create deprivileged page tables

In reply to Ben Catterall
Quoted 92 lines · Ben Catterall
Quoted 36 lines · Andrew Cooper
Quoted 35 lines · Ben Catterall

The paging structure mappings for the deprivileged mode are added to the monitor page table for HVM guests. The entries are generated by walking the page tables and mapping in new pages. If a higher-level page table
mapping exists, we attempt to traverse all the way down to a leaf page and add
the page there. Access bits are flipped as needed.

The page entries are generated for deprivileged .text, .data and a stack. The
data is copied from sections allocated by the linker. The mappings are setup in
an unused portion of the Xen virtual address space. The pages are mapped in as
user mode accessible, with NX bits set for the data and stack regions and the
code region is set to be executable and read-only.

The needed pages are allocated on the HAP page heap and are deallocated when
those heap pages are deallocated (on domain destruction).

---
  xen/arch/x86/hvm/Makefile          |   1 +
  xen/arch/x86/hvm/deprivileged.c    | 441
+++++++++++++++++++++++++++++++++++++
  xen/arch/x86/mm/hap/hap.c          |  10 +-
  xen/arch/x86/xen.lds.S             |  19 ++
  xen/include/asm-x86/config.h       |  10 +-
  xen/include/xen/hvm/deprivileged.h |  94 ++++++++
  6 files changed, 573 insertions(+), 2 deletions(-)

create mode 100644 xen/arch/x86/hvm/deprivileged.c create mode 100644 xen/include/xen/hvm/deprivileged.h

Quoted 12 lines

xen/arch/x86/hvm/Makefile obj-y += pmtimer.o · line 19

Quoted 9 lines
xen/arch/x86/hvm/Makefile +1 -0
index 794e793..bd83ba3 100644
@@ -16,6 +16,7 @@ obj-y += pmtimer.o
  obj-y += quirks.o
  obj-y += rtc.o
  obj-y += save.o
+obj-y += deprivileged.o

We attempt to keep objects linked in alphabetical order, where possible.

apologies

Quoted 33 lines
Quoted 33 lines
xen/arch/x86/hvm/Makefile +0 -0
  obj-y += stdvga.o
  obj-y += vioapic.o
  obj-y += viridian.o
xen/arch/x86/hvm/deprivileged.c new file +23 -0
new file mode 100644
index 0000000..071d900
@@ -0,0 +1,441 @@
+/*
+ * HVM deprivileged mode to provide support for running operations in
+ * user mode from Xen
+ */
+#include <xen/lib.h>
+#include <xen/mm.h>
+#include <xen/domain_page.h>
+#include <xen/config.h>
+#include <xen/types.h>
+#include <xen/sched.h>
+#include <asm/paging.h>
+#include <xen/compiler.h>
+#include <asm/hap.h>
+#include <asm/paging.h>
+#include <asm-x86/page.h>
+#include <public/domctl.h>
+#include <xen/domain_page.h>
+#include <asm/hvm/vmx/vmx.h>
+#include <xen/hvm/deprivileged.h>
+
+void hvm_deprivileged_init(struct domain *d, l4_pgentry_t *l4e)
+{
+    int ret;
Quoted 9 lines

xen/arch/x86/hvm/deprivileged.c line 27

Quoted 4 lines
xen/arch/x86/hvm/deprivileged.c new file +4 -0
+    void *p;
+    unsigned long int size;
+
+    /* Copy the .text segment for deprivileged code */

Why do you need to copy the deprivileged text section at all? It is read only and completely common. All you should need to do is make userspace mappings to it where it resides in the Xen linked area.

Quoted 6 lines

tbh: At the time, I was unsure if it could open a hole if, when Xen switched over to superpages, and the deprivileged code was not aligned on a 4KB page boundary, then mapping it in might prove problematic. Mainly as we'd map in some of Xen's ring 0 code by accident, which could prove useful to an attacker as they could then call this from userspace.

The monitor tables are only used in the context of HVM guests. PV guests run in their own pagetables (including a subset of the idle tables), but have no chance of accidentally gaining these mappings. (A 64bit PV kernel will get legitimately irate if part of it was replaced with some hvm depriv code.)

Creating user mappings of Xen's .text section does allow a PV guest to execute the code, but only at the current privilege of the PV guest. Therefore, while a bug, doesn't present an increased attack surface. (It might be interesting as a side channel to analyse for RoP purposes, but not as a direct attack surface.)

Quoted 4 lines

Though, now I've thought about it more, I can ensure in the linker that it's aligned properly and I think map_pages_to_xen() will do what I need.

Playing with alignment is easy.

Quoted 32 lines
Quoted 23 lines
Quoted 23 lines
xen/arch/x86/hvm/deprivileged.c new file +4 -0
+           (unsigned long int)&__hvm_deprivileged_text_start;
+
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long

int)&__hvm_deprivileged_text_start,
+ (unsigned long
int)HVM_DEPRIVILEGED_TEXT_ADDR,

xen/arch/x86/hvm/deprivileged.c new file +5 -0
+                              size, 0 /* No write */);
+
+    if( ret )
+    {
+        printk("HVM: Error when initialising depriv .text. Code:

%d", ret);

xen/arch/x86/hvm/deprivileged.c new file +8 -0
+        domain_crash(d);
+        return;
+    }
+
+    /* Copy the .data segment for ring3 code */
+    size = (unsigned long int)&__hvm_deprivileged_data_end -
+           (unsigned long int)&__hvm_deprivileged_data_start;
+
Quoted 9 lines
Quoted 6 lines
xen/arch/x86/hvm/deprivileged.c new file +2 -0
+    ret = hvm_deprivileged_copy_pages(d, l4e,
+                              (unsigned long

int)&__hvm_deprivileged_data_start,
+ (unsigned long
int)HVM_DEPRIVILEGED_DATA_ADDR,
+ size, _PAGE_NX | _PAGE_RW);

What do you expect to end up in a data section like this?

Quoted 4 lines

It's for passing in configuration data at the start when we run the device (reduce the number of system calls needed) and for local data which the emulated devices may need. It can also be used to put the results of any system calls that the deprivileged code may call.

You can achieve the same thing by making the "stacks" larger and segmenting them. The API could pass a pointer to the data in one of the registers, and it just happens to be sheer coincidence that the "stack" and "data area" happen to be adjacent.

Quoted 52 lines
Quoted 40 lines
Quoted 31 lines
xen/arch/x86/hvm/deprivileged.c new file +4 -0
+}
+
+/* Create a copy of the data at the specified virtual address.
+ * When writing to the source, it will walk the page table

hierarchy, creating
+ * new levels as needed.
+ *
+ * If we find a leaf entry in a page table (one which holds the
+ * mfn of a 4KB, 2MB, etc. page frame) which has already been
+ * mapped in, then we bail as we have a collision and this likely
+ * means a bug or the memory configuration has been changed.
+ *
+ * Pages have PAGE_USER, PAGE_GLOBAL (if supported) and PAGE_PRESENT set by
+ * default. The extra l1_flags are used for extra control e.g. PAGE_RW.
+ * The PAGE_RW flag will be enabled for all page structure entries
+ * above the leaf page if that leaf page has PAGE_RW set. This is needed to
+ * permit the writes on the leaf pages. See the Intel manual 3A section 4.6.
+ *
+ * TODO: We proceed down to L1 4KB pages and then map these in. We should
+ * stop the recursion on L3/L2 for a 1GB or 2MB page which would mean faster
+ * page access. When we stop would depend on size (e.g. use 2MB pages for a
+ * few MBs)
+ */

xen/arch/x86/hvm/deprivileged.c line 120

Quoted 6 lines
xen/arch/x86/hvm/deprivileged.c new file +6 -0
+int hvm_deprivileged_copy_pages(struct domain *d,
+                            l4_pgentry_t *l4t_base,
+                            unsigned long int src_start,
+                            unsigned long int dst_start,
+                            unsigned long int size,
+                            unsigned int l1_flags)

<large snip>

Quoted 4 lines

Does map_pages_to_xen() not do everything you need here? It certainly should be fine for the .text section, and will keep the idle and monitor tables up to date for you.

As it updates the idle tables I haven't used it. From my
understanding: those idle tables are also used by the PV guests when the guest is created as the idle table is copied from FIRST_XEN_SLOT up to the end of the table. In config.h, the region where I'm mapping in my new mode has been allocated for PV guest-defined usage. I can edit init_guest_l4_table so that it doesn't copy this last slot across. I don't know if this would have further repercussions.

Quoted 1 line

What would you suggest? Thanks!

The idle pagetables are Xens primary set of pagetables. Globally common stuff such the depriv .text should reside in them.

PV guest pagetables are constructed by memcpy()ing certain slots from the idle pagetables, the vast majority of the virtual address space is owned by the guest, so is untouched by Xen.

In this case, your new depriv extensions live in an area which unused for HVM monitor tables, but would belong to a PV guest kernel.

However, map_pages_to_xen() isn't quite appropriate for making a set of Xen pagetables for mappings to be hooked into monitor tables, so you are going to have to keep the current allocation functions.

~Andrew

#5 lore raw

Re: [RFC 1/4] HVM x86 deprivileged mode: Page allocation helper

In reply to Ben Catterall

Hi,

Quoted 22 lines · Ben Catterall
Quoted 10 lines · Andrew Cooper
Quoted 5 lines · Ben Catterall

This allocation function is used by the deprivileged mode initialisation code to allocate pages for the new page table mappings and page frames on the HAP page heap.

This is fine for your test box, but isn't fine for systems out there without hardware EPT/NPT support. For older systems like that (or in certain specific workloads), shadow paging is used instead.

Quoted 5 lines

This feature is applicable to any HVM domain, which means that it shouldn't depend on HAP or shadow paging.

How much memory is allocated for the depriv area, and what exactly is allocated in total?

So, per-vcpu:
- a user mode stack which, from your comments in [RFC 2/4], can be 2 pages
- local data (may or may not be needed, depends on the device) which will be around
a page or two.

Quoted 7 lines

Text segment: as per your comments in RFC 2/4, this will be changed to be an alias
so no extra memory.

Quoted 4 lines

I expect it isn't very much, and would suggest using d->arch.paging.alloc_page() instead (which is the generic "get me some memory accounted against the domain" helper) which looks as if it should suffice.

Whie I agree that it would be good to account this to the domain, paging->alloc_page() is an internal _paging assistance_ helper. :) This new allocation is nothing to do with mm/paging-assistance, so either it should find its own memory or the hap/shadow pool needs to be made more generic.

Cheers,

Tim.

#6 lore raw

Re: [RFC 1/4] HVM x86 deprivileged mode: Page allocation helper

Quoted 33 lines · Tim Deegan

Hi,

Quoted 22 lines · Ben Catterall
Quoted 10 lines · Andrew Cooper
Quoted 5 lines · Ben Catterall

This allocation function is used by the deprivileged mode initialisation code to allocate pages for the new page table mappings and page frames on the HAP page heap.

This is fine for your test box, but isn't fine for systems out there without hardware EPT/NPT support. For older systems like that (or in certain specific workloads), shadow paging is used instead.

Quoted 5 lines

This feature is applicable to any HVM domain, which means that it shouldn't depend on HAP or shadow paging.

How much memory is allocated for the depriv area, and what exactly is allocated in total?

So, per-vcpu:
- a user mode stack which, from your comments in [RFC 2/4], can be 2 pages
- local data (may or may not be needed, depends on the device) which will be around
a page or two.

Quoted 7 lines

Text segment: as per your comments in RFC 2/4, this will be changed to be an alias
so no extra memory.

Quoted 4 lines

I expect it isn't very much, and would suggest using d->arch.paging.alloc_page() instead (which is the generic "get me some memory accounted against the domain" helper) which looks as if it should suffice.

Quoted 5 lines

Whie I agree that it would be good to account this to the domain, paging->alloc_page() is an internal _paging assistance_ helper. :) This new allocation is nothing to do with mm/paging-assistance, so either it should find its own memory or the hap/shadow pool needs to be made more generic.

...at which point other HVM overheads - VMCx pages, bitmaps &c - could be allocated from it as well.

Cheers,

Tim.

#7 lore raw

Re: [RFC 1/4] HVM x86 deprivileged mode: Page allocation helper

Quoted 33 lines · Tim Deegan
Quoted 32 lines · Tim Deegan

Hi,

Quoted 29 lines · Ben Catterall
Quoted 10 lines · Andrew Cooper
Quoted 5 lines · Ben Catterall

This allocation function is used by the deprivileged mode initialisation code to allocate pages for the new page table mappings and page frames on the HAP page heap.

This is fine for your test box, but isn't fine for systems out there without hardware EPT/NPT support. For older systems like that (or in certain specific workloads), shadow paging is used instead.

Quoted 5 lines

This feature is applicable to any HVM domain, which means that it shouldn't depend on HAP or shadow paging.

How much memory is allocated for the depriv area, and what exactly is allocated in total?

So, per-vcpu:
- a user mode stack which, from your comments in [RFC 2/4], can be 2 pages
- local data (may or may not be needed, depends on the device) which will be around
a page or two.

Text segment: as per your comments in RFC 2/4, this will be changed to be an alias
so no extra memory.

Quoted 4 lines

I expect it isn't very much, and would suggest using d->arch.paging.alloc_page() instead (which is the generic "get me some memory accounted against the domain" helper) which looks as if it should suffice.

Quoted 7 lines
Quoted 5 lines

Whie I agree that it would be good to account this to the domain, paging->alloc_page() is an internal _paging assistance_ helper. :) This new allocation is nothing to do with mm/paging-assistance, so either it should find its own memory or the hap/shadow pool needs to be made more generic.

...at which point other HVM overheads - VMCx pages, bitmaps &c - could be allocated from it as well.

I agree very much in principle, but I believe other threads have
settles on all allocations being global, or per-pcpu, which means no per-domain allocation.

(Not that we shouldn't have a general per-domain pool longterm)

~Andrew

#19 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Ben Catterall

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

If we do have to copy, we could track whether the original stack has been clobbered by an interrupt, and so avoid (at least some of) the copy back afterwards?

One nit in the assembler - if I've followed correctly, this saved IP:

xen/arch/x86/hvm/deprivileged_asm.S line 49

Quoted 2 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +2 -0
+        /* Perform a near call to push rip onto the stack */
+        call   1f

is returned to (with adjustments) here:

xen/arch/x86/hvm/deprivileged_asm.S line 172

Quoted 2 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +2 -0
+        /* Go to user mode return code */
+        jmp    *(%rsi)

It would be good to make this a matched pair of call/ret if we can; the CPU has special branch prediction tracking for function calls that gets confused by a call that's not returned to.

Cheers,

Tim.

#46 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Ben Catterall

Hi,

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 695

Quoted 12 lines
xen/arch/x86/mm/hap/hap.c +8 -0
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v, unsigned long va,
 {
     struct domain *d = v->domain;
 
+    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);
+        domain_crash_synchronous();
+    }
+

This should happen in paging_fault() so it can guard the shadow-pagetable paths too. Once it's there, it'll need a check for is_hvm_vcpu() as well as for user_mode. Maybe have a helper function 'is_hvm_deprivileged_vcpu()' to do both checks, also used in hvm_deprivileged_check_trap() &c.

Quoted 19 lines
xen/arch/x86/mm/hap/hap.c +1 -0
     HAP_ERROR("Intercepted a guest #PF (%u:%u) with HAP enabled.\n",
               d->domain_id, v->vcpu_id);
+
     domain_crash(d);
     return 0;
 }
xen/arch/x86/traps.c +1 -0
index 9f5a6c6..19d465f 100644
@@ -74,6 +74,7 @@
 #include <asm/vpmu.h>
 #include <public/arch-x86/cpuid.h>
 #include <xsm/xsm.h>
+#include <xen/hvm/deprivileged.h>
 
 /*
  * opt_nmi: one of 'ignore', 'dom0', or 'fatal'.

xen/arch/x86/traps.c static void do_guest_trap( · line 507

Quoted 7 lines
xen/arch/x86/traps.c +4 -0
@@ -500,6 +501,11 @@ static void do_guest_trap(
     struct trap_bounce *tb;
     const struct trap_info *ti;
 
+    /* If we take the trap whilst in HVM deprivileged mode
+     * then we should crash the domain.
+     */
+    hvm_deprivileged_check_trap(__FUNCTION__);

I wonder whether it would be better to switch to an IDT with all unacceptable traps stubbed out, rather than have to blacklist them all separately. Probably not - this check is cheap, and maintaining the parallel tables would be a pain.

Or maybe there's some single point upstream of here, in the asm handlers, that would catch all the cases where this check is needed?

In any case, the check needs to return an error code so the caller knows to return without running the rest of the handler (and likewise elsewhere).

Cheers,

Tim.

#8 lore raw

Re: [RFC 1/4] HVM x86 deprivileged mode: Page allocation helper

In reply to Andrew Cooper
Quoted 6 lines · Andrew Cooper
Quoted 5 lines · Tim Deegan
Quoted 5 lines

Whie I agree that it would be good to account this to the domain, paging->alloc_page() is an internal _paging assistance_ helper. :) This new allocation is nothing to do with mm/paging-assistance, so either it should find its own memory or the hap/shadow pool needs to be made more generic.

Quoted 6 lines
Quoted 2 lines

...at which point other HVM overheads - VMCx pages, bitmaps &c - could be allocated from it as well.

I agree very much in principle, but I believe other threads have
settles on all allocations being global, or per-pcpu, which means no per-domain allocation.

Grand so. :)

Tim.

#20 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Tim Deegan
Quoted 12 lines · Tim Deegan

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

Quoted 6 lines

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

That should happen naturally by virtue of the privilege level change involved in taking the interrupt. Conceptually, taking interrupts from depriv mode is no different to taking them in a PV guest.

Some complications which come to mind (none insurmountable):

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

~Andrew

#18 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Andrew Cooper
Quoted 25 lines · Andrew Cooper
Quoted 24 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to
setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's
registers up to the current stack pointer. This allows us to restore the stack
when we have finished the deprivileged mode operation, meaning we can continue
execution from that point. This is similar to if a context switch had happened.

To exit deprivileged mode, we copy the stack back, replacing the current stack.
We can then continue execution from where we left off, which will unwind the
stack and free up resources. This method means that we do not need to change any other code paths and its invocation will be transparent to callers.
This should allow the feature to be more easily deployed to different parts
of Xen.

Quoted 7 lines
Quoted 3 lines

Note that this copy of the stack is per-vcpu but, it will contain per -pcpu data.
Extra work is needed to properly migrate vcpus between pcpus.

Under what circumstances do you see there being persistent state in the depriv area between calls, given that the calls are synchronous from VM actions?

Would we not want to keep (some of) the device model's state in a depriv area? e.g. anything which is purely internal to the DM which is therefore only accessed from depriv-land?

Ian.

#21 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Andrew Cooper
Quoted 17 lines · Andrew Cooper
Quoted 16 lines · Tim Deegan

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

Quoted 5 lines
Quoted 2 lines

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

That should happen naturally by virtue of the privilege level change involved in taking the interrupt.

Right, and this is why we need a third stack - so interrupts don't trash the existing priv state on the 'normal' Xen stack. And so we either need to copy the priv stack out (and maybe copy it back), or tell the CPU to use a different stack.

If we had enough headroom, we could try to be clever and tell the CPU to take interrupts on the priv stack _below_ the existing state. That would avoid the first of your problems below.

Quoted 5 lines

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :(

Tim.

#47 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Tim Deegan
Quoted 6 lines · Tim Deegan

Hi,

Quoted 4 lines
xen/arch/x86/mm/hap/hap.c +0 -0
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v, unsigned long va,
  {
      struct domain *d = v->domain;
 
Quoted 15 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 695

Quoted 8 lines
xen/arch/x86/mm/hap/hap.c +8 -0
+    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);
+        domain_crash_synchronous();
+    }
+

This should happen in paging_fault() so it can guard the shadow-pagetable paths too. Once it's there, it'll need a check for is_hvm_vcpu() as well as for user_mode. Maybe have a helper function 'is_hvm_deprivileged_vcpu()' to do both checks, also used in hvm_deprivileged_check_trap() &c.

Ok, I'll make this change.

Quoted 32 lines
Quoted 19 lines
xen/arch/x86/mm/hap/hap.c +1 -0
      HAP_ERROR("Intercepted a guest #PF (%u:%u) with HAP enabled.\n",
                d->domain_id, v->vcpu_id);
+
      domain_crash(d);
      return 0;
  }
xen/arch/x86/traps.c +1 -0
index 9f5a6c6..19d465f 100644
@@ -74,6 +74,7 @@
  #include <asm/vpmu.h>
  #include <public/arch-x86/cpuid.h>
  #include <xsm/xsm.h>
+#include <xen/hvm/deprivileged.h>
 
  /*
   * opt_nmi: one of 'ignore', 'dom0', or 'fatal'.

xen/arch/x86/traps.c static void do_guest_trap( · line 507

Quoted 7 lines
xen/arch/x86/traps.c +4 -0
@@ -500,6 +501,11 @@ static void do_guest_trap(
      struct trap_bounce *tb;
      const struct trap_info *ti;
 
+    /* If we take the trap whilst in HVM deprivileged mode
+     * then we should crash the domain.
+     */
+    hvm_deprivileged_check_trap(__FUNCTION__);

I wonder whether it would be better to switch to an IDT with all unacceptable traps stubbed out, rather than have to blacklist them all separately. Probably not - this check is cheap, and maintaining the parallel tables would be a pain.

Quoted 3 lines

Or maybe there's some single point upstream of here, in the asm handlers, that would catch all the cases where this check is needed?

Yep, I think this can be done.

Quoted 4 lines

In any case, the check needs to return an error code so the caller knows to return without running the rest of the handler (and likewise elsewhere).

understood.

Quoted 4 lines

Cheers,

Tim.

#40 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Tim Deegan
Quoted 29 lines · Tim Deegan

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

If we do have to copy, we could track whether the original stack has been clobbered by an interrupt, and so avoid (at least some of) the copy back afterwards?

One nit in the assembler - if I've followed correctly, this saved IP:

xen/arch/x86/hvm/deprivileged_asm.S line 49

Quoted 2 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +2 -0
+        /* Perform a near call to push rip onto the stack */
+        call   1f
Quoted 9 lines

is returned to (with adjustments) here:

xen/arch/x86/hvm/deprivileged_asm.S line 172

Quoted 2 lines
xen/arch/x86/hvm/deprivileged_asm.S new file +2 -0
+        /* Go to user mode return code */
+        jmp    *(%rsi)

It would be good to make this a matched pair of call/ret if we can; the CPU has special branch prediction tracking for function calls that gets confused by a call that's not returned to.

sure, will do.

Quoted 4 lines

Cheers,

Tim.

#22 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Tim Deegan
Quoted 21 lines · Tim Deegan
Quoted 20 lines · Andrew Cooper
Quoted 18 lines · Tim Deegan

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

Quoted 7 lines
Quoted 2 lines

That should happen naturally by virtue of the privilege level change involved in taking the interrupt.

Right, and this is why we need a third stack - so interrupts don't trash the existing priv state on the 'normal' Xen stack. And so we either need to copy the priv stack out (and maybe copy it back), or tell the CPU to use a different stack.

The copy is relatively small and paid only on the first and last entries into the mode. I don't know if this is cheaper than the bookwork that would be needed on entering and returning from the mode to switch to these stacks. I'm assuming the sp pointers in the TSS and ISTs would need changing on the first and last entry/exit if we have the extra stack, is that correct? Or, is this a more dramatic change in that everything uses this three stack model rather than just this feature.

I'm not sure how much in Xen would need changing to switch across to using three stacks. Also, would this also need to be done for PV guests? Would that need to be a separate patch series?

What's the overall consensus? Thanks!

Quoted 5 lines

If we had enough headroom, we could try to be clever and tell the CPU to take interrupts on the priv stack _below_ the existing state. That would avoid the first of your problems below.

Quoted 7 lines
Quoted 5 lines

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

Quoted 3 lines

Tim.

#23 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Hi,

Quoted 30 lines · Ben Catterall
Quoted 21 lines · Tim Deegan
Quoted 20 lines · Andrew Cooper
Quoted 18 lines · Tim Deegan

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

Quoted 7 lines
Quoted 2 lines

That should happen naturally by virtue of the privilege level change involved in taking the interrupt.

Right, and this is why we need a third stack - so interrupts don't trash the existing priv state on the 'normal' Xen stack. And so we either need to copy the priv stack out (and maybe copy it back), or tell the CPU to use a different stack.

Quoted 6 lines

The copy is relatively small and paid only on the first and last entries into the mode. I don't know if this is cheaper than the bookwork that would be needed on entering and returning from the mode to switch to these stacks. I'm assuming the sp pointers in the TSS and ISTs would need changing on the first and last entry/exit if we have the extra stack, is that correct?

Yep.

Quoted 2 lines

Or, is this a more dramatic change in that
everything uses this three stack model rather than just this feature.

Well, some other parts would have to change to accomodate this new behaviour - that was what Andrew was talking about.

BTW, I think there need to be three stacks anyway, since the depriv code shouldn't be allowed to write to the priv code's stack frames. Or maybe I've misunderstood how much access the depriv code will have.

Quoted 5 lines

I'm not sure how much in Xen would need changing to switch across to using three stacks. Also, would this also need to be done for PV guests? Would that need to be a separate patch series?

What's the overall consensus? Thanks!

I'm not sure there is one yet -- needs some more discussion of whether the non-copying approach is feasible.

Quoted 4 lines
Quoted 4 lines

If we had enough headroom, we could try to be clever and tell the CPU to take interrupts on the priv stack _below_ the existing state. That would avoid the first of your problems below.

Quoted 8 lines
Quoted 7 lines
Quoted 5 lines

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

IIRC: AMD processors don't context switch TR on vmexit, which makes using IST handlers tricky there. We'd have to do the TR context switch ourselves, and that would be expensive. Andrew, am I remembering that right?

Tim.

#24 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 9 lines · Tim Deegan
Quoted 8 lines
Quoted 7 lines
Quoted 6 lines

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

IIRC: AMD processors don't context switch TR on vmexit,

Correct

Quoted 1 line

which makes using IST handlers tricky there.

(That is one way of putting it)

IST handlers cannot be used by Xen if Xen does not switch the task register before stgi, or IST exceptions (NMI, MCE and double fault) will be taken with guest-supplied stack pointers.

Quoted 1 line

We'd have to do the TR context switch ourselves, and that would be expensive.

It is suspected to be expensive, but I have never actually seen any numbers one way or another.

Quoted 1 line

Andrew, am I remembering that right?

Looks about right.

I have been meaning to investigate this for a while, but never had the time.

Xen opts for disabling interrupt stack tables in the context of AMD HVM vcpus, which interacts catastrophically with debug builds using MEMORY_GUARD. MEMORY_GUARD shoots a page out of the primary stack to detect stack overflows, but without an IST double fault hander, ends in a triple fault rather than a host crash detailing the stack overflow.

KVM unilaterally reloads the host task register on vmexit, and I suspect this is probably the way to go, but have not had time to investigate whether there is any performance impact from doing so. Given how little of a TSS is actually used in long mode, I wouldn't expect an ltr to be as expensive as it might have been in legacy modes.

(CC'ing the AMD SVM maintainers to see if they have any information on this subject)

~Andrew

#25 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 33 lines · Andrew Cooper
Quoted 8 lines · Tim Deegan
Quoted 7 lines
Quoted 6 lines
Quoted 5 lines

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

IIRC: AMD processors don't context switch TR on vmexit,

Correct

Quoted 1 line

which makes using IST handlers tricky there.

(That is one way of putting it)

IST handlers cannot be used by Xen if Xen does not switch the task register before stgi, or IST exceptions (NMI, MCE and double fault) will be taken with guest-supplied stack pointers.

Quoted 1 line

We'd have to do the TR context switch ourselves, and that would be expensive.

It is suspected to be expensive, but I have never actually seen any numbers one way or another.

Quoted 1 line

Andrew, am I remembering that right?

Looks about right.

I have been meaning to investigate this for a while, but never had the time.

Xen opts for disabling interrupt stack tables in the context of AMD HVM vcpus, which interacts catastrophically with debug builds using MEMORY_GUARD. MEMORY_GUARD shoots a page out of the primary stack to detect stack overflows, but without an IST double fault hander, ends in a triple fault rather than a host crash detailing the stack overflow.

Quoted 9 lines

KVM unilaterally reloads the host task register on vmexit, and I suspect this is probably the way to go, but have not had time to investigate whether there is any performance impact from doing so. Given how little of a TSS is actually used in long mode, I wouldn't expect an ltr to be as expensive as it might have been in legacy modes.

(CC'ing the AMD SVM maintainers to see if they have any information on this subject)

I actually didn't even realize that TR is not saved on vmexit ;-/.

Would switching TR only when we know that we need to enter this deprivileged mode help? Assuming that it is less expensive than copying the stack.

-boris

#51 lore raw
In reply to Ben Catterall
Quoted 7 lines
Quoted 1 line
Quoted 1 line · On 06.08.15 at 18:45, <[email protected]> wrote:

Performance testing
-------------------
Performance testing indicates that the overhead for this deprivileged mode is approximately 25%. This overhead is the cost of moving into deprivileged mode and then fully back out of deprivileged mode.

Quoted 6 lines

I performed 100000 writes to a single I/O port on an Intel 2.2GHz Xeon E5-2407 0 processor. This was done from a python script within the HVM guest using time.time() and running Debian Jessie. Each write was trapped to cause a vmexit and the time for each write was calculated. These experiments were repeated. Note that only the host and this HVM guest were running (both Debian Jessie) during the experiments.

I'm not sure I/O port writes (the more without saying to which port) are the best suited item for evaluating the overhead: Ideally you would pick an operation that is comparably fast (I/O port accesses generally aren't if the net effect is that the emulator accesses a physical port). But it certainly serves as a first indication (not too bad, but large enough that I wouldn't be convinced this is a good idea).

Jan

#36 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Andrew Cooper
Quoted 6 lines
Quoted 1 line
Quoted 1 line · On 11.08.15 at 19:19, <[email protected]> wrote:

KVM unilaterally reloads the host task register on vmexit, and I suspect this is probably the way to go, but have not had time to investigate whether there is any performance impact from doing so. Given how little of a TSS is actually used in long mode, I wouldn't expect an ltr to be as expensive as it might have been in legacy modes.

How much of the TSS is being used shouldn't matter at all for LTR execution time, since the instruction doesn't access the TSS itself (and iirc there's also no caching documented for TSS uses).

Jan

#52 lore raw
In reply to Jan Beulich
Quoted 22 lines · Jan Beulich
Quoted 7 lines
Quoted 1 line
Quoted 1 line · On 06.08.15 at 18:45, <[email protected]> wrote:

Performance testing
-------------------
Performance testing indicates that the overhead for this deprivileged mode is approximately 25%. This overhead is the cost of moving into deprivileged mode and then fully back out of deprivileged mode.

Quoted 6 lines

I performed 100000 writes to a single I/O port on an Intel 2.2GHz Xeon E5-2407 0 processor. This was done from a python script within the HVM guest using time.time() and running Debian Jessie. Each write was trapped to cause a vmexit and the time for each write was calculated. These experiments were repeated. Note that only the host and this HVM guest were running (both Debian Jessie) during the experiments.

I'm not sure I/O port writes (the more without saying to which port) are the best suited item for evaluating the overhead: Ideally you would pick an operation that is comparably fast (I/O port accesses generally aren't if the net effect is that the emulator accesses a physical port). But it certainly serves as a first indication (not too bad, but large enough that I wouldn't be convinced this is a good idea).

Quoted 2 lines

Jan

Thanks for this Jan: I overlooked this.

Retested with the port (0x1000) i/o emulation operation replaced with a nop to get the pure overhead. With the operation takes 5.2e-6s and without takes 1.7e-6s. So the difference is 3.5e-6. That's about 308% overhead on a nop. So, I'm guessing that whether this is used or not will depend on the overhead and frequency of the operation it will be handling.

Thanks,
Ben

#37 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Tim Deegan
Quoted 45 lines · Tim Deegan

Hi,

Quoted 30 lines · Ben Catterall
Quoted 21 lines · Tim Deegan
Quoted 20 lines · Andrew Cooper
Quoted 18 lines · Tim Deegan

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

Quoted 7 lines
Quoted 2 lines

That should happen naturally by virtue of the privilege level change involved in taking the interrupt.

Right, and this is why we need a third stack - so interrupts don't trash the existing priv state on the 'normal' Xen stack. And so we either need to copy the priv stack out (and maybe copy it back), or tell the CPU to use a different stack.

Quoted 6 lines

The copy is relatively small and paid only on the first and last entries into the mode. I don't know if this is cheaper than the bookwork that would be needed on entering and returning from the mode to switch to these stacks. I'm assuming the sp pointers in the TSS and ISTs would need changing on the first and last entry/exit if we have the extra stack, is that correct?

Yep.

Quoted 2 lines

Or, is this a more dramatic change in that
everything uses this three stack model rather than just this feature.

Quoted 6 lines

Well, some other parts would have to change to accomodate this new behaviour - that was what Andrew was talking about.

BTW, I think there need to be three stacks anyway, since the depriv code shouldn't be allowed to write to the priv code's stack frames. Or maybe I've misunderstood how much access the depriv code will have.

So, just to clarify:

We have a separate deprivileged stack allocated which the deprivileged code uses. This is mapped in user mode.

We have the privileged stack which Xen runs on. To prevent this being clobbered when we are in our mode and take an interrupt, we copy this out to a buffer. This buffer is the saved privileged stack state.

So, we sort of have three stacks already, just the privileged stack is copied out to a buffer, rather than switching pointers to another interrupt stack.

Hopefully that clarifies?

Quoted 20 lines
Quoted 6 lines

I'm not sure how much in Xen would need changing to switch across to using three stacks. Also, would this also need to be done for PV guests? Would that need to be a separate patch series?

What's the overall consensus? Thanks!

I'm not sure there is one yet -- needs some more discussion of whether the non-copying approach is feasible.

Quoted 10 lines
Quoted 10 lines

If we had enough headroom, we could try to be clever and tell the CPU to take interrupts on the priv stack _below_ the existing state. That would avoid the first of your problems below.

Quoted 5 lines

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Quoted 8 lines
Quoted 2 lines
Quoted 1 line

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

IIRC: AMD processors don't context switch TR on vmexit, which makes using IST handlers tricky there. We'd have to do the TR context switch ourselves, and that would be expensive. Andrew, am I remembering that right?

Thanks!

Quoted 2 lines

Tim.

#38 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 13 lines · Ben Catterall
Quoted 3 lines · Tim Deegan

BTW, I think there need to be three stacks anyway, since the depriv code shouldn't be allowed to write to the priv code's stack frames. Or maybe I've misunderstood how much access the depriv code will have.

So, just to clarify:

We have a separate deprivileged stack allocated which the deprivileged code uses. This is mapped in user mode.

We have the privileged stack which Xen runs on. To prevent this being clobbered when we are in our mode and take an interrupt, we copy this out to a buffer. This buffer is the saved privileged stack state.

Quoted 5 lines

So, we sort of have three stacks already, just the privileged stack is copied out to a buffer, rather than switching pointers to another interrupt stack.

Hopefully that clarifies?

Yes, thanks -- the buffer is what I was thinking of as a third stack.

Cheers,

Tim.

#26 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Boris Ostrovsky
Quoted 45 lines · Boris Ostrovsky
Quoted 44 lines · Andrew Cooper
Quoted 11 lines · Tim Deegan
Quoted 10 lines
Quoted 8 lines
Quoted 7 lines

* Under this model, PV exception handlers should copy themselves onto
the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if
they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

IIRC: AMD processors don't context switch TR on vmexit,

Correct

Quoted 1 line

which makes using IST handlers tricky there.

(That is one way of putting it)

IST handlers cannot be used by Xen if Xen does not switch the task register before stgi, or IST exceptions (NMI, MCE and double fault) will be taken with guest-supplied stack pointers.

Quoted 2 lines

We'd have to do the TR context switch ourselves, and that would be expensive.

It is suspected to be expensive, but I have never actually seen any numbers one way or another.

Quoted 1 line

Andrew, am I remembering that right?

Looks about right.

I have been meaning to investigate this for a while, but never had the time.

Xen opts for disabling interrupt stack tables in the context of AMD HVM vcpus, which interacts catastrophically with debug builds using MEMORY_GUARD. MEMORY_GUARD shoots a page out of the primary stack to detect stack overflows, but without an IST double fault hander, ends in a triple fault rather than a host crash detailing the stack overflow.

KVM unilaterally reloads the host task register on vmexit, and I suspect this is probably the way to go, but have not had time to investigate whether there is any performance impact from doing so. Given how little of a TSS is actually used in long mode, I wouldn't expect an ltr to be as expensive as it might have been in legacy modes.

Quoted 8 lines
Quoted 3 lines

(CC'ing the AMD SVM maintainers to see if they have any information on this subject)

I actually didn't even realize that TR is not saved on vmexit ;-/.

Would switching TR only when we know that we need to enter this deprivileged mode help?

This is an absolute must. It is not safe to use syscall/sysexit without IST in place for NMIs and MCEs.

Quoted 1 line

Assuming that it is less expensive than copying the stack.

I was referring to the stack overflow issue, and whether it might be sensible to pro-actively which TR.

~Andrew

#27 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 51 lines · Andrew Cooper
Quoted 50 lines · Boris Ostrovsky
Quoted 38 lines · Andrew Cooper
Quoted 11 lines · Tim Deegan
Quoted 10 lines
Quoted 8 lines
Quoted 7 lines

* Under this model, PV exception handlers should copy themselves onto
the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if
they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

IIRC: AMD processors don't context switch TR on vmexit,

Correct

Quoted 1 line

which makes using IST handlers tricky there.

(That is one way of putting it)

IST handlers cannot be used by Xen if Xen does not switch the task register before stgi, or IST exceptions (NMI, MCE and double fault) will be taken with guest-supplied stack pointers.

Quoted 2 lines

We'd have to do the TR context switch ourselves, and that would be expensive.

It is suspected to be expensive, but I have never actually seen any numbers one way or another.

Quoted 1 line

Andrew, am I remembering that right?

Looks about right.

I have been meaning to investigate this for a while, but never had the time.

Xen opts for disabling interrupt stack tables in the context of AMD HVM vcpus, which interacts catastrophically with debug builds using MEMORY_GUARD. MEMORY_GUARD shoots a page out of the primary stack to detect stack overflows, but without an IST double fault hander, ends in a triple fault rather than a host crash detailing the stack overflow.

Quoted 9 lines

KVM unilaterally reloads the host task register on vmexit, and I suspect this is probably the way to go, but have not had time to investigate whether there is any performance impact from doing so. Given how little of a TSS is actually used in long mode, I wouldn't expect an ltr to be as expensive as it might have been in legacy modes.

(CC'ing the AMD SVM maintainers to see if they have any information on this subject)

I actually didn't even realize that TR is not saved on vmexit ;-/.

Quoted 8 lines
Quoted 2 lines

Would switching TR only when we know that we need to enter this deprivileged mode help?

This is an absolute must. It is not safe to use syscall/sysexit without IST in place for NMIs and MCEs.

Quoted 1 line

Assuming that it is less expensive than copying the stack.

I was referring to the stack overflow issue, and whether it might be sensible to pro-actively which TR.

Ahem! s/which/switch/

~Andrew

#28 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 57 lines · Andrew Cooper
Quoted 56 lines · Andrew Cooper
Quoted 45 lines · Boris Ostrovsky
Quoted 44 lines · Andrew Cooper
Quoted 11 lines · Tim Deegan
Quoted 10 lines
Quoted 8 lines
Quoted 7 lines

* Under this model, PV exception handlers should copy themselves onto
the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if
they interrupt guest context.
* AMD Task Register on vmexit. (this old gem)

Gah, this thing. :

Curious (and I can't seem find this in the manuals): What is this thing?

IIRC: AMD processors don't context switch TR on vmexit,

Correct

Quoted 1 line

which makes using IST handlers tricky there.

(That is one way of putting it)

IST handlers cannot be used by Xen if Xen does not switch the task register before stgi, or IST exceptions (NMI, MCE and double fault) will be taken with guest-supplied stack pointers.

Quoted 2 lines

We'd have to do the TR context switch ourselves, and that would be expensive.

It is suspected to be expensive, but I have never actually seen any numbers one way or another.

Quoted 1 line

Andrew, am I remembering that right?

Looks about right.

I have been meaning to investigate this for a while, but never had the time.

Xen opts for disabling interrupt stack tables in the context of AMD HVM vcpus, which interacts catastrophically with debug builds using MEMORY_GUARD. MEMORY_GUARD shoots a page out of the primary stack to detect stack overflows, but without an IST double fault hander, ends in a triple fault rather than a host crash detailing the stack overflow.

KVM unilaterally reloads the host task register on vmexit, and I suspect this is probably the way to go, but have not had time to investigate whether there is any performance impact from doing so. Given how little of a TSS is actually used in long mode, I wouldn't expect an ltr to be as expensive as it might have been in legacy modes.

Quoted 7 lines
Quoted 3 lines

(CC'ing the AMD SVM maintainers to see if they have any information on this subject)

I actually didn't even realize that TR is not saved on vmexit ;-/.

Would switching TR only when we know that we need to enter this deprivileged mode help?

This is an absolute must. It is not safe to use syscall/sysexit without IST in place for NMIs and MCEs.

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

Assuming that it is less expensive than copying the stack.

I was referring to the stack overflow issue, and whether it might be sensible to pro-actively which TR.

Ahem! s/which/switch/

~Andrew

So, have we arrived at a decision for this? Thanks!

Ben

#48 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Ben Catterall
Quoted 10 lines · Ben Catterall
Quoted 7 lines · Tim Deegan

Hi,

Quoted 5 lines
xen/arch/x86/mm/hap/hap.c +0 -0
@@ -685,8 +685,17 @@ static int hap_page_fault(struct vcpu *v,
 unsigned long va,
  {
      struct domain *d = v->domain;
 
Quoted 14 lines
Quoted 9 lines

xen/arch/x86/mm/hap/hap.c static int hap_page_fault(struct vcpu *v, unsigned long va, · line 695

Quoted 8 lines
xen/arch/x86/mm/hap/hap.c +8 -0
+    /* If we get a page fault whilst in HVM security user mode */
+    if( v->user_mode == 1 )
+    {
+        printk("HVM: #PF (%u:%u) whilst in user mode\n",
+                 d->domain_id, v->vcpu_id);
+        domain_crash_synchronous();
+    }
+
Quoted 5 lines

This should happen in paging_fault() so it can guard the shadow-pagetable paths too. Once it's there, it'll need a check for is_hvm_vcpu() as well as for user_mode. Maybe have a helper function 'is_hvm_deprivileged_vcpu()' to do both checks, also used in hvm_deprivileged_check_trap() &c.

I've moved this and now need to add shadow page table support as this currently only supports HAP.

Quoted 34 lines
Quoted 1 line

Ok, I'll make this change.

Quoted 32 lines
Quoted 19 lines
xen/arch/x86/mm/hap/hap.c +1 -0
      HAP_ERROR("Intercepted a guest #PF (%u:%u) with HAP enabled.\n",
                d->domain_id, v->vcpu_id);
+
      domain_crash(d);
      return 0;
  }
xen/arch/x86/traps.c +1 -0
index 9f5a6c6..19d465f 100644
@@ -74,6 +74,7 @@
  #include <asm/vpmu.h>
  #include <public/arch-x86/cpuid.h>
  #include <xsm/xsm.h>
+#include <xen/hvm/deprivileged.h>
 
  /*
   * opt_nmi: one of 'ignore', 'dom0', or 'fatal'.

xen/arch/x86/traps.c static void do_guest_trap( · line 507

Quoted 7 lines
xen/arch/x86/traps.c +4 -0
@@ -500,6 +501,11 @@ static void do_guest_trap(
      struct trap_bounce *tb;
      const struct trap_info *ti;
 
+    /* If we take the trap whilst in HVM deprivileged mode
+     * then we should crash the domain.
+     */
+    hvm_deprivileged_check_trap(__FUNCTION__);

I wonder whether it would be better to switch to an IDT with all unacceptable traps stubbed out, rather than have to blacklist them all separately. Probably not - this check is cheap, and maintaining the parallel tables would be a pain.

Quoted 4 lines
Quoted 3 lines

Or maybe there's some single point upstream of here, in the asm handlers, that would catch all the cases where this check is needed?

Yep, I think this can be done.

Had a deeper look at this. There is a point where all exceptions come in in the asm (handle_exception in entry.S) and we could branch out at this point. It does mean that we'd treat _all_ exceptions that occur in this mode the same way whereas the current way means that we can treat them differently (e.g. get __func__). So, should I make all exceptions go to the same point or keep as is?

Thanks!

Quoted 9 lines
Quoted 4 lines

In any case, the check needs to return an error code so the caller knows to return without running the rest of the handler (and likewise elsewhere).

understood.

Quoted 4 lines

Cheers,

Tim.

#49 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

Quoted 9 lines · Ben Catterall
Quoted 6 lines · Ben Catterall
Quoted 5 lines · Tim Deegan

This should happen in paging_fault() so it can guard the shadow-pagetable paths too. Once it's there, it'll need a check for is_hvm_vcpu() as well as for user_mode. Maybe have a helper function 'is_hvm_deprivileged_vcpu()' to do both checks, also used in hvm_deprivileged_check_trap() &c.

I've moved this and now need to add shadow page table support as this currently only supports HAP.

Thanks. There shouldn't be very much work to do for this -- after all we're not running in the guest's pagetables so the actual shadow PT mechanism won't be needed. Maybe just a common helper function called from the shadow & hap monitor-table builders?

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

I wonder whether it would be better to switch to an IDT with all unacceptable traps stubbed out, rather than have to blacklist them all separately. Probably not - this check is cheap, and maintaining the parallel tables would be a pain.

Or maybe there's some single point upstream of here, in the asm handlers, that would catch all the cases where this check is needed?

Quoted 7 lines
Quoted 1 line

Yep, I think this can be done.

Had a deeper look at this. There is a point where all exceptions come in in the asm (handle_exception in entry.S) and we could branch out at this point. It does mean that we'd treat _all_ exceptions that occur in this mode the same way whereas the current way means that we can treat them differently (e.g. get __func__). So, should I make all exceptions go to the same point or keep as is?

I think trap them all at the same point, unless you plan to have any exceptions that don't just kill the guest. I don't think you do, do you?

This code is really Jan and Andrew's area, though.

Cheers,

Tim.

#29 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Ben Catterall
Quoted 12 lines · Ben Catterall
Quoted 11 lines · Andrew Cooper
Quoted 9 lines · Andrew Cooper
Quoted 2 lines · Boris Ostrovsky

Would switching TR only when we know that we need to enter this deprivileged mode help?

This is an absolute must. It is not safe to use syscall/sysexit without IST in place for NMIs and MCEs.

Quoted 1 line

Assuming that it is less expensive than copying the stack.

I was referring to the stack overflow issue, and whether it might be sensible to pro-actively which TR.

Quoted 6 lines
Quoted 4 lines

Ahem! s/which/switch/

~Andrew

So, have we arrived at a decision for this? Thanks!

Seems to have stalled a bit. OK, I propose that:
- we use TR/IST to make Xen take interrupts/exceptions at a different SP;
- we make that SP be an extension of the main stack, so that things like current() Just Work[tm];
- we set this up and tear it down when we enter/leave depriv mode.
- someone ought to look at the case where IST handlers copy themselves to the main stack, and see if we need to adjust that too.

Any other proposals?

I think we can leave the question of TR switching on VMEXIT as a separate issue.

Cheers,

Tim.

#50 lore raw

Re: [RFC 4/4] HVM x86 deprivileged mode: Trap handlers for deprivileged mode

In reply to Tim Deegan
Quoted 20 lines
Quoted 1 line
Quoted 1 line · On 17.08.15 at 16:58, <[email protected]> wrote:
Quoted 10 lines · Ben Catterall
Quoted 9 lines · Ben Catterall
Quoted 8 lines · Tim Deegan

I wonder whether it would be better to switch to an IDT with all unacceptable traps stubbed out, rather than have to blacklist them all separately. Probably not - this check is cheap, and maintaining the parallel tables would be a pain.

Or maybe there's some single point upstream of here, in the asm handlers, that would catch all the cases where this check is needed?

Quoted 7 lines
Quoted 1 line

Yep, I think this can be done.

Had a deeper look at this. There is a point where all exceptions come in in the asm (handle_exception in entry.S) and we could branch out at this point. It does mean that we'd treat _all_ exceptions that occur in this mode the same way whereas the current way means that we can treat them differently (e.g. get __func__). So, should I make all exceptions go to the same point or keep as is?

Quoted 5 lines

I think trap them all at the same point, unless you plan to have any exceptions that don't just kill the guest. I don't think you do, do you?

This code is really Jan and Andrew's area, though.

And I think that deciding one way or the other here isn't necessary at this point in time. Once there is a clear picture of whether the route being explored here is actually usable, we can decide which one is the better model. For now I'd recommend using whatever is cheaper to implement.

Jan

#30 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Tim Deegan
Quoted 12 lines
Quoted 1 line
Quoted 1 line · On 17.08.15 at 17:07, <[email protected]> wrote:
Quoted 1 line · Ben Catterall

So, have we arrived at a decision for this? Thanks!

Seems to have stalled a bit. OK, I propose that:
- we use TR/IST to make Xen take interrupts/exceptions at a different SP;
- we make that SP be an extension of the main stack, so that things like current() Just Work[tm];
- we set this up and tear it down when we enter/leave depriv mode.
- someone ought to look at the case where IST handlers copy themselves to the main stack, and see if we need to adjust that too.

Quoted 1 line

Any other proposals?

No.

Quoted 2 lines

I think we can leave the question of TR switching on VMEXIT as a separate issue.

Just like for the other one - at this point I think anything that work should be okay. Dealing with quirks can be deferred (but it would be nice if a respective note was added in a prominent place so it doesn't get forgotten once/if these patches leave RFC state).

Jan

#31 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 8 lines · Jan Beulich
Quoted 8 lines
Quoted 1 line
Quoted 1 line · On 17.08.15 at 17:07, <[email protected]> wrote:
Quoted 1 line · Ben Catterall

So, have we arrived at a decision for this? Thanks!

Seems to have stalled a bit. OK, I propose that:
- we use TR/IST to make Xen take interrupts/exceptions at a different SP;
- we make that SP be an extension of the main stack, so that things

    like current() Just Work[tm];

From Xen's cpu stack layout, page 4 is currently unused so I'll put it here. Is this an acceptable?

Quoted 13 lines
Quoted 5 lines

- we set this up and tear it down when we enter/leave depriv mode.
- someone ought to look at the case where IST handlers copy themselves to the main stack, and see if we need to adjust that too.

Any other proposals?

No.

Quoted 2 lines

I think we can leave the question of TR switching on VMEXIT as a separate issue.

Quoted 7 lines

Just like for the other one - at this point I think anything that work should be okay. Dealing with quirks can be deferred (but it would be nice if a respective note was added in a prominent place so it doesn't get forgotten once/if these patches leave RFC state).

Jan

Ok, thanks all!

#32 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 7 lines · Ben Catterall
Quoted 4 lines · Jan Beulich
Quoted 4 lines
Quoted 1 line
Quoted 1 line · On 17.08.15 at 17:07, <[email protected]> wrote:
Quoted 1 line · Ben Catterall

So, have we arrived at a decision for this? Thanks!

Quoted 7 lines
Quoted 5 lines
Quoted 5 lines

Seems to have stalled a bit. OK, I propose that:
- we use TR/IST to make Xen take interrupts/exceptions at a
different SP;
- we make that SP be an extension of the main stack, so that things

    like current() Just Work[tm];

From Xen's cpu stack layout, page 4 is currently unused so I'll put it
here. Is this an acceptable?

Or, would it be better to put it at position 5, and move the optional MEMORY_GUARD page down to position 4?

Quoted 21 lines
Quoted 13 lines
Quoted 5 lines

- we set this up and tear it down when we enter/leave depriv mode.
- someone ought to look at the case where IST handlers copy themselves to the main stack, and see if we need to adjust that too.

Any other proposals?

No.

Quoted 2 lines

I think we can leave the question of TR switching on VMEXIT as a separate issue.

Quoted 7 lines

Just like for the other one - at this point I think anything that work should be okay. Dealing with quirks can be deferred (but it would be nice if a respective note was added in a prominent place so it doesn't get forgotten once/if these patches leave RFC state).

Jan

Ok, thanks all!

#33 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 12 lines
Quoted 1 line
Quoted 1 line · On 18.08.15 at 12:26, <[email protected]> wrote:
Quoted 10 lines · Ben Catterall
Quoted 9 lines · Jan Beulich
Quoted 9 lines
Quoted 1 line
Quoted 1 line · On 17.08.15 at 17:07, <[email protected]> wrote:
Quoted 1 line · Ben Catterall

So, have we arrived at a decision for this? Thanks!

Seems to have stalled a bit. OK, I propose that:
- we use TR/IST to make Xen take interrupts/exceptions at a
different SP;
- we make that SP be an extension of the main stack, so that things

    like current() Just Work[tm];
Quoted 4 lines
Quoted 2 lines

From Xen's cpu stack layout, page 4 is currently unused so I'll put it
here. Is this an acceptable?

Or, would it be better to put it at position 5, and move the optional MEMORY_GUARD page down to position 4?

At this stage either would do. Once (if) the experiment yielded positive results, we can still evaluate the pros and cons of either placement.

Jan

#34 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Tim Deegan
Quoted 9 lines · Tim Deegan
Quoted 8 lines · Ben Catterall
Quoted 7 lines · Andrew Cooper
Quoted 6 lines · Andrew Cooper
Quoted 2 lines · Boris Ostrovsky

Would switching TR only when we know that we need to enter this deprivileged mode help?

This is an absolute must. It is not safe to use syscall/sysexit without IST in place for NMIs and MCEs.

Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
Quoted 3 lines
Quoted 1 line

Assuming that it is less expensive than copying the stack.

I was referring to the stack overflow issue, and whether it might be sensible to pro-actively which TR.

Ahem! s/which/switch/

~Andrew

So, have we arrived at a decision for this? Thanks!

Apologies for the delay - I am currently at the Xen Developer Summit.

Quoted 2 lines

Seems to have stalled a bit. OK, I propose that:
- we use TR/IST to make Xen take interrupts/exceptions at a different SP;

Xen re-enables interrupts in most interrupt handlers, which means that they must not have an IST set. If an IST was set, a second interrupt would clobber the frame of the first.

However, just adjusting tss->rsp0 and syscall top-of-stack to the current rsp when entering depriv mode should be sufficient, and will avoid needing to copy the stack.

Quoted 5 lines

- we make that SP be an extension of the main stack, so that things

    like current() Just Work[tm];

- we set this up and tear it down when we enter/leave depriv mode.
- someone ought to look at the case where IST handlers copy themselves to the main stack, and see if we need to adjust that too.

They will need adjusting, but just disabling the copy entirely should be ok.

Quoted 5 lines

Any other proposals?

I think we can leave the question of TR switching on VMEXIT as a separate issue.

Agreed. It is orthogonal to this problem.

~Andrew

#35 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

Quoted 16 lines · Andrew Cooper
Quoted 13 lines · Tim Deegan
Quoted 12 lines · Ben Catterall
Quoted 11 lines · Andrew Cooper
Quoted 10 lines · Andrew Cooper
Quoted 2 lines · Boris Ostrovsky

Would switching TR only when we know that we need to enter this deprivileged mode help?

This is an absolute must. It is not safe to use syscall/sysexit without
IST in place for NMIs and MCEs.

Quoted 1 line

Assuming that it is less expensive than copying the stack.

I was referring to the stack overflow issue, and whether it might be sensible to pro-actively which TR.

Quoted 8 lines
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

Ahem! s/which/switch/

~Andrew

So, have we arrived at a decision for this? Thanks!

Apologies for the delay - I am currently at the Xen Developer Summit.

No worries! Hope you're enjoying the summit. :)

Quoted 11 lines
Quoted 3 lines

Seems to have stalled a bit. OK, I propose that:
- we use TR/IST to make Xen take interrupts/exceptions at a
different SP;

Xen re-enables interrupts in most interrupt handlers, which means that they must not have an IST set. If an IST was set, a second interrupt would clobber the frame of the first.

However, just adjusting tss->rsp0 and syscall top-of-stack to the current rsp when entering depriv mode should be sufficient, and will avoid needing to copy the stack.

Got it, thanks!

Quoted 9 lines
Quoted 6 lines

- we make that SP be an extension of the main stack, so that things

    like current() Just Work[tm];

- we set this up and tear it down when we enter/leave depriv mode.
- someone ought to look at the case where IST handlers copy themselves to the main stack, and see if we need to adjust that too.

They will need adjusting, but just disabling the copy entirely should be ok.

ok.

Quoted 10 lines
Quoted 6 lines

Any other proposals?

I think we can leave the question of TR switching on VMEXIT as a separate issue.

Agreed. It is orthogonal to this problem.

~Andrew

#39 lore raw

Re: [RFC 3/4] HVM x86 deprivileged mode: Code for switching into/out of deprivileged mode

In reply to Andrew Cooper
Quoted 24 lines · Andrew Cooper
Quoted 12 lines · Tim Deegan

Hi,

Quoted 5 lines · Ben Catterall

The process to switch into and out of deprivileged mode can be likened to setjmp/longjmp.

To enter deprivileged mode, we take a copy of the stack from the guest's registers up to the current stack pointer.

This copy is pretty unfortunate, but I can see that avoiding it will be a bit complex. Could we do something with more stacks? AFAICS there have to be three stacks anyway:

Quoted 6 lines

- one to hold the depriv execution context;
- one to hold the privileged execution context; and
- one to take interrupts on.

So maybe we could do some fiddling to make Xen take interrupts on a different stack while we're depriv'd?

That should happen naturally by virtue of the privilege level change involved in taking the interrupt. Conceptually, taking interrupts from depriv mode is no different to taking them in a PV guest.

Quoted 6 lines

Some complications which come to mind (none insurmountable):

* Under this model, PV exception handlers should copy themselves onto the privileged execution stack.
* Currently, the IST handlers copy themselves onto the primary stack if they interrupt guest context.

From what I understand from entry.S's assembly:
handle_ist_exception is used for machine_check and nmi ISTs and these perform this copy. The double fault handler does not do this copy.
- we take the IST on a different stack page
- the handler copies the guest's registers from its current page to
the bottom of the privileged stack so access routines for this still
work as usual
- Moves its rsp to just after this structure in the privileged stack
- Calls do_nmi
- does a ret_from_intr with the stack ptr on the privileged stack

Now, I _think_ it's sufficient to perform this copy and then just keep the rsp on the IST stack page (rather than moving it across as is currently done) so that we don't clobber the privileged stack.

Then, on the return path, move our rsp back to the privileged stack, just after the guest registers so that ret_from_intr can use the copied (and possibly modified) guest's registers.

Does that sound reasonable?

Thanks in advance!

Quoted 4 lines

* AMD Task Register on vmexit. (this old gem)

~Andrew