Merge branch 'master' of git://git.infradead.org/~dedekind/ubi-2.6
[linux-2.6] / drivers / 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 "kvm.h"
19 #include "x86_emulate.h"
20 #include "irq.h"
21 #include "vmx.h"
22 #include "segment_descriptor.h"
23
24 #include <linux/module.h>
25 #include <linux/kernel.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/sched.h>
29
30 #include <asm/io.h>
31 #include <asm/desc.h>
32
33 MODULE_AUTHOR("Qumranet");
34 MODULE_LICENSE("GPL");
35
36 struct vmcs {
37         u32 revision_id;
38         u32 abort;
39         char data[0];
40 };
41
42 struct vcpu_vmx {
43         struct kvm_vcpu       vcpu;
44         int                   launched;
45         u8                    fail;
46         struct kvm_msr_entry *guest_msrs;
47         struct kvm_msr_entry *host_msrs;
48         int                   nmsrs;
49         int                   save_nmsrs;
50         int                   msr_offset_efer;
51 #ifdef CONFIG_X86_64
52         int                   msr_offset_kernel_gs_base;
53 #endif
54         struct vmcs          *vmcs;
55         struct {
56                 int           loaded;
57                 u16           fs_sel, gs_sel, ldt_sel;
58                 int           gs_ldt_reload_needed;
59                 int           fs_reload_needed;
60         }host_state;
61
62 };
63
64 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
65 {
66         return container_of(vcpu, struct vcpu_vmx, vcpu);
67 }
68
69 static int init_rmode_tss(struct kvm *kvm);
70
71 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
72 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
73
74 static struct page *vmx_io_bitmap_a;
75 static struct page *vmx_io_bitmap_b;
76
77 #define EFER_SAVE_RESTORE_BITS ((u64)EFER_SCE)
78
79 static struct vmcs_config {
80         int size;
81         int order;
82         u32 revision_id;
83         u32 pin_based_exec_ctrl;
84         u32 cpu_based_exec_ctrl;
85         u32 vmexit_ctrl;
86         u32 vmentry_ctrl;
87 } vmcs_config;
88
89 #define VMX_SEGMENT_FIELD(seg)                                  \
90         [VCPU_SREG_##seg] = {                                   \
91                 .selector = GUEST_##seg##_SELECTOR,             \
92                 .base = GUEST_##seg##_BASE,                     \
93                 .limit = GUEST_##seg##_LIMIT,                   \
94                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
95         }
96
97 static struct kvm_vmx_segment_field {
98         unsigned selector;
99         unsigned base;
100         unsigned limit;
101         unsigned ar_bytes;
102 } kvm_vmx_segment_fields[] = {
103         VMX_SEGMENT_FIELD(CS),
104         VMX_SEGMENT_FIELD(DS),
105         VMX_SEGMENT_FIELD(ES),
106         VMX_SEGMENT_FIELD(FS),
107         VMX_SEGMENT_FIELD(GS),
108         VMX_SEGMENT_FIELD(SS),
109         VMX_SEGMENT_FIELD(TR),
110         VMX_SEGMENT_FIELD(LDTR),
111 };
112
113 /*
114  * Keep MSR_K6_STAR at the end, as setup_msrs() will try to optimize it
115  * away by decrementing the array size.
116  */
117 static const u32 vmx_msr_index[] = {
118 #ifdef CONFIG_X86_64
119         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR, MSR_KERNEL_GS_BASE,
120 #endif
121         MSR_EFER, MSR_K6_STAR,
122 };
123 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
124
125 static void load_msrs(struct kvm_msr_entry *e, int n)
126 {
127         int i;
128
129         for (i = 0; i < n; ++i)
130                 wrmsrl(e[i].index, e[i].data);
131 }
132
133 static void save_msrs(struct kvm_msr_entry *e, int n)
134 {
135         int i;
136
137         for (i = 0; i < n; ++i)
138                 rdmsrl(e[i].index, e[i].data);
139 }
140
141 static inline u64 msr_efer_save_restore_bits(struct kvm_msr_entry msr)
142 {
143         return (u64)msr.data & EFER_SAVE_RESTORE_BITS;
144 }
145
146 static inline int msr_efer_need_save_restore(struct vcpu_vmx *vmx)
147 {
148         int efer_offset = vmx->msr_offset_efer;
149         return msr_efer_save_restore_bits(vmx->host_msrs[efer_offset]) !=
150                 msr_efer_save_restore_bits(vmx->guest_msrs[efer_offset]);
151 }
152
153 static inline int is_page_fault(u32 intr_info)
154 {
155         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
156                              INTR_INFO_VALID_MASK)) ==
157                 (INTR_TYPE_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
158 }
159
160 static inline int is_no_device(u32 intr_info)
161 {
162         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
163                              INTR_INFO_VALID_MASK)) ==
164                 (INTR_TYPE_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
165 }
166
167 static inline int is_external_interrupt(u32 intr_info)
168 {
169         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
170                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
171 }
172
173 static inline int cpu_has_vmx_tpr_shadow(void)
174 {
175         return (vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW);
176 }
177
178 static inline int vm_need_tpr_shadow(struct kvm *kvm)
179 {
180         return ((cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm)));
181 }
182
183 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
184 {
185         int i;
186
187         for (i = 0; i < vmx->nmsrs; ++i)
188                 if (vmx->guest_msrs[i].index == msr)
189                         return i;
190         return -1;
191 }
192
193 static struct kvm_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
194 {
195         int i;
196
197         i = __find_msr_index(vmx, msr);
198         if (i >= 0)
199                 return &vmx->guest_msrs[i];
200         return NULL;
201 }
202
203 static void vmcs_clear(struct vmcs *vmcs)
204 {
205         u64 phys_addr = __pa(vmcs);
206         u8 error;
207
208         asm volatile (ASM_VMX_VMCLEAR_RAX "; setna %0"
209                       : "=g"(error) : "a"(&phys_addr), "m"(phys_addr)
210                       : "cc", "memory");
211         if (error)
212                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
213                        vmcs, phys_addr);
214 }
215
216 static void __vcpu_clear(void *arg)
217 {
218         struct vcpu_vmx *vmx = arg;
219         int cpu = raw_smp_processor_id();
220
221         if (vmx->vcpu.cpu == cpu)
222                 vmcs_clear(vmx->vmcs);
223         if (per_cpu(current_vmcs, cpu) == vmx->vmcs)
224                 per_cpu(current_vmcs, cpu) = NULL;
225         rdtscll(vmx->vcpu.host_tsc);
226 }
227
228 static void vcpu_clear(struct vcpu_vmx *vmx)
229 {
230         if (vmx->vcpu.cpu != raw_smp_processor_id() && vmx->vcpu.cpu != -1)
231                 smp_call_function_single(vmx->vcpu.cpu, __vcpu_clear,
232                                          vmx, 0, 1);
233         else
234                 __vcpu_clear(vmx);
235         vmx->launched = 0;
236 }
237
238 static unsigned long vmcs_readl(unsigned long field)
239 {
240         unsigned long value;
241
242         asm volatile (ASM_VMX_VMREAD_RDX_RAX
243                       : "=a"(value) : "d"(field) : "cc");
244         return value;
245 }
246
247 static u16 vmcs_read16(unsigned long field)
248 {
249         return vmcs_readl(field);
250 }
251
252 static u32 vmcs_read32(unsigned long field)
253 {
254         return vmcs_readl(field);
255 }
256
257 static u64 vmcs_read64(unsigned long field)
258 {
259 #ifdef CONFIG_X86_64
260         return vmcs_readl(field);
261 #else
262         return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
263 #endif
264 }
265
266 static noinline void vmwrite_error(unsigned long field, unsigned long value)
267 {
268         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
269                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
270         dump_stack();
271 }
272
273 static void vmcs_writel(unsigned long field, unsigned long value)
274 {
275         u8 error;
276
277         asm volatile (ASM_VMX_VMWRITE_RAX_RDX "; setna %0"
278                        : "=q"(error) : "a"(value), "d"(field) : "cc" );
279         if (unlikely(error))
280                 vmwrite_error(field, value);
281 }
282
283 static void vmcs_write16(unsigned long field, u16 value)
284 {
285         vmcs_writel(field, value);
286 }
287
288 static void vmcs_write32(unsigned long field, u32 value)
289 {
290         vmcs_writel(field, value);
291 }
292
293 static void vmcs_write64(unsigned long field, u64 value)
294 {
295 #ifdef CONFIG_X86_64
296         vmcs_writel(field, value);
297 #else
298         vmcs_writel(field, value);
299         asm volatile ("");
300         vmcs_writel(field+1, value >> 32);
301 #endif
302 }
303
304 static void vmcs_clear_bits(unsigned long field, u32 mask)
305 {
306         vmcs_writel(field, vmcs_readl(field) & ~mask);
307 }
308
309 static void vmcs_set_bits(unsigned long field, u32 mask)
310 {
311         vmcs_writel(field, vmcs_readl(field) | mask);
312 }
313
314 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
315 {
316         u32 eb;
317
318         eb = 1u << PF_VECTOR;
319         if (!vcpu->fpu_active)
320                 eb |= 1u << NM_VECTOR;
321         if (vcpu->guest_debug.enabled)
322                 eb |= 1u << 1;
323         if (vcpu->rmode.active)
324                 eb = ~0;
325         vmcs_write32(EXCEPTION_BITMAP, eb);
326 }
327
328 static void reload_tss(void)
329 {
330 #ifndef CONFIG_X86_64
331
332         /*
333          * VT restores TR but not its size.  Useless.
334          */
335         struct descriptor_table gdt;
336         struct segment_descriptor *descs;
337
338         get_gdt(&gdt);
339         descs = (void *)gdt.base;
340         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
341         load_TR_desc();
342 #endif
343 }
344
345 static void load_transition_efer(struct vcpu_vmx *vmx)
346 {
347         u64 trans_efer;
348         int efer_offset = vmx->msr_offset_efer;
349
350         trans_efer = vmx->host_msrs[efer_offset].data;
351         trans_efer &= ~EFER_SAVE_RESTORE_BITS;
352         trans_efer |= msr_efer_save_restore_bits(vmx->guest_msrs[efer_offset]);
353         wrmsrl(MSR_EFER, trans_efer);
354         vmx->vcpu.stat.efer_reload++;
355 }
356
357 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
358 {
359         struct vcpu_vmx *vmx = to_vmx(vcpu);
360
361         if (vmx->host_state.loaded)
362                 return;
363
364         vmx->host_state.loaded = 1;
365         /*
366          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
367          * allow segment selectors with cpl > 0 or ti == 1.
368          */
369         vmx->host_state.ldt_sel = read_ldt();
370         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
371         vmx->host_state.fs_sel = read_fs();
372         if (!(vmx->host_state.fs_sel & 7)) {
373                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
374                 vmx->host_state.fs_reload_needed = 0;
375         } else {
376                 vmcs_write16(HOST_FS_SELECTOR, 0);
377                 vmx->host_state.fs_reload_needed = 1;
378         }
379         vmx->host_state.gs_sel = read_gs();
380         if (!(vmx->host_state.gs_sel & 7))
381                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
382         else {
383                 vmcs_write16(HOST_GS_SELECTOR, 0);
384                 vmx->host_state.gs_ldt_reload_needed = 1;
385         }
386
387 #ifdef CONFIG_X86_64
388         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
389         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
390 #else
391         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
392         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
393 #endif
394
395 #ifdef CONFIG_X86_64
396         if (is_long_mode(&vmx->vcpu)) {
397                 save_msrs(vmx->host_msrs +
398                           vmx->msr_offset_kernel_gs_base, 1);
399         }
400 #endif
401         load_msrs(vmx->guest_msrs, vmx->save_nmsrs);
402         if (msr_efer_need_save_restore(vmx))
403                 load_transition_efer(vmx);
404 }
405
406 static void vmx_load_host_state(struct vcpu_vmx *vmx)
407 {
408         unsigned long flags;
409
410         if (!vmx->host_state.loaded)
411                 return;
412
413         vmx->host_state.loaded = 0;
414         if (vmx->host_state.fs_reload_needed)
415                 load_fs(vmx->host_state.fs_sel);
416         if (vmx->host_state.gs_ldt_reload_needed) {
417                 load_ldt(vmx->host_state.ldt_sel);
418                 /*
419                  * If we have to reload gs, we must take care to
420                  * preserve our gs base.
421                  */
422                 local_irq_save(flags);
423                 load_gs(vmx->host_state.gs_sel);
424 #ifdef CONFIG_X86_64
425                 wrmsrl(MSR_GS_BASE, vmcs_readl(HOST_GS_BASE));
426 #endif
427                 local_irq_restore(flags);
428         }
429         reload_tss();
430         save_msrs(vmx->guest_msrs, vmx->save_nmsrs);
431         load_msrs(vmx->host_msrs, vmx->save_nmsrs);
432         if (msr_efer_need_save_restore(vmx))
433                 load_msrs(vmx->host_msrs + vmx->msr_offset_efer, 1);
434 }
435
436 /*
437  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
438  * vcpu mutex is already taken.
439  */
440 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
441 {
442         struct vcpu_vmx *vmx = to_vmx(vcpu);
443         u64 phys_addr = __pa(vmx->vmcs);
444         u64 tsc_this, delta;
445
446         if (vcpu->cpu != cpu) {
447                 vcpu_clear(vmx);
448                 kvm_migrate_apic_timer(vcpu);
449         }
450
451         if (per_cpu(current_vmcs, cpu) != vmx->vmcs) {
452                 u8 error;
453
454                 per_cpu(current_vmcs, cpu) = vmx->vmcs;
455                 asm volatile (ASM_VMX_VMPTRLD_RAX "; setna %0"
456                               : "=g"(error) : "a"(&phys_addr), "m"(phys_addr)
457                               : "cc");
458                 if (error)
459                         printk(KERN_ERR "kvm: vmptrld %p/%llx fail\n",
460                                vmx->vmcs, phys_addr);
461         }
462
463         if (vcpu->cpu != cpu) {
464                 struct descriptor_table dt;
465                 unsigned long sysenter_esp;
466
467                 vcpu->cpu = cpu;
468                 /*
469                  * Linux uses per-cpu TSS and GDT, so set these when switching
470                  * processors.
471                  */
472                 vmcs_writel(HOST_TR_BASE, read_tr_base()); /* 22.2.4 */
473                 get_gdt(&dt);
474                 vmcs_writel(HOST_GDTR_BASE, dt.base);   /* 22.2.4 */
475
476                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
477                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
478
479                 /*
480                  * Make sure the time stamp counter is monotonous.
481                  */
482                 rdtscll(tsc_this);
483                 delta = vcpu->host_tsc - tsc_this;
484                 vmcs_write64(TSC_OFFSET, vmcs_read64(TSC_OFFSET) + delta);
485         }
486 }
487
488 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
489 {
490         vmx_load_host_state(to_vmx(vcpu));
491         kvm_put_guest_fpu(vcpu);
492 }
493
494 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
495 {
496         if (vcpu->fpu_active)
497                 return;
498         vcpu->fpu_active = 1;
499         vmcs_clear_bits(GUEST_CR0, X86_CR0_TS);
500         if (vcpu->cr0 & X86_CR0_TS)
501                 vmcs_set_bits(GUEST_CR0, X86_CR0_TS);
502         update_exception_bitmap(vcpu);
503 }
504
505 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
506 {
507         if (!vcpu->fpu_active)
508                 return;
509         vcpu->fpu_active = 0;
510         vmcs_set_bits(GUEST_CR0, X86_CR0_TS);
511         update_exception_bitmap(vcpu);
512 }
513
514 static void vmx_vcpu_decache(struct kvm_vcpu *vcpu)
515 {
516         vcpu_clear(to_vmx(vcpu));
517 }
518
519 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
520 {
521         return vmcs_readl(GUEST_RFLAGS);
522 }
523
524 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
525 {
526         vmcs_writel(GUEST_RFLAGS, rflags);
527 }
528
529 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
530 {
531         unsigned long rip;
532         u32 interruptibility;
533
534         rip = vmcs_readl(GUEST_RIP);
535         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
536         vmcs_writel(GUEST_RIP, rip);
537
538         /*
539          * We emulated an instruction, so temporary interrupt blocking
540          * should be removed, if set.
541          */
542         interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
543         if (interruptibility & 3)
544                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
545                              interruptibility & ~3);
546         vcpu->interrupt_window_open = 1;
547 }
548
549 static void vmx_inject_gp(struct kvm_vcpu *vcpu, unsigned error_code)
550 {
551         printk(KERN_DEBUG "inject_general_protection: rip 0x%lx\n",
552                vmcs_readl(GUEST_RIP));
553         vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
554         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
555                      GP_VECTOR |
556                      INTR_TYPE_EXCEPTION |
557                      INTR_INFO_DELIEVER_CODE_MASK |
558                      INTR_INFO_VALID_MASK);
559 }
560
561 /*
562  * Swap MSR entry in host/guest MSR entry array.
563  */
564 #ifdef CONFIG_X86_64
565 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
566 {
567         struct kvm_msr_entry tmp;
568
569         tmp = vmx->guest_msrs[to];
570         vmx->guest_msrs[to] = vmx->guest_msrs[from];
571         vmx->guest_msrs[from] = tmp;
572         tmp = vmx->host_msrs[to];
573         vmx->host_msrs[to] = vmx->host_msrs[from];
574         vmx->host_msrs[from] = tmp;
575 }
576 #endif
577
578 /*
579  * Set up the vmcs to automatically save and restore system
580  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
581  * mode, as fiddling with msrs is very expensive.
582  */
583 static void setup_msrs(struct vcpu_vmx *vmx)
584 {
585         int save_nmsrs;
586
587         save_nmsrs = 0;
588 #ifdef CONFIG_X86_64
589         if (is_long_mode(&vmx->vcpu)) {
590                 int index;
591
592                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
593                 if (index >= 0)
594                         move_msr_up(vmx, index, save_nmsrs++);
595                 index = __find_msr_index(vmx, MSR_LSTAR);
596                 if (index >= 0)
597                         move_msr_up(vmx, index, save_nmsrs++);
598                 index = __find_msr_index(vmx, MSR_CSTAR);
599                 if (index >= 0)
600                         move_msr_up(vmx, index, save_nmsrs++);
601                 index = __find_msr_index(vmx, MSR_KERNEL_GS_BASE);
602                 if (index >= 0)
603                         move_msr_up(vmx, index, save_nmsrs++);
604                 /*
605                  * MSR_K6_STAR is only needed on long mode guests, and only
606                  * if efer.sce is enabled.
607                  */
608                 index = __find_msr_index(vmx, MSR_K6_STAR);
609                 if ((index >= 0) && (vmx->vcpu.shadow_efer & EFER_SCE))
610                         move_msr_up(vmx, index, save_nmsrs++);
611         }
612 #endif
613         vmx->save_nmsrs = save_nmsrs;
614
615 #ifdef CONFIG_X86_64
616         vmx->msr_offset_kernel_gs_base =
617                 __find_msr_index(vmx, MSR_KERNEL_GS_BASE);
618 #endif
619         vmx->msr_offset_efer = __find_msr_index(vmx, MSR_EFER);
620 }
621
622 /*
623  * reads and returns guest's timestamp counter "register"
624  * guest_tsc = host_tsc + tsc_offset    -- 21.3
625  */
626 static u64 guest_read_tsc(void)
627 {
628         u64 host_tsc, tsc_offset;
629
630         rdtscll(host_tsc);
631         tsc_offset = vmcs_read64(TSC_OFFSET);
632         return host_tsc + tsc_offset;
633 }
634
635 /*
636  * writes 'guest_tsc' into guest's timestamp counter "register"
637  * guest_tsc = host_tsc + tsc_offset ==> tsc_offset = guest_tsc - host_tsc
638  */
639 static void guest_write_tsc(u64 guest_tsc)
640 {
641         u64 host_tsc;
642
643         rdtscll(host_tsc);
644         vmcs_write64(TSC_OFFSET, guest_tsc - host_tsc);
645 }
646
647 /*
648  * Reads an msr value (of 'msr_index') into 'pdata'.
649  * Returns 0 on success, non-0 otherwise.
650  * Assumes vcpu_load() was already called.
651  */
652 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
653 {
654         u64 data;
655         struct kvm_msr_entry *msr;
656
657         if (!pdata) {
658                 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
659                 return -EINVAL;
660         }
661
662         switch (msr_index) {
663 #ifdef CONFIG_X86_64
664         case MSR_FS_BASE:
665                 data = vmcs_readl(GUEST_FS_BASE);
666                 break;
667         case MSR_GS_BASE:
668                 data = vmcs_readl(GUEST_GS_BASE);
669                 break;
670         case MSR_EFER:
671                 return kvm_get_msr_common(vcpu, msr_index, pdata);
672 #endif
673         case MSR_IA32_TIME_STAMP_COUNTER:
674                 data = guest_read_tsc();
675                 break;
676         case MSR_IA32_SYSENTER_CS:
677                 data = vmcs_read32(GUEST_SYSENTER_CS);
678                 break;
679         case MSR_IA32_SYSENTER_EIP:
680                 data = vmcs_readl(GUEST_SYSENTER_EIP);
681                 break;
682         case MSR_IA32_SYSENTER_ESP:
683                 data = vmcs_readl(GUEST_SYSENTER_ESP);
684                 break;
685         default:
686                 msr = find_msr_entry(to_vmx(vcpu), msr_index);
687                 if (msr) {
688                         data = msr->data;
689                         break;
690                 }
691                 return kvm_get_msr_common(vcpu, msr_index, pdata);
692         }
693
694         *pdata = data;
695         return 0;
696 }
697
698 /*
699  * Writes msr value into into the appropriate "register".
700  * Returns 0 on success, non-0 otherwise.
701  * Assumes vcpu_load() was already called.
702  */
703 static int vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
704 {
705         struct vcpu_vmx *vmx = to_vmx(vcpu);
706         struct kvm_msr_entry *msr;
707         int ret = 0;
708
709         switch (msr_index) {
710 #ifdef CONFIG_X86_64
711         case MSR_EFER:
712                 ret = kvm_set_msr_common(vcpu, msr_index, data);
713                 if (vmx->host_state.loaded)
714                         load_transition_efer(vmx);
715                 break;
716         case MSR_FS_BASE:
717                 vmcs_writel(GUEST_FS_BASE, data);
718                 break;
719         case MSR_GS_BASE:
720                 vmcs_writel(GUEST_GS_BASE, data);
721                 break;
722 #endif
723         case MSR_IA32_SYSENTER_CS:
724                 vmcs_write32(GUEST_SYSENTER_CS, data);
725                 break;
726         case MSR_IA32_SYSENTER_EIP:
727                 vmcs_writel(GUEST_SYSENTER_EIP, data);
728                 break;
729         case MSR_IA32_SYSENTER_ESP:
730                 vmcs_writel(GUEST_SYSENTER_ESP, data);
731                 break;
732         case MSR_IA32_TIME_STAMP_COUNTER:
733                 guest_write_tsc(data);
734                 break;
735         default:
736                 msr = find_msr_entry(vmx, msr_index);
737                 if (msr) {
738                         msr->data = data;
739                         if (vmx->host_state.loaded)
740                                 load_msrs(vmx->guest_msrs, vmx->save_nmsrs);
741                         break;
742                 }
743                 ret = kvm_set_msr_common(vcpu, msr_index, data);
744         }
745
746         return ret;
747 }
748
749 /*
750  * Sync the rsp and rip registers into the vcpu structure.  This allows
751  * registers to be accessed by indexing vcpu->regs.
752  */
753 static void vcpu_load_rsp_rip(struct kvm_vcpu *vcpu)
754 {
755         vcpu->regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
756         vcpu->rip = vmcs_readl(GUEST_RIP);
757 }
758
759 /*
760  * Syncs rsp and rip back into the vmcs.  Should be called after possible
761  * modification.
762  */
763 static void vcpu_put_rsp_rip(struct kvm_vcpu *vcpu)
764 {
765         vmcs_writel(GUEST_RSP, vcpu->regs[VCPU_REGS_RSP]);
766         vmcs_writel(GUEST_RIP, vcpu->rip);
767 }
768
769 static int set_guest_debug(struct kvm_vcpu *vcpu, struct kvm_debug_guest *dbg)
770 {
771         unsigned long dr7 = 0x400;
772         int old_singlestep;
773
774         old_singlestep = vcpu->guest_debug.singlestep;
775
776         vcpu->guest_debug.enabled = dbg->enabled;
777         if (vcpu->guest_debug.enabled) {
778                 int i;
779
780                 dr7 |= 0x200;  /* exact */
781                 for (i = 0; i < 4; ++i) {
782                         if (!dbg->breakpoints[i].enabled)
783                                 continue;
784                         vcpu->guest_debug.bp[i] = dbg->breakpoints[i].address;
785                         dr7 |= 2 << (i*2);    /* global enable */
786                         dr7 |= 0 << (i*4+16); /* execution breakpoint */
787                 }
788
789                 vcpu->guest_debug.singlestep = dbg->singlestep;
790         } else
791                 vcpu->guest_debug.singlestep = 0;
792
793         if (old_singlestep && !vcpu->guest_debug.singlestep) {
794                 unsigned long flags;
795
796                 flags = vmcs_readl(GUEST_RFLAGS);
797                 flags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
798                 vmcs_writel(GUEST_RFLAGS, flags);
799         }
800
801         update_exception_bitmap(vcpu);
802         vmcs_writel(GUEST_DR7, dr7);
803
804         return 0;
805 }
806
807 static int vmx_get_irq(struct kvm_vcpu *vcpu)
808 {
809         u32 idtv_info_field;
810
811         idtv_info_field = vmcs_read32(IDT_VECTORING_INFO_FIELD);
812         if (idtv_info_field & INTR_INFO_VALID_MASK) {
813                 if (is_external_interrupt(idtv_info_field))
814                         return idtv_info_field & VECTORING_INFO_VECTOR_MASK;
815                 else
816                         printk("pending exception: not handled yet\n");
817         }
818         return -1;
819 }
820
821 static __init int cpu_has_kvm_support(void)
822 {
823         unsigned long ecx = cpuid_ecx(1);
824         return test_bit(5, &ecx); /* CPUID.1:ECX.VMX[bit 5] -> VT */
825 }
826
827 static __init int vmx_disabled_by_bios(void)
828 {
829         u64 msr;
830
831         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
832         return (msr & (MSR_IA32_FEATURE_CONTROL_LOCKED |
833                        MSR_IA32_FEATURE_CONTROL_VMXON_ENABLED))
834             == MSR_IA32_FEATURE_CONTROL_LOCKED;
835         /* locked but not enabled */
836 }
837
838 static void hardware_enable(void *garbage)
839 {
840         int cpu = raw_smp_processor_id();
841         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
842         u64 old;
843
844         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
845         if ((old & (MSR_IA32_FEATURE_CONTROL_LOCKED |
846                     MSR_IA32_FEATURE_CONTROL_VMXON_ENABLED))
847             != (MSR_IA32_FEATURE_CONTROL_LOCKED |
848                 MSR_IA32_FEATURE_CONTROL_VMXON_ENABLED))
849                 /* enable and lock */
850                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old |
851                        MSR_IA32_FEATURE_CONTROL_LOCKED |
852                        MSR_IA32_FEATURE_CONTROL_VMXON_ENABLED);
853         write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
854         asm volatile (ASM_VMX_VMXON_RAX : : "a"(&phys_addr), "m"(phys_addr)
855                       : "memory", "cc");
856 }
857
858 static void hardware_disable(void *garbage)
859 {
860         asm volatile (ASM_VMX_VMXOFF : : : "cc");
861 }
862
863 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
864                                       u32 msr, u32* result)
865 {
866         u32 vmx_msr_low, vmx_msr_high;
867         u32 ctl = ctl_min | ctl_opt;
868
869         rdmsr(msr, vmx_msr_low, vmx_msr_high);
870
871         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
872         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
873
874         /* Ensure minimum (required) set of control bits are supported. */
875         if (ctl_min & ~ctl)
876                 return -EIO;
877
878         *result = ctl;
879         return 0;
880 }
881
882 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
883 {
884         u32 vmx_msr_low, vmx_msr_high;
885         u32 min, opt;
886         u32 _pin_based_exec_control = 0;
887         u32 _cpu_based_exec_control = 0;
888         u32 _vmexit_control = 0;
889         u32 _vmentry_control = 0;
890
891         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
892         opt = 0;
893         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
894                                 &_pin_based_exec_control) < 0)
895                 return -EIO;
896
897         min = CPU_BASED_HLT_EXITING |
898 #ifdef CONFIG_X86_64
899               CPU_BASED_CR8_LOAD_EXITING |
900               CPU_BASED_CR8_STORE_EXITING |
901 #endif
902               CPU_BASED_USE_IO_BITMAPS |
903               CPU_BASED_MOV_DR_EXITING |
904               CPU_BASED_USE_TSC_OFFSETING;
905 #ifdef CONFIG_X86_64
906         opt = CPU_BASED_TPR_SHADOW;
907 #else
908         opt = 0;
909 #endif
910         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
911                                 &_cpu_based_exec_control) < 0)
912                 return -EIO;
913 #ifdef CONFIG_X86_64
914         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
915                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
916                                            ~CPU_BASED_CR8_STORE_EXITING;
917 #endif
918
919         min = 0;
920 #ifdef CONFIG_X86_64
921         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
922 #endif
923         opt = 0;
924         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
925                                 &_vmexit_control) < 0)
926                 return -EIO;
927
928         min = opt = 0;
929         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
930                                 &_vmentry_control) < 0)
931                 return -EIO;
932
933         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
934
935         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
936         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
937                 return -EIO;
938
939 #ifdef CONFIG_X86_64
940         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
941         if (vmx_msr_high & (1u<<16))
942                 return -EIO;
943 #endif
944
945         /* Require Write-Back (WB) memory type for VMCS accesses. */
946         if (((vmx_msr_high >> 18) & 15) != 6)
947                 return -EIO;
948
949         vmcs_conf->size = vmx_msr_high & 0x1fff;
950         vmcs_conf->order = get_order(vmcs_config.size);
951         vmcs_conf->revision_id = vmx_msr_low;
952
953         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
954         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
955         vmcs_conf->vmexit_ctrl         = _vmexit_control;
956         vmcs_conf->vmentry_ctrl        = _vmentry_control;
957
958         return 0;
959 }
960
961 static struct vmcs *alloc_vmcs_cpu(int cpu)
962 {
963         int node = cpu_to_node(cpu);
964         struct page *pages;
965         struct vmcs *vmcs;
966
967         pages = alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
968         if (!pages)
969                 return NULL;
970         vmcs = page_address(pages);
971         memset(vmcs, 0, vmcs_config.size);
972         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
973         return vmcs;
974 }
975
976 static struct vmcs *alloc_vmcs(void)
977 {
978         return alloc_vmcs_cpu(raw_smp_processor_id());
979 }
980
981 static void free_vmcs(struct vmcs *vmcs)
982 {
983         free_pages((unsigned long)vmcs, vmcs_config.order);
984 }
985
986 static void free_kvm_area(void)
987 {
988         int cpu;
989
990         for_each_online_cpu(cpu)
991                 free_vmcs(per_cpu(vmxarea, cpu));
992 }
993
994 static __init int alloc_kvm_area(void)
995 {
996         int cpu;
997
998         for_each_online_cpu(cpu) {
999                 struct vmcs *vmcs;
1000
1001                 vmcs = alloc_vmcs_cpu(cpu);
1002                 if (!vmcs) {
1003                         free_kvm_area();
1004                         return -ENOMEM;
1005                 }
1006
1007                 per_cpu(vmxarea, cpu) = vmcs;
1008         }
1009         return 0;
1010 }
1011
1012 static __init int hardware_setup(void)
1013 {
1014         if (setup_vmcs_config(&vmcs_config) < 0)
1015                 return -EIO;
1016         return alloc_kvm_area();
1017 }
1018
1019 static __exit void hardware_unsetup(void)
1020 {
1021         free_kvm_area();
1022 }
1023
1024 static void fix_pmode_dataseg(int seg, struct kvm_save_segment *save)
1025 {
1026         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1027
1028         if (vmcs_readl(sf->base) == save->base && (save->base & AR_S_MASK)) {
1029                 vmcs_write16(sf->selector, save->selector);
1030                 vmcs_writel(sf->base, save->base);
1031                 vmcs_write32(sf->limit, save->limit);
1032                 vmcs_write32(sf->ar_bytes, save->ar);
1033         } else {
1034                 u32 dpl = (vmcs_read16(sf->selector) & SELECTOR_RPL_MASK)
1035                         << AR_DPL_SHIFT;
1036                 vmcs_write32(sf->ar_bytes, 0x93 | dpl);
1037         }
1038 }
1039
1040 static void enter_pmode(struct kvm_vcpu *vcpu)
1041 {
1042         unsigned long flags;
1043
1044         vcpu->rmode.active = 0;
1045
1046         vmcs_writel(GUEST_TR_BASE, vcpu->rmode.tr.base);
1047         vmcs_write32(GUEST_TR_LIMIT, vcpu->rmode.tr.limit);
1048         vmcs_write32(GUEST_TR_AR_BYTES, vcpu->rmode.tr.ar);
1049
1050         flags = vmcs_readl(GUEST_RFLAGS);
1051         flags &= ~(IOPL_MASK | X86_EFLAGS_VM);
1052         flags |= (vcpu->rmode.save_iopl << IOPL_SHIFT);
1053         vmcs_writel(GUEST_RFLAGS, flags);
1054
1055         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
1056                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
1057
1058         update_exception_bitmap(vcpu);
1059
1060         fix_pmode_dataseg(VCPU_SREG_ES, &vcpu->rmode.es);
1061         fix_pmode_dataseg(VCPU_SREG_DS, &vcpu->rmode.ds);
1062         fix_pmode_dataseg(VCPU_SREG_GS, &vcpu->rmode.gs);
1063         fix_pmode_dataseg(VCPU_SREG_FS, &vcpu->rmode.fs);
1064
1065         vmcs_write16(GUEST_SS_SELECTOR, 0);
1066         vmcs_write32(GUEST_SS_AR_BYTES, 0x93);
1067
1068         vmcs_write16(GUEST_CS_SELECTOR,
1069                      vmcs_read16(GUEST_CS_SELECTOR) & ~SELECTOR_RPL_MASK);
1070         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
1071 }
1072
1073 static gva_t rmode_tss_base(struct kvm* kvm)
1074 {
1075         gfn_t base_gfn = kvm->memslots[0].base_gfn + kvm->memslots[0].npages - 3;
1076         return base_gfn << PAGE_SHIFT;
1077 }
1078
1079 static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
1080 {
1081         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1082
1083         save->selector = vmcs_read16(sf->selector);
1084         save->base = vmcs_readl(sf->base);
1085         save->limit = vmcs_read32(sf->limit);
1086         save->ar = vmcs_read32(sf->ar_bytes);
1087         vmcs_write16(sf->selector, vmcs_readl(sf->base) >> 4);
1088         vmcs_write32(sf->limit, 0xffff);
1089         vmcs_write32(sf->ar_bytes, 0xf3);
1090 }
1091
1092 static void enter_rmode(struct kvm_vcpu *vcpu)
1093 {
1094         unsigned long flags;
1095
1096         vcpu->rmode.active = 1;
1097
1098         vcpu->rmode.tr.base = vmcs_readl(GUEST_TR_BASE);
1099         vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
1100
1101         vcpu->rmode.tr.limit = vmcs_read32(GUEST_TR_LIMIT);
1102         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
1103
1104         vcpu->rmode.tr.ar = vmcs_read32(GUEST_TR_AR_BYTES);
1105         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
1106
1107         flags = vmcs_readl(GUEST_RFLAGS);
1108         vcpu->rmode.save_iopl = (flags & IOPL_MASK) >> IOPL_SHIFT;
1109
1110         flags |= IOPL_MASK | X86_EFLAGS_VM;
1111
1112         vmcs_writel(GUEST_RFLAGS, flags);
1113         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
1114         update_exception_bitmap(vcpu);
1115
1116         vmcs_write16(GUEST_SS_SELECTOR, vmcs_readl(GUEST_SS_BASE) >> 4);
1117         vmcs_write32(GUEST_SS_LIMIT, 0xffff);
1118         vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
1119
1120         vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
1121         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
1122         if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
1123                 vmcs_writel(GUEST_CS_BASE, 0xf0000);
1124         vmcs_write16(GUEST_CS_SELECTOR, vmcs_readl(GUEST_CS_BASE) >> 4);
1125
1126         fix_rmode_seg(VCPU_SREG_ES, &vcpu->rmode.es);
1127         fix_rmode_seg(VCPU_SREG_DS, &vcpu->rmode.ds);
1128         fix_rmode_seg(VCPU_SREG_GS, &vcpu->rmode.gs);
1129         fix_rmode_seg(VCPU_SREG_FS, &vcpu->rmode.fs);
1130
1131         init_rmode_tss(vcpu->kvm);
1132 }
1133
1134 #ifdef CONFIG_X86_64
1135
1136 static void enter_lmode(struct kvm_vcpu *vcpu)
1137 {
1138         u32 guest_tr_ar;
1139
1140         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
1141         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
1142                 printk(KERN_DEBUG "%s: tss fixup for long mode. \n",
1143                        __FUNCTION__);
1144                 vmcs_write32(GUEST_TR_AR_BYTES,
1145                              (guest_tr_ar & ~AR_TYPE_MASK)
1146                              | AR_TYPE_BUSY_64_TSS);
1147         }
1148
1149         vcpu->shadow_efer |= EFER_LMA;
1150
1151         find_msr_entry(to_vmx(vcpu), MSR_EFER)->data |= EFER_LMA | EFER_LME;
1152         vmcs_write32(VM_ENTRY_CONTROLS,
1153                      vmcs_read32(VM_ENTRY_CONTROLS)
1154                      | VM_ENTRY_IA32E_MODE);
1155 }
1156
1157 static void exit_lmode(struct kvm_vcpu *vcpu)
1158 {
1159         vcpu->shadow_efer &= ~EFER_LMA;
1160
1161         vmcs_write32(VM_ENTRY_CONTROLS,
1162                      vmcs_read32(VM_ENTRY_CONTROLS)
1163                      & ~VM_ENTRY_IA32E_MODE);
1164 }
1165
1166 #endif
1167
1168 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
1169 {
1170         vcpu->cr4 &= KVM_GUEST_CR4_MASK;
1171         vcpu->cr4 |= vmcs_readl(GUEST_CR4) & ~KVM_GUEST_CR4_MASK;
1172 }
1173
1174 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1175 {
1176         vmx_fpu_deactivate(vcpu);
1177
1178         if (vcpu->rmode.active && (cr0 & X86_CR0_PE))
1179                 enter_pmode(vcpu);
1180
1181         if (!vcpu->rmode.active && !(cr0 & X86_CR0_PE))
1182                 enter_rmode(vcpu);
1183
1184 #ifdef CONFIG_X86_64
1185         if (vcpu->shadow_efer & EFER_LME) {
1186                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
1187                         enter_lmode(vcpu);
1188                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
1189                         exit_lmode(vcpu);
1190         }
1191 #endif
1192
1193         vmcs_writel(CR0_READ_SHADOW, cr0);
1194         vmcs_writel(GUEST_CR0,
1195                     (cr0 & ~KVM_GUEST_CR0_MASK) | KVM_VM_CR0_ALWAYS_ON);
1196         vcpu->cr0 = cr0;
1197
1198         if (!(cr0 & X86_CR0_TS) || !(cr0 & X86_CR0_PE))
1199                 vmx_fpu_activate(vcpu);
1200 }
1201
1202 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1203 {
1204         vmcs_writel(GUEST_CR3, cr3);
1205         if (vcpu->cr0 & X86_CR0_PE)
1206                 vmx_fpu_deactivate(vcpu);
1207 }
1208
1209 static void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1210 {
1211         vmcs_writel(CR4_READ_SHADOW, cr4);
1212         vmcs_writel(GUEST_CR4, cr4 | (vcpu->rmode.active ?
1213                     KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON));
1214         vcpu->cr4 = cr4;
1215 }
1216
1217 #ifdef CONFIG_X86_64
1218
1219 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
1220 {
1221         struct vcpu_vmx *vmx = to_vmx(vcpu);
1222         struct kvm_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
1223
1224         vcpu->shadow_efer = efer;
1225         if (efer & EFER_LMA) {
1226                 vmcs_write32(VM_ENTRY_CONTROLS,
1227                                      vmcs_read32(VM_ENTRY_CONTROLS) |
1228                                      VM_ENTRY_IA32E_MODE);
1229                 msr->data = efer;
1230
1231         } else {
1232                 vmcs_write32(VM_ENTRY_CONTROLS,
1233                                      vmcs_read32(VM_ENTRY_CONTROLS) &
1234                                      ~VM_ENTRY_IA32E_MODE);
1235
1236                 msr->data = efer & ~EFER_LME;
1237         }
1238         setup_msrs(vmx);
1239 }
1240
1241 #endif
1242
1243 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1244 {
1245         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1246
1247         return vmcs_readl(sf->base);
1248 }
1249
1250 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1251                             struct kvm_segment *var, int seg)
1252 {
1253         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1254         u32 ar;
1255
1256         var->base = vmcs_readl(sf->base);
1257         var->limit = vmcs_read32(sf->limit);
1258         var->selector = vmcs_read16(sf->selector);
1259         ar = vmcs_read32(sf->ar_bytes);
1260         if (ar & AR_UNUSABLE_MASK)
1261                 ar = 0;
1262         var->type = ar & 15;
1263         var->s = (ar >> 4) & 1;
1264         var->dpl = (ar >> 5) & 3;
1265         var->present = (ar >> 7) & 1;
1266         var->avl = (ar >> 12) & 1;
1267         var->l = (ar >> 13) & 1;
1268         var->db = (ar >> 14) & 1;
1269         var->g = (ar >> 15) & 1;
1270         var->unusable = (ar >> 16) & 1;
1271 }
1272
1273 static u32 vmx_segment_access_rights(struct kvm_segment *var)
1274 {
1275         u32 ar;
1276
1277         if (var->unusable)
1278                 ar = 1 << 16;
1279         else {
1280                 ar = var->type & 15;
1281                 ar |= (var->s & 1) << 4;
1282                 ar |= (var->dpl & 3) << 5;
1283                 ar |= (var->present & 1) << 7;
1284                 ar |= (var->avl & 1) << 12;
1285                 ar |= (var->l & 1) << 13;
1286                 ar |= (var->db & 1) << 14;
1287                 ar |= (var->g & 1) << 15;
1288         }
1289         if (ar == 0) /* a 0 value means unusable */
1290                 ar = AR_UNUSABLE_MASK;
1291
1292         return ar;
1293 }
1294
1295 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1296                             struct kvm_segment *var, int seg)
1297 {
1298         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1299         u32 ar;
1300
1301         if (vcpu->rmode.active && seg == VCPU_SREG_TR) {
1302                 vcpu->rmode.tr.selector = var->selector;
1303                 vcpu->rmode.tr.base = var->base;
1304                 vcpu->rmode.tr.limit = var->limit;
1305                 vcpu->rmode.tr.ar = vmx_segment_access_rights(var);
1306                 return;
1307         }
1308         vmcs_writel(sf->base, var->base);
1309         vmcs_write32(sf->limit, var->limit);
1310         vmcs_write16(sf->selector, var->selector);
1311         if (vcpu->rmode.active && var->s) {
1312                 /*
1313                  * Hack real-mode segments into vm86 compatibility.
1314                  */
1315                 if (var->base == 0xffff0000 && var->selector == 0xf000)
1316                         vmcs_writel(sf->base, 0xf0000);
1317                 ar = 0xf3;
1318         } else
1319                 ar = vmx_segment_access_rights(var);
1320         vmcs_write32(sf->ar_bytes, ar);
1321 }
1322
1323 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
1324 {
1325         u32 ar = vmcs_read32(GUEST_CS_AR_BYTES);
1326
1327         *db = (ar >> 14) & 1;
1328         *l = (ar >> 13) & 1;
1329 }
1330
1331 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1332 {
1333         dt->limit = vmcs_read32(GUEST_IDTR_LIMIT);
1334         dt->base = vmcs_readl(GUEST_IDTR_BASE);
1335 }
1336
1337 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1338 {
1339         vmcs_write32(GUEST_IDTR_LIMIT, dt->limit);
1340         vmcs_writel(GUEST_IDTR_BASE, dt->base);
1341 }
1342
1343 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1344 {
1345         dt->limit = vmcs_read32(GUEST_GDTR_LIMIT);
1346         dt->base = vmcs_readl(GUEST_GDTR_BASE);
1347 }
1348
1349 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct descriptor_table *dt)
1350 {
1351         vmcs_write32(GUEST_GDTR_LIMIT, dt->limit);
1352         vmcs_writel(GUEST_GDTR_BASE, dt->base);
1353 }
1354
1355 static int init_rmode_tss(struct kvm* kvm)
1356 {
1357         struct page *p1, *p2, *p3;
1358         gfn_t fn = rmode_tss_base(kvm) >> PAGE_SHIFT;
1359         char *page;
1360
1361         p1 = gfn_to_page(kvm, fn++);
1362         p2 = gfn_to_page(kvm, fn++);
1363         p3 = gfn_to_page(kvm, fn);
1364
1365         if (!p1 || !p2 || !p3) {
1366                 kvm_printf(kvm,"%s: gfn_to_page failed\n", __FUNCTION__);
1367                 return 0;
1368         }
1369
1370         page = kmap_atomic(p1, KM_USER0);
1371         clear_page(page);
1372         *(u16*)(page + 0x66) = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
1373         kunmap_atomic(page, KM_USER0);
1374
1375         page = kmap_atomic(p2, KM_USER0);
1376         clear_page(page);
1377         kunmap_atomic(page, KM_USER0);
1378
1379         page = kmap_atomic(p3, KM_USER0);
1380         clear_page(page);
1381         *(page + RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1) = ~0;
1382         kunmap_atomic(page, KM_USER0);
1383
1384         return 1;
1385 }
1386
1387 static void seg_setup(int seg)
1388 {
1389         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1390
1391         vmcs_write16(sf->selector, 0);
1392         vmcs_writel(sf->base, 0);
1393         vmcs_write32(sf->limit, 0xffff);
1394         vmcs_write32(sf->ar_bytes, 0x93);
1395 }
1396
1397 /*
1398  * Sets up the vmcs for emulated real mode.
1399  */
1400 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
1401 {
1402         u32 host_sysenter_cs;
1403         u32 junk;
1404         unsigned long a;
1405         struct descriptor_table dt;
1406         int i;
1407         int ret = 0;
1408         unsigned long kvm_vmx_return;
1409         u64 msr;
1410         u32 exec_control;
1411
1412         if (!init_rmode_tss(vmx->vcpu.kvm)) {
1413                 ret = -ENOMEM;
1414                 goto out;
1415         }
1416
1417         vmx->vcpu.rmode.active = 0;
1418
1419         vmx->vcpu.regs[VCPU_REGS_RDX] = get_rdx_init_val();
1420         set_cr8(&vmx->vcpu, 0);
1421         msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
1422         if (vmx->vcpu.vcpu_id == 0)
1423                 msr |= MSR_IA32_APICBASE_BSP;
1424         kvm_set_apic_base(&vmx->vcpu, msr);
1425
1426         fx_init(&vmx->vcpu);
1427
1428         /*
1429          * GUEST_CS_BASE should really be 0xffff0000, but VT vm86 mode
1430          * insists on having GUEST_CS_BASE == GUEST_CS_SELECTOR << 4.  Sigh.
1431          */
1432         if (vmx->vcpu.vcpu_id == 0) {
1433                 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
1434                 vmcs_writel(GUEST_CS_BASE, 0x000f0000);
1435         } else {
1436                 vmcs_write16(GUEST_CS_SELECTOR, vmx->vcpu.sipi_vector << 8);
1437                 vmcs_writel(GUEST_CS_BASE, vmx->vcpu.sipi_vector << 12);
1438         }
1439         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
1440         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
1441
1442         seg_setup(VCPU_SREG_DS);
1443         seg_setup(VCPU_SREG_ES);
1444         seg_setup(VCPU_SREG_FS);
1445         seg_setup(VCPU_SREG_GS);
1446         seg_setup(VCPU_SREG_SS);
1447
1448         vmcs_write16(GUEST_TR_SELECTOR, 0);
1449         vmcs_writel(GUEST_TR_BASE, 0);
1450         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
1451         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
1452
1453         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
1454         vmcs_writel(GUEST_LDTR_BASE, 0);
1455         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
1456         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
1457
1458         vmcs_write32(GUEST_SYSENTER_CS, 0);
1459         vmcs_writel(GUEST_SYSENTER_ESP, 0);
1460         vmcs_writel(GUEST_SYSENTER_EIP, 0);
1461
1462         vmcs_writel(GUEST_RFLAGS, 0x02);
1463         if (vmx->vcpu.vcpu_id == 0)
1464                 vmcs_writel(GUEST_RIP, 0xfff0);
1465         else
1466                 vmcs_writel(GUEST_RIP, 0);
1467         vmcs_writel(GUEST_RSP, 0);
1468
1469         //todo: dr0 = dr1 = dr2 = dr3 = 0; dr6 = 0xffff0ff0
1470         vmcs_writel(GUEST_DR7, 0x400);
1471
1472         vmcs_writel(GUEST_GDTR_BASE, 0);
1473         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
1474
1475         vmcs_writel(GUEST_IDTR_BASE, 0);
1476         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
1477
1478         vmcs_write32(GUEST_ACTIVITY_STATE, 0);
1479         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
1480         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
1481
1482         /* I/O */
1483         vmcs_write64(IO_BITMAP_A, page_to_phys(vmx_io_bitmap_a));
1484         vmcs_write64(IO_BITMAP_B, page_to_phys(vmx_io_bitmap_b));
1485
1486         guest_write_tsc(0);
1487
1488         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
1489
1490         /* Special registers */
1491         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
1492
1493         /* Control */
1494         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
1495                 vmcs_config.pin_based_exec_ctrl);
1496
1497         exec_control = vmcs_config.cpu_based_exec_ctrl;
1498         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
1499                 exec_control &= ~CPU_BASED_TPR_SHADOW;
1500 #ifdef CONFIG_X86_64
1501                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
1502                                 CPU_BASED_CR8_LOAD_EXITING;
1503 #endif
1504         }
1505         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
1506
1507         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
1508         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
1509         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
1510
1511         vmcs_writel(HOST_CR0, read_cr0());  /* 22.2.3 */
1512         vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
1513         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
1514
1515         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
1516         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
1517         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
1518         vmcs_write16(HOST_FS_SELECTOR, read_fs());    /* 22.2.4 */
1519         vmcs_write16(HOST_GS_SELECTOR, read_gs());    /* 22.2.4 */
1520         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
1521 #ifdef CONFIG_X86_64
1522         rdmsrl(MSR_FS_BASE, a);
1523         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
1524         rdmsrl(MSR_GS_BASE, a);
1525         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
1526 #else
1527         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
1528         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
1529 #endif
1530
1531         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
1532
1533         get_idt(&dt);
1534         vmcs_writel(HOST_IDTR_BASE, dt.base);   /* 22.2.4 */
1535
1536         asm ("mov $.Lkvm_vmx_return, %0" : "=r"(kvm_vmx_return));
1537         vmcs_writel(HOST_RIP, kvm_vmx_return); /* 22.2.5 */
1538         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
1539         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
1540         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
1541
1542         rdmsr(MSR_IA32_SYSENTER_CS, host_sysenter_cs, junk);
1543         vmcs_write32(HOST_IA32_SYSENTER_CS, host_sysenter_cs);
1544         rdmsrl(MSR_IA32_SYSENTER_ESP, a);
1545         vmcs_writel(HOST_IA32_SYSENTER_ESP, a);   /* 22.2.3 */
1546         rdmsrl(MSR_IA32_SYSENTER_EIP, a);
1547         vmcs_writel(HOST_IA32_SYSENTER_EIP, a);   /* 22.2.3 */
1548
1549         for (i = 0; i < NR_VMX_MSR; ++i) {
1550                 u32 index = vmx_msr_index[i];
1551                 u32 data_low, data_high;
1552                 u64 data;
1553                 int j = vmx->nmsrs;
1554
1555                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
1556                         continue;
1557                 if (wrmsr_safe(index, data_low, data_high) < 0)
1558                         continue;
1559                 data = data_low | ((u64)data_high << 32);
1560                 vmx->host_msrs[j].index = index;
1561                 vmx->host_msrs[j].reserved = 0;
1562                 vmx->host_msrs[j].data = data;
1563                 vmx->guest_msrs[j] = vmx->host_msrs[j];
1564                 ++vmx->nmsrs;
1565         }
1566
1567         setup_msrs(vmx);
1568
1569         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
1570
1571         /* 22.2.1, 20.8.1 */
1572         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
1573
1574         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
1575
1576 #ifdef CONFIG_X86_64
1577         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
1578         if (vm_need_tpr_shadow(vmx->vcpu.kvm))
1579                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
1580                              page_to_phys(vmx->vcpu.apic->regs_page));
1581         vmcs_write32(TPR_THRESHOLD, 0);
1582 #endif
1583
1584         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
1585         vmcs_writel(CR4_GUEST_HOST_MASK, KVM_GUEST_CR4_MASK);
1586
1587         vmx->vcpu.cr0 = 0x60000010;
1588         vmx_set_cr0(&vmx->vcpu, vmx->vcpu.cr0); // enter rmode
1589         vmx_set_cr4(&vmx->vcpu, 0);
1590 #ifdef CONFIG_X86_64
1591         vmx_set_efer(&vmx->vcpu, 0);
1592 #endif
1593         vmx_fpu_activate(&vmx->vcpu);
1594         update_exception_bitmap(&vmx->vcpu);
1595
1596         return 0;
1597
1598 out:
1599         return ret;
1600 }
1601
1602 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu)
1603 {
1604         struct vcpu_vmx *vmx = to_vmx(vcpu);
1605
1606         vmx_vcpu_setup(vmx);
1607 }
1608
1609 static void inject_rmode_irq(struct kvm_vcpu *vcpu, int irq)
1610 {
1611         u16 ent[2];
1612         u16 cs;
1613         u16 ip;
1614         unsigned long flags;
1615         unsigned long ss_base = vmcs_readl(GUEST_SS_BASE);
1616         u16 sp =  vmcs_readl(GUEST_RSP);
1617         u32 ss_limit = vmcs_read32(GUEST_SS_LIMIT);
1618
1619         if (sp > ss_limit || sp < 6 ) {
1620                 vcpu_printf(vcpu, "%s: #SS, rsp 0x%lx ss 0x%lx limit 0x%x\n",
1621                             __FUNCTION__,
1622                             vmcs_readl(GUEST_RSP),
1623                             vmcs_readl(GUEST_SS_BASE),
1624                             vmcs_read32(GUEST_SS_LIMIT));
1625                 return;
1626         }
1627
1628         if (emulator_read_std(irq * sizeof(ent), &ent, sizeof(ent), vcpu) !=
1629                                                         X86EMUL_CONTINUE) {
1630                 vcpu_printf(vcpu, "%s: read guest err\n", __FUNCTION__);
1631                 return;
1632         }
1633
1634         flags =  vmcs_readl(GUEST_RFLAGS);
1635         cs =  vmcs_readl(GUEST_CS_BASE) >> 4;
1636         ip =  vmcs_readl(GUEST_RIP);
1637
1638
1639         if (emulator_write_emulated(ss_base + sp - 2, &flags, 2, vcpu) != X86EMUL_CONTINUE ||
1640             emulator_write_emulated(ss_base + sp - 4, &cs, 2, vcpu) != X86EMUL_CONTINUE ||
1641             emulator_write_emulated(ss_base + sp - 6, &ip, 2, vcpu) != X86EMUL_CONTINUE) {
1642                 vcpu_printf(vcpu, "%s: write guest err\n", __FUNCTION__);
1643                 return;
1644         }
1645
1646         vmcs_writel(GUEST_RFLAGS, flags &
1647                     ~( X86_EFLAGS_IF | X86_EFLAGS_AC | X86_EFLAGS_TF));
1648         vmcs_write16(GUEST_CS_SELECTOR, ent[1]) ;
1649         vmcs_writel(GUEST_CS_BASE, ent[1] << 4);
1650         vmcs_writel(GUEST_RIP, ent[0]);
1651         vmcs_writel(GUEST_RSP, (vmcs_readl(GUEST_RSP) & ~0xffff) | (sp - 6));
1652 }
1653
1654 static void vmx_inject_irq(struct kvm_vcpu *vcpu, int irq)
1655 {
1656         if (vcpu->rmode.active) {
1657                 inject_rmode_irq(vcpu, irq);
1658                 return;
1659         }
1660         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
1661                         irq | INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1662 }
1663
1664 static void kvm_do_inject_irq(struct kvm_vcpu *vcpu)
1665 {
1666         int word_index = __ffs(vcpu->irq_summary);
1667         int bit_index = __ffs(vcpu->irq_pending[word_index]);
1668         int irq = word_index * BITS_PER_LONG + bit_index;
1669
1670         clear_bit(bit_index, &vcpu->irq_pending[word_index]);
1671         if (!vcpu->irq_pending[word_index])
1672                 clear_bit(word_index, &vcpu->irq_summary);
1673         vmx_inject_irq(vcpu, irq);
1674 }
1675
1676
1677 static void do_interrupt_requests(struct kvm_vcpu *vcpu,
1678                                        struct kvm_run *kvm_run)
1679 {
1680         u32 cpu_based_vm_exec_control;
1681
1682         vcpu->interrupt_window_open =
1683                 ((vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
1684                  (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 3) == 0);
1685
1686         if (vcpu->interrupt_window_open &&
1687             vcpu->irq_summary &&
1688             !(vmcs_read32(VM_ENTRY_INTR_INFO_FIELD) & INTR_INFO_VALID_MASK))
1689                 /*
1690                  * If interrupts enabled, and not blocked by sti or mov ss. Good.
1691                  */
1692                 kvm_do_inject_irq(vcpu);
1693
1694         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
1695         if (!vcpu->interrupt_window_open &&
1696             (vcpu->irq_summary || kvm_run->request_interrupt_window))
1697                 /*
1698                  * Interrupts blocked.  Wait for unblock.
1699                  */
1700                 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
1701         else
1702                 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
1703         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
1704 }
1705
1706 static void kvm_guest_debug_pre(struct kvm_vcpu *vcpu)
1707 {
1708         struct kvm_guest_debug *dbg = &vcpu->guest_debug;
1709
1710         set_debugreg(dbg->bp[0], 0);
1711         set_debugreg(dbg->bp[1], 1);
1712         set_debugreg(dbg->bp[2], 2);
1713         set_debugreg(dbg->bp[3], 3);
1714
1715         if (dbg->singlestep) {
1716                 unsigned long flags;
1717
1718                 flags = vmcs_readl(GUEST_RFLAGS);
1719                 flags |= X86_EFLAGS_TF | X86_EFLAGS_RF;
1720                 vmcs_writel(GUEST_RFLAGS, flags);
1721         }
1722 }
1723
1724 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
1725                                   int vec, u32 err_code)
1726 {
1727         if (!vcpu->rmode.active)
1728                 return 0;
1729
1730         /*
1731          * Instruction with address size override prefix opcode 0x67
1732          * Cause the #SS fault with 0 error code in VM86 mode.
1733          */
1734         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0)
1735                 if (emulate_instruction(vcpu, NULL, 0, 0) == EMULATE_DONE)
1736                         return 1;
1737         return 0;
1738 }
1739
1740 static int handle_exception(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1741 {
1742         u32 intr_info, error_code;
1743         unsigned long cr2, rip;
1744         u32 vect_info;
1745         enum emulation_result er;
1746         int r;
1747
1748         vect_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
1749         intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
1750
1751         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
1752                                                 !is_page_fault(intr_info)) {
1753                 printk(KERN_ERR "%s: unexpected, vectoring info 0x%x "
1754                        "intr info 0x%x\n", __FUNCTION__, vect_info, intr_info);
1755         }
1756
1757         if (!irqchip_in_kernel(vcpu->kvm) && is_external_interrupt(vect_info)) {
1758                 int irq = vect_info & VECTORING_INFO_VECTOR_MASK;
1759                 set_bit(irq, vcpu->irq_pending);
1760                 set_bit(irq / BITS_PER_LONG, &vcpu->irq_summary);
1761         }
1762
1763         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == 0x200) { /* nmi */
1764                 asm ("int $2");
1765                 return 1;
1766         }
1767
1768         if (is_no_device(intr_info)) {
1769                 vmx_fpu_activate(vcpu);
1770                 return 1;
1771         }
1772
1773         error_code = 0;
1774         rip = vmcs_readl(GUEST_RIP);
1775         if (intr_info & INTR_INFO_DELIEVER_CODE_MASK)
1776                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
1777         if (is_page_fault(intr_info)) {
1778                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
1779
1780                 mutex_lock(&vcpu->kvm->lock);
1781                 r = kvm_mmu_page_fault(vcpu, cr2, error_code);
1782                 if (r < 0) {
1783                         mutex_unlock(&vcpu->kvm->lock);
1784                         return r;
1785                 }
1786                 if (!r) {
1787                         mutex_unlock(&vcpu->kvm->lock);
1788                         return 1;
1789                 }
1790
1791                 er = emulate_instruction(vcpu, kvm_run, cr2, error_code);
1792                 mutex_unlock(&vcpu->kvm->lock);
1793
1794                 switch (er) {
1795                 case EMULATE_DONE:
1796                         return 1;
1797                 case EMULATE_DO_MMIO:
1798                         ++vcpu->stat.mmio_exits;
1799                         return 0;
1800                  case EMULATE_FAIL:
1801                         kvm_report_emulation_failure(vcpu, "pagetable");
1802                         break;
1803                 default:
1804                         BUG();
1805                 }
1806         }
1807
1808         if (vcpu->rmode.active &&
1809             handle_rmode_exception(vcpu, intr_info & INTR_INFO_VECTOR_MASK,
1810                                                                 error_code)) {
1811                 if (vcpu->halt_request) {
1812                         vcpu->halt_request = 0;
1813                         return kvm_emulate_halt(vcpu);
1814                 }
1815                 return 1;
1816         }
1817
1818         if ((intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK)) == (INTR_TYPE_EXCEPTION | 1)) {
1819                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1820                 return 0;
1821         }
1822         kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
1823         kvm_run->ex.exception = intr_info & INTR_INFO_VECTOR_MASK;
1824         kvm_run->ex.error_code = error_code;
1825         return 0;
1826 }
1827
1828 static int handle_external_interrupt(struct kvm_vcpu *vcpu,
1829                                      struct kvm_run *kvm_run)
1830 {
1831         ++vcpu->stat.irq_exits;
1832         return 1;
1833 }
1834
1835 static int handle_triple_fault(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1836 {
1837         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
1838         return 0;
1839 }
1840
1841 static int handle_io(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1842 {
1843         unsigned long exit_qualification;
1844         int size, down, in, string, rep;
1845         unsigned port;
1846
1847         ++vcpu->stat.io_exits;
1848         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
1849         string = (exit_qualification & 16) != 0;
1850
1851         if (string) {
1852                 if (emulate_instruction(vcpu, kvm_run, 0, 0) == EMULATE_DO_MMIO)
1853                         return 0;
1854                 return 1;
1855         }
1856
1857         size = (exit_qualification & 7) + 1;
1858         in = (exit_qualification & 8) != 0;
1859         down = (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_DF) != 0;
1860         rep = (exit_qualification & 32) != 0;
1861         port = exit_qualification >> 16;
1862
1863         return kvm_emulate_pio(vcpu, kvm_run, in, size, port);
1864 }
1865
1866 static void
1867 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
1868 {
1869         /*
1870          * Patch in the VMCALL instruction:
1871          */
1872         hypercall[0] = 0x0f;
1873         hypercall[1] = 0x01;
1874         hypercall[2] = 0xc1;
1875         hypercall[3] = 0xc3;
1876 }
1877
1878 static int handle_cr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1879 {
1880         unsigned long exit_qualification;
1881         int cr;
1882         int reg;
1883
1884         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
1885         cr = exit_qualification & 15;
1886         reg = (exit_qualification >> 8) & 15;
1887         switch ((exit_qualification >> 4) & 3) {
1888         case 0: /* mov to cr */
1889                 switch (cr) {
1890                 case 0:
1891                         vcpu_load_rsp_rip(vcpu);
1892                         set_cr0(vcpu, vcpu->regs[reg]);
1893                         skip_emulated_instruction(vcpu);
1894                         return 1;
1895                 case 3:
1896                         vcpu_load_rsp_rip(vcpu);
1897                         set_cr3(vcpu, vcpu->regs[reg]);
1898                         skip_emulated_instruction(vcpu);
1899                         return 1;
1900                 case 4:
1901                         vcpu_load_rsp_rip(vcpu);
1902                         set_cr4(vcpu, vcpu->regs[reg]);
1903                         skip_emulated_instruction(vcpu);
1904                         return 1;
1905                 case 8:
1906                         vcpu_load_rsp_rip(vcpu);
1907                         set_cr8(vcpu, vcpu->regs[reg]);
1908                         skip_emulated_instruction(vcpu);
1909                         kvm_run->exit_reason = KVM_EXIT_SET_TPR;
1910                         return 0;
1911                 };
1912                 break;
1913         case 2: /* clts */
1914                 vcpu_load_rsp_rip(vcpu);
1915                 vmx_fpu_deactivate(vcpu);
1916                 vcpu->cr0 &= ~X86_CR0_TS;
1917                 vmcs_writel(CR0_READ_SHADOW, vcpu->cr0);
1918                 vmx_fpu_activate(vcpu);
1919                 skip_emulated_instruction(vcpu);
1920                 return 1;
1921         case 1: /*mov from cr*/
1922                 switch (cr) {
1923                 case 3:
1924                         vcpu_load_rsp_rip(vcpu);
1925                         vcpu->regs[reg] = vcpu->cr3;
1926                         vcpu_put_rsp_rip(vcpu);
1927                         skip_emulated_instruction(vcpu);
1928                         return 1;
1929                 case 8:
1930                         vcpu_load_rsp_rip(vcpu);
1931                         vcpu->regs[reg] = get_cr8(vcpu);
1932                         vcpu_put_rsp_rip(vcpu);
1933                         skip_emulated_instruction(vcpu);
1934                         return 1;
1935                 }
1936                 break;
1937         case 3: /* lmsw */
1938                 lmsw(vcpu, (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f);
1939
1940                 skip_emulated_instruction(vcpu);
1941                 return 1;
1942         default:
1943                 break;
1944         }
1945         kvm_run->exit_reason = 0;
1946         pr_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
1947                (int)(exit_qualification >> 4) & 3, cr);
1948         return 0;
1949 }
1950
1951 static int handle_dr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1952 {
1953         unsigned long exit_qualification;
1954         unsigned long val;
1955         int dr, reg;
1956
1957         /*
1958          * FIXME: this code assumes the host is debugging the guest.
1959          *        need to deal with guest debugging itself too.
1960          */
1961         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
1962         dr = exit_qualification & 7;
1963         reg = (exit_qualification >> 8) & 15;
1964         vcpu_load_rsp_rip(vcpu);
1965         if (exit_qualification & 16) {
1966                 /* mov from dr */
1967                 switch (dr) {
1968                 case 6:
1969                         val = 0xffff0ff0;
1970                         break;
1971                 case 7:
1972                         val = 0x400;
1973                         break;
1974                 default:
1975                         val = 0;
1976                 }
1977                 vcpu->regs[reg] = val;
1978         } else {
1979                 /* mov to dr */
1980         }
1981         vcpu_put_rsp_rip(vcpu);
1982         skip_emulated_instruction(vcpu);
1983         return 1;
1984 }
1985
1986 static int handle_cpuid(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1987 {
1988         kvm_emulate_cpuid(vcpu);
1989         return 1;
1990 }
1991
1992 static int handle_rdmsr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1993 {
1994         u32 ecx = vcpu->regs[VCPU_REGS_RCX];
1995         u64 data;
1996
1997         if (vmx_get_msr(vcpu, ecx, &data)) {
1998                 vmx_inject_gp(vcpu, 0);
1999                 return 1;
2000         }
2001
2002         /* FIXME: handling of bits 32:63 of rax, rdx */
2003         vcpu->regs[VCPU_REGS_RAX] = data & -1u;
2004         vcpu->regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
2005         skip_emulated_instruction(vcpu);
2006         return 1;
2007 }
2008
2009 static int handle_wrmsr(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2010 {
2011         u32 ecx = vcpu->regs[VCPU_REGS_RCX];
2012         u64 data = (vcpu->regs[VCPU_REGS_RAX] & -1u)
2013                 | ((u64)(vcpu->regs[VCPU_REGS_RDX] & -1u) << 32);
2014
2015         if (vmx_set_msr(vcpu, ecx, data) != 0) {
2016                 vmx_inject_gp(vcpu, 0);
2017                 return 1;
2018         }
2019
2020         skip_emulated_instruction(vcpu);
2021         return 1;
2022 }
2023
2024 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu,
2025                                       struct kvm_run *kvm_run)
2026 {
2027         return 1;
2028 }
2029
2030 static int handle_interrupt_window(struct kvm_vcpu *vcpu,
2031                                    struct kvm_run *kvm_run)
2032 {
2033         u32 cpu_based_vm_exec_control;
2034
2035         /* clear pending irq */
2036         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2037         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
2038         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
2039         /*
2040          * If the user space waits to inject interrupts, exit as soon as
2041          * possible
2042          */
2043         if (kvm_run->request_interrupt_window &&
2044             !vcpu->irq_summary) {
2045                 kvm_run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
2046                 ++vcpu->stat.irq_window_exits;
2047                 return 0;
2048         }
2049         return 1;
2050 }
2051
2052 static int handle_halt(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2053 {
2054         skip_emulated_instruction(vcpu);
2055         return kvm_emulate_halt(vcpu);
2056 }
2057
2058 static int handle_vmcall(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2059 {
2060         skip_emulated_instruction(vcpu);
2061         return kvm_hypercall(vcpu, kvm_run);
2062 }
2063
2064 /*
2065  * The exit handlers return 1 if the exit was handled fully and guest execution
2066  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
2067  * to be done to userspace and return 0.
2068  */
2069 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu,
2070                                       struct kvm_run *kvm_run) = {
2071         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
2072         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
2073         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
2074         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
2075         [EXIT_REASON_CR_ACCESS]               = handle_cr,
2076         [EXIT_REASON_DR_ACCESS]               = handle_dr,
2077         [EXIT_REASON_CPUID]                   = handle_cpuid,
2078         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
2079         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
2080         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
2081         [EXIT_REASON_HLT]                     = handle_halt,
2082         [EXIT_REASON_VMCALL]                  = handle_vmcall,
2083         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold
2084 };
2085
2086 static const int kvm_vmx_max_exit_handlers =
2087         ARRAY_SIZE(kvm_vmx_exit_handlers);
2088
2089 /*
2090  * The guest has exited.  See if we can fix it or if we need userspace
2091  * assistance.
2092  */
2093 static int kvm_handle_exit(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
2094 {
2095         u32 vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
2096         u32 exit_reason = vmcs_read32(VM_EXIT_REASON);
2097         struct vcpu_vmx *vmx = to_vmx(vcpu);
2098
2099         if (unlikely(vmx->fail)) {
2100                 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
2101                 kvm_run->fail_entry.hardware_entry_failure_reason
2102                         = vmcs_read32(VM_INSTRUCTION_ERROR);
2103                 return 0;
2104         }
2105
2106         if ( (vectoring_info & VECTORING_INFO_VALID_MASK) &&
2107                                 exit_reason != EXIT_REASON_EXCEPTION_NMI )
2108                 printk(KERN_WARNING "%s: unexpected, valid vectoring info and "
2109                        "exit reason is 0x%x\n", __FUNCTION__, exit_reason);
2110         if (exit_reason < kvm_vmx_max_exit_handlers
2111             && kvm_vmx_exit_handlers[exit_reason])
2112                 return kvm_vmx_exit_handlers[exit_reason](vcpu, kvm_run);
2113         else {
2114                 kvm_run->exit_reason = KVM_EXIT_UNKNOWN;
2115                 kvm_run->hw.hardware_exit_reason = exit_reason;
2116         }
2117         return 0;
2118 }
2119
2120 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
2121 {
2122 }
2123
2124 static void update_tpr_threshold(struct kvm_vcpu *vcpu)
2125 {
2126         int max_irr, tpr;
2127
2128         if (!vm_need_tpr_shadow(vcpu->kvm))
2129                 return;
2130
2131         if (!kvm_lapic_enabled(vcpu) ||
2132             ((max_irr = kvm_lapic_find_highest_irr(vcpu)) == -1)) {
2133                 vmcs_write32(TPR_THRESHOLD, 0);
2134                 return;
2135         }
2136
2137         tpr = (kvm_lapic_get_cr8(vcpu) & 0x0f) << 4;
2138         vmcs_write32(TPR_THRESHOLD, (max_irr > tpr) ? tpr >> 4 : max_irr >> 4);
2139 }
2140
2141 static void enable_irq_window(struct kvm_vcpu *vcpu)
2142 {
2143         u32 cpu_based_vm_exec_control;
2144
2145         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2146         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
2147         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
2148 }
2149
2150 static void vmx_intr_assist(struct kvm_vcpu *vcpu)
2151 {
2152         u32 idtv_info_field, intr_info_field;
2153         int has_ext_irq, interrupt_window_open;
2154         int vector;
2155
2156         kvm_inject_pending_timer_irqs(vcpu);
2157         update_tpr_threshold(vcpu);
2158
2159         has_ext_irq = kvm_cpu_has_interrupt(vcpu);
2160         intr_info_field = vmcs_read32(VM_ENTRY_INTR_INFO_FIELD);
2161         idtv_info_field = vmcs_read32(IDT_VECTORING_INFO_FIELD);
2162         if (intr_info_field & INTR_INFO_VALID_MASK) {
2163                 if (idtv_info_field & INTR_INFO_VALID_MASK) {
2164                         /* TODO: fault when IDT_Vectoring */
2165                         printk(KERN_ERR "Fault when IDT_Vectoring\n");
2166                 }
2167                 if (has_ext_irq)
2168                         enable_irq_window(vcpu);
2169                 return;
2170         }
2171         if (unlikely(idtv_info_field & INTR_INFO_VALID_MASK)) {
2172                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, idtv_info_field);
2173                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2174                                 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
2175
2176                 if (unlikely(idtv_info_field & INTR_INFO_DELIEVER_CODE_MASK))
2177                         vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
2178                                 vmcs_read32(IDT_VECTORING_ERROR_CODE));
2179                 if (unlikely(has_ext_irq))
2180                         enable_irq_window(vcpu);
2181                 return;
2182         }
2183         if (!has_ext_irq)
2184                 return;
2185         interrupt_window_open =
2186                 ((vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
2187                  (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 3) == 0);
2188         if (interrupt_window_open) {
2189                 vector = kvm_cpu_get_interrupt(vcpu);
2190                 vmx_inject_irq(vcpu, vector);
2191                 kvm_timer_intr_post(vcpu, vector);
2192         } else
2193                 enable_irq_window(vcpu);
2194 }
2195
2196 static void vmx_vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2197 {
2198         struct vcpu_vmx *vmx = to_vmx(vcpu);
2199
2200         /*
2201          * Loading guest fpu may have cleared host cr0.ts
2202          */
2203         vmcs_writel(HOST_CR0, read_cr0());
2204
2205         asm (
2206                 /* Store host registers */
2207 #ifdef CONFIG_X86_64
2208                 "push %%rax; push %%rbx; push %%rdx;"
2209                 "push %%rsi; push %%rdi; push %%rbp;"
2210                 "push %%r8;  push %%r9;  push %%r10; push %%r11;"
2211                 "push %%r12; push %%r13; push %%r14; push %%r15;"
2212                 "push %%rcx \n\t"
2213                 ASM_VMX_VMWRITE_RSP_RDX "\n\t"
2214 #else
2215                 "pusha; push %%ecx \n\t"
2216                 ASM_VMX_VMWRITE_RSP_RDX "\n\t"
2217 #endif
2218                 /* Check if vmlaunch of vmresume is needed */
2219                 "cmp $0, %1 \n\t"
2220                 /* Load guest registers.  Don't clobber flags. */
2221 #ifdef CONFIG_X86_64
2222                 "mov %c[cr2](%3), %%rax \n\t"
2223                 "mov %%rax, %%cr2 \n\t"
2224                 "mov %c[rax](%3), %%rax \n\t"
2225                 "mov %c[rbx](%3), %%rbx \n\t"
2226                 "mov %c[rdx](%3), %%rdx \n\t"
2227                 "mov %c[rsi](%3), %%rsi \n\t"
2228                 "mov %c[rdi](%3), %%rdi \n\t"
2229                 "mov %c[rbp](%3), %%rbp \n\t"
2230                 "mov %c[r8](%3),  %%r8  \n\t"
2231                 "mov %c[r9](%3),  %%r9  \n\t"
2232                 "mov %c[r10](%3), %%r10 \n\t"
2233                 "mov %c[r11](%3), %%r11 \n\t"
2234                 "mov %c[r12](%3), %%r12 \n\t"
2235                 "mov %c[r13](%3), %%r13 \n\t"
2236                 "mov %c[r14](%3), %%r14 \n\t"
2237                 "mov %c[r15](%3), %%r15 \n\t"
2238                 "mov %c[rcx](%3), %%rcx \n\t" /* kills %3 (rcx) */
2239 #else
2240                 "mov %c[cr2](%3), %%eax \n\t"
2241                 "mov %%eax,   %%cr2 \n\t"
2242                 "mov %c[rax](%3), %%eax \n\t"
2243                 "mov %c[rbx](%3), %%ebx \n\t"
2244                 "mov %c[rdx](%3), %%edx \n\t"
2245                 "mov %c[rsi](%3), %%esi \n\t"
2246                 "mov %c[rdi](%3), %%edi \n\t"
2247                 "mov %c[rbp](%3), %%ebp \n\t"
2248                 "mov %c[rcx](%3), %%ecx \n\t" /* kills %3 (ecx) */
2249 #endif
2250                 /* Enter guest mode */
2251                 "jne .Llaunched \n\t"
2252                 ASM_VMX_VMLAUNCH "\n\t"
2253                 "jmp .Lkvm_vmx_return \n\t"
2254                 ".Llaunched: " ASM_VMX_VMRESUME "\n\t"
2255                 ".Lkvm_vmx_return: "
2256                 /* Save guest registers, load host registers, keep flags */
2257 #ifdef CONFIG_X86_64
2258                 "xchg %3,     (%%rsp) \n\t"
2259                 "mov %%rax, %c[rax](%3) \n\t"
2260                 "mov %%rbx, %c[rbx](%3) \n\t"
2261                 "pushq (%%rsp); popq %c[rcx](%3) \n\t"
2262                 "mov %%rdx, %c[rdx](%3) \n\t"
2263                 "mov %%rsi, %c[rsi](%3) \n\t"
2264                 "mov %%rdi, %c[rdi](%3) \n\t"
2265                 "mov %%rbp, %c[rbp](%3) \n\t"
2266                 "mov %%r8,  %c[r8](%3) \n\t"
2267                 "mov %%r9,  %c[r9](%3) \n\t"
2268                 "mov %%r10, %c[r10](%3) \n\t"
2269                 "mov %%r11, %c[r11](%3) \n\t"
2270                 "mov %%r12, %c[r12](%3) \n\t"
2271                 "mov %%r13, %c[r13](%3) \n\t"
2272                 "mov %%r14, %c[r14](%3) \n\t"
2273                 "mov %%r15, %c[r15](%3) \n\t"
2274                 "mov %%cr2, %%rax   \n\t"
2275                 "mov %%rax, %c[cr2](%3) \n\t"
2276                 "mov (%%rsp), %3 \n\t"
2277
2278                 "pop  %%rcx; pop  %%r15; pop  %%r14; pop  %%r13; pop  %%r12;"
2279                 "pop  %%r11; pop  %%r10; pop  %%r9;  pop  %%r8;"
2280                 "pop  %%rbp; pop  %%rdi; pop  %%rsi;"
2281                 "pop  %%rdx; pop  %%rbx; pop  %%rax \n\t"
2282 #else
2283                 "xchg %3, (%%esp) \n\t"
2284                 "mov %%eax, %c[rax](%3) \n\t"
2285                 "mov %%ebx, %c[rbx](%3) \n\t"
2286                 "pushl (%%esp); popl %c[rcx](%3) \n\t"
2287                 "mov %%edx, %c[rdx](%3) \n\t"
2288                 "mov %%esi, %c[rsi](%3) \n\t"
2289                 "mov %%edi, %c[rdi](%3) \n\t"
2290                 "mov %%ebp, %c[rbp](%3) \n\t"
2291                 "mov %%cr2, %%eax  \n\t"
2292                 "mov %%eax, %c[cr2](%3) \n\t"
2293                 "mov (%%esp), %3 \n\t"
2294
2295                 "pop %%ecx; popa \n\t"
2296 #endif
2297                 "setbe %0 \n\t"
2298               : "=q" (vmx->fail)
2299               : "r"(vmx->launched), "d"((unsigned long)HOST_RSP),
2300                 "c"(vcpu),
2301                 [rax]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_RAX])),
2302                 [rbx]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_RBX])),
2303                 [rcx]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_RCX])),
2304                 [rdx]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_RDX])),
2305                 [rsi]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_RSI])),
2306                 [rdi]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_RDI])),
2307                 [rbp]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_RBP])),
2308 #ifdef CONFIG_X86_64
2309                 [r8 ]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R8 ])),
2310                 [r9 ]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R9 ])),
2311                 [r10]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R10])),
2312                 [r11]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R11])),
2313                 [r12]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R12])),
2314                 [r13]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R13])),
2315                 [r14]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R14])),
2316                 [r15]"i"(offsetof(struct kvm_vcpu, regs[VCPU_REGS_R15])),
2317 #endif
2318                 [cr2]"i"(offsetof(struct kvm_vcpu, cr2))
2319               : "cc", "memory" );
2320
2321         vcpu->interrupt_window_open = (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 3) == 0;
2322
2323         asm ("mov %0, %%ds; mov %0, %%es" : : "r"(__USER_DS));
2324         vmx->launched = 1;
2325 }
2326
2327 static void vmx_inject_page_fault(struct kvm_vcpu *vcpu,
2328                                   unsigned long addr,
2329                                   u32 err_code)
2330 {
2331         u32 vect_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
2332
2333         ++vcpu->stat.pf_guest;
2334
2335         if (is_page_fault(vect_info)) {
2336                 printk(KERN_DEBUG "inject_page_fault: "
2337                        "double fault 0x%lx @ 0x%lx\n",
2338                        addr, vmcs_readl(GUEST_RIP));
2339                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, 0);
2340                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2341                              DF_VECTOR |
2342                              INTR_TYPE_EXCEPTION |
2343                              INTR_INFO_DELIEVER_CODE_MASK |
2344                              INTR_INFO_VALID_MASK);
2345                 return;
2346         }
2347         vcpu->cr2 = addr;
2348         vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, err_code);
2349         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2350                      PF_VECTOR |
2351                      INTR_TYPE_EXCEPTION |
2352                      INTR_INFO_DELIEVER_CODE_MASK |
2353                      INTR_INFO_VALID_MASK);
2354
2355 }
2356
2357 static void vmx_free_vmcs(struct kvm_vcpu *vcpu)
2358 {
2359         struct vcpu_vmx *vmx = to_vmx(vcpu);
2360
2361         if (vmx->vmcs) {
2362                 on_each_cpu(__vcpu_clear, vmx, 0, 1);
2363                 free_vmcs(vmx->vmcs);
2364                 vmx->vmcs = NULL;
2365         }
2366 }
2367
2368 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
2369 {
2370         struct vcpu_vmx *vmx = to_vmx(vcpu);
2371
2372         vmx_free_vmcs(vcpu);
2373         kfree(vmx->host_msrs);
2374         kfree(vmx->guest_msrs);
2375         kvm_vcpu_uninit(vcpu);
2376         kmem_cache_free(kvm_vcpu_cache, vmx);
2377 }
2378
2379 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
2380 {
2381         int err;
2382         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
2383         int cpu;
2384
2385         if (!vmx)
2386                 return ERR_PTR(-ENOMEM);
2387
2388         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
2389         if (err)
2390                 goto free_vcpu;
2391
2392         if (irqchip_in_kernel(kvm)) {
2393                 err = kvm_create_lapic(&vmx->vcpu);
2394                 if (err < 0)
2395                         goto free_vcpu;
2396         }
2397
2398         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
2399         if (!vmx->guest_msrs) {
2400                 err = -ENOMEM;
2401                 goto uninit_vcpu;
2402         }
2403
2404         vmx->host_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
2405         if (!vmx->host_msrs)
2406                 goto free_guest_msrs;
2407
2408         vmx->vmcs = alloc_vmcs();
2409         if (!vmx->vmcs)
2410                 goto free_msrs;
2411
2412         vmcs_clear(vmx->vmcs);
2413
2414         cpu = get_cpu();
2415         vmx_vcpu_load(&vmx->vcpu, cpu);
2416         err = vmx_vcpu_setup(vmx);
2417         vmx_vcpu_put(&vmx->vcpu);
2418         put_cpu();
2419         if (err)
2420                 goto free_vmcs;
2421
2422         return &vmx->vcpu;
2423
2424 free_vmcs:
2425         free_vmcs(vmx->vmcs);
2426 free_msrs:
2427         kfree(vmx->host_msrs);
2428 free_guest_msrs:
2429         kfree(vmx->guest_msrs);
2430 uninit_vcpu:
2431         kvm_vcpu_uninit(&vmx->vcpu);
2432 free_vcpu:
2433         kmem_cache_free(kvm_vcpu_cache, vmx);
2434         return ERR_PTR(err);
2435 }
2436
2437 static void __init vmx_check_processor_compat(void *rtn)
2438 {
2439         struct vmcs_config vmcs_conf;
2440
2441         *(int *)rtn = 0;
2442         if (setup_vmcs_config(&vmcs_conf) < 0)
2443                 *(int *)rtn = -EIO;
2444         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
2445                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
2446                                 smp_processor_id());
2447                 *(int *)rtn = -EIO;
2448         }
2449 }
2450
2451 static struct kvm_x86_ops vmx_x86_ops = {
2452         .cpu_has_kvm_support = cpu_has_kvm_support,
2453         .disabled_by_bios = vmx_disabled_by_bios,
2454         .hardware_setup = hardware_setup,
2455         .hardware_unsetup = hardware_unsetup,
2456         .check_processor_compatibility = vmx_check_processor_compat,
2457         .hardware_enable = hardware_enable,
2458         .hardware_disable = hardware_disable,
2459
2460         .vcpu_create = vmx_create_vcpu,
2461         .vcpu_free = vmx_free_vcpu,
2462         .vcpu_reset = vmx_vcpu_reset,
2463
2464         .prepare_guest_switch = vmx_save_host_state,
2465         .vcpu_load = vmx_vcpu_load,
2466         .vcpu_put = vmx_vcpu_put,
2467         .vcpu_decache = vmx_vcpu_decache,
2468
2469         .set_guest_debug = set_guest_debug,
2470         .guest_debug_pre = kvm_guest_debug_pre,
2471         .get_msr = vmx_get_msr,
2472         .set_msr = vmx_set_msr,
2473         .get_segment_base = vmx_get_segment_base,
2474         .get_segment = vmx_get_segment,
2475         .set_segment = vmx_set_segment,
2476         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
2477         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
2478         .set_cr0 = vmx_set_cr0,
2479         .set_cr3 = vmx_set_cr3,
2480         .set_cr4 = vmx_set_cr4,
2481 #ifdef CONFIG_X86_64
2482         .set_efer = vmx_set_efer,
2483 #endif
2484         .get_idt = vmx_get_idt,
2485         .set_idt = vmx_set_idt,
2486         .get_gdt = vmx_get_gdt,
2487         .set_gdt = vmx_set_gdt,
2488         .cache_regs = vcpu_load_rsp_rip,
2489         .decache_regs = vcpu_put_rsp_rip,
2490         .get_rflags = vmx_get_rflags,
2491         .set_rflags = vmx_set_rflags,
2492
2493         .tlb_flush = vmx_flush_tlb,
2494         .inject_page_fault = vmx_inject_page_fault,
2495
2496         .inject_gp = vmx_inject_gp,
2497
2498         .run = vmx_vcpu_run,
2499         .handle_exit = kvm_handle_exit,
2500         .skip_emulated_instruction = skip_emulated_instruction,
2501         .patch_hypercall = vmx_patch_hypercall,
2502         .get_irq = vmx_get_irq,
2503         .set_irq = vmx_inject_irq,
2504         .inject_pending_irq = vmx_intr_assist,
2505         .inject_pending_vectors = do_interrupt_requests,
2506 };
2507
2508 static int __init vmx_init(void)
2509 {
2510         void *iova;
2511         int r;
2512
2513         vmx_io_bitmap_a = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
2514         if (!vmx_io_bitmap_a)
2515                 return -ENOMEM;
2516
2517         vmx_io_bitmap_b = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
2518         if (!vmx_io_bitmap_b) {
2519                 r = -ENOMEM;
2520                 goto out;
2521         }
2522
2523         /*
2524          * Allow direct access to the PC debug port (it is often used for I/O
2525          * delays, but the vmexits simply slow things down).
2526          */
2527         iova = kmap(vmx_io_bitmap_a);
2528         memset(iova, 0xff, PAGE_SIZE);
2529         clear_bit(0x80, iova);
2530         kunmap(vmx_io_bitmap_a);
2531
2532         iova = kmap(vmx_io_bitmap_b);
2533         memset(iova, 0xff, PAGE_SIZE);
2534         kunmap(vmx_io_bitmap_b);
2535
2536         r = kvm_init_x86(&vmx_x86_ops, sizeof(struct vcpu_vmx), THIS_MODULE);
2537         if (r)
2538                 goto out1;
2539
2540         return 0;
2541
2542 out1:
2543         __free_page(vmx_io_bitmap_b);
2544 out:
2545         __free_page(vmx_io_bitmap_a);
2546         return r;
2547 }
2548
2549 static void __exit vmx_exit(void)
2550 {
2551         __free_page(vmx_io_bitmap_b);
2552         __free_page(vmx_io_bitmap_a);
2553
2554         kvm_exit_x86();
2555 }
2556
2557 module_init(vmx_init)
2558 module_exit(vmx_exit)