vmmcp: allow basic IO and more MSRs
[akaros.git] / kern / arch / x86 / vmm / intel / vmx.c
1 //#define DEBUG
2 /**
3  *  vmx.c - The Intel VT-x driver for Dune
4  *
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.
8  *
9  * Original Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
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
20  *
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.
24  *
25  * This driver is a research prototype and as such has the following
26  * limitations:
27  *
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
30  * driver.
31  *
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.
35  *
36  * FIXME: We need to support hotplugged physical CPUs.
37  *
38  * Authors:
39  *   Adam Belay   <abelay@stanford.edu>
40  */
41
42 /* Basic flow.
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
45  *
46  * 1) your CPU is going to be capable of running VMs, and you need state for that.
47  *
48  * 2) you're about to start a guest, and you need state for that.
49  *
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.
54  *
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
67  * anyway.
68  *
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.
73  *
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.
76  *
77  * Reserve bit 0 in the vpid bitmap as guests can not use that
78  *
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.
84  *
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
90  * to host guests.
91  *
92  * Setting up a guest.
93  * We divide this into two things: vmm_proc_init and vm_run.
94  * Currently, on Intel, vmm_proc_init does nothing.
95  *
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.
101  *
102  * The sequence of operations:
103  * create a vcpu
104  * while (1) {
105  * get a vcpu
106  * disable irqs (required or you can't enter the VM)
107  * vmx_run_vcpu()
108  * enable irqs
109  * manage the vm exit
110  * }
111  *
112  * get a vcpu
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.
115  *
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.
120  *
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.
131  *
132  */
133
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.
138  */
139 #include <kmalloc.h>
140 #include <string.h>
141 #include <stdio.h>
142 #include <assert.h>
143 #include <error.h>
144 #include <pmap.h>
145 #include <sys/queue.h>
146 #include <smp.h>
147 #include <kref.h>
148 #include <atomic.h>
149 #include <alarm.h>
150 #include <event.h>
151 #include <umem.h>
152 #include <bitops.h>
153 #include <arch/types.h>
154 #include <syscall.h>
155 #include <arch/io.h>
156
157 #include "vmx.h"
158 #include "../vmm.h"
159 #include <ros/vmm.h>
160
161 #include "cpufeature.h"
162
163 #define currentcpu (&per_cpu_info[core_id()])
164
165 static unsigned long *msr_bitmap;
166 #define VMX_IO_BITMAP_ORDER             4       /* 64 KB */
167 #define VMX_IO_BITMAP_SZ                (1 << (VMX_IO_BITMAP_ORDER + PGSHIFT))
168 static unsigned long *io_bitmap;
169
170 int x86_ept_pte_fix_ups = 0;
171
172 struct vmx_capability vmx_capability;
173 struct vmcs_config vmcs_config;
174
175 static int autoloaded_msrs[] = {
176         MSR_KERNEL_GS_BASE,
177         MSR_LSTAR,
178         MSR_STAR,
179         MSR_SFMASK,
180 };
181
182 static char *cr_access_type[] = {
183         "move to cr",
184         "move from cr",
185         "clts",
186         "lmsw"
187 };
188
189 static char *cr_gpr[] = {
190         "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
191         "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
192 };
193
194 static int guest_cr_num[16] = {
195         GUEST_CR0,
196         -1,
197         -1,
198         GUEST_CR3,
199         GUEST_CR4,
200         -1,
201         -1,
202         -1,
203         -1, /* 8? */
204         -1, -1, -1, -1, -1, -1, -1
205 };
206 __always_inline unsigned long vmcs_readl(unsigned long field);
207 /* See section 24-3 of The Good Book */
208 void show_cr_access(uint64_t val) {
209         int crnr = val & 0xf;
210         int type = (val>>4) & 3;
211         int reg = (val >> 11) & 0xf;
212         printk("%s: %d: ", cr_access_type[type], crnr);
213         if (type < 2) {
214                 printk("%s", cr_gpr[reg]);
215                 if (guest_cr_num[crnr] > -1) {
216                         printk(": 0x%x", vmcs_readl(guest_cr_num[crnr]));
217                 }
218         }
219         printk("\n");
220 }
221
222 void ept_flush(uint64_t eptp)
223 {
224         ept_sync_context(eptp);
225 }
226
227 static void vmcs_clear(struct vmcs *vmcs)
228 {
229         uint64_t phys_addr = PADDR(vmcs);
230         uint8_t error;
231
232         asm volatile (ASM_VMX_VMCLEAR_RAX "; setna %0"
233                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
234                       : "cc", "memory");
235         if (error)
236                 printk("vmclear fail: %p/%llx\n",
237                        vmcs, phys_addr);
238 }
239
240 static void vmcs_load(struct vmcs *vmcs)
241 {
242         uint64_t phys_addr = PADDR(vmcs);
243         uint8_t error;
244
245         asm volatile (ASM_VMX_VMPTRLD_RAX "; setna %0"
246                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
247                         : "cc", "memory");
248         if (error)
249                 printk("vmptrld %p/%llx failed\n",
250                        vmcs, phys_addr);
251 }
252
253 /* Returns the paddr pointer of the current CPU's VMCS region, or -1 if none. */
254 static physaddr_t vmcs_get_current(void)
255 {
256         physaddr_t vmcs_paddr;
257         /* RAX contains the addr of the location to store the VMCS pointer.  The
258          * compiler doesn't know the ASM will deref that pointer, hence the =m */
259         asm volatile (ASM_VMX_VMPTRST_RAX : "=m"(vmcs_paddr) : "a"(&vmcs_paddr));
260         return vmcs_paddr;
261 }
262
263 __always_inline unsigned long vmcs_readl(unsigned long field)
264 {
265         unsigned long value;
266
267         asm volatile (ASM_VMX_VMREAD_RDX_RAX
268                       : "=a"(value) : "d"(field) : "cc");
269         return value;
270 }
271
272 __always_inline uint16_t vmcs_read16(unsigned long field)
273 {
274         return vmcs_readl(field);
275 }
276
277 static __always_inline uint32_t vmcs_read32(unsigned long field)
278 {
279         return vmcs_readl(field);
280 }
281
282 static __always_inline uint64_t vmcs_read64(unsigned long field)
283 {
284         return vmcs_readl(field);
285 }
286
287 void vmwrite_error(unsigned long field, unsigned long value)
288 {
289         printk("vmwrite error: reg %lx value %lx (err %d)\n",
290                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
291 }
292
293 void vmcs_writel(unsigned long field, unsigned long value)
294 {
295         uint8_t error;
296
297         asm volatile (ASM_VMX_VMWRITE_RAX_RDX "; setna %0"
298                        : "=q"(error) : "a"(value), "d"(field) : "cc");
299         if (error)
300                 vmwrite_error(field, value);
301 }
302
303 static void vmcs_write16(unsigned long field, uint16_t value)
304 {
305         vmcs_writel(field, value);
306 }
307
308 static void vmcs_write32(unsigned long field, uint32_t value)
309 {
310         vmcs_writel(field, value);
311 }
312
313 static void vmcs_write64(unsigned long field, uint64_t value)
314 {
315         vmcs_writel(field, value);
316 }
317
318 /*
319  * A note on Things You Can't Make Up.
320  * or
321  * "George, you can type this shit, but you can't say it" -- Harrison Ford
322  *
323  * There are 5 VMCS 32-bit words that control guest permissions. If
324  * you set these correctly, you've got a guest that will behave. If
325  * you get even one bit wrong, you've got a guest that will chew your
326  * leg off. Some bits must be 1, some must be 0, and some can be set
327  * either way. To add to the fun, the docs are sort of a docudrama or,
328  * as the quote goes, "interesting if true."
329  *
330  * To determine what bit can be set in what VMCS 32-bit control word,
331  * there are 5 corresponding 64-bit MSRs.  And, to make it even more
332  * fun, the standard set of MSRs have errors in them, i.e. report
333  * incorrect values, for legacy reasons, and so you are supposed to
334  * "look around" to another set, which have correct bits in
335  * them. There are four such 'correct' registers, and they have _TRUE_
336  * in the names as you can see below. We test for the value of VMCS
337  * control bits in the _TRUE_ registers if possible. The fifth
338  * register, CPU Secondary Exec Controls, which came later, needs no
339  * _TRUE_ variant.
340  *
341  * For each MSR, the high 32 bits tell you what bits can be "1" by a
342  * "1" in that position; the low 32 bits tell you what bit can be "0"
343  * by a "0" in that position. So, for each of 32 bits in a given VMCS
344  * control word, there is a pair of bits in an MSR that tells you what
345  * values it can take. The two bits, of which there are *four*
346  * combinations, describe the *three* possible operations on a
347  * bit. The two bits, taken together, form an untruth table: There are
348  * three possibilities: The VMCS bit can be set to 0 or 1, or it can
349  * only be 0, or only 1. The fourth combination is not supposed to
350  * happen.
351  *
352  * So: there is the 1 bit from the upper 32 bits of the msr.
353  * If this bit is set, then the bit can be 1. If clear, it can not be 1.
354  *
355  * Then there is the 0 bit, from low 32 bits. If clear, the VMCS bit
356  * can be 0. If 1, the VMCS bit can not be 0.
357  *
358  * SO, let's call the 1 bit R1, and the 0 bit R0, we have:
359  *  R1 R0
360  *  0 0 -> must be 0
361  *  1 0 -> can be 1, can be 0
362  *  0 1 -> can not be 1, can not be 0. --> JACKPOT! Not seen yet.
363  *  1 1 -> must be one.
364  *
365  * It's also pretty hard to know what you can and can't set, and
366  * that's led to inadvertant opening of permissions at times.  Because
367  * of this complexity we've decided on the following: the driver must
368  * define EVERY bit, UNIQUELY, for each of the 5 registers, that it wants
369  * set. Further, for any bit that's settable, the driver must specify
370  * a setting; for any bit that's reserved, the driver settings must
371  * match that bit. If there are reserved bits we don't specify, that's
372  * ok; we'll take them as is.
373  *
374  * We use a set-means-set, and set-means-clear model, i.e. we use a
375  * 32-bit word to contain the bits we want to be 1, indicated by one;
376  * and another 32-bit word in which a bit we want to be 0 is indicated
377  * by a 1. This allows us to easily create masks of all bits we're
378  * going to set, for example.
379  *
380  * We have two 32-bit numbers for each 32-bit VMCS field: bits we want
381  * set and bits we want clear.  If you read the MSR for that field,
382  * compute the reserved 0 and 1 settings, and | them together, they
383  * need to result in 0xffffffff. You can see that we can create other
384  * tests for conflicts (i.e. overlap).
385  *
386  * At this point, I've tested check_vmx_controls in every way
387  * possible, beause I kept screwing the bitfields up. You'll get a nice
388  * error it won't work at all, which is what we want: a
389  * failure-prone setup, where even errors that might result in correct
390  * values are caught -- "right answer, wrong method, zero credit." If there's
391  * weirdness in the bits, we don't want to run.
392  */
393
394 static bool check_vmxec_controls(struct vmxec const *v, bool have_true_msr,
395                                  uint32_t *result)
396 {
397         bool err = false;
398         uint32_t vmx_msr_low, vmx_msr_high;
399         uint32_t reserved_0, reserved_1, changeable_bits;
400
401         if (have_true_msr)
402                 rdmsr(v->truemsr, vmx_msr_low, vmx_msr_high);
403         else
404                 rdmsr(v->msr, vmx_msr_low, vmx_msr_high);
405
406         if (vmx_msr_low & ~vmx_msr_high)
407                 warn("JACKPOT: Conflicting VMX ec ctls for %s, high 0x%08x low 0x%08x",
408                      v->name, vmx_msr_high, vmx_msr_low);
409
410         reserved_0 = (~vmx_msr_low) & (~vmx_msr_high);
411         reserved_1 = vmx_msr_low & vmx_msr_high;
412         changeable_bits = ~(reserved_0 | reserved_1);
413
414         /*
415          * this is very much as follows:
416          * accept the things I cannot change,
417          * change the things I can,
418          * know the difference.
419          */
420
421         /* Conflict. Don't try to both set and reset bits. */
422         if (v->set_to_0 & v->set_to_1) {
423                 printk("%s: set to 0 (0x%x) and set to 1 (0x%x) overlap: 0x%x\n",
424                        v->name, v->set_to_0, v->set_to_1, v->set_to_0 & v->set_to_1);
425                 err = true;
426         }
427
428         /* coverage */
429         if (((v->set_to_0 | v->set_to_1) & changeable_bits) !=
430             changeable_bits) {
431                 printk("%s: Need to cover 0x%x and have 0x%x,0x%x\n",
432                        v->name, changeable_bits, v->set_to_0,  v->set_to_1);
433                 err = true;
434         }
435
436         if ((v->set_to_0 | v->set_to_1 | reserved_0 | reserved_1) !=
437             0xffffffff) {
438                 printk("%s: incomplete coverage: have 0x%x, want 0x%x\n",
439                        v->name, v->set_to_0 | v->set_to_1 |
440                        reserved_0 | reserved_1, 0xffffffff);
441                 err = true;
442         }
443
444         /* Don't try to change bits that can't be changed. */
445         if ((v->set_to_0 & (reserved_0 | changeable_bits)) != v->set_to_0) {
446                 printk("%s: set to 0 (0x%x) can't be done\n", v->name,
447                         v->set_to_0);
448                 err = true;
449         }
450
451         if ((v->set_to_1 & (reserved_1 | changeable_bits)) != v->set_to_1) {
452                 printk("%s: set to 1 (0x%x) can't be done\n",
453                        v->name, v->set_to_1);
454                 err = true;
455         }
456
457         /* If there's been any error at all, spill our guts and return. */
458         if (err) {
459                 printk("%s: vmx_msr_high 0x%x, vmx_msr_low 0x%x, ",
460                        v->name, vmx_msr_high, vmx_msr_low);
461                 printk("set_to_1 0x%x,set_to_0 0x%x,reserved_1 0x%x",
462                        v->set_to_1, v->set_to_0, reserved_1);
463                 printk(" reserved_0 0x%x", reserved_0);
464                 printk(" changeable_bits 0x%x\n", changeable_bits);
465                 return false;
466         }
467
468         *result = v->set_to_1 | reserved_1;
469
470         printd("%s: check_vmxec_controls succeeds with result 0x%x\n",
471                v->name, *result);
472         return true;
473 }
474
475 /*
476  * We're trying to make this as readable as possible. Realistically, it will
477  * rarely if ever change, if the past is any guide.
478  */
479 static const struct vmxec pbec = {
480         .name = "Pin Based Execution Controls",
481         .msr = MSR_IA32_VMX_PINBASED_CTLS,
482         .truemsr = MSR_IA32_VMX_TRUE_PINBASED_CTLS,
483
484         .set_to_1 = (PIN_BASED_EXT_INTR_MASK |
485                      PIN_BASED_NMI_EXITING |
486                      PIN_BASED_VIRTUAL_NMIS),
487
488         .set_to_0 = (PIN_BASED_VMX_PREEMPTION_TIMER |
489                      PIN_BASED_POSTED_INTR),
490 };
491
492 static const struct vmxec cbec = {
493         .name = "CPU Based Execution Controls",
494         .msr = MSR_IA32_VMX_PROCBASED_CTLS,
495         .truemsr = MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
496
497         .set_to_1 = (CPU_BASED_HLT_EXITING |
498                      CPU_BASED_MWAIT_EXITING |
499                      CPU_BASED_RDPMC_EXITING |
500                      CPU_BASED_CR8_LOAD_EXITING |
501                      CPU_BASED_CR8_STORE_EXITING |
502                      CPU_BASED_USE_MSR_BITMAPS |
503                      CPU_BASED_MONITOR_EXITING |
504                      CPU_BASED_USE_IO_BITMAPS |
505                      CPU_BASED_ACTIVATE_SECONDARY_CONTROLS),
506
507         .set_to_0 = (CPU_BASED_VIRTUAL_INTR_PENDING |
508                      CPU_BASED_INVLPG_EXITING |
509                      CPU_BASED_USE_TSC_OFFSETING |
510                      CPU_BASED_RDTSC_EXITING |
511                      CPU_BASED_CR3_LOAD_EXITING |
512                      CPU_BASED_CR3_STORE_EXITING |
513                      CPU_BASED_TPR_SHADOW |
514                      CPU_BASED_MOV_DR_EXITING |
515                      CPU_BASED_VIRTUAL_NMI_PENDING |
516                      CPU_BASED_MONITOR_TRAP |
517                      CPU_BASED_PAUSE_EXITING |
518                      CPU_BASED_UNCOND_IO_EXITING),
519 };
520
521 static const struct vmxec cb2ec = {
522         .name = "CPU Based 2nd Execution Controls",
523         .msr = MSR_IA32_VMX_PROCBASED_CTLS2,
524         .truemsr = MSR_IA32_VMX_PROCBASED_CTLS2,
525
526         .set_to_1 = (SECONDARY_EXEC_ENABLE_EPT |
527                      SECONDARY_EXEC_WBINVD_EXITING),
528
529         .set_to_0 = (SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
530                      SECONDARY_EXEC_DESCRIPTOR_EXITING |
531                      SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
532                      SECONDARY_EXEC_ENABLE_VPID |
533                      SECONDARY_EXEC_UNRESTRICTED_GUEST |
534                      SECONDARY_EXEC_APIC_REGISTER_VIRT |
535                      SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
536                      SECONDARY_EXEC_PAUSE_LOOP_EXITING |
537                      SECONDARY_EXEC_RDRAND_EXITING |
538                      SECONDARY_EXEC_ENABLE_INVPCID |
539                      SECONDARY_EXEC_ENABLE_VMFUNC |
540                      SECONDARY_EXEC_SHADOW_VMCS |
541                      SECONDARY_EXEC_RDSEED_EXITING |
542                      SECONDARY_EPT_VE |
543                      /* TODO: re enable this via a "Want" struct
544                         member at some point */
545                      SECONDARY_EXEC_RDTSCP |
546                      SECONDARY_ENABLE_XSAV_RESTORE)
547 };
548
549 static const struct vmxec vmentry = {
550         .name = "VMENTRY controls",
551         .msr = MSR_IA32_VMX_ENTRY_CTLS,
552         .truemsr = MSR_IA32_VMX_TRUE_ENTRY_CTLS,
553         /* exact order from vmx.h; only the first two are enabled. */
554
555         .set_to_1 =  (VM_ENTRY_LOAD_DEBUG_CONTROLS | /* can't set to 0 */
556                       VM_ENTRY_LOAD_IA32_EFER |
557                       VM_ENTRY_IA32E_MODE),
558
559         .set_to_0 = (VM_ENTRY_SMM |
560                      VM_ENTRY_DEACT_DUAL_MONITOR |
561                      VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
562                      VM_ENTRY_LOAD_IA32_PAT),
563 };
564
565 static const struct vmxec vmexit = {
566         .name = "VMEXIT controls",
567         .msr = MSR_IA32_VMX_EXIT_CTLS,
568         .truemsr = MSR_IA32_VMX_TRUE_EXIT_CTLS,
569
570         .set_to_1 = (VM_EXIT_SAVE_DEBUG_CONTROLS | /* can't set to 0 */
571                      VM_EXIT_SAVE_IA32_EFER |
572                      VM_EXIT_LOAD_IA32_EFER |
573                      VM_EXIT_HOST_ADDR_SPACE_SIZE), /* 64 bit */
574
575         .set_to_0 = (VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
576                      VM_EXIT_ACK_INTR_ON_EXIT |
577                      VM_EXIT_SAVE_IA32_PAT |
578                      VM_EXIT_LOAD_IA32_PAT |
579                      VM_EXIT_SAVE_VMX_PREEMPTION_TIMER),
580 };
581
582 static void setup_vmcs_config(void *p)
583 {
584         int *ret = p;
585         struct vmcs_config *vmcs_conf = &vmcs_config;
586         uint32_t vmx_msr_high;
587         uint64_t vmx_msr;
588         bool have_true_msrs = false;
589         bool ok;
590
591         *ret = -EIO;
592
593         vmx_msr = read_msr(MSR_IA32_VMX_BASIC);
594         vmx_msr_high = vmx_msr >> 32;
595
596         /*
597          * If bit 55 (VMX_BASIC_HAVE_TRUE_MSRS) is set, then we
598          * can go for the true MSRs.  Else, we ask you to get a better CPU.
599          */
600         if (vmx_msr & VMX_BASIC_TRUE_CTLS) {
601                 have_true_msrs = true;
602                 printd("Running with TRUE MSRs\n");
603         } else {
604                 printk("Running with non-TRUE MSRs, this is old hardware\n");
605         }
606
607         /*
608          * Don't worry that one or more of these might fail and leave
609          * the VMCS in some kind of incomplete state. If one of these
610          * fails, the caller is going to discard the VMCS.
611          * It is written this way to ensure we get results of all tests and avoid
612          * BMAFR behavior.
613          */
614         ok = check_vmxec_controls(&pbec, have_true_msrs,
615                                   &vmcs_conf->pin_based_exec_ctrl);
616         ok = check_vmxec_controls(&cbec, have_true_msrs,
617                                   &vmcs_conf->cpu_based_exec_ctrl) && ok;
618         /* Only check cb2ec if we're still ok, o/w we may GPF */
619         ok = ok && check_vmxec_controls(&cb2ec, have_true_msrs,
620                                         &vmcs_conf->cpu_based_2nd_exec_ctrl);
621         ok = check_vmxec_controls(&vmentry, have_true_msrs,
622                                   &vmcs_conf->vmentry_ctrl) && ok;
623         ok = check_vmxec_controls(&vmexit, have_true_msrs,
624                                   &vmcs_conf->vmexit_ctrl) && ok;
625         if (! ok) {
626                 printk("vmxexec controls is no good.\n");
627                 return;
628         }
629
630         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
631         if ((vmx_msr_high & 0x1fff) > PGSIZE) {
632                 printk("vmx_msr_high & 0x1fff) is 0x%x, > PAGE_SIZE 0x%x\n",
633                        vmx_msr_high & 0x1fff, PGSIZE);
634                 return;
635         }
636
637         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
638         if (vmx_msr & VMX_BASIC_64) {
639                 printk("VMX doesn't support 64 bit width!\n");
640                 return;
641         }
642
643         if (((vmx_msr & VMX_BASIC_MEM_TYPE_MASK) >> VMX_BASIC_MEM_TYPE_SHIFT)
644             != VMX_BASIC_MEM_TYPE_WB) {
645                 printk("VMX doesn't support WB memory for VMCS accesses!\n");
646                 return;
647         }
648
649         vmcs_conf->size = vmx_msr_high & 0x1fff;
650         vmcs_conf->order = LOG2_UP(nr_pages(vmcs_config.size));
651         vmcs_conf->revision_id = (uint32_t)vmx_msr;
652
653         /* Read in the caps for runtime checks.  This MSR is only available if
654          * secondary controls and ept or vpid is on, which we check earlier */
655         rdmsr(MSR_IA32_VMX_EPT_VPID_CAP, vmx_capability.ept, vmx_capability.vpid);
656
657         *ret = 0;
658 }
659
660 static struct vmcs *__vmx_alloc_vmcs(int node)
661 {
662         struct vmcs *vmcs;
663
664         vmcs = get_cont_pages_node(node, vmcs_config.order, KMALLOC_WAIT);
665         if (!vmcs)
666                 return 0;
667         memset(vmcs, 0, vmcs_config.size);
668         vmcs->revision_id = vmcs_config.revision_id;    /* vmcs revision id */
669         printd("%d: set rev id %d\n", core_id(), vmcs->revision_id);
670         return vmcs;
671 }
672
673 /**
674  * vmx_alloc_vmcs - allocates a VMCS region
675  *
676  * NOTE: Assumes the new region will be used by the current CPU.
677  *
678  * Returns a valid VMCS region.
679  */
680 static struct vmcs *vmx_alloc_vmcs(void)
681 {
682         return __vmx_alloc_vmcs(numa_id());
683 }
684
685 /**
686  * vmx_free_vmcs - frees a VMCS region
687  */
688 static void vmx_free_vmcs(struct vmcs *vmcs)
689 {
690   //free_pages((unsigned long)vmcs, vmcs_config.order);
691 }
692
693 /*
694  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
695  * will not change in the lifetime of the guest.
696  * Note that host-state that does change is set elsewhere. E.g., host-state
697  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
698  */
699 static void vmx_setup_constant_host_state(void)
700 {
701         uint32_t low32, high32;
702         unsigned long tmpl;
703         pseudodesc_t dt;
704
705         vmcs_writel(HOST_CR0, rcr0() & ~X86_CR0_TS);  /* 22.2.3 */
706         vmcs_writel(HOST_CR4, rcr4());  /* 22.2.3, 22.2.5 */
707         vmcs_writel(HOST_CR3, rcr3());  /* 22.2.3 */
708
709         vmcs_write16(HOST_CS_SELECTOR, GD_KT);  /* 22.2.4 */
710         vmcs_write16(HOST_DS_SELECTOR, GD_KD);  /* 22.2.4 */
711         vmcs_write16(HOST_ES_SELECTOR, GD_KD);  /* 22.2.4 */
712         vmcs_write16(HOST_SS_SELECTOR, GD_KD);  /* 22.2.4 */
713         vmcs_write16(HOST_TR_SELECTOR, GD_TSS);  /* 22.2.4 */
714
715         native_store_idt(&dt);
716         vmcs_writel(HOST_IDTR_BASE, dt.pd_base);   /* 22.2.4 */
717
718         asm("mov $.Lkvm_vmx_return, %0" : "=r"(tmpl));
719         vmcs_writel(HOST_RIP, tmpl); /* 22.2.5 */
720
721         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
722         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
723         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
724         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
725
726         rdmsr(MSR_EFER, low32, high32);
727         vmcs_write32(HOST_IA32_EFER, low32);
728
729         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
730                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
731                 vmcs_write64(HOST_IA32_PAT, low32 | ((uint64_t) high32 << 32));
732         }
733
734         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
735         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
736
737         /* TODO: This (at least gs) is per cpu */
738         rdmsrl(MSR_FS_BASE, tmpl);
739         vmcs_writel(HOST_FS_BASE, tmpl); /* 22.2.4 */
740         rdmsrl(MSR_GS_BASE, tmpl);
741         vmcs_writel(HOST_GS_BASE, tmpl); /* 22.2.4 */
742 }
743
744 static inline uint16_t vmx_read_ldt(void)
745 {
746         uint16_t ldt;
747         asm("sldt %0" : "=g"(ldt));
748         return ldt;
749 }
750
751 static unsigned long segment_base(uint16_t selector)
752 {
753         pseudodesc_t *gdt = &currentcpu->host_gdt;
754         struct desc_struct *d;
755         unsigned long table_base;
756         unsigned long v;
757
758         if (!(selector & ~3)) {
759                 return 0;
760         }
761
762         table_base = gdt->pd_base;
763
764         if (selector & 4) {           /* from ldt */
765                 uint16_t ldt_selector = vmx_read_ldt();
766
767                 if (!(ldt_selector & ~3)) {
768                         return 0;
769                 }
770
771                 table_base = segment_base(ldt_selector);
772         }
773         d = (struct desc_struct *)(table_base + (selector & ~7));
774         v = get_desc_base(d);
775         if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
776                 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
777         return v;
778 }
779
780 static inline unsigned long vmx_read_tr_base(void)
781 {
782         uint16_t tr;
783         asm("str %0" : "=g"(tr));
784         return segment_base(tr);
785 }
786
787 static void __vmx_setup_cpu(void)
788 {
789         pseudodesc_t *gdt = &currentcpu->host_gdt;
790         unsigned long sysenter_esp;
791         unsigned long tmpl;
792
793         /*
794          * Linux uses per-cpu TSS and GDT, so set these when switching
795          * processors.
796          */
797         vmcs_writel(HOST_TR_BASE, vmx_read_tr_base()); /* 22.2.4 */
798         vmcs_writel(HOST_GDTR_BASE, gdt->pd_base);   /* 22.2.4 */
799
800         rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
801         vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
802
803         rdmsrl(MSR_FS_BASE, tmpl);
804         vmcs_writel(HOST_FS_BASE, tmpl); /* 22.2.4 */
805         rdmsrl(MSR_GS_BASE, tmpl);
806         vmcs_writel(HOST_GS_BASE, tmpl); /* 22.2.4 */
807 }
808
809 /**
810  * vmx_get_cpu - called before using a cpu
811  * @vcpu: VCPU that will be loaded.
812  *
813  * Disables preemption. Call vmx_put_cpu() when finished.
814  */
815 static void vmx_get_cpu(struct vmx_vcpu *vcpu)
816 {
817         int cur_cpu = core_id();
818         handler_wrapper_t *w;
819
820         if (currentcpu->local_vcpu)
821                 panic("get_cpu: currentcpu->localvcpu was non-NULL");
822         if (currentcpu->local_vcpu != vcpu) {
823                 currentcpu->local_vcpu = vcpu;
824
825                 if (vcpu->cpu != cur_cpu) {
826                         if (vcpu->cpu >= 0) {
827                                 panic("vcpu->cpu is not -1, it's %d\n", vcpu->cpu);
828                         } else
829                                 vmcs_clear(vcpu->vmcs);
830
831                         ept_sync_context(vcpu_get_eptp(vcpu));
832
833                         vcpu->launched = 0;
834                         vmcs_load(vcpu->vmcs);
835                         __vmx_setup_cpu();
836                         vcpu->cpu = cur_cpu;
837                 } else {
838                         vmcs_load(vcpu->vmcs);
839                 }
840         }
841 }
842
843 /**
844  * vmx_put_cpu - called after using a cpu
845  * @vcpu: VCPU that was loaded.
846  */
847 static void vmx_put_cpu(struct vmx_vcpu *vcpu)
848 {
849         if (core_id() != vcpu->cpu)
850                 panic("%s: core_id() %d != vcpu->cpu %d\n",
851                       __func__, core_id(), vcpu->cpu);
852
853         if (currentcpu->local_vcpu != vcpu)
854                 panic("vmx_put_cpu: asked to clear something not ours");
855
856         ept_sync_context(vcpu_get_eptp(vcpu));
857         vmcs_clear(vcpu->vmcs);
858         vcpu->cpu = -1;
859         currentcpu->local_vcpu = NULL;
860         //put_cpu();
861 }
862
863 /**
864  * vmx_dump_cpu - prints the CPU state
865  * @vcpu: VCPU to print
866  */
867 static void vmx_dump_cpu(struct vmx_vcpu *vcpu)
868 {
869
870         unsigned long flags;
871
872         vmx_get_cpu(vcpu);
873         vcpu->regs.tf_rip = vmcs_readl(GUEST_RIP);
874         vcpu->regs.tf_rsp = vmcs_readl(GUEST_RSP);
875         flags = vmcs_readl(GUEST_RFLAGS);
876         vmx_put_cpu(vcpu);
877
878         printk("--- Begin VCPU Dump ---\n");
879         printk("CPU %d VPID %d\n", vcpu->cpu, 0);
880         printk("RIP 0x%016lx RFLAGS 0x%08lx\n",
881                vcpu->regs.tf_rip, flags);
882         printk("RAX 0x%016lx RCX 0x%016lx\n",
883                 vcpu->regs.tf_rax, vcpu->regs.tf_rcx);
884         printk("RDX 0x%016lx RBX 0x%016lx\n",
885                 vcpu->regs.tf_rdx, vcpu->regs.tf_rbx);
886         printk("RSP 0x%016lx RBP 0x%016lx\n",
887                 vcpu->regs.tf_rsp, vcpu->regs.tf_rbp);
888         printk("RSI 0x%016lx RDI 0x%016lx\n",
889                 vcpu->regs.tf_rsi, vcpu->regs.tf_rdi);
890         printk("R8  0x%016lx R9  0x%016lx\n",
891                 vcpu->regs.tf_r8, vcpu->regs.tf_r9);
892         printk("R10 0x%016lx R11 0x%016lx\n",
893                 vcpu->regs.tf_r10, vcpu->regs.tf_r11);
894         printk("R12 0x%016lx R13 0x%016lx\n",
895                 vcpu->regs.tf_r12, vcpu->regs.tf_r13);
896         printk("R14 0x%016lx R15 0x%016lx\n",
897                 vcpu->regs.tf_r14, vcpu->regs.tf_r15);
898         printk("--- End VCPU Dump ---\n");
899
900 }
901
902 uint64_t construct_eptp(physaddr_t root_hpa)
903 {
904         uint64_t eptp;
905
906         /* set WB memory and 4 levels of walk.  we checked these in ept_init */
907         eptp = VMX_EPT_MEM_TYPE_WB |
908                (VMX_EPT_GAW_4_LVL << VMX_EPT_GAW_EPTP_SHIFT);
909         if (cpu_has_vmx_ept_ad_bits())
910                 eptp |= VMX_EPT_AD_ENABLE_BIT;
911         eptp |= (root_hpa & PAGE_MASK);
912
913         return eptp;
914 }
915
916 /**
917  * vmx_setup_initial_guest_state - configures the initial state of guest registers
918  */
919 static void vmx_setup_initial_guest_state(void)
920 {
921         unsigned long tmpl;
922         unsigned long cr4 = X86_CR4_PAE | X86_CR4_VMXE | X86_CR4_OSXMMEXCPT |
923                             X86_CR4_PGE | X86_CR4_OSFXSR;
924         uint32_t protected_mode = X86_CR0_PG | X86_CR0_PE;
925 #if 0
926         do we need it
927         if (boot_cpu_has(X86_FEATURE_PCID))
928                 cr4 |= X86_CR4_PCIDE;
929         if (boot_cpu_has(X86_FEATURE_OSXSAVE))
930                 cr4 |= X86_CR4_OSXSAVE;
931 #endif
932         /* we almost certainly have this */
933         /* we'll go sour if we don't. */
934         if (1) //boot_cpu_has(X86_FEATURE_FSGSBASE))
935                 cr4 |= X86_CR4_RDWRGSFS;
936
937         /* configure control and data registers */
938         vmcs_writel(GUEST_CR0, protected_mode | X86_CR0_WP |
939                                X86_CR0_MP | X86_CR0_ET | X86_CR0_NE);
940         vmcs_writel(CR0_READ_SHADOW, protected_mode | X86_CR0_WP |
941                                      X86_CR0_MP | X86_CR0_ET | X86_CR0_NE);
942         vmcs_writel(GUEST_CR3, rcr3());
943         vmcs_writel(GUEST_CR4, cr4);
944         vmcs_writel(CR4_READ_SHADOW, cr4);
945         vmcs_writel(GUEST_IA32_EFER, EFER_LME | EFER_LMA |
946                     EFER_SCE /*| EFER_FFXSR*/);
947         vmcs_writel(GUEST_GDTR_BASE, 0);
948         vmcs_writel(GUEST_GDTR_LIMIT, 0);
949         vmcs_writel(GUEST_IDTR_BASE, 0);
950         vmcs_writel(GUEST_IDTR_LIMIT, 0);
951         vmcs_writel(GUEST_RIP, 0xdeadbeef);
952         vmcs_writel(GUEST_RSP, 0xdeadbeef);
953         vmcs_writel(GUEST_RFLAGS, 0x02);
954         vmcs_writel(GUEST_DR7, 0);
955
956         /* guest segment bases */
957         vmcs_writel(GUEST_CS_BASE, 0);
958         vmcs_writel(GUEST_DS_BASE, 0);
959         vmcs_writel(GUEST_ES_BASE, 0);
960         vmcs_writel(GUEST_GS_BASE, 0);
961         vmcs_writel(GUEST_SS_BASE, 0);
962         rdmsrl(MSR_FS_BASE, tmpl);
963         vmcs_writel(GUEST_FS_BASE, tmpl);
964
965         /* guest segment access rights */
966         vmcs_writel(GUEST_CS_AR_BYTES, 0xA09B);
967         vmcs_writel(GUEST_DS_AR_BYTES, 0xA093);
968         vmcs_writel(GUEST_ES_AR_BYTES, 0xA093);
969         vmcs_writel(GUEST_FS_AR_BYTES, 0xA093);
970         vmcs_writel(GUEST_GS_AR_BYTES, 0xA093);
971         vmcs_writel(GUEST_SS_AR_BYTES, 0xA093);
972
973         /* guest segment limits */
974         vmcs_write32(GUEST_CS_LIMIT, 0xFFFFFFFF);
975         vmcs_write32(GUEST_DS_LIMIT, 0xFFFFFFFF);
976         vmcs_write32(GUEST_ES_LIMIT, 0xFFFFFFFF);
977         vmcs_write32(GUEST_FS_LIMIT, 0xFFFFFFFF);
978         vmcs_write32(GUEST_GS_LIMIT, 0xFFFFFFFF);
979         vmcs_write32(GUEST_SS_LIMIT, 0xFFFFFFFF);
980
981         /* configure segment selectors */
982         vmcs_write16(GUEST_CS_SELECTOR, 0);
983         vmcs_write16(GUEST_DS_SELECTOR, 0);
984         vmcs_write16(GUEST_ES_SELECTOR, 0);
985         vmcs_write16(GUEST_FS_SELECTOR, 0);
986         vmcs_write16(GUEST_GS_SELECTOR, 0);
987         vmcs_write16(GUEST_SS_SELECTOR, 0);
988         vmcs_write16(GUEST_TR_SELECTOR, 0);
989
990         /* guest LDTR */
991         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
992         vmcs_writel(GUEST_LDTR_AR_BYTES, 0x0082);
993         vmcs_writel(GUEST_LDTR_BASE, 0);
994         vmcs_writel(GUEST_LDTR_LIMIT, 0);
995
996         /* guest TSS */
997         vmcs_writel(GUEST_TR_BASE, 0);
998         vmcs_writel(GUEST_TR_AR_BYTES, 0x0080 | AR_TYPE_BUSY_64_TSS);
999         vmcs_writel(GUEST_TR_LIMIT, 0xff);
1000
1001         /* initialize sysenter */
1002         vmcs_write32(GUEST_SYSENTER_CS, 0);
1003         vmcs_writel(GUEST_SYSENTER_ESP, 0);
1004         vmcs_writel(GUEST_SYSENTER_EIP, 0);
1005
1006         /* other random initialization */
1007         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1008         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
1009         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
1010         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
1011         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
1012 }
1013
1014 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap, uint32_t msr)
1015 {
1016         int f = sizeof(unsigned long);
1017         /*
1018          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
1019          * have the write-low and read-high bitmap offsets the wrong way round.
1020          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
1021          */
1022         if (msr <= 0x1fff) {
1023                 __clear_bit(msr, msr_bitmap + 0x000 / f); /* read-low */
1024                 __clear_bit(msr, msr_bitmap + 0x800 / f); /* write-low */
1025         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1026                 msr &= 0x1fff;
1027                 __clear_bit(msr, msr_bitmap + 0x400 / f); /* read-high */
1028                 __clear_bit(msr, msr_bitmap + 0xc00 / f); /* write-high */
1029         }
1030 }
1031
1032 /* note the io_bitmap is big enough for the 64K port space. */
1033 static void __vmx_disable_intercept_for_io(unsigned long *io_bitmap, uint16_t port)
1034 {
1035         __clear_bit(port, io_bitmap);
1036 }
1037
1038 static void vcpu_print_autoloads(struct vmx_vcpu *vcpu)
1039 {
1040         struct vmx_msr_entry *e;
1041         int sz = sizeof(autoloaded_msrs) / sizeof(*autoloaded_msrs);
1042         printk("Host Autoloads:\n-------------------\n");
1043         for (int i = 0; i < sz; i++) {
1044                 e = &vcpu->msr_autoload.host[i];
1045                 printk("\tMSR 0x%08x: %p\n", e->index, e->value);
1046         }
1047         printk("Guest Autoloads:\n-------------------\n");
1048         for (int i = 0; i < sz; i++) {
1049                 e = &vcpu->msr_autoload.guest[i];
1050                 printk("\tMSR 0x%08x %p\n", e->index, e->value);
1051         }
1052 }
1053
1054 static void dumpmsrs(void)
1055 {
1056         int i;
1057         int set[] = {
1058                 MSR_LSTAR,
1059                 MSR_FS_BASE,
1060                 MSR_GS_BASE,
1061                 MSR_KERNEL_GS_BASE,
1062                 MSR_SFMASK,
1063                 MSR_IA32_PEBS_ENABLE
1064         };
1065         for(i = 0; i < ARRAY_SIZE(set); i++) {
1066                 printk("%p: %p\n", set[i], read_msr(set[i]));
1067         }
1068         printk("core id %d\n", core_id());
1069 }
1070
1071 /* emulated msr. For now, an msr value and a pointer to a helper that
1072  * performs the requested operation.
1073  */
1074 struct emmsr {
1075         uint32_t reg;
1076         char *name;
1077         int (*f)(struct vmx_vcpu *vcpu, struct emmsr *, uint32_t, uint32_t);
1078         bool written;
1079         uint32_t edx, eax;
1080 };
1081
1082 int emsr_mustmatch(struct vmx_vcpu *vcpu, struct emmsr *, uint32_t, uint32_t);
1083 int emsr_readonly(struct vmx_vcpu *vcpu, struct emmsr *, uint32_t, uint32_t);
1084 int emsr_fakewrite(struct vmx_vcpu *vcpu, struct emmsr *, uint32_t, uint32_t);
1085 int emsr_ok(struct vmx_vcpu *vcpu, struct emmsr *, uint32_t, uint32_t);
1086
1087 struct emmsr emmsrs[] = {
1088         {MSR_IA32_MISC_ENABLE, "MSR_IA32_MISC_ENABLE", emsr_mustmatch},
1089         {MSR_IA32_SYSENTER_CS, "MSR_IA32_SYSENTER_CS", emsr_ok},
1090         {MSR_IA32_SYSENTER_EIP, "MSR_IA32_SYSENTER_EIP", emsr_ok},
1091         {MSR_IA32_SYSENTER_ESP, "MSR_IA32_SYSENTER_ESP", emsr_ok},
1092         {MSR_IA32_UCODE_REV, "MSR_IA32_UCODE_REV", emsr_fakewrite},
1093         {MSR_CSTAR, "MSR_CSTAR", emsr_fakewrite},
1094         {MSR_IA32_VMX_BASIC_MSR, "MSR_IA32_VMX_BASIC_MSR", emsr_fakewrite},
1095         {MSR_IA32_VMX_PINBASED_CTLS_MSR, "MSR_IA32_VMX_PINBASED_CTLS_MSR", emsr_fakewrite},
1096         {MSR_IA32_VMX_PROCBASED_CTLS_MSR, "MSR_IA32_VMX_PROCBASED_CTLS_MSR", emsr_fakewrite},
1097         {MSR_IA32_VMX_PROCBASED_CTLS2, "MSR_IA32_VMX_PROCBASED_CTLS2", emsr_fakewrite},
1098         {MSR_IA32_VMX_EXIT_CTLS_MSR, "MSR_IA32_VMX_EXIT_CTLS_MSR", emsr_fakewrite},
1099         {MSR_IA32_VMX_ENTRY_CTLS_MSR, "MSR_IA32_VMX_ENTRY_CTLS_MSR", emsr_fakewrite},
1100         {MSR_IA32_ENERGY_PERF_BIAS, "MSR_IA32_ENERGY_PERF_BIAS", emsr_fakewrite},
1101
1102 };
1103
1104 #define set_low32(hi,lo) (((hi) & 0xffffffff00000000ULL ) | (lo))
1105 int emsr_mustmatch(struct vmx_vcpu *vcpu, struct emmsr *msr, uint32_t opcode, uint32_t qual)
1106 {
1107         uint32_t eax, edx;
1108         rdmsr(msr->reg, eax, edx);
1109         /* we just let them read the misc msr for now. */
1110         if (opcode == EXIT_REASON_MSR_READ) {
1111                 vcpu->regs.tf_rax = set_low32(vcpu->regs.tf_rax, eax);
1112                 vcpu->regs.tf_rdx = set_low32(vcpu->regs.tf_rdx, edx);
1113                 return 0;
1114         } else {
1115                 /* if they are writing what is already written, that's ok. */
1116                 if (((uint32_t)vcpu->regs.tf_rax == eax) && ((uint32_t)vcpu->regs.tf_rdx == edx))
1117                         return 0;
1118         }
1119         printk("%s: Wanted to write 0x%x:0x%x, but could not; value was 0x%x:0x%x\n",
1120                 msr->name, (uint32_t)vcpu->regs.tf_rdx, (uint32_t)vcpu->regs.tf_rax, edx, eax);
1121         return SHUTDOWN_UNHANDLED_EXIT_REASON;
1122 }
1123
1124 int emsr_ok(struct vmx_vcpu *vcpu, struct emmsr *msr, uint32_t opcode, uint32_t qual)
1125 {
1126         if (opcode == EXIT_REASON_MSR_READ) {
1127                 rdmsr(msr->reg, vcpu->regs.tf_rdx, vcpu->regs.tf_rax);
1128         } else {
1129                 uint64_t val = (uint64_t)vcpu->regs.tf_rdx<<32 | vcpu->regs.tf_rax;
1130                 write_msr(msr->reg, val);
1131         }
1132         return 0;
1133 }
1134
1135 /* return what's there. Let them think they are writing it if they are not changing anything. */
1136 int emsr_readonly(struct vmx_vcpu *vcpu, struct emmsr *msr, uint32_t opcode, uint32_t qual)
1137 {
1138         uint32_t eax, edx;
1139         rdmsr((uint32_t)vcpu->regs.tf_rcx, eax, edx);
1140         /* we just let them read the misc msr for now. */
1141         if (opcode == EXIT_REASON_MSR_READ) {
1142                 vcpu->regs.tf_rax = set_low32(vcpu->regs.tf_rax, eax);
1143                 vcpu->regs.tf_rdx = set_low32(vcpu->regs.tf_rdx, edx);
1144                 return 0;
1145         } else {
1146                 /* if they are writing what is already written, that's ok. */
1147                 if (((uint32_t)vcpu->regs.tf_rax == eax) && ((uint32_t)vcpu->regs.tf_rdx == edx))
1148                         return 0;
1149                 printk("%s write 0x%lx failed: msr is (0x%lx,0x%lx) and wanted (0x%lx,0x%lx)\n",
1150                         __func__, vcpu->regs.tf_rcx, edx, eax, (uint32_t)vcpu->regs.tf_rdx, (uint32_t)vcpu->regs.tf_rax);
1151         }
1152         return SHUTDOWN_UNHANDLED_EXIT_REASON;
1153 }
1154
1155 /* pretend to write it, but don't write it. */
1156 int emsr_fakewrite(struct vmx_vcpu *vcpu, struct emmsr *msr, uint32_t opcode, uint32_t qual)
1157 {
1158         uint32_t eax, edx;
1159         if (! msr->written) {
1160                 rdmsr(msr->reg, eax, edx);
1161         } else {
1162                 edx = msr->edx;
1163                 eax = msr->eax;
1164         }
1165         /* we just let them read the misc msr for now. */
1166         if (opcode == EXIT_REASON_MSR_READ) {
1167                 vcpu->regs.tf_rax = set_low32(vcpu->regs.tf_rax, eax);
1168                 vcpu->regs.tf_rdx = set_low32(vcpu->regs.tf_rdx, edx);
1169                 return 0;
1170         } else {
1171                 /* if they are writing what is already written, that's ok. */
1172                 if (((uint32_t)vcpu->regs.tf_rax == eax) && ((uint32_t)vcpu->regs.tf_rdx == edx))
1173                         return 0;
1174                 msr->edx = vcpu->regs.tf_rdx;
1175                 msr->eax = vcpu->regs.tf_rax;
1176                 msr->written = true;
1177         }
1178         return 0;
1179 }
1180
1181 int
1182 msrio(struct vmx_vcpu *vcpu, uint32_t opcode, uint32_t qual)
1183 {
1184         int i;
1185         for (i = 0; i < ARRAY_SIZE(emmsrs); i++) {
1186                 if (emmsrs[i].reg != vcpu->regs.tf_rcx)
1187                         continue;
1188                 return emmsrs[i].f(vcpu, &emmsrs[i], opcode, qual);
1189         }
1190         printk("msrio for 0x%lx failed\n", vcpu->regs.tf_rcx);
1191         return SHUTDOWN_UNHANDLED_EXIT_REASON;
1192 }
1193 /* Notes on autoloading.  We can't autoload FS_BASE or GS_BASE, according to the
1194  * manual, but that's because they are automatically saved and restored when all
1195  * of the other architectural registers are saved and restored, such as cs, ds,
1196  * es, and other fun things. (See 24.4.1).  We need to make sure we don't
1197  * accidentally intercept them too, since they are magically autloaded..
1198  *
1199  * We'll need to be careful of any MSR we neither autoload nor intercept
1200  * whenever we vmenter/vmexit, and we intercept by default.
1201  *
1202  * Other MSRs, such as MSR_IA32_PEBS_ENABLE only work on certain architectures
1203  * only work on certain architectures. */
1204 static void setup_msr(struct vmx_vcpu *vcpu)
1205 {
1206         struct vmx_msr_entry *e;
1207         int sz = sizeof(autoloaded_msrs) / sizeof(*autoloaded_msrs);
1208         int i;
1209
1210         static_assert((sizeof(autoloaded_msrs) / sizeof(*autoloaded_msrs)) <=
1211                       NR_AUTOLOAD_MSRS);
1212
1213         vcpu->msr_autoload.nr = sz;
1214
1215         /* Since PADDR(msr_bitmap) is non-zero, and the bitmap is all 0xff, we now
1216          * intercept all MSRs */
1217         vmcs_write64(MSR_BITMAP, PADDR(msr_bitmap));
1218
1219         vmcs_write64(IO_BITMAP_A, PADDR(io_bitmap));
1220         vmcs_write64(IO_BITMAP_B, PADDR((uintptr_t)io_bitmap +
1221                                         (VMX_IO_BITMAP_SZ / 2)));
1222
1223         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vcpu->msr_autoload.nr);
1224         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vcpu->msr_autoload.nr);
1225         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vcpu->msr_autoload.nr);
1226
1227         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, PADDR(vcpu->msr_autoload.host));
1228         vmcs_write64(VM_EXIT_MSR_STORE_ADDR, PADDR(vcpu->msr_autoload.guest));
1229         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, PADDR(vcpu->msr_autoload.guest));
1230
1231         for (i = 0; i < sz; i++) {
1232                 uint64_t val;
1233
1234                 e = &vcpu->msr_autoload.host[i];
1235                 e->index = autoloaded_msrs[i];
1236                 __vmx_disable_intercept_for_msr(msr_bitmap, e->index);
1237                 rdmsrl(e->index, val);
1238                 e->value = val;
1239                 printk("host index %p val %p\n", e->index, e->value);
1240
1241                 e = &vcpu->msr_autoload.guest[i];
1242                 e->index = autoloaded_msrs[i];
1243                 e->value = 0xDEADBEEF;
1244                 printk("guest index %p val %p\n", e->index, e->value);
1245         }
1246 }
1247
1248 /**
1249  *  vmx_setup_vmcs - configures the vmcs with starting parameters
1250  */
1251 static void vmx_setup_vmcs(struct vmx_vcpu *vcpu)
1252 {
1253         vmcs_write16(VIRTUAL_PROCESSOR_ID, 0);
1254         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
1255
1256         /* Control */
1257         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
1258                 vmcs_config.pin_based_exec_ctrl);
1259
1260         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
1261                 vmcs_config.cpu_based_exec_ctrl);
1262
1263         if (cpu_has_secondary_exec_ctrls()) {
1264                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
1265                              vmcs_config.cpu_based_2nd_exec_ctrl);
1266         }
1267
1268         vmcs_write64(EPT_POINTER, vcpu_get_eptp(vcpu));
1269
1270         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
1271         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
1272         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
1273
1274         setup_msr(vcpu);
1275
1276         vmcs_config.vmentry_ctrl |= VM_ENTRY_IA32E_MODE;
1277
1278         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
1279         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
1280
1281         vmcs_writel(CR0_GUEST_HOST_MASK, 0); // ~0ul);
1282         vmcs_writel(CR4_GUEST_HOST_MASK, 0); // ~0ul);
1283
1284         //kvm_write_tsc(&vmx->vcpu, 0);
1285         vmcs_writel(TSC_OFFSET, 0);
1286
1287         vmx_setup_constant_host_state();
1288 }
1289
1290 /**
1291  * vmx_create_vcpu - allocates and initializes a new virtual cpu
1292  *
1293  * Returns: A new VCPU structure
1294  */
1295 struct vmx_vcpu *vmx_create_vcpu(struct proc *p)
1296 {
1297         struct vmx_vcpu *vcpu = kmalloc(sizeof(struct vmx_vcpu), KMALLOC_WAIT);
1298         if (!vcpu) {
1299                 return NULL;
1300         }
1301
1302         memset(vcpu, 0, sizeof(*vcpu));
1303
1304         vcpu->proc = p; /* uncounted (weak) reference */
1305         vcpu->vmcs = vmx_alloc_vmcs();
1306         printd("%d: vcpu->vmcs is %p\n", core_id(), vcpu->vmcs);
1307         if (!vcpu->vmcs)
1308                 goto fail_vmcs;
1309
1310         vcpu->cpu = -1;
1311
1312         vmx_get_cpu(vcpu);
1313         vmx_setup_vmcs(vcpu);
1314         vmx_setup_initial_guest_state();
1315         vmx_put_cpu(vcpu);
1316
1317         return vcpu;
1318
1319 fail_vmcs:
1320         kfree(vcpu);
1321         return NULL;
1322 }
1323
1324 /**
1325  * vmx_destroy_vcpu - destroys and frees an existing virtual cpu
1326  * @vcpu: the VCPU to destroy
1327  */
1328 void vmx_destroy_vcpu(struct vmx_vcpu *vcpu)
1329 {
1330         vmx_free_vmcs(vcpu->vmcs);
1331         kfree(vcpu);
1332 }
1333
1334 /**
1335  * vmx_current_vcpu - returns a pointer to the vcpu for the current task.
1336  *
1337  * In the contexts where this is used the vcpu pointer should never be NULL.
1338  */
1339 static inline struct vmx_vcpu *vmx_current_vcpu(void)
1340 {
1341         struct vmx_vcpu *vcpu = currentcpu->local_vcpu;
1342         if (!vcpu)
1343                 panic("Core has no vcpu!");
1344         return vcpu;
1345 }
1346
1347 /**
1348  * vmx_run_vcpu - launches the CPU into non-root mode
1349  * We ONLY support 64-bit guests.
1350  * @vcpu: the vmx instance to launch
1351  */
1352 static int vmx_run_vcpu(struct vmx_vcpu *vcpu)
1353 {
1354         asm(
1355                 /* Store host registers */
1356                 "push %%rdx; push %%rbp;"
1357                 "push %%rcx \n\t" /* placeholder for guest rcx */
1358                 "push %%rcx \n\t"
1359                 "cmp %%rsp, %c[host_rsp](%0) \n\t"
1360                 "je 1f \n\t"
1361                 "mov %%rsp, %c[host_rsp](%0) \n\t"
1362                 ASM_VMX_VMWRITE_RSP_RDX "\n\t"
1363                 "1: \n\t"
1364                 /* Reload cr2 if changed */
1365                 "mov %c[cr2](%0), %%rax \n\t"
1366                 "mov %%cr2, %%rdx \n\t"
1367                 "cmp %%rax, %%rdx \n\t"
1368                 "je 2f \n\t"
1369                 "mov %%rax, %%cr2 \n\t"
1370                 "2: \n\t"
1371                 /* Check if vmlaunch of vmresume is needed */
1372                 "cmpl $0, %c[launched](%0) \n\t"
1373                 /* Load guest registers.  Don't clobber flags. */
1374                 "mov %c[rax](%0), %%rax \n\t"
1375                 "mov %c[rbx](%0), %%rbx \n\t"
1376                 "mov %c[rdx](%0), %%rdx \n\t"
1377                 "mov %c[rsi](%0), %%rsi \n\t"
1378                 "mov %c[rdi](%0), %%rdi \n\t"
1379                 "mov %c[rbp](%0), %%rbp \n\t"
1380                 "mov %c[r8](%0),  %%r8  \n\t"
1381                 "mov %c[r9](%0),  %%r9  \n\t"
1382                 "mov %c[r10](%0), %%r10 \n\t"
1383                 "mov %c[r11](%0), %%r11 \n\t"
1384                 "mov %c[r12](%0), %%r12 \n\t"
1385                 "mov %c[r13](%0), %%r13 \n\t"
1386                 "mov %c[r14](%0), %%r14 \n\t"
1387                 "mov %c[r15](%0), %%r15 \n\t"
1388                 "mov %c[rcx](%0), %%rcx \n\t" /* kills %0 (ecx) */
1389
1390                 /* Enter guest mode */
1391                 "jne .Llaunched \n\t"
1392                 ASM_VMX_VMLAUNCH "\n\t"
1393                 "jmp .Lkvm_vmx_return \n\t"
1394                 ".Llaunched: " ASM_VMX_VMRESUME "\n\t"
1395                 ".Lkvm_vmx_return: "
1396                 /* Save guest registers, load host registers, keep flags */
1397                 "mov %0, %c[wordsize](%%rsp) \n\t"
1398                 "pop %0 \n\t"
1399                 "mov %%rax, %c[rax](%0) \n\t"
1400                 "mov %%rbx, %c[rbx](%0) \n\t"
1401                 "popq %c[rcx](%0) \n\t"
1402                 "mov %%rdx, %c[rdx](%0) \n\t"
1403                 "mov %%rsi, %c[rsi](%0) \n\t"
1404                 "mov %%rdi, %c[rdi](%0) \n\t"
1405                 "mov %%rbp, %c[rbp](%0) \n\t"
1406                 "mov %%r8,  %c[r8](%0) \n\t"
1407                 "mov %%r9,  %c[r9](%0) \n\t"
1408                 "mov %%r10, %c[r10](%0) \n\t"
1409                 "mov %%r11, %c[r11](%0) \n\t"
1410                 "mov %%r12, %c[r12](%0) \n\t"
1411                 "mov %%r13, %c[r13](%0) \n\t"
1412                 "mov %%r14, %c[r14](%0) \n\t"
1413                 "mov %%r15, %c[r15](%0) \n\t"
1414                 "mov %%rax, %%r10 \n\t"
1415                 "mov %%rdx, %%r11 \n\t"
1416
1417                 "mov %%cr2, %%rax   \n\t"
1418                 "mov %%rax, %c[cr2](%0) \n\t"
1419
1420                 "pop  %%rbp; pop  %%rdx \n\t"
1421                 "setbe %c[fail](%0) \n\t"
1422                 "mov $" STRINGIFY(GD_UD) ", %%rax \n\t"
1423                 "mov %%rax, %%ds \n\t"
1424                 "mov %%rax, %%es \n\t"
1425               : : "c"(vcpu), "d"((unsigned long)HOST_RSP),
1426                 [launched]"i"(offsetof(struct vmx_vcpu, launched)),
1427                 [fail]"i"(offsetof(struct vmx_vcpu, fail)),
1428                 [host_rsp]"i"(offsetof(struct vmx_vcpu, host_rsp)),
1429                 [rax]"i"(offsetof(struct vmx_vcpu, regs.tf_rax)),
1430                 [rbx]"i"(offsetof(struct vmx_vcpu, regs.tf_rbx)),
1431                 [rcx]"i"(offsetof(struct vmx_vcpu, regs.tf_rcx)),
1432                 [rdx]"i"(offsetof(struct vmx_vcpu, regs.tf_rdx)),
1433                 [rsi]"i"(offsetof(struct vmx_vcpu, regs.tf_rsi)),
1434                 [rdi]"i"(offsetof(struct vmx_vcpu, regs.tf_rdi)),
1435                 [rbp]"i"(offsetof(struct vmx_vcpu, regs.tf_rbp)),
1436                 [r8]"i"(offsetof(struct vmx_vcpu, regs.tf_r8)),
1437                 [r9]"i"(offsetof(struct vmx_vcpu, regs.tf_r9)),
1438                 [r10]"i"(offsetof(struct vmx_vcpu, regs.tf_r10)),
1439                 [r11]"i"(offsetof(struct vmx_vcpu, regs.tf_r11)),
1440                 [r12]"i"(offsetof(struct vmx_vcpu, regs.tf_r12)),
1441                 [r13]"i"(offsetof(struct vmx_vcpu, regs.tf_r13)),
1442                 [r14]"i"(offsetof(struct vmx_vcpu, regs.tf_r14)),
1443                 [r15]"i"(offsetof(struct vmx_vcpu, regs.tf_r15)),
1444                 [cr2]"i"(offsetof(struct vmx_vcpu, cr2)),
1445                 [wordsize]"i"(sizeof(unsigned long))
1446               : "cc", "memory"
1447                 , "rax", "rbx", "rdi", "rsi"
1448                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
1449         );
1450
1451         vcpu->regs.tf_rip = vmcs_readl(GUEST_RIP);
1452         vcpu->regs.tf_rsp = vmcs_readl(GUEST_RSP);
1453         printd("RETURN. ip %016lx sp %016lx cr2 %016lx\n",
1454                vcpu->regs.tf_rip, vcpu->regs.tf_rsp, vcpu->cr2);
1455         /* FIXME: do we need to set up other flags? */
1456         vcpu->regs.tf_rflags = (vmcs_readl(GUEST_RFLAGS) & 0xFF) |
1457                       X86_EFLAGS_IF | 0x2;
1458
1459         vcpu->regs.tf_cs = GD_UT;
1460         vcpu->regs.tf_ss = GD_UD;
1461
1462         vcpu->launched = 1;
1463
1464         if (vcpu->fail) {
1465                 printk("failure detected (err %x)\n",
1466                        vmcs_read32(VM_INSTRUCTION_ERROR));
1467                 return VMX_EXIT_REASONS_FAILED_VMENTRY;
1468         }
1469
1470         return vmcs_read32(VM_EXIT_REASON);
1471
1472 #if 0
1473         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
1474         vmx_complete_atomic_exit(vmx);
1475         vmx_recover_nmi_blocking(vmx);
1476         vmx_complete_interrupts(vmx);
1477 #endif
1478 }
1479
1480 static void vmx_step_instruction(void)
1481 {
1482         vmcs_writel(GUEST_RIP, vmcs_readl(GUEST_RIP) +
1483                                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
1484 }
1485
1486 static int vmx_handle_ept_violation(struct vmx_vcpu *vcpu)
1487 {
1488         unsigned long gva, gpa;
1489         int exit_qual, ret = -1;
1490         page_t *page;
1491
1492         vmx_get_cpu(vcpu);
1493         exit_qual = vmcs_read32(EXIT_QUALIFICATION);
1494         gva = vmcs_readl(GUEST_LINEAR_ADDRESS);
1495         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
1496
1497         vmx_put_cpu(vcpu);
1498
1499         int prot = 0;
1500         prot |= exit_qual & VMX_EPT_FAULT_READ ? PROT_READ : 0;
1501         prot |= exit_qual & VMX_EPT_FAULT_WRITE ? PROT_WRITE : 0;
1502         prot |= exit_qual & VMX_EPT_FAULT_INS ? PROT_EXEC : 0;
1503         ret = handle_page_fault(current, gpa, prot);
1504
1505         if (ret) {
1506                 printk("EPT page fault failure %d, GPA: %p, GVA: %p\n", ret, gpa, gva);
1507                 vmx_dump_cpu(vcpu);
1508         }
1509
1510         return ret;
1511 }
1512
1513 static void vmx_handle_cpuid(struct vmx_vcpu *vcpu)
1514 {
1515         unsigned int eax, ebx, ecx, edx;
1516
1517         eax = vcpu->regs.tf_rax;
1518         ecx = vcpu->regs.tf_rcx;
1519         cpuid(eax, ecx, &eax, &ebx, &ecx, &edx);
1520         vcpu->regs.tf_rax = eax;
1521         vcpu->regs.tf_rbx = ebx;
1522         vcpu->regs.tf_rcx = ecx;
1523         vcpu->regs.tf_rdx = edx;
1524 }
1525
1526 static int vmx_handle_nmi_exception(struct vmx_vcpu *vcpu)
1527 {
1528         uint32_t intr_info;
1529
1530         vmx_get_cpu(vcpu);
1531         intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
1532         vmx_put_cpu(vcpu);
1533
1534         printk("vmx (vcpu %p): got an exception\n", vcpu);
1535         printk("vmx (vcpu %p): pid %d\n", vcpu, vcpu->proc->pid);
1536         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) {
1537                 return 0;
1538         }
1539
1540         printk("unhandled nmi, intr_info %x\n", intr_info);
1541         return -EIO;
1542 }
1543
1544 /**
1545  * vmx_launch - the main loop for a VMX Dune process
1546  * @conf: the launch configuration
1547  */
1548 int vmx_launch(uint64_t rip, uint64_t rsp, uint64_t cr3)
1549 {
1550         int ret;
1551         struct vmx_vcpu *vcpu;
1552         int errors = 0;
1553         int advance;
1554
1555         printd("RUNNING: %s: rip %p rsp %p cr3 %p \n",
1556                __func__, rip, rsp, cr3);
1557         /* TODO: dirty hack til we have VMM contexts */
1558         vcpu = current->vmm.guest_pcores[0];
1559         if (!vcpu) {
1560                 printk("Failed to get a CPU!\n");
1561                 return -ENOMEM;
1562         }
1563
1564         /* We need to prep the host's autoload region for our current core.  Right
1565          * now, the only autoloaded MSR that varies at runtime (in this case per
1566          * core is the KERN_GS_BASE). */
1567         rdmsrl(MSR_KERNEL_GS_BASE, vcpu->msr_autoload.host[0].value);
1568         /* if cr3 is set, means 'set everything', else means 'start where you left off' */
1569         if (cr3) {
1570                 vmx_get_cpu(vcpu);
1571                 vmcs_writel(GUEST_RIP, rip);
1572                 vmcs_writel(GUEST_RSP, rsp);
1573                 vmcs_writel(GUEST_CR3, cr3);
1574                 vmx_put_cpu(vcpu);
1575         }
1576
1577         vcpu->ret_code = -1;
1578
1579         while (1) {
1580                 advance = 0;
1581                 vmx_get_cpu(vcpu);
1582
1583                 // TODO: manage the fpu when we restart.
1584
1585                 // TODO: see if we need to exit before we go much further.
1586                 disable_irq();
1587                 //dumpmsrs();
1588                 ret = vmx_run_vcpu(vcpu);
1589                 //dumpmsrs();
1590                 enable_irq();
1591                 vmx_put_cpu(vcpu);
1592
1593                 if (ret == EXIT_REASON_VMCALL) {
1594                         if (current->vmm.flags & VMM_VMCALL_PRINTF) {
1595                                 uint8_t byte = vcpu->regs.tf_rdi;
1596                                 printd("System call\n");
1597 #ifdef DEBUG
1598                                 vmx_dump_cpu(vcpu);
1599 #endif
1600                                 advance = 3;
1601                                 printk("%c", byte);
1602                                 // adjust the RIP
1603                         } else {
1604                                 vcpu->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
1605                                 uint8_t byte = vcpu->regs.tf_rdi;
1606                                 printk("%p %c\n", byte, vcpu->regs.tf_rdi);
1607                                 vmx_dump_cpu(vcpu);
1608                                 printd("system call! WTF\n");
1609                         }
1610                 } else if (ret == EXIT_REASON_CR_ACCESS) {
1611                         show_cr_access(vmcs_read32(EXIT_QUALIFICATION));
1612                         vmx_dump_cpu(vcpu);
1613                         vcpu->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
1614                 } else if (ret == EXIT_REASON_CPUID) {
1615                         vmx_handle_cpuid(vcpu);
1616                         vmx_get_cpu(vcpu);
1617                         vmcs_writel(GUEST_RIP, vcpu->regs.tf_rip + 2);
1618                         vmx_put_cpu(vcpu);
1619                 } else if (ret == EXIT_REASON_EPT_VIOLATION) {
1620                         if (vmx_handle_ept_violation(vcpu))
1621                                 vcpu->shutdown = SHUTDOWN_EPT_VIOLATION;
1622                 } else if (ret == EXIT_REASON_EXCEPTION_NMI) {
1623                         if (vmx_handle_nmi_exception(vcpu))
1624                                 vcpu->shutdown = SHUTDOWN_NMI_EXCEPTION;
1625                 } else if (ret == EXIT_REASON_EXTERNAL_INTERRUPT) {
1626                         printd("External interrupt\n");
1627                         vcpu->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
1628                 } else if (ret == EXIT_REASON_MSR_READ) {
1629                         printd("msr read\n");
1630                         vmx_dump_cpu(vcpu);
1631                         vcpu->shutdown = msrio(vcpu, ret, vmcs_read32(EXIT_QUALIFICATION));
1632                         advance = 2;
1633                 } else if (ret == EXIT_REASON_MSR_WRITE) {
1634                         printd("msr write\n");
1635                         vmx_dump_cpu(vcpu);
1636                         vcpu->shutdown = msrio(vcpu, ret, vmcs_read32(EXIT_QUALIFICATION));
1637                         advance = 2;
1638                 } else {
1639                         printk("unhandled exit: reason 0x%x, exit qualification 0x%x\n",
1640                                ret, vmcs_read32(EXIT_QUALIFICATION));
1641                         vmx_dump_cpu(vcpu);
1642                         vcpu->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
1643                 }
1644
1645                 /* TODO: we can't just return and relaunch the VMCS, in case we blocked.
1646                  * similar to how proc_restartcore/smp_idle only restart the pcpui
1647                  * cur_ctx, we need to do the same, via the VMCS resume business. */
1648                 if (vcpu->shutdown)
1649                         break;
1650
1651                 if (advance) {
1652                         vmx_get_cpu(vcpu);
1653                         vmcs_writel(GUEST_RIP, vcpu->regs.tf_rip + advance);
1654                         vmx_put_cpu(vcpu);
1655                 }
1656         }
1657
1658         printd("RETURN. ip %016lx sp %016lx\n",
1659                 vcpu->regs.tf_rip, vcpu->regs.tf_rsp);
1660 //      hexdump((void *)vcpu->regs.tf_rsp, 128 * 8);
1661         /*
1662          * Return both the reason for the shutdown and a status value.
1663          * The exit() and exit_group() system calls only need 8 bits for
1664          * the status but we allow 16 bits in case we might want to
1665          * return more information for one of the other shutdown reasons.
1666          */
1667         ret = (vcpu->shutdown << 16) | (vcpu->ret_code & 0xffff);
1668
1669         return ret;
1670 }
1671
1672 /**
1673  * __vmx_enable - low-level enable of VMX mode on the current CPU
1674  * @vmxon_buf: an opaque buffer for use as the VMXON region
1675  */
1676 static  int __vmx_enable(struct vmcs *vmxon_buf)
1677 {
1678         uint64_t phys_addr = PADDR(vmxon_buf);
1679         uint64_t old, test_bits;
1680
1681         if (rcr4() & X86_CR4_VMXE) {
1682                 panic("Should never have this happen");
1683                 return -EBUSY;
1684         }
1685
1686         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
1687
1688         test_bits = FEATURE_CONTROL_LOCKED;
1689         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
1690
1691         if (0) // tboot_enabled())
1692                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
1693
1694         if ((old & test_bits) != test_bits) {
1695                 /* If it's locked, then trying to set it will cause a GPF.
1696                  * No Dune for you!
1697                  */
1698                 if (old & FEATURE_CONTROL_LOCKED) {
1699                         printk("Dune: MSR_IA32_FEATURE_CONTROL is locked!\n");
1700                         return -1;
1701                 }
1702
1703                 /* enable and lock */
1704                 write_msr(MSR_IA32_FEATURE_CONTROL, old | test_bits);
1705         }
1706         lcr4(rcr4() | X86_CR4_VMXE);
1707
1708         __vmxon(phys_addr);
1709         vpid_sync_vcpu_global();        /* good idea, even if we aren't using vpids */
1710         ept_sync_global();
1711
1712         return 0;
1713 }
1714
1715 /**
1716  * vmx_enable - enables VMX mode on the current CPU
1717  * @unused: not used (required for on_each_cpu())
1718  *
1719  * Sets up necessary state for enable (e.g. a scratchpad for VMXON.)
1720  */
1721 static void vmx_enable(void)
1722 {
1723         struct vmcs *vmxon_buf = currentcpu->vmxarea;
1724         int ret;
1725
1726         ret = __vmx_enable(vmxon_buf);
1727         if (ret)
1728                 goto failed;
1729
1730         currentcpu->vmx_enabled = 1;
1731         // TODO: do we need this?
1732         store_gdt(&currentcpu->host_gdt);
1733
1734         printk("VMX enabled on CPU %d\n", core_id());
1735         return;
1736
1737 failed:
1738         printk("Failed to enable VMX on core %d, err = %d\n", core_id(), ret);
1739 }
1740
1741 /**
1742  * vmx_disable - disables VMX mode on the current CPU
1743  */
1744 static void vmx_disable(void *unused)
1745 {
1746         if (currentcpu->vmx_enabled) {
1747                 __vmxoff();
1748                 lcr4(rcr4() & ~X86_CR4_VMXE);
1749                 currentcpu->vmx_enabled = 0;
1750         }
1751 }
1752
1753 /* Probe the cpus to see which ones can do vmx.
1754  * Return -errno if it fails, and 1 if it succeeds.
1755  */
1756 static bool probe_cpu_vmx(void)
1757 {
1758         /* The best way to test this code is:
1759          * wrmsr -p <cpu> 0x3a 1
1760          * This will lock vmx off; then modprobe dune.
1761          * Frequently, however, systems have all 0x3a registers set to 5,
1762          * meaning testing is impossible, as vmx can not be disabled.
1763          * We have to simulate it being unavailable in most cases.
1764          * The 'test' variable provides an easy way to simulate
1765          * unavailability of vmx on some, none, or all cpus.
1766          */
1767         if (!cpu_has_vmx()) {
1768                 printk("Machine does not support VT-x\n");
1769                 return FALSE;
1770         } else {
1771                 printk("Machine supports VT-x\n");
1772                 return TRUE;
1773         }
1774 }
1775
1776 static void setup_vmxarea(void)
1777 {
1778                 struct vmcs *vmxon_buf;
1779                 printd("Set up vmxarea for cpu %d\n", core_id());
1780                 vmxon_buf = __vmx_alloc_vmcs(core_id());
1781                 if (!vmxon_buf) {
1782                         printk("setup_vmxarea failed on node %d\n", core_id());
1783                         return;
1784                 }
1785                 currentcpu->vmxarea = vmxon_buf;
1786 }
1787
1788 static int ept_init(void)
1789 {
1790         if (!cpu_has_vmx_ept()) {
1791                 printk("VMX doesn't support EPT!\n");
1792                 return -1;
1793         }
1794         if (!cpu_has_vmx_eptp_writeback()) {
1795                 printk("VMX EPT doesn't support WB memory!\n");
1796                 return -1;
1797         }
1798         if (!cpu_has_vmx_ept_4levels()) {
1799                 printk("VMX EPT doesn't support 4 level walks!\n");
1800                 return -1;
1801         }
1802         switch (arch_max_jumbo_page_shift()) {
1803                 case PML3_SHIFT:
1804                         if (!cpu_has_vmx_ept_1g_page()) {
1805                                 printk("VMX EPT doesn't support 1 GB pages!\n");
1806                                 return -1;
1807                         }
1808                         break;
1809                 case PML2_SHIFT:
1810                         if (!cpu_has_vmx_ept_2m_page()) {
1811                                 printk("VMX EPT doesn't support 2 MB pages!\n");
1812                                 return -1;
1813                         }
1814                         break;
1815                 default:
1816                         printk("Unexpected jumbo page size %d\n",
1817                                arch_max_jumbo_page_shift());
1818                         return -1;
1819         }
1820         if (!cpu_has_vmx_ept_ad_bits()) {
1821                 printk("VMX EPT doesn't support accessed/dirty!\n");
1822                 x86_ept_pte_fix_ups |= EPTE_A | EPTE_D;
1823         }
1824         if (!cpu_has_vmx_invept() || !cpu_has_vmx_invept_global()) {
1825                 printk("VMX EPT can't invalidate PTEs/TLBs!\n");
1826                 return -1;
1827         }
1828
1829         return 0;
1830 }
1831
1832 /**
1833  * vmx_init sets up physical core data areas that are required to run a vm at all.
1834  * These data areas are not connected to a specific user process in any way. Instead,
1835  * they are in some sense externalizing what would other wise be a very large ball of
1836  * state that would be inside the CPU.
1837  */
1838 int intel_vmm_init(void)
1839 {
1840         int r, cpu, ret;
1841
1842         if (! probe_cpu_vmx()) {
1843                 return -EOPNOTSUPP;
1844         }
1845
1846         setup_vmcs_config(&ret);
1847
1848         if (ret) {
1849                 printk("setup_vmcs_config failed: %d\n", ret);
1850                 return ret;
1851         }
1852
1853         msr_bitmap = (unsigned long *)kpage_zalloc_addr();
1854         if (!msr_bitmap) {
1855                 printk("Could not allocate msr_bitmap\n");
1856                 return -ENOMEM;
1857         }
1858         io_bitmap = (unsigned long *)get_cont_pages(VMX_IO_BITMAP_ORDER,
1859                                                     KMALLOC_WAIT);
1860         if (!io_bitmap) {
1861                 printk("Could not allocate msr_bitmap\n");
1862                 kfree(msr_bitmap);
1863                 return -ENOMEM;
1864         }
1865         /* FIXME: do we need APIC virtualization (flexpriority?) */
1866
1867         memset(msr_bitmap, 0xff, PAGE_SIZE);
1868         memset(io_bitmap, 0xff, VMX_IO_BITMAP_SZ);
1869
1870         /* These are the only MSRs that are not autoloaded and not intercepted */
1871         __vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE);
1872         __vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE);
1873         __vmx_disable_intercept_for_msr(msr_bitmap, MSR_EFER);
1874
1875         /* TODO: this might be dangerous, since they can do more than just read the
1876          * CMOS */
1877         __vmx_disable_intercept_for_io(io_bitmap, CMOS_RAM_IDX);
1878         __vmx_disable_intercept_for_io(io_bitmap, CMOS_RAM_DATA);
1879
1880         if ((ret = ept_init())) {
1881                 printk("EPT init failed, %d\n", ret);
1882                 return ret;
1883         }
1884         printk("VMX setup succeeded\n");
1885         return 0;
1886 }
1887
1888 int intel_vmm_pcpu_init(void)
1889 {
1890         setup_vmxarea();
1891         vmx_enable();
1892         return 0;
1893 }