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