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