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