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