Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net-2.6
[linux-2.6] / arch / x86 / kvm / vmx.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  *
9  * Authors:
10  *   Avi Kivity   <avi@qumranet.com>
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #include "irq.h"
19 #include "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_apic_timer(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 }
1040
1041 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
1042                                       u32 msr, u32 *result)
1043 {
1044         u32 vmx_msr_low, vmx_msr_high;
1045         u32 ctl = ctl_min | ctl_opt;
1046
1047         rdmsr(msr, vmx_msr_low, vmx_msr_high);
1048
1049         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
1050         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
1051
1052         /* Ensure minimum (required) set of control bits are supported. */
1053         if (ctl_min & ~ctl)
1054                 return -EIO;
1055
1056         *result = ctl;
1057         return 0;
1058 }
1059
1060 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
1061 {
1062         u32 vmx_msr_low, vmx_msr_high;
1063         u32 min, opt, min2, opt2;
1064         u32 _pin_based_exec_control = 0;
1065         u32 _cpu_based_exec_control = 0;
1066         u32 _cpu_based_2nd_exec_control = 0;
1067         u32 _vmexit_control = 0;
1068         u32 _vmentry_control = 0;
1069
1070         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
1071         opt = 0;
1072         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
1073                                 &_pin_based_exec_control) < 0)
1074                 return -EIO;
1075
1076         min = CPU_BASED_HLT_EXITING |
1077 #ifdef CONFIG_X86_64
1078               CPU_BASED_CR8_LOAD_EXITING |
1079               CPU_BASED_CR8_STORE_EXITING |
1080 #endif
1081               CPU_BASED_CR3_LOAD_EXITING |
1082               CPU_BASED_CR3_STORE_EXITING |
1083               CPU_BASED_USE_IO_BITMAPS |
1084               CPU_BASED_MOV_DR_EXITING |
1085               CPU_BASED_USE_TSC_OFFSETING;
1086         opt = CPU_BASED_TPR_SHADOW |
1087               CPU_BASED_USE_MSR_BITMAPS |
1088               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1089         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
1090                                 &_cpu_based_exec_control) < 0)
1091                 return -EIO;
1092 #ifdef CONFIG_X86_64
1093         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
1094                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
1095                                            ~CPU_BASED_CR8_STORE_EXITING;
1096 #endif
1097         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
1098                 min2 = 0;
1099                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
1100                         SECONDARY_EXEC_WBINVD_EXITING |
1101                         SECONDARY_EXEC_ENABLE_VPID |
1102                         SECONDARY_EXEC_ENABLE_EPT;
1103                 if (adjust_vmx_controls(min2, opt2,
1104                                         MSR_IA32_VMX_PROCBASED_CTLS2,
1105                                         &_cpu_based_2nd_exec_control) < 0)
1106                         return -EIO;
1107         }
1108 #ifndef CONFIG_X86_64
1109         if (!(_cpu_based_2nd_exec_control &
1110                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
1111                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
1112 #endif
1113         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
1114                 /* CR3 accesses don't need to cause VM Exits when EPT enabled */
1115                 min &= ~(CPU_BASED_CR3_LOAD_EXITING |
1116                          CPU_BASED_CR3_STORE_EXITING);
1117                 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
1118                                         &_cpu_based_exec_control) < 0)
1119                         return -EIO;
1120                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
1121                       vmx_capability.ept, vmx_capability.vpid);
1122         }
1123
1124         min = 0;
1125 #ifdef CONFIG_X86_64
1126         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
1127 #endif
1128         opt = 0;
1129         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
1130                                 &_vmexit_control) < 0)
1131                 return -EIO;
1132
1133         min = opt = 0;
1134         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
1135                                 &_vmentry_control) < 0)
1136                 return -EIO;
1137
1138         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
1139
1140         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
1141         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
1142                 return -EIO;
1143
1144 #ifdef CONFIG_X86_64
1145         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
1146         if (vmx_msr_high & (1u<<16))
1147                 return -EIO;
1148 #endif
1149
1150         /* Require Write-Back (WB) memory type for VMCS accesses. */
1151         if (((vmx_msr_high >> 18) & 15) != 6)
1152                 return -EIO;
1153
1154         vmcs_conf->size = vmx_msr_high & 0x1fff;
1155         vmcs_conf->order = get_order(vmcs_config.size);
1156         vmcs_conf->revision_id = vmx_msr_low;
1157
1158         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
1159         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
1160         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
1161         vmcs_conf->vmexit_ctrl         = _vmexit_control;
1162         vmcs_conf->vmentry_ctrl        = _vmentry_control;
1163
1164         return 0;
1165 }
1166
1167 static struct vmcs *alloc_vmcs_cpu(int cpu)
1168 {
1169         int node = cpu_to_node(cpu);
1170         struct page *pages;
1171         struct vmcs *vmcs;
1172
1173         pages = alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
1174         if (!pages)
1175                 return NULL;
1176         vmcs = page_address(pages);
1177         memset(vmcs, 0, vmcs_config.size);
1178         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
1179         return vmcs;
1180 }
1181
1182 static struct vmcs *alloc_vmcs(void)
1183 {
1184         return alloc_vmcs_cpu(raw_smp_processor_id());
1185 }
1186
1187 static void free_vmcs(struct vmcs *vmcs)
1188 {
1189         free_pages((unsigned long)vmcs, vmcs_config.order);
1190 }
1191
1192 static void free_kvm_area(void)
1193 {
1194         int cpu;
1195
1196         for_each_online_cpu(cpu)
1197                 free_vmcs(per_cpu(vmxarea, cpu));
1198 }
1199
1200 static __init int alloc_kvm_area(void)
1201 {
1202         int cpu;
1203
1204         for_each_online_cpu(cpu) {
1205                 struct vmcs *vmcs;
1206
1207                 vmcs = alloc_vmcs_cpu(cpu);
1208                 if (!vmcs) {
1209                         free_kvm_area();
1210                         return -ENOMEM;
1211                 }
1212
1213                 per_cpu(vmxarea, cpu) = vmcs;
1214         }
1215         return 0;
1216 }
1217
1218 static __init int hardware_setup(void)
1219 {
1220         if (setup_vmcs_config(&vmcs_config) < 0)
1221                 return -EIO;
1222
1223         if (boot_cpu_has(X86_FEATURE_NX))
1224                 kvm_enable_efer_bits(EFER_NX);
1225
1226         return alloc_kvm_area();
1227 }
1228
1229 static __exit void hardware_unsetup(void)
1230 {
1231         free_kvm_area();
1232 }
1233
1234 static void fix_pmode_dataseg(int seg, struct kvm_save_segment *save)
1235 {
1236         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1237
1238         if (vmcs_readl(sf->base) == save->base && (save->base & AR_S_MASK)) {
1239                 vmcs_write16(sf->selector, save->selector);
1240                 vmcs_writel(sf->base, save->base);
1241                 vmcs_write32(sf->limit, save->limit);
1242                 vmcs_write32(sf->ar_bytes, save->ar);
1243         } else {
1244                 u32 dpl = (vmcs_read16(sf->selector) & SELECTOR_RPL_MASK)
1245                         << AR_DPL_SHIFT;
1246                 vmcs_write32(sf->ar_bytes, 0x93 | dpl);
1247         }
1248 }
1249
1250 static void enter_pmode(struct kvm_vcpu *vcpu)
1251 {
1252         unsigned long flags;
1253
1254         vcpu->arch.rmode.active = 0;
1255
1256         vmcs_writel(GUEST_TR_BASE, vcpu->arch.rmode.tr.base);
1257         vmcs_write32(GUEST_TR_LIMIT, vcpu->arch.rmode.tr.limit);
1258         vmcs_write32(GUEST_TR_AR_BYTES, vcpu->arch.rmode.tr.ar);
1259
1260         flags = vmcs_readl(GUEST_RFLAGS);
1261         flags &= ~(X86_EFLAGS_IOPL | X86_EFLAGS_VM);
1262         flags |= (vcpu->arch.rmode.save_iopl << IOPL_SHIFT);
1263         vmcs_writel(GUEST_RFLAGS, flags);
1264
1265         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
1266                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
1267
1268         update_exception_bitmap(vcpu);
1269
1270         fix_pmode_dataseg(VCPU_SREG_ES, &vcpu->arch.rmode.es);
1271         fix_pmode_dataseg(VCPU_SREG_DS, &vcpu->arch.rmode.ds);
1272         fix_pmode_dataseg(VCPU_SREG_GS, &vcpu->arch.rmode.gs);
1273         fix_pmode_dataseg(VCPU_SREG_FS, &vcpu->arch.rmode.fs);
1274
1275         vmcs_write16(GUEST_SS_SELECTOR, 0);
1276         vmcs_write32(GUEST_SS_AR_BYTES, 0x93);
1277
1278         vmcs_write16(GUEST_CS_SELECTOR,
1279                      vmcs_read16(GUEST_CS_SELECTOR) & ~SELECTOR_RPL_MASK);
1280         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
1281 }
1282
1283 static gva_t rmode_tss_base(struct kvm *kvm)
1284 {
1285         if (!kvm->arch.tss_addr) {
1286                 gfn_t base_gfn = kvm->memslots[0].base_gfn +
1287                                  kvm->memslots[0].npages - 3;
1288                 return base_gfn << PAGE_SHIFT;
1289         }
1290         return kvm->arch.tss_addr;
1291 }
1292
1293 static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
1294 {
1295         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1296
1297         save->selector = vmcs_read16(sf->selector);
1298         save->base = vmcs_readl(sf->base);
1299         save->limit = vmcs_read32(sf->limit);
1300         save->ar = vmcs_read32(sf->ar_bytes);
1301         vmcs_write16(sf->selector, save->base >> 4);
1302         vmcs_write32(sf->base, save->base & 0xfffff);
1303         vmcs_write32(sf->limit, 0xffff);
1304         vmcs_write32(sf->ar_bytes, 0xf3);
1305 }
1306
1307 static void enter_rmode(struct kvm_vcpu *vcpu)
1308 {
1309         unsigned long flags;
1310
1311         vcpu->arch.rmode.active = 1;
1312
1313         vcpu->arch.rmode.tr.base = vmcs_readl(GUEST_TR_BASE);
1314         vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
1315
1316         vcpu->arch.rmode.tr.limit = vmcs_read32(GUEST_TR_LIMIT);
1317         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
1318
1319         vcpu->arch.rmode.tr.ar = vmcs_read32(GUEST_TR_AR_BYTES);
1320         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
1321
1322         flags = vmcs_readl(GUEST_RFLAGS);
1323         vcpu->arch.rmode.save_iopl
1324                 = (flags & X86_EFLAGS_IOPL) >> IOPL_SHIFT;
1325
1326         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1327
1328         vmcs_writel(GUEST_RFLAGS, flags);
1329         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
1330         update_exception_bitmap(vcpu);
1331
1332         vmcs_write16(GUEST_SS_SELECTOR, vmcs_readl(GUEST_SS_BASE) >> 4);
1333         vmcs_write32(GUEST_SS_LIMIT, 0xffff);
1334         vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
1335
1336         vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
1337         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
1338         if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
1339                 vmcs_writel(GUEST_CS_BASE, 0xf0000);
1340         vmcs_write16(GUEST_CS_SELECTOR, vmcs_readl(GUEST_CS_BASE) >> 4);
1341
1342         fix_rmode_seg(VCPU_SREG_ES, &vcpu->arch.rmode.es);
1343         fix_rmode_seg(VCPU_SREG_DS, &vcpu->arch.rmode.ds);
1344         fix_rmode_seg(VCPU_SREG_GS, &vcpu->arch.rmode.gs);
1345         fix_rmode_seg(VCPU_SREG_FS, &vcpu->arch.rmode.fs);
1346
1347         kvm_mmu_reset_context(vcpu);
1348         init_rmode(vcpu->kvm);
1349 }
1350
1351 #ifdef CONFIG_X86_64
1352
1353 static void enter_lmode(struct kvm_vcpu *vcpu)
1354 {
1355         u32 guest_tr_ar;
1356
1357         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
1358         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
1359                 printk(KERN_DEBUG "%s: tss fixup for long mode. \n",
1360                        __func__);
1361                 vmcs_write32(GUEST_TR_AR_BYTES,
1362                              (guest_tr_ar & ~AR_TYPE_MASK)
1363                              | AR_TYPE_BUSY_64_TSS);
1364         }
1365
1366         vcpu->arch.shadow_efer |= EFER_LMA;
1367
1368         find_msr_entry(to_vmx(vcpu), MSR_EFER)->data |= EFER_LMA | EFER_LME;
1369         vmcs_write32(VM_ENTRY_CONTROLS,
1370                      vmcs_read32(VM_ENTRY_CONTROLS)
1371                      | VM_ENTRY_IA32E_MODE);
1372 }
1373
1374 static void exit_lmode(struct kvm_vcpu *vcpu)
1375 {
1376         vcpu->arch.shadow_efer &= ~EFER_LMA;
1377
1378         vmcs_write32(VM_ENTRY_CONTROLS,
1379                      vmcs_read32(VM_ENTRY_CONTROLS)
1380                      & ~VM_ENTRY_IA32E_MODE);
1381 }
1382
1383 #endif
1384
1385 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
1386 {
1387         vpid_sync_vcpu_all(to_vmx(vcpu));
1388 }
1389
1390 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
1391 {
1392         vcpu->arch.cr4 &= KVM_GUEST_CR4_MASK;
1393         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & ~KVM_GUEST_CR4_MASK;
1394 }
1395
1396 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
1397 {
1398         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
1399                 if (!load_pdptrs(vcpu, vcpu->arch.cr3)) {
1400                         printk(KERN_ERR "EPT: Fail to load pdptrs!\n");
1401                         return;
1402                 }
1403                 vmcs_write64(GUEST_PDPTR0, vcpu->arch.pdptrs[0]);
1404                 vmcs_write64(GUEST_PDPTR1, vcpu->arch.pdptrs[1]);
1405                 vmcs_write64(GUEST_PDPTR2, vcpu->arch.pdptrs[2]);
1406                 vmcs_write64(GUEST_PDPTR3, vcpu->arch.pdptrs[3]);
1407         }
1408 }
1409
1410 static void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
1411
1412 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
1413                                         unsigned long cr0,
1414                                         struct kvm_vcpu *vcpu)
1415 {
1416         if (!(cr0 & X86_CR0_PG)) {
1417                 /* From paging/starting to nonpaging */
1418                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
1419                              vmcs_config.cpu_based_exec_ctrl |
1420                              (CPU_BASED_CR3_LOAD_EXITING |
1421                               CPU_BASED_CR3_STORE_EXITING));
1422                 vcpu->arch.cr0 = cr0;
1423                 vmx_set_cr4(vcpu, vcpu->arch.cr4);
1424                 *hw_cr0 |= X86_CR0_PE | X86_CR0_PG;
1425                 *hw_cr0 &= ~X86_CR0_WP;
1426         } else if (!is_paging(vcpu)) {
1427                 /* From nonpaging to paging */
1428                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
1429                              vmcs_config.cpu_based_exec_ctrl &
1430                              ~(CPU_BASED_CR3_LOAD_EXITING |
1431                                CPU_BASED_CR3_STORE_EXITING));
1432                 vcpu->arch.cr0 = cr0;
1433                 vmx_set_cr4(vcpu, vcpu->arch.cr4);
1434                 if (!(vcpu->arch.cr0 & X86_CR0_WP))
1435                         *hw_cr0 &= ~X86_CR0_WP;
1436         }
1437 }
1438
1439 static void ept_update_paging_mode_cr4(unsigned long *hw_cr4,
1440                                         struct kvm_vcpu *vcpu)
1441 {
1442         if (!is_paging(vcpu)) {
1443                 *hw_cr4 &= ~X86_CR4_PAE;
1444                 *hw_cr4 |= X86_CR4_PSE;
1445         } else if (!(vcpu->arch.cr4 & X86_CR4_PAE))
1446                 *hw_cr4 &= ~X86_CR4_PAE;
1447 }
1448
1449 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1450 {
1451         unsigned long hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK) |
1452                                 KVM_VM_CR0_ALWAYS_ON;
1453
1454         vmx_fpu_deactivate(vcpu);
1455
1456         if (vcpu->arch.rmode.active && (cr0 & X86_CR0_PE))
1457                 enter_pmode(vcpu);
1458
1459         if (!vcpu->arch.rmode.active && !(cr0 & X86_CR0_PE))
1460                 enter_rmode(vcpu);
1461
1462 #ifdef CONFIG_X86_64
1463         if (vcpu->arch.shadow_efer & EFER_LME) {
1464                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
1465                         enter_lmode(vcpu);
1466                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
1467                         exit_lmode(vcpu);
1468         }
1469 #endif
1470
1471         if (vm_need_ept())
1472                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
1473
1474         vmcs_writel(CR0_READ_SHADOW, cr0);
1475         vmcs_writel(GUEST_CR0, hw_cr0);
1476         vcpu->arch.cr0 = cr0;
1477
1478         if (!(cr0 & X86_CR0_TS) || !(cr0 & X86_CR0_PE))
1479                 vmx_fpu_activate(vcpu);
1480 }
1481
1482 static u64 construct_eptp(unsigned long root_hpa)
1483 {
1484         u64 eptp;
1485
1486         /* TODO write the value reading from MSR */
1487         eptp = VMX_EPT_DEFAULT_MT |
1488                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
1489         eptp |= (root_hpa & PAGE_MASK);
1490
1491         return eptp;
1492 }
1493
1494 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1495 {
1496         unsigned long guest_cr3;
1497         u64 eptp;
1498
1499         guest_cr3 = cr3;
1500         if (vm_need_ept()) {
1501                 eptp = construct_eptp(cr3);
1502                 vmcs_write64(EPT_POINTER, eptp);
1503                 ept_sync_context(eptp);
1504                 ept_load_pdptrs(vcpu);
1505                 guest_cr3 = is_paging(vcpu) ? vcpu->arch.cr3 :
1506                         VMX_EPT_IDENTITY_PAGETABLE_ADDR;
1507         }
1508
1509         vmx_flush_tlb(vcpu);
1510         vmcs_writel(GUEST_CR3, guest_cr3);
1511         if (vcpu->arch.cr0 & X86_CR0_PE)
1512                 vmx_fpu_deactivate(vcpu);
1513 }
1514
1515 static void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1516 {
1517         unsigned long hw_cr4 = cr4 | (vcpu->arch.rmode.active ?
1518                     KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
1519
1520         vcpu->arch.cr4 = cr4;
1521         if (vm_need_ept())
1522                 ept_update_paging_mode_cr4(&hw_cr4, vcpu);
1523
1524         vmcs_writel(CR4_READ_SHADOW, cr4);
1525         vmcs_writel(GUEST_CR4, hw_cr4);
1526 }
1527
1528 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
1529 {
1530         struct vcpu_vmx *vmx = to_vmx(vcpu);
1531         struct kvm_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
1532
1533         vcpu->arch.shadow_efer = efer;
1534         if (!msr)
1535                 return;
1536         if (efer & EFER_LMA) {
1537                 vmcs_write32(VM_ENTRY_CONTROLS,
1538                                      vmcs_read32(VM_ENTRY_CONTROLS) |
1539                                      VM_ENTRY_IA32E_MODE);
1540                 msr->data = efer;
1541
1542         } else {
1543                 vmcs_write32(VM_ENTRY_CONTROLS,
1544                                      vmcs_read32(VM_ENTRY_CONTROLS) &
1545                                      ~VM_ENTRY_IA32E_MODE);
1546
1547                 msr->data = efer & ~EFER_LME;
1548         }
1549         setup_msrs(vmx);
1550 }
1551
1552 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1553 {
1554         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1555
1556         return vmcs_readl(sf->base);
1557 }
1558
1559 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1560                             struct kvm_segment *var, int seg)
1561 {
1562         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1563         u32 ar;
1564
1565         var->base = vmcs_readl(sf->base);
1566         var->limit = vmcs_read32(sf->limit);
1567         var->selector = vmcs_read16(sf->selector);
1568         ar = vmcs_read32(sf->ar_bytes);
1569         if (ar & AR_UNUSABLE_MASK)
1570                 ar = 0;
1571         var->type = ar & 15;
1572         var->s = (ar >> 4) & 1;
1573         var->dpl = (ar >> 5) & 3;
1574         var->present = (ar >> 7) & 1;
1575         var->avl = (ar >> 12) & 1;
1576         var->l = (ar >> 13) & 1;
1577         var->db = (ar >> 14) & 1;
1578         var->g = (ar >> 15) & 1;
1579         var->unusable = (ar >> 16) & 1;
1580 }
1581
1582 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
1583 {
1584         struct kvm_segment kvm_seg;
1585
1586         if (!(vcpu->arch.cr0 & X86_CR0_PE)) /* if real mode */
1587                 return 0;
1588
1589         if (vmx_get_rflags(vcpu) & X86_EFLAGS_VM) /* if virtual 8086 */
1590                 return 3;
1591
1592         vmx_get_segment(vcpu, &kvm_seg, VCPU_SREG_CS);
1593         return kvm_seg.selector & 3;
1594 }
1595
1596 static u32 vmx_segment_access_rights(struct kvm_segment *var)
1597 {
1598         u32 ar;
1599
1600         if (var->unusable)
1601                 ar = 1 << 16;
1602         else {
1603                 ar = var->type & 15;
1604                 ar |= (var->s & 1) << 4;
1605                 ar |= (var->dpl & 3) << 5;
1606                 ar |= (var->present & 1) << 7;
1607                 ar |= (var->avl & 1) << 12;
1608                 ar |= (var->l & 1) << 13;
1609                 ar |= (var->db & 1) << 14;
1610                 ar |= (var->g & 1) << 15;
1611         }
1612         if (ar == 0) /* a 0 value means unusable */
1613                 ar = AR_UNUSABLE_MASK;
1614
1615         return ar;
1616 }
1617
1618 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1619                             struct kvm_segment *var, int seg)
1620 {
1621         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1622         u32 ar;
1623
1624         if (vcpu->arch.rmode.active && seg == VCPU_SREG_TR) {
1625                 vcpu->arch.rmode.tr.selector = var->selector;
1626                 vcpu->arch.rmode.tr.base = var->base;
1627                 vcpu->arch.rmode.tr.limit = var->limit;
1628                 vcpu->arch.rmode.tr.ar = vmx_segment_access_rights(var);
1629                 return;
1630         }
1631         vmcs_writel(sf->base, var->base);
1632         vmcs_write32(sf->limit, var->limit);
1633         vmcs_write16(sf->selector, var->selector);
1634         if (vcpu->arch.rmode.active && var->s) {
1635                 /*
1636                  * Hack real-mode segments into vm86 compatibility.
1637                  */
1638                 if (var->base == 0xffff0000 && var->selector == 0xf000)
1639                         vmcs_writel(sf->base, 0xf0000);
1640                 ar = 0xf3;
1641         } else
1642                 ar = vmx_segment_access_rights(var);
1643         vmcs_write32(sf->ar_bytes, ar);
1644 }
1645
1646 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
1647 {
1648         u32 ar = vmcs_read32(GUEST_CS_AR_BYTES);
1649
1650         *db = (ar >> 14) & 1;
1651         *l = (ar >> 13) & 1;
1652 }
1653
1654 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1655 {
1656         dt->limit = vmcs_read32(GUEST_IDTR_LIMIT);
1657         dt->base = vmcs_readl(GUEST_IDTR_BASE);
1658 }
1659
1660 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1661 {
1662         vmcs_write32(GUEST_IDTR_LIMIT, dt->limit);
1663         vmcs_writel(GUEST_IDTR_BASE, dt->base);
1664 }
1665
1666 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1667 {
1668         dt->limit = vmcs_read32(GUEST_GDTR_LIMIT);
1669         dt->base = vmcs_readl(GUEST_GDTR_BASE);
1670 }
1671
1672 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1673 {
1674         vmcs_write32(GUEST_GDTR_LIMIT, dt->limit);
1675         vmcs_writel(GUEST_GDTR_BASE, dt->base);
1676 }
1677
1678 static int init_rmode_tss(struct kvm *kvm)
1679 {
1680         gfn_t fn = rmode_tss_base(kvm) >> PAGE_SHIFT;
1681         u16 data = 0;
1682         int ret = 0;
1683         int r;
1684
1685         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
1686         if (r < 0)
1687                 goto out;
1688         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
1689         r = kvm_write_guest_page(kvm, fn++, &data, 0x66, sizeof(u16));
1690         if (r < 0)
1691                 goto out;
1692         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
1693         if (r < 0)
1694                 goto out;
1695         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
1696         if (r < 0)
1697                 goto out;
1698         data = ~0;
1699         r = kvm_write_guest_page(kvm, fn, &data,
1700                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
1701                                  sizeof(u8));
1702         if (r < 0)
1703                 goto out;
1704
1705         ret = 1;
1706 out:
1707         return ret;
1708 }
1709
1710 static int init_rmode_identity_map(struct kvm *kvm)
1711 {
1712         int i, r, ret;
1713         pfn_t identity_map_pfn;
1714         u32 tmp;
1715
1716         if (!vm_need_ept())
1717                 return 1;
1718         if (unlikely(!kvm->arch.ept_identity_pagetable)) {
1719                 printk(KERN_ERR "EPT: identity-mapping pagetable "
1720                         "haven't been allocated!\n");
1721                 return 0;
1722         }
1723         if (likely(kvm->arch.ept_identity_pagetable_done))
1724                 return 1;
1725         ret = 0;
1726         identity_map_pfn = VMX_EPT_IDENTITY_PAGETABLE_ADDR >> PAGE_SHIFT;
1727         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
1728         if (r < 0)
1729                 goto out;
1730         /* Set up identity-mapping pagetable for EPT in real mode */
1731         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
1732                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
1733                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
1734                 r = kvm_write_guest_page(kvm, identity_map_pfn,
1735                                 &tmp, i * sizeof(tmp), sizeof(tmp));
1736                 if (r < 0)
1737                         goto out;
1738         }
1739         kvm->arch.ept_identity_pagetable_done = true;
1740         ret = 1;
1741 out:
1742         return ret;
1743 }
1744
1745 static void seg_setup(int seg)
1746 {
1747         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1748
1749         vmcs_write16(sf->selector, 0);
1750         vmcs_writel(sf->base, 0);
1751         vmcs_write32(sf->limit, 0xffff);
1752         vmcs_write32(sf->ar_bytes, 0x93);
1753 }
1754
1755 static int alloc_apic_access_page(struct kvm *kvm)
1756 {
1757         struct kvm_userspace_memory_region kvm_userspace_mem;
1758         int r = 0;
1759
1760         down_write(&kvm->slots_lock);
1761         if (kvm->arch.apic_access_page)
1762                 goto out;
1763         kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
1764         kvm_userspace_mem.flags = 0;
1765         kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
1766         kvm_userspace_mem.memory_size = PAGE_SIZE;
1767         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
1768         if (r)
1769                 goto out;
1770
1771         down_read(&current->mm->mmap_sem);
1772         kvm->arch.apic_access_page = gfn_to_page(kvm, 0xfee00);
1773         up_read(&current->mm->mmap_sem);
1774 out:
1775         up_write(&kvm->slots_lock);
1776         return r;
1777 }
1778
1779 static int alloc_identity_pagetable(struct kvm *kvm)
1780 {
1781         struct kvm_userspace_memory_region kvm_userspace_mem;
1782         int r = 0;
1783
1784         down_write(&kvm->slots_lock);
1785         if (kvm->arch.ept_identity_pagetable)
1786                 goto out;
1787         kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
1788         kvm_userspace_mem.flags = 0;
1789         kvm_userspace_mem.guest_phys_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
1790         kvm_userspace_mem.memory_size = PAGE_SIZE;
1791         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
1792         if (r)
1793                 goto out;
1794
1795         down_read(&current->mm->mmap_sem);
1796         kvm->arch.ept_identity_pagetable = gfn_to_page(kvm,
1797                         VMX_EPT_IDENTITY_PAGETABLE_ADDR >> PAGE_SHIFT);
1798         up_read(&current->mm->mmap_sem);
1799 out:
1800         up_write(&kvm->slots_lock);
1801         return r;
1802 }
1803
1804 static void allocate_vpid(struct vcpu_vmx *vmx)
1805 {
1806         int vpid;
1807
1808         vmx->vpid = 0;
1809         if (!enable_vpid || !cpu_has_vmx_vpid())
1810                 return;
1811         spin_lock(&vmx_vpid_lock);
1812         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
1813         if (vpid < VMX_NR_VPIDS) {
1814                 vmx->vpid = vpid;
1815                 __set_bit(vpid, vmx_vpid_bitmap);
1816         }
1817         spin_unlock(&vmx_vpid_lock);
1818 }
1819
1820 void vmx_disable_intercept_for_msr(struct page *msr_bitmap, u32 msr)
1821 {
1822         void *va;
1823
1824         if (!cpu_has_vmx_msr_bitmap())
1825                 return;
1826
1827         /*
1828          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
1829          * have the write-low and read-high bitmap offsets the wrong way round.
1830          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
1831          */
1832         va = kmap(msr_bitmap);
1833         if (msr <= 0x1fff) {
1834                 __clear_bit(msr, va + 0x000); /* read-low */
1835                 __clear_bit(msr, va + 0x800); /* write-low */
1836         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1837                 msr &= 0x1fff;
1838                 __clear_bit(msr, va + 0x400); /* read-high */
1839                 __clear_bit(msr, va + 0xc00); /* write-high */
1840         }
1841         kunmap(msr_bitmap);
1842 }
1843
1844 /*
1845  * Sets up the vmcs for emulated real mode.
1846  */
1847 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
1848 {
1849         u32 host_sysenter_cs;
1850         u32 junk;
1851         unsigned long a;
1852         struct descriptor_table dt;
1853         int i;
1854         unsigned long kvm_vmx_return;
1855         u32 exec_control;
1856
1857         /* I/O */
1858         vmcs_write64(IO_BITMAP_A, page_to_phys(vmx_io_bitmap_a));
1859         vmcs_write64(IO_BITMAP_B, page_to_phys(vmx_io_bitmap_b));
1860
1861         if (cpu_has_vmx_msr_bitmap())
1862                 vmcs_write64(MSR_BITMAP, page_to_phys(vmx_msr_bitmap));
1863
1864         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
1865
1866         /* Control */
1867         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
1868                 vmcs_config.pin_based_exec_ctrl);
1869
1870         exec_control = vmcs_config.cpu_based_exec_ctrl;
1871         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
1872                 exec_control &= ~CPU_BASED_TPR_SHADOW;
1873 #ifdef CONFIG_X86_64
1874                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
1875                                 CPU_BASED_CR8_LOAD_EXITING;
1876 #endif
1877         }
1878         if (!vm_need_ept())
1879                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
1880                                 CPU_BASED_CR3_LOAD_EXITING;
1881         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
1882
1883         if (cpu_has_secondary_exec_ctrls()) {
1884                 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
1885                 if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
1886                         exec_control &=
1887                                 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1888                 if (vmx->vpid == 0)
1889                         exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
1890                 if (!vm_need_ept())
1891                         exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
1892                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
1893         }
1894
1895         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, !!bypass_guest_pf);
1896         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, !!bypass_guest_pf);
1897         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
1898
1899         vmcs_writel(HOST_CR0, read_cr0());  /* 22.2.3 */
1900         vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
1901         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
1902
1903         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
1904         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
1905         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
1906         vmcs_write16(HOST_FS_SELECTOR, read_fs());    /* 22.2.4 */
1907         vmcs_write16(HOST_GS_SELECTOR, read_gs());    /* 22.2.4 */
1908         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
1909 #ifdef CONFIG_X86_64
1910         rdmsrl(MSR_FS_BASE, a);
1911         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
1912         rdmsrl(MSR_GS_BASE, a);
1913         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
1914 #else
1915         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
1916         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
1917 #endif
1918
1919         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
1920
1921         get_idt(&dt);
1922         vmcs_writel(HOST_IDTR_BASE, dt.base);   /* 22.2.4 */
1923
1924         asm("mov $.Lkvm_vmx_return, %0" : "=r"(kvm_vmx_return));
1925         vmcs_writel(HOST_RIP, kvm_vmx_return); /* 22.2.5 */
1926         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
1927         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
1928         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
1929
1930         rdmsr(MSR_IA32_SYSENTER_CS, host_sysenter_cs, junk);
1931         vmcs_write32(HOST_IA32_SYSENTER_CS, host_sysenter_cs);
1932         rdmsrl(MSR_IA32_SYSENTER_ESP, a);
1933         vmcs_writel(HOST_IA32_SYSENTER_ESP, a);   /* 22.2.3 */
1934         rdmsrl(MSR_IA32_SYSENTER_EIP, a);
1935         vmcs_writel(HOST_IA32_SYSENTER_EIP, a);   /* 22.2.3 */
1936
1937         for (i = 0; i < NR_VMX_MSR; ++i) {
1938                 u32 index = vmx_msr_index[i];
1939                 u32 data_low, data_high;
1940                 u64 data;
1941                 int j = vmx->nmsrs;
1942
1943                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
1944                         continue;
1945                 if (wrmsr_safe(index, data_low, data_high) < 0)
1946                         continue;
1947                 data = data_low | ((u64)data_high << 32);
1948                 vmx->host_msrs[j].index = index;
1949                 vmx->host_msrs[j].reserved = 0;
1950                 vmx->host_msrs[j].data = data;
1951                 vmx->guest_msrs[j] = vmx->host_msrs[j];
1952                 ++vmx->nmsrs;
1953         }
1954
1955         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
1956
1957         /* 22.2.1, 20.8.1 */
1958         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
1959
1960         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
1961         vmcs_writel(CR4_GUEST_HOST_MASK, KVM_GUEST_CR4_MASK);
1962
1963
1964         return 0;
1965 }
1966
1967 static int init_rmode(struct kvm *kvm)
1968 {
1969         if (!init_rmode_tss(kvm))
1970                 return 0;
1971         if (!init_rmode_identity_map(kvm))
1972                 return 0;
1973         return 1;
1974 }
1975
1976 static int vmx_vcpu_reset(struct kvm_vcpu *vcpu)
1977 {
1978         struct vcpu_vmx *vmx = to_vmx(vcpu);
1979         u64 msr;
1980         int ret;
1981
1982         down_read(&vcpu->kvm->slots_lock);
1983         if (!init_rmode(vmx->vcpu.kvm)) {
1984                 ret = -ENOMEM;
1985                 goto out;
1986         }
1987
1988         vmx->vcpu.arch.rmode.active = 0;
1989
1990         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
1991         kvm_set_cr8(&vmx->vcpu, 0);
1992         msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
1993         if (vmx->vcpu.vcpu_id == 0)
1994                 msr |= MSR_IA32_APICBASE_BSP;
1995         kvm_set_apic_base(&vmx->vcpu, msr);
1996
1997         fx_init(&vmx->vcpu);
1998
1999         /*
2000          * GUEST_CS_BASE should really be 0xffff0000, but VT vm86 mode
2001          * insists on having GUEST_CS_BASE == GUEST_CS_SELECTOR << 4.  Sigh.
2002          */
2003         if (vmx->vcpu.vcpu_id == 0) {
2004                 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
2005                 vmcs_writel(GUEST_CS_BASE, 0x000f0000);
2006         } else {
2007                 vmcs_write16(GUEST_CS_SELECTOR, vmx->vcpu.arch.sipi_vector << 8);
2008                 vmcs_writel(GUEST_CS_BASE, vmx->vcpu.arch.sipi_vector << 12);
2009         }
2010         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
2011         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
2012
2013         seg_setup(VCPU_SREG_DS);
2014         seg_setup(VCPU_SREG_ES);
2015         seg_setup(VCPU_SREG_FS);
2016         seg_setup(VCPU_SREG_GS);
2017         seg_setup(VCPU_SREG_SS);
2018
2019         vmcs_write16(GUEST_TR_SELECTOR, 0);
2020         vmcs_writel(GUEST_TR_BASE, 0);
2021         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
2022         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2023
2024         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
2025         vmcs_writel(GUEST_LDTR_BASE, 0);
2026         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
2027         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
2028
2029         vmcs_write32(GUEST_SYSENTER_CS, 0);
2030         vmcs_writel(GUEST_SYSENTER_ESP, 0);
2031         vmcs_writel(GUEST_SYSENTER_EIP, 0);
2032
2033         vmcs_writel(GUEST_RFLAGS, 0x02);
2034         if (vmx->vcpu.vcpu_id == 0)
2035                 vmcs_writel(GUEST_RIP, 0xfff0);
2036         else
2037                 vmcs_writel(GUEST_RIP, 0);
2038         vmcs_writel(GUEST_RSP, 0);
2039
2040         /* todo: dr0 = dr1 = dr2 = dr3 = 0; dr6 = 0xffff0ff0 */
2041         vmcs_writel(GUEST_DR7, 0x400);
2042
2043         vmcs_writel(GUEST_GDTR_BASE, 0);
2044         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
2045
2046         vmcs_writel(GUEST_IDTR_BASE, 0);
2047         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
2048
2049         vmcs_write32(GUEST_ACTIVITY_STATE, 0);
2050         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
2051         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
2052
2053         guest_write_tsc(0);
2054
2055         /* Special registers */
2056         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
2057
2058         setup_msrs(vmx);
2059
2060         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
2061
2062         if (cpu_has_vmx_tpr_shadow()) {
2063                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
2064                 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
2065                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
2066                                 page_to_phys(vmx->vcpu.arch.apic->regs_page));
2067                 vmcs_write32(TPR_THRESHOLD, 0);
2068         }
2069
2070         if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
2071                 vmcs_write64(APIC_ACCESS_ADDR,
2072                              page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
2073
2074         if (vmx->vpid != 0)
2075                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
2076
2077         vmx->vcpu.arch.cr0 = 0x60000010;
2078         vmx_set_cr0(&vmx->vcpu, vmx->vcpu.arch.cr0); /* enter rmode */
2079         vmx_set_cr4(&vmx->vcpu, 0);
2080         vmx_set_efer(&vmx->vcpu, 0);
2081         vmx_fpu_activate(&vmx->vcpu);
2082         update_exception_bitmap(&vmx->vcpu);
2083
2084         vpid_sync_vcpu_all(vmx);
2085
2086         ret = 0;
2087
2088 out:
2089         up_read(&vcpu->kvm->slots_lock);
2090         return ret;
2091 }
2092
2093 static void vmx_inject_irq(struct kvm_vcpu *vcpu, int irq)
2094 {
2095         struct vcpu_vmx *vmx = to_vmx(vcpu);
2096
2097         KVMTRACE_1D(INJ_VIRQ, vcpu, (u32)irq, handler);
2098
2099         if (vcpu->arch.rmode.active) {
2100                 vmx->rmode.irq.pending = true;
2101                 vmx->rmode.irq.vector = irq;
2102                 vmx->rmode.irq.rip = vmcs_readl(GUEST_RIP);
2103                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2104                              irq | INTR_TYPE_SOFT_INTR | INTR_INFO_VALID_MASK);
2105                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, 1);
2106                 vmcs_writel(GUEST_RIP, vmx->rmode.irq.rip - 1);
2107                 return;
2108         }
2109         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2110                         irq | INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
2111 }
2112
2113 static void kvm_do_inject_irq(struct kvm_vcpu *vcpu)
2114 {
2115         int word_index = __ffs(vcpu->arch.irq_summary);
2116         int bit_index = __ffs(vcpu->arch.irq_pending[word_index]);
2117         int irq = word_index * BITS_PER_LONG + bit_index;
2118
2119         clear_bit(bit_index, &vcpu->arch.irq_pending[word_index]);
2120         if (!vcpu->arch.irq_pending[word_index])
2121                 clear_bit(word_index, &vcpu->arch.irq_summary);
2122         vmx_inject_irq(vcpu, irq);
2123 }
2124
2125
2126 static void do_interrupt_requests(struct kvm_vcpu *vcpu,
2127                                        struct kvm_run *kvm_run)
2128 {
2129         u32 cpu_based_vm_exec_control;
2130
2131         vcpu->arch.interrupt_window_open =
2132                 ((vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
2133                  (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 3) == 0);
2134
2135         if (vcpu->arch.interrupt_window_open &&
2136             vcpu->arch.irq_summary &&
2137             !(vmcs_read32(VM_ENTRY_INTR_INFO_FIELD) & INTR_INFO_VALID_MASK))
2138                 /*
2139                  * If interrupts enabled, and not blocked by sti or mov ss. Good.
2140                  */
2141                 kvm_do_inject_irq(vcpu);
2142
2143         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2144         if (!vcpu->arch.interrupt_window_open &&
2145             (vcpu->arch.irq_summary || kvm_run->request_interrupt_window))
2146                 /*
2147                  * Interrupts blocked.  Wait for unblock.
2148                  */
2149                 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
2150         else
2151                 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
2152         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
2153 }
2154
2155 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
2156 {
2157         int ret;
2158         struct kvm_userspace_memory_region tss_mem = {
2159                 .slot = 8,
2160                 .guest_phys_addr = addr,
2161                 .memory_size = PAGE_SIZE * 3,
2162                 .flags = 0,
2163         };
2164
2165         ret = kvm_set_memory_region(kvm, &tss_mem, 0);
2166         if (ret)
2167                 return ret;
2168         kvm->arch.tss_addr = addr;
2169         return 0;
2170 }
2171
2172 static void kvm_guest_debug_pre(struct kvm_vcpu *vcpu)
2173 {
2174         struct kvm_guest_debug *dbg = &vcpu->guest_debug;
2175
2176         set_debugreg(dbg->bp[0], 0);
2177         set_debugreg(dbg->bp[1], 1);
2178         set_debugreg(dbg->bp[2], 2);
2179         set_debugreg(dbg->bp[3], 3);
2180
2181         if (dbg->singlestep) {
2182                 unsigned long flags;
2183
2184                 flags = vmcs_readl(GUEST_RFLAGS);
2185                 flags |= X86_EFLAGS_TF | X86_EFLAGS_RF;
2186                 vmcs_writel(GUEST_RFLAGS, flags);
2187         }
2188 }
2189
2190 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
2191                                   int vec, u32 err_code)
2192 {
2193         if (!vcpu->arch.rmode.active)
2194                 return 0;
2195
2196         /*
2197          * Instruction with address size override prefix opcode 0x67
2198          * Cause the #SS fault with 0 error code in VM86 mode.
2199          */
2200         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0)
2201                 if (emulate_instruction(vcpu, NULL, 0, 0, 0) == EMULATE_DONE)
2202                         return 1;
2203         return 0;
2204 }
2205
2206 static int handle_exception(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2207 {
2208         struct vcpu_vmx *vmx = to_vmx(vcpu);
2209         u32 intr_info, error_code;
2210         unsigned long cr2, rip;
2211         u32 vect_info;
2212         enum emulation_result er;
2213
2214         vect_info = vmx->idt_vectoring_info;
2215         intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
2216
2217         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
2218                                                 !is_page_fault(intr_info))
2219                 printk(KERN_ERR "%s: unexpected, vectoring info 0x%x "
2220                        "intr info 0x%x\n", __func__, vect_info, intr_info);
2221
2222         if (!irqchip_in_kernel(vcpu->kvm) && is_external_interrupt(vect_info)) {
2223                 int irq = vect_info & VECTORING_INFO_VECTOR_MASK;
2224                 set_bit(irq, vcpu->arch.irq_pending);
2225                 set_bit(irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
2226         }
2227
2228         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == 0x200) /* nmi */
2229                 return 1;  /* already handled by vmx_vcpu_run() */
2230
2231         if (is_no_device(intr_info)) {
2232                 vmx_fpu_activate(vcpu);
2233                 return 1;
2234         }
2235
2236         if (is_invalid_opcode(intr_info)) {
2237                 er = emulate_instruction(vcpu, kvm_run, 0, 0, EMULTYPE_TRAP_UD);
2238                 if (er != EMULATE_DONE)
2239                         kvm_queue_exception(vcpu, UD_VECTOR);
2240                 return 1;
2241         }
2242
2243         error_code = 0;
2244         rip = vmcs_readl(GUEST_RIP);
2245         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
2246                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
2247         if (is_page_fault(intr_info)) {
2248                 /* EPT won't cause page fault directly */
2249                 if (vm_need_ept())
2250                         BUG();
2251                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
2252                 KVMTRACE_3D(PAGE_FAULT, vcpu, error_code, (u32)cr2,
2253                             (u32)((u64)cr2 >> 32), handler);
2254                 return kvm_mmu_page_fault(vcpu, cr2, error_code);
2255         }
2256
2257         if (vcpu->arch.rmode.active &&
2258             handle_rmode_exception(vcpu, intr_info & INTR_INFO_VECTOR_MASK,
2259                                                                 error_code)) {
2260                 if (vcpu->arch.halt_request) {
2261                         vcpu->arch.halt_request = 0;
2262                         return kvm_emulate_halt(vcpu);
2263                 }
2264                 return 1;
2265         }
2266
2267         if ((intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK)) ==
2268             (INTR_TYPE_EXCEPTION | 1)) {
2269                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2270                 return 0;
2271         }
2272         kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
2273         kvm_run->ex.exception = intr_info & INTR_INFO_VECTOR_MASK;
2274         kvm_run->ex.error_code = error_code;
2275         return 0;
2276 }
2277
2278 static int handle_external_interrupt(struct kvm_vcpu *vcpu,
2279                                      struct kvm_run *kvm_run)
2280 {
2281         ++vcpu->stat.irq_exits;
2282         KVMTRACE_1D(INTR, vcpu, vmcs_read32(VM_EXIT_INTR_INFO), handler);
2283         return 1;
2284 }
2285
2286 static int handle_triple_fault(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2287 {
2288         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2289         return 0;
2290 }
2291
2292 static int handle_io(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2293 {
2294         unsigned long exit_qualification;
2295         int size, down, in, string, rep;
2296         unsigned port;
2297
2298         ++vcpu->stat.io_exits;
2299         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
2300         string = (exit_qualification & 16) != 0;
2301
2302         if (string) {
2303                 if (emulate_instruction(vcpu,
2304                                         kvm_run, 0, 0, 0) == EMULATE_DO_MMIO)
2305                         return 0;
2306                 return 1;
2307         }
2308
2309         size = (exit_qualification & 7) + 1;
2310         in = (exit_qualification & 8) != 0;
2311         down = (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_DF) != 0;
2312         rep = (exit_qualification & 32) != 0;
2313         port = exit_qualification >> 16;
2314
2315         return kvm_emulate_pio(vcpu, kvm_run, in, size, port);
2316 }
2317
2318 static void
2319 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
2320 {
2321         /*
2322          * Patch in the VMCALL instruction:
2323          */
2324         hypercall[0] = 0x0f;
2325         hypercall[1] = 0x01;
2326         hypercall[2] = 0xc1;
2327 }
2328
2329 static int handle_cr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2330 {
2331         unsigned long exit_qualification;
2332         int cr;
2333         int reg;
2334
2335         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
2336         cr = exit_qualification & 15;
2337         reg = (exit_qualification >> 8) & 15;
2338         switch ((exit_qualification >> 4) & 3) {
2339         case 0: /* mov to cr */
2340                 KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)vcpu->arch.regs[reg],
2341                             (u32)((u64)vcpu->arch.regs[reg] >> 32), handler);
2342                 switch (cr) {
2343                 case 0:
2344                         vcpu_load_rsp_rip(vcpu);
2345                         kvm_set_cr0(vcpu, vcpu->arch.regs[reg]);
2346                         skip_emulated_instruction(vcpu);
2347                         return 1;
2348                 case 3:
2349                         vcpu_load_rsp_rip(vcpu);
2350                         kvm_set_cr3(vcpu, vcpu->arch.regs[reg]);
2351                         skip_emulated_instruction(vcpu);
2352                         return 1;
2353                 case 4:
2354                         vcpu_load_rsp_rip(vcpu);
2355                         kvm_set_cr4(vcpu, vcpu->arch.regs[reg]);
2356                         skip_emulated_instruction(vcpu);
2357                         return 1;
2358                 case 8:
2359                         vcpu_load_rsp_rip(vcpu);
2360                         kvm_set_cr8(vcpu, vcpu->arch.regs[reg]);
2361                         skip_emulated_instruction(vcpu);
2362                         if (irqchip_in_kernel(vcpu->kvm))
2363                                 return 1;
2364                         kvm_run->exit_reason = KVM_EXIT_SET_TPR;
2365                         return 0;
2366                 };
2367                 break;
2368         case 2: /* clts */
2369                 vcpu_load_rsp_rip(vcpu);
2370                 vmx_fpu_deactivate(vcpu);
2371                 vcpu->arch.cr0 &= ~X86_CR0_TS;
2372                 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
2373                 vmx_fpu_activate(vcpu);
2374                 KVMTRACE_0D(CLTS, vcpu, handler);
2375                 skip_emulated_instruction(vcpu);
2376                 return 1;
2377         case 1: /*mov from cr*/
2378                 switch (cr) {
2379                 case 3:
2380                         vcpu_load_rsp_rip(vcpu);
2381                         vcpu->arch.regs[reg] = vcpu->arch.cr3;
2382                         vcpu_put_rsp_rip(vcpu);
2383                         KVMTRACE_3D(CR_READ, vcpu, (u32)cr,
2384                                     (u32)vcpu->arch.regs[reg],
2385                                     (u32)((u64)vcpu->arch.regs[reg] >> 32),
2386                                     handler);
2387                         skip_emulated_instruction(vcpu);
2388                         return 1;
2389                 case 8:
2390                         vcpu_load_rsp_rip(vcpu);
2391                         vcpu->arch.regs[reg] = kvm_get_cr8(vcpu);
2392                         vcpu_put_rsp_rip(vcpu);
2393                         KVMTRACE_2D(CR_READ, vcpu, (u32)cr,
2394                                     (u32)vcpu->arch.regs[reg], handler);
2395                         skip_emulated_instruction(vcpu);
2396                         return 1;
2397                 }
2398                 break;
2399         case 3: /* lmsw */
2400                 kvm_lmsw(vcpu, (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f);
2401
2402                 skip_emulated_instruction(vcpu);
2403                 return 1;
2404         default:
2405                 break;
2406         }
2407         kvm_run->exit_reason = 0;
2408         pr_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
2409                (int)(exit_qualification >> 4) & 3, cr);
2410         return 0;
2411 }
2412
2413 static int handle_dr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2414 {
2415         unsigned long exit_qualification;
2416         unsigned long val;
2417         int dr, reg;
2418
2419         /*
2420          * FIXME: this code assumes the host is debugging the guest.
2421          *        need to deal with guest debugging itself too.
2422          */
2423         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
2424         dr = exit_qualification & 7;
2425         reg = (exit_qualification >> 8) & 15;
2426         vcpu_load_rsp_rip(vcpu);
2427         if (exit_qualification & 16) {
2428                 /* mov from dr */
2429                 switch (dr) {
2430                 case 6:
2431                         val = 0xffff0ff0;
2432                         break;
2433                 case 7:
2434                         val = 0x400;
2435                         break;
2436                 default:
2437                         val = 0;
2438                 }
2439                 vcpu->arch.regs[reg] = val;
2440                 KVMTRACE_2D(DR_READ, vcpu, (u32)dr, (u32)val, handler);
2441         } else {
2442                 /* mov to dr */
2443         }
2444         vcpu_put_rsp_rip(vcpu);
2445         skip_emulated_instruction(vcpu);
2446         return 1;
2447 }
2448
2449 static int handle_cpuid(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2450 {
2451         kvm_emulate_cpuid(vcpu);
2452         return 1;
2453 }
2454
2455 static int handle_rdmsr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2456 {
2457         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
2458         u64 data;
2459
2460         if (vmx_get_msr(vcpu, ecx, &data)) {
2461                 kvm_inject_gp(vcpu, 0);
2462                 return 1;
2463         }
2464
2465         KVMTRACE_3D(MSR_READ, vcpu, ecx, (u32)data, (u32)(data >> 32),
2466                     handler);
2467
2468         /* FIXME: handling of bits 32:63 of rax, rdx */
2469         vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
2470         vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
2471         skip_emulated_instruction(vcpu);
2472         return 1;
2473 }
2474
2475 static int handle_wrmsr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2476 {
2477         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
2478         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
2479                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
2480
2481         KVMTRACE_3D(MSR_WRITE, vcpu, ecx, (u32)data, (u32)(data >> 32),
2482                     handler);
2483
2484         if (vmx_set_msr(vcpu, ecx, data) != 0) {
2485                 kvm_inject_gp(vcpu, 0);
2486                 return 1;
2487         }
2488
2489         skip_emulated_instruction(vcpu);
2490         return 1;
2491 }
2492
2493 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu,
2494                                       struct kvm_run *kvm_run)
2495 {
2496         return 1;
2497 }
2498
2499 static int handle_interrupt_window(struct kvm_vcpu *vcpu,
2500                                    struct kvm_run *kvm_run)
2501 {
2502         u32 cpu_based_vm_exec_control;
2503
2504         /* clear pending irq */
2505         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2506         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
2507         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
2508
2509         KVMTRACE_0D(PEND_INTR, vcpu, handler);
2510
2511         /*
2512          * If the user space waits to inject interrupts, exit as soon as
2513          * possible
2514          */
2515         if (kvm_run->request_interrupt_window &&
2516             !vcpu->arch.irq_summary) {
2517                 kvm_run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
2518                 ++vcpu->stat.irq_window_exits;
2519                 return 0;
2520         }
2521         return 1;
2522 }
2523
2524 static int handle_halt(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2525 {
2526         skip_emulated_instruction(vcpu);
2527         return kvm_emulate_halt(vcpu);
2528 }
2529
2530 static int handle_vmcall(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2531 {
2532         skip_emulated_instruction(vcpu);
2533         kvm_emulate_hypercall(vcpu);
2534         return 1;
2535 }
2536
2537 static int handle_wbinvd(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2538 {
2539         skip_emulated_instruction(vcpu);
2540         /* TODO: Add support for VT-d/pass-through device */
2541         return 1;
2542 }
2543
2544 static int handle_apic_access(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2545 {
2546         u64 exit_qualification;
2547         enum emulation_result er;
2548         unsigned long offset;
2549
2550         exit_qualification = vmcs_read64(EXIT_QUALIFICATION);
2551         offset = exit_qualification & 0xffful;
2552
2553         KVMTRACE_1D(APIC_ACCESS, vcpu, (u32)offset, handler);
2554
2555         er = emulate_instruction(vcpu, kvm_run, 0, 0, 0);
2556
2557         if (er !=  EMULATE_DONE) {
2558                 printk(KERN_ERR
2559                        "Fail to handle apic access vmexit! Offset is 0x%lx\n",
2560                        offset);
2561                 return -ENOTSUPP;
2562         }
2563         return 1;
2564 }
2565
2566 static int handle_task_switch(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2567 {
2568         unsigned long exit_qualification;
2569         u16 tss_selector;
2570         int reason;
2571
2572         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
2573
2574         reason = (u32)exit_qualification >> 30;
2575         tss_selector = exit_qualification;
2576
2577         return kvm_task_switch(vcpu, tss_selector, reason);
2578 }
2579
2580 static int handle_ept_violation(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2581 {
2582         u64 exit_qualification;
2583         enum emulation_result er;
2584         gpa_t gpa;
2585         unsigned long hva;
2586         int gla_validity;
2587         int r;
2588
2589         exit_qualification = vmcs_read64(EXIT_QUALIFICATION);
2590
2591         if (exit_qualification & (1 << 6)) {
2592                 printk(KERN_ERR "EPT: GPA exceeds GAW!\n");
2593                 return -ENOTSUPP;
2594         }
2595
2596         gla_validity = (exit_qualification >> 7) & 0x3;
2597         if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
2598                 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
2599                 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
2600                         (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
2601                         (long unsigned int)vmcs_read64(GUEST_LINEAR_ADDRESS));
2602                 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
2603                         (long unsigned int)exit_qualification);
2604                 kvm_run->exit_reason = KVM_EXIT_UNKNOWN;
2605                 kvm_run->hw.hardware_exit_reason = 0;
2606                 return -ENOTSUPP;
2607         }
2608
2609         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
2610         hva = gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT);
2611         if (!kvm_is_error_hva(hva)) {
2612                 r = kvm_mmu_page_fault(vcpu, gpa & PAGE_MASK, 0);
2613                 if (r < 0) {
2614                         printk(KERN_ERR "EPT: Not enough memory!\n");
2615                         return -ENOMEM;
2616                 }
2617                 return 1;
2618         } else {
2619                 /* must be MMIO */
2620                 er = emulate_instruction(vcpu, kvm_run, 0, 0, 0);
2621
2622                 if (er == EMULATE_FAIL) {
2623                         printk(KERN_ERR
2624                          "EPT: Fail to handle EPT violation vmexit!er is %d\n",
2625                          er);
2626                         printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
2627                          (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
2628                          (long unsigned int)vmcs_read64(GUEST_LINEAR_ADDRESS));
2629                         printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
2630                                 (long unsigned int)exit_qualification);
2631                         return -ENOTSUPP;
2632                 } else if (er == EMULATE_DO_MMIO)
2633                         return 0;
2634         }
2635         return 1;
2636 }
2637
2638 /*
2639  * The exit handlers return 1 if the exit was handled fully and guest execution
2640  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
2641  * to be done to userspace and return 0.
2642  */
2643 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu,
2644                                       struct kvm_run *kvm_run) = {
2645         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
2646         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
2647         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
2648         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
2649         [EXIT_REASON_CR_ACCESS]               = handle_cr,
2650         [EXIT_REASON_DR_ACCESS]               = handle_dr,
2651         [EXIT_REASON_CPUID]                   = handle_cpuid,
2652         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
2653         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
2654         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
2655         [EXIT_REASON_HLT]                     = handle_halt,
2656         [EXIT_REASON_VMCALL]                  = handle_vmcall,
2657         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
2658         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
2659         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
2660         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
2661         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
2662 };
2663
2664 static const int kvm_vmx_max_exit_handlers =
2665         ARRAY_SIZE(kvm_vmx_exit_handlers);
2666
2667 /*
2668  * The guest has exited.  See if we can fix it or if we need userspace
2669  * assistance.
2670  */
2671 static int kvm_handle_exit(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
2672 {
2673         u32 exit_reason = vmcs_read32(VM_EXIT_REASON);
2674         struct vcpu_vmx *vmx = to_vmx(vcpu);
2675         u32 vectoring_info = vmx->idt_vectoring_info;
2676
2677         KVMTRACE_3D(VMEXIT, vcpu, exit_reason, (u32)vmcs_readl(GUEST_RIP),
2678                     (u32)((u64)vmcs_readl(GUEST_RIP) >> 32), entryexit);
2679
2680         /* Access CR3 don't cause VMExit in paging mode, so we need
2681          * to sync with guest real CR3. */
2682         if (vm_need_ept() && is_paging(vcpu)) {
2683                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2684                 ept_load_pdptrs(vcpu);
2685         }
2686
2687         if (unlikely(vmx->fail)) {
2688                 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
2689                 kvm_run->fail_entry.hardware_entry_failure_reason
2690                         = vmcs_read32(VM_INSTRUCTION_ERROR);
2691                 return 0;
2692         }
2693
2694         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
2695                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
2696                         exit_reason != EXIT_REASON_EPT_VIOLATION))
2697                 printk(KERN_WARNING "%s: unexpected, valid vectoring info and "
2698                        "exit reason is 0x%x\n", __func__, exit_reason);
2699         if (exit_reason < kvm_vmx_max_exit_handlers
2700             && kvm_vmx_exit_handlers[exit_reason])
2701                 return kvm_vmx_exit_handlers[exit_reason](vcpu, kvm_run);
2702         else {
2703                 kvm_run->exit_reason = KVM_EXIT_UNKNOWN;
2704                 kvm_run->hw.hardware_exit_reason = exit_reason;
2705         }
2706         return 0;
2707 }
2708
2709 static void update_tpr_threshold(struct kvm_vcpu *vcpu)
2710 {
2711         int max_irr, tpr;
2712
2713         if (!vm_need_tpr_shadow(vcpu->kvm))
2714                 return;
2715
2716         if (!kvm_lapic_enabled(vcpu) ||
2717             ((max_irr = kvm_lapic_find_highest_irr(vcpu)) == -1)) {
2718                 vmcs_write32(TPR_THRESHOLD, 0);
2719                 return;
2720         }
2721
2722         tpr = (kvm_lapic_get_cr8(vcpu) & 0x0f) << 4;
2723         vmcs_write32(TPR_THRESHOLD, (max_irr > tpr) ? tpr >> 4 : max_irr >> 4);
2724 }
2725
2726 static void enable_irq_window(struct kvm_vcpu *vcpu)
2727 {
2728         u32 cpu_based_vm_exec_control;
2729
2730         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2731         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
2732         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
2733 }
2734
2735 static void vmx_intr_assist(struct kvm_vcpu *vcpu)
2736 {
2737         struct vcpu_vmx *vmx = to_vmx(vcpu);
2738         u32 idtv_info_field, intr_info_field;
2739         int has_ext_irq, interrupt_window_open;
2740         int vector;
2741
2742         update_tpr_threshold(vcpu);
2743
2744         has_ext_irq = kvm_cpu_has_interrupt(vcpu);
2745         intr_info_field = vmcs_read32(VM_ENTRY_INTR_INFO_FIELD);
2746         idtv_info_field = vmx->idt_vectoring_info;
2747         if (intr_info_field & INTR_INFO_VALID_MASK) {
2748                 if (idtv_info_field & INTR_INFO_VALID_MASK) {
2749                         /* TODO: fault when IDT_Vectoring */
2750                         if (printk_ratelimit())
2751                                 printk(KERN_ERR "Fault when IDT_Vectoring\n");
2752                 }
2753                 if (has_ext_irq)
2754                         enable_irq_window(vcpu);
2755                 return;
2756         }
2757         if (unlikely(idtv_info_field & INTR_INFO_VALID_MASK)) {
2758                 if ((idtv_info_field & VECTORING_INFO_TYPE_MASK)
2759                     == INTR_TYPE_EXT_INTR
2760                     && vcpu->arch.rmode.active) {
2761                         u8 vect = idtv_info_field & VECTORING_INFO_VECTOR_MASK;
2762
2763                         vmx_inject_irq(vcpu, vect);
2764                         if (unlikely(has_ext_irq))
2765                                 enable_irq_window(vcpu);
2766                         return;
2767                 }
2768
2769                 KVMTRACE_1D(REDELIVER_EVT, vcpu, idtv_info_field, handler);
2770
2771                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, idtv_info_field);
2772                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2773                                 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
2774
2775                 if (unlikely(idtv_info_field & INTR_INFO_DELIVER_CODE_MASK))
2776                         vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
2777                                 vmcs_read32(IDT_VECTORING_ERROR_CODE));
2778                 if (unlikely(has_ext_irq))
2779                         enable_irq_window(vcpu);
2780                 return;
2781         }
2782         if (!has_ext_irq)
2783                 return;
2784         interrupt_window_open =
2785                 ((vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
2786                  (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 3) == 0);
2787         if (interrupt_window_open) {
2788                 vector = kvm_cpu_get_interrupt(vcpu);
2789                 vmx_inject_irq(vcpu, vector);
2790                 kvm_timer_intr_post(vcpu, vector);
2791         } else
2792                 enable_irq_window(vcpu);
2793 }
2794
2795 /*
2796  * Failure to inject an interrupt should give us the information
2797  * in IDT_VECTORING_INFO_FIELD.  However, if the failure occurs
2798  * when fetching the interrupt redirection bitmap in the real-mode
2799  * tss, this doesn't happen.  So we do it ourselves.
2800  */
2801 static void fixup_rmode_irq(struct vcpu_vmx *vmx)
2802 {
2803         vmx->rmode.irq.pending = 0;
2804         if (vmcs_readl(GUEST_RIP) + 1 != vmx->rmode.irq.rip)
2805                 return;
2806         vmcs_writel(GUEST_RIP, vmx->rmode.irq.rip);
2807         if (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK) {
2808                 vmx->idt_vectoring_info &= ~VECTORING_INFO_TYPE_MASK;
2809                 vmx->idt_vectoring_info |= INTR_TYPE_EXT_INTR;
2810                 return;
2811         }
2812         vmx->idt_vectoring_info =
2813                 VECTORING_INFO_VALID_MASK
2814                 | INTR_TYPE_EXT_INTR
2815                 | vmx->rmode.irq.vector;
2816 }
2817
2818 static void vmx_vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2819 {
2820         struct vcpu_vmx *vmx = to_vmx(vcpu);
2821         u32 intr_info;
2822
2823         /*
2824          * Loading guest fpu may have cleared host cr0.ts
2825          */
2826         vmcs_writel(HOST_CR0, read_cr0());
2827
2828         asm(
2829                 /* Store host registers */
2830 #ifdef CONFIG_X86_64
2831                 "push %%rdx; push %%rbp;"
2832                 "push %%rcx \n\t"
2833 #else
2834                 "push %%edx; push %%ebp;"
2835                 "push %%ecx \n\t"
2836 #endif
2837                 ASM_VMX_VMWRITE_RSP_RDX "\n\t"
2838                 /* Check if vmlaunch of vmresume is needed */
2839                 "cmpl $0, %c[launched](%0) \n\t"
2840                 /* Load guest registers.  Don't clobber flags. */
2841 #ifdef CONFIG_X86_64
2842                 "mov %c[cr2](%0), %%rax \n\t"
2843                 "mov %%rax, %%cr2 \n\t"
2844                 "mov %c[rax](%0), %%rax \n\t"
2845                 "mov %c[rbx](%0), %%rbx \n\t"
2846                 "mov %c[rdx](%0), %%rdx \n\t"
2847                 "mov %c[rsi](%0), %%rsi \n\t"
2848                 "mov %c[rdi](%0), %%rdi \n\t"
2849                 "mov %c[rbp](%0), %%rbp \n\t"
2850                 "mov %c[r8](%0),  %%r8  \n\t"
2851                 "mov %c[r9](%0),  %%r9  \n\t"
2852                 "mov %c[r10](%0), %%r10 \n\t"
2853                 "mov %c[r11](%0), %%r11 \n\t"
2854                 "mov %c[r12](%0), %%r12 \n\t"
2855                 "mov %c[r13](%0), %%r13 \n\t"
2856                 "mov %c[r14](%0), %%r14 \n\t"
2857                 "mov %c[r15](%0), %%r15 \n\t"
2858                 "mov %c[rcx](%0), %%rcx \n\t" /* kills %0 (rcx) */
2859 #else
2860                 "mov %c[cr2](%0), %%eax \n\t"
2861                 "mov %%eax,   %%cr2 \n\t"
2862                 "mov %c[rax](%0), %%eax \n\t"
2863                 "mov %c[rbx](%0), %%ebx \n\t"
2864                 "mov %c[rdx](%0), %%edx \n\t"
2865                 "mov %c[rsi](%0), %%esi \n\t"
2866                 "mov %c[rdi](%0), %%edi \n\t"
2867                 "mov %c[rbp](%0), %%ebp \n\t"
2868                 "mov %c[rcx](%0), %%ecx \n\t" /* kills %0 (ecx) */
2869 #endif
2870                 /* Enter guest mode */
2871                 "jne .Llaunched \n\t"
2872                 ASM_VMX_VMLAUNCH "\n\t"
2873                 "jmp .Lkvm_vmx_return \n\t"
2874                 ".Llaunched: " ASM_VMX_VMRESUME "\n\t"
2875                 ".Lkvm_vmx_return: "
2876                 /* Save guest registers, load host registers, keep flags */
2877 #ifdef CONFIG_X86_64
2878                 "xchg %0,     (%%rsp) \n\t"
2879                 "mov %%rax, %c[rax](%0) \n\t"
2880                 "mov %%rbx, %c[rbx](%0) \n\t"
2881                 "pushq (%%rsp); popq %c[rcx](%0) \n\t"
2882                 "mov %%rdx, %c[rdx](%0) \n\t"
2883                 "mov %%rsi, %c[rsi](%0) \n\t"
2884                 "mov %%rdi, %c[rdi](%0) \n\t"
2885                 "mov %%rbp, %c[rbp](%0) \n\t"
2886                 "mov %%r8,  %c[r8](%0) \n\t"
2887                 "mov %%r9,  %c[r9](%0) \n\t"
2888                 "mov %%r10, %c[r10](%0) \n\t"
2889                 "mov %%r11, %c[r11](%0) \n\t"
2890                 "mov %%r12, %c[r12](%0) \n\t"
2891                 "mov %%r13, %c[r13](%0) \n\t"
2892                 "mov %%r14, %c[r14](%0) \n\t"
2893                 "mov %%r15, %c[r15](%0) \n\t"
2894                 "mov %%cr2, %%rax   \n\t"
2895                 "mov %%rax, %c[cr2](%0) \n\t"
2896
2897                 "pop  %%rbp; pop  %%rbp; pop  %%rdx \n\t"
2898 #else
2899                 "xchg %0, (%%esp) \n\t"
2900                 "mov %%eax, %c[rax](%0) \n\t"
2901                 "mov %%ebx, %c[rbx](%0) \n\t"
2902                 "pushl (%%esp); popl %c[rcx](%0) \n\t"
2903                 "mov %%edx, %c[rdx](%0) \n\t"
2904                 "mov %%esi, %c[rsi](%0) \n\t"
2905                 "mov %%edi, %c[rdi](%0) \n\t"
2906                 "mov %%ebp, %c[rbp](%0) \n\t"
2907                 "mov %%cr2, %%eax  \n\t"
2908                 "mov %%eax, %c[cr2](%0) \n\t"
2909
2910                 "pop %%ebp; pop %%ebp; pop %%edx \n\t"
2911 #endif
2912                 "setbe %c[fail](%0) \n\t"
2913               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
2914                 [launched]"i"(offsetof(struct vcpu_vmx, launched)),
2915                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
2916                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
2917                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
2918                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
2919                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
2920                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
2921                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
2922                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
2923 #ifdef CONFIG_X86_64
2924                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
2925                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
2926                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
2927                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
2928                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
2929                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
2930                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
2931                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
2932 #endif
2933                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2))
2934               : "cc", "memory"
2935 #ifdef CONFIG_X86_64
2936                 , "rbx", "rdi", "rsi"
2937                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
2938 #else
2939                 , "ebx", "edi", "rsi"
2940 #endif
2941               );
2942
2943         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
2944         if (vmx->rmode.irq.pending)
2945                 fixup_rmode_irq(vmx);
2946
2947         vcpu->arch.interrupt_window_open =
2948                 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 3) == 0;
2949
2950         asm("mov %0, %%ds; mov %0, %%es" : : "r"(__USER_DS));
2951         vmx->launched = 1;
2952
2953         intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
2954
2955         /* We need to handle NMIs before interrupts are enabled */
2956         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == 0x200) { /* nmi */
2957                 KVMTRACE_0D(NMI, vcpu, handler);
2958                 asm("int $2");
2959         }
2960 }
2961
2962 static void vmx_free_vmcs(struct kvm_vcpu *vcpu)
2963 {
2964         struct vcpu_vmx *vmx = to_vmx(vcpu);
2965
2966         if (vmx->vmcs) {
2967                 on_each_cpu(__vcpu_clear, vmx, 0, 1);
2968                 free_vmcs(vmx->vmcs);
2969                 vmx->vmcs = NULL;
2970         }
2971 }
2972
2973 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
2974 {
2975         struct vcpu_vmx *vmx = to_vmx(vcpu);
2976
2977         spin_lock(&vmx_vpid_lock);
2978         if (vmx->vpid != 0)
2979                 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
2980         spin_unlock(&vmx_vpid_lock);
2981         vmx_free_vmcs(vcpu);
2982         kfree(vmx->host_msrs);
2983         kfree(vmx->guest_msrs);
2984         kvm_vcpu_uninit(vcpu);
2985         kmem_cache_free(kvm_vcpu_cache, vmx);
2986 }
2987
2988 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
2989 {
2990         int err;
2991         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
2992         int cpu;
2993
2994         if (!vmx)
2995                 return ERR_PTR(-ENOMEM);
2996
2997         allocate_vpid(vmx);
2998         if (id == 0 && vm_need_ept()) {
2999                 kvm_mmu_set_base_ptes(VMX_EPT_READABLE_MASK |
3000                         VMX_EPT_WRITABLE_MASK |
3001                         VMX_EPT_DEFAULT_MT << VMX_EPT_MT_EPTE_SHIFT);
3002                 kvm_mmu_set_mask_ptes(0ull, VMX_EPT_FAKE_ACCESSED_MASK,
3003                                 VMX_EPT_FAKE_DIRTY_MASK, 0ull,
3004                                 VMX_EPT_EXECUTABLE_MASK);
3005                 kvm_enable_tdp();
3006         }
3007
3008         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
3009         if (err)
3010                 goto free_vcpu;
3011
3012         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
3013         if (!vmx->guest_msrs) {
3014                 err = -ENOMEM;
3015                 goto uninit_vcpu;
3016         }
3017
3018         vmx->host_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
3019         if (!vmx->host_msrs)
3020                 goto free_guest_msrs;
3021
3022         vmx->vmcs = alloc_vmcs();
3023         if (!vmx->vmcs)
3024                 goto free_msrs;
3025
3026         vmcs_clear(vmx->vmcs);
3027
3028         cpu = get_cpu();
3029         vmx_vcpu_load(&vmx->vcpu, cpu);
3030         err = vmx_vcpu_setup(vmx);
3031         vmx_vcpu_put(&vmx->vcpu);
3032         put_cpu();
3033         if (err)
3034                 goto free_vmcs;
3035         if (vm_need_virtualize_apic_accesses(kvm))
3036                 if (alloc_apic_access_page(kvm) != 0)
3037                         goto free_vmcs;
3038
3039         if (vm_need_ept())
3040                 if (alloc_identity_pagetable(kvm) != 0)
3041                         goto free_vmcs;
3042
3043         return &vmx->vcpu;
3044
3045 free_vmcs:
3046         free_vmcs(vmx->vmcs);
3047 free_msrs:
3048         kfree(vmx->host_msrs);
3049 free_guest_msrs:
3050         kfree(vmx->guest_msrs);
3051 uninit_vcpu:
3052         kvm_vcpu_uninit(&vmx->vcpu);
3053 free_vcpu:
3054         kmem_cache_free(kvm_vcpu_cache, vmx);
3055         return ERR_PTR(err);
3056 }
3057
3058 static void __init vmx_check_processor_compat(void *rtn)
3059 {
3060         struct vmcs_config vmcs_conf;
3061
3062         *(int *)rtn = 0;
3063         if (setup_vmcs_config(&vmcs_conf) < 0)
3064                 *(int *)rtn = -EIO;
3065         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
3066                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
3067                                 smp_processor_id());
3068                 *(int *)rtn = -EIO;
3069         }
3070 }
3071
3072 static int get_ept_level(void)
3073 {
3074         return VMX_EPT_DEFAULT_GAW + 1;
3075 }
3076
3077 static struct kvm_x86_ops vmx_x86_ops = {
3078         .cpu_has_kvm_support = cpu_has_kvm_support,
3079         .disabled_by_bios = vmx_disabled_by_bios,
3080         .hardware_setup = hardware_setup,
3081         .hardware_unsetup = hardware_unsetup,
3082         .check_processor_compatibility = vmx_check_processor_compat,
3083         .hardware_enable = hardware_enable,
3084         .hardware_disable = hardware_disable,
3085         .cpu_has_accelerated_tpr = cpu_has_vmx_virtualize_apic_accesses,
3086
3087         .vcpu_create = vmx_create_vcpu,
3088         .vcpu_free = vmx_free_vcpu,
3089         .vcpu_reset = vmx_vcpu_reset,
3090
3091         .prepare_guest_switch = vmx_save_host_state,
3092         .vcpu_load = vmx_vcpu_load,
3093         .vcpu_put = vmx_vcpu_put,
3094         .vcpu_decache = vmx_vcpu_decache,
3095
3096         .set_guest_debug = set_guest_debug,
3097         .guest_debug_pre = kvm_guest_debug_pre,
3098         .get_msr = vmx_get_msr,
3099         .set_msr = vmx_set_msr,
3100         .get_segment_base = vmx_get_segment_base,
3101         .get_segment = vmx_get_segment,
3102         .set_segment = vmx_set_segment,
3103         .get_cpl = vmx_get_cpl,
3104         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
3105         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
3106         .set_cr0 = vmx_set_cr0,
3107         .set_cr3 = vmx_set_cr3,
3108         .set_cr4 = vmx_set_cr4,
3109         .set_efer = vmx_set_efer,
3110         .get_idt = vmx_get_idt,
3111         .set_idt = vmx_set_idt,
3112         .get_gdt = vmx_get_gdt,
3113         .set_gdt = vmx_set_gdt,
3114         .cache_regs = vcpu_load_rsp_rip,
3115         .decache_regs = vcpu_put_rsp_rip,
3116         .get_rflags = vmx_get_rflags,
3117         .set_rflags = vmx_set_rflags,
3118
3119         .tlb_flush = vmx_flush_tlb,
3120
3121         .run = vmx_vcpu_run,
3122         .handle_exit = kvm_handle_exit,
3123         .skip_emulated_instruction = skip_emulated_instruction,
3124         .patch_hypercall = vmx_patch_hypercall,
3125         .get_irq = vmx_get_irq,
3126         .set_irq = vmx_inject_irq,
3127         .queue_exception = vmx_queue_exception,
3128         .exception_injected = vmx_exception_injected,
3129         .inject_pending_irq = vmx_intr_assist,
3130         .inject_pending_vectors = do_interrupt_requests,
3131
3132         .set_tss_addr = vmx_set_tss_addr,
3133         .get_tdp_level = get_ept_level,
3134 };
3135
3136 static int __init vmx_init(void)
3137 {
3138         void *va;
3139         int r;
3140
3141         vmx_io_bitmap_a = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
3142         if (!vmx_io_bitmap_a)
3143                 return -ENOMEM;
3144
3145         vmx_io_bitmap_b = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
3146         if (!vmx_io_bitmap_b) {
3147                 r = -ENOMEM;
3148                 goto out;
3149         }
3150
3151         vmx_msr_bitmap = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
3152         if (!vmx_msr_bitmap) {
3153                 r = -ENOMEM;
3154                 goto out1;
3155         }
3156
3157         /*
3158          * Allow direct access to the PC debug port (it is often used for I/O
3159          * delays, but the vmexits simply slow things down).
3160          */
3161         va = kmap(vmx_io_bitmap_a);
3162         memset(va, 0xff, PAGE_SIZE);
3163         clear_bit(0x80, va);
3164         kunmap(vmx_io_bitmap_a);
3165
3166         va = kmap(vmx_io_bitmap_b);
3167         memset(va, 0xff, PAGE_SIZE);
3168         kunmap(vmx_io_bitmap_b);
3169
3170         va = kmap(vmx_msr_bitmap);
3171         memset(va, 0xff, PAGE_SIZE);
3172         kunmap(vmx_msr_bitmap);
3173
3174         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
3175
3176         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx), THIS_MODULE);
3177         if (r)
3178                 goto out2;
3179
3180         vmx_disable_intercept_for_msr(vmx_msr_bitmap, MSR_FS_BASE);
3181         vmx_disable_intercept_for_msr(vmx_msr_bitmap, MSR_GS_BASE);
3182         vmx_disable_intercept_for_msr(vmx_msr_bitmap, MSR_IA32_SYSENTER_CS);
3183         vmx_disable_intercept_for_msr(vmx_msr_bitmap, MSR_IA32_SYSENTER_ESP);
3184         vmx_disable_intercept_for_msr(vmx_msr_bitmap, MSR_IA32_SYSENTER_EIP);
3185
3186         if (cpu_has_vmx_ept())
3187                 bypass_guest_pf = 0;
3188
3189         if (bypass_guest_pf)
3190                 kvm_mmu_set_nonpresent_ptes(~0xffeull, 0ull);
3191
3192         ept_sync_global();
3193
3194         return 0;
3195
3196 out2:
3197         __free_page(vmx_msr_bitmap);
3198 out1:
3199         __free_page(vmx_io_bitmap_b);
3200 out:
3201         __free_page(vmx_io_bitmap_a);
3202         return r;
3203 }
3204
3205 static void __exit vmx_exit(void)
3206 {
3207         __free_page(vmx_msr_bitmap);
3208         __free_page(vmx_io_bitmap_b);
3209         __free_page(vmx_io_bitmap_a);
3210
3211         kvm_exit();
3212 }
3213
3214 module_init(vmx_init)
3215 module_exit(vmx_exit)