Skip to contentSkip to conversation

HVM x86 deprivileged mode summary

RFC PATCH In review Ben Catterall 2 participants 9 messages Sep 11, 2015 – Sep 23, 2015

lore
Share & tools
lore
#0 lore raw

v3 cover HVM x86 deprivileged mode summary

Hi all,

I have now finished my internship at Citrix and am posting this final version of my RFC series. I would like to express my thanks to all of those who have taken the time to review, comment and discuss this series, as well as to my colleagues who have provided excellent guidance and help. I have learned a great deal and have greatly enjoyed working with all of you. Thank you.

Hopefully the series will be beneficial. I believe that it has shown that a deprivileged mode in Xen is a possible and viable option, as long as performance impact vs security is carefully considered on a case-by-case basis. The end of this series contains an example of moving some of the vpic into deprivileged mode which has allowed me to test and verify that the feature works. There are enhancements and some clean up which is needed but, after that, the feature could be deployed to HVM devices currently found in Xen such as the VPIC.

Patches one to four are (hopefully) now fairly stable. Patch 5 is the new system call and deprivileged dispatch mode which is new to this series. Patch 6 is also new and is a demonstration of using this for the vpic and hass mainly been used to test and exercise this feature.

As this patch series is in RFC, there are some debug printks which should be removed when/if it leaves RFC but, they are useful in fixing the known issue so I have left them in until that can be resolved.

There are some efficiency savings that can be made and an instance of a general issue (detailed later) which will need to be addressed.

Many thanks once again,
Ben

TODOs
-----
There is a set of TODOs in this patch series, some issues in the later patches which need addressing and some other considerations which I've summarised here.

Patch 1:
- Consider hvm_deprivileged_map_* and an efficiency saving by mapping in larger pages. See the TODO at the top of the L4 version of this method.

Patch 2:
- We have a much more heavyweight version of the deprivileged mode context switch after testing for AMD SVM found that this was necessary. However, the FPU is currently also saved and this may not be necessary. Consideration is needed to work out if we can cut this down even more.

Patch 4:
- The watchdog timer is hooked currently to kill deprivileged mode operations that run for too long and is hardcoded to be at least one watchdog tick and at most two. This may want to be refined.

Patch 5:
- Alias data for deprivileged mode. There is a large comment at the top of deprivileged_syscall.c which outlines considerations.
- Check if we need to map_domain_page the pages when we do the copy in hvm_deprivileged_copy_data{to/from}
- Check for unsigned integer wrapping on addition in hvm_deprivileged_copy_data_{to/from}
- Move hvm_deprivileged_syscall into the syscall macro. It's a stub and unless extra code is needed there it can be folded into the macro.
- Check maintainers' thoughts on the deprivileged mode function checks in hvm_deprivileged_user_mode. See the TODO comment.

Patches 5 & 6:
- Fix/work around the GCC switch statement issue.

KNOWN ISSUES
------------
- Page fault for vpic_ioport_write due to GCC switch statements placing the jump table in .rodata which is in the privileged mode area.

This has been traced to the first of the switch statements in the function. Though other switches in that function may also be affected. Compiled using GCC 4.9.2-10.

You can get the offset into this function by doing:
(RIP - (depriv_vpic_ioport_write - __hvm_deprivileged_text_start))

It appears to be a built-in default of GCC to put switch jump tables in .rodata or .text and there does not appear to be a way to change this (except to patch the compiler, though hopefully there _is_ another option I just haven't been able to find...). Note that GCC will not necessarily allocate jump tables for each switch statment, it appears to depends on a number of factors such as the optimiser, the number of cases, the type of the case, compiler version etc.

Thus, when we relocate a deprivileged method containing code using a switch statement which GCC has created a jump table for, this leads to a page fault. This is because we have not mapped in the rodata section as we should not (depriv should not have access to it).

A workaround would be to patch the generated assembly so that this table is moved into hvm_deprivileged.rodata. This can be done by adding, .section .hvm_deprivileged.rodata, around the generated table. We can then relocate this.

Note that GCC is using RIP-relative addressing for this, so the offset of depriv .rodata to the depriv .text segment will need to be the same when it is mapped in.

#1 lore raw

RFC PATCH v3 1/6 HVM x86 deprivileged mode: Create deprivileged page tables

The paging structure mappings for the deprivileged mode are added to the monitor page table for HVM guests for HAP and shadow table paging. The entries are generated by walking the page tables and mapping in new pages. Access bits are flipped as needed.

The page entries are generated for deprivileged .text, .data and a stack. The .text section is only allocated once at HVM domain initialisation and then we alias it from then onwards. The data section 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 paging heap and are deallocated when those heap pages are deallocated (on domain destruction).

Changes since v1
----------------
* .text section is now aliased when needed
* Reduced user stack size to two pages
* Changed allocator used for pages
* Changed types to using __hvm_$foo[] for linker variables
* Moved some #define's to page.h
* Small bug fix: Testing global bit on L3 not relevant

Changes since v2:
-----------------
* Bug fix: Pass return value back through page table generation code
* Coding style: Added space before if, for, etc.

---
 xen/arch/x86/hvm/Makefile          |   1 +
 xen/arch/x86/hvm/deprivileged.c    | 538 +++++++++++++++++++++++++++++++++++++
 xen/arch/x86/mm/hap/hap.c          |   8 +
 xen/arch/x86/mm/shadow/multi.c     |   8 +
 xen/arch/x86/xen.lds.S             |  19 ++
 xen/include/asm-x86/config.h       |  29 +-
 xen/include/asm-x86/x86_64/page.h  |  15 ++
 xen/include/xen/hvm/deprivileged.h |  95 +++++++
 xen/include/xen/sched.h            |   4 +
 9 files changed, 710 insertions(+), 7 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..df5ebb8 100644
@@ -2,6 +2,7 @@ subdir-y += svm
 subdir-y += vmx
 
 obj-y += asid.o
+obj-y += deprivileged.o
 obj-y += emulate.o
 obj-y += event.o
 obj-y += hpet.o
xen/arch/x86/hvm/deprivileged.c new file +538 -0

538 lines not on this page · raw message

xen/arch/x86/mm/hap/hap.c +8 -0
index e9c0080..4048929 100644
@@ -42,6 +42,7 @@
 #include <asm/hvm/nestedhvm.h>
 
 #include "private.h"
+#include <xen/hvm/deprivileged.h>
 
 /* Override macros from asm/page.h to make them work with mfn_t */
 #undef mfn_to_page
@@ -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/mm/shadow/multi.c +8 -0
index 22081a1..deed4fd 100644
@@ -38,6 +38,7 @@
 #include <asm/mtrr.h>
 #include <asm/guest_pt.h>
 #include <public/sched.h>
+#include <xen/hvm/deprivileged.h>
 #include "private.h"
 #include "types.h"
 
@@ -1429,6 +1430,13 @@ void sh_install_xen_entries_in_l4(struct domain *d, mfn_t gl4mfn, mfn_t sl4mfn)
            &idle_pg_table[ROOT_PAGETABLE_FIRST_XEN_SLOT],
            slots * sizeof(l4_pgentry_t));
 
+    /*
+     * Initialise the HVM deprivileged mode feature.
+     * The shadow_l4e_t is a typedef for l4_pgentry_t as are all of the
+     * paging structure so this method will work for the shadow table as well.
+     */
+    hvm_deprivileged_init(d, (l4_pgentry_t *)sl4e);
+
     /* Install the per-domain mappings for this domain */
     sl4e[shadow_l4_table_offset(PERDOMAIN_VIRT_START)] =
         shadow_l4e_from_mfn(page_to_mfn(d->arch.perdomain_l3_pg),
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 +22 -7
index 3e9be83..b5f4e14 100644
@@ -183,10 +183,12 @@ extern unsigned char boot_edid_info[128];
 #endif
  *  0xffff880000000000 - 0xffffffffffffffff [120TB,             PML4:272-511]
  *    PV: Guest-defined use.
- *  0xffff880000000000 - 0xffffff7fffffffff [119.5TB,           PML4:272-510]
+ *  0xffff880000000000 - 0xffffff0000000000 [119TB,             PML4:272-509]
  *    HVM/idle: continuation of 1:1 mapping
+ *  0xffffff0000000000 - 0xfffff7ffffffffff [512GB, 2^39 bytes  PML4:510]
+ *    HVM: HVM deprivileged mode .text segment
  *  0xffffff8000000000 - 0xffffffffffffffff [512GB, 2^39 bytes  PML4:511]
- *    HVM/idle: unused
+ *    HVM: HVM deprivileged mode data and stack segments
  *
  * Compatibility guest area layout:
  *  0x0000000000000000 - 0x00000000f57fffff [3928MB,            PML4:0]
@@ -201,7 +203,6 @@ extern unsigned char boot_edid_info[128];
  *    Reserved for future use.
  */
 
-
 #define ROOT_PAGETABLE_FIRST_XEN_SLOT 256
 #define ROOT_PAGETABLE_LAST_XEN_SLOT  271
 #define ROOT_PAGETABLE_XEN_SLOTS \
@@ -270,16 +271,30 @@ extern unsigned char boot_edid_info[128];
 #define FRAMETABLE_VIRT_START   (FRAMETABLE_VIRT_END - FRAMETABLE_SIZE)
 
 #ifndef CONFIG_BIGMEM
-/* Slot 262-271/510: A direct 1:1 mapping of all of physical memory. */
+/* Slot 262-271/509: A direct 1:1 mapping of all of physical memory. */
 #define DIRECTMAP_VIRT_START    (PML4_ADDR(262))
-#define DIRECTMAP_SIZE          (PML4_ENTRY_BYTES * (511 - 262))
+#define DIRECTMAP_SIZE          (PML4_ENTRY_BYTES * (510 - 262))
 #else
-/* Slot 265-271/510: A direct 1:1 mapping of all of physical memory. */
+/* Slot 265-271/509: A direct 1:1 mapping of all of physical memory. */
 #define DIRECTMAP_VIRT_START    (PML4_ADDR(265))
-#define DIRECTMAP_SIZE          (PML4_ENTRY_BYTES * (511 - 265))
+#define DIRECTMAP_SIZE          (PML4_ENTRY_BYTES * (510 - 265))
 #endif
 #define DIRECTMAP_VIRT_END      (DIRECTMAP_VIRT_START + DIRECTMAP_SIZE)
 
+/*
+ * Slots 510-511: HVM deprivileged mode
+ * The virtual addresses where the .text, .data and stack should be
+ * placed.
+ * We put the .text section in 510 by itself so that, we can easily create an
+ * alias of it. This is because we use the same mfn for a page entry when
+ * aliasign it and so, if we put the data and text in with the .text at PML4
+ * level then, they would conflict with the other address spaces which is not
+ * correct.
+ */
+#define HVM_DEPRIVILEGED_TEXT_ADDR  (PML4_ADDR(510))
+#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/asm-x86/x86_64/page.h +15 -0
index 19ab4d0..8ecb877 100644
@@ -22,6 +22,21 @@
 #define __PAGE_OFFSET           DIRECTMAP_VIRT_START
 #define __XEN_VIRT_START        XEN_VIRT_START
 
+/* The sizes of the pages */
+#define PAGESIZE_1GB (1ul << L3_PAGETABLE_SHIFT)
+#define PAGESIZE_2MB (1ul << L2_PAGETABLE_SHIFT)
+#define PAGESIZE_4KB (1ul << L1_PAGETABLE_SHIFT)
+
+/*
+ * 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 L4_PAGE_RANGE (PAGESIZE_1GB << 9)
+#define L3_PAGE_RANGE (PAGESIZE_2MB << 9)
+#define L2_PAGE_RANGE (PAGESIZE_4KB << 9)
+#define L1_PAGE_RANGE (PAGESIZE_4KB     )
+
+
 /* These are architectural limits. Current CPUs support only 40-bit phys. */
 #define PADDR_BITS              52
 #define VADDR_BITS              48
xen/include/xen/hvm/deprivileged.h new file +95 -0

95 lines not on this page · raw message

xen/include/xen/sched.h +4 -0
index 73d3bc8..66f4f5e 100644
@@ -462,6 +462,10 @@ struct domain
     /* vNUMA topology accesses are protected by rwlock. */
     rwlock_t vnuma_rwlock;
     struct vnuma_info *vnuma;
+
+    /* HVM deprivileged mode data */
+    int hvm_depriv_valid_l4e_code;
+    l4_pgentry_t hvm_depriv_l4e_code;
 };
 
 struct domain_setup_info
Signature · 1 line
2.1.4
#2 lore raw

RFC PATCH v3 2/6 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.

Xen is non-preemptive and taking an interrupt/exception, SYSCALL, SYSENTER, NMI or any IST will currently clobber the Xen privileged stack. We need this stack to be preserved so that after executing deprivileged mode, we can return to our previous privileged execution point. This allows us to unwind the stack, cleaning up memory allocations.

To enter deprivileged mode, we move the interrupt/exception rsp, SYSENTER rsp and SYSCALL rsp to point to lower down Xen's privileged stack to prevent them from clobbering it. The IST NMI and DF handlers used to copy themselves onto the privileged stack. This is no longer the case, they now leave themselves on their predefined stacks.

This means that we can continue execution from that point. This is similar behaviour to a context switch.

To exit deprivileged mode, we restore the original interrupt/exception rsp, SYSENTER rsp and SYSCALL rsp. 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.

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

Changed since v1
----------------
* Added support for AMD SVM
* Moved to the new stack approach
* IST handlers no longer copy themselves
* Updated context switching code to perform a full context-switch. This means that depriv mode will execute with host register states not (partial) guest register state. This allows for crashing the domain (later patch) whilst in depriv mode, alleviates potential security vulnerabilities and is necessaryto work around the AMD TR issue.
* Moved processor-specific code to processor-specific files.
* Changed call/jmp pair in deprivileged_asm.S to call/ret pair to not confuse processor branch predictors.

Changed since v2:
-----------------
* Coding style: Add space after if, for, etc.

---
 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 | 167 ++++++++++++++++++++++++++++++++++++
 xen/arch/x86/hvm/svm/svm.c          | 130 +++++++++++++++++++++++++++-
 xen/arch/x86/hvm/vmx/vmx.c          | 118 +++++++++++++++++++++++++
 xen/arch/x86/mm/hap/hap.c           |   2 +-
 xen/arch/x86/x86_64/asm-offsets.c   |   5 ++
 xen/arch/x86/x86_64/entry.S         |  38 ++++++--
 xen/arch/x86/x86_64/traps.c         |  13 ++-
 xen/include/asm-x86/current.h       |   2 +
 xen/include/asm-x86/hvm/svm/svm.h   |  13 +++
 xen/include/asm-x86/hvm/vcpu.h      |  15 ++++
 xen/include/asm-x86/hvm/vmx/vmx.h   |   2 +
 xen/include/asm-x86/processor.h     |   2 +
 xen/include/asm-x86/system.h        |   3 +
 xen/include/xen/hvm/deprivileged.h  |  45 ++++++++++
 xen/include/xen/sched.h             |  18 +++-
 18 files changed, 674 insertions(+), 15 deletions(-)
 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 df5ebb8..e16960a 100644
@@ -3,6 +3,7 @@ subdir-y += vmx
 
 obj-y += asid.o
 obj-y += deprivileged.o
+obj-y += deprivileged_asm.o
 obj-y += emulate.o
 obj-y += event.o
 obj-y += hpet.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 +167 -0

167 lines not on this page · raw message

xen/arch/x86/hvm/svm/svm.c +129 -1

166 lines not on this page · raw message

xen/arch/x86/hvm/vmx/vmx.c +118 -0

154 lines not on this page · raw message

xen/arch/x86/mm/hap/hap.c +1 -1
index 4048929..5633e82 100644
@@ -40,7 +40,7 @@
 #include <asm/domain.h>
 #include <xen/numa.h>
 #include <asm/hvm/nestedhvm.h>
-
+#include <asm/hvm/vmx/vmx.h>
 #include "private.h"
 #include <xen/hvm/deprivileged.h>
 
xen/arch/x86/x86_64/asm-offsets.c +5 -0
index 447c650..7af824a 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_depriv_rsp, struct vcpu, arch.hvm_vcpu.depriv_rsp);
+    OFFSET(VCPU_depriv_user_mode, struct vcpu, arch.hvm_vcpu.depriv_user_mode);
+    OFFSET(VCPU_depriv_destroy, struct vcpu, arch.hvm_vcpu.depriv_destroy);
+    BLANK();
+
     OFFSET(DOMAIN_is_32bit_pv, struct domain, arch.is_32bit_pv);
     BLANK();
 
xen/arch/x86/x86_64/entry.S +29 -9
index 74677a2..9590065 100644
@@ -102,6 +102,18 @@ restore_all_xen:
         RESTORE_ALL adj=8
         iretq
 
+
+/* Returning from user mode */
+ENTRY(handle_hvm_user_mode)
+
+        call hvm_deprivileged_handle_user_mode
+
+        /* fallthrough */
+hvm_depriv_mode:
+
+        /* Go back into user mode */
+        jmp   restore_all_guest
+
 /*
  * When entering SYSCALL from kernel mode:
  *  %rax                            = hypercall vector
@@ -128,6 +140,11 @@ ENTRY(lstar_enter)
         pushq $0
         SAVE_VOLATILE TRAP_syscall
         GET_CURRENT(%rbx)
+
+        /* Were we in Xen's ring 3?  */
+        cmpq  $1, VCPU_depriv_user_mode(%rbx)
+        je    handle_hvm_user_mode
+
         testb $TF_kernel_mode,VCPU_thread_flags(%rbx)
         jz    switch_to_kernel
 
@@ -487,6 +504,10 @@ ENTRY(common_interrupt)
 /* No special register assumptions. */
 ENTRY(ret_from_intr)
         GET_CURRENT(%rbx)
+
+        /* If we are in Xen's user mode */
+        cmpq  $1,VCPU_depriv_user_mode(%rbx)
+        je    hvm_depriv_mode
         testb $3,UREGS_cs(%rsp)
         jz    restore_all_xen
         movq  VCPU_domain(%rbx),%rax
@@ -509,6 +530,10 @@ handle_exception_saved:
         GET_CURRENT(%rbx)
         PERFC_INCR(exceptions, %rax, %rbx)
         callq *(%rdx,%rax,8)
+
+        /* If we are in Xen's user mode */
+        cmpq  $1, VCPU_depriv_user_mode(%rbx)
+        je    hvm_depriv_mode
         testb $3,UREGS_cs(%rsp)
         jz    restore_all_xen
         leaq  VCPU_trap_bounce(%rbx),%rdx
@@ -636,15 +661,7 @@ ENTRY(nmi)
         movl  $TRAP_nmi,4(%rsp)
 handle_ist_exception:
         SAVE_ALL CLAC
-        testb $3,UREGS_cs(%rsp)
-        jz    1f
-        /* Interrupted guest context. Copy the context to stack bottom. */
-        GET_CPUINFO_FIELD(guest_cpu_user_regs,%rdi)
-        movq  %rsp,%rsi
-        movl  $UREGS_kernel_sizeof/8,%ecx
-        movq  %rdi,%rsp
-        rep   movsq
-1:      movq  %rsp,%rdi
+        movq  %rsp,%rdi
         movzbl UREGS_entry_vector(%rsp),%eax
         leaq  exception_table(%rip),%rdx
         callq *(%rdx,%rax,8)
@@ -664,6 +681,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/arch/x86/x86_64/traps.c +10 -3
index 0846a19..c7e6077 100644
@@ -24,6 +24,7 @@
 #include <asm/hvm/hvm.h>
 #include <asm/hvm/support.h>
 #include <public/callback.h>
+#include <asm/hvm/svm/svm.h>
 
 
 static void print_xen_info(void)
@@ -337,7 +338,7 @@ unsigned long do_iret(void)
     return 0;
 }
 
-static unsigned int write_stub_trampoline(
+unsigned int write_stub_trampoline(
     unsigned char *stub, unsigned long stub_va,
     unsigned long stack_bottom, unsigned long target_va)
 {
@@ -368,8 +369,6 @@ static unsigned int write_stub_trampoline(
 }
 
 DEFINE_PER_CPU(struct stubs, stubs);
-void lstar_enter(void);
-void cstar_enter(void);
 
 void __devinit subarch_percpu_traps_init(void)
 {
@@ -385,6 +384,14 @@ void __devinit subarch_percpu_traps_init(void)
 
     /* Trampoline for SYSCALL entry from 64-bit mode. */
     wrmsrl(MSR_LSTAR, stub_va);
+
+    /*
+     * HVM deprivileged mode on AMD. The writes for MSR_{L}STAR
+     * are not trapped so we need to keep a copy of the host's msrs
+     */
+    svm_depriv_write_msr_star((unsigned long)((FLAT_RING3_CS32<<16) | __HYPERVISOR_CS) << 32);
+    svm_depriv_write_msr_lstar(stub_va);
+
     offset = write_stub_trampoline(stub_page + (stub_va & ~PAGE_MASK),
                                    stub_va, stack_bottom,
                                    (unsigned long)lstar_enter);
xen/include/asm-x86/current.h +2 -0
index f011d2d..c1dae3a 100644
@@ -23,6 +23,8 @@
  * 2 - MCE IST stack
  * 1 - NMI IST stack
  * 0 - Double Fault IST stack
+ *
+ * NOTE: This layout changes slightly in HVM deprivileged mode.
  */
 
 /*
xen/include/asm-x86/hvm/svm/svm.h +13 -0
index d60ec23..45dd125 100644
@@ -110,4 +110,17 @@ extern void svm_host_osvw_init(void);
 #define _NPT_PFEC_in_gpt       33
 #define NPT_PFEC_in_gpt        (1UL<<_NPT_PFEC_in_gpt)
 
+/*
+ * HVM deprivileged mode svm cache of host MSR_{L}STARs
+ * The svm mode does not trap guest writes to these so we
+ * need to preserve them.
+ */
+DECLARE_PER_CPU(u64, svm_depriv_msr_lstar);
+DECLARE_PER_CPU(u64, svm_depriv_msr_star);
+
+unsigned long svm_depriv_read_msr_star(void);
+void svm_depriv_write_msr_star(unsigned long star);
+unsigned long svm_depriv_read_msr_lstar(void);
+void svm_depriv_write_msr_lstar(unsigned long lstar);
+
 #endif /* __ASM_X86_HVM_SVM_H__ */
xen/include/asm-x86/hvm/vcpu.h +15 -0
index f553814..f7df9d4 100644
@@ -202,6 +202,21 @@ struct hvm_vcpu {
     void (*fpu_exception_callback)(void *, struct cpu_user_regs *);
     void *fpu_exception_callback_arg;
 
+    /* Context switching for HVM deprivileged mode */
+    void (*depriv_ctxt_switch_to)(struct vcpu *v);
+    void (*depriv_ctxt_switch_from)(struct vcpu *v);
+    void (*depriv_setup_stacks)(unsigned long stack_ptr);
+    void (*depriv_restore_stacks)(void);
+
+    /* HVM deprivileged mode state */
+    struct segment_register depriv_tr;
+    unsigned long depriv_rsp;      /* rsp of our stack to restore our data to */
+    unsigned long depriv_user_mode;   /* Are we in user mode */
+    unsigned long depriv_efer;
+    unsigned long depriv_tss_rsp0;
+    unsigned long depriv_destroy;
+    unsigned long depriv_watchdog_count;
+    
     /* Pending hw/sw interrupt (.vector = -1 means nothing pending). */
     struct hvm_trap     inject_trap;
 
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/asm-x86/processor.h +2 -0
index f507f5e..0fde516 100644
@@ -547,6 +547,8 @@ void sysenter_entry(void);
 void sysenter_eflags_saved(void);
 void compat_hypercall(void);
 void int80_direct_trap(void);
+void lstar_enter(void);
+void cstar_enter(void);
 
 #define STUBS_PER_PAGE (PAGE_SIZE / STUB_BUF_SIZE)
 
xen/include/asm-x86/system.h +3 -0
index 25a6a2a..e092f36 100644
@@ -240,5 +240,8 @@ void init_idt_traps(void);
 void load_system_tables(void);
 void percpu_traps_init(void);
 void subarch_percpu_traps_init(void);
+unsigned int write_stub_trampoline(
+    unsigned char *stub, unsigned long stub_va,
+    unsigned long stack_bottom, unsigned long target_va);
 
 #endif
xen/include/xen/hvm/deprivileged.h +45 -0

65 lines not on this page · raw message

xen/include/xen/sched.h +17 -1
index 66f4f5e..6c05969 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
#3 lore raw

RFC PATCH v3 3/6 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.

On calling a domain_crash() whilst in deprivileged mode, we need to restore the host's context so that we do not have guest-defined registers and values in use after this point due to lazy loading of these values in the SVM and VMX implementations.

Changed since v1
----------------
* Changed to domain_crash(), domain_crash_synchronous was used previously.
* Updated to perform a HVM context switch on crashing a domain
* Updated hvm_deprivileged_check_trap() to return a testable error code and return based on this.

Changed since v2
----------------
* Coding style: Added space after if, for, etc.
* hvm_deprivileged_user_mode() now returns a value to indicate success or failure.

---
 xen/arch/x86/hvm/deprivileged.c    | 70 +++++++++++++++++++++++++++++++++++++-
 xen/arch/x86/traps.c               | 55 ++++++++++++++++++++++++++++++
 xen/include/xen/hvm/deprivileged.h | 25 +++++++++++++-
 3 files changed, 148 insertions(+), 2 deletions(-)
xen/arch/x86/hvm/deprivileged.c +69 -1
index 5574c50..68c40ad 100644
@@ -560,7 +560,7 @@ void hvm_deprivileged_destroy_vcpu(struct vcpu *vcpu)
  * This method is then jumped into to restore execution context after
  * exiting user mode.
  */
-void hvm_deprivileged_user_mode(void)
+int hvm_deprivileged_user_mode(void)
 {
     struct vcpu *vcpu = get_current();
 
@@ -576,6 +576,20 @@ void hvm_deprivileged_user_mode(void)
 
     vcpu->arch.hvm_vcpu.depriv_user_mode = 0;
     vcpu->arch.hvm_vcpu.depriv_rsp = 0;
+
+    /*
+     * If we need to crash the domain at this point. We will return up the call
+     * stack, undoing any allocations and then the event testers in the exit
+     * assembly stubs will test for the SOFTIRQ_TIMER event generated by a
+     * domain_crash and will crash the domain for us.
+     */
+    if ( vcpu->arch.hvm_vcpu.depriv_destroy )
+    {
+        domain_crash(vcpu->domain);
+        return 1;
+    }
+
+    return 0;
 }
 
 /*
@@ -639,3 +653,57 @@ void hvm_deprivileged_finish_user_mode(void)
 
     hvm_deprivileged_finish_user_mode_asm();
 }
+
+/* Check if we are in deprivileged mode */
+int is_hvm_deprivileged_vcpu(void)
+{
+    struct vcpu *v = get_current();
+
+    if ( is_hvm_vcpu(v) && (v->arch.hvm_vcpu.depriv_user_mode) )
+        return 1;
+
+    return 0;
+}
+
+/*
+ * Crash the domain. This should not be called if there are any memory
+ * allocations which will be freed by code following its invocation in the
+ * current execution context (current stack). This is because it causes a
+ * permanent 'context switch' and the current stack will be cloberred so
+ * any allocations made which are not freed by other paths will leak.
+ * This function should only be used after deprivileged mode has been
+ * successfully switched into, otherwise, the normal domain_crash function
+ * should be used.
+ *
+ * The domain which is crashed is that of the current vcpu.
+ *
+ * To crash the domain, we need to return to our privileged stack as we may have
+ * memory allocations which need to be cleaned up. Then, after we have returned
+ * to this stack, we can then crash the domain. We set a flag which we check
+ * when returning.
+ */
+void hvm_deprivileged_crash_domain(const char *reason)
+{
+    struct vcpu *vcpu = get_current();
+
+    vcpu->arch.hvm_vcpu.depriv_destroy = 1;
+
+    printk(XENLOG_ERR "HVM Deprivileged Mode: Crashing domain. Reason: %s\n",
+           reason);
+
+    /*
+     * Restore the processor's state. We need to do the privileged return
+     * path to undo any allocations that got us to this state
+     */
+    hvm_deprivileged_finish_user_mode();
+    /* DOES NOT RETURN */
+}
+
+/* Handle a trap event */
+int hvm_deprivileged_check_trap(const char* func_name)
+{
+    if ( is_hvm_deprivileged_vcpu() )
+        hvm_deprivileged_crash_domain(func_name);
+
+    return 0;
+}
xen/arch/x86/traps.c +55 -0

112 lines not on this page · raw message

xen/include/xen/hvm/deprivileged.h +24 -1
index 5915224..b6e575d 100644
@@ -84,7 +84,7 @@ int hvm_deprivileged_prepare_vcpu(struct vcpu *vcpu);
 void hvm_deprivileged_destroy_vcpu(struct vcpu *vcpu);
 
 /* Called to perform a user mode operation. */
-void hvm_deprivileged_user_mode(void);
+int hvm_deprivileged_user_mode(void);
 
 /* Called when the user mode operation has completed */
 void hvm_deprivileged_finish_user_mode(void);
@@ -106,9 +106,32 @@ void hvm_deprivileged_setup_stacks(unsigned long stack_ptr);
 /* Use to restore the stacks for deprivileged mode */
 void hvm_deprivileged_restore_stacks(void);
 
+/* Check if we are in deprivileged mode */
+int is_hvm_deprivileged_vcpu(void);
+
 /* The ring 3 code */
 void hvm_deprivileged_ring3(void);
 
+/*
+ * Crash the domain. This should not be called if there are any memory
+ * allocations which will be freed by code following its invocation in the
+ * current execution context (current stack). This is because it causes a
+ * permanent 'context switch' and the current stack will be cloberred so
+ * any allocations made which are not freed by other paths will leak.
+ * This function should only be used after deprivileged mode has been
+ * successfully switched into, otherwise, the normal domain_crash function
+ * should be used.
+ *
+ * The domain which is crashed is that of the current vcpu.
+ */
+void hvm_deprivileged_crash_domain(const char *reason);
+
+/*
+ * 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.
+ */
+int hvm_deprivileged_check_trap(const char* func_name);
+
 /* The segments where the user mode .text and .data are stored */
 extern unsigned long __hvm_deprivileged_text_start[];
 extern unsigned long __hvm_deprivileged_text_end[];
Signature · 1 line
2.1.4
#4 lore raw

RFC PATCH v3 4/6 HVM x86 deprivileged mode: Watchdog for DoS prevention

In reply to Ben Catterall

A watchdog timer is used to prevent the deprivileged mode running for too long, aimed at handling a bug or attempted DoS. If the watchdog has occurred more than once whilst we have been in the same deprivileged mode context, then we crash the domain. This can be adjusted for longer running times in future.

Changed since v2:
* Coding style: Added space after if

---
 xen/arch/x86/hvm/deprivileged.c |  4 ++++
 xen/arch/x86/nmi.c              | 17 +++++++++++++++++
 2 files changed, 21 insertions(+)
xen/arch/x86/hvm/deprivileged.c +4 -0
index 68c40ad..0b02065 100644
@@ -8,6 +8,7 @@
 #include <xen/config.h>
 #include <xen/types.h>
 #include <xen/sched.h>
+#include <xen/watchdog.h>
 #include <asm/paging.h>
 #include <xen/compiler.h>
 #include <asm/hap.h>
@@ -17,6 +18,7 @@
 #include <xen/domain_page.h>
 #include <asm/hvm/vmx/vmx.h>
 #include <xen/hvm/deprivileged.h>
+#include <xen/hvm/deprivileged_syscall.h>
 
 void hvm_deprivileged_init(struct domain *d, l4_pgentry_t *l4t_base)
 {
@@ -577,6 +579,8 @@ int hvm_deprivileged_user_mode(void)
     vcpu->arch.hvm_vcpu.depriv_user_mode = 0;
     vcpu->arch.hvm_vcpu.depriv_rsp = 0;
 
+    vcpu->arch.hvm_vcpu.depriv_watchdog_count = 0;
+
     /*
      * If we need to crash the domain at this point. We will return up the call
      * stack, undoing any allocations and then the event testers in the exit
xen/arch/x86/nmi.c +17 -0
index 2ab97a0..e5598a2 100644
@@ -26,6 +26,7 @@
 #include <xen/smp.h>
 #include <xen/keyhandler.h>
 #include <xen/cpu.h>
+#include <xen/hvm/deprivileged.h>
 #include <asm/current.h>
 #include <asm/mc146818rtc.h>
 #include <asm/msr.h>
@@ -463,9 +464,25 @@ int __init watchdog_setup(void)
 /* Returns false if this was not a watchdog NMI, true otherwise */
 bool_t nmi_watchdog_tick(const struct cpu_user_regs *regs)
 {
+    struct vcpu *vcpu = current;
     bool_t watchdog_tick = 1;
     unsigned int sum = this_cpu(nmi_timer_ticks);
 
+    /*
+     * If the domain has been running in deprivileged mode for two watchdog
+     * ticks, then we kill it to prevent a DoS. We use two ticks as a coarse
+     * measure as this ensures that at least a full watchdog tick duration has
+     * occurred. This means that we do not need to track entry time and do
+     * time calculations.
+     */
+    if ( is_hvm_deprivileged_vcpu() )
+    {
+        if ( vcpu->arch.hvm_vcpu.depriv_watchdog_count )
+            hvm_deprivileged_crash_domain("HVM Deprivileged domain: Domain exceeded running time.");
+        else
+            vcpu->arch.hvm_vcpu.depriv_watchdog_count = 1;
+    }
+
     if ( (this_cpu(last_irq_sums) == sum) && watchdog_enabled() )
     {
         /*
Signature · 1 line
2.1.4
#5 lore raw

RFC PATCH v3 5/6 HVM x86 deprivileged mode: Syscall and deprivileged operation dispatcher

In reply to Ben Catterall

We have two operations:
1) dispatching a deprivileged mode operation
2) deprivileged mode executing a system call

For (1):
We have a table of methods which can be dispatched. All deprivileged mode methods which can be dispatched need to be in this array. This aims to prevent dispatching functions which are not designed for deprivileged mode and means that we do not dispatch on an aribitrary pointer. We then dispatch to the function pointer stored in this array. This goes via an assembly stub in deprivileged mode which calls the function and then issues a syscall to return to privileged mode when the operation completes. This allows the deprivileged function to return normally.

For (2):
We again have a table of methods which are the syscall handlers. All system calls which we handle need to be in this table. Deprivileged mode passes an integer to select which operation to call. The system call is wrapped to marshall the paramters as necessary and then jumps to a stub to issue the syscall.

Data transfer for (1):
To pass data to deprivileged mode, we can pass up to five integer or pointer parameters in registers. This is thanks to the 64-bit Linux calling convention which puts these into 64-bit registers. The dispatch code takes these parameters and arranges them so that when the deprivileged mode operation executes, they are in the registers specified by the calling convention. This means that it is transparent to the operation that it was not invoked by a function call.

To pass the data which pointers correspond to, we use the deprivileged data section. We copy this data to the section and change the pointer so that it points into this section. Any extra parameters are also copied into the data section.

To return data from deprivileged mode, the operation can supply a return value which we pass through back to the caller. If extra data is needed, which may be needed to make logical decisions after invocation of the operation, then this is placed at the end of the data section. The caller of the operation can then access this data. We copy back the data which we initially copied in so that the caller sees any changes made by the callee.
NOTE: You need to handle the case where these structures can be updated whilst in deprivileged mode.

It is necessary to clear out the data page between deprivilegeged mode operations to prevent data leakage between operations which _may_ be useful to an attacker.

Data transfer for (2):
We need to transfer data to the syscall handler and then back to the deprivileged mode operation. To pass data, we use the same method as in (1) for the first five parameters. For extra data, this will be placed at the end of the data section and will be fetched by the handler. We also use the same method as in (1) for passing data back to the operation.

The general process to create a deprivilged mode operation is as follows:
- Keep the old method prototype the same so that callers do not need to be modified. This helps to reduce the impact of this feature on the rest of the code base
- Move the old code into a new deprv_F version of the function.
- Marshall and unmarshall arguments as needed in the old function
- Call the depriv version using depriv#n(F, params) function which is a wrapper around hvm_deprivileged_user_mode(F, params) in case we want to change this interface later or need better/extra argument marshalling.
- Use the return code to work out what further processing is needed then return
- Add an entry into the depriv_operation_table and add an operation number

With this done, there are no edits which need to be made to callers. If aliasing of data is added to the feature, then this may not longer be the case.

The process to create a syscall is as follows:
- Create a syscall with a name do_depriv_* using the depriv_syscall_t type
- Write the syscall body
- Return a result to depriv mode
- Add an entry to the depriv_syscall_table and create a syscall number

Syscalls are made using DEPRIV_SYSCALL_CALL(op, ret, params) which takes the operation number, the return variable and the paramters for the system call, executes the system call using the Linux 64-bit calling convention and then sets ret to the return value.

TODO:
-----
- Alias data for deprivileged mode. There is a large comment at the top of deprivileged_syscall.c which outlines considerations.
- Check if we need to map_domain_page the pages when we do the copy in hvm_deprivileged_copy_data{to/from}
- Check for unsigned integer wrapping on addition in hvm_deprivileged_copy_data_{to/from}
- Move hvm_deprivileged_syscall into the syscall macro. It's a stub and unless extra code is needed there it can be folded into the macro.
- Check maintainers' thoughts on the deprivileged mode function checks in hvm_deprivileged_user_mode. See the TODO comment.

We copy the data for ease of implementation and for small enough structures, this is acceptable. For larger structures, or ones which can be updated whilst deprivileged mode uses them, it would be better to alias them. This would require the caller to provide the data on separate pages (so that only the required data is passed in, we don't want deprivileged mode to be able to access any other Xen data). We can then alias these through a page table mapping. It would make sense to preallocate a set of pages in the monitor table to do this, so that, when aliasing, we just need to switch the mfn on the L1 page table, rather than allocating and mapping in a whole new paging hierarchy. Then, we only need to invalidate those L1 page table TLB entries when we exit the mode.

---
 xen/arch/x86/hvm/Makefile                  |   1 +
 xen/arch/x86/hvm/deprivileged.c            |  56 +++++-
 xen/arch/x86/hvm/deprivileged_asm.S        | 170 +++++++++++++-----
 xen/arch/x86/hvm/deprivileged_syscall.c    | 277 +++++++++++++++++++++++++++++
 xen/arch/x86/hvm/svm/svm.c                 |   2 +-
 xen/arch/x86/hvm/vmx/vmx.c                 |   1 -
 xen/arch/x86/x86_64/asm-offsets.c          |   1 +
 xen/arch/x86/x86_64/entry.S                |   8 +-
 xen/include/asm-x86/hvm/vcpu.h             |   5 +-
 xen/include/xen/hvm/deprivileged.h         |  17 +-
 xen/include/xen/hvm/deprivileged_syscall.h | 200 +++++++++++++++++++++
 11 files changed, 686 insertions(+), 52 deletions(-)
 create mode 100644 xen/arch/x86/hvm/deprivileged_syscall.c
 create mode 100644 xen/include/xen/hvm/deprivileged_syscall.h
xen/arch/x86/hvm/Makefile +1 -0
index e16960a..cf93e3e 100644
@@ -4,6 +4,7 @@ subdir-y += vmx
 obj-y += asid.o
 obj-y += deprivileged.o
 obj-y += deprivileged_asm.o
+obj-y += deprivileged_syscall.o
 obj-y += emulate.o
 obj-y += event.o
 obj-y += hpet.o
xen/arch/x86/hvm/deprivileged.c +54 -2

77 lines not on this page · raw message

xen/arch/x86/hvm/deprivileged_asm.S +129 -41

237 lines not on this page · raw message

xen/arch/x86/hvm/deprivileged_syscall.c new file +277 -0

277 lines not on this page · raw message

xen/arch/x86/hvm/svm/svm.c +1 -1
index 3393fb5..4ca6d53 100644
@@ -2670,7 +2670,7 @@ void svm_vmexit_handler(struct cpu_user_regs *regs)
             {
                 if( guest_cpu_user_regs()->eax == 0x1)
                 {
-                    hvm_deprivileged_user_mode();
+//                    hvm_deprivileged_user_mode();
                 }
                 __update_guest_eip(regs, vmcb->exitinfo2 - vmcb->rip);
                 break;
xen/arch/x86/hvm/vmx/vmx.c +0 -1
index 1ec23f9..b93b0b6 100644
@@ -3453,7 +3453,6 @@ void vmx_vmexit_handler(struct cpu_user_regs *regs)
             {
                 if( guest_cpu_user_regs()->eax == 0x1)
                 {
-                    hvm_deprivileged_user_mode();
                 }
                 update_guest_eip(); /* Safe: IN, OUT */
                 break;
xen/arch/x86/x86_64/asm-offsets.c +1 -0
index 7af824a..4e2a96c 100644
@@ -118,6 +118,7 @@ void __dummy__(void)
     OFFSET(VCPU_depriv_rsp, struct vcpu, arch.hvm_vcpu.depriv_rsp);
     OFFSET(VCPU_depriv_user_mode, struct vcpu, arch.hvm_vcpu.depriv_user_mode);
     OFFSET(VCPU_depriv_destroy, struct vcpu, arch.hvm_vcpu.depriv_destroy);
+    OFFSET(VCPU_depriv_return_code, struct vcpu, arch.hvm_vcpu.depriv_return_code);
     BLANK();
 
     OFFSET(DOMAIN_is_32bit_pv, struct domain, arch.is_32bit_pv);
xen/arch/x86/x86_64/entry.S +7 -1
index 9590065..df434f2 100644
@@ -106,6 +106,7 @@ restore_all_xen:
 /* Returning from user mode */
 ENTRY(handle_hvm_user_mode)
 
+        movq %rsp, %rdi
         call hvm_deprivileged_handle_user_mode
 
         /* fallthrough */
@@ -141,7 +142,12 @@ ENTRY(lstar_enter)
         SAVE_VOLATILE TRAP_syscall
         GET_CURRENT(%rbx)
 
-        /* Were we in Xen's ring 3?  */
+        /*
+         * Were we in Xen's ring 3?
+         * From lstar_enter up to saving all registers, we need to preserve rdi,
+         * rsi, rdx, rcx, r8 and r9 so that syscalls into deprivileged mode can
+         * function as expected
+         */
         cmpq  $1, VCPU_depriv_user_mode(%rbx)
         je    handle_hvm_user_mode
 
xen/include/asm-x86/hvm/vcpu.h +4 -1
index f7df9d4..dcdecf1 100644
@@ -216,7 +216,10 @@ struct hvm_vcpu {
     unsigned long depriv_tss_rsp0;
     unsigned long depriv_destroy;
     unsigned long depriv_watchdog_count;
-    
+    unsigned long depriv_return_code;
+    /* Offset into our data page where we can put data for depriv operations */
+    unsigned long depriv_data_offset;
+
     /* Pending hw/sw interrupt (.vector = -1 means nothing pending). */
     struct hvm_trap     inject_trap;
 
xen/include/xen/hvm/deprivileged.h +12 -5
index b6e575d..d7228be 100644
@@ -17,6 +17,7 @@
 #include <asm-x86/page.h>
 #include <public/domctl.h>
 #include <xen/domain_page.h>
+#include <xen/hvm/deprivileged_syscall.h>
 
 /*
  * Initialise the HVM deprivileged mode. This just sets up the general
@@ -83,16 +84,21 @@ 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. */
-int 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
+/* Dispatch a deprivileged user mode operation */
+int hvm_deprivileged_user_mode(unsigned long operation, register_t a,
+                               register_t b, register_t c, register_t d,
+                               register_t e);
+
+/*
+ * Called to move into and then out of user mode. Needed for accessing
  * assembly features.
  */
-void hvm_deprivileged_user_mode_asm(void);
+void hvm_deprivileged_user_mode_asm(depriv_syscall_fn_t f, register_t a,
+                                    register_t b, register_t c, register_t d,
+                                    register_t e);
 
 /* Called on the return path to return to the correct execution point */
 void hvm_deprivileged_finish_user_mode_asm(void);
@@ -151,6 +157,7 @@ extern unsigned long __hvm_deprivileged_data_end[];
 #define HVM_ERR_PG_ALLOC -1
 #define HVM_DEPRIV_ALIAS 1
 #define HVM_DEPRIV_COPY 0
+#define HVM_DISPATCH_ERR -1
 
 /*
  * The user mode stack pointer.
xen/include/xen/hvm/deprivileged_syscall.h new file +200 -0

200 lines not on this page · raw message

Signature · 1 line
2.1.4
#6 lore raw

RFC PATCH v3 6/6 HVM x86 deprivileged mode: Move VPIC to deprivileged mode

In reply to Ben Catterall

First steps of moving the VPIC into deprivileged mode.

For the VPIC, some of its functions are called from both privileged code and deprivileged code. Some of these are also called from non-hvm domains. This means that we cannot just convert the entire function to a depriv only one, but need to handle this case. vpic_get_priority() shows one way of doing this but there may be other ways. The main aim will be to minimise code duplication and logic needed to determine where the call is coming from. This will not be a unique problem so some thought will be needed as to the best way to resolve this in general.

A clean up method handles a deprivileged mode domain crashing whilst holding resources. For example, if we hold a lock or have allocated memory which Xen will not clean up for us when we crash, we need to release these. Otherwise we fail on ASSERT_NOT_IN_ATOMIC in vmx_asm_vmexit_handler due to an unreleased lock and then panic. We could also leak memory if we allocate from a pool which Xen does not clean up for us on crashing the domain.

TODO
----
Patches 5 & 6:
- Fix the GCC switch statement issue which causes a page fault

Patch 6:
- Fix vpic lock release on domain crash.
- Finish moving parts of the VPIC into deprivileged mode

KNOWN ISSUES
------------
- Page fault for vpic_ioport_write due to GCC switch statements placing the jump table in .rodata which is in the privileged mode area.

This has been traced to the first of the switch statements in the function. Though other switches in that function may also be affected. Compiled using GCC 4.9.2-10.

You can get the offset into this function by doing:
(RIP - (depriv_vpic_ioport_write - __hvm_deprivileged_text_start))

It appears to be a built-in default of GCC to put switch jump tables in .rodata or .text and there does not appear to be a way to change this (except to patch the compiler). Note that GCC will not necessarily allocate jump tables for each switch statment, it depends on the optimiser.

Thus, when we relocate a deprivileged method containing code using a switch statement which GCC has created a jump table for, this leads to a page fault. This is because we have not mapped in the rodata section as we should not (depriv should not have access to it).

A workaround would be to patch the generated assembly so that this table is moved into hvm_deprivileged.rodata. This can be done by adding, .section .hvm_deprivileged.rodata, around the generated table. We can then relocate

Note that GCC is using RIP-relative addressing for this, so the offset of depriv .rodata to the depriv .text segment will need to be the same when it is mapped in.

---
 xen/arch/x86/hvm/deprivileged.c         |  49 +++++++++++
 xen/arch/x86/hvm/deprivileged_syscall.c |   4 +-
 xen/arch/x86/hvm/vpic.c                 | 151 ++++++++++++++++++++++++++++----
 xen/arch/x86/traps.c                    |   5 +-
 xen/include/asm-x86/hvm/vcpu.h          |   2 +
 xen/include/xen/hvm/deprivileged.h      |   3 +
 6 files changed, 192 insertions(+), 22 deletions(-)
xen/arch/x86/hvm/deprivileged.c +49 -0
index 5606f9a..9561054 100644
@@ -20,7 +20,14 @@
 #include <xen/hvm/deprivileged.h>
 #include <xen/hvm/deprivileged_syscall.h>
 
+/* TODO: move to a better place than here */
+int depriv_vpic_ioport_write(unsigned long *ret_data_ptr,
+                             struct hvm_hw_vpic *vpic, int32_t addr,
+                             uint32_t val) DEPRIV_TEXT_SEGMENT;
+
+
 static depriv_syscall_t depriv_operation_table[] = {
+    DEPRIV_OPERATION(vpic_ioport_write, 4)
 };
 
 void hvm_deprivileged_init(struct domain *d, l4_pgentry_t *l4t_base)
@@ -641,6 +648,11 @@ int hvm_deprivileged_user_mode(unsigned long operation, register_t a,
      */
     if ( vcpu->arch.hvm_vcpu.depriv_destroy )
     {
+        /*
+         * Track which operation we are currently performing so that we can
+         * clean up if we have to crash the domain whilst doing it.
+         */
+        hvm_deprivileged_clean_up(vcpu, operation);
         domain_crash(vcpu->domain);
         return 1;
     }
@@ -763,3 +775,40 @@ int hvm_deprivileged_check_trap(const char* func_name)
 
     return 0;
 }
+
+/*
+ * Clean up when destroying the domain
+ * When we destroy the domain whilst performing a deprivilged mode operation,
+ * we need to make sure that we do not hold any locks or have any memory which
+ * we have allocated related to the deprivileged mode operation which will
+ * not be cleared up by Xen automatically as part of domain destruction.
+ *
+ * An example is when we crash whilst holding a lock, we need to release this
+ * lock.
+ */
+void hvm_deprivileged_clean_up(struct vcpu *vcpu, unsigned long op)
+{
+    struct hvm_hw_vpic *vpic;
+
+    /* The vpic lock is not released if we crash the domain. This means that the
+     * preempt count is not decremented so we fail on an ASSERT_NOT_IN_ATOMIC in
+     * vmx_asm_vmexit_handler on our way back to the guest. After this, we would
+     * test for a SOFTIRQ to deschedule and then destroy the guest. But, this
+     * fail results in a panic instead. The solution is to release this
+     * lock when we crash the domain and we have determined that we are
+     * performing a vpic  operation.
+     */
+    switch(op)
+    {
+    case DEPRIV_OPERATION_vpic_ioport_write:
+       /* We have cached the current vpic so that we can clean up */
+        vpic = (struct hvm_hw_vpic *)vcpu->arch.hvm_vcpu.depriv_cleanup_data;
+        printk("Cleaning up... %lx\n", (unsigned long)vpic);
+        spin_unlock(&container_of((vpic), struct hvm_domain,
+                                  vpic[!(vpic)->is_master])->irq_lock);
+        break;
+    default:
+        /* No clean up needed for this operation if not covered by the above */
+        break;
+    }
+}
xen/arch/x86/hvm/deprivileged_syscall.c +2 -2
index 34dfee9..c98ff96 100644
@@ -73,11 +73,11 @@
  * Used for handling a syscall from deprivileged mode or dispatching a
  * deprivileged mode operation.
  */
-
+int do_depriv_vpic_get_priority(struct hvm_hw_vpic *vpic, uint8_t mask);
 
 /* This table holds the functions which can be called from deprivileged mode. */
 static depriv_syscall_t depriv_syscall_table[] = {
-
+    DEPRIV_SYSCALL(vpic_get_priority, 2),
 };
 
 /* Handle a syscall from deprivileged mode */
xen/arch/x86/hvm/vpic.c +132 -19

207 lines not on this page · raw message

xen/arch/x86/traps.c +4 -1
index f14a845..1a449a5 100644
@@ -1525,7 +1525,10 @@ void do_page_fault(struct cpu_user_regs *regs)
     perfc_incr(page_faults);
 
     /* If we get a page fault whilst in HVM deprivileged mode */
-    if( hvm_deprivileged_check_trap(__func__) )
+    if (is_hvm_deprivileged_vcpu() )
+        printk("Addr: %lx code: %d, rip: %lx\n", addr, error_code, regs->rip);
+
+    if ( hvm_deprivileged_check_trap(__func__) )
         return;
 
     if ( unlikely(fixup_page_fault(addr, regs) != 0) )
xen/include/asm-x86/hvm/vcpu.h +2 -0
index dcdecf1..482b6ae 100644
@@ -217,6 +217,8 @@ struct hvm_vcpu {
     unsigned long depriv_destroy;
     unsigned long depriv_watchdog_count;
     unsigned long depriv_return_code;
+    /* Pointer to data to help with clean up if we have to crash the domain */
+    void* depriv_cleanup_data;
     /* Offset into our data page where we can put data for depriv operations */
     unsigned long depriv_data_offset;
 
xen/include/xen/hvm/deprivileged.h +3 -0
index d7228be..c640788 100644
@@ -115,6 +115,9 @@ void hvm_deprivileged_restore_stacks(void);
 /* Check if we are in deprivileged mode */
 int is_hvm_deprivileged_vcpu(void);
 
+/* Clean up when destroying the domain */
+void hvm_deprivileged_clean_up(struct vcpu *vcpu, unsigned long op);
+
 /* The ring 3 code */
 void hvm_deprivileged_ring3(void);
 
Signature · 1 line
2.1.4
#7 lore raw
In reply to Ben Catterall

Hi all,

Here are two Python scripts which I have used to collect performance benchmarks for this series. I am putting them here in case they are useful.

Ben

Quoted 107 lines · Ben Catterall

Hi all,

I have now finished my internship at Citrix and am posting this final version of my RFC series. I would like to express my thanks to all of those who have taken the time to review, comment and discuss this series, as well as to my colleagues who have provided excellent guidance and help. I have learned a great deal and have greatly enjoyed working with all of you. Thank you.

Hopefully the series will be beneficial. I believe that it has shown that a deprivileged mode in Xen is a possible and viable option, as long as performance impact vs security is carefully considered on a case-by-case basis. The end of this series contains an example of moving some of the vpic into deprivileged mode which has allowed me to test and verify that the feature works. There are enhancements and some clean up which is needed but, after that, the feature could be deployed to HVM devices currently found in Xen such as the VPIC.

Patches one to four are (hopefully) now fairly stable. Patch 5 is the new system call and deprivileged dispatch mode which is new to this series. Patch 6 is also new and is a demonstration of using this for the vpic and hass mainly been used to test and exercise this feature.

As this patch series is in RFC, there are some debug printks which should be removed when/if it leaves RFC but, they are useful in fixing the known issue so I have left them in until that can be resolved.

There are some efficiency savings that can be made and an instance of a general issue (detailed later) which will need to be addressed.

Many thanks once again,
Ben

TODOs
-----
There is a set of TODOs in this patch series, some issues in the later patches which need addressing and some other considerations which I've summarised here.

Patch 1:
- Consider hvm_deprivileged_map_* and an efficiency saving by mapping in larger pages. See the TODO at the top of the L4 version of this method.

Patch 2:
- We have a much more heavyweight version of the deprivileged mode context switch after testing for AMD SVM found that this was necessary. However, the FPU is currently also saved and this may not be necessary. Consideration is needed to work out if we can cut this down even more.

Patch 4:
- The watchdog timer is hooked currently to kill deprivileged mode operations that run for too long and is hardcoded to be at least one watchdog tick and at most two. This may want to be refined.

Patch 5:
- Alias data for deprivileged mode. There is a large comment at the top of deprivileged_syscall.c which outlines considerations.
- Check if we need to map_domain_page the pages when we do the copy in

    hvm_deprivileged_copy_data{to/from}
  - Check for unsigned integer wrapping on addition in
    hvm_deprivileged_copy_data_{to/from}

- Move hvm_deprivileged_syscall into the syscall macro. It's a stub and unless extra code is needed there it can be folded into the macro.
- Check maintainers' thoughts on the deprivileged mode function checks in hvm_deprivileged_user_mode. See the TODO comment.

Patches 5 & 6:
- Fix/work around the GCC switch statement issue.

KNOWN ISSUES
------------
- Page fault for vpic_ioport_write due to GCC switch statements placing the jump table in .rodata which is in the privileged mode area.

This has been traced to the first of the switch statements in the function. Though other switches in that function may also be affected. Compiled using GCC 4.9.2-10.

You can get the offset into this function by doing:
(RIP - (depriv_vpic_ioport_write - __hvm_deprivileged_text_start))

It appears to be a built-in default of GCC to put switch jump tables in .rodata or .text and there does not appear to be a way to change this (except to patch the compiler, though hopefully there _is_ another option I just haven't been able to find...). Note that GCC will not necessarily allocate jump tables for each switch statment, it appears to depends on a number of factors such as the optimiser, the number of cases, the type of the case, compiler version etc.

Thus, when we relocate a deprivileged method containing code using a switch statement which GCC has created a jump table for, this leads to a page fault. This is because we have not mapped in the rodata section as we should not (depriv should not have access to it).

A workaround would be to patch the generated assembly so that this table is moved into hvm_deprivileged.rodata. This can be done by adding, .section .hvm_deprivileged.rodata, around the generated table. We can then relocate this.

Note that GCC is using RIP-relative addressing for this, so the offset of depriv .rodata to the depriv .text segment will need to be the same when it is mapped in.

Quoted 5 lines

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt

#Use for running rsync
import subprocess

#Use for command line args
import sys, argparse

import array
import pickle
from matplotlib.pyplot import savefig

'''
Plot the data and output to a file
'''
def plot(xList,filename):

    i = 0
    colours = ["red", "blue"]
    labels = ["Enabled", "Disabled"]
    bins = array.array('f')

    #Get max and min
    max = np.amax(xList[0])
    if np.amax(xList[1]) > max:
        max = np.amax(xList[1])

    min = np.amin(xList[0])
    if np.amin(xList[1]) < min:
        min = np.amin(xList[1])

    intervalBins = np.linspace(min, max, num=100)

    for data in xList:
        n, bins, patches = plt.hist(data, intervalBins, facecolor=colours[i],
                                    alpha=0.75, label=labels[i]);

        print(str(n) + " " + str(bins) + " " + str(patches) + "\n")
        i = i + 1

        print("Mean: " + str(np.mean(data)) + " seconds\n")
        print("Std:  " + str(np.std(data,dtype=np.float64)) + " seconds\n")
        print("Max: "  + str(np.amax(data)) + " Min: " + str(np.amin(data)) + "\n")

    plt.legend(loc='upper right')
    plt.ylabel("Frequency")
    plt.xlabel("Time/s")
    plt.title("Graph of Xen deprivileged user performance")
    plt.ticklabel_format(axis='x', style='sci', scilimits=(-2,2))
    fg = plt.gcf()

    fg.savefig(filename)

    return

def main():
#Setup parser
parser = argparse.ArgumentParser(description="Test HVM depriv performance.") parser.add_argument("-p", "--plot", nargs=2, metavar=("[DATA FILE NAME]", "[GRAPH FILE NAME]"),
help="Plot the data and output a graph at file name")

args = parser.parse_args()

#Process args
if args.plot:
print("Plotting...\n")

#Use Pickle to load in the array timeData = pickle.load(open(args.plot[0], "rb"))

#Parse it and plot
plot(timeData, args.plot[1])

print("DONE")

if __name__ == '__main__':

        main()

#!/usr/bin/python3
'''
To make use of this script, you will need to run it as root and have installed the Python portio package.

You need to have patched the portio operation in vmx.c and svm.c which can be found at xen/arch/x86/hvm/{vmx,svm}/{vmx.c,svm.c} as shown below so that it will run the deprivileged mode when we perform a particular port operation. My series has the basic hook in there for patch 2 but this is commented
out/removed in later patches as there was a functional change (you can
no longer just enter the mode, you need to supply an operation to jump to so this will need to be updated to work with that).

This is in vmx_vmexit_handler and svm_vmexit_handler

Here is the svm part of this copied here for completeness:

             uint16_t port = (vmcb->exitinfo1 >> 16) & 0xFFFF;
             int bytes = ((vmcb->exitinfo1 >> 4) & 0x07);

             int dir = (vmcb->exitinfo1 & 1) ? IOREQ_READ : IOREQ_WRITE;
             /* DEBUG: Run only for a specific port */
             if(port == 0x1000)
             {
                 if( guest_cpu_user_regs()->eax == 0x1)
                 {
                     hvm_deprivileged_user_mode();
                 }
                 __update_guest_eip(regs, vmcb->exitinfo2 - vmcb->rip);
                 break;
             }

             if ( handle_pio(port, bytes, dir) )
                 __update_guest_eip(regs, vmcb->exitinfo2 - vmcb->rip);
         }

'''
import array

#Use for command line args
import sys
import pickle
import time

from portio import ioperm, iopl, outb

def prepare_portio(port):
#Get access to all ports (needed on Linux pre 2.6.? kernel) if( iopl(3) != 0 ):
print("ERROR: Elevating access to ports " + str(port) + "\n") return False

#get access to port, only one port, and enable it if( ioperm(port, 1, 1) != 0 ):
print("ERROR: Preparing port " + str(port) + "\n") return False

return True

"""
Clean up after portio operations
"""
def release_portio(port):

if( ioperm(port, 1, 0) != 0 ):
print("ERROR: Releasing port " + str(port) + " \n") return False

if( iopl(0) != 0 ):
print("ERROR: Clearing access to ports " + str(port) + "\n") return False

return True

'''
Needs root to run
'''
def send_data(port, data):
outb(data, port)

def profile(outputTimes, numIterations, port, data):
i = 0
while (i < numIterations):
before = time.time()
send_data(port, data)
after = time.time()

timeDelta = after - before

outputTimes.append( timeDelta)

i = i + 1

def main():

    outputTimesWith = array.array("f")
    outputTimesWithout = array.array("f")
    portWith = 0x1000
    portWithout = 0x1000
    dataWith = 0x1
    dataWithout =0x2
    numIterations = 100000

    prepare_portio(portWith)

    #Profile the system
    #With the deprivileged op
    profile(outputTimesWith, numIterations, portWith, dataWith);
    release_portio(portWith)

    #Without the deprivileged op
    prepare_portio(portWithout)
    profile(outputTimesWithout, numIterations, portWithout, dataWithout);
    release_portio(portWithout)

    data =[outputTimesWith, outputTimesWithout]

    outputFile = open("data", "wb")

    pickle.dump(data, outputFile)

    outputFile.close()
    return

if __name__ == '__main__':

    main()

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

#8 lore raw
In reply to Ben Catterall
Quoted 7 lines · Ben Catterall

Hi all,

I have now finished my internship at Citrix and am posting this final version of my RFC series. I would like to express my thanks to all of those who have taken the time to review, comment and discuss this series, as well as to my colleagues who have provided excellent guidance and help. I have learned a great deal and have greatly enjoyed working with all of you. Thank you.

Thank you for posting them!