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