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