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