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