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