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