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