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