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