3 * vmx.c - The Intel VT-x driver for Dune
5 * This file is derived from Linux KVM VT-x support.
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10 * Avi Kivity <avi@qumranet.com>
11 * Yaniv Kamay <yaniv@qumranet.com>
13 * This modified version is simpler because it avoids the following
14 * features that are not requirements for Dune:
15 * * Real-mode emulation
16 * * Nested VT-x support
17 * * I/O hardware emulation
18 * * Any of the more esoteric X86 features and registers
19 * * KVM-specific functionality
21 * In essence we provide only the minimum functionality needed to run
22 * a process in vmx non-root mode rather than the full hardware emulation
23 * needed to support an entire OS.
25 * This driver is a research prototype and as such has the following
28 * FIXME: Backward compatability is currently a non-goal, and only recent
29 * full-featured (EPT, PCID, VPID, etc.) Intel hardware is supported by this
32 * FIXME: Eventually we should handle concurrent user's of VT-x more
33 * gracefully instead of requiring exclusive access. This would allow
34 * Dune to interoperate with KVM and other HV solutions.
36 * FIXME: We need to support hotplugged physical CPUs.
39 * Adam Belay <abelay@stanford.edu>
43 * Yep, it's confusing. This is in part because the vmcs is used twice, for two different things.
44 * You're left with the feeling that they got part way through and realized they had to have one for
46 * 1) your CPU is going to be capable of running VMs, and you need state for that.
48 * 2) you're about to start a guest, and you need state for that.
50 * So there is get cpu set up to be able to run VMs stuff, and now
51 * let's start a guest stuff. In Akaros, CPUs will always be set up
52 * to run a VM if that is possible. Processes can flip themselves into
53 * a VM and that will require another VMCS.
55 * So: at kernel startup time, the SMP boot stuff calls
56 * k/a/x86/vmm/vmm.c:vmm_init, which calls arch-dependent bits, which
57 * in the case of this file is intel_vmm_init. That does some code
58 * that sets up stuff for ALL sockets, based on the capabilities of
59 * the socket it runs on. If any cpu supports vmx, it assumes they all
60 * do. That's a realistic assumption. So the call_function_all is kind
61 * of stupid, really; it could just see what's on the current cpu and
62 * assume it's on all. HOWEVER: there are systems in the wilde that
63 * can run VMs on some but not all CPUs, due to BIOS mistakes, so we
64 * might as well allow for the chance that wel'll only all VMMCPs on a
65 * subset (not implemented yet however). So: probe all CPUs, get a
66 * count of how many support VMX and, for now, assume they all do
69 * Next, call setup_vmcs_config to configure the GLOBAL vmcs_config struct,
70 * which contains all the naughty bits settings for all the cpus that can run a VM.
71 * Realistically, all VMX-capable cpus in a system will have identical configurations.
72 * So: 0 or more cpus can run VMX; all cpus which can run VMX will have the same configuration.
74 * configure the msr_bitmap. This is the bitmap of MSRs which the
75 * guest can manipulate. Currently, we only allow GS and FS base.
77 * Reserve bit 0 in the vpid bitmap as guests can not use that
79 * Set up the what we call the vmxarea. The vmxarea is per-cpu, not
80 * per-guest. Once set up, it is left alone. The ONLY think we set in
81 * there is the revision area. The VMX is page-sized per cpu and
82 * page-aligned. Note that it can be smaller, but why bother? We know
83 * the max size and alightment, and it's convenient.
85 * Now that it is set up, enable vmx on all cpus. This involves
86 * testing VMXE in cr4, to see if we've been here before (TODO: delete
87 * this test), then testing MSR_IA32_FEATURE_CONTROL to see if we can
88 * do a VM, the setting the VMXE in cr4, calling vmxon (does a vmxon
89 * instruction), and syncing vpid's and ept's. Now the CPU is ready
93 * We divide this into two things: vmm_proc_init and vm_run.
94 * Currently, on Intel, vmm_proc_init does nothing.
96 * vm_run is really complicated. It is called with a coreid, rip, rsp,
97 * cr3, and flags. On intel, it calls vmx_launch. vmx_launch is set
98 * up for a few test cases. If rip is 1, it sets the guest rip to
99 * a function which will deref 0 and should exit with failure 2. If rip is 0,
100 * it calls an infinite loop in the guest.
102 * The sequence of operations:
106 * disable irqs (required or you can't enter the VM)
113 * See if the current cpu has a vcpu. If so, and is the same as the vcpu we want,
114 * vmcs_load(vcpu->vmcs) -- i.e. issue a VMPTRLD.
116 * If it's not the same, see if the vcpu thinks it is on the core. If it is not, call
117 * __vmx_get_cpu_helper on the other cpu, to free it up. Else vmcs_clear the one
118 * attached to this cpu. Then vmcs_load the vmcs for vcpu on this this cpu,
119 * call __vmx_setup_cpu, mark this vcpu as being attached to this cpu, done.
121 * vmx_run_vcpu this one gets messy, mainly because it's a giant wad
122 * of inline assembly with embedded CPP crap. I suspect we'll want to
123 * un-inline it someday, but maybe not. It's called with a vcpu
124 * struct from which it loads guest state, and to which it stores
125 * non-virtualized host state. It issues a vmlaunch or vmresume
126 * instruction depending, and on return, it evaluates if things the
127 * launch/resume had an error in that operation. Note this is NOT the
128 * same as an error while in the virtual machine; this is an error in
129 * startup due to misconfiguration. Depending on whatis returned it's
130 * either a failed vm startup or an exit for lots of many reasons.
134 /* basically: only rename those globals that might conflict
135 * with existing names. Leave all else the same.
136 * this code is more modern than the other code, yet still
137 * well encapsulated, it seems.
145 #include <sys/queue.h>
153 #include <arch/types.h>
160 #include "cpufeature.h"
162 #define currentcpu (&per_cpu_info[core_id()])
164 static unsigned long *msr_bitmap;
166 int x86_ept_pte_fix_ups = 0;
168 struct vmx_capability vmx_capability;
169 struct vmcs_config vmcs_config;
171 static int autoloaded_msrs[] = {
178 void ept_flush(uint64_t eptp)
180 ept_sync_context(eptp);
183 static void vmcs_clear(struct vmcs *vmcs)
185 uint64_t phys_addr = PADDR(vmcs);
188 asm volatile (ASM_VMX_VMCLEAR_RAX "; setna %0"
189 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
192 printk("vmclear fail: %p/%llx\n",
196 static void vmcs_load(struct vmcs *vmcs)
198 uint64_t phys_addr = PADDR(vmcs);
201 asm volatile (ASM_VMX_VMPTRLD_RAX "; setna %0"
202 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
205 printk("vmptrld %p/%llx failed\n",
209 /* Returns the paddr pointer of the current CPU's VMCS region, or -1 if none. */
210 static physaddr_t vmcs_get_current(void)
212 physaddr_t vmcs_paddr;
213 /* RAX contains the addr of the location to store the VMCS pointer. The
214 * compiler doesn't know the ASM will deref that pointer, hence the =m */
215 asm volatile (ASM_VMX_VMPTRST_RAX : "=m"(vmcs_paddr) : "a"(&vmcs_paddr));
219 __always_inline unsigned long vmcs_readl(unsigned long field)
223 asm volatile (ASM_VMX_VMREAD_RDX_RAX
224 : "=a"(value) : "d"(field) : "cc");
228 __always_inline uint16_t vmcs_read16(unsigned long field)
230 return vmcs_readl(field);
233 static __always_inline uint32_t vmcs_read32(unsigned long field)
235 return vmcs_readl(field);
238 static __always_inline uint64_t vmcs_read64(unsigned long field)
240 return vmcs_readl(field);
243 void vmwrite_error(unsigned long field, unsigned long value)
245 printk("vmwrite error: reg %lx value %lx (err %d)\n",
246 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
249 void vmcs_writel(unsigned long field, unsigned long value)
253 asm volatile (ASM_VMX_VMWRITE_RAX_RDX "; setna %0"
254 : "=q"(error) : "a"(value), "d"(field) : "cc");
256 vmwrite_error(field, value);
259 static void vmcs_write16(unsigned long field, uint16_t value)
261 vmcs_writel(field, value);
264 static void vmcs_write32(unsigned long field, uint32_t value)
266 vmcs_writel(field, value);
269 static void vmcs_write64(unsigned long field, uint64_t value)
271 vmcs_writel(field, value);
275 * A note on Things You Can't Make Up.
277 * "George, you can type this shit, but you can't say it" -- Harrison Ford
279 * There are 5 VMCS 32-bit words that control guest permissions. If
280 * you set these correctly, you've got a guest that will behave. If
281 * you get even one bit wrong, you've got a guest that will chew your
282 * leg off. Some bits must be 1, some must be 0, and some can be set
283 * either way. To add to the fun, the docs are sort of a docudrama or,
284 * as the quote goes, "interesting if true."
286 * To determine what bit can be set in what VMCS 32-bit control word,
287 * there are 5 corresponding 64-bit MSRs. And, to make it even more
288 * fun, the standard set of MSRs have errors in them, i.e. report
289 * incorrect values, for legacy reasons, and so you are supposed to
290 * "look around" to another set, which have correct bits in
291 * them. There are four such 'correct' registers, and they have _TRUE_
292 * in the names as you can see below. We test for the value of VMCS
293 * control bits in the _TRUE_ registers if possible. The fifth
294 * register, CPU Secondary Exec Controls, which came later, needs no
297 * For each MSR, the high 32 bits tell you what bits can be "1" by a
298 * "1" in that position; the low 32 bits tell you what bit can be "0"
299 * by a "0" in that position. So, for each of 32 bits in a given VMCS
300 * control word, there is a pair of bits in an MSR that tells you what
301 * values it can take. The two bits, of which there are *four*
302 * combinations, describe the *three* possible operations on a
303 * bit. The two bits, taken together, form an untruth table: There are
304 * three possibilities: The VMCS bit can be set to 0 or 1, or it can
305 * only be 0, or only 1. The fourth combination is not supposed to
308 * So: there is the 1 bit from the upper 32 bits of the msr.
309 * If this bit is set, then the bit can be 1. If clear, it can not be 1.
311 * Then there is the 0 bit, from low 32 bits. If clear, the VMCS bit
312 * can be 0. If 1, the VMCS bit can not be 0.
314 * SO, let's call the 1 bit R1, and the 0 bit R0, we have:
317 * 1 0 -> can be 1, can be 0
318 * 0 1 -> can not be 1, can not be 0. --> JACKPOT! Not seen yet.
319 * 1 1 -> must be one.
321 * It's also pretty hard to know what you can and can't set, and
322 * that's led to inadvertant opening of permissions at times. Because
323 * of this complexity we've decided on the following: the driver must
324 * define EVERY bit, UNIQUELY, for each of the 5 registers, that it wants
325 * set. Further, for any bit that's settable, the driver must specify
326 * a setting; for any bit that's reserved, the driver settings must
327 * match that bit. If there are reserved bits we don't specify, that's
328 * ok; we'll take them as is.
330 * We use a set-means-set, and set-means-clear model, i.e. we use a
331 * 32-bit word to contain the bits we want to be 1, indicated by one;
332 * and another 32-bit word in which a bit we want to be 0 is indicated
333 * by a 1. This allows us to easily create masks of all bits we're
334 * going to set, for example.
336 * We have two 32-bit numbers for each 32-bit VMCS field: bits we want
337 * set and bits we want clear. If you read the MSR for that field,
338 * compute the reserved 0 and 1 settings, and | them together, they
339 * need to result in 0xffffffff. You can see that we can create other
340 * tests for conflicts (i.e. overlap).
342 * At this point, I've tested check_vmx_controls in every way
343 * possible, beause I kept screwing the bitfields up. You'll get a nice
344 * error it won't work at all, which is what we want: a
345 * failure-prone setup, where even errors that might result in correct
346 * values are caught -- "right answer, wrong method, zero credit." If there's
347 * weirdness in the bits, we don't want to run.
350 static bool check_vmxec_controls(struct vmxec const *v, bool have_true_msr,
354 uint32_t vmx_msr_low, vmx_msr_high;
355 uint32_t reserved_0, reserved_1, changeable_bits;
358 rdmsr(v->truemsr, vmx_msr_low, vmx_msr_high);
360 rdmsr(v->msr, vmx_msr_low, vmx_msr_high);
362 if (vmx_msr_low & ~vmx_msr_high)
363 warn("JACKPOT: Conflicting VMX ec ctls for %s, high 0x%08x low 0x%08x",
364 v->name, vmx_msr_high, vmx_msr_low);
366 reserved_0 = (~vmx_msr_low) & (~vmx_msr_high);
367 reserved_1 = vmx_msr_low & vmx_msr_high;
368 changeable_bits = ~(reserved_0 | reserved_1);
371 * this is very much as follows:
372 * accept the things I cannot change,
373 * change the things I can,
374 * know the difference.
377 /* Conflict. Don't try to both set and reset bits. */
378 if (v->set_to_0 & v->set_to_1) {
379 printk("%s: set to 0 (0x%x) and set to 1 (0x%x) overlap: 0x%x\n",
380 v->name, v->set_to_0, v->set_to_1, v->set_to_0 & v->set_to_1);
385 if (((v->set_to_0 | v->set_to_1) & changeable_bits) !=
387 printk("%s: Need to cover 0x%x and have 0x%x,0x%x\n",
388 v->name, changeable_bits, v->set_to_0, v->set_to_1);
392 if ((v->set_to_0 | v->set_to_1 | reserved_0 | reserved_1) !=
394 printk("%s: incomplete coverage: have 0x%x, want 0x%x\n",
395 v->name, v->set_to_0 | v->set_to_1 |
396 reserved_0 | reserved_1, 0xffffffff);
400 /* Don't try to change bits that can't be changed. */
401 if ((v->set_to_0 & (reserved_0 | changeable_bits)) != v->set_to_0) {
402 printk("%s: set to 0 (0x%x) can't be done\n", v->name,
407 if ((v->set_to_1 & (reserved_1 | changeable_bits)) != v->set_to_1) {
408 printk("%s: set to 1 (0x%x) can't be done\n",
409 v->name, v->set_to_1);
413 /* If there's been any error at all, spill our guts and return. */
415 printk("%s: vmx_msr_high 0x%x, vmx_msr_low 0x%x, ",
416 v->name, vmx_msr_high, vmx_msr_low);
417 printk("set_to_1 0x%x,set_to_0 0x%x,reserved_1 0x%x",
418 v->set_to_1, v->set_to_0, reserved_1);
419 printk(" reserved_0 0x%x", reserved_0);
420 printk(" changeable_bits 0x%x\n", changeable_bits);
424 *result = v->set_to_1 | reserved_1;
426 printd("%s: check_vmxec_controls succeeds with result 0x%x\n",
432 * We're trying to make this as readable as possible. Realistically, it will
433 * rarely if ever change, if the past is any guide.
435 static const struct vmxec pbec = {
436 .name = "Pin Based Execution Controls",
437 .msr = MSR_IA32_VMX_PINBASED_CTLS,
438 .truemsr = MSR_IA32_VMX_TRUE_PINBASED_CTLS,
440 .set_to_1 = (PIN_BASED_EXT_INTR_MASK |
441 PIN_BASED_NMI_EXITING |
442 PIN_BASED_VIRTUAL_NMIS),
444 .set_to_0 = (PIN_BASED_VMX_PREEMPTION_TIMER |
445 PIN_BASED_POSTED_INTR),
448 static const struct vmxec cbec = {
449 .name = "CPU Based Execution Controls",
450 .msr = MSR_IA32_VMX_PROCBASED_CTLS,
451 .truemsr = MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
453 .set_to_1 = (CPU_BASED_HLT_EXITING |
454 CPU_BASED_INVLPG_EXITING |
455 CPU_BASED_MWAIT_EXITING |
456 CPU_BASED_RDPMC_EXITING |
457 CPU_BASED_CR8_LOAD_EXITING |
458 CPU_BASED_CR8_STORE_EXITING |
459 CPU_BASED_MOV_DR_EXITING |
460 CPU_BASED_UNCOND_IO_EXITING |
461 CPU_BASED_USE_MSR_BITMAPS |
462 CPU_BASED_MONITOR_EXITING |
463 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS),
465 .set_to_0 = (CPU_BASED_VIRTUAL_INTR_PENDING |
466 CPU_BASED_USE_TSC_OFFSETING |
467 CPU_BASED_RDTSC_EXITING |
468 CPU_BASED_CR3_LOAD_EXITING |
469 CPU_BASED_CR3_STORE_EXITING |
470 CPU_BASED_TPR_SHADOW |
471 CPU_BASED_VIRTUAL_NMI_PENDING |
472 CPU_BASED_MONITOR_TRAP |
473 CPU_BASED_PAUSE_EXITING |
474 CPU_BASED_USE_IO_BITMAPS),
477 static const struct vmxec cb2ec = {
478 .name = "CPU Based 2nd Execution Controls",
479 .msr = MSR_IA32_VMX_PROCBASED_CTLS2,
480 .truemsr = MSR_IA32_VMX_PROCBASED_CTLS2,
482 .set_to_1 = (SECONDARY_EXEC_ENABLE_EPT |
483 SECONDARY_EXEC_WBINVD_EXITING),
485 .set_to_0 = (SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
486 SECONDARY_EXEC_DESCRIPTOR_EXITING |
487 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
488 SECONDARY_EXEC_ENABLE_VPID |
489 SECONDARY_EXEC_UNRESTRICTED_GUEST |
490 SECONDARY_EXEC_APIC_REGISTER_VIRT |
491 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
492 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
493 SECONDARY_EXEC_RDRAND_EXITING |
494 SECONDARY_EXEC_ENABLE_INVPCID |
495 SECONDARY_EXEC_ENABLE_VMFUNC |
496 SECONDARY_EXEC_SHADOW_VMCS |
497 SECONDARY_EXEC_RDSEED_EXITING |
499 /* TODO: re enable this via a "Want" struct
500 member at some point */
501 SECONDARY_EXEC_RDTSCP |
502 SECONDARY_ENABLE_XSAV_RESTORE)
505 static const struct vmxec vmentry = {
506 .name = "VMENTRY controls",
507 .msr = MSR_IA32_VMX_ENTRY_CTLS,
508 .truemsr = MSR_IA32_VMX_TRUE_ENTRY_CTLS,
509 /* exact order from vmx.h; only the first two are enabled. */
511 .set_to_1 = (VM_ENTRY_LOAD_DEBUG_CONTROLS | /* can't set to 0 */
512 VM_ENTRY_IA32E_MODE),
514 .set_to_0 = (VM_ENTRY_SMM |
515 VM_ENTRY_DEACT_DUAL_MONITOR |
516 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
517 VM_ENTRY_LOAD_IA32_PAT |
518 VM_ENTRY_LOAD_IA32_EFER),
521 static const struct vmxec vmexit = {
522 .name = "VMEXIT controls",
523 .msr = MSR_IA32_VMX_EXIT_CTLS,
524 .truemsr = MSR_IA32_VMX_TRUE_EXIT_CTLS,
526 .set_to_1 = (VM_EXIT_SAVE_DEBUG_CONTROLS | /* can't set to 0 */
527 VM_EXIT_HOST_ADDR_SPACE_SIZE), /* 64 bit */
529 .set_to_0 = (VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
530 VM_EXIT_ACK_INTR_ON_EXIT |
531 VM_EXIT_SAVE_IA32_PAT |
532 VM_EXIT_LOAD_IA32_PAT |
533 VM_EXIT_SAVE_IA32_EFER |
534 VM_EXIT_LOAD_IA32_EFER |
535 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER),
538 static void setup_vmcs_config(void *p)
541 struct vmcs_config *vmcs_conf = &vmcs_config;
542 uint32_t vmx_msr_high;
544 bool have_true_msrs = false;
549 vmx_msr = read_msr(MSR_IA32_VMX_BASIC);
550 vmx_msr_high = vmx_msr >> 32;
553 * If bit 55 (VMX_BASIC_HAVE_TRUE_MSRS) is set, then we
554 * can go for the true MSRs. Else, we ask you to get a better CPU.
556 if (vmx_msr & VMX_BASIC_TRUE_CTLS) {
557 have_true_msrs = true;
558 printd("Running with TRUE MSRs\n");
560 printk("Running with non-TRUE MSRs, this is old hardware\n");
564 * Don't worry that one or more of these might fail and leave
565 * the VMCS in some kind of incomplete state. If one of these
566 * fails, the caller is going to discard the VMCS.
567 * It is written this way to ensure we get results of all tests and avoid
570 ok = check_vmxec_controls(&pbec, have_true_msrs,
571 &vmcs_conf->pin_based_exec_ctrl);
572 ok = check_vmxec_controls(&cbec, have_true_msrs,
573 &vmcs_conf->cpu_based_exec_ctrl) && ok;
574 ok = check_vmxec_controls(&cb2ec, have_true_msrs,
575 &vmcs_conf->cpu_based_2nd_exec_ctrl) && ok;
576 ok = check_vmxec_controls(&vmentry, have_true_msrs,
577 &vmcs_conf->vmentry_ctrl) && ok;
578 ok = check_vmxec_controls(&vmexit, have_true_msrs,
579 &vmcs_conf->vmexit_ctrl) && ok;
581 printk("vmxexec controls is no good.\n");
585 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
586 if ((vmx_msr_high & 0x1fff) > PGSIZE) {
587 printk("vmx_msr_high & 0x1fff) is 0x%x, > PAGE_SIZE 0x%x\n",
588 vmx_msr_high & 0x1fff, PGSIZE);
592 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
593 if (vmx_msr & VMX_BASIC_64) {
594 printk("VMX doesn't support 64 bit width!\n");
598 if (((vmx_msr & VMX_BASIC_MEM_TYPE_MASK) >> VMX_BASIC_MEM_TYPE_SHIFT)
599 != VMX_BASIC_MEM_TYPE_WB) {
600 printk("VMX doesn't support WB memory for VMCS accesses!\n");
604 vmcs_conf->size = vmx_msr_high & 0x1fff;
605 vmcs_conf->order = LOG2_UP(nr_pages(vmcs_config.size));
606 vmcs_conf->revision_id = (uint32_t)vmx_msr;
608 /* Read in the caps for runtime checks. This MSR is only available if
609 * secondary controls and ept or vpid is on, which we check earlier */
610 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP, vmx_capability.ept, vmx_capability.vpid);
615 static struct vmcs *__vmx_alloc_vmcs(int node)
619 vmcs = get_cont_pages_node(node, vmcs_config.order, KMALLOC_WAIT);
622 memset(vmcs, 0, vmcs_config.size);
623 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
624 printd("%d: set rev id %d\n", core_id(), vmcs->revision_id);
629 * vmx_alloc_vmcs - allocates a VMCS region
631 * NOTE: Assumes the new region will be used by the current CPU.
633 * Returns a valid VMCS region.
635 static struct vmcs *vmx_alloc_vmcs(void)
637 return __vmx_alloc_vmcs(numa_id());
641 * vmx_free_vmcs - frees a VMCS region
643 static void vmx_free_vmcs(struct vmcs *vmcs)
645 //free_pages((unsigned long)vmcs, vmcs_config.order);
649 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
650 * will not change in the lifetime of the guest.
651 * Note that host-state that does change is set elsewhere. E.g., host-state
652 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
654 static void vmx_setup_constant_host_state(void)
656 uint32_t low32, high32;
660 vmcs_writel(HOST_CR0, rcr0() & ~X86_CR0_TS); /* 22.2.3 */
661 vmcs_writel(HOST_CR4, rcr4()); /* 22.2.3, 22.2.5 */
662 vmcs_writel(HOST_CR3, rcr3()); /* 22.2.3 */
664 vmcs_write16(HOST_CS_SELECTOR, GD_KT); /* 22.2.4 */
665 vmcs_write16(HOST_DS_SELECTOR, GD_KD); /* 22.2.4 */
666 vmcs_write16(HOST_ES_SELECTOR, GD_KD); /* 22.2.4 */
667 vmcs_write16(HOST_SS_SELECTOR, GD_KD); /* 22.2.4 */
668 vmcs_write16(HOST_TR_SELECTOR, GD_TSS); /* 22.2.4 */
670 native_store_idt(&dt);
671 vmcs_writel(HOST_IDTR_BASE, dt.pd_base); /* 22.2.4 */
673 asm("mov $.Lkvm_vmx_return, %0" : "=r"(tmpl));
674 vmcs_writel(HOST_RIP, tmpl); /* 22.2.5 */
676 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
677 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
678 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
679 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
681 rdmsr(MSR_EFER, low32, high32);
682 vmcs_write32(HOST_IA32_EFER, low32);
684 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
685 rdmsr(MSR_IA32_CR_PAT, low32, high32);
686 vmcs_write64(HOST_IA32_PAT, low32 | ((uint64_t) high32 << 32));
689 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
690 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
692 /* TODO: This (at least gs) is per cpu */
693 rdmsrl(MSR_FS_BASE, tmpl);
694 vmcs_writel(HOST_FS_BASE, tmpl); /* 22.2.4 */
695 rdmsrl(MSR_GS_BASE, tmpl);
696 vmcs_writel(HOST_GS_BASE, tmpl); /* 22.2.4 */
699 static inline uint16_t vmx_read_ldt(void)
702 asm("sldt %0" : "=g"(ldt));
706 static unsigned long segment_base(uint16_t selector)
708 pseudodesc_t *gdt = ¤tcpu->host_gdt;
709 struct desc_struct *d;
710 unsigned long table_base;
713 if (!(selector & ~3)) {
717 table_base = gdt->pd_base;
719 if (selector & 4) { /* from ldt */
720 uint16_t ldt_selector = vmx_read_ldt();
722 if (!(ldt_selector & ~3)) {
726 table_base = segment_base(ldt_selector);
728 d = (struct desc_struct *)(table_base + (selector & ~7));
729 v = get_desc_base(d);
730 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
731 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
735 static inline unsigned long vmx_read_tr_base(void)
738 asm("str %0" : "=g"(tr));
739 return segment_base(tr);
742 static void __vmx_setup_cpu(void)
744 pseudodesc_t *gdt = ¤tcpu->host_gdt;
745 unsigned long sysenter_esp;
749 * Linux uses per-cpu TSS and GDT, so set these when switching
752 vmcs_writel(HOST_TR_BASE, vmx_read_tr_base()); /* 22.2.4 */
753 vmcs_writel(HOST_GDTR_BASE, gdt->pd_base); /* 22.2.4 */
755 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
756 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
758 rdmsrl(MSR_FS_BASE, tmpl);
759 vmcs_writel(HOST_FS_BASE, tmpl); /* 22.2.4 */
760 rdmsrl(MSR_GS_BASE, tmpl);
761 vmcs_writel(HOST_GS_BASE, tmpl); /* 22.2.4 */
765 * vmx_get_cpu - called before using a cpu
766 * @vcpu: VCPU that will be loaded.
768 * Disables preemption. Call vmx_put_cpu() when finished.
770 static void vmx_get_cpu(struct vmx_vcpu *vcpu)
772 int cur_cpu = core_id();
773 handler_wrapper_t *w;
775 if (currentcpu->local_vcpu)
776 panic("get_cpu: currentcpu->localvcpu was non-NULL");
777 if (currentcpu->local_vcpu != vcpu) {
778 currentcpu->local_vcpu = vcpu;
780 if (vcpu->cpu != cur_cpu) {
781 if (vcpu->cpu >= 0) {
782 panic("vcpu->cpu is not -1, it's %d\n", vcpu->cpu);
784 vmcs_clear(vcpu->vmcs);
786 ept_sync_context(vcpu_get_eptp(vcpu));
789 vmcs_load(vcpu->vmcs);
793 vmcs_load(vcpu->vmcs);
799 * vmx_put_cpu - called after using a cpu
800 * @vcpu: VCPU that was loaded.
802 static void vmx_put_cpu(struct vmx_vcpu *vcpu)
804 if (core_id() != vcpu->cpu)
805 panic("%s: core_id() %d != vcpu->cpu %d\n",
806 __func__, core_id(), vcpu->cpu);
808 if (currentcpu->local_vcpu != vcpu)
809 panic("vmx_put_cpu: asked to clear something not ours");
811 ept_sync_context(vcpu_get_eptp(vcpu));
812 vmcs_clear(vcpu->vmcs);
814 currentcpu->local_vcpu = NULL;
819 * vmx_dump_cpu - prints the CPU state
820 * @vcpu: VCPU to print
822 static void vmx_dump_cpu(struct vmx_vcpu *vcpu)
828 vcpu->regs.tf_rip = vmcs_readl(GUEST_RIP);
829 vcpu->regs.tf_rsp = vmcs_readl(GUEST_RSP);
830 flags = vmcs_readl(GUEST_RFLAGS);
833 printk("--- Begin VCPU Dump ---\n");
834 printk("CPU %d VPID %d\n", vcpu->cpu, 0);
835 printk("RIP 0x%016lx RFLAGS 0x%08lx\n",
836 vcpu->regs.tf_rip, flags);
837 printk("RAX 0x%016lx RCX 0x%016lx\n",
838 vcpu->regs.tf_rax, vcpu->regs.tf_rcx);
839 printk("RDX 0x%016lx RBX 0x%016lx\n",
840 vcpu->regs.tf_rdx, vcpu->regs.tf_rbx);
841 printk("RSP 0x%016lx RBP 0x%016lx\n",
842 vcpu->regs.tf_rsp, vcpu->regs.tf_rbp);
843 printk("RSI 0x%016lx RDI 0x%016lx\n",
844 vcpu->regs.tf_rsi, vcpu->regs.tf_rdi);
845 printk("R8 0x%016lx R9 0x%016lx\n",
846 vcpu->regs.tf_r8, vcpu->regs.tf_r9);
847 printk("R10 0x%016lx R11 0x%016lx\n",
848 vcpu->regs.tf_r10, vcpu->regs.tf_r11);
849 printk("R12 0x%016lx R13 0x%016lx\n",
850 vcpu->regs.tf_r12, vcpu->regs.tf_r13);
851 printk("R14 0x%016lx R15 0x%016lx\n",
852 vcpu->regs.tf_r14, vcpu->regs.tf_r15);
853 printk("--- End VCPU Dump ---\n");
857 uint64_t construct_eptp(physaddr_t root_hpa)
861 /* set WB memory and 4 levels of walk. we checked these in ept_init */
862 eptp = VMX_EPT_MEM_TYPE_WB |
863 (VMX_EPT_GAW_4_LVL << VMX_EPT_GAW_EPTP_SHIFT);
864 if (cpu_has_vmx_ept_ad_bits())
865 eptp |= VMX_EPT_AD_ENABLE_BIT;
866 eptp |= (root_hpa & PAGE_MASK);
872 * vmx_setup_initial_guest_state - configures the initial state of guest registers
874 static void vmx_setup_initial_guest_state(void)
877 unsigned long cr4 = X86_CR4_PAE | X86_CR4_VMXE | X86_CR4_OSXMMEXCPT |
878 X86_CR4_PGE | X86_CR4_OSFXSR;
879 uint32_t protected_mode = X86_CR0_PG | X86_CR0_PE;
882 if (boot_cpu_has(X86_FEATURE_PCID))
883 cr4 |= X86_CR4_PCIDE;
884 if (boot_cpu_has(X86_FEATURE_OSXSAVE))
885 cr4 |= X86_CR4_OSXSAVE;
887 /* we almost certainly have this */
888 /* we'll go sour if we don't. */
889 if (1) //boot_cpu_has(X86_FEATURE_FSGSBASE))
890 cr4 |= X86_CR4_RDWRGSFS;
892 /* configure control and data registers */
893 vmcs_writel(GUEST_CR0, protected_mode | X86_CR0_WP |
894 X86_CR0_MP | X86_CR0_ET | X86_CR0_NE);
895 vmcs_writel(CR0_READ_SHADOW, protected_mode | X86_CR0_WP |
896 X86_CR0_MP | X86_CR0_ET | X86_CR0_NE);
897 vmcs_writel(GUEST_CR3, rcr3());
898 vmcs_writel(GUEST_CR4, cr4);
899 vmcs_writel(CR4_READ_SHADOW, cr4);
900 vmcs_writel(GUEST_IA32_EFER, EFER_LME | EFER_LMA |
901 EFER_SCE | EFER_FFXSR);
902 vmcs_writel(GUEST_GDTR_BASE, 0);
903 vmcs_writel(GUEST_GDTR_LIMIT, 0);
904 vmcs_writel(GUEST_IDTR_BASE, 0);
905 vmcs_writel(GUEST_IDTR_LIMIT, 0);
906 vmcs_writel(GUEST_RIP, 0xdeadbeef);
907 vmcs_writel(GUEST_RSP, 0xdeadbeef);
908 vmcs_writel(GUEST_RFLAGS, 0x02);
909 vmcs_writel(GUEST_DR7, 0);
911 /* guest segment bases */
912 vmcs_writel(GUEST_CS_BASE, 0);
913 vmcs_writel(GUEST_DS_BASE, 0);
914 vmcs_writel(GUEST_ES_BASE, 0);
915 vmcs_writel(GUEST_GS_BASE, 0);
916 vmcs_writel(GUEST_SS_BASE, 0);
917 rdmsrl(MSR_FS_BASE, tmpl);
918 vmcs_writel(GUEST_FS_BASE, tmpl);
920 /* guest segment access rights */
921 vmcs_writel(GUEST_CS_AR_BYTES, 0xA09B);
922 vmcs_writel(GUEST_DS_AR_BYTES, 0xA093);
923 vmcs_writel(GUEST_ES_AR_BYTES, 0xA093);
924 vmcs_writel(GUEST_FS_AR_BYTES, 0xA093);
925 vmcs_writel(GUEST_GS_AR_BYTES, 0xA093);
926 vmcs_writel(GUEST_SS_AR_BYTES, 0xA093);
928 /* guest segment limits */
929 vmcs_write32(GUEST_CS_LIMIT, 0xFFFFFFFF);
930 vmcs_write32(GUEST_DS_LIMIT, 0xFFFFFFFF);
931 vmcs_write32(GUEST_ES_LIMIT, 0xFFFFFFFF);
932 vmcs_write32(GUEST_FS_LIMIT, 0xFFFFFFFF);
933 vmcs_write32(GUEST_GS_LIMIT, 0xFFFFFFFF);
934 vmcs_write32(GUEST_SS_LIMIT, 0xFFFFFFFF);
936 /* configure segment selectors */
937 vmcs_write16(GUEST_CS_SELECTOR, 0);
938 vmcs_write16(GUEST_DS_SELECTOR, 0);
939 vmcs_write16(GUEST_ES_SELECTOR, 0);
940 vmcs_write16(GUEST_FS_SELECTOR, 0);
941 vmcs_write16(GUEST_GS_SELECTOR, 0);
942 vmcs_write16(GUEST_SS_SELECTOR, 0);
943 vmcs_write16(GUEST_TR_SELECTOR, 0);
946 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
947 vmcs_writel(GUEST_LDTR_AR_BYTES, 0x0082);
948 vmcs_writel(GUEST_LDTR_BASE, 0);
949 vmcs_writel(GUEST_LDTR_LIMIT, 0);
952 vmcs_writel(GUEST_TR_BASE, 0);
953 vmcs_writel(GUEST_TR_AR_BYTES, 0x0080 | AR_TYPE_BUSY_64_TSS);
954 vmcs_writel(GUEST_TR_LIMIT, 0xff);
956 /* initialize sysenter */
957 vmcs_write32(GUEST_SYSENTER_CS, 0);
958 vmcs_writel(GUEST_SYSENTER_ESP, 0);
959 vmcs_writel(GUEST_SYSENTER_EIP, 0);
961 /* other random initialization */
962 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
963 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
964 vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
965 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
966 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
969 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap, uint32_t msr)
971 int f = sizeof(unsigned long);
973 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
974 * have the write-low and read-high bitmap offsets the wrong way round.
975 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
978 __clear_bit(msr, msr_bitmap + 0x000 / f); /* read-low */
979 __clear_bit(msr, msr_bitmap + 0x800 / f); /* write-low */
980 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
982 __clear_bit(msr, msr_bitmap + 0x400 / f); /* read-high */
983 __clear_bit(msr, msr_bitmap + 0xc00 / f); /* write-high */
987 static void vcpu_print_autoloads(struct vmx_vcpu *vcpu)
989 struct vmx_msr_entry *e;
990 int sz = sizeof(autoloaded_msrs) / sizeof(*autoloaded_msrs);
991 printk("Host Autoloads:\n-------------------\n");
992 for (int i = 0; i < sz; i++) {
993 e = &vcpu->msr_autoload.host[i];
994 printk("\tMSR 0x%08x: %p\n", e->index, e->value);
996 printk("Guest Autoloads:\n-------------------\n");
997 for (int i = 0; i < sz; i++) {
998 e = &vcpu->msr_autoload.guest[i];
999 printk("\tMSR 0x%08x %p\n", e->index, e->value);
1003 static void dumpmsrs(void)
1012 MSR_IA32_PEBS_ENABLE
1014 for(i = 0; i < ARRAY_SIZE(set); i++) {
1015 printk("%p: %p\n", set[i], read_msr(set[i]));
1017 printk("core id %d\n", core_id());
1020 /* Notes on autoloading. We can't autoload FS_BASE or GS_BASE, according to the
1021 * manual, but that's because they are automatically saved and restored when all
1022 * of the other architectural registers are saved and restored, such as cs, ds,
1023 * es, and other fun things. (See 24.4.1). We need to make sure we don't
1024 * accidentally intercept them too, since they are magically autloaded..
1026 * We'll need to be careful of any MSR we neither autoload nor intercept
1027 * whenever we vmenter/vmexit, and we intercept by default.
1029 * Other MSRs, such as MSR_IA32_PEBS_ENABLE only work on certain architectures
1030 * only work on certain architectures. */
1031 static void setup_msr(struct vmx_vcpu *vcpu)
1033 struct vmx_msr_entry *e;
1034 int sz = sizeof(autoloaded_msrs) / sizeof(*autoloaded_msrs);
1037 static_assert((sizeof(autoloaded_msrs) / sizeof(*autoloaded_msrs)) <=
1040 vcpu->msr_autoload.nr = sz;
1042 /* Since PADDR(msr_bitmap) is non-zero, and the bitmap is all 0xff, we now
1043 * intercept all MSRs */
1044 vmcs_write64(MSR_BITMAP, PADDR(msr_bitmap));
1046 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vcpu->msr_autoload.nr);
1047 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vcpu->msr_autoload.nr);
1048 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vcpu->msr_autoload.nr);
1050 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, PADDR(vcpu->msr_autoload.host));
1051 vmcs_write64(VM_EXIT_MSR_STORE_ADDR, PADDR(vcpu->msr_autoload.guest));
1052 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, PADDR(vcpu->msr_autoload.guest));
1054 for (i = 0; i < sz; i++) {
1057 e = &vcpu->msr_autoload.host[i];
1058 e->index = autoloaded_msrs[i];
1059 __vmx_disable_intercept_for_msr(msr_bitmap, e->index);
1060 rdmsrl(e->index, val);
1062 printk("host index %p val %p\n", e->index, e->value);
1064 e = &vcpu->msr_autoload.guest[i];
1065 e->index = autoloaded_msrs[i];
1066 e->value = 0xDEADBEEF;
1067 printk("guest index %p val %p\n", e->index, e->value);
1072 * vmx_setup_vmcs - configures the vmcs with starting parameters
1074 static void vmx_setup_vmcs(struct vmx_vcpu *vcpu)
1076 vmcs_write16(VIRTUAL_PROCESSOR_ID, 0);
1077 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
1080 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
1081 vmcs_config.pin_based_exec_ctrl);
1083 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
1084 vmcs_config.cpu_based_exec_ctrl);
1086 if (cpu_has_secondary_exec_ctrls()) {
1087 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
1088 vmcs_config.cpu_based_2nd_exec_ctrl);
1091 vmcs_write64(EPT_POINTER, vcpu_get_eptp(vcpu));
1093 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
1094 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
1095 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
1099 vmcs_config.vmentry_ctrl |= VM_ENTRY_IA32E_MODE;
1101 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
1102 vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
1104 vmcs_writel(CR0_GUEST_HOST_MASK, ~0ul);
1105 vmcs_writel(CR4_GUEST_HOST_MASK, ~0ul);
1107 //kvm_write_tsc(&vmx->vcpu, 0);
1108 vmcs_writel(TSC_OFFSET, 0);
1110 vmx_setup_constant_host_state();
1114 * vmx_create_vcpu - allocates and initializes a new virtual cpu
1116 * Returns: A new VCPU structure
1118 struct vmx_vcpu *vmx_create_vcpu(struct proc *p)
1120 struct vmx_vcpu *vcpu = kmalloc(sizeof(struct vmx_vcpu), KMALLOC_WAIT);
1125 memset(vcpu, 0, sizeof(*vcpu));
1127 vcpu->proc = p; /* uncounted (weak) reference */
1128 vcpu->vmcs = vmx_alloc_vmcs();
1129 printd("%d: vcpu->vmcs is %p\n", core_id(), vcpu->vmcs);
1136 vmx_setup_vmcs(vcpu);
1137 vmx_setup_initial_guest_state();
1148 * vmx_destroy_vcpu - destroys and frees an existing virtual cpu
1149 * @vcpu: the VCPU to destroy
1151 void vmx_destroy_vcpu(struct vmx_vcpu *vcpu)
1153 vmx_free_vmcs(vcpu->vmcs);
1158 * vmx_current_vcpu - returns a pointer to the vcpu for the current task.
1160 * In the contexts where this is used the vcpu pointer should never be NULL.
1162 static inline struct vmx_vcpu *vmx_current_vcpu(void)
1164 struct vmx_vcpu *vcpu = currentcpu->local_vcpu;
1166 panic("Core has no vcpu!");
1171 * vmx_run_vcpu - launches the CPU into non-root mode
1172 * We ONLY support 64-bit guests.
1173 * @vcpu: the vmx instance to launch
1175 static int vmx_run_vcpu(struct vmx_vcpu *vcpu)
1178 /* Store host registers */
1179 "push %%rdx; push %%rbp;"
1180 "push %%rcx \n\t" /* placeholder for guest rcx */
1182 "cmp %%rsp, %c[host_rsp](%0) \n\t"
1184 "mov %%rsp, %c[host_rsp](%0) \n\t"
1185 ASM_VMX_VMWRITE_RSP_RDX "\n\t"
1187 /* Reload cr2 if changed */
1188 "mov %c[cr2](%0), %%rax \n\t"
1189 "mov %%cr2, %%rdx \n\t"
1190 "cmp %%rax, %%rdx \n\t"
1192 "mov %%rax, %%cr2 \n\t"
1194 /* Check if vmlaunch of vmresume is needed */
1195 "cmpl $0, %c[launched](%0) \n\t"
1196 /* Load guest registers. Don't clobber flags. */
1197 "mov %c[rax](%0), %%rax \n\t"
1198 "mov %c[rbx](%0), %%rbx \n\t"
1199 "mov %c[rdx](%0), %%rdx \n\t"
1200 "mov %c[rsi](%0), %%rsi \n\t"
1201 "mov %c[rdi](%0), %%rdi \n\t"
1202 "mov %c[rbp](%0), %%rbp \n\t"
1203 "mov %c[r8](%0), %%r8 \n\t"
1204 "mov %c[r9](%0), %%r9 \n\t"
1205 "mov %c[r10](%0), %%r10 \n\t"
1206 "mov %c[r11](%0), %%r11 \n\t"
1207 "mov %c[r12](%0), %%r12 \n\t"
1208 "mov %c[r13](%0), %%r13 \n\t"
1209 "mov %c[r14](%0), %%r14 \n\t"
1210 "mov %c[r15](%0), %%r15 \n\t"
1211 "mov %c[rcx](%0), %%rcx \n\t" /* kills %0 (ecx) */
1213 /* Enter guest mode */
1214 "jne .Llaunched \n\t"
1215 ASM_VMX_VMLAUNCH "\n\t"
1216 "jmp .Lkvm_vmx_return \n\t"
1217 ".Llaunched: " ASM_VMX_VMRESUME "\n\t"
1218 ".Lkvm_vmx_return: "
1219 /* Save guest registers, load host registers, keep flags */
1220 "mov %0, %c[wordsize](%%rsp) \n\t"
1222 "mov %%rax, %c[rax](%0) \n\t"
1223 "mov %%rbx, %c[rbx](%0) \n\t"
1224 "popq %c[rcx](%0) \n\t"
1225 "mov %%rdx, %c[rdx](%0) \n\t"
1226 "mov %%rsi, %c[rsi](%0) \n\t"
1227 "mov %%rdi, %c[rdi](%0) \n\t"
1228 "mov %%rbp, %c[rbp](%0) \n\t"
1229 "mov %%r8, %c[r8](%0) \n\t"
1230 "mov %%r9, %c[r9](%0) \n\t"
1231 "mov %%r10, %c[r10](%0) \n\t"
1232 "mov %%r11, %c[r11](%0) \n\t"
1233 "mov %%r12, %c[r12](%0) \n\t"
1234 "mov %%r13, %c[r13](%0) \n\t"
1235 "mov %%r14, %c[r14](%0) \n\t"
1236 "mov %%r15, %c[r15](%0) \n\t"
1237 "mov %%rax, %%r10 \n\t"
1238 "mov %%rdx, %%r11 \n\t"
1240 "mov %%cr2, %%rax \n\t"
1241 "mov %%rax, %c[cr2](%0) \n\t"
1243 "pop %%rbp; pop %%rdx \n\t"
1244 "setbe %c[fail](%0) \n\t"
1245 "mov $" STRINGIFY(GD_UD) ", %%rax \n\t"
1246 "mov %%rax, %%ds \n\t"
1247 "mov %%rax, %%es \n\t"
1248 : : "c"(vcpu), "d"((unsigned long)HOST_RSP),
1249 [launched]"i"(offsetof(struct vmx_vcpu, launched)),
1250 [fail]"i"(offsetof(struct vmx_vcpu, fail)),
1251 [host_rsp]"i"(offsetof(struct vmx_vcpu, host_rsp)),
1252 [rax]"i"(offsetof(struct vmx_vcpu, regs.tf_rax)),
1253 [rbx]"i"(offsetof(struct vmx_vcpu, regs.tf_rbx)),
1254 [rcx]"i"(offsetof(struct vmx_vcpu, regs.tf_rcx)),
1255 [rdx]"i"(offsetof(struct vmx_vcpu, regs.tf_rdx)),
1256 [rsi]"i"(offsetof(struct vmx_vcpu, regs.tf_rsi)),
1257 [rdi]"i"(offsetof(struct vmx_vcpu, regs.tf_rdi)),
1258 [rbp]"i"(offsetof(struct vmx_vcpu, regs.tf_rbp)),
1259 [r8]"i"(offsetof(struct vmx_vcpu, regs.tf_r8)),
1260 [r9]"i"(offsetof(struct vmx_vcpu, regs.tf_r9)),
1261 [r10]"i"(offsetof(struct vmx_vcpu, regs.tf_r10)),
1262 [r11]"i"(offsetof(struct vmx_vcpu, regs.tf_r11)),
1263 [r12]"i"(offsetof(struct vmx_vcpu, regs.tf_r12)),
1264 [r13]"i"(offsetof(struct vmx_vcpu, regs.tf_r13)),
1265 [r14]"i"(offsetof(struct vmx_vcpu, regs.tf_r14)),
1266 [r15]"i"(offsetof(struct vmx_vcpu, regs.tf_r15)),
1267 [cr2]"i"(offsetof(struct vmx_vcpu, cr2)),
1268 [wordsize]"i"(sizeof(unsigned long))
1270 , "rax", "rbx", "rdi", "rsi"
1271 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
1274 vcpu->regs.tf_rip = vmcs_readl(GUEST_RIP);
1275 vcpu->regs.tf_rsp = vmcs_readl(GUEST_RSP);
1276 printd("RETURN. ip %016lx sp %016lx cr2 %016lx\n",
1277 vcpu->regs.tf_rip, vcpu->regs.tf_rsp, vcpu->cr2);
1278 /* FIXME: do we need to set up other flags? */
1279 vcpu->regs.tf_rflags = (vmcs_readl(GUEST_RFLAGS) & 0xFF) |
1280 X86_EFLAGS_IF | 0x2;
1282 vcpu->regs.tf_cs = GD_UT;
1283 vcpu->regs.tf_ss = GD_UD;
1288 printk("failure detected (err %x)\n",
1289 vmcs_read32(VM_INSTRUCTION_ERROR));
1290 return VMX_EXIT_REASONS_FAILED_VMENTRY;
1293 return vmcs_read32(VM_EXIT_REASON);
1296 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
1297 vmx_complete_atomic_exit(vmx);
1298 vmx_recover_nmi_blocking(vmx);
1299 vmx_complete_interrupts(vmx);
1303 static void vmx_step_instruction(void)
1305 vmcs_writel(GUEST_RIP, vmcs_readl(GUEST_RIP) +
1306 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
1309 static int vmx_handle_ept_violation(struct vmx_vcpu *vcpu)
1311 unsigned long gva, gpa;
1312 int exit_qual, ret = -1;
1316 exit_qual = vmcs_read32(EXIT_QUALIFICATION);
1317 gva = vmcs_readl(GUEST_LINEAR_ADDRESS);
1318 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
1323 prot |= exit_qual & VMX_EPT_FAULT_READ ? PROT_READ : 0;
1324 prot |= exit_qual & VMX_EPT_FAULT_WRITE ? PROT_WRITE : 0;
1325 prot |= exit_qual & VMX_EPT_FAULT_INS ? PROT_EXEC : 0;
1326 ret = handle_page_fault(current, gpa, prot);
1329 printk("EPT page fault failure %d, GPA: %p, GVA: %p\n", ret, gpa, gva);
1336 static void vmx_handle_cpuid(struct vmx_vcpu *vcpu)
1338 unsigned int eax, ebx, ecx, edx;
1340 eax = vcpu->regs.tf_rax;
1341 ecx = vcpu->regs.tf_rcx;
1342 cpuid(0, 2, &eax, &ebx, &ecx, &edx);
1343 vcpu->regs.tf_rax = eax;
1344 vcpu->regs.tf_rbx = ebx;
1345 vcpu->regs.tf_rcx = ecx;
1346 vcpu->regs.tf_rdx = edx;
1349 static int vmx_handle_nmi_exception(struct vmx_vcpu *vcpu)
1354 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
1357 printk("vmx (vcpu %p): got an exception\n", vcpu);
1358 printk("vmx (vcpu %p): pid %d\n", vcpu, vcpu->proc->pid);
1359 if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) {
1363 printk("unhandled nmi, intr_info %x\n", intr_info);
1368 * vmx_launch - the main loop for a VMX Dune process
1369 * @conf: the launch configuration
1371 int vmx_launch(uint64_t rip, uint64_t rsp, uint64_t cr3)
1374 struct vmx_vcpu *vcpu;
1377 printd("RUNNING: %s: rip %p rsp %p cr3 %p \n",
1378 __func__, rip, rsp, cr3);
1379 /* TODO: dirty hack til we have VMM contexts */
1380 vcpu = current->vmm.guest_pcores[0];
1382 printk("Failed to get a CPU!\n");
1386 /* We need to prep the host's autoload region for our current core. Right
1387 * now, the only autoloaded MSR that varies at runtime (in this case per
1388 * core is the KERN_GS_BASE). */
1389 rdmsrl(MSR_KERNEL_GS_BASE, vcpu->msr_autoload.host[0].value);
1390 /* if cr3 is set, means 'set everything', else means 'start where you left off' */
1393 vmcs_writel(GUEST_RIP, rip);
1394 vmcs_writel(GUEST_RSP, rsp);
1395 vmcs_writel(GUEST_CR3, cr3);
1399 vcpu->ret_code = -1;
1404 // TODO: manage the fpu when we restart.
1406 // TODO: see if we need to exit before we go much further.
1409 ret = vmx_run_vcpu(vcpu);
1414 if (ret == EXIT_REASON_VMCALL) {
1415 if (current->vmm.flags & VMM_VMCALL_PRINTF) {
1416 uint8_t byte = vcpu->regs.tf_rdi;
1420 vmcs_writel(GUEST_RIP, vcpu->regs.tf_rip + 3);
1423 vcpu->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
1424 uint8_t byte = vcpu->regs.tf_rdi;
1425 printk("%p %c\n", byte, vcpu->regs.tf_rdi);
1427 printd("system call! WTF\n");
1429 } else if (ret == EXIT_REASON_CPUID) {
1430 vmx_handle_cpuid(vcpu);
1432 vmcs_writel(GUEST_RIP, vcpu->regs.tf_rip + 2);
1434 } else if (ret == EXIT_REASON_EPT_VIOLATION) {
1435 if (vmx_handle_ept_violation(vcpu))
1436 vcpu->shutdown = SHUTDOWN_EPT_VIOLATION;
1437 } else if (ret == EXIT_REASON_EXCEPTION_NMI) {
1438 if (vmx_handle_nmi_exception(vcpu))
1439 vcpu->shutdown = SHUTDOWN_NMI_EXCEPTION;
1440 } else if (ret == EXIT_REASON_EXTERNAL_INTERRUPT) {
1441 printd("External interrupt\n");
1442 vcpu->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
1444 printk("unhandled exit: reason 0x%x, exit qualification 0x%x\n",
1445 ret, vmcs_read32(EXIT_QUALIFICATION));
1447 vcpu->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
1450 /* TODO: we can't just return and relaunch the VMCS, in case we blocked.
1451 * similar to how proc_restartcore/smp_idle only restart the pcpui
1452 * cur_ctx, we need to do the same, via the VMCS resume business. */
1458 printd("RETURN. ip %016lx sp %016lx\n",
1459 vcpu->regs.tf_rip, vcpu->regs.tf_rsp);
1462 * Return both the reason for the shutdown and a status value.
1463 * The exit() and exit_group() system calls only need 8 bits for
1464 * the status but we allow 16 bits in case we might want to
1465 * return more information for one of the other shutdown reasons.
1467 ret = (vcpu->shutdown << 16) | (vcpu->ret_code & 0xffff);
1473 * __vmx_enable - low-level enable of VMX mode on the current CPU
1474 * @vmxon_buf: an opaque buffer for use as the VMXON region
1476 static int __vmx_enable(struct vmcs *vmxon_buf)
1478 uint64_t phys_addr = PADDR(vmxon_buf);
1479 uint64_t old, test_bits;
1481 if (rcr4() & X86_CR4_VMXE) {
1482 panic("Should never have this happen");
1486 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
1488 test_bits = FEATURE_CONTROL_LOCKED;
1489 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
1491 if (0) // tboot_enabled())
1492 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
1494 if ((old & test_bits) != test_bits) {
1495 /* If it's locked, then trying to set it will cause a GPF.
1498 if (old & FEATURE_CONTROL_LOCKED) {
1499 printk("Dune: MSR_IA32_FEATURE_CONTROL is locked!\n");
1503 /* enable and lock */
1504 write_msr(MSR_IA32_FEATURE_CONTROL, old | test_bits);
1506 lcr4(rcr4() | X86_CR4_VMXE);
1509 vpid_sync_vcpu_global(); /* good idea, even if we aren't using vpids */
1516 * vmx_enable - enables VMX mode on the current CPU
1517 * @unused: not used (required for on_each_cpu())
1519 * Sets up necessary state for enable (e.g. a scratchpad for VMXON.)
1521 static void vmx_enable(void)
1523 struct vmcs *vmxon_buf = currentcpu->vmxarea;
1526 ret = __vmx_enable(vmxon_buf);
1530 currentcpu->vmx_enabled = 1;
1531 // TODO: do we need this?
1532 store_gdt(¤tcpu->host_gdt);
1534 printk("VMX enabled on CPU %d\n", core_id());
1538 printk("Failed to enable VMX on core %d, err = %d\n", core_id(), ret);
1542 * vmx_disable - disables VMX mode on the current CPU
1544 static void vmx_disable(void *unused)
1546 if (currentcpu->vmx_enabled) {
1548 lcr4(rcr4() & ~X86_CR4_VMXE);
1549 currentcpu->vmx_enabled = 0;
1553 /* Probe the cpus to see which ones can do vmx.
1554 * Return -errno if it fails, and 1 if it succeeds.
1556 static bool probe_cpu_vmx(void)
1558 /* The best way to test this code is:
1559 * wrmsr -p <cpu> 0x3a 1
1560 * This will lock vmx off; then modprobe dune.
1561 * Frequently, however, systems have all 0x3a registers set to 5,
1562 * meaning testing is impossible, as vmx can not be disabled.
1563 * We have to simulate it being unavailable in most cases.
1564 * The 'test' variable provides an easy way to simulate
1565 * unavailability of vmx on some, none, or all cpus.
1567 if (!cpu_has_vmx()) {
1568 printk("Machine does not support VT-x\n");
1571 printk("Machine supports VT-x\n");
1576 static void setup_vmxarea(void)
1578 struct vmcs *vmxon_buf;
1579 printd("Set up vmxarea for cpu %d\n", core_id());
1580 vmxon_buf = __vmx_alloc_vmcs(core_id());
1582 printk("setup_vmxarea failed on node %d\n", core_id());
1585 currentcpu->vmxarea = vmxon_buf;
1588 static int ept_init(void)
1590 if (!cpu_has_vmx_ept()) {
1591 printk("VMX doesn't support EPT!\n");
1594 if (!cpu_has_vmx_eptp_writeback()) {
1595 printk("VMX EPT doesn't support WB memory!\n");
1598 if (!cpu_has_vmx_ept_4levels()) {
1599 printk("VMX EPT doesn't support 4 level walks!\n");
1602 switch (arch_max_jumbo_page_shift()) {
1604 if (!cpu_has_vmx_ept_1g_page()) {
1605 printk("VMX EPT doesn't support 1 GB pages!\n");
1610 if (!cpu_has_vmx_ept_2m_page()) {
1611 printk("VMX EPT doesn't support 2 MB pages!\n");
1616 printk("Unexpected jumbo page size %d\n",
1617 arch_max_jumbo_page_shift());
1620 if (!cpu_has_vmx_ept_ad_bits()) {
1621 printk("VMX EPT doesn't support accessed/dirty!\n");
1622 x86_ept_pte_fix_ups |= EPTE_A | EPTE_D;
1624 if (!cpu_has_vmx_invept() || !cpu_has_vmx_invept_global()) {
1625 printk("VMX EPT can't invalidate PTEs/TLBs!\n");
1633 * vmx_init sets up physical core data areas that are required to run a vm at all.
1634 * These data areas are not connected to a specific user process in any way. Instead,
1635 * they are in some sense externalizing what would other wise be a very large ball of
1636 * state that would be inside the CPU.
1638 int intel_vmm_init(void)
1642 if (! probe_cpu_vmx()) {
1646 setup_vmcs_config(&ret);
1649 printk("setup_vmcs_config failed: %d\n", ret);
1653 msr_bitmap = (unsigned long *)kpage_zalloc_addr();
1655 printk("Could not allocate msr_bitmap\n");
1658 /* FIXME: do we need APIC virtualization (flexpriority?) */
1660 memset(msr_bitmap, 0xff, PAGE_SIZE);
1661 /* These are the only MSRs that are not autoloaded and not intercepted */
1662 __vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE);
1663 __vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE);
1665 if ((ret = ept_init())) {
1666 printk("EPT init failed, %d\n", ret);
1669 printk("VMX setup succeeded\n");
1673 int intel_vmm_pcpu_init(void)