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