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