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