include cleanup: Update gfp.h and slab.h includes to prepare for breaking implicit...
[linux-2.6.git] / arch / x86 / kvm / vmx.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "irq.h"
19 #include "mmu.h"
20
21 #include <linux/kvm_host.h>
22 #include <linux/module.h>
23 #include <linux/kernel.h>
24 #include <linux/mm.h>
25 #include <linux/highmem.h>
26 #include <linux/sched.h>
27 #include <linux/moduleparam.h>
28 #include <linux/ftrace_event.h>
29 #include <linux/slab.h>
30 #include "kvm_cache_regs.h"
31 #include "x86.h"
32
33 #include <asm/io.h>
34 #include <asm/desc.h>
35 #include <asm/vmx.h>
36 #include <asm/virtext.h>
37 #include <asm/mce.h>
38
39 #include "trace.h"
40
41 #define __ex(x) __kvm_handle_fault_on_reboot(x)
42
43 MODULE_AUTHOR("Qumranet");
44 MODULE_LICENSE("GPL");
45
46 static int __read_mostly bypass_guest_pf = 1;
47 module_param(bypass_guest_pf, bool, S_IRUGO);
48
49 static int __read_mostly enable_vpid = 1;
50 module_param_named(vpid, enable_vpid, bool, 0444);
51
52 static int __read_mostly flexpriority_enabled = 1;
53 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
54
55 static int __read_mostly enable_ept = 1;
56 module_param_named(ept, enable_ept, bool, S_IRUGO);
57
58 static int __read_mostly enable_unrestricted_guest = 1;
59 module_param_named(unrestricted_guest,
60                         enable_unrestricted_guest, bool, S_IRUGO);
61
62 static int __read_mostly emulate_invalid_guest_state = 0;
63 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
64
65 #define KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST                           \
66         (X86_CR0_WP | X86_CR0_NE | X86_CR0_NW | X86_CR0_CD)
67 #define KVM_GUEST_CR0_MASK                                              \
68         (KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
69 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST                         \
70         (X86_CR0_WP | X86_CR0_NE)
71 #define KVM_VM_CR0_ALWAYS_ON                                            \
72         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
73 #define KVM_CR4_GUEST_OWNED_BITS                                      \
74         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
75          | X86_CR4_OSXMMEXCPT)
76
77 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
78 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
79
80 /*
81  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
82  * ple_gap:    upper bound on the amount of time between two successive
83  *             executions of PAUSE in a loop. Also indicate if ple enabled.
84  *             According to test, this time is usually small than 41 cycles.
85  * ple_window: upper bound on the amount of time a guest is allowed to execute
86  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
87  *             less than 2^12 cycles
88  * Time is measured based on a counter that runs at the same rate as the TSC,
89  * refer SDM volume 3b section 21.6.13 & 22.1.3.
90  */
91 #define KVM_VMX_DEFAULT_PLE_GAP    41
92 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
93 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
94 module_param(ple_gap, int, S_IRUGO);
95
96 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
97 module_param(ple_window, int, S_IRUGO);
98
99 struct vmcs {
100         u32 revision_id;
101         u32 abort;
102         char data[0];
103 };
104
105 struct shared_msr_entry {
106         unsigned index;
107         u64 data;
108         u64 mask;
109 };
110
111 struct vcpu_vmx {
112         struct kvm_vcpu       vcpu;
113         struct list_head      local_vcpus_link;
114         unsigned long         host_rsp;
115         int                   launched;
116         u8                    fail;
117         u32                   idt_vectoring_info;
118         struct shared_msr_entry *guest_msrs;
119         int                   nmsrs;
120         int                   save_nmsrs;
121 #ifdef CONFIG_X86_64
122         u64                   msr_host_kernel_gs_base;
123         u64                   msr_guest_kernel_gs_base;
124 #endif
125         struct vmcs          *vmcs;
126         struct {
127                 int           loaded;
128                 u16           fs_sel, gs_sel, ldt_sel;
129                 int           gs_ldt_reload_needed;
130                 int           fs_reload_needed;
131         } host_state;
132         struct {
133                 int vm86_active;
134                 u8 save_iopl;
135                 struct kvm_save_segment {
136                         u16 selector;
137                         unsigned long base;
138                         u32 limit;
139                         u32 ar;
140                 } tr, es, ds, fs, gs;
141                 struct {
142                         bool pending;
143                         u8 vector;
144                         unsigned rip;
145                 } irq;
146         } rmode;
147         int vpid;
148         bool emulation_required;
149
150         /* Support for vnmi-less CPUs */
151         int soft_vnmi_blocked;
152         ktime_t entry_time;
153         s64 vnmi_blocked_time;
154         u32 exit_reason;
155
156         bool rdtscp_enabled;
157 };
158
159 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
160 {
161         return container_of(vcpu, struct vcpu_vmx, vcpu);
162 }
163
164 static int init_rmode(struct kvm *kvm);
165 static u64 construct_eptp(unsigned long root_hpa);
166
167 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
168 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
169 static DEFINE_PER_CPU(struct list_head, vcpus_on_cpu);
170
171 static unsigned long *vmx_io_bitmap_a;
172 static unsigned long *vmx_io_bitmap_b;
173 static unsigned long *vmx_msr_bitmap_legacy;
174 static unsigned long *vmx_msr_bitmap_longmode;
175
176 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
177 static DEFINE_SPINLOCK(vmx_vpid_lock);
178
179 static struct vmcs_config {
180         int size;
181         int order;
182         u32 revision_id;
183         u32 pin_based_exec_ctrl;
184         u32 cpu_based_exec_ctrl;
185         u32 cpu_based_2nd_exec_ctrl;
186         u32 vmexit_ctrl;
187         u32 vmentry_ctrl;
188 } vmcs_config;
189
190 static struct vmx_capability {
191         u32 ept;
192         u32 vpid;
193 } vmx_capability;
194
195 #define VMX_SEGMENT_FIELD(seg)                                  \
196         [VCPU_SREG_##seg] = {                                   \
197                 .selector = GUEST_##seg##_SELECTOR,             \
198                 .base = GUEST_##seg##_BASE,                     \
199                 .limit = GUEST_##seg##_LIMIT,                   \
200                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
201         }
202
203 static struct kvm_vmx_segment_field {
204         unsigned selector;
205         unsigned base;
206         unsigned limit;
207         unsigned ar_bytes;
208 } kvm_vmx_segment_fields[] = {
209         VMX_SEGMENT_FIELD(CS),
210         VMX_SEGMENT_FIELD(DS),
211         VMX_SEGMENT_FIELD(ES),
212         VMX_SEGMENT_FIELD(FS),
213         VMX_SEGMENT_FIELD(GS),
214         VMX_SEGMENT_FIELD(SS),
215         VMX_SEGMENT_FIELD(TR),
216         VMX_SEGMENT_FIELD(LDTR),
217 };
218
219 static u64 host_efer;
220
221 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
222
223 /*
224  * Keep MSR_K6_STAR at the end, as setup_msrs() will try to optimize it
225  * away by decrementing the array size.
226  */
227 static const u32 vmx_msr_index[] = {
228 #ifdef CONFIG_X86_64
229         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
230 #endif
231         MSR_EFER, MSR_TSC_AUX, MSR_K6_STAR,
232 };
233 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
234
235 static inline int is_page_fault(u32 intr_info)
236 {
237         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
238                              INTR_INFO_VALID_MASK)) ==
239                 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
240 }
241
242 static inline int is_no_device(u32 intr_info)
243 {
244         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
245                              INTR_INFO_VALID_MASK)) ==
246                 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
247 }
248
249 static inline int is_invalid_opcode(u32 intr_info)
250 {
251         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
252                              INTR_INFO_VALID_MASK)) ==
253                 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
254 }
255
256 static inline int is_external_interrupt(u32 intr_info)
257 {
258         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
259                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
260 }
261
262 static inline int is_machine_check(u32 intr_info)
263 {
264         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
265                              INTR_INFO_VALID_MASK)) ==
266                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
267 }
268
269 static inline int cpu_has_vmx_msr_bitmap(void)
270 {
271         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
272 }
273
274 static inline int cpu_has_vmx_tpr_shadow(void)
275 {
276         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
277 }
278
279 static inline int vm_need_tpr_shadow(struct kvm *kvm)
280 {
281         return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
282 }
283
284 static inline int cpu_has_secondary_exec_ctrls(void)
285 {
286         return vmcs_config.cpu_based_exec_ctrl &
287                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
288 }
289
290 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
291 {
292         return vmcs_config.cpu_based_2nd_exec_ctrl &
293                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
294 }
295
296 static inline bool cpu_has_vmx_flexpriority(void)
297 {
298         return cpu_has_vmx_tpr_shadow() &&
299                 cpu_has_vmx_virtualize_apic_accesses();
300 }
301
302 static inline bool cpu_has_vmx_ept_execute_only(void)
303 {
304         return !!(vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT);
305 }
306
307 static inline bool cpu_has_vmx_eptp_uncacheable(void)
308 {
309         return !!(vmx_capability.ept & VMX_EPTP_UC_BIT);
310 }
311
312 static inline bool cpu_has_vmx_eptp_writeback(void)
313 {
314         return !!(vmx_capability.ept & VMX_EPTP_WB_BIT);
315 }
316
317 static inline bool cpu_has_vmx_ept_2m_page(void)
318 {
319         return !!(vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT);
320 }
321
322 static inline bool cpu_has_vmx_ept_1g_page(void)
323 {
324         return !!(vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT);
325 }
326
327 static inline int cpu_has_vmx_invept_individual_addr(void)
328 {
329         return !!(vmx_capability.ept & VMX_EPT_EXTENT_INDIVIDUAL_BIT);
330 }
331
332 static inline int cpu_has_vmx_invept_context(void)
333 {
334         return !!(vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT);
335 }
336
337 static inline int cpu_has_vmx_invept_global(void)
338 {
339         return !!(vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT);
340 }
341
342 static inline int cpu_has_vmx_ept(void)
343 {
344         return vmcs_config.cpu_based_2nd_exec_ctrl &
345                 SECONDARY_EXEC_ENABLE_EPT;
346 }
347
348 static inline int cpu_has_vmx_unrestricted_guest(void)
349 {
350         return vmcs_config.cpu_based_2nd_exec_ctrl &
351                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
352 }
353
354 static inline int cpu_has_vmx_ple(void)
355 {
356         return vmcs_config.cpu_based_2nd_exec_ctrl &
357                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
358 }
359
360 static inline int vm_need_virtualize_apic_accesses(struct kvm *kvm)
361 {
362         return flexpriority_enabled && irqchip_in_kernel(kvm);
363 }
364
365 static inline int cpu_has_vmx_vpid(void)
366 {
367         return vmcs_config.cpu_based_2nd_exec_ctrl &
368                 SECONDARY_EXEC_ENABLE_VPID;
369 }
370
371 static inline int cpu_has_vmx_rdtscp(void)
372 {
373         return vmcs_config.cpu_based_2nd_exec_ctrl &
374                 SECONDARY_EXEC_RDTSCP;
375 }
376
377 static inline int cpu_has_virtual_nmis(void)
378 {
379         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
380 }
381
382 static inline bool report_flexpriority(void)
383 {
384         return flexpriority_enabled;
385 }
386
387 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
388 {
389         int i;
390
391         for (i = 0; i < vmx->nmsrs; ++i)
392                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
393                         return i;
394         return -1;
395 }
396
397 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
398 {
399     struct {
400         u64 vpid : 16;
401         u64 rsvd : 48;
402         u64 gva;
403     } operand = { vpid, 0, gva };
404
405     asm volatile (__ex(ASM_VMX_INVVPID)
406                   /* CF==1 or ZF==1 --> rc = -1 */
407                   "; ja 1f ; ud2 ; 1:"
408                   : : "a"(&operand), "c"(ext) : "cc", "memory");
409 }
410
411 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
412 {
413         struct {
414                 u64 eptp, gpa;
415         } operand = {eptp, gpa};
416
417         asm volatile (__ex(ASM_VMX_INVEPT)
418                         /* CF==1 or ZF==1 --> rc = -1 */
419                         "; ja 1f ; ud2 ; 1:\n"
420                         : : "a" (&operand), "c" (ext) : "cc", "memory");
421 }
422
423 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
424 {
425         int i;
426
427         i = __find_msr_index(vmx, msr);
428         if (i >= 0)
429                 return &vmx->guest_msrs[i];
430         return NULL;
431 }
432
433 static void vmcs_clear(struct vmcs *vmcs)
434 {
435         u64 phys_addr = __pa(vmcs);
436         u8 error;
437
438         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
439                       : "=g"(error) : "a"(&phys_addr), "m"(phys_addr)
440                       : "cc", "memory");
441         if (error)
442                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
443                        vmcs, phys_addr);
444 }
445
446 static void __vcpu_clear(void *arg)
447 {
448         struct vcpu_vmx *vmx = arg;
449         int cpu = raw_smp_processor_id();
450
451         if (vmx->vcpu.cpu == cpu)
452                 vmcs_clear(vmx->vmcs);
453         if (per_cpu(current_vmcs, cpu) == vmx->vmcs)
454                 per_cpu(current_vmcs, cpu) = NULL;
455         rdtscll(vmx->vcpu.arch.host_tsc);
456         list_del(&vmx->local_vcpus_link);
457         vmx->vcpu.cpu = -1;
458         vmx->launched = 0;
459 }
460
461 static void vcpu_clear(struct vcpu_vmx *vmx)
462 {
463         if (vmx->vcpu.cpu == -1)
464                 return;
465         smp_call_function_single(vmx->vcpu.cpu, __vcpu_clear, vmx, 1);
466 }
467
468 static inline void vpid_sync_vcpu_all(struct vcpu_vmx *vmx)
469 {
470         if (vmx->vpid == 0)
471                 return;
472
473         __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
474 }
475
476 static inline void ept_sync_global(void)
477 {
478         if (cpu_has_vmx_invept_global())
479                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
480 }
481
482 static inline void ept_sync_context(u64 eptp)
483 {
484         if (enable_ept) {
485                 if (cpu_has_vmx_invept_context())
486                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
487                 else
488                         ept_sync_global();
489         }
490 }
491
492 static inline void ept_sync_individual_addr(u64 eptp, gpa_t gpa)
493 {
494         if (enable_ept) {
495                 if (cpu_has_vmx_invept_individual_addr())
496                         __invept(VMX_EPT_EXTENT_INDIVIDUAL_ADDR,
497                                         eptp, gpa);
498                 else
499                         ept_sync_context(eptp);
500         }
501 }
502
503 static unsigned long vmcs_readl(unsigned long field)
504 {
505         unsigned long value;
506
507         asm volatile (__ex(ASM_VMX_VMREAD_RDX_RAX)
508                       : "=a"(value) : "d"(field) : "cc");
509         return value;
510 }
511
512 static u16 vmcs_read16(unsigned long field)
513 {
514         return vmcs_readl(field);
515 }
516
517 static u32 vmcs_read32(unsigned long field)
518 {
519         return vmcs_readl(field);
520 }
521
522 static u64 vmcs_read64(unsigned long field)
523 {
524 #ifdef CONFIG_X86_64
525         return vmcs_readl(field);
526 #else
527         return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
528 #endif
529 }
530
531 static noinline void vmwrite_error(unsigned long field, unsigned long value)
532 {
533         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
534                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
535         dump_stack();
536 }
537
538 static void vmcs_writel(unsigned long field, unsigned long value)
539 {
540         u8 error;
541
542         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
543                        : "=q"(error) : "a"(value), "d"(field) : "cc");
544         if (unlikely(error))
545                 vmwrite_error(field, value);
546 }
547
548 static void vmcs_write16(unsigned long field, u16 value)
549 {
550         vmcs_writel(field, value);
551 }
552
553 static void vmcs_write32(unsigned long field, u32 value)
554 {
555         vmcs_writel(field, value);
556 }
557
558 static void vmcs_write64(unsigned long field, u64 value)
559 {
560         vmcs_writel(field, value);
561 #ifndef CONFIG_X86_64
562         asm volatile ("");
563         vmcs_writel(field+1, value >> 32);
564 #endif
565 }
566
567 static void vmcs_clear_bits(unsigned long field, u32 mask)
568 {
569         vmcs_writel(field, vmcs_readl(field) & ~mask);
570 }
571
572 static void vmcs_set_bits(unsigned long field, u32 mask)
573 {
574         vmcs_writel(field, vmcs_readl(field) | mask);
575 }
576
577 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
578 {
579         u32 eb;
580
581         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
582              (1u << NM_VECTOR) | (1u << DB_VECTOR);
583         if ((vcpu->guest_debug &
584              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
585             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
586                 eb |= 1u << BP_VECTOR;
587         if (to_vmx(vcpu)->rmode.vm86_active)
588                 eb = ~0;
589         if (enable_ept)
590                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
591         if (vcpu->fpu_active)
592                 eb &= ~(1u << NM_VECTOR);
593         vmcs_write32(EXCEPTION_BITMAP, eb);
594 }
595
596 static void reload_tss(void)
597 {
598         /*
599          * VT restores TR but not its size.  Useless.
600          */
601         struct descriptor_table gdt;
602         struct desc_struct *descs;
603
604         kvm_get_gdt(&gdt);
605         descs = (void *)gdt.base;
606         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
607         load_TR_desc();
608 }
609
610 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
611 {
612         u64 guest_efer;
613         u64 ignore_bits;
614
615         guest_efer = vmx->vcpu.arch.efer;
616
617         /*
618          * NX is emulated; LMA and LME handled by hardware; SCE meaninless
619          * outside long mode
620          */
621         ignore_bits = EFER_NX | EFER_SCE;
622 #ifdef CONFIG_X86_64
623         ignore_bits |= EFER_LMA | EFER_LME;
624         /* SCE is meaningful only in long mode on Intel */
625         if (guest_efer & EFER_LMA)
626                 ignore_bits &= ~(u64)EFER_SCE;
627 #endif
628         guest_efer &= ~ignore_bits;
629         guest_efer |= host_efer & ignore_bits;
630         vmx->guest_msrs[efer_offset].data = guest_efer;
631         vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
632         return true;
633 }
634
635 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
636 {
637         struct vcpu_vmx *vmx = to_vmx(vcpu);
638         int i;
639
640         if (vmx->host_state.loaded)
641                 return;
642
643         vmx->host_state.loaded = 1;
644         /*
645          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
646          * allow segment selectors with cpl > 0 or ti == 1.
647          */
648         vmx->host_state.ldt_sel = kvm_read_ldt();
649         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
650         vmx->host_state.fs_sel = kvm_read_fs();
651         if (!(vmx->host_state.fs_sel & 7)) {
652                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
653                 vmx->host_state.fs_reload_needed = 0;
654         } else {
655                 vmcs_write16(HOST_FS_SELECTOR, 0);
656                 vmx->host_state.fs_reload_needed = 1;
657         }
658         vmx->host_state.gs_sel = kvm_read_gs();
659         if (!(vmx->host_state.gs_sel & 7))
660                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
661         else {
662                 vmcs_write16(HOST_GS_SELECTOR, 0);
663                 vmx->host_state.gs_ldt_reload_needed = 1;
664         }
665
666 #ifdef CONFIG_X86_64
667         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
668         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
669 #else
670         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
671         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
672 #endif
673
674 #ifdef CONFIG_X86_64
675         if (is_long_mode(&vmx->vcpu)) {
676                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
677                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
678         }
679 #endif
680         for (i = 0; i < vmx->save_nmsrs; ++i)
681                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
682                                    vmx->guest_msrs[i].data,
683                                    vmx->guest_msrs[i].mask);
684 }
685
686 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
687 {
688         unsigned long flags;
689
690         if (!vmx->host_state.loaded)
691                 return;
692
693         ++vmx->vcpu.stat.host_state_reload;
694         vmx->host_state.loaded = 0;
695         if (vmx->host_state.fs_reload_needed)
696                 kvm_load_fs(vmx->host_state.fs_sel);
697         if (vmx->host_state.gs_ldt_reload_needed) {
698                 kvm_load_ldt(vmx->host_state.ldt_sel);
699                 /*
700                  * If we have to reload gs, we must take care to
701                  * preserve our gs base.
702                  */
703                 local_irq_save(flags);
704                 kvm_load_gs(vmx->host_state.gs_sel);
705 #ifdef CONFIG_X86_64
706                 wrmsrl(MSR_GS_BASE, vmcs_readl(HOST_GS_BASE));
707 #endif
708                 local_irq_restore(flags);
709         }
710         reload_tss();
711 #ifdef CONFIG_X86_64
712         if (is_long_mode(&vmx->vcpu)) {
713                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
714                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
715         }
716 #endif
717 }
718
719 static void vmx_load_host_state(struct vcpu_vmx *vmx)
720 {
721         preempt_disable();
722         __vmx_load_host_state(vmx);
723         preempt_enable();
724 }
725
726 /*
727  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
728  * vcpu mutex is already taken.
729  */
730 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
731 {
732         struct vcpu_vmx *vmx = to_vmx(vcpu);
733         u64 phys_addr = __pa(vmx->vmcs);
734         u64 tsc_this, delta, new_offset;
735
736         if (vcpu->cpu != cpu) {
737                 vcpu_clear(vmx);
738                 kvm_migrate_timers(vcpu);
739                 set_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests);
740                 local_irq_disable();
741                 list_add(&vmx->local_vcpus_link,
742                          &per_cpu(vcpus_on_cpu, cpu));
743                 local_irq_enable();
744         }
745
746         if (per_cpu(current_vmcs, cpu) != vmx->vmcs) {
747                 u8 error;
748
749                 per_cpu(current_vmcs, cpu) = vmx->vmcs;
750                 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
751                               : "=g"(error) : "a"(&phys_addr), "m"(phys_addr)
752                               : "cc");
753                 if (error)
754                         printk(KERN_ERR "kvm: vmptrld %p/%llx fail\n",
755                                vmx->vmcs, phys_addr);
756         }
757
758         if (vcpu->cpu != cpu) {
759                 struct descriptor_table dt;
760                 unsigned long sysenter_esp;
761
762                 vcpu->cpu = cpu;
763                 /*
764                  * Linux uses per-cpu TSS and GDT, so set these when switching
765                  * processors.
766                  */
767                 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
768                 kvm_get_gdt(&dt);
769                 vmcs_writel(HOST_GDTR_BASE, dt.base);   /* 22.2.4 */
770
771                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
772                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
773
774                 /*
775                  * Make sure the time stamp counter is monotonous.
776                  */
777                 rdtscll(tsc_this);
778                 if (tsc_this < vcpu->arch.host_tsc) {
779                         delta = vcpu->arch.host_tsc - tsc_this;
780                         new_offset = vmcs_read64(TSC_OFFSET) + delta;
781                         vmcs_write64(TSC_OFFSET, new_offset);
782                 }
783         }
784 }
785
786 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
787 {
788         __vmx_load_host_state(to_vmx(vcpu));
789 }
790
791 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
792 {
793         ulong cr0;
794
795         if (vcpu->fpu_active)
796                 return;
797         vcpu->fpu_active = 1;
798         cr0 = vmcs_readl(GUEST_CR0);
799         cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
800         cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
801         vmcs_writel(GUEST_CR0, cr0);
802         update_exception_bitmap(vcpu);
803         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
804         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
805 }
806
807 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
808
809 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
810 {
811         vmx_decache_cr0_guest_bits(vcpu);
812         vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
813         update_exception_bitmap(vcpu);
814         vcpu->arch.cr0_guest_owned_bits = 0;
815         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
816         vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
817 }
818
819 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
820 {
821         unsigned long rflags;
822
823         rflags = vmcs_readl(GUEST_RFLAGS);
824         if (to_vmx(vcpu)->rmode.vm86_active)
825                 rflags &= ~(unsigned long)(X86_EFLAGS_IOPL | X86_EFLAGS_VM);
826         return rflags;
827 }
828
829 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
830 {
831         if (to_vmx(vcpu)->rmode.vm86_active)
832                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
833         vmcs_writel(GUEST_RFLAGS, rflags);
834 }
835
836 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
837 {
838         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
839         int ret = 0;
840
841         if (interruptibility & GUEST_INTR_STATE_STI)
842                 ret |= X86_SHADOW_INT_STI;
843         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
844                 ret |= X86_SHADOW_INT_MOV_SS;
845
846         return ret & mask;
847 }
848
849 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
850 {
851         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
852         u32 interruptibility = interruptibility_old;
853
854         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
855
856         if (mask & X86_SHADOW_INT_MOV_SS)
857                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
858         if (mask & X86_SHADOW_INT_STI)
859                 interruptibility |= GUEST_INTR_STATE_STI;
860
861         if ((interruptibility != interruptibility_old))
862                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
863 }
864
865 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
866 {
867         unsigned long rip;
868
869         rip = kvm_rip_read(vcpu);
870         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
871         kvm_rip_write(vcpu, rip);
872
873         /* skipping an emulated instruction also counts */
874         vmx_set_interrupt_shadow(vcpu, 0);
875 }
876
877 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
878                                 bool has_error_code, u32 error_code)
879 {
880         struct vcpu_vmx *vmx = to_vmx(vcpu);
881         u32 intr_info = nr | INTR_INFO_VALID_MASK;
882
883         if (has_error_code) {
884                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
885                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
886         }
887
888         if (vmx->rmode.vm86_active) {
889                 vmx->rmode.irq.pending = true;
890                 vmx->rmode.irq.vector = nr;
891                 vmx->rmode.irq.rip = kvm_rip_read(vcpu);
892                 if (kvm_exception_is_soft(nr))
893                         vmx->rmode.irq.rip +=
894                                 vmx->vcpu.arch.event_exit_inst_len;
895                 intr_info |= INTR_TYPE_SOFT_INTR;
896                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
897                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, 1);
898                 kvm_rip_write(vcpu, vmx->rmode.irq.rip - 1);
899                 return;
900         }
901
902         if (kvm_exception_is_soft(nr)) {
903                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
904                              vmx->vcpu.arch.event_exit_inst_len);
905                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
906         } else
907                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
908
909         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
910 }
911
912 static bool vmx_rdtscp_supported(void)
913 {
914         return cpu_has_vmx_rdtscp();
915 }
916
917 /*
918  * Swap MSR entry in host/guest MSR entry array.
919  */
920 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
921 {
922         struct shared_msr_entry tmp;
923
924         tmp = vmx->guest_msrs[to];
925         vmx->guest_msrs[to] = vmx->guest_msrs[from];
926         vmx->guest_msrs[from] = tmp;
927 }
928
929 /*
930  * Set up the vmcs to automatically save and restore system
931  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
932  * mode, as fiddling with msrs is very expensive.
933  */
934 static void setup_msrs(struct vcpu_vmx *vmx)
935 {
936         int save_nmsrs, index;
937         unsigned long *msr_bitmap;
938
939         vmx_load_host_state(vmx);
940         save_nmsrs = 0;
941 #ifdef CONFIG_X86_64
942         if (is_long_mode(&vmx->vcpu)) {
943                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
944                 if (index >= 0)
945                         move_msr_up(vmx, index, save_nmsrs++);
946                 index = __find_msr_index(vmx, MSR_LSTAR);
947                 if (index >= 0)
948                         move_msr_up(vmx, index, save_nmsrs++);
949                 index = __find_msr_index(vmx, MSR_CSTAR);
950                 if (index >= 0)
951                         move_msr_up(vmx, index, save_nmsrs++);
952                 index = __find_msr_index(vmx, MSR_TSC_AUX);
953                 if (index >= 0 && vmx->rdtscp_enabled)
954                         move_msr_up(vmx, index, save_nmsrs++);
955                 /*
956                  * MSR_K6_STAR is only needed on long mode guests, and only
957                  * if efer.sce is enabled.
958                  */
959                 index = __find_msr_index(vmx, MSR_K6_STAR);
960                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
961                         move_msr_up(vmx, index, save_nmsrs++);
962         }
963 #endif
964         index = __find_msr_index(vmx, MSR_EFER);
965         if (index >= 0 && update_transition_efer(vmx, index))
966                 move_msr_up(vmx, index, save_nmsrs++);
967
968         vmx->save_nmsrs = save_nmsrs;
969
970         if (cpu_has_vmx_msr_bitmap()) {
971                 if (is_long_mode(&vmx->vcpu))
972                         msr_bitmap = vmx_msr_bitmap_longmode;
973                 else
974                         msr_bitmap = vmx_msr_bitmap_legacy;
975
976                 vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
977         }
978 }
979
980 /*
981  * reads and returns guest's timestamp counter "register"
982  * guest_tsc = host_tsc + tsc_offset    -- 21.3
983  */
984 static u64 guest_read_tsc(void)
985 {
986         u64 host_tsc, tsc_offset;
987
988         rdtscll(host_tsc);
989         tsc_offset = vmcs_read64(TSC_OFFSET);
990         return host_tsc + tsc_offset;
991 }
992
993 /*
994  * writes 'guest_tsc' into guest's timestamp counter "register"
995  * guest_tsc = host_tsc + tsc_offset ==> tsc_offset = guest_tsc - host_tsc
996  */
997 static void guest_write_tsc(u64 guest_tsc, u64 host_tsc)
998 {
999         vmcs_write64(TSC_OFFSET, guest_tsc - host_tsc);
1000 }
1001
1002 /*
1003  * Reads an msr value (of 'msr_index') into 'pdata'.
1004  * Returns 0 on success, non-0 otherwise.
1005  * Assumes vcpu_load() was already called.
1006  */
1007 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1008 {
1009         u64 data;
1010         struct shared_msr_entry *msr;
1011
1012         if (!pdata) {
1013                 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
1014                 return -EINVAL;
1015         }
1016
1017         switch (msr_index) {
1018 #ifdef CONFIG_X86_64
1019         case MSR_FS_BASE:
1020                 data = vmcs_readl(GUEST_FS_BASE);
1021                 break;
1022         case MSR_GS_BASE:
1023                 data = vmcs_readl(GUEST_GS_BASE);
1024                 break;
1025         case MSR_KERNEL_GS_BASE:
1026                 vmx_load_host_state(to_vmx(vcpu));
1027                 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
1028                 break;
1029 #endif
1030         case MSR_EFER:
1031                 return kvm_get_msr_common(vcpu, msr_index, pdata);
1032         case MSR_IA32_TSC:
1033                 data = guest_read_tsc();
1034                 break;
1035         case MSR_IA32_SYSENTER_CS:
1036                 data = vmcs_read32(GUEST_SYSENTER_CS);
1037                 break;
1038         case MSR_IA32_SYSENTER_EIP:
1039                 data = vmcs_readl(GUEST_SYSENTER_EIP);
1040                 break;
1041         case MSR_IA32_SYSENTER_ESP:
1042                 data = vmcs_readl(GUEST_SYSENTER_ESP);
1043                 break;
1044         case MSR_TSC_AUX:
1045                 if (!to_vmx(vcpu)->rdtscp_enabled)
1046                         return 1;
1047                 /* Otherwise falls through */
1048         default:
1049                 vmx_load_host_state(to_vmx(vcpu));
1050                 msr = find_msr_entry(to_vmx(vcpu), msr_index);
1051                 if (msr) {
1052                         vmx_load_host_state(to_vmx(vcpu));
1053                         data = msr->data;
1054                         break;
1055                 }
1056                 return kvm_get_msr_common(vcpu, msr_index, pdata);
1057         }
1058
1059         *pdata = data;
1060         return 0;
1061 }
1062
1063 /*
1064  * Writes msr value into into the appropriate "register".
1065  * Returns 0 on success, non-0 otherwise.
1066  * Assumes vcpu_load() was already called.
1067  */
1068 static int vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1069 {
1070         struct vcpu_vmx *vmx = to_vmx(vcpu);
1071         struct shared_msr_entry *msr;
1072         u64 host_tsc;
1073         int ret = 0;
1074
1075         switch (msr_index) {
1076         case MSR_EFER:
1077                 vmx_load_host_state(vmx);
1078                 ret = kvm_set_msr_common(vcpu, msr_index, data);
1079                 break;
1080 #ifdef CONFIG_X86_64
1081         case MSR_FS_BASE:
1082                 vmcs_writel(GUEST_FS_BASE, data);
1083                 break;
1084         case MSR_GS_BASE:
1085                 vmcs_writel(GUEST_GS_BASE, data);
1086                 break;
1087         case MSR_KERNEL_GS_BASE:
1088                 vmx_load_host_state(vmx);
1089                 vmx->msr_guest_kernel_gs_base = data;
1090                 break;
1091 #endif
1092         case MSR_IA32_SYSENTER_CS:
1093                 vmcs_write32(GUEST_SYSENTER_CS, data);
1094                 break;
1095         case MSR_IA32_SYSENTER_EIP:
1096                 vmcs_writel(GUEST_SYSENTER_EIP, data);
1097                 break;
1098         case MSR_IA32_SYSENTER_ESP:
1099                 vmcs_writel(GUEST_SYSENTER_ESP, data);
1100                 break;
1101         case MSR_IA32_TSC:
1102                 rdtscll(host_tsc);
1103                 guest_write_tsc(data, host_tsc);
1104                 break;
1105         case MSR_IA32_CR_PAT:
1106                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1107                         vmcs_write64(GUEST_IA32_PAT, data);
1108                         vcpu->arch.pat = data;
1109                         break;
1110                 }
1111                 ret = kvm_set_msr_common(vcpu, msr_index, data);
1112                 break;
1113         case MSR_TSC_AUX:
1114                 if (!vmx->rdtscp_enabled)
1115                         return 1;
1116                 /* Check reserved bit, higher 32 bits should be zero */
1117                 if ((data >> 32) != 0)
1118                         return 1;
1119                 /* Otherwise falls through */
1120         default:
1121                 msr = find_msr_entry(vmx, msr_index);
1122                 if (msr) {
1123                         vmx_load_host_state(vmx);
1124                         msr->data = data;
1125                         break;
1126                 }
1127                 ret = kvm_set_msr_common(vcpu, msr_index, data);
1128         }
1129
1130         return ret;
1131 }
1132
1133 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1134 {
1135         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
1136         switch (reg) {
1137         case VCPU_REGS_RSP:
1138                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
1139                 break;
1140         case VCPU_REGS_RIP:
1141                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
1142                 break;
1143         case VCPU_EXREG_PDPTR:
1144                 if (enable_ept)
1145                         ept_save_pdptrs(vcpu);
1146                 break;
1147         default:
1148                 break;
1149         }
1150 }
1151
1152 static void set_guest_debug(struct kvm_vcpu *vcpu, struct kvm_guest_debug *dbg)
1153 {
1154         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1155                 vmcs_writel(GUEST_DR7, dbg->arch.debugreg[7]);
1156         else
1157                 vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
1158
1159         update_exception_bitmap(vcpu);
1160 }
1161
1162 static __init int cpu_has_kvm_support(void)
1163 {
1164         return cpu_has_vmx();
1165 }
1166
1167 static __init int vmx_disabled_by_bios(void)
1168 {
1169         u64 msr;
1170
1171         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
1172         return (msr & (FEATURE_CONTROL_LOCKED |
1173                        FEATURE_CONTROL_VMXON_ENABLED))
1174             == FEATURE_CONTROL_LOCKED;
1175         /* locked but not enabled */
1176 }
1177
1178 static int hardware_enable(void *garbage)
1179 {
1180         int cpu = raw_smp_processor_id();
1181         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1182         u64 old;
1183
1184         if (read_cr4() & X86_CR4_VMXE)
1185                 return -EBUSY;
1186
1187         INIT_LIST_HEAD(&per_cpu(vcpus_on_cpu, cpu));
1188         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
1189         if ((old & (FEATURE_CONTROL_LOCKED |
1190                     FEATURE_CONTROL_VMXON_ENABLED))
1191             != (FEATURE_CONTROL_LOCKED |
1192                 FEATURE_CONTROL_VMXON_ENABLED))
1193                 /* enable and lock */
1194                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old |
1195                        FEATURE_CONTROL_LOCKED |
1196                        FEATURE_CONTROL_VMXON_ENABLED);
1197         write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
1198         asm volatile (ASM_VMX_VMXON_RAX
1199                       : : "a"(&phys_addr), "m"(phys_addr)
1200                       : "memory", "cc");
1201
1202         ept_sync_global();
1203
1204         return 0;
1205 }
1206
1207 static void vmclear_local_vcpus(void)
1208 {
1209         int cpu = raw_smp_processor_id();
1210         struct vcpu_vmx *vmx, *n;
1211
1212         list_for_each_entry_safe(vmx, n, &per_cpu(vcpus_on_cpu, cpu),
1213                                  local_vcpus_link)
1214                 __vcpu_clear(vmx);
1215 }
1216
1217
1218 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
1219  * tricks.
1220  */
1221 static void kvm_cpu_vmxoff(void)
1222 {
1223         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
1224         write_cr4(read_cr4() & ~X86_CR4_VMXE);
1225 }
1226
1227 static void hardware_disable(void *garbage)
1228 {
1229         vmclear_local_vcpus();
1230         kvm_cpu_vmxoff();
1231 }
1232
1233 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
1234                                       u32 msr, u32 *result)
1235 {
1236         u32 vmx_msr_low, vmx_msr_high;
1237         u32 ctl = ctl_min | ctl_opt;
1238
1239         rdmsr(msr, vmx_msr_low, vmx_msr_high);
1240
1241         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
1242         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
1243
1244         /* Ensure minimum (required) set of control bits are supported. */
1245         if (ctl_min & ~ctl)
1246                 return -EIO;
1247
1248         *result = ctl;
1249         return 0;
1250 }
1251
1252 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
1253 {
1254         u32 vmx_msr_low, vmx_msr_high;
1255         u32 min, opt, min2, opt2;
1256         u32 _pin_based_exec_control = 0;
1257         u32 _cpu_based_exec_control = 0;
1258         u32 _cpu_based_2nd_exec_control = 0;
1259         u32 _vmexit_control = 0;
1260         u32 _vmentry_control = 0;
1261
1262         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
1263         opt = PIN_BASED_VIRTUAL_NMIS;
1264         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
1265                                 &_pin_based_exec_control) < 0)
1266                 return -EIO;
1267
1268         min = CPU_BASED_HLT_EXITING |
1269 #ifdef CONFIG_X86_64
1270               CPU_BASED_CR8_LOAD_EXITING |
1271               CPU_BASED_CR8_STORE_EXITING |
1272 #endif
1273               CPU_BASED_CR3_LOAD_EXITING |
1274               CPU_BASED_CR3_STORE_EXITING |
1275               CPU_BASED_USE_IO_BITMAPS |
1276               CPU_BASED_MOV_DR_EXITING |
1277               CPU_BASED_USE_TSC_OFFSETING |
1278               CPU_BASED_MWAIT_EXITING |
1279               CPU_BASED_MONITOR_EXITING |
1280               CPU_BASED_INVLPG_EXITING;
1281         opt = CPU_BASED_TPR_SHADOW |
1282               CPU_BASED_USE_MSR_BITMAPS |
1283               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1284         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
1285                                 &_cpu_based_exec_control) < 0)
1286                 return -EIO;
1287 #ifdef CONFIG_X86_64
1288         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
1289                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
1290                                            ~CPU_BASED_CR8_STORE_EXITING;
1291 #endif
1292         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
1293                 min2 = 0;
1294                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
1295                         SECONDARY_EXEC_WBINVD_EXITING |
1296                         SECONDARY_EXEC_ENABLE_VPID |
1297                         SECONDARY_EXEC_ENABLE_EPT |
1298                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
1299                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
1300                         SECONDARY_EXEC_RDTSCP;
1301                 if (adjust_vmx_controls(min2, opt2,
1302                                         MSR_IA32_VMX_PROCBASED_CTLS2,
1303                                         &_cpu_based_2nd_exec_control) < 0)
1304                         return -EIO;
1305         }
1306 #ifndef CONFIG_X86_64
1307         if (!(_cpu_based_2nd_exec_control &
1308                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
1309                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
1310 #endif
1311         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
1312                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
1313                    enabled */
1314                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
1315                                              CPU_BASED_CR3_STORE_EXITING |
1316                                              CPU_BASED_INVLPG_EXITING);
1317                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
1318                       vmx_capability.ept, vmx_capability.vpid);
1319         }
1320
1321         min = 0;
1322 #ifdef CONFIG_X86_64
1323         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
1324 #endif
1325         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT;
1326         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
1327                                 &_vmexit_control) < 0)
1328                 return -EIO;
1329
1330         min = 0;
1331         opt = VM_ENTRY_LOAD_IA32_PAT;
1332         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
1333                                 &_vmentry_control) < 0)
1334                 return -EIO;
1335
1336         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
1337
1338         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
1339         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
1340                 return -EIO;
1341
1342 #ifdef CONFIG_X86_64
1343         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
1344         if (vmx_msr_high & (1u<<16))
1345                 return -EIO;
1346 #endif
1347
1348         /* Require Write-Back (WB) memory type for VMCS accesses. */
1349         if (((vmx_msr_high >> 18) & 15) != 6)
1350                 return -EIO;
1351
1352         vmcs_conf->size = vmx_msr_high & 0x1fff;
1353         vmcs_conf->order = get_order(vmcs_config.size);
1354         vmcs_conf->revision_id = vmx_msr_low;
1355
1356         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
1357         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
1358         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
1359         vmcs_conf->vmexit_ctrl         = _vmexit_control;
1360         vmcs_conf->vmentry_ctrl        = _vmentry_control;
1361
1362         return 0;
1363 }
1364
1365 static struct vmcs *alloc_vmcs_cpu(int cpu)
1366 {
1367         int node = cpu_to_node(cpu);
1368         struct page *pages;
1369         struct vmcs *vmcs;
1370
1371         pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
1372         if (!pages)
1373                 return NULL;
1374         vmcs = page_address(pages);
1375         memset(vmcs, 0, vmcs_config.size);
1376         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
1377         return vmcs;
1378 }
1379
1380 static struct vmcs *alloc_vmcs(void)
1381 {
1382         return alloc_vmcs_cpu(raw_smp_processor_id());
1383 }
1384
1385 static void free_vmcs(struct vmcs *vmcs)
1386 {
1387         free_pages((unsigned long)vmcs, vmcs_config.order);
1388 }
1389
1390 static void free_kvm_area(void)
1391 {
1392         int cpu;
1393
1394         for_each_possible_cpu(cpu) {
1395                 free_vmcs(per_cpu(vmxarea, cpu));
1396                 per_cpu(vmxarea, cpu) = NULL;
1397         }
1398 }
1399
1400 static __init int alloc_kvm_area(void)
1401 {
1402         int cpu;
1403
1404         for_each_possible_cpu(cpu) {
1405                 struct vmcs *vmcs;
1406
1407                 vmcs = alloc_vmcs_cpu(cpu);
1408                 if (!vmcs) {
1409                         free_kvm_area();
1410                         return -ENOMEM;
1411                 }
1412
1413                 per_cpu(vmxarea, cpu) = vmcs;
1414         }
1415         return 0;
1416 }
1417
1418 static __init int hardware_setup(void)
1419 {
1420         if (setup_vmcs_config(&vmcs_config) < 0)
1421                 return -EIO;
1422
1423         if (boot_cpu_has(X86_FEATURE_NX))
1424                 kvm_enable_efer_bits(EFER_NX);
1425
1426         if (!cpu_has_vmx_vpid())
1427                 enable_vpid = 0;
1428
1429         if (!cpu_has_vmx_ept()) {
1430                 enable_ept = 0;
1431                 enable_unrestricted_guest = 0;
1432         }
1433
1434         if (!cpu_has_vmx_unrestricted_guest())
1435                 enable_unrestricted_guest = 0;
1436
1437         if (!cpu_has_vmx_flexpriority())
1438                 flexpriority_enabled = 0;
1439
1440         if (!cpu_has_vmx_tpr_shadow())
1441                 kvm_x86_ops->update_cr8_intercept = NULL;
1442
1443         if (enable_ept && !cpu_has_vmx_ept_2m_page())
1444                 kvm_disable_largepages();
1445
1446         if (!cpu_has_vmx_ple())
1447                 ple_gap = 0;
1448
1449         return alloc_kvm_area();
1450 }
1451
1452 static __exit void hardware_unsetup(void)
1453 {
1454         free_kvm_area();
1455 }
1456
1457 static void fix_pmode_dataseg(int seg, struct kvm_save_segment *save)
1458 {
1459         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1460
1461         if (vmcs_readl(sf->base) == save->base && (save->base & AR_S_MASK)) {
1462                 vmcs_write16(sf->selector, save->selector);
1463                 vmcs_writel(sf->base, save->base);
1464                 vmcs_write32(sf->limit, save->limit);
1465                 vmcs_write32(sf->ar_bytes, save->ar);
1466         } else {
1467                 u32 dpl = (vmcs_read16(sf->selector) & SELECTOR_RPL_MASK)
1468                         << AR_DPL_SHIFT;
1469                 vmcs_write32(sf->ar_bytes, 0x93 | dpl);
1470         }
1471 }
1472
1473 static void enter_pmode(struct kvm_vcpu *vcpu)
1474 {
1475         unsigned long flags;
1476         struct vcpu_vmx *vmx = to_vmx(vcpu);
1477
1478         vmx->emulation_required = 1;
1479         vmx->rmode.vm86_active = 0;
1480
1481         vmcs_writel(GUEST_TR_BASE, vmx->rmode.tr.base);
1482         vmcs_write32(GUEST_TR_LIMIT, vmx->rmode.tr.limit);
1483         vmcs_write32(GUEST_TR_AR_BYTES, vmx->rmode.tr.ar);
1484
1485         flags = vmcs_readl(GUEST_RFLAGS);
1486         flags &= ~(X86_EFLAGS_IOPL | X86_EFLAGS_VM);
1487         flags |= (vmx->rmode.save_iopl << IOPL_SHIFT);
1488         vmcs_writel(GUEST_RFLAGS, flags);
1489
1490         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
1491                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
1492
1493         update_exception_bitmap(vcpu);
1494
1495         if (emulate_invalid_guest_state)
1496                 return;
1497
1498         fix_pmode_dataseg(VCPU_SREG_ES, &vmx->rmode.es);
1499         fix_pmode_dataseg(VCPU_SREG_DS, &vmx->rmode.ds);
1500         fix_pmode_dataseg(VCPU_SREG_GS, &vmx->rmode.gs);
1501         fix_pmode_dataseg(VCPU_SREG_FS, &vmx->rmode.fs);
1502
1503         vmcs_write16(GUEST_SS_SELECTOR, 0);
1504         vmcs_write32(GUEST_SS_AR_BYTES, 0x93);
1505
1506         vmcs_write16(GUEST_CS_SELECTOR,
1507                      vmcs_read16(GUEST_CS_SELECTOR) & ~SELECTOR_RPL_MASK);
1508         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
1509 }
1510
1511 static gva_t rmode_tss_base(struct kvm *kvm)
1512 {
1513         if (!kvm->arch.tss_addr) {
1514                 struct kvm_memslots *slots;
1515                 gfn_t base_gfn;
1516
1517                 slots = rcu_dereference(kvm->memslots);
1518                 base_gfn = kvm->memslots->memslots[0].base_gfn +
1519                                  kvm->memslots->memslots[0].npages - 3;
1520                 return base_gfn << PAGE_SHIFT;
1521         }
1522         return kvm->arch.tss_addr;
1523 }
1524
1525 static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
1526 {
1527         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1528
1529         save->selector = vmcs_read16(sf->selector);
1530         save->base = vmcs_readl(sf->base);
1531         save->limit = vmcs_read32(sf->limit);
1532         save->ar = vmcs_read32(sf->ar_bytes);
1533         vmcs_write16(sf->selector, save->base >> 4);
1534         vmcs_write32(sf->base, save->base & 0xfffff);
1535         vmcs_write32(sf->limit, 0xffff);
1536         vmcs_write32(sf->ar_bytes, 0xf3);
1537 }
1538
1539 static void enter_rmode(struct kvm_vcpu *vcpu)
1540 {
1541         unsigned long flags;
1542         struct vcpu_vmx *vmx = to_vmx(vcpu);
1543
1544         if (enable_unrestricted_guest)
1545                 return;
1546
1547         vmx->emulation_required = 1;
1548         vmx->rmode.vm86_active = 1;
1549
1550         vmx->rmode.tr.base = vmcs_readl(GUEST_TR_BASE);
1551         vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
1552
1553         vmx->rmode.tr.limit = vmcs_read32(GUEST_TR_LIMIT);
1554         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
1555
1556         vmx->rmode.tr.ar = vmcs_read32(GUEST_TR_AR_BYTES);
1557         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
1558
1559         flags = vmcs_readl(GUEST_RFLAGS);
1560         vmx->rmode.save_iopl
1561                 = (flags & X86_EFLAGS_IOPL) >> IOPL_SHIFT;
1562
1563         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1564
1565         vmcs_writel(GUEST_RFLAGS, flags);
1566         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
1567         update_exception_bitmap(vcpu);
1568
1569         if (emulate_invalid_guest_state)
1570                 goto continue_rmode;
1571
1572         vmcs_write16(GUEST_SS_SELECTOR, vmcs_readl(GUEST_SS_BASE) >> 4);
1573         vmcs_write32(GUEST_SS_LIMIT, 0xffff);
1574         vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
1575
1576         vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
1577         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
1578         if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
1579                 vmcs_writel(GUEST_CS_BASE, 0xf0000);
1580         vmcs_write16(GUEST_CS_SELECTOR, vmcs_readl(GUEST_CS_BASE) >> 4);
1581
1582         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.es);
1583         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.ds);
1584         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.gs);
1585         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.fs);
1586
1587 continue_rmode:
1588         kvm_mmu_reset_context(vcpu);
1589         init_rmode(vcpu->kvm);
1590 }
1591
1592 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
1593 {
1594         struct vcpu_vmx *vmx = to_vmx(vcpu);
1595         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
1596
1597         if (!msr)
1598                 return;
1599
1600         /*
1601          * Force kernel_gs_base reloading before EFER changes, as control
1602          * of this msr depends on is_long_mode().
1603          */
1604         vmx_load_host_state(to_vmx(vcpu));
1605         vcpu->arch.efer = efer;
1606         if (efer & EFER_LMA) {
1607                 vmcs_write32(VM_ENTRY_CONTROLS,
1608                              vmcs_read32(VM_ENTRY_CONTROLS) |
1609                              VM_ENTRY_IA32E_MODE);
1610                 msr->data = efer;
1611         } else {
1612                 vmcs_write32(VM_ENTRY_CONTROLS,
1613                              vmcs_read32(VM_ENTRY_CONTROLS) &
1614                              ~VM_ENTRY_IA32E_MODE);
1615
1616                 msr->data = efer & ~EFER_LME;
1617         }
1618         setup_msrs(vmx);
1619 }
1620
1621 #ifdef CONFIG_X86_64
1622
1623 static void enter_lmode(struct kvm_vcpu *vcpu)
1624 {
1625         u32 guest_tr_ar;
1626
1627         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
1628         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
1629                 printk(KERN_DEBUG "%s: tss fixup for long mode. \n",
1630                        __func__);
1631                 vmcs_write32(GUEST_TR_AR_BYTES,
1632                              (guest_tr_ar & ~AR_TYPE_MASK)
1633                              | AR_TYPE_BUSY_64_TSS);
1634         }
1635         vcpu->arch.efer |= EFER_LMA;
1636         vmx_set_efer(vcpu, vcpu->arch.efer);
1637 }
1638
1639 static void exit_lmode(struct kvm_vcpu *vcpu)
1640 {
1641         vcpu->arch.efer &= ~EFER_LMA;
1642
1643         vmcs_write32(VM_ENTRY_CONTROLS,
1644                      vmcs_read32(VM_ENTRY_CONTROLS)
1645                      & ~VM_ENTRY_IA32E_MODE);
1646 }
1647
1648 #endif
1649
1650 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
1651 {
1652         vpid_sync_vcpu_all(to_vmx(vcpu));
1653         if (enable_ept)
1654                 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
1655 }
1656
1657 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
1658 {
1659         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
1660
1661         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
1662         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
1663 }
1664
1665 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
1666 {
1667         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
1668
1669         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
1670         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
1671 }
1672
1673 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
1674 {
1675         if (!test_bit(VCPU_EXREG_PDPTR,
1676                       (unsigned long *)&vcpu->arch.regs_dirty))
1677                 return;
1678
1679         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
1680                 vmcs_write64(GUEST_PDPTR0, vcpu->arch.pdptrs[0]);
1681                 vmcs_write64(GUEST_PDPTR1, vcpu->arch.pdptrs[1]);
1682                 vmcs_write64(GUEST_PDPTR2, vcpu->arch.pdptrs[2]);
1683                 vmcs_write64(GUEST_PDPTR3, vcpu->arch.pdptrs[3]);
1684         }
1685 }
1686
1687 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
1688 {
1689         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
1690                 vcpu->arch.pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
1691                 vcpu->arch.pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
1692                 vcpu->arch.pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
1693                 vcpu->arch.pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
1694         }
1695
1696         __set_bit(VCPU_EXREG_PDPTR,
1697                   (unsigned long *)&vcpu->arch.regs_avail);
1698         __set_bit(VCPU_EXREG_PDPTR,
1699                   (unsigned long *)&vcpu->arch.regs_dirty);
1700 }
1701
1702 static void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
1703
1704 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
1705                                         unsigned long cr0,
1706                                         struct kvm_vcpu *vcpu)
1707 {
1708         if (!(cr0 & X86_CR0_PG)) {
1709                 /* From paging/starting to nonpaging */
1710                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
1711                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
1712                              (CPU_BASED_CR3_LOAD_EXITING |
1713                               CPU_BASED_CR3_STORE_EXITING));
1714                 vcpu->arch.cr0 = cr0;
1715                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
1716         } else if (!is_paging(vcpu)) {
1717                 /* From nonpaging to paging */
1718                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
1719                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
1720                              ~(CPU_BASED_CR3_LOAD_EXITING |
1721                                CPU_BASED_CR3_STORE_EXITING));
1722                 vcpu->arch.cr0 = cr0;
1723                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
1724         }
1725
1726         if (!(cr0 & X86_CR0_WP))
1727                 *hw_cr0 &= ~X86_CR0_WP;
1728 }
1729
1730 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1731 {
1732         struct vcpu_vmx *vmx = to_vmx(vcpu);
1733         unsigned long hw_cr0;
1734
1735         if (enable_unrestricted_guest)
1736                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST)
1737                         | KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
1738         else
1739                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK) | KVM_VM_CR0_ALWAYS_ON;
1740
1741         if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
1742                 enter_pmode(vcpu);
1743
1744         if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
1745                 enter_rmode(vcpu);
1746
1747 #ifdef CONFIG_X86_64
1748         if (vcpu->arch.efer & EFER_LME) {
1749                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
1750                         enter_lmode(vcpu);
1751                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
1752                         exit_lmode(vcpu);
1753         }
1754 #endif
1755
1756         if (enable_ept)
1757                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
1758
1759         if (!vcpu->fpu_active)
1760                 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
1761
1762         vmcs_writel(CR0_READ_SHADOW, cr0);
1763         vmcs_writel(GUEST_CR0, hw_cr0);
1764         vcpu->arch.cr0 = cr0;
1765 }
1766
1767 static u64 construct_eptp(unsigned long root_hpa)
1768 {
1769         u64 eptp;
1770
1771         /* TODO write the value reading from MSR */
1772         eptp = VMX_EPT_DEFAULT_MT |
1773                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
1774         eptp |= (root_hpa & PAGE_MASK);
1775
1776         return eptp;
1777 }
1778
1779 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1780 {
1781         unsigned long guest_cr3;
1782         u64 eptp;
1783
1784         guest_cr3 = cr3;
1785         if (enable_ept) {
1786                 eptp = construct_eptp(cr3);
1787                 vmcs_write64(EPT_POINTER, eptp);
1788                 guest_cr3 = is_paging(vcpu) ? vcpu->arch.cr3 :
1789                         vcpu->kvm->arch.ept_identity_map_addr;
1790                 ept_load_pdptrs(vcpu);
1791         }
1792
1793         vmx_flush_tlb(vcpu);
1794         vmcs_writel(GUEST_CR3, guest_cr3);
1795 }
1796
1797 static void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1798 {
1799         unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
1800                     KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
1801
1802         vcpu->arch.cr4 = cr4;
1803         if (enable_ept) {
1804                 if (!is_paging(vcpu)) {
1805                         hw_cr4 &= ~X86_CR4_PAE;
1806                         hw_cr4 |= X86_CR4_PSE;
1807                 } else if (!(cr4 & X86_CR4_PAE)) {
1808                         hw_cr4 &= ~X86_CR4_PAE;
1809                 }
1810         }
1811
1812         vmcs_writel(CR4_READ_SHADOW, cr4);
1813         vmcs_writel(GUEST_CR4, hw_cr4);
1814 }
1815
1816 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1817 {
1818         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1819
1820         return vmcs_readl(sf->base);
1821 }
1822
1823 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1824                             struct kvm_segment *var, int seg)
1825 {
1826         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1827         u32 ar;
1828
1829         var->base = vmcs_readl(sf->base);
1830         var->limit = vmcs_read32(sf->limit);
1831         var->selector = vmcs_read16(sf->selector);
1832         ar = vmcs_read32(sf->ar_bytes);
1833         if ((ar & AR_UNUSABLE_MASK) && !emulate_invalid_guest_state)
1834                 ar = 0;
1835         var->type = ar & 15;
1836         var->s = (ar >> 4) & 1;
1837         var->dpl = (ar >> 5) & 3;
1838         var->present = (ar >> 7) & 1;
1839         var->avl = (ar >> 12) & 1;
1840         var->l = (ar >> 13) & 1;
1841         var->db = (ar >> 14) & 1;
1842         var->g = (ar >> 15) & 1;
1843         var->unusable = (ar >> 16) & 1;
1844 }
1845
1846 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
1847 {
1848         if (!is_protmode(vcpu))
1849                 return 0;
1850
1851         if (vmx_get_rflags(vcpu) & X86_EFLAGS_VM) /* if virtual 8086 */
1852                 return 3;
1853
1854         return vmcs_read16(GUEST_CS_SELECTOR) & 3;
1855 }
1856
1857 static u32 vmx_segment_access_rights(struct kvm_segment *var)
1858 {
1859         u32 ar;
1860
1861         if (var->unusable)
1862                 ar = 1 << 16;
1863         else {
1864                 ar = var->type & 15;
1865                 ar |= (var->s & 1) << 4;
1866                 ar |= (var->dpl & 3) << 5;
1867                 ar |= (var->present & 1) << 7;
1868                 ar |= (var->avl & 1) << 12;
1869                 ar |= (var->l & 1) << 13;
1870                 ar |= (var->db & 1) << 14;
1871                 ar |= (var->g & 1) << 15;
1872         }
1873         if (ar == 0) /* a 0 value means unusable */
1874                 ar = AR_UNUSABLE_MASK;
1875
1876         return ar;
1877 }
1878
1879 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1880                             struct kvm_segment *var, int seg)
1881 {
1882         struct vcpu_vmx *vmx = to_vmx(vcpu);
1883         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1884         u32 ar;
1885
1886         if (vmx->rmode.vm86_active && seg == VCPU_SREG_TR) {
1887                 vmx->rmode.tr.selector = var->selector;
1888                 vmx->rmode.tr.base = var->base;
1889                 vmx->rmode.tr.limit = var->limit;
1890                 vmx->rmode.tr.ar = vmx_segment_access_rights(var);
1891                 return;
1892         }
1893         vmcs_writel(sf->base, var->base);
1894         vmcs_write32(sf->limit, var->limit);
1895         vmcs_write16(sf->selector, var->selector);
1896         if (vmx->rmode.vm86_active && var->s) {
1897                 /*
1898                  * Hack real-mode segments into vm86 compatibility.
1899                  */
1900                 if (var->base == 0xffff0000 && var->selector == 0xf000)
1901                         vmcs_writel(sf->base, 0xf0000);
1902                 ar = 0xf3;
1903         } else
1904                 ar = vmx_segment_access_rights(var);
1905
1906         /*
1907          *   Fix the "Accessed" bit in AR field of segment registers for older
1908          * qemu binaries.
1909          *   IA32 arch specifies that at the time of processor reset the
1910          * "Accessed" bit in the AR field of segment registers is 1. And qemu
1911          * is setting it to 0 in the usedland code. This causes invalid guest
1912          * state vmexit when "unrestricted guest" mode is turned on.
1913          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
1914          * tree. Newer qemu binaries with that qemu fix would not need this
1915          * kvm hack.
1916          */
1917         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
1918                 ar |= 0x1; /* Accessed */
1919
1920         vmcs_write32(sf->ar_bytes, ar);
1921 }
1922
1923 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
1924 {
1925         u32 ar = vmcs_read32(GUEST_CS_AR_BYTES);
1926
1927         *db = (ar >> 14) & 1;
1928         *l = (ar >> 13) & 1;
1929 }
1930
1931 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1932 {
1933         dt->limit = vmcs_read32(GUEST_IDTR_LIMIT);
1934         dt->base = vmcs_readl(GUEST_IDTR_BASE);
1935 }
1936
1937 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1938 {
1939         vmcs_write32(GUEST_IDTR_LIMIT, dt->limit);
1940         vmcs_writel(GUEST_IDTR_BASE, dt->base);
1941 }
1942
1943 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1944 {
1945         dt->limit = vmcs_read32(GUEST_GDTR_LIMIT);
1946         dt->base = vmcs_readl(GUEST_GDTR_BASE);
1947 }
1948
1949 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1950 {
1951         vmcs_write32(GUEST_GDTR_LIMIT, dt->limit);
1952         vmcs_writel(GUEST_GDTR_BASE, dt->base);
1953 }
1954
1955 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
1956 {
1957         struct kvm_segment var;
1958         u32 ar;
1959
1960         vmx_get_segment(vcpu, &var, seg);
1961         ar = vmx_segment_access_rights(&var);
1962
1963         if (var.base != (var.selector << 4))
1964                 return false;
1965         if (var.limit != 0xffff)
1966                 return false;
1967         if (ar != 0xf3)
1968                 return false;
1969
1970         return true;
1971 }
1972
1973 static bool code_segment_valid(struct kvm_vcpu *vcpu)
1974 {
1975         struct kvm_segment cs;
1976         unsigned int cs_rpl;
1977
1978         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
1979         cs_rpl = cs.selector & SELECTOR_RPL_MASK;
1980
1981         if (cs.unusable)
1982                 return false;
1983         if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
1984                 return false;
1985         if (!cs.s)
1986                 return false;
1987         if (cs.type & AR_TYPE_WRITEABLE_MASK) {
1988                 if (cs.dpl > cs_rpl)
1989                         return false;
1990         } else {
1991                 if (cs.dpl != cs_rpl)
1992                         return false;
1993         }
1994         if (!cs.present)
1995                 return false;
1996
1997         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
1998         return true;
1999 }
2000
2001 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
2002 {
2003         struct kvm_segment ss;
2004         unsigned int ss_rpl;
2005
2006         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2007         ss_rpl = ss.selector & SELECTOR_RPL_MASK;
2008
2009         if (ss.unusable)
2010                 return true;
2011         if (ss.type != 3 && ss.type != 7)
2012                 return false;
2013         if (!ss.s)
2014                 return false;
2015         if (ss.dpl != ss_rpl) /* DPL != RPL */
2016                 return false;
2017         if (!ss.present)
2018                 return false;
2019
2020         return true;
2021 }
2022
2023 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
2024 {
2025         struct kvm_segment var;
2026         unsigned int rpl;
2027
2028         vmx_get_segment(vcpu, &var, seg);
2029         rpl = var.selector & SELECTOR_RPL_MASK;
2030
2031         if (var.unusable)
2032                 return true;
2033         if (!var.s)
2034                 return false;
2035         if (!var.present)
2036                 return false;
2037         if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
2038                 if (var.dpl < rpl) /* DPL < RPL */
2039                         return false;
2040         }
2041
2042         /* TODO: Add other members to kvm_segment_field to allow checking for other access
2043          * rights flags
2044          */
2045         return true;
2046 }
2047
2048 static bool tr_valid(struct kvm_vcpu *vcpu)
2049 {
2050         struct kvm_segment tr;
2051
2052         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
2053
2054         if (tr.unusable)
2055                 return false;
2056         if (tr.selector & SELECTOR_TI_MASK)     /* TI = 1 */
2057                 return false;
2058         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
2059                 return false;
2060         if (!tr.present)
2061                 return false;
2062
2063         return true;
2064 }
2065
2066 static bool ldtr_valid(struct kvm_vcpu *vcpu)
2067 {
2068         struct kvm_segment ldtr;
2069
2070         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
2071
2072         if (ldtr.unusable)
2073                 return true;
2074         if (ldtr.selector & SELECTOR_TI_MASK)   /* TI = 1 */
2075                 return false;
2076         if (ldtr.type != 2)
2077                 return false;
2078         if (!ldtr.present)
2079                 return false;
2080
2081         return true;
2082 }
2083
2084 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
2085 {
2086         struct kvm_segment cs, ss;
2087
2088         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
2089         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2090
2091         return ((cs.selector & SELECTOR_RPL_MASK) ==
2092                  (ss.selector & SELECTOR_RPL_MASK));
2093 }
2094
2095 /*
2096  * Check if guest state is valid. Returns true if valid, false if
2097  * not.
2098  * We assume that registers are always usable
2099  */
2100 static bool guest_state_valid(struct kvm_vcpu *vcpu)
2101 {
2102         /* real mode guest state checks */
2103         if (!is_protmode(vcpu)) {
2104                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
2105                         return false;
2106                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
2107                         return false;
2108                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
2109                         return false;
2110                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
2111                         return false;
2112                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
2113                         return false;
2114                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
2115                         return false;
2116         } else {
2117         /* protected mode guest state checks */
2118                 if (!cs_ss_rpl_check(vcpu))
2119                         return false;
2120                 if (!code_segment_valid(vcpu))
2121                         return false;
2122                 if (!stack_segment_valid(vcpu))
2123                         return false;
2124                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
2125                         return false;
2126                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
2127                         return false;
2128                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
2129                         return false;
2130                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
2131                         return false;
2132                 if (!tr_valid(vcpu))
2133                         return false;
2134                 if (!ldtr_valid(vcpu))
2135                         return false;
2136         }
2137         /* TODO:
2138          * - Add checks on RIP
2139          * - Add checks on RFLAGS
2140          */
2141
2142         return true;
2143 }
2144
2145 static int init_rmode_tss(struct kvm *kvm)
2146 {
2147         gfn_t fn = rmode_tss_base(kvm) >> PAGE_SHIFT;
2148         u16 data = 0;
2149         int ret = 0;
2150         int r;
2151
2152         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
2153         if (r < 0)
2154                 goto out;
2155         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
2156         r = kvm_write_guest_page(kvm, fn++, &data,
2157                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
2158         if (r < 0)
2159                 goto out;
2160         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
2161         if (r < 0)
2162                 goto out;
2163         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
2164         if (r < 0)
2165                 goto out;
2166         data = ~0;
2167         r = kvm_write_guest_page(kvm, fn, &data,
2168                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
2169                                  sizeof(u8));
2170         if (r < 0)
2171                 goto out;
2172
2173         ret = 1;
2174 out:
2175         return ret;
2176 }
2177
2178 static int init_rmode_identity_map(struct kvm *kvm)
2179 {
2180         int i, r, ret;
2181         pfn_t identity_map_pfn;
2182         u32 tmp;
2183
2184         if (!enable_ept)
2185                 return 1;
2186         if (unlikely(!kvm->arch.ept_identity_pagetable)) {
2187                 printk(KERN_ERR "EPT: identity-mapping pagetable "
2188                         "haven't been allocated!\n");
2189                 return 0;
2190         }
2191         if (likely(kvm->arch.ept_identity_pagetable_done))
2192                 return 1;
2193         ret = 0;
2194         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
2195         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
2196         if (r < 0)
2197                 goto out;
2198         /* Set up identity-mapping pagetable for EPT in real mode */
2199         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
2200                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
2201                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
2202                 r = kvm_write_guest_page(kvm, identity_map_pfn,
2203                                 &tmp, i * sizeof(tmp), sizeof(tmp));
2204                 if (r < 0)
2205                         goto out;
2206         }
2207         kvm->arch.ept_identity_pagetable_done = true;
2208         ret = 1;
2209 out:
2210         return ret;
2211 }
2212
2213 static void seg_setup(int seg)
2214 {
2215         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2216         unsigned int ar;
2217
2218         vmcs_write16(sf->selector, 0);
2219         vmcs_writel(sf->base, 0);
2220         vmcs_write32(sf->limit, 0xffff);
2221         if (enable_unrestricted_guest) {
2222                 ar = 0x93;
2223                 if (seg == VCPU_SREG_CS)
2224                         ar |= 0x08; /* code segment */
2225         } else
2226                 ar = 0xf3;
2227
2228         vmcs_write32(sf->ar_bytes, ar);
2229 }
2230
2231 static int alloc_apic_access_page(struct kvm *kvm)
2232 {
2233         struct kvm_userspace_memory_region kvm_userspace_mem;
2234         int r = 0;
2235
2236         mutex_lock(&kvm->slots_lock);
2237         if (kvm->arch.apic_access_page)
2238                 goto out;
2239         kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
2240         kvm_userspace_mem.flags = 0;
2241         kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
2242         kvm_userspace_mem.memory_size = PAGE_SIZE;
2243         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
2244         if (r)
2245                 goto out;
2246
2247         kvm->arch.apic_access_page = gfn_to_page(kvm, 0xfee00);
2248 out:
2249         mutex_unlock(&kvm->slots_lock);
2250         return r;
2251 }
2252
2253 static int alloc_identity_pagetable(struct kvm *kvm)
2254 {
2255         struct kvm_userspace_memory_region kvm_userspace_mem;
2256         int r = 0;
2257
2258         mutex_lock(&kvm->slots_lock);
2259         if (kvm->arch.ept_identity_pagetable)
2260                 goto out;
2261         kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
2262         kvm_userspace_mem.flags = 0;
2263         kvm_userspace_mem.guest_phys_addr =
2264                 kvm->arch.ept_identity_map_addr;
2265         kvm_userspace_mem.memory_size = PAGE_SIZE;
2266         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
2267         if (r)
2268                 goto out;
2269
2270         kvm->arch.ept_identity_pagetable = gfn_to_page(kvm,
2271                         kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
2272 out:
2273         mutex_unlock(&kvm->slots_lock);
2274         return r;
2275 }
2276
2277 static void allocate_vpid(struct vcpu_vmx *vmx)
2278 {
2279         int vpid;
2280
2281         vmx->vpid = 0;
2282         if (!enable_vpid)
2283                 return;
2284         spin_lock(&vmx_vpid_lock);
2285         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
2286         if (vpid < VMX_NR_VPIDS) {
2287                 vmx->vpid = vpid;
2288                 __set_bit(vpid, vmx_vpid_bitmap);
2289         }
2290         spin_unlock(&vmx_vpid_lock);
2291 }
2292
2293 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap, u32 msr)
2294 {
2295         int f = sizeof(unsigned long);
2296
2297         if (!cpu_has_vmx_msr_bitmap())
2298                 return;
2299
2300         /*
2301          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
2302          * have the write-low and read-high bitmap offsets the wrong way round.
2303          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
2304          */
2305         if (msr <= 0x1fff) {
2306                 __clear_bit(msr, msr_bitmap + 0x000 / f); /* read-low */
2307                 __clear_bit(msr, msr_bitmap + 0x800 / f); /* write-low */
2308         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2309                 msr &= 0x1fff;
2310                 __clear_bit(msr, msr_bitmap + 0x400 / f); /* read-high */
2311                 __clear_bit(msr, msr_bitmap + 0xc00 / f); /* write-high */
2312         }
2313 }
2314
2315 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
2316 {
2317         if (!longmode_only)
2318                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy, msr);
2319         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode, msr);
2320 }
2321
2322 /*
2323  * Sets up the vmcs for emulated real mode.
2324  */
2325 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
2326 {
2327         u32 host_sysenter_cs, msr_low, msr_high;
2328         u32 junk;
2329         u64 host_pat, tsc_this, tsc_base;
2330         unsigned long a;
2331         struct descriptor_table dt;
2332         int i;
2333         unsigned long kvm_vmx_return;
2334         u32 exec_control;
2335
2336         /* I/O */
2337         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
2338         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
2339
2340         if (cpu_has_vmx_msr_bitmap())
2341                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
2342
2343         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
2344
2345         /* Control */
2346         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
2347                 vmcs_config.pin_based_exec_ctrl);
2348
2349         exec_control = vmcs_config.cpu_based_exec_ctrl;
2350         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
2351                 exec_control &= ~CPU_BASED_TPR_SHADOW;
2352 #ifdef CONFIG_X86_64
2353                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
2354                                 CPU_BASED_CR8_LOAD_EXITING;
2355 #endif
2356         }
2357         if (!enable_ept)
2358                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
2359                                 CPU_BASED_CR3_LOAD_EXITING  |
2360                                 CPU_BASED_INVLPG_EXITING;
2361         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
2362
2363         if (cpu_has_secondary_exec_ctrls()) {
2364                 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
2365                 if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
2366                         exec_control &=
2367                                 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
2368                 if (vmx->vpid == 0)
2369                         exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
2370                 if (!enable_ept) {
2371                         exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
2372                         enable_unrestricted_guest = 0;
2373                 }
2374                 if (!enable_unrestricted_guest)
2375                         exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
2376                 if (!ple_gap)
2377                         exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
2378                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
2379         }
2380
2381         if (ple_gap) {
2382                 vmcs_write32(PLE_GAP, ple_gap);
2383                 vmcs_write32(PLE_WINDOW, ple_window);
2384         }
2385
2386         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, !!bypass_guest_pf);
2387         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, !!bypass_guest_pf);
2388         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
2389
2390         vmcs_writel(HOST_CR0, read_cr0());  /* 22.2.3 */
2391         vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
2392         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
2393
2394         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
2395         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
2396         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
2397         vmcs_write16(HOST_FS_SELECTOR, kvm_read_fs());    /* 22.2.4 */
2398         vmcs_write16(HOST_GS_SELECTOR, kvm_read_gs());    /* 22.2.4 */
2399         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
2400 #ifdef CONFIG_X86_64
2401         rdmsrl(MSR_FS_BASE, a);
2402         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
2403         rdmsrl(MSR_GS_BASE, a);
2404         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
2405 #else
2406         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
2407         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
2408 #endif
2409
2410         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
2411
2412         kvm_get_idt(&dt);
2413         vmcs_writel(HOST_IDTR_BASE, dt.base);   /* 22.2.4 */
2414
2415         asm("mov $.Lkvm_vmx_return, %0" : "=r"(kvm_vmx_return));
2416         vmcs_writel(HOST_RIP, kvm_vmx_return); /* 22.2.5 */
2417         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
2418         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
2419         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
2420
2421         rdmsr(MSR_IA32_SYSENTER_CS, host_sysenter_cs, junk);
2422         vmcs_write32(HOST_IA32_SYSENTER_CS, host_sysenter_cs);
2423         rdmsrl(MSR_IA32_SYSENTER_ESP, a);
2424         vmcs_writel(HOST_IA32_SYSENTER_ESP, a);   /* 22.2.3 */
2425         rdmsrl(MSR_IA32_SYSENTER_EIP, a);
2426         vmcs_writel(HOST_IA32_SYSENTER_EIP, a);   /* 22.2.3 */
2427
2428         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
2429                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
2430                 host_pat = msr_low | ((u64) msr_high << 32);
2431                 vmcs_write64(HOST_IA32_PAT, host_pat);
2432         }
2433         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2434                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
2435                 host_pat = msr_low | ((u64) msr_high << 32);
2436                 /* Write the default value follow host pat */
2437                 vmcs_write64(GUEST_IA32_PAT, host_pat);
2438                 /* Keep arch.pat sync with GUEST_IA32_PAT */
2439                 vmx->vcpu.arch.pat = host_pat;
2440         }
2441
2442         for (i = 0; i < NR_VMX_MSR; ++i) {
2443                 u32 index = vmx_msr_index[i];
2444                 u32 data_low, data_high;
2445                 int j = vmx->nmsrs;
2446
2447                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
2448                         continue;
2449                 if (wrmsr_safe(index, data_low, data_high) < 0)
2450                         continue;
2451                 vmx->guest_msrs[j].index = i;
2452                 vmx->guest_msrs[j].data = 0;
2453                 vmx->guest_msrs[j].mask = -1ull;
2454                 ++vmx->nmsrs;
2455         }
2456
2457         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
2458
2459         /* 22.2.1, 20.8.1 */
2460         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
2461
2462         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
2463         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
2464         if (enable_ept)
2465                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
2466         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
2467
2468         tsc_base = vmx->vcpu.kvm->arch.vm_init_tsc;
2469         rdtscll(tsc_this);
2470         if (tsc_this < vmx->vcpu.kvm->arch.vm_init_tsc)
2471                 tsc_base = tsc_this;
2472
2473         guest_write_tsc(0, tsc_base);
2474
2475         return 0;
2476 }
2477
2478 static int init_rmode(struct kvm *kvm)
2479 {
2480         if (!init_rmode_tss(kvm))
2481                 return 0;
2482         if (!init_rmode_identity_map(kvm))
2483                 return 0;
2484         return 1;
2485 }
2486
2487 static int vmx_vcpu_reset(struct kvm_vcpu *vcpu)
2488 {
2489         struct vcpu_vmx *vmx = to_vmx(vcpu);
2490         u64 msr;
2491         int ret, idx;
2492
2493         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP));
2494         idx = srcu_read_lock(&vcpu->kvm->srcu);
2495         if (!init_rmode(vmx->vcpu.kvm)) {
2496                 ret = -ENOMEM;
2497                 goto out;
2498         }
2499
2500         vmx->rmode.vm86_active = 0;
2501
2502         vmx->soft_vnmi_blocked = 0;
2503
2504         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
2505         kvm_set_cr8(&vmx->vcpu, 0);
2506         msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
2507         if (kvm_vcpu_is_bsp(&vmx->vcpu))
2508                 msr |= MSR_IA32_APICBASE_BSP;
2509         kvm_set_apic_base(&vmx->vcpu, msr);
2510
2511         fx_init(&vmx->vcpu);
2512
2513         seg_setup(VCPU_SREG_CS);
2514         /*
2515          * GUEST_CS_BASE should really be 0xffff0000, but VT vm86 mode
2516          * insists on having GUEST_CS_BASE == GUEST_CS_SELECTOR << 4.  Sigh.
2517          */
2518         if (kvm_vcpu_is_bsp(&vmx->vcpu)) {
2519                 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
2520                 vmcs_writel(GUEST_CS_BASE, 0x000f0000);
2521         } else {
2522                 vmcs_write16(GUEST_CS_SELECTOR, vmx->vcpu.arch.sipi_vector << 8);
2523                 vmcs_writel(GUEST_CS_BASE, vmx->vcpu.arch.sipi_vector << 12);
2524         }
2525
2526         seg_setup(VCPU_SREG_DS);
2527         seg_setup(VCPU_SREG_ES);
2528         seg_setup(VCPU_SREG_FS);
2529         seg_setup(VCPU_SREG_GS);
2530         seg_setup(VCPU_SREG_SS);
2531
2532         vmcs_write16(GUEST_TR_SELECTOR, 0);
2533         vmcs_writel(GUEST_TR_BASE, 0);
2534         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
2535         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2536
2537         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
2538         vmcs_writel(GUEST_LDTR_BASE, 0);
2539         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
2540         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
2541
2542         vmcs_write32(GUEST_SYSENTER_CS, 0);
2543         vmcs_writel(GUEST_SYSENTER_ESP, 0);
2544         vmcs_writel(GUEST_SYSENTER_EIP, 0);
2545
2546         vmcs_writel(GUEST_RFLAGS, 0x02);
2547         if (kvm_vcpu_is_bsp(&vmx->vcpu))
2548                 kvm_rip_write(vcpu, 0xfff0);
2549         else
2550                 kvm_rip_write(vcpu, 0);
2551         kvm_register_write(vcpu, VCPU_REGS_RSP, 0);
2552
2553         vmcs_writel(GUEST_DR7, 0x400);
2554
2555         vmcs_writel(GUEST_GDTR_BASE, 0);
2556         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
2557
2558         vmcs_writel(GUEST_IDTR_BASE, 0);
2559         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
2560
2561         vmcs_write32(GUEST_ACTIVITY_STATE, 0);
2562         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
2563         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
2564
2565         /* Special registers */
2566         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
2567
2568         setup_msrs(vmx);
2569
2570         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
2571
2572         if (cpu_has_vmx_tpr_shadow()) {
2573                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
2574                 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
2575                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
2576                                 page_to_phys(vmx->vcpu.arch.apic->regs_page));
2577                 vmcs_write32(TPR_THRESHOLD, 0);
2578         }
2579
2580         if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
2581                 vmcs_write64(APIC_ACCESS_ADDR,
2582                              page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
2583
2584         if (vmx->vpid != 0)
2585                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
2586
2587         vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
2588         vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
2589         vmx_set_cr4(&vmx->vcpu, 0);
2590         vmx_set_efer(&vmx->vcpu, 0);
2591         vmx_fpu_activate(&vmx->vcpu);
2592         update_exception_bitmap(&vmx->vcpu);
2593
2594         vpid_sync_vcpu_all(vmx);
2595
2596         ret = 0;
2597
2598         /* HACK: Don't enable emulation on guest boot/reset */
2599         vmx->emulation_required = 0;
2600
2601 out:
2602         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2603         return ret;
2604 }
2605
2606 static void enable_irq_window(struct kvm_vcpu *vcpu)
2607 {
2608         u32 cpu_based_vm_exec_control;
2609
2610         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2611         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
2612         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
2613 }
2614
2615 static void enable_nmi_window(struct kvm_vcpu *vcpu)
2616 {
2617         u32 cpu_based_vm_exec_control;
2618
2619         if (!cpu_has_virtual_nmis()) {
2620                 enable_irq_window(vcpu);
2621                 return;
2622         }
2623
2624         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2625         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
2626         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
2627 }
2628
2629 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
2630 {
2631         struct vcpu_vmx *vmx = to_vmx(vcpu);
2632         uint32_t intr;
2633         int irq = vcpu->arch.interrupt.nr;
2634
2635         trace_kvm_inj_virq(irq);
2636
2637         ++vcpu->stat.irq_injections;
2638         if (vmx->rmode.vm86_active) {
2639                 vmx->rmode.irq.pending = true;
2640                 vmx->rmode.irq.vector = irq;
2641                 vmx->rmode.irq.rip = kvm_rip_read(vcpu);
2642                 if (vcpu->arch.interrupt.soft)
2643                         vmx->rmode.irq.rip +=
2644                                 vmx->vcpu.arch.event_exit_inst_len;
2645                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2646                              irq | INTR_TYPE_SOFT_INTR | INTR_INFO_VALID_MASK);
2647                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, 1);
2648                 kvm_rip_write(vcpu, vmx->rmode.irq.rip - 1);
2649                 return;
2650         }
2651         intr = irq | INTR_INFO_VALID_MASK;
2652         if (vcpu->arch.interrupt.soft) {
2653                 intr |= INTR_TYPE_SOFT_INTR;
2654                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2655                              vmx->vcpu.arch.event_exit_inst_len);
2656         } else
2657                 intr |= INTR_TYPE_EXT_INTR;
2658         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
2659 }
2660
2661 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
2662 {
2663         struct vcpu_vmx *vmx = to_vmx(vcpu);
2664
2665         if (!cpu_has_virtual_nmis()) {
2666                 /*
2667                  * Tracking the NMI-blocked state in software is built upon
2668                  * finding the next open IRQ window. This, in turn, depends on
2669                  * well-behaving guests: They have to keep IRQs disabled at
2670                  * least as long as the NMI handler runs. Otherwise we may
2671                  * cause NMI nesting, maybe breaking the guest. But as this is
2672                  * highly unlikely, we can live with the residual risk.
2673                  */
2674                 vmx->soft_vnmi_blocked = 1;
2675                 vmx->vnmi_blocked_time = 0;
2676         }
2677
2678         ++vcpu->stat.nmi_injections;
2679         if (vmx->rmode.vm86_active) {
2680                 vmx->rmode.irq.pending = true;
2681                 vmx->rmode.irq.vector = NMI_VECTOR;
2682                 vmx->rmode.irq.rip = kvm_rip_read(vcpu);
2683                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2684                              NMI_VECTOR | INTR_TYPE_SOFT_INTR |
2685                              INTR_INFO_VALID_MASK);
2686                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, 1);
2687                 kvm_rip_write(vcpu, vmx->rmode.irq.rip - 1);
2688                 return;
2689         }
2690         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2691                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
2692 }
2693
2694 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
2695 {
2696         if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
2697                 return 0;
2698
2699         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
2700                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS |
2701                                 GUEST_INTR_STATE_NMI));
2702 }
2703
2704 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
2705 {
2706         if (!cpu_has_virtual_nmis())
2707                 return to_vmx(vcpu)->soft_vnmi_blocked;
2708         else
2709                 return !!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
2710                           GUEST_INTR_STATE_NMI);
2711 }
2712
2713 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
2714 {
2715         struct vcpu_vmx *vmx = to_vmx(vcpu);
2716
2717         if (!cpu_has_virtual_nmis()) {
2718                 if (vmx->soft_vnmi_blocked != masked) {
2719                         vmx->soft_vnmi_blocked = masked;
2720                         vmx->vnmi_blocked_time = 0;
2721                 }
2722         } else {
2723                 if (masked)
2724                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
2725                                       GUEST_INTR_STATE_NMI);
2726                 else
2727                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
2728                                         GUEST_INTR_STATE_NMI);
2729         }
2730 }
2731
2732 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
2733 {
2734         return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
2735                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
2736                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
2737 }
2738
2739 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
2740 {
2741         int ret;
2742         struct kvm_userspace_memory_region tss_mem = {
2743                 .slot = TSS_PRIVATE_MEMSLOT,
2744                 .guest_phys_addr = addr,
2745                 .memory_size = PAGE_SIZE * 3,
2746                 .flags = 0,
2747         };
2748
2749         ret = kvm_set_memory_region(kvm, &tss_mem, 0);
2750         if (ret)
2751                 return ret;
2752         kvm->arch.tss_addr = addr;
2753         return 0;
2754 }
2755
2756 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
2757                                   int vec, u32 err_code)
2758 {
2759         /*
2760          * Instruction with address size override prefix opcode 0x67
2761          * Cause the #SS fault with 0 error code in VM86 mode.
2762          */
2763         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0)
2764                 if (emulate_instruction(vcpu, 0, 0, 0) == EMULATE_DONE)
2765                         return 1;
2766         /*
2767          * Forward all other exceptions that are valid in real mode.
2768          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
2769          *        the required debugging infrastructure rework.
2770          */
2771         switch (vec) {
2772         case DB_VECTOR:
2773                 if (vcpu->guest_debug &
2774                     (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
2775                         return 0;
2776                 kvm_queue_exception(vcpu, vec);
2777                 return 1;
2778         case BP_VECTOR:
2779                 /*
2780                  * Update instruction length as we may reinject the exception
2781                  * from user space while in guest debugging mode.
2782                  */
2783                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
2784                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2785                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2786                         return 0;
2787                 /* fall through */
2788         case DE_VECTOR:
2789         case OF_VECTOR:
2790         case BR_VECTOR:
2791         case UD_VECTOR:
2792         case DF_VECTOR:
2793         case SS_VECTOR:
2794         case GP_VECTOR:
2795         case MF_VECTOR:
2796                 kvm_queue_exception(vcpu, vec);
2797                 return 1;
2798         }
2799         return 0;
2800 }
2801
2802 /*
2803  * Trigger machine check on the host. We assume all the MSRs are already set up
2804  * by the CPU and that we still run on the same CPU as the MCE occurred on.
2805  * We pass a fake environment to the machine check handler because we want
2806  * the guest to be always treated like user space, no matter what context
2807  * it used internally.
2808  */
2809 static void kvm_machine_check(void)
2810 {
2811 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
2812         struct pt_regs regs = {
2813                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
2814                 .flags = X86_EFLAGS_IF,
2815         };
2816
2817         do_machine_check(&regs, 0);
2818 #endif
2819 }
2820
2821 static int handle_machine_check(struct kvm_vcpu *vcpu)
2822 {
2823         /* already handled by vcpu_run */
2824         return 1;
2825 }
2826
2827 static int handle_exception(struct kvm_vcpu *vcpu)
2828 {
2829         struct vcpu_vmx *vmx = to_vmx(vcpu);
2830         struct kvm_run *kvm_run = vcpu->run;
2831         u32 intr_info, ex_no, error_code;
2832         unsigned long cr2, rip, dr6;
2833         u32 vect_info;
2834         enum emulation_result er;
2835
2836         vect_info = vmx->idt_vectoring_info;
2837         intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
2838
2839         if (is_machine_check(intr_info))
2840                 return handle_machine_check(vcpu);
2841
2842         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
2843             !is_page_fault(intr_info)) {
2844                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2845                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
2846                 vcpu->run->internal.ndata = 2;
2847                 vcpu->run->internal.data[0] = vect_info;
2848                 vcpu->run->internal.data[1] = intr_info;
2849                 return 0;
2850         }
2851
2852         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
2853                 return 1;  /* already handled by vmx_vcpu_run() */
2854
2855         if (is_no_device(intr_info)) {
2856                 vmx_fpu_activate(vcpu);
2857                 return 1;
2858         }
2859
2860         if (is_invalid_opcode(intr_info)) {
2861                 er = emulate_instruction(vcpu, 0, 0, EMULTYPE_TRAP_UD);
2862                 if (er != EMULATE_DONE)
2863                         kvm_queue_exception(vcpu, UD_VECTOR);
2864                 return 1;
2865         }
2866
2867         error_code = 0;
2868         rip = kvm_rip_read(vcpu);
2869         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
2870                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
2871         if (is_page_fault(intr_info)) {
2872                 /* EPT won't cause page fault directly */
2873                 if (enable_ept)
2874                         BUG();
2875                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
2876                 trace_kvm_page_fault(cr2, error_code);
2877
2878                 if (kvm_event_needs_reinjection(vcpu))
2879                         kvm_mmu_unprotect_page_virt(vcpu, cr2);
2880                 return kvm_mmu_page_fault(vcpu, cr2, error_code);
2881         }
2882
2883         if (vmx->rmode.vm86_active &&
2884             handle_rmode_exception(vcpu, intr_info & INTR_INFO_VECTOR_MASK,
2885                                                                 error_code)) {
2886                 if (vcpu->arch.halt_request) {
2887                         vcpu->arch.halt_request = 0;
2888                         return kvm_emulate_halt(vcpu);
2889                 }
2890                 return 1;
2891         }
2892
2893         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
2894         switch (ex_no) {
2895         case DB_VECTOR:
2896                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
2897                 if (!(vcpu->guest_debug &
2898                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
2899                         vcpu->arch.dr6 = dr6 | DR6_FIXED_1;
2900                         kvm_queue_exception(vcpu, DB_VECTOR);
2901                         return 1;
2902                 }
2903                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
2904                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
2905                 /* fall through */
2906         case BP_VECTOR:
2907                 /*
2908                  * Update instruction length as we may reinject #BP from
2909                  * user space while in guest debugging mode. Reading it for
2910                  * #DB as well causes no harm, it is not used in that case.
2911                  */
2912                 vmx->vcpu.arch.event_exit_inst_len =
2913                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2914                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2915                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
2916                 kvm_run->debug.arch.exception = ex_no;
2917                 break;
2918         default:
2919                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
2920                 kvm_run->ex.exception = ex_no;
2921                 kvm_run->ex.error_code = error_code;
2922                 break;
2923         }
2924         return 0;
2925 }
2926
2927 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
2928 {
2929         ++vcpu->stat.irq_exits;
2930         return 1;
2931 }
2932
2933 static int handle_triple_fault(struct kvm_vcpu *vcpu)
2934 {
2935         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
2936         return 0;
2937 }
2938
2939 static int handle_io(struct kvm_vcpu *vcpu)
2940 {
2941         unsigned long exit_qualification;
2942         int size, in, string;
2943         unsigned port;
2944
2945         ++vcpu->stat.io_exits;
2946         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
2947         string = (exit_qualification & 16) != 0;
2948
2949         if (string) {
2950                 if (emulate_instruction(vcpu, 0, 0, 0) == EMULATE_DO_MMIO)
2951                         return 0;
2952                 return 1;
2953         }
2954
2955         size = (exit_qualification & 7) + 1;
2956         in = (exit_qualification & 8) != 0;
2957         port = exit_qualification >> 16;
2958
2959         skip_emulated_instruction(vcpu);
2960         return kvm_emulate_pio(vcpu, in, size, port);
2961 }
2962
2963 static void
2964 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
2965 {
2966         /*
2967          * Patch in the VMCALL instruction:
2968          */
2969         hypercall[0] = 0x0f;
2970         hypercall[1] = 0x01;
2971         hypercall[2] = 0xc1;
2972 }
2973
2974 static int handle_cr(struct kvm_vcpu *vcpu)
2975 {
2976         unsigned long exit_qualification, val;
2977         int cr;
2978         int reg;
2979
2980         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
2981         cr = exit_qualification & 15;
2982         reg = (exit_qualification >> 8) & 15;
2983         switch ((exit_qualification >> 4) & 3) {
2984         case 0: /* mov to cr */
2985                 val = kvm_register_read(vcpu, reg);
2986                 trace_kvm_cr_write(cr, val);
2987                 switch (cr) {
2988                 case 0:
2989                         kvm_set_cr0(vcpu, val);
2990                         skip_emulated_instruction(vcpu);
2991                         return 1;
2992                 case 3:
2993                         kvm_set_cr3(vcpu, val);
2994                         skip_emulated_instruction(vcpu);
2995                         return 1;
2996                 case 4:
2997                         kvm_set_cr4(vcpu, val);
2998                         skip_emulated_instruction(vcpu);
2999                         return 1;
3000                 case 8: {
3001                                 u8 cr8_prev = kvm_get_cr8(vcpu);
3002                                 u8 cr8 = kvm_register_read(vcpu, reg);
3003                                 kvm_set_cr8(vcpu, cr8);
3004                                 skip_emulated_instruction(vcpu);
3005                                 if (irqchip_in_kernel(vcpu->kvm))
3006                                         return 1;
3007                                 if (cr8_prev <= cr8)
3008                                         return 1;
3009                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
3010                                 return 0;
3011                         }
3012                 };
3013                 break;
3014         case 2: /* clts */
3015                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
3016                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
3017                 skip_emulated_instruction(vcpu);
3018                 vmx_fpu_activate(vcpu);
3019                 return 1;
3020         case 1: /*mov from cr*/
3021                 switch (cr) {
3022                 case 3:
3023                         kvm_register_write(vcpu, reg, vcpu->arch.cr3);
3024                         trace_kvm_cr_read(cr, vcpu->arch.cr3);
3025                         skip_emulated_instruction(vcpu);
3026                         return 1;
3027                 case 8:
3028                         val = kvm_get_cr8(vcpu);
3029                         kvm_register_write(vcpu, reg, val);
3030                         trace_kvm_cr_read(cr, val);
3031                         skip_emulated_instruction(vcpu);
3032                         return 1;
3033                 }
3034                 break;
3035         case 3: /* lmsw */
3036                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
3037                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
3038                 kvm_lmsw(vcpu, val);
3039
3040                 skip_emulated_instruction(vcpu);
3041                 return 1;
3042         default:
3043                 break;
3044         }
3045         vcpu->run->exit_reason = 0;
3046         pr_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
3047                (int)(exit_qualification >> 4) & 3, cr);
3048         return 0;
3049 }
3050
3051 static int check_dr_alias(struct kvm_vcpu *vcpu)
3052 {
3053         if (kvm_read_cr4_bits(vcpu, X86_CR4_DE)) {
3054                 kvm_queue_exception(vcpu, UD_VECTOR);
3055                 return -1;
3056         }
3057         return 0;
3058 }
3059
3060 static int handle_dr(struct kvm_vcpu *vcpu)
3061 {
3062         unsigned long exit_qualification;
3063         unsigned long val;
3064         int dr, reg;
3065
3066         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
3067         if (!kvm_require_cpl(vcpu, 0))
3068                 return 1;
3069         dr = vmcs_readl(GUEST_DR7);
3070         if (dr & DR7_GD) {
3071                 /*
3072                  * As the vm-exit takes precedence over the debug trap, we
3073                  * need to emulate the latter, either for the host or the
3074                  * guest debugging itself.
3075                  */
3076                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
3077                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
3078                         vcpu->run->debug.arch.dr7 = dr;
3079                         vcpu->run->debug.arch.pc =
3080                                 vmcs_readl(GUEST_CS_BASE) +
3081                                 vmcs_readl(GUEST_RIP);
3082                         vcpu->run->debug.arch.exception = DB_VECTOR;
3083                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
3084                         return 0;
3085                 } else {
3086                         vcpu->arch.dr7 &= ~DR7_GD;
3087                         vcpu->arch.dr6 |= DR6_BD;
3088                         vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
3089                         kvm_queue_exception(vcpu, DB_VECTOR);
3090                         return 1;
3091                 }
3092         }
3093
3094         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3095         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
3096         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
3097         if (exit_qualification & TYPE_MOV_FROM_DR) {
3098                 switch (dr) {
3099                 case 0 ... 3:
3100                         val = vcpu->arch.db[dr];
3101                         break;
3102                 case 4:
3103                         if (check_dr_alias(vcpu) < 0)
3104                                 return 1;
3105                         /* fall through */
3106                 case 6:
3107                         val = vcpu->arch.dr6;
3108                         break;
3109                 case 5:
3110                         if (check_dr_alias(vcpu) < 0)
3111                                 return 1;
3112                         /* fall through */
3113                 default: /* 7 */
3114                         val = vcpu->arch.dr7;
3115                         break;
3116                 }
3117                 kvm_register_write(vcpu, reg, val);
3118         } else {
3119                 val = vcpu->arch.regs[reg];
3120                 switch (dr) {
3121                 case 0 ... 3:
3122                         vcpu->arch.db[dr] = val;
3123                         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
3124                                 vcpu->arch.eff_db[dr] = val;
3125                         break;
3126                 case 4:
3127                         if (check_dr_alias(vcpu) < 0)
3128                                 return 1;
3129                         /* fall through */
3130                 case 6:
3131                         if (val & 0xffffffff00000000ULL) {
3132                                 kvm_inject_gp(vcpu, 0);
3133                                 return 1;
3134                         }
3135                         vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
3136                         break;
3137                 case 5:
3138                         if (check_dr_alias(vcpu) < 0)
3139                                 return 1;
3140                         /* fall through */
3141                 default: /* 7 */
3142                         if (val & 0xffffffff00000000ULL) {
3143                                 kvm_inject_gp(vcpu, 0);
3144                                 return 1;
3145                         }
3146                         vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
3147                         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
3148                                 vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
3149                                 vcpu->arch.switch_db_regs =
3150                                         (val & DR7_BP_EN_MASK);
3151                         }
3152                         break;
3153                 }
3154         }
3155         skip_emulated_instruction(vcpu);
3156         return 1;
3157 }
3158
3159 static int handle_cpuid(struct kvm_vcpu *vcpu)
3160 {
3161         kvm_emulate_cpuid(vcpu);
3162         return 1;
3163 }
3164
3165 static int handle_rdmsr(struct kvm_vcpu *vcpu)
3166 {
3167         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
3168         u64 data;
3169
3170         if (vmx_get_msr(vcpu, ecx, &data)) {
3171                 trace_kvm_msr_read_ex(ecx);
3172                 kvm_inject_gp(vcpu, 0);
3173                 return 1;
3174         }
3175
3176         trace_kvm_msr_read(ecx, data);
3177
3178         /* FIXME: handling of bits 32:63 of rax, rdx */
3179         vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
3180         vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
3181         skip_emulated_instruction(vcpu);
3182         return 1;
3183 }
3184
3185 static int handle_wrmsr(struct kvm_vcpu *vcpu)
3186 {
3187         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
3188         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
3189                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
3190
3191         if (vmx_set_msr(vcpu, ecx, data) != 0) {
3192                 trace_kvm_msr_write_ex(ecx, data);
3193                 kvm_inject_gp(vcpu, 0);
3194                 return 1;
3195         }
3196
3197         trace_kvm_msr_write(ecx, data);
3198         skip_emulated_instruction(vcpu);
3199         return 1;
3200 }
3201
3202 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
3203 {
3204         return 1;
3205 }
3206
3207 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
3208 {
3209         u32 cpu_based_vm_exec_control;
3210
3211         /* clear pending irq */
3212         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
3213         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
3214         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
3215
3216         ++vcpu->stat.irq_window_exits;
3217
3218         /*
3219          * If the user space waits to inject interrupts, exit as soon as
3220          * possible
3221          */
3222         if (!irqchip_in_kernel(vcpu->kvm) &&
3223             vcpu->run->request_interrupt_window &&
3224             !kvm_cpu_has_interrupt(vcpu)) {
3225                 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
3226                 return 0;
3227         }
3228         return 1;
3229 }
3230
3231 static int handle_halt(struct kvm_vcpu *vcpu)
3232 {
3233         skip_emulated_instruction(vcpu);
3234         return kvm_emulate_halt(vcpu);
3235 }
3236
3237 static int handle_vmcall(struct kvm_vcpu *vcpu)
3238 {
3239         skip_emulated_instruction(vcpu);
3240         kvm_emulate_hypercall(vcpu);
3241         return 1;
3242 }
3243
3244 static int handle_vmx_insn(struct kvm_vcpu *vcpu)
3245 {
3246         kvm_queue_exception(vcpu, UD_VECTOR);
3247         return 1;
3248 }
3249
3250 static int handle_invlpg(struct kvm_vcpu *vcpu)
3251 {
3252         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3253
3254         kvm_mmu_invlpg(vcpu, exit_qualification);
3255         skip_emulated_instruction(vcpu);
3256         return 1;
3257 }
3258
3259 static int handle_wbinvd(struct kvm_vcpu *vcpu)
3260 {
3261         skip_emulated_instruction(vcpu);
3262         /* TODO: Add support for VT-d/pass-through device */
3263         return 1;
3264 }
3265
3266 static int handle_apic_access(struct kvm_vcpu *vcpu)
3267 {
3268         unsigned long exit_qualification;
3269         enum emulation_result er;
3270         unsigned long offset;
3271
3272         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3273         offset = exit_qualification & 0xffful;
3274
3275         er = emulate_instruction(vcpu, 0, 0, 0);
3276
3277         if (er !=  EMULATE_DONE) {
3278                 printk(KERN_ERR
3279                        "Fail to handle apic access vmexit! Offset is 0x%lx\n",
3280                        offset);
3281                 return -ENOEXEC;
3282         }
3283         return 1;
3284 }
3285
3286 static int handle_task_switch(struct kvm_vcpu *vcpu)
3287 {
3288         struct vcpu_vmx *vmx = to_vmx(vcpu);
3289         unsigned long exit_qualification;
3290         u16 tss_selector;
3291         int reason, type, idt_v;
3292
3293         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
3294         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
3295
3296         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3297
3298         reason = (u32)exit_qualification >> 30;
3299         if (reason == TASK_SWITCH_GATE && idt_v) {
3300                 switch (type) {
3301                 case INTR_TYPE_NMI_INTR:
3302                         vcpu->arch.nmi_injected = false;
3303                         if (cpu_has_virtual_nmis())
3304                                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
3305                                               GUEST_INTR_STATE_NMI);
3306                         break;
3307                 case INTR_TYPE_EXT_INTR:
3308                 case INTR_TYPE_SOFT_INTR:
3309                         kvm_clear_interrupt_queue(vcpu);
3310                         break;
3311                 case INTR_TYPE_HARD_EXCEPTION:
3312                 case INTR_TYPE_SOFT_EXCEPTION:
3313                         kvm_clear_exception_queue(vcpu);
3314                         break;
3315                 default:
3316                         break;
3317                 }
3318         }
3319         tss_selector = exit_qualification;
3320
3321         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
3322                        type != INTR_TYPE_EXT_INTR &&
3323                        type != INTR_TYPE_NMI_INTR))
3324                 skip_emulated_instruction(vcpu);
3325
3326         if (!kvm_task_switch(vcpu, tss_selector, reason))
3327                 return 0;
3328
3329         /* clear all local breakpoint enable flags */
3330         vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55);
3331
3332         /*
3333          * TODO: What about debug traps on tss switch?
3334          *       Are we supposed to inject them and update dr6?
3335          */
3336
3337         return 1;
3338 }
3339
3340 static int handle_ept_violation(struct kvm_vcpu *vcpu)
3341 {
3342         unsigned long exit_qualification;
3343         gpa_t gpa;
3344         int gla_validity;
3345
3346         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3347
3348         if (exit_qualification & (1 << 6)) {
3349                 printk(KERN_ERR "EPT: GPA exceeds GAW!\n");
3350                 return -EINVAL;
3351         }
3352
3353         gla_validity = (exit_qualification >> 7) & 0x3;
3354         if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
3355                 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
3356                 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
3357                         (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
3358                         vmcs_readl(GUEST_LINEAR_ADDRESS));
3359                 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
3360                         (long unsigned int)exit_qualification);
3361                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
3362                 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
3363                 return 0;
3364         }
3365
3366         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
3367         trace_kvm_page_fault(gpa, exit_qualification);
3368         return kvm_mmu_page_fault(vcpu, gpa & PAGE_MASK, 0);
3369 }
3370
3371 static u64 ept_rsvd_mask(u64 spte, int level)
3372 {
3373         int i;
3374         u64 mask = 0;
3375
3376         for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
3377                 mask |= (1ULL << i);
3378
3379         if (level > 2)
3380                 /* bits 7:3 reserved */
3381                 mask |= 0xf8;
3382         else if (level == 2) {
3383                 if (spte & (1ULL << 7))
3384                         /* 2MB ref, bits 20:12 reserved */
3385                         mask |= 0x1ff000;
3386                 else
3387                         /* bits 6:3 reserved */
3388                         mask |= 0x78;
3389         }
3390
3391         return mask;
3392 }
3393
3394 static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
3395                                        int level)
3396 {
3397         printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
3398
3399         /* 010b (write-only) */
3400         WARN_ON((spte & 0x7) == 0x2);
3401
3402         /* 110b (write/execute) */
3403         WARN_ON((spte & 0x7) == 0x6);
3404
3405         /* 100b (execute-only) and value not supported by logical processor */
3406         if (!cpu_has_vmx_ept_execute_only())
3407                 WARN_ON((spte & 0x7) == 0x4);
3408
3409         /* not 000b */
3410         if ((spte & 0x7)) {
3411                 u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
3412
3413                 if (rsvd_bits != 0) {
3414                         printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
3415                                          __func__, rsvd_bits);
3416                         WARN_ON(1);
3417                 }
3418
3419                 if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
3420                         u64 ept_mem_type = (spte & 0x38) >> 3;
3421
3422                         if (ept_mem_type == 2 || ept_mem_type == 3 ||
3423                             ept_mem_type == 7) {
3424                                 printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
3425                                                 __func__, ept_mem_type);
3426                                 WARN_ON(1);
3427                         }
3428                 }
3429         }
3430 }
3431
3432 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
3433 {
3434         u64 sptes[4];
3435         int nr_sptes, i;
3436         gpa_t gpa;
3437
3438         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
3439
3440         printk(KERN_ERR "EPT: Misconfiguration.\n");
3441         printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
3442
3443         nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
3444
3445         for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
3446                 ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
3447
3448         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
3449         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
3450
3451         return 0;
3452 }
3453
3454 static int handle_nmi_window(struct kvm_vcpu *vcpu)
3455 {
3456         u32 cpu_based_vm_exec_control;
3457
3458         /* clear pending NMI */
3459         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
3460         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
3461         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
3462         ++vcpu->stat.nmi_window_exits;
3463
3464         return 1;
3465 }
3466
3467 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
3468 {
3469         struct vcpu_vmx *vmx = to_vmx(vcpu);
3470         enum emulation_result err = EMULATE_DONE;
3471         int ret = 1;
3472
3473         while (!guest_state_valid(vcpu)) {
3474                 err = emulate_instruction(vcpu, 0, 0, 0);
3475
3476                 if (err == EMULATE_DO_MMIO) {
3477                         ret = 0;
3478                         goto out;
3479                 }
3480
3481                 if (err != EMULATE_DONE) {
3482                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3483                         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3484                         vcpu->run->internal.ndata = 0;
3485                         ret = 0;
3486                         goto out;
3487                 }
3488
3489                 if (signal_pending(current))
3490                         goto out;
3491                 if (need_resched())
3492                         schedule();
3493         }
3494
3495         vmx->emulation_required = 0;
3496 out:
3497         return ret;
3498 }
3499
3500 /*
3501  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
3502  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
3503  */
3504 static int handle_pause(struct kvm_vcpu *vcpu)
3505 {
3506         skip_emulated_instruction(vcpu);
3507         kvm_vcpu_on_spin(vcpu);
3508
3509         return 1;
3510 }
3511
3512 static int handle_invalid_op(struct kvm_vcpu *vcpu)
3513 {
3514         kvm_queue_exception(vcpu, UD_VECTOR);
3515         return 1;
3516 }
3517
3518 /*
3519  * The exit handlers return 1 if the exit was handled fully and guest execution
3520  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
3521  * to be done to userspace and return 0.
3522  */
3523 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3524         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
3525         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
3526         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
3527         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
3528         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
3529         [EXIT_REASON_CR_ACCESS]               = handle_cr,
3530         [EXIT_REASON_DR_ACCESS]               = handle_dr,
3531         [EXIT_REASON_CPUID]                   = handle_cpuid,
3532         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
3533         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
3534         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
3535         [EXIT_REASON_HLT]                     = handle_halt,
3536         [EXIT_REASON_INVLPG]                  = handle_invlpg,
3537         [EXIT_REASON_VMCALL]                  = handle_vmcall,
3538         [EXIT_REASON_VMCLEAR]                 = handle_vmx_insn,
3539         [EXIT_REASON_VMLAUNCH]                = handle_vmx_insn,
3540         [EXIT_REASON_VMPTRLD]                 = handle_vmx_insn,
3541         [EXIT_REASON_VMPTRST]                 = handle_vmx_insn,
3542         [EXIT_REASON_VMREAD]                  = handle_vmx_insn,
3543         [EXIT_REASON_VMRESUME]                = handle_vmx_insn,
3544         [EXIT_REASON_VMWRITE]                 = handle_vmx_insn,
3545         [EXIT_REASON_VMOFF]                   = handle_vmx_insn,
3546         [EXIT_REASON_VMON]                    = handle_vmx_insn,
3547         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
3548         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
3549         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
3550         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
3551         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
3552         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
3553         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
3554         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
3555         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_invalid_op,
3556         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_invalid_op,
3557 };
3558
3559 static const int kvm_vmx_max_exit_handlers =
3560         ARRAY_SIZE(kvm_vmx_exit_handlers);
3561
3562 /*
3563  * The guest has exited.  See if we can fix it or if we need userspace
3564  * assistance.
3565  */
3566 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
3567 {
3568         struct vcpu_vmx *vmx = to_vmx(vcpu);
3569         u32 exit_reason = vmx->exit_reason;
3570         u32 vectoring_info = vmx->idt_vectoring_info;
3571
3572         trace_kvm_exit(exit_reason, kvm_rip_read(vcpu));
3573
3574         /* If guest state is invalid, start emulating */
3575         if (vmx->emulation_required && emulate_invalid_guest_state)
3576                 return handle_invalid_guest_state(vcpu);
3577
3578         /* Access CR3 don't cause VMExit in paging mode, so we need
3579          * to sync with guest real CR3. */
3580         if (enable_ept && is_paging(vcpu))
3581                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
3582
3583         if (unlikely(vmx->fail)) {
3584                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3585                 vcpu->run->fail_entry.hardware_entry_failure_reason
3586                         = vmcs_read32(VM_INSTRUCTION_ERROR);
3587                 return 0;
3588         }
3589
3590         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
3591                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
3592                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
3593                         exit_reason != EXIT_REASON_TASK_SWITCH))
3594                 printk(KERN_WARNING "%s: unexpected, valid vectoring info "
3595                        "(0x%x) and exit reason is 0x%x\n",
3596                        __func__, vectoring_info, exit_reason);
3597
3598         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked)) {
3599                 if (vmx_interrupt_allowed(vcpu)) {
3600                         vmx->soft_vnmi_blocked = 0;
3601                 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
3602                            vcpu->arch.nmi_pending) {
3603                         /*
3604                          * This CPU don't support us in finding the end of an
3605                          * NMI-blocked window if the guest runs with IRQs
3606                          * disabled. So we pull the trigger after 1 s of
3607                          * futile waiting, but inform the user about this.
3608                          */
3609                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
3610                                "state on VCPU %d after 1 s timeout\n",
3611                                __func__, vcpu->vcpu_id);
3612                         vmx->soft_vnmi_blocked = 0;
3613                 }
3614         }
3615
3616         if (exit_reason < kvm_vmx_max_exit_handlers
3617             && kvm_vmx_exit_handlers[exit_reason])
3618                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
3619         else {
3620                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
3621                 vcpu->run->hw.hardware_exit_reason = exit_reason;
3622         }
3623         return 0;
3624 }
3625
3626 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3627 {
3628         if (irr == -1 || tpr < irr) {
3629                 vmcs_write32(TPR_THRESHOLD, 0);
3630                 return;
3631         }
3632
3633         vmcs_write32(TPR_THRESHOLD, irr);
3634 }
3635
3636 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
3637 {
3638         u32 exit_intr_info;
3639         u32 idt_vectoring_info = vmx->idt_vectoring_info;
3640         bool unblock_nmi;
3641         u8 vector;
3642         int type;
3643         bool idtv_info_valid;
3644
3645         exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
3646
3647         vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
3648
3649         /* Handle machine checks before interrupts are enabled */
3650         if ((vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY)
3651             || (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI
3652                 && is_machine_check(exit_intr_info)))
3653                 kvm_machine_check();
3654
3655         /* We need to handle NMIs before interrupts are enabled */
3656         if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
3657             (exit_intr_info & INTR_INFO_VALID_MASK))
3658                 asm("int $2");
3659
3660         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
3661
3662         if (cpu_has_virtual_nmis()) {
3663                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
3664                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
3665                 /*
3666                  * SDM 3: 27.7.1.2 (September 2008)
3667                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
3668                  * a guest IRET fault.
3669                  * SDM 3: 23.2.2 (September 2008)
3670                  * Bit 12 is undefined in any of the following cases:
3671                  *  If the VM exit sets the valid bit in the IDT-vectoring
3672                  *   information field.
3673                  *  If the VM exit is due to a double fault.
3674                  */
3675                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
3676                     vector != DF_VECTOR && !idtv_info_valid)
3677                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
3678                                       GUEST_INTR_STATE_NMI);
3679         } else if (unlikely(vmx->soft_vnmi_blocked))
3680                 vmx->vnmi_blocked_time +=
3681                         ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
3682
3683         vmx->vcpu.arch.nmi_injected = false;
3684         kvm_clear_exception_queue(&vmx->vcpu);
3685         kvm_clear_interrupt_queue(&vmx->vcpu);
3686
3687         if (!idtv_info_valid)
3688                 return;
3689
3690         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
3691         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
3692
3693         switch (type) {
3694         case INTR_TYPE_NMI_INTR:
3695                 vmx->vcpu.arch.nmi_injected = true;
3696                 /*
3697                  * SDM 3: 27.7.1.2 (September 2008)
3698                  * Clear bit "block by NMI" before VM entry if a NMI
3699                  * delivery faulted.
3700                  */
3701                 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
3702                                 GUEST_INTR_STATE_NMI);
3703                 break;
3704         case INTR_TYPE_SOFT_EXCEPTION:
3705                 vmx->vcpu.arch.event_exit_inst_len =
3706                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3707                 /* fall through */
3708         case INTR_TYPE_HARD_EXCEPTION:
3709                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
3710                         u32 err = vmcs_read32(IDT_VECTORING_ERROR_CODE);
3711                         kvm_queue_exception_e(&vmx->vcpu, vector, err);
3712                 } else
3713                         kvm_queue_exception(&vmx->vcpu, vector);
3714                 break;
3715         case INTR_TYPE_SOFT_INTR:
3716                 vmx->vcpu.arch.event_exit_inst_len =
3717                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3718                 /* fall through */
3719         case INTR_TYPE_EXT_INTR:
3720                 kvm_queue_interrupt(&vmx->vcpu, vector,
3721                         type == INTR_TYPE_SOFT_INTR);
3722                 break;
3723         default:
3724                 break;
3725         }
3726 }
3727
3728 /*
3729  * Failure to inject an interrupt should give us the information
3730  * in IDT_VECTORING_INFO_FIELD.  However, if the failure occurs
3731  * when fetching the interrupt redirection bitmap in the real-mode
3732  * tss, this doesn't happen.  So we do it ourselves.
3733  */
3734 static void fixup_rmode_irq(struct vcpu_vmx *vmx)
3735 {
3736         vmx->rmode.irq.pending = 0;
3737         if (kvm_rip_read(&vmx->vcpu) + 1 != vmx->rmode.irq.rip)
3738                 return;
3739         kvm_rip_write(&vmx->vcpu, vmx->rmode.irq.rip);
3740         if (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK) {
3741                 vmx->idt_vectoring_info &= ~VECTORING_INFO_TYPE_MASK;
3742                 vmx->idt_vectoring_info |= INTR_TYPE_EXT_INTR;
3743                 return;
3744         }
3745         vmx->idt_vectoring_info =
3746                 VECTORING_INFO_VALID_MASK
3747                 | INTR_TYPE_EXT_INTR
3748                 | vmx->rmode.irq.vector;
3749 }
3750
3751 #ifdef CONFIG_X86_64
3752 #define R "r"
3753 #define Q "q"
3754 #else
3755 #define R "e"
3756 #define Q "l"
3757 #endif
3758
3759 static void vmx_vcpu_run(struct kvm_vcpu *vcpu)
3760 {
3761         struct vcpu_vmx *vmx = to_vmx(vcpu);
3762
3763         /* Record the guest's net vcpu time for enforced NMI injections. */
3764         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
3765                 vmx->entry_time = ktime_get();
3766
3767         /* Don't enter VMX if guest state is invalid, let the exit handler
3768            start emulation until we arrive back to a valid state */
3769         if (vmx->emulation_required && emulate_invalid_guest_state)
3770                 return;
3771
3772         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
3773                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
3774         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
3775                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
3776
3777         /* When single-stepping over STI and MOV SS, we must clear the
3778          * corresponding interruptibility bits in the guest state. Otherwise
3779          * vmentry fails as it then expects bit 14 (BS) in pending debug
3780          * exceptions being set, but that's not correct for the guest debugging
3781          * case. */
3782         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
3783                 vmx_set_interrupt_shadow(vcpu, 0);
3784
3785         /*
3786          * Loading guest fpu may have cleared host cr0.ts
3787          */
3788         vmcs_writel(HOST_CR0, read_cr0());
3789
3790         asm(
3791                 /* Store host registers */
3792                 "push %%"R"dx; push %%"R"bp;"
3793                 "push %%"R"cx \n\t"
3794                 "cmp %%"R"sp, %c[host_rsp](%0) \n\t"
3795                 "je 1f \n\t"
3796                 "mov %%"R"sp, %c[host_rsp](%0) \n\t"
3797                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
3798                 "1: \n\t"
3799                 /* Reload cr2 if changed */
3800                 "mov %c[cr2](%0), %%"R"ax \n\t"
3801                 "mov %%cr2, %%"R"dx \n\t"
3802                 "cmp %%"R"ax, %%"R"dx \n\t"
3803                 "je 2f \n\t"
3804                 "mov %%"R"ax, %%cr2 \n\t"
3805                 "2: \n\t"
3806                 /* Check if vmlaunch of vmresume is needed */
3807                 "cmpl $0, %c[launched](%0) \n\t"
3808                 /* Load guest registers.  Don't clobber flags. */
3809                 "mov %c[rax](%0), %%"R"ax \n\t"
3810                 "mov %c[rbx](%0), %%"R"bx \n\t"
3811                 "mov %c[rdx](%0), %%"R"dx \n\t"
3812                 "mov %c[rsi](%0), %%"R"si \n\t"
3813                 "mov %c[rdi](%0), %%"R"di \n\t"
3814                 "mov %c[rbp](%0), %%"R"bp \n\t"
3815 #ifdef CONFIG_X86_64
3816                 "mov %c[r8](%0),  %%r8  \n\t"
3817                 "mov %c[r9](%0),  %%r9  \n\t"
3818                 "mov %c[r10](%0), %%r10 \n\t"
3819                 "mov %c[r11](%0), %%r11 \n\t"
3820                 "mov %c[r12](%0), %%r12 \n\t"
3821                 "mov %c[r13](%0), %%r13 \n\t"
3822                 "mov %c[r14](%0), %%r14 \n\t"
3823                 "mov %c[r15](%0), %%r15 \n\t"
3824 #endif
3825                 "mov %c[rcx](%0), %%"R"cx \n\t" /* kills %0 (ecx) */
3826
3827                 /* Enter guest mode */
3828                 "jne .Llaunched \n\t"
3829                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
3830                 "jmp .Lkvm_vmx_return \n\t"
3831                 ".Llaunched: " __ex(ASM_VMX_VMRESUME) "\n\t"
3832                 ".Lkvm_vmx_return: "
3833                 /* Save guest registers, load host registers, keep flags */
3834                 "xchg %0,     (%%"R"sp) \n\t"
3835                 "mov %%"R"ax, %c[rax](%0) \n\t"
3836                 "mov %%"R"bx, %c[rbx](%0) \n\t"
3837                 "push"Q" (%%"R"sp); pop"Q" %c[rcx](%0) \n\t"
3838                 "mov %%"R"dx, %c[rdx](%0) \n\t"
3839                 "mov %%"R"si, %c[rsi](%0) \n\t"
3840                 "mov %%"R"di, %c[rdi](%0) \n\t"
3841                 "mov %%"R"bp, %c[rbp](%0) \n\t"
3842 #ifdef CONFIG_X86_64
3843                 "mov %%r8,  %c[r8](%0) \n\t"
3844                 "mov %%r9,  %c[r9](%0) \n\t"
3845                 "mov %%r10, %c[r10](%0) \n\t"
3846                 "mov %%r11, %c[r11](%0) \n\t"
3847                 "mov %%r12, %c[r12](%0) \n\t"
3848                 "mov %%r13, %c[r13](%0) \n\t"
3849                 "mov %%r14, %c[r14](%0) \n\t"
3850                 "mov %%r15, %c[r15](%0) \n\t"
3851 #endif
3852                 "mov %%cr2, %%"R"ax   \n\t"
3853                 "mov %%"R"ax, %c[cr2](%0) \n\t"
3854
3855                 "pop  %%"R"bp; pop  %%"R"bp; pop  %%"R"dx \n\t"
3856                 "setbe %c[fail](%0) \n\t"
3857               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
3858                 [launched]"i"(offsetof(struct vcpu_vmx, launched)),
3859                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
3860                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
3861                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
3862                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
3863                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
3864                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
3865                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
3866                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
3867                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
3868 #ifdef CONFIG_X86_64
3869                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
3870                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
3871                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
3872                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
3873                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
3874                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
3875                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
3876                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
3877 #endif
3878                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2))
3879               : "cc", "memory"
3880                 , R"bx", R"di", R"si"
3881 #ifdef CONFIG_X86_64
3882                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
3883 #endif
3884               );
3885
3886         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
3887                                   | (1 << VCPU_EXREG_PDPTR));
3888         vcpu->arch.regs_dirty = 0;
3889
3890         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
3891         if (vmx->rmode.irq.pending)
3892                 fixup_rmode_irq(vmx);
3893
3894         asm("mov %0, %%ds; mov %0, %%es" : : "r"(__USER_DS));
3895         vmx->launched = 1;
3896
3897         vmx_complete_interrupts(vmx);
3898 }
3899
3900 #undef R
3901 #undef Q
3902
3903 static void vmx_free_vmcs(struct kvm_vcpu *vcpu)
3904 {
3905         struct vcpu_vmx *vmx = to_vmx(vcpu);
3906
3907         if (vmx->vmcs) {
3908                 vcpu_clear(vmx);
3909                 free_vmcs(vmx->vmcs);
3910                 vmx->vmcs = NULL;
3911         }
3912 }
3913
3914 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
3915 {
3916         struct vcpu_vmx *vmx = to_vmx(vcpu);
3917
3918         spin_lock(&vmx_vpid_lock);
3919         if (vmx->vpid != 0)
3920                 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
3921         spin_unlock(&vmx_vpid_lock);
3922         vmx_free_vmcs(vcpu);
3923         kfree(vmx->guest_msrs);
3924         kvm_vcpu_uninit(vcpu);
3925         kmem_cache_free(kvm_vcpu_cache, vmx);
3926 }
3927
3928 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
3929 {
3930         int err;
3931         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
3932         int cpu;
3933
3934         if (!vmx)
3935                 return ERR_PTR(-ENOMEM);
3936
3937         allocate_vpid(vmx);
3938
3939         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
3940         if (err)
3941                 goto free_vcpu;
3942
3943         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
3944         if (!vmx->guest_msrs) {
3945                 err = -ENOMEM;
3946                 goto uninit_vcpu;
3947         }
3948
3949         vmx->vmcs = alloc_vmcs();
3950         if (!vmx->vmcs)
3951                 goto free_msrs;
3952
3953         vmcs_clear(vmx->vmcs);
3954
3955         cpu = get_cpu();
3956         vmx_vcpu_load(&vmx->vcpu, cpu);
3957         err = vmx_vcpu_setup(vmx);
3958         vmx_vcpu_put(&vmx->vcpu);
3959         put_cpu();
3960         if (err)
3961                 goto free_vmcs;
3962         if (vm_need_virtualize_apic_accesses(kvm))
3963                 if (alloc_apic_access_page(kvm) != 0)
3964                         goto free_vmcs;
3965
3966         if (enable_ept) {
3967                 if (!kvm->arch.ept_identity_map_addr)
3968                         kvm->arch.ept_identity_map_addr =
3969                                 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3970                 if (alloc_identity_pagetable(kvm) != 0)
3971                         goto free_vmcs;
3972         }
3973
3974         return &vmx->vcpu;
3975
3976 free_vmcs:
3977         free_vmcs(vmx->vmcs);
3978 free_msrs:
3979         kfree(vmx->guest_msrs);
3980 uninit_vcpu:
3981         kvm_vcpu_uninit(&vmx->vcpu);
3982 free_vcpu:
3983         kmem_cache_free(kvm_vcpu_cache, vmx);
3984         return ERR_PTR(err);
3985 }
3986
3987 static void __init vmx_check_processor_compat(void *rtn)
3988 {
3989         struct vmcs_config vmcs_conf;
3990
3991         *(int *)rtn = 0;
3992         if (setup_vmcs_config(&vmcs_conf) < 0)
3993                 *(int *)rtn = -EIO;
3994         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
3995                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
3996                                 smp_processor_id());
3997                 *(int *)rtn = -EIO;
3998         }
3999 }
4000
4001 static int get_ept_level(void)
4002 {
4003         return VMX_EPT_DEFAULT_GAW + 1;
4004 }
4005
4006 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
4007 {
4008         u64 ret;
4009
4010         /* For VT-d and EPT combination
4011          * 1. MMIO: always map as UC
4012          * 2. EPT with VT-d:
4013          *   a. VT-d without snooping control feature: can't guarantee the
4014          *      result, try to trust guest.
4015          *   b. VT-d with snooping control feature: snooping control feature of
4016          *      VT-d engine can guarantee the cache correctness. Just set it
4017          *      to WB to keep consistent with host. So the same as item 3.
4018          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
4019          *    consistent with host MTRR
4020          */
4021         if (is_mmio)
4022                 ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
4023         else if (vcpu->kvm->arch.iommu_domain &&
4024                 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY))
4025                 ret = kvm_get_guest_memory_type(vcpu, gfn) <<
4026                       VMX_EPT_MT_EPTE_SHIFT;
4027         else
4028                 ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
4029                         | VMX_EPT_IPAT_BIT;
4030
4031         return ret;
4032 }
4033
4034 #define _ER(x) { EXIT_REASON_##x, #x }
4035
4036 static const struct trace_print_flags vmx_exit_reasons_str[] = {
4037         _ER(EXCEPTION_NMI),
4038         _ER(EXTERNAL_INTERRUPT),
4039         _ER(TRIPLE_FAULT),
4040         _ER(PENDING_INTERRUPT),
4041         _ER(NMI_WINDOW),
4042         _ER(TASK_SWITCH),
4043         _ER(CPUID),
4044         _ER(HLT),
4045         _ER(INVLPG),
4046         _ER(RDPMC),
4047         _ER(RDTSC),
4048         _ER(VMCALL),
4049         _ER(VMCLEAR),
4050         _ER(VMLAUNCH),
4051         _ER(VMPTRLD),
4052         _ER(VMPTRST),
4053         _ER(VMREAD),
4054         _ER(VMRESUME),
4055         _ER(VMWRITE),
4056         _ER(VMOFF),
4057         _ER(VMON),
4058         _ER(CR_ACCESS),
4059         _ER(DR_ACCESS),
4060         _ER(IO_INSTRUCTION),
4061         _ER(MSR_READ),
4062         _ER(MSR_WRITE),
4063         _ER(MWAIT_INSTRUCTION),
4064         _ER(MONITOR_INSTRUCTION),
4065         _ER(PAUSE_INSTRUCTION),
4066         _ER(MCE_DURING_VMENTRY),
4067         _ER(TPR_BELOW_THRESHOLD),
4068         _ER(APIC_ACCESS),
4069         _ER(EPT_VIOLATION),
4070         _ER(EPT_MISCONFIG),
4071         _ER(WBINVD),
4072         { -1, NULL }
4073 };
4074
4075 #undef _ER
4076
4077 static int vmx_get_lpage_level(void)
4078 {
4079         if (enable_ept && !cpu_has_vmx_ept_1g_page())
4080                 return PT_DIRECTORY_LEVEL;
4081         else
4082                 /* For shadow and EPT supported 1GB page */
4083                 return PT_PDPE_LEVEL;
4084 }
4085
4086 static inline u32 bit(int bitno)
4087 {
4088         return 1 << (bitno & 31);
4089 }
4090
4091 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
4092 {
4093         struct kvm_cpuid_entry2 *best;
4094         struct vcpu_vmx *vmx = to_vmx(vcpu);
4095         u32 exec_control;
4096
4097         vmx->rdtscp_enabled = false;
4098         if (vmx_rdtscp_supported()) {
4099                 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
4100                 if (exec_control & SECONDARY_EXEC_RDTSCP) {
4101                         best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
4102                         if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
4103                                 vmx->rdtscp_enabled = true;
4104                         else {
4105                                 exec_control &= ~SECONDARY_EXEC_RDTSCP;
4106                                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4107                                                 exec_control);
4108                         }
4109                 }
4110         }
4111 }
4112
4113 static struct kvm_x86_ops vmx_x86_ops = {
4114         .cpu_has_kvm_support = cpu_has_kvm_support,
4115         .disabled_by_bios = vmx_disabled_by_bios,
4116         .hardware_setup = hardware_setup,
4117         .hardware_unsetup = hardware_unsetup,
4118         .check_processor_compatibility = vmx_check_processor_compat,
4119         .hardware_enable = hardware_enable,
4120         .hardware_disable = hardware_disable,
4121         .cpu_has_accelerated_tpr = report_flexpriority,
4122
4123         .vcpu_create = vmx_create_vcpu,
4124         .vcpu_free = vmx_free_vcpu,
4125         .vcpu_reset = vmx_vcpu_reset,
4126
4127         .prepare_guest_switch = vmx_save_host_state,
4128         .vcpu_load = vmx_vcpu_load,
4129         .vcpu_put = vmx_vcpu_put,
4130
4131         .set_guest_debug = set_guest_debug,
4132         .get_msr = vmx_get_msr,
4133         .set_msr = vmx_set_msr,
4134         .get_segment_base = vmx_get_segment_base,
4135         .get_segment = vmx_get_segment,
4136         .set_segment = vmx_set_segment,
4137         .get_cpl = vmx_get_cpl,
4138         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
4139         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
4140         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
4141         .set_cr0 = vmx_set_cr0,
4142         .set_cr3 = vmx_set_cr3,
4143         .set_cr4 = vmx_set_cr4,
4144         .set_efer = vmx_set_efer,
4145         .get_idt = vmx_get_idt,
4146         .set_idt = vmx_set_idt,
4147         .get_gdt = vmx_get_gdt,
4148         .set_gdt = vmx_set_gdt,
4149         .cache_reg = vmx_cache_reg,
4150         .get_rflags = vmx_get_rflags,
4151         .set_rflags = vmx_set_rflags,
4152         .fpu_activate = vmx_fpu_activate,
4153         .fpu_deactivate = vmx_fpu_deactivate,
4154
4155         .tlb_flush = vmx_flush_tlb,
4156
4157         .run = vmx_vcpu_run,
4158         .handle_exit = vmx_handle_exit,
4159         .skip_emulated_instruction = skip_emulated_instruction,
4160         .set_interrupt_shadow = vmx_set_interrupt_shadow,
4161         .get_interrupt_shadow = vmx_get_interrupt_shadow,
4162         .patch_hypercall = vmx_patch_hypercall,
4163         .set_irq = vmx_inject_irq,
4164         .set_nmi = vmx_inject_nmi,
4165         .queue_exception = vmx_queue_exception,
4166         .interrupt_allowed = vmx_interrupt_allowed,
4167         .nmi_allowed = vmx_nmi_allowed,
4168         .get_nmi_mask = vmx_get_nmi_mask,
4169         .set_nmi_mask = vmx_set_nmi_mask,
4170         .enable_nmi_window = enable_nmi_window,
4171         .enable_irq_window = enable_irq_window,
4172         .update_cr8_intercept = update_cr8_intercept,
4173
4174         .set_tss_addr = vmx_set_tss_addr,
4175         .get_tdp_level = get_ept_level,
4176         .get_mt_mask = vmx_get_mt_mask,
4177
4178         .exit_reasons_str = vmx_exit_reasons_str,
4179         .get_lpage_level = vmx_get_lpage_level,
4180
4181         .cpuid_update = vmx_cpuid_update,
4182
4183         .rdtscp_supported = vmx_rdtscp_supported,
4184 };
4185
4186 static int __init vmx_init(void)
4187 {
4188         int r, i;
4189
4190         rdmsrl_safe(MSR_EFER, &host_efer);
4191
4192         for (i = 0; i < NR_VMX_MSR; ++i)
4193                 kvm_define_shared_msr(i, vmx_msr_index[i]);
4194
4195         vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
4196         if (!vmx_io_bitmap_a)
4197                 return -ENOMEM;
4198
4199         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
4200         if (!vmx_io_bitmap_b) {
4201                 r = -ENOMEM;
4202                 goto out;
4203         }
4204
4205         vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
4206         if (!vmx_msr_bitmap_legacy) {
4207                 r = -ENOMEM;
4208                 goto out1;
4209         }
4210
4211         vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
4212         if (!vmx_msr_bitmap_longmode) {
4213                 r = -ENOMEM;
4214                 goto out2;
4215         }
4216
4217         /*
4218          * Allow direct access to the PC debug port (it is often used for I/O
4219          * delays, but the vmexits simply slow things down).
4220          */
4221         memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
4222         clear_bit(0x80, vmx_io_bitmap_a);
4223
4224         memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
4225
4226         memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
4227         memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
4228
4229         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
4230
4231         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx), THIS_MODULE);
4232         if (r)
4233                 goto out3;
4234
4235         vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
4236         vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
4237         vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
4238         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
4239         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
4240         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
4241
4242         if (enable_ept) {
4243                 bypass_guest_pf = 0;
4244                 kvm_mmu_set_base_ptes(VMX_EPT_READABLE_MASK |
4245                         VMX_EPT_WRITABLE_MASK);
4246                 kvm_mmu_set_mask_ptes(0ull, 0ull, 0ull, 0ull,
4247                                 VMX_EPT_EXECUTABLE_MASK);
4248                 kvm_enable_tdp();
4249         } else
4250                 kvm_disable_tdp();
4251
4252         if (bypass_guest_pf)
4253                 kvm_mmu_set_nonpresent_ptes(~0xffeull, 0ull);
4254
4255         return 0;
4256
4257 out3:
4258         free_page((unsigned long)vmx_msr_bitmap_longmode);
4259 out2:
4260         free_page((unsigned long)vmx_msr_bitmap_legacy);
4261 out1:
4262         free_page((unsigned long)vmx_io_bitmap_b);
4263 out:
4264         free_page((unsigned long)vmx_io_bitmap_a);
4265         return r;
4266 }
4267
4268 static void __exit vmx_exit(void)
4269 {
4270         free_page((unsigned long)vmx_msr_bitmap_legacy);
4271         free_page((unsigned long)vmx_msr_bitmap_longmode);
4272         free_page((unsigned long)vmx_io_bitmap_b);
4273         free_page((unsigned long)vmx_io_bitmap_a);
4274
4275         kvm_exit();
4276 }
4277
4278 module_init(vmx_init)
4279 module_exit(vmx_exit)