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