]> err.no Git - linux-2.6/blob - drivers/kvm/x86.c
7237cb25f77d27030ffe3f160320a52346938a3b
[linux-2.6] / drivers / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  *
8  * Authors:
9  *   Avi Kivity   <avi@qumranet.com>
10  *   Yaniv Kamay  <yaniv@qumranet.com>
11  *
12  * This work is licensed under the terms of the GNU GPL, version 2.  See
13  * the COPYING file in the top-level directory.
14  *
15  */
16
17 #include "kvm.h"
18 #include "x86.h"
19 #include "x86_emulate.h"
20 #include "segment_descriptor.h"
21 #include "irq.h"
22
23 #include <linux/kvm.h>
24 #include <linux/fs.h>
25 #include <linux/vmalloc.h>
26 #include <linux/module.h>
27 #include <linux/mman.h>
28
29 #include <asm/uaccess.h>
30 #include <asm/msr.h>
31
32 #define MAX_IO_MSRS 256
33 #define CR0_RESERVED_BITS                                               \
34         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
35                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
36                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
37 #define CR4_RESERVED_BITS                                               \
38         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
39                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
40                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
41                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
42
43 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
44 #define EFER_RESERVED_BITS 0xfffffffffffff2fe
45
46 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
47 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
48
49 struct kvm_x86_ops *kvm_x86_ops;
50
51 struct kvm_stats_debugfs_item debugfs_entries[] = {
52         { "pf_fixed", VCPU_STAT(pf_fixed) },
53         { "pf_guest", VCPU_STAT(pf_guest) },
54         { "tlb_flush", VCPU_STAT(tlb_flush) },
55         { "invlpg", VCPU_STAT(invlpg) },
56         { "exits", VCPU_STAT(exits) },
57         { "io_exits", VCPU_STAT(io_exits) },
58         { "mmio_exits", VCPU_STAT(mmio_exits) },
59         { "signal_exits", VCPU_STAT(signal_exits) },
60         { "irq_window", VCPU_STAT(irq_window_exits) },
61         { "halt_exits", VCPU_STAT(halt_exits) },
62         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
63         { "request_irq", VCPU_STAT(request_irq_exits) },
64         { "irq_exits", VCPU_STAT(irq_exits) },
65         { "host_state_reload", VCPU_STAT(host_state_reload) },
66         { "efer_reload", VCPU_STAT(efer_reload) },
67         { "fpu_reload", VCPU_STAT(fpu_reload) },
68         { "insn_emulation", VCPU_STAT(insn_emulation) },
69         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
70         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
71         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
72         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
73         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
74         { "mmu_flooded", VM_STAT(mmu_flooded) },
75         { "mmu_recycled", VM_STAT(mmu_recycled) },
76         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
77         { NULL }
78 };
79
80
81 unsigned long segment_base(u16 selector)
82 {
83         struct descriptor_table gdt;
84         struct segment_descriptor *d;
85         unsigned long table_base;
86         unsigned long v;
87
88         if (selector == 0)
89                 return 0;
90
91         asm("sgdt %0" : "=m"(gdt));
92         table_base = gdt.base;
93
94         if (selector & 4) {           /* from ldt */
95                 u16 ldt_selector;
96
97                 asm("sldt %0" : "=g"(ldt_selector));
98                 table_base = segment_base(ldt_selector);
99         }
100         d = (struct segment_descriptor *)(table_base + (selector & ~7));
101         v = d->base_low | ((unsigned long)d->base_mid << 16) |
102                 ((unsigned long)d->base_high << 24);
103 #ifdef CONFIG_X86_64
104         if (d->system == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
105                 v |= ((unsigned long) \
106                       ((struct segment_descriptor_64 *)d)->base_higher) << 32;
107 #endif
108         return v;
109 }
110 EXPORT_SYMBOL_GPL(segment_base);
111
112 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
113 {
114         if (irqchip_in_kernel(vcpu->kvm))
115                 return vcpu->apic_base;
116         else
117                 return vcpu->apic_base;
118 }
119 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
120
121 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
122 {
123         /* TODO: reserve bits check */
124         if (irqchip_in_kernel(vcpu->kvm))
125                 kvm_lapic_set_base(vcpu, data);
126         else
127                 vcpu->apic_base = data;
128 }
129 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
130
131 static void inject_gp(struct kvm_vcpu *vcpu)
132 {
133         kvm_x86_ops->inject_gp(vcpu, 0);
134 }
135
136 /*
137  * Load the pae pdptrs.  Return true is they are all valid.
138  */
139 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
140 {
141         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
142         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
143         int i;
144         int ret;
145         u64 pdpte[ARRAY_SIZE(vcpu->pdptrs)];
146
147         mutex_lock(&vcpu->kvm->lock);
148         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
149                                   offset * sizeof(u64), sizeof(pdpte));
150         if (ret < 0) {
151                 ret = 0;
152                 goto out;
153         }
154         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
155                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
156                         ret = 0;
157                         goto out;
158                 }
159         }
160         ret = 1;
161
162         memcpy(vcpu->pdptrs, pdpte, sizeof(vcpu->pdptrs));
163 out:
164         mutex_unlock(&vcpu->kvm->lock);
165
166         return ret;
167 }
168
169 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
170 {
171         u64 pdpte[ARRAY_SIZE(vcpu->pdptrs)];
172         bool changed = true;
173         int r;
174
175         if (is_long_mode(vcpu) || !is_pae(vcpu))
176                 return false;
177
178         mutex_lock(&vcpu->kvm->lock);
179         r = kvm_read_guest(vcpu->kvm, vcpu->cr3 & ~31u, pdpte, sizeof(pdpte));
180         if (r < 0)
181                 goto out;
182         changed = memcmp(pdpte, vcpu->pdptrs, sizeof(pdpte)) != 0;
183 out:
184         mutex_unlock(&vcpu->kvm->lock);
185
186         return changed;
187 }
188
189 void set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
190 {
191         if (cr0 & CR0_RESERVED_BITS) {
192                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
193                        cr0, vcpu->cr0);
194                 inject_gp(vcpu);
195                 return;
196         }
197
198         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
199                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
200                 inject_gp(vcpu);
201                 return;
202         }
203
204         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
205                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
206                        "and a clear PE flag\n");
207                 inject_gp(vcpu);
208                 return;
209         }
210
211         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
212 #ifdef CONFIG_X86_64
213                 if ((vcpu->shadow_efer & EFER_LME)) {
214                         int cs_db, cs_l;
215
216                         if (!is_pae(vcpu)) {
217                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
218                                        "in long mode while PAE is disabled\n");
219                                 inject_gp(vcpu);
220                                 return;
221                         }
222                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
223                         if (cs_l) {
224                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
225                                        "in long mode while CS.L == 1\n");
226                                 inject_gp(vcpu);
227                                 return;
228
229                         }
230                 } else
231 #endif
232                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->cr3)) {
233                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
234                                "reserved bits\n");
235                         inject_gp(vcpu);
236                         return;
237                 }
238
239         }
240
241         kvm_x86_ops->set_cr0(vcpu, cr0);
242         vcpu->cr0 = cr0;
243
244         mutex_lock(&vcpu->kvm->lock);
245         kvm_mmu_reset_context(vcpu);
246         mutex_unlock(&vcpu->kvm->lock);
247         return;
248 }
249 EXPORT_SYMBOL_GPL(set_cr0);
250
251 void lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
252 {
253         set_cr0(vcpu, (vcpu->cr0 & ~0x0ful) | (msw & 0x0f));
254 }
255 EXPORT_SYMBOL_GPL(lmsw);
256
257 void set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
258 {
259         if (cr4 & CR4_RESERVED_BITS) {
260                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
261                 inject_gp(vcpu);
262                 return;
263         }
264
265         if (is_long_mode(vcpu)) {
266                 if (!(cr4 & X86_CR4_PAE)) {
267                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
268                                "in long mode\n");
269                         inject_gp(vcpu);
270                         return;
271                 }
272         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
273                    && !load_pdptrs(vcpu, vcpu->cr3)) {
274                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
275                 inject_gp(vcpu);
276                 return;
277         }
278
279         if (cr4 & X86_CR4_VMXE) {
280                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
281                 inject_gp(vcpu);
282                 return;
283         }
284         kvm_x86_ops->set_cr4(vcpu, cr4);
285         vcpu->cr4 = cr4;
286         mutex_lock(&vcpu->kvm->lock);
287         kvm_mmu_reset_context(vcpu);
288         mutex_unlock(&vcpu->kvm->lock);
289 }
290 EXPORT_SYMBOL_GPL(set_cr4);
291
292 void set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
293 {
294         if (cr3 == vcpu->cr3 && !pdptrs_changed(vcpu)) {
295                 kvm_mmu_flush_tlb(vcpu);
296                 return;
297         }
298
299         if (is_long_mode(vcpu)) {
300                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
301                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
302                         inject_gp(vcpu);
303                         return;
304                 }
305         } else {
306                 if (is_pae(vcpu)) {
307                         if (cr3 & CR3_PAE_RESERVED_BITS) {
308                                 printk(KERN_DEBUG
309                                        "set_cr3: #GP, reserved bits\n");
310                                 inject_gp(vcpu);
311                                 return;
312                         }
313                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
314                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
315                                        "reserved bits\n");
316                                 inject_gp(vcpu);
317                                 return;
318                         }
319                 }
320                 /*
321                  * We don't check reserved bits in nonpae mode, because
322                  * this isn't enforced, and VMware depends on this.
323                  */
324         }
325
326         mutex_lock(&vcpu->kvm->lock);
327         /*
328          * Does the new cr3 value map to physical memory? (Note, we
329          * catch an invalid cr3 even in real-mode, because it would
330          * cause trouble later on when we turn on paging anyway.)
331          *
332          * A real CPU would silently accept an invalid cr3 and would
333          * attempt to use it - with largely undefined (and often hard
334          * to debug) behavior on the guest side.
335          */
336         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
337                 inject_gp(vcpu);
338         else {
339                 vcpu->cr3 = cr3;
340                 vcpu->mmu.new_cr3(vcpu);
341         }
342         mutex_unlock(&vcpu->kvm->lock);
343 }
344 EXPORT_SYMBOL_GPL(set_cr3);
345
346 void set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
347 {
348         if (cr8 & CR8_RESERVED_BITS) {
349                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
350                 inject_gp(vcpu);
351                 return;
352         }
353         if (irqchip_in_kernel(vcpu->kvm))
354                 kvm_lapic_set_tpr(vcpu, cr8);
355         else
356                 vcpu->cr8 = cr8;
357 }
358 EXPORT_SYMBOL_GPL(set_cr8);
359
360 unsigned long get_cr8(struct kvm_vcpu *vcpu)
361 {
362         if (irqchip_in_kernel(vcpu->kvm))
363                 return kvm_lapic_get_cr8(vcpu);
364         else
365                 return vcpu->cr8;
366 }
367 EXPORT_SYMBOL_GPL(get_cr8);
368
369 /*
370  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
371  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
372  *
373  * This list is modified at module load time to reflect the
374  * capabilities of the host cpu.
375  */
376 static u32 msrs_to_save[] = {
377         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
378         MSR_K6_STAR,
379 #ifdef CONFIG_X86_64
380         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
381 #endif
382         MSR_IA32_TIME_STAMP_COUNTER,
383 };
384
385 static unsigned num_msrs_to_save;
386
387 static u32 emulated_msrs[] = {
388         MSR_IA32_MISC_ENABLE,
389 };
390
391 #ifdef CONFIG_X86_64
392
393 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
394 {
395         if (efer & EFER_RESERVED_BITS) {
396                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
397                        efer);
398                 inject_gp(vcpu);
399                 return;
400         }
401
402         if (is_paging(vcpu)
403             && (vcpu->shadow_efer & EFER_LME) != (efer & EFER_LME)) {
404                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
405                 inject_gp(vcpu);
406                 return;
407         }
408
409         kvm_x86_ops->set_efer(vcpu, efer);
410
411         efer &= ~EFER_LMA;
412         efer |= vcpu->shadow_efer & EFER_LMA;
413
414         vcpu->shadow_efer = efer;
415 }
416
417 #endif
418
419 /*
420  * Writes msr value into into the appropriate "register".
421  * Returns 0 on success, non-0 otherwise.
422  * Assumes vcpu_load() was already called.
423  */
424 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
425 {
426         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
427 }
428
429 /*
430  * Adapt set_msr() to msr_io()'s calling convention
431  */
432 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
433 {
434         return kvm_set_msr(vcpu, index, *data);
435 }
436
437
438 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
439 {
440         switch (msr) {
441 #ifdef CONFIG_X86_64
442         case MSR_EFER:
443                 set_efer(vcpu, data);
444                 break;
445 #endif
446         case MSR_IA32_MC0_STATUS:
447                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
448                        __FUNCTION__, data);
449                 break;
450         case MSR_IA32_MCG_STATUS:
451                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
452                         __FUNCTION__, data);
453                 break;
454         case MSR_IA32_UCODE_REV:
455         case MSR_IA32_UCODE_WRITE:
456         case 0x200 ... 0x2ff: /* MTRRs */
457                 break;
458         case MSR_IA32_APICBASE:
459                 kvm_set_apic_base(vcpu, data);
460                 break;
461         case MSR_IA32_MISC_ENABLE:
462                 vcpu->ia32_misc_enable_msr = data;
463                 break;
464         default:
465                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x\n", msr);
466                 return 1;
467         }
468         return 0;
469 }
470 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
471
472
473 /*
474  * Reads an msr value (of 'msr_index') into 'pdata'.
475  * Returns 0 on success, non-0 otherwise.
476  * Assumes vcpu_load() was already called.
477  */
478 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
479 {
480         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
481 }
482
483 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
484 {
485         u64 data;
486
487         switch (msr) {
488         case 0xc0010010: /* SYSCFG */
489         case 0xc0010015: /* HWCR */
490         case MSR_IA32_PLATFORM_ID:
491         case MSR_IA32_P5_MC_ADDR:
492         case MSR_IA32_P5_MC_TYPE:
493         case MSR_IA32_MC0_CTL:
494         case MSR_IA32_MCG_STATUS:
495         case MSR_IA32_MCG_CAP:
496         case MSR_IA32_MC0_MISC:
497         case MSR_IA32_MC0_MISC+4:
498         case MSR_IA32_MC0_MISC+8:
499         case MSR_IA32_MC0_MISC+12:
500         case MSR_IA32_MC0_MISC+16:
501         case MSR_IA32_UCODE_REV:
502         case MSR_IA32_PERF_STATUS:
503         case MSR_IA32_EBL_CR_POWERON:
504                 /* MTRR registers */
505         case 0xfe:
506         case 0x200 ... 0x2ff:
507                 data = 0;
508                 break;
509         case 0xcd: /* fsb frequency */
510                 data = 3;
511                 break;
512         case MSR_IA32_APICBASE:
513                 data = kvm_get_apic_base(vcpu);
514                 break;
515         case MSR_IA32_MISC_ENABLE:
516                 data = vcpu->ia32_misc_enable_msr;
517                 break;
518 #ifdef CONFIG_X86_64
519         case MSR_EFER:
520                 data = vcpu->shadow_efer;
521                 break;
522 #endif
523         default:
524                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
525                 return 1;
526         }
527         *pdata = data;
528         return 0;
529 }
530 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
531
532 /*
533  * Read or write a bunch of msrs. All parameters are kernel addresses.
534  *
535  * @return number of msrs set successfully.
536  */
537 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
538                     struct kvm_msr_entry *entries,
539                     int (*do_msr)(struct kvm_vcpu *vcpu,
540                                   unsigned index, u64 *data))
541 {
542         int i;
543
544         vcpu_load(vcpu);
545
546         for (i = 0; i < msrs->nmsrs; ++i)
547                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
548                         break;
549
550         vcpu_put(vcpu);
551
552         return i;
553 }
554
555 /*
556  * Read or write a bunch of msrs. Parameters are user addresses.
557  *
558  * @return number of msrs set successfully.
559  */
560 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
561                   int (*do_msr)(struct kvm_vcpu *vcpu,
562                                 unsigned index, u64 *data),
563                   int writeback)
564 {
565         struct kvm_msrs msrs;
566         struct kvm_msr_entry *entries;
567         int r, n;
568         unsigned size;
569
570         r = -EFAULT;
571         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
572                 goto out;
573
574         r = -E2BIG;
575         if (msrs.nmsrs >= MAX_IO_MSRS)
576                 goto out;
577
578         r = -ENOMEM;
579         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
580         entries = vmalloc(size);
581         if (!entries)
582                 goto out;
583
584         r = -EFAULT;
585         if (copy_from_user(entries, user_msrs->entries, size))
586                 goto out_free;
587
588         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
589         if (r < 0)
590                 goto out_free;
591
592         r = -EFAULT;
593         if (writeback && copy_to_user(user_msrs->entries, entries, size))
594                 goto out_free;
595
596         r = n;
597
598 out_free:
599         vfree(entries);
600 out:
601         return r;
602 }
603
604 /*
605  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
606  * cached on it.
607  */
608 void decache_vcpus_on_cpu(int cpu)
609 {
610         struct kvm *vm;
611         struct kvm_vcpu *vcpu;
612         int i;
613
614         spin_lock(&kvm_lock);
615         list_for_each_entry(vm, &vm_list, vm_list)
616                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
617                         vcpu = vm->vcpus[i];
618                         if (!vcpu)
619                                 continue;
620                         /*
621                          * If the vcpu is locked, then it is running on some
622                          * other cpu and therefore it is not cached on the
623                          * cpu in question.
624                          *
625                          * If it's not locked, check the last cpu it executed
626                          * on.
627                          */
628                         if (mutex_trylock(&vcpu->mutex)) {
629                                 if (vcpu->cpu == cpu) {
630                                         kvm_x86_ops->vcpu_decache(vcpu);
631                                         vcpu->cpu = -1;
632                                 }
633                                 mutex_unlock(&vcpu->mutex);
634                         }
635                 }
636         spin_unlock(&kvm_lock);
637 }
638
639 int kvm_dev_ioctl_check_extension(long ext)
640 {
641         int r;
642
643         switch (ext) {
644         case KVM_CAP_IRQCHIP:
645         case KVM_CAP_HLT:
646         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
647         case KVM_CAP_USER_MEMORY:
648         case KVM_CAP_SET_TSS_ADDR:
649         case KVM_CAP_EXT_CPUID:
650                 r = 1;
651                 break;
652         default:
653                 r = 0;
654                 break;
655         }
656         return r;
657
658 }
659
660 long kvm_arch_dev_ioctl(struct file *filp,
661                         unsigned int ioctl, unsigned long arg)
662 {
663         void __user *argp = (void __user *)arg;
664         long r;
665
666         switch (ioctl) {
667         case KVM_GET_MSR_INDEX_LIST: {
668                 struct kvm_msr_list __user *user_msr_list = argp;
669                 struct kvm_msr_list msr_list;
670                 unsigned n;
671
672                 r = -EFAULT;
673                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
674                         goto out;
675                 n = msr_list.nmsrs;
676                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
677                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
678                         goto out;
679                 r = -E2BIG;
680                 if (n < num_msrs_to_save)
681                         goto out;
682                 r = -EFAULT;
683                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
684                                  num_msrs_to_save * sizeof(u32)))
685                         goto out;
686                 if (copy_to_user(user_msr_list->indices
687                                  + num_msrs_to_save * sizeof(u32),
688                                  &emulated_msrs,
689                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
690                         goto out;
691                 r = 0;
692                 break;
693         }
694         default:
695                 r = -EINVAL;
696         }
697 out:
698         return r;
699 }
700
701 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
702 {
703         kvm_x86_ops->vcpu_load(vcpu, cpu);
704 }
705
706 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
707 {
708         kvm_x86_ops->vcpu_put(vcpu);
709         kvm_put_guest_fpu(vcpu);
710 }
711
712 static int is_efer_nx(void)
713 {
714         u64 efer;
715
716         rdmsrl(MSR_EFER, efer);
717         return efer & EFER_NX;
718 }
719
720 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
721 {
722         int i;
723         struct kvm_cpuid_entry2 *e, *entry;
724
725         entry = NULL;
726         for (i = 0; i < vcpu->cpuid_nent; ++i) {
727                 e = &vcpu->cpuid_entries[i];
728                 if (e->function == 0x80000001) {
729                         entry = e;
730                         break;
731                 }
732         }
733         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
734                 entry->edx &= ~(1 << 20);
735                 printk(KERN_INFO "kvm: guest NX capability removed\n");
736         }
737 }
738
739 /* when an old userspace process fills a new kernel module */
740 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
741                                     struct kvm_cpuid *cpuid,
742                                     struct kvm_cpuid_entry __user *entries)
743 {
744         int r, i;
745         struct kvm_cpuid_entry *cpuid_entries;
746
747         r = -E2BIG;
748         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
749                 goto out;
750         r = -ENOMEM;
751         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
752         if (!cpuid_entries)
753                 goto out;
754         r = -EFAULT;
755         if (copy_from_user(cpuid_entries, entries,
756                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
757                 goto out_free;
758         for (i = 0; i < cpuid->nent; i++) {
759                 vcpu->cpuid_entries[i].function = cpuid_entries[i].function;
760                 vcpu->cpuid_entries[i].eax = cpuid_entries[i].eax;
761                 vcpu->cpuid_entries[i].ebx = cpuid_entries[i].ebx;
762                 vcpu->cpuid_entries[i].ecx = cpuid_entries[i].ecx;
763                 vcpu->cpuid_entries[i].edx = cpuid_entries[i].edx;
764                 vcpu->cpuid_entries[i].index = 0;
765                 vcpu->cpuid_entries[i].flags = 0;
766                 vcpu->cpuid_entries[i].padding[0] = 0;
767                 vcpu->cpuid_entries[i].padding[1] = 0;
768                 vcpu->cpuid_entries[i].padding[2] = 0;
769         }
770         vcpu->cpuid_nent = cpuid->nent;
771         cpuid_fix_nx_cap(vcpu);
772         r = 0;
773
774 out_free:
775         vfree(cpuid_entries);
776 out:
777         return r;
778 }
779
780 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
781                                     struct kvm_cpuid2 *cpuid,
782                                     struct kvm_cpuid_entry2 __user *entries)
783 {
784         int r;
785
786         r = -E2BIG;
787         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
788                 goto out;
789         r = -EFAULT;
790         if (copy_from_user(&vcpu->cpuid_entries, entries,
791                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
792                 goto out;
793         vcpu->cpuid_nent = cpuid->nent;
794         return 0;
795
796 out:
797         return r;
798 }
799
800 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
801                                     struct kvm_cpuid2 *cpuid,
802                                     struct kvm_cpuid_entry2 __user *entries)
803 {
804         int r;
805
806         r = -E2BIG;
807         if (cpuid->nent < vcpu->cpuid_nent)
808                 goto out;
809         r = -EFAULT;
810         if (copy_to_user(entries, &vcpu->cpuid_entries,
811                            vcpu->cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
812                 goto out;
813         return 0;
814
815 out:
816         cpuid->nent = vcpu->cpuid_nent;
817         return r;
818 }
819
820 static inline u32 bit(int bitno)
821 {
822         return 1 << (bitno & 31);
823 }
824
825 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
826                           u32 index)
827 {
828         entry->function = function;
829         entry->index = index;
830         cpuid_count(entry->function, entry->index,
831                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
832         entry->flags = 0;
833 }
834
835 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
836                          u32 index, int *nent, int maxnent)
837 {
838         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
839                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
840                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
841                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
842                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
843                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
844                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
845                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
846                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
847                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
848         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
849                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
850                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
851                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
852                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
853                 bit(X86_FEATURE_PGE) |
854                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
855                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
856                 bit(X86_FEATURE_SYSCALL) |
857                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
858 #ifdef CONFIG_X86_64
859                 bit(X86_FEATURE_LM) |
860 #endif
861                 bit(X86_FEATURE_MMXEXT) |
862                 bit(X86_FEATURE_3DNOWEXT) |
863                 bit(X86_FEATURE_3DNOW);
864         const u32 kvm_supported_word3_x86_features =
865                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
866         const u32 kvm_supported_word6_x86_features =
867                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
868
869         /* all func 2 cpuid_count() should be called on the same cpu */
870         get_cpu();
871         do_cpuid_1_ent(entry, function, index);
872         ++*nent;
873
874         switch (function) {
875         case 0:
876                 entry->eax = min(entry->eax, (u32)0xb);
877                 break;
878         case 1:
879                 entry->edx &= kvm_supported_word0_x86_features;
880                 entry->ecx &= kvm_supported_word3_x86_features;
881                 break;
882         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
883          * may return different values. This forces us to get_cpu() before
884          * issuing the first command, and also to emulate this annoying behavior
885          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
886         case 2: {
887                 int t, times = entry->eax & 0xff;
888
889                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
890                 for (t = 1; t < times && *nent < maxnent; ++t) {
891                         do_cpuid_1_ent(&entry[t], function, 0);
892                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
893                         ++*nent;
894                 }
895                 break;
896         }
897         /* function 4 and 0xb have additional index. */
898         case 4: {
899                 int index, cache_type;
900
901                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
902                 /* read more entries until cache_type is zero */
903                 for (index = 1; *nent < maxnent; ++index) {
904                         cache_type = entry[index - 1].eax & 0x1f;
905                         if (!cache_type)
906                                 break;
907                         do_cpuid_1_ent(&entry[index], function, index);
908                         entry[index].flags |=
909                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
910                         ++*nent;
911                 }
912                 break;
913         }
914         case 0xb: {
915                 int index, level_type;
916
917                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
918                 /* read more entries until level_type is zero */
919                 for (index = 1; *nent < maxnent; ++index) {
920                         level_type = entry[index - 1].ecx & 0xff;
921                         if (!level_type)
922                                 break;
923                         do_cpuid_1_ent(&entry[index], function, index);
924                         entry[index].flags |=
925                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
926                         ++*nent;
927                 }
928                 break;
929         }
930         case 0x80000000:
931                 entry->eax = min(entry->eax, 0x8000001a);
932                 break;
933         case 0x80000001:
934                 entry->edx &= kvm_supported_word1_x86_features;
935                 entry->ecx &= kvm_supported_word6_x86_features;
936                 break;
937         }
938         put_cpu();
939 }
940
941 static int kvm_vm_ioctl_get_supported_cpuid(struct kvm *kvm,
942                                     struct kvm_cpuid2 *cpuid,
943                                     struct kvm_cpuid_entry2 __user *entries)
944 {
945         struct kvm_cpuid_entry2 *cpuid_entries;
946         int limit, nent = 0, r = -E2BIG;
947         u32 func;
948
949         if (cpuid->nent < 1)
950                 goto out;
951         r = -ENOMEM;
952         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
953         if (!cpuid_entries)
954                 goto out;
955
956         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
957         limit = cpuid_entries[0].eax;
958         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
959                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
960                                 &nent, cpuid->nent);
961         r = -E2BIG;
962         if (nent >= cpuid->nent)
963                 goto out_free;
964
965         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
966         limit = cpuid_entries[nent - 1].eax;
967         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
968                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
969                                &nent, cpuid->nent);
970         r = -EFAULT;
971         if (copy_to_user(entries, cpuid_entries,
972                         nent * sizeof(struct kvm_cpuid_entry2)))
973                 goto out_free;
974         cpuid->nent = nent;
975         r = 0;
976
977 out_free:
978         vfree(cpuid_entries);
979 out:
980         return r;
981 }
982
983 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
984                                     struct kvm_lapic_state *s)
985 {
986         vcpu_load(vcpu);
987         memcpy(s->regs, vcpu->apic->regs, sizeof *s);
988         vcpu_put(vcpu);
989
990         return 0;
991 }
992
993 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
994                                     struct kvm_lapic_state *s)
995 {
996         vcpu_load(vcpu);
997         memcpy(vcpu->apic->regs, s->regs, sizeof *s);
998         kvm_apic_post_state_restore(vcpu);
999         vcpu_put(vcpu);
1000
1001         return 0;
1002 }
1003
1004 long kvm_arch_vcpu_ioctl(struct file *filp,
1005                          unsigned int ioctl, unsigned long arg)
1006 {
1007         struct kvm_vcpu *vcpu = filp->private_data;
1008         void __user *argp = (void __user *)arg;
1009         int r;
1010
1011         switch (ioctl) {
1012         case KVM_GET_LAPIC: {
1013                 struct kvm_lapic_state lapic;
1014
1015                 memset(&lapic, 0, sizeof lapic);
1016                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1017                 if (r)
1018                         goto out;
1019                 r = -EFAULT;
1020                 if (copy_to_user(argp, &lapic, sizeof lapic))
1021                         goto out;
1022                 r = 0;
1023                 break;
1024         }
1025         case KVM_SET_LAPIC: {
1026                 struct kvm_lapic_state lapic;
1027
1028                 r = -EFAULT;
1029                 if (copy_from_user(&lapic, argp, sizeof lapic))
1030                         goto out;
1031                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1032                 if (r)
1033                         goto out;
1034                 r = 0;
1035                 break;
1036         }
1037         case KVM_SET_CPUID: {
1038                 struct kvm_cpuid __user *cpuid_arg = argp;
1039                 struct kvm_cpuid cpuid;
1040
1041                 r = -EFAULT;
1042                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1043                         goto out;
1044                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1045                 if (r)
1046                         goto out;
1047                 break;
1048         }
1049         case KVM_SET_CPUID2: {
1050                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1051                 struct kvm_cpuid2 cpuid;
1052
1053                 r = -EFAULT;
1054                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1055                         goto out;
1056                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1057                                 cpuid_arg->entries);
1058                 if (r)
1059                         goto out;
1060                 break;
1061         }
1062         case KVM_GET_CPUID2: {
1063                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1064                 struct kvm_cpuid2 cpuid;
1065
1066                 r = -EFAULT;
1067                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1068                         goto out;
1069                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1070                                 cpuid_arg->entries);
1071                 if (r)
1072                         goto out;
1073                 r = -EFAULT;
1074                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1075                         goto out;
1076                 r = 0;
1077                 break;
1078         }
1079         case KVM_GET_MSRS:
1080                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1081                 break;
1082         case KVM_SET_MSRS:
1083                 r = msr_io(vcpu, argp, do_set_msr, 0);
1084                 break;
1085         default:
1086                 r = -EINVAL;
1087         }
1088 out:
1089         return r;
1090 }
1091
1092 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1093 {
1094         int ret;
1095
1096         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1097                 return -1;
1098         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1099         return ret;
1100 }
1101
1102 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1103                                           u32 kvm_nr_mmu_pages)
1104 {
1105         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1106                 return -EINVAL;
1107
1108         mutex_lock(&kvm->lock);
1109
1110         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1111         kvm->n_requested_mmu_pages = kvm_nr_mmu_pages;
1112
1113         mutex_unlock(&kvm->lock);
1114         return 0;
1115 }
1116
1117 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1118 {
1119         return kvm->n_alloc_mmu_pages;
1120 }
1121
1122 /*
1123  * Set a new alias region.  Aliases map a portion of physical memory into
1124  * another portion.  This is useful for memory windows, for example the PC
1125  * VGA region.
1126  */
1127 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1128                                          struct kvm_memory_alias *alias)
1129 {
1130         int r, n;
1131         struct kvm_mem_alias *p;
1132
1133         r = -EINVAL;
1134         /* General sanity checks */
1135         if (alias->memory_size & (PAGE_SIZE - 1))
1136                 goto out;
1137         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1138                 goto out;
1139         if (alias->slot >= KVM_ALIAS_SLOTS)
1140                 goto out;
1141         if (alias->guest_phys_addr + alias->memory_size
1142             < alias->guest_phys_addr)
1143                 goto out;
1144         if (alias->target_phys_addr + alias->memory_size
1145             < alias->target_phys_addr)
1146                 goto out;
1147
1148         mutex_lock(&kvm->lock);
1149
1150         p = &kvm->aliases[alias->slot];
1151         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1152         p->npages = alias->memory_size >> PAGE_SHIFT;
1153         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1154
1155         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1156                 if (kvm->aliases[n - 1].npages)
1157                         break;
1158         kvm->naliases = n;
1159
1160         kvm_mmu_zap_all(kvm);
1161
1162         mutex_unlock(&kvm->lock);
1163
1164         return 0;
1165
1166 out:
1167         return r;
1168 }
1169
1170 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1171 {
1172         int r;
1173
1174         r = 0;
1175         switch (chip->chip_id) {
1176         case KVM_IRQCHIP_PIC_MASTER:
1177                 memcpy(&chip->chip.pic,
1178                         &pic_irqchip(kvm)->pics[0],
1179                         sizeof(struct kvm_pic_state));
1180                 break;
1181         case KVM_IRQCHIP_PIC_SLAVE:
1182                 memcpy(&chip->chip.pic,
1183                         &pic_irqchip(kvm)->pics[1],
1184                         sizeof(struct kvm_pic_state));
1185                 break;
1186         case KVM_IRQCHIP_IOAPIC:
1187                 memcpy(&chip->chip.ioapic,
1188                         ioapic_irqchip(kvm),
1189                         sizeof(struct kvm_ioapic_state));
1190                 break;
1191         default:
1192                 r = -EINVAL;
1193                 break;
1194         }
1195         return r;
1196 }
1197
1198 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1199 {
1200         int r;
1201
1202         r = 0;
1203         switch (chip->chip_id) {
1204         case KVM_IRQCHIP_PIC_MASTER:
1205                 memcpy(&pic_irqchip(kvm)->pics[0],
1206                         &chip->chip.pic,
1207                         sizeof(struct kvm_pic_state));
1208                 break;
1209         case KVM_IRQCHIP_PIC_SLAVE:
1210                 memcpy(&pic_irqchip(kvm)->pics[1],
1211                         &chip->chip.pic,
1212                         sizeof(struct kvm_pic_state));
1213                 break;
1214         case KVM_IRQCHIP_IOAPIC:
1215                 memcpy(ioapic_irqchip(kvm),
1216                         &chip->chip.ioapic,
1217                         sizeof(struct kvm_ioapic_state));
1218                 break;
1219         default:
1220                 r = -EINVAL;
1221                 break;
1222         }
1223         kvm_pic_update_irq(pic_irqchip(kvm));
1224         return r;
1225 }
1226
1227 /*
1228  * Get (and clear) the dirty memory log for a memory slot.
1229  */
1230 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1231                                       struct kvm_dirty_log *log)
1232 {
1233         int r;
1234         int n;
1235         struct kvm_memory_slot *memslot;
1236         int is_dirty = 0;
1237
1238         mutex_lock(&kvm->lock);
1239
1240         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1241         if (r)
1242                 goto out;
1243
1244         /* If nothing is dirty, don't bother messing with page tables. */
1245         if (is_dirty) {
1246                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1247                 kvm_flush_remote_tlbs(kvm);
1248                 memslot = &kvm->memslots[log->slot];
1249                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1250                 memset(memslot->dirty_bitmap, 0, n);
1251         }
1252         r = 0;
1253 out:
1254         mutex_unlock(&kvm->lock);
1255         return r;
1256 }
1257
1258 long kvm_arch_vm_ioctl(struct file *filp,
1259                        unsigned int ioctl, unsigned long arg)
1260 {
1261         struct kvm *kvm = filp->private_data;
1262         void __user *argp = (void __user *)arg;
1263         int r = -EINVAL;
1264
1265         switch (ioctl) {
1266         case KVM_SET_TSS_ADDR:
1267                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1268                 if (r < 0)
1269                         goto out;
1270                 break;
1271         case KVM_SET_MEMORY_REGION: {
1272                 struct kvm_memory_region kvm_mem;
1273                 struct kvm_userspace_memory_region kvm_userspace_mem;
1274
1275                 r = -EFAULT;
1276                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1277                         goto out;
1278                 kvm_userspace_mem.slot = kvm_mem.slot;
1279                 kvm_userspace_mem.flags = kvm_mem.flags;
1280                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1281                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1282                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1283                 if (r)
1284                         goto out;
1285                 break;
1286         }
1287         case KVM_SET_NR_MMU_PAGES:
1288                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1289                 if (r)
1290                         goto out;
1291                 break;
1292         case KVM_GET_NR_MMU_PAGES:
1293                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1294                 break;
1295         case KVM_SET_MEMORY_ALIAS: {
1296                 struct kvm_memory_alias alias;
1297
1298                 r = -EFAULT;
1299                 if (copy_from_user(&alias, argp, sizeof alias))
1300                         goto out;
1301                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
1302                 if (r)
1303                         goto out;
1304                 break;
1305         }
1306         case KVM_CREATE_IRQCHIP:
1307                 r = -ENOMEM;
1308                 kvm->vpic = kvm_create_pic(kvm);
1309                 if (kvm->vpic) {
1310                         r = kvm_ioapic_init(kvm);
1311                         if (r) {
1312                                 kfree(kvm->vpic);
1313                                 kvm->vpic = NULL;
1314                                 goto out;
1315                         }
1316                 } else
1317                         goto out;
1318                 break;
1319         case KVM_IRQ_LINE: {
1320                 struct kvm_irq_level irq_event;
1321
1322                 r = -EFAULT;
1323                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1324                         goto out;
1325                 if (irqchip_in_kernel(kvm)) {
1326                         mutex_lock(&kvm->lock);
1327                         if (irq_event.irq < 16)
1328                                 kvm_pic_set_irq(pic_irqchip(kvm),
1329                                         irq_event.irq,
1330                                         irq_event.level);
1331                         kvm_ioapic_set_irq(kvm->vioapic,
1332                                         irq_event.irq,
1333                                         irq_event.level);
1334                         mutex_unlock(&kvm->lock);
1335                         r = 0;
1336                 }
1337                 break;
1338         }
1339         case KVM_GET_IRQCHIP: {
1340                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1341                 struct kvm_irqchip chip;
1342
1343                 r = -EFAULT;
1344                 if (copy_from_user(&chip, argp, sizeof chip))
1345                         goto out;
1346                 r = -ENXIO;
1347                 if (!irqchip_in_kernel(kvm))
1348                         goto out;
1349                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1350                 if (r)
1351                         goto out;
1352                 r = -EFAULT;
1353                 if (copy_to_user(argp, &chip, sizeof chip))
1354                         goto out;
1355                 r = 0;
1356                 break;
1357         }
1358         case KVM_SET_IRQCHIP: {
1359                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1360                 struct kvm_irqchip chip;
1361
1362                 r = -EFAULT;
1363                 if (copy_from_user(&chip, argp, sizeof chip))
1364                         goto out;
1365                 r = -ENXIO;
1366                 if (!irqchip_in_kernel(kvm))
1367                         goto out;
1368                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1369                 if (r)
1370                         goto out;
1371                 r = 0;
1372                 break;
1373         }
1374         case KVM_GET_SUPPORTED_CPUID: {
1375                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1376                 struct kvm_cpuid2 cpuid;
1377
1378                 r = -EFAULT;
1379                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1380                         goto out;
1381                 r = kvm_vm_ioctl_get_supported_cpuid(kvm, &cpuid,
1382                         cpuid_arg->entries);
1383                 if (r)
1384                         goto out;
1385
1386                 r = -EFAULT;
1387                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1388                         goto out;
1389                 r = 0;
1390                 break;
1391         }
1392         default:
1393                 ;
1394         }
1395 out:
1396         return r;
1397 }
1398
1399 static void kvm_init_msr_list(void)
1400 {
1401         u32 dummy[2];
1402         unsigned i, j;
1403
1404         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1405                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1406                         continue;
1407                 if (j < i)
1408                         msrs_to_save[j] = msrs_to_save[i];
1409                 j++;
1410         }
1411         num_msrs_to_save = j;
1412 }
1413
1414 /*
1415  * Only apic need an MMIO device hook, so shortcut now..
1416  */
1417 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1418                                                 gpa_t addr)
1419 {
1420         struct kvm_io_device *dev;
1421
1422         if (vcpu->apic) {
1423                 dev = &vcpu->apic->dev;
1424                 if (dev->in_range(dev, addr))
1425                         return dev;
1426         }
1427         return NULL;
1428 }
1429
1430
1431 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1432                                                 gpa_t addr)
1433 {
1434         struct kvm_io_device *dev;
1435
1436         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1437         if (dev == NULL)
1438                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1439         return dev;
1440 }
1441
1442 int emulator_read_std(unsigned long addr,
1443                              void *val,
1444                              unsigned int bytes,
1445                              struct kvm_vcpu *vcpu)
1446 {
1447         void *data = val;
1448
1449         while (bytes) {
1450                 gpa_t gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1451                 unsigned offset = addr & (PAGE_SIZE-1);
1452                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1453                 int ret;
1454
1455                 if (gpa == UNMAPPED_GVA)
1456                         return X86EMUL_PROPAGATE_FAULT;
1457                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1458                 if (ret < 0)
1459                         return X86EMUL_UNHANDLEABLE;
1460
1461                 bytes -= tocopy;
1462                 data += tocopy;
1463                 addr += tocopy;
1464         }
1465
1466         return X86EMUL_CONTINUE;
1467 }
1468 EXPORT_SYMBOL_GPL(emulator_read_std);
1469
1470 static int emulator_read_emulated(unsigned long addr,
1471                                   void *val,
1472                                   unsigned int bytes,
1473                                   struct kvm_vcpu *vcpu)
1474 {
1475         struct kvm_io_device *mmio_dev;
1476         gpa_t                 gpa;
1477
1478         if (vcpu->mmio_read_completed) {
1479                 memcpy(val, vcpu->mmio_data, bytes);
1480                 vcpu->mmio_read_completed = 0;
1481                 return X86EMUL_CONTINUE;
1482         }
1483
1484         gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1485
1486         /* For APIC access vmexit */
1487         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1488                 goto mmio;
1489
1490         if (emulator_read_std(addr, val, bytes, vcpu)
1491                         == X86EMUL_CONTINUE)
1492                 return X86EMUL_CONTINUE;
1493         if (gpa == UNMAPPED_GVA)
1494                 return X86EMUL_PROPAGATE_FAULT;
1495
1496 mmio:
1497         /*
1498          * Is this MMIO handled locally?
1499          */
1500         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1501         if (mmio_dev) {
1502                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1503                 return X86EMUL_CONTINUE;
1504         }
1505
1506         vcpu->mmio_needed = 1;
1507         vcpu->mmio_phys_addr = gpa;
1508         vcpu->mmio_size = bytes;
1509         vcpu->mmio_is_write = 0;
1510
1511         return X86EMUL_UNHANDLEABLE;
1512 }
1513
1514 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1515                                const void *val, int bytes)
1516 {
1517         int ret;
1518
1519         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1520         if (ret < 0)
1521                 return 0;
1522         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1523         return 1;
1524 }
1525
1526 static int emulator_write_emulated_onepage(unsigned long addr,
1527                                            const void *val,
1528                                            unsigned int bytes,
1529                                            struct kvm_vcpu *vcpu)
1530 {
1531         struct kvm_io_device *mmio_dev;
1532         gpa_t                 gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1533
1534         if (gpa == UNMAPPED_GVA) {
1535                 kvm_x86_ops->inject_page_fault(vcpu, addr, 2);
1536                 return X86EMUL_PROPAGATE_FAULT;
1537         }
1538
1539         /* For APIC access vmexit */
1540         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1541                 goto mmio;
1542
1543         if (emulator_write_phys(vcpu, gpa, val, bytes))
1544                 return X86EMUL_CONTINUE;
1545
1546 mmio:
1547         /*
1548          * Is this MMIO handled locally?
1549          */
1550         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1551         if (mmio_dev) {
1552                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1553                 return X86EMUL_CONTINUE;
1554         }
1555
1556         vcpu->mmio_needed = 1;
1557         vcpu->mmio_phys_addr = gpa;
1558         vcpu->mmio_size = bytes;
1559         vcpu->mmio_is_write = 1;
1560         memcpy(vcpu->mmio_data, val, bytes);
1561
1562         return X86EMUL_CONTINUE;
1563 }
1564
1565 int emulator_write_emulated(unsigned long addr,
1566                                    const void *val,
1567                                    unsigned int bytes,
1568                                    struct kvm_vcpu *vcpu)
1569 {
1570         /* Crossing a page boundary? */
1571         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1572                 int rc, now;
1573
1574                 now = -addr & ~PAGE_MASK;
1575                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1576                 if (rc != X86EMUL_CONTINUE)
1577                         return rc;
1578                 addr += now;
1579                 val += now;
1580                 bytes -= now;
1581         }
1582         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1583 }
1584 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1585
1586 static int emulator_cmpxchg_emulated(unsigned long addr,
1587                                      const void *old,
1588                                      const void *new,
1589                                      unsigned int bytes,
1590                                      struct kvm_vcpu *vcpu)
1591 {
1592         static int reported;
1593
1594         if (!reported) {
1595                 reported = 1;
1596                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1597         }
1598         return emulator_write_emulated(addr, new, bytes, vcpu);
1599 }
1600
1601 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1602 {
1603         return kvm_x86_ops->get_segment_base(vcpu, seg);
1604 }
1605
1606 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1607 {
1608         return X86EMUL_CONTINUE;
1609 }
1610
1611 int emulate_clts(struct kvm_vcpu *vcpu)
1612 {
1613         kvm_x86_ops->set_cr0(vcpu, vcpu->cr0 & ~X86_CR0_TS);
1614         return X86EMUL_CONTINUE;
1615 }
1616
1617 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
1618 {
1619         struct kvm_vcpu *vcpu = ctxt->vcpu;
1620
1621         switch (dr) {
1622         case 0 ... 3:
1623                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
1624                 return X86EMUL_CONTINUE;
1625         default:
1626                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __FUNCTION__, dr);
1627                 return X86EMUL_UNHANDLEABLE;
1628         }
1629 }
1630
1631 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1632 {
1633         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1634         int exception;
1635
1636         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1637         if (exception) {
1638                 /* FIXME: better handling */
1639                 return X86EMUL_UNHANDLEABLE;
1640         }
1641         return X86EMUL_CONTINUE;
1642 }
1643
1644 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
1645 {
1646         static int reported;
1647         u8 opcodes[4];
1648         unsigned long rip = vcpu->rip;
1649         unsigned long rip_linear;
1650
1651         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
1652
1653         if (reported)
1654                 return;
1655
1656         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
1657
1658         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
1659                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1660         reported = 1;
1661 }
1662 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
1663
1664 struct x86_emulate_ops emulate_ops = {
1665         .read_std            = emulator_read_std,
1666         .read_emulated       = emulator_read_emulated,
1667         .write_emulated      = emulator_write_emulated,
1668         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1669 };
1670
1671 int emulate_instruction(struct kvm_vcpu *vcpu,
1672                         struct kvm_run *run,
1673                         unsigned long cr2,
1674                         u16 error_code,
1675                         int no_decode)
1676 {
1677         int r;
1678
1679         vcpu->mmio_fault_cr2 = cr2;
1680         kvm_x86_ops->cache_regs(vcpu);
1681
1682         vcpu->mmio_is_write = 0;
1683         vcpu->pio.string = 0;
1684
1685         if (!no_decode) {
1686                 int cs_db, cs_l;
1687                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1688
1689                 vcpu->emulate_ctxt.vcpu = vcpu;
1690                 vcpu->emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
1691                 vcpu->emulate_ctxt.cr2 = cr2;
1692                 vcpu->emulate_ctxt.mode =
1693                         (vcpu->emulate_ctxt.eflags & X86_EFLAGS_VM)
1694                         ? X86EMUL_MODE_REAL : cs_l
1695                         ? X86EMUL_MODE_PROT64 : cs_db
1696                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1697
1698                 if (vcpu->emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1699                         vcpu->emulate_ctxt.cs_base = 0;
1700                         vcpu->emulate_ctxt.ds_base = 0;
1701                         vcpu->emulate_ctxt.es_base = 0;
1702                         vcpu->emulate_ctxt.ss_base = 0;
1703                 } else {
1704                         vcpu->emulate_ctxt.cs_base =
1705                                         get_segment_base(vcpu, VCPU_SREG_CS);
1706                         vcpu->emulate_ctxt.ds_base =
1707                                         get_segment_base(vcpu, VCPU_SREG_DS);
1708                         vcpu->emulate_ctxt.es_base =
1709                                         get_segment_base(vcpu, VCPU_SREG_ES);
1710                         vcpu->emulate_ctxt.ss_base =
1711                                         get_segment_base(vcpu, VCPU_SREG_SS);
1712                 }
1713
1714                 vcpu->emulate_ctxt.gs_base =
1715                                         get_segment_base(vcpu, VCPU_SREG_GS);
1716                 vcpu->emulate_ctxt.fs_base =
1717                                         get_segment_base(vcpu, VCPU_SREG_FS);
1718
1719                 r = x86_decode_insn(&vcpu->emulate_ctxt, &emulate_ops);
1720                 ++vcpu->stat.insn_emulation;
1721                 if (r)  {
1722                         ++vcpu->stat.insn_emulation_fail;
1723                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1724                                 return EMULATE_DONE;
1725                         return EMULATE_FAIL;
1726                 }
1727         }
1728
1729         r = x86_emulate_insn(&vcpu->emulate_ctxt, &emulate_ops);
1730
1731         if (vcpu->pio.string)
1732                 return EMULATE_DO_MMIO;
1733
1734         if ((r || vcpu->mmio_is_write) && run) {
1735                 run->exit_reason = KVM_EXIT_MMIO;
1736                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1737                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1738                 run->mmio.len = vcpu->mmio_size;
1739                 run->mmio.is_write = vcpu->mmio_is_write;
1740         }
1741
1742         if (r) {
1743                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1744                         return EMULATE_DONE;
1745                 if (!vcpu->mmio_needed) {
1746                         kvm_report_emulation_failure(vcpu, "mmio");
1747                         return EMULATE_FAIL;
1748                 }
1749                 return EMULATE_DO_MMIO;
1750         }
1751
1752         kvm_x86_ops->decache_regs(vcpu);
1753         kvm_x86_ops->set_rflags(vcpu, vcpu->emulate_ctxt.eflags);
1754
1755         if (vcpu->mmio_is_write) {
1756                 vcpu->mmio_needed = 0;
1757                 return EMULATE_DO_MMIO;
1758         }
1759
1760         return EMULATE_DONE;
1761 }
1762 EXPORT_SYMBOL_GPL(emulate_instruction);
1763
1764 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
1765 {
1766         int i;
1767
1768         for (i = 0; i < ARRAY_SIZE(vcpu->pio.guest_pages); ++i)
1769                 if (vcpu->pio.guest_pages[i]) {
1770                         kvm_release_page_dirty(vcpu->pio.guest_pages[i]);
1771                         vcpu->pio.guest_pages[i] = NULL;
1772                 }
1773 }
1774
1775 static int pio_copy_data(struct kvm_vcpu *vcpu)
1776 {
1777         void *p = vcpu->pio_data;
1778         void *q;
1779         unsigned bytes;
1780         int nr_pages = vcpu->pio.guest_pages[1] ? 2 : 1;
1781
1782         q = vmap(vcpu->pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1783                  PAGE_KERNEL);
1784         if (!q) {
1785                 free_pio_guest_pages(vcpu);
1786                 return -ENOMEM;
1787         }
1788         q += vcpu->pio.guest_page_offset;
1789         bytes = vcpu->pio.size * vcpu->pio.cur_count;
1790         if (vcpu->pio.in)
1791                 memcpy(q, p, bytes);
1792         else
1793                 memcpy(p, q, bytes);
1794         q -= vcpu->pio.guest_page_offset;
1795         vunmap(q);
1796         free_pio_guest_pages(vcpu);
1797         return 0;
1798 }
1799
1800 int complete_pio(struct kvm_vcpu *vcpu)
1801 {
1802         struct kvm_pio_request *io = &vcpu->pio;
1803         long delta;
1804         int r;
1805
1806         kvm_x86_ops->cache_regs(vcpu);
1807
1808         if (!io->string) {
1809                 if (io->in)
1810                         memcpy(&vcpu->regs[VCPU_REGS_RAX], vcpu->pio_data,
1811                                io->size);
1812         } else {
1813                 if (io->in) {
1814                         r = pio_copy_data(vcpu);
1815                         if (r) {
1816                                 kvm_x86_ops->cache_regs(vcpu);
1817                                 return r;
1818                         }
1819                 }
1820
1821                 delta = 1;
1822                 if (io->rep) {
1823                         delta *= io->cur_count;
1824                         /*
1825                          * The size of the register should really depend on
1826                          * current address size.
1827                          */
1828                         vcpu->regs[VCPU_REGS_RCX] -= delta;
1829                 }
1830                 if (io->down)
1831                         delta = -delta;
1832                 delta *= io->size;
1833                 if (io->in)
1834                         vcpu->regs[VCPU_REGS_RDI] += delta;
1835                 else
1836                         vcpu->regs[VCPU_REGS_RSI] += delta;
1837         }
1838
1839         kvm_x86_ops->decache_regs(vcpu);
1840
1841         io->count -= io->cur_count;
1842         io->cur_count = 0;
1843
1844         return 0;
1845 }
1846
1847 static void kernel_pio(struct kvm_io_device *pio_dev,
1848                        struct kvm_vcpu *vcpu,
1849                        void *pd)
1850 {
1851         /* TODO: String I/O for in kernel device */
1852
1853         mutex_lock(&vcpu->kvm->lock);
1854         if (vcpu->pio.in)
1855                 kvm_iodevice_read(pio_dev, vcpu->pio.port,
1856                                   vcpu->pio.size,
1857                                   pd);
1858         else
1859                 kvm_iodevice_write(pio_dev, vcpu->pio.port,
1860                                    vcpu->pio.size,
1861                                    pd);
1862         mutex_unlock(&vcpu->kvm->lock);
1863 }
1864
1865 static void pio_string_write(struct kvm_io_device *pio_dev,
1866                              struct kvm_vcpu *vcpu)
1867 {
1868         struct kvm_pio_request *io = &vcpu->pio;
1869         void *pd = vcpu->pio_data;
1870         int i;
1871
1872         mutex_lock(&vcpu->kvm->lock);
1873         for (i = 0; i < io->cur_count; i++) {
1874                 kvm_iodevice_write(pio_dev, io->port,
1875                                    io->size,
1876                                    pd);
1877                 pd += io->size;
1878         }
1879         mutex_unlock(&vcpu->kvm->lock);
1880 }
1881
1882 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
1883                                                gpa_t addr)
1884 {
1885         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
1886 }
1887
1888 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1889                   int size, unsigned port)
1890 {
1891         struct kvm_io_device *pio_dev;
1892
1893         vcpu->run->exit_reason = KVM_EXIT_IO;
1894         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1895         vcpu->run->io.size = vcpu->pio.size = size;
1896         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1897         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = 1;
1898         vcpu->run->io.port = vcpu->pio.port = port;
1899         vcpu->pio.in = in;
1900         vcpu->pio.string = 0;
1901         vcpu->pio.down = 0;
1902         vcpu->pio.guest_page_offset = 0;
1903         vcpu->pio.rep = 0;
1904
1905         kvm_x86_ops->cache_regs(vcpu);
1906         memcpy(vcpu->pio_data, &vcpu->regs[VCPU_REGS_RAX], 4);
1907         kvm_x86_ops->decache_regs(vcpu);
1908
1909         kvm_x86_ops->skip_emulated_instruction(vcpu);
1910
1911         pio_dev = vcpu_find_pio_dev(vcpu, port);
1912         if (pio_dev) {
1913                 kernel_pio(pio_dev, vcpu, vcpu->pio_data);
1914                 complete_pio(vcpu);
1915                 return 1;
1916         }
1917         return 0;
1918 }
1919 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
1920
1921 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1922                   int size, unsigned long count, int down,
1923                   gva_t address, int rep, unsigned port)
1924 {
1925         unsigned now, in_page;
1926         int i, ret = 0;
1927         int nr_pages = 1;
1928         struct page *page;
1929         struct kvm_io_device *pio_dev;
1930
1931         vcpu->run->exit_reason = KVM_EXIT_IO;
1932         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1933         vcpu->run->io.size = vcpu->pio.size = size;
1934         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1935         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = count;
1936         vcpu->run->io.port = vcpu->pio.port = port;
1937         vcpu->pio.in = in;
1938         vcpu->pio.string = 1;
1939         vcpu->pio.down = down;
1940         vcpu->pio.guest_page_offset = offset_in_page(address);
1941         vcpu->pio.rep = rep;
1942
1943         if (!count) {
1944                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1945                 return 1;
1946         }
1947
1948         if (!down)
1949                 in_page = PAGE_SIZE - offset_in_page(address);
1950         else
1951                 in_page = offset_in_page(address) + size;
1952         now = min(count, (unsigned long)in_page / size);
1953         if (!now) {
1954                 /*
1955                  * String I/O straddles page boundary.  Pin two guest pages
1956                  * so that we satisfy atomicity constraints.  Do just one
1957                  * transaction to avoid complexity.
1958                  */
1959                 nr_pages = 2;
1960                 now = 1;
1961         }
1962         if (down) {
1963                 /*
1964                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
1965                  */
1966                 pr_unimpl(vcpu, "guest string pio down\n");
1967                 inject_gp(vcpu);
1968                 return 1;
1969         }
1970         vcpu->run->io.count = now;
1971         vcpu->pio.cur_count = now;
1972
1973         if (vcpu->pio.cur_count == vcpu->pio.count)
1974                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1975
1976         for (i = 0; i < nr_pages; ++i) {
1977                 mutex_lock(&vcpu->kvm->lock);
1978                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
1979                 vcpu->pio.guest_pages[i] = page;
1980                 mutex_unlock(&vcpu->kvm->lock);
1981                 if (!page) {
1982                         inject_gp(vcpu);
1983                         free_pio_guest_pages(vcpu);
1984                         return 1;
1985                 }
1986         }
1987
1988         pio_dev = vcpu_find_pio_dev(vcpu, port);
1989         if (!vcpu->pio.in) {
1990                 /* string PIO write */
1991                 ret = pio_copy_data(vcpu);
1992                 if (ret >= 0 && pio_dev) {
1993                         pio_string_write(pio_dev, vcpu);
1994                         complete_pio(vcpu);
1995                         if (vcpu->pio.count == 0)
1996                                 ret = 1;
1997                 }
1998         } else if (pio_dev)
1999                 pr_unimpl(vcpu, "no string pio read support yet, "
2000                        "port %x size %d count %ld\n",
2001                         port, size, count);
2002
2003         return ret;
2004 }
2005 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2006
2007 int kvm_arch_init(void *opaque)
2008 {
2009         int r;
2010         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2011
2012         r = kvm_mmu_module_init();
2013         if (r)
2014                 goto out_fail;
2015
2016         kvm_init_msr_list();
2017
2018         if (kvm_x86_ops) {
2019                 printk(KERN_ERR "kvm: already loaded the other module\n");
2020                 r = -EEXIST;
2021                 goto out;
2022         }
2023
2024         if (!ops->cpu_has_kvm_support()) {
2025                 printk(KERN_ERR "kvm: no hardware support\n");
2026                 r = -EOPNOTSUPP;
2027                 goto out;
2028         }
2029         if (ops->disabled_by_bios()) {
2030                 printk(KERN_ERR "kvm: disabled by bios\n");
2031                 r = -EOPNOTSUPP;
2032                 goto out;
2033         }
2034
2035         kvm_x86_ops = ops;
2036         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2037         return 0;
2038
2039 out:
2040         kvm_mmu_module_exit();
2041 out_fail:
2042         return r;
2043 }
2044
2045 void kvm_arch_exit(void)
2046 {
2047         kvm_x86_ops = NULL;
2048         kvm_mmu_module_exit();
2049 }
2050
2051 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2052 {
2053         ++vcpu->stat.halt_exits;
2054         if (irqchip_in_kernel(vcpu->kvm)) {
2055                 vcpu->mp_state = VCPU_MP_STATE_HALTED;
2056                 kvm_vcpu_block(vcpu);
2057                 if (vcpu->mp_state != VCPU_MP_STATE_RUNNABLE)
2058                         return -EINTR;
2059                 return 1;
2060         } else {
2061                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2062                 return 0;
2063         }
2064 }
2065 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2066
2067 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2068 {
2069         unsigned long nr, a0, a1, a2, a3, ret;
2070
2071         kvm_x86_ops->cache_regs(vcpu);
2072
2073         nr = vcpu->regs[VCPU_REGS_RAX];
2074         a0 = vcpu->regs[VCPU_REGS_RBX];
2075         a1 = vcpu->regs[VCPU_REGS_RCX];
2076         a2 = vcpu->regs[VCPU_REGS_RDX];
2077         a3 = vcpu->regs[VCPU_REGS_RSI];
2078
2079         if (!is_long_mode(vcpu)) {
2080                 nr &= 0xFFFFFFFF;
2081                 a0 &= 0xFFFFFFFF;
2082                 a1 &= 0xFFFFFFFF;
2083                 a2 &= 0xFFFFFFFF;
2084                 a3 &= 0xFFFFFFFF;
2085         }
2086
2087         switch (nr) {
2088         default:
2089                 ret = -KVM_ENOSYS;
2090                 break;
2091         }
2092         vcpu->regs[VCPU_REGS_RAX] = ret;
2093         kvm_x86_ops->decache_regs(vcpu);
2094         return 0;
2095 }
2096 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2097
2098 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2099 {
2100         char instruction[3];
2101         int ret = 0;
2102
2103         mutex_lock(&vcpu->kvm->lock);
2104
2105         /*
2106          * Blow out the MMU to ensure that no other VCPU has an active mapping
2107          * to ensure that the updated hypercall appears atomically across all
2108          * VCPUs.
2109          */
2110         kvm_mmu_zap_all(vcpu->kvm);
2111
2112         kvm_x86_ops->cache_regs(vcpu);
2113         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2114         if (emulator_write_emulated(vcpu->rip, instruction, 3, vcpu)
2115             != X86EMUL_CONTINUE)
2116                 ret = -EFAULT;
2117
2118         mutex_unlock(&vcpu->kvm->lock);
2119
2120         return ret;
2121 }
2122
2123 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2124 {
2125         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2126 }
2127
2128 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2129 {
2130         struct descriptor_table dt = { limit, base };
2131
2132         kvm_x86_ops->set_gdt(vcpu, &dt);
2133 }
2134
2135 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2136 {
2137         struct descriptor_table dt = { limit, base };
2138
2139         kvm_x86_ops->set_idt(vcpu, &dt);
2140 }
2141
2142 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2143                    unsigned long *rflags)
2144 {
2145         lmsw(vcpu, msw);
2146         *rflags = kvm_x86_ops->get_rflags(vcpu);
2147 }
2148
2149 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2150 {
2151         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2152         switch (cr) {
2153         case 0:
2154                 return vcpu->cr0;
2155         case 2:
2156                 return vcpu->cr2;
2157         case 3:
2158                 return vcpu->cr3;
2159         case 4:
2160                 return vcpu->cr4;
2161         default:
2162                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2163                 return 0;
2164         }
2165 }
2166
2167 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2168                      unsigned long *rflags)
2169 {
2170         switch (cr) {
2171         case 0:
2172                 set_cr0(vcpu, mk_cr_64(vcpu->cr0, val));
2173                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2174                 break;
2175         case 2:
2176                 vcpu->cr2 = val;
2177                 break;
2178         case 3:
2179                 set_cr3(vcpu, val);
2180                 break;
2181         case 4:
2182                 set_cr4(vcpu, mk_cr_64(vcpu->cr4, val));
2183                 break;
2184         default:
2185                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2186         }
2187 }
2188
2189 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2190 {
2191         struct kvm_cpuid_entry2 *e = &vcpu->cpuid_entries[i];
2192         int j, nent = vcpu->cpuid_nent;
2193
2194         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2195         /* when no next entry is found, the current entry[i] is reselected */
2196         for (j = i + 1; j == i; j = (j + 1) % nent) {
2197                 struct kvm_cpuid_entry2 *ej = &vcpu->cpuid_entries[j];
2198                 if (ej->function == e->function) {
2199                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2200                         return j;
2201                 }
2202         }
2203         return 0; /* silence gcc, even though control never reaches here */
2204 }
2205
2206 /* find an entry with matching function, matching index (if needed), and that
2207  * should be read next (if it's stateful) */
2208 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2209         u32 function, u32 index)
2210 {
2211         if (e->function != function)
2212                 return 0;
2213         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2214                 return 0;
2215         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2216                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2217                 return 0;
2218         return 1;
2219 }
2220
2221 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2222 {
2223         int i;
2224         u32 function, index;
2225         struct kvm_cpuid_entry2 *e, *best;
2226
2227         kvm_x86_ops->cache_regs(vcpu);
2228         function = vcpu->regs[VCPU_REGS_RAX];
2229         index = vcpu->regs[VCPU_REGS_RCX];
2230         vcpu->regs[VCPU_REGS_RAX] = 0;
2231         vcpu->regs[VCPU_REGS_RBX] = 0;
2232         vcpu->regs[VCPU_REGS_RCX] = 0;
2233         vcpu->regs[VCPU_REGS_RDX] = 0;
2234         best = NULL;
2235         for (i = 0; i < vcpu->cpuid_nent; ++i) {
2236                 e = &vcpu->cpuid_entries[i];
2237                 if (is_matching_cpuid_entry(e, function, index)) {
2238                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2239                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2240                         best = e;
2241                         break;
2242                 }
2243                 /*
2244                  * Both basic or both extended?
2245                  */
2246                 if (((e->function ^ function) & 0x80000000) == 0)
2247                         if (!best || e->function > best->function)
2248                                 best = e;
2249         }
2250         if (best) {
2251                 vcpu->regs[VCPU_REGS_RAX] = best->eax;
2252                 vcpu->regs[VCPU_REGS_RBX] = best->ebx;
2253                 vcpu->regs[VCPU_REGS_RCX] = best->ecx;
2254                 vcpu->regs[VCPU_REGS_RDX] = best->edx;
2255         }
2256         kvm_x86_ops->decache_regs(vcpu);
2257         kvm_x86_ops->skip_emulated_instruction(vcpu);
2258 }
2259 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2260
2261 /*
2262  * Check if userspace requested an interrupt window, and that the
2263  * interrupt window is open.
2264  *
2265  * No need to exit to userspace if we already have an interrupt queued.
2266  */
2267 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2268                                           struct kvm_run *kvm_run)
2269 {
2270         return (!vcpu->irq_summary &&
2271                 kvm_run->request_interrupt_window &&
2272                 vcpu->interrupt_window_open &&
2273                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2274 }
2275
2276 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2277                               struct kvm_run *kvm_run)
2278 {
2279         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2280         kvm_run->cr8 = get_cr8(vcpu);
2281         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2282         if (irqchip_in_kernel(vcpu->kvm))
2283                 kvm_run->ready_for_interrupt_injection = 1;
2284         else
2285                 kvm_run->ready_for_interrupt_injection =
2286                                         (vcpu->interrupt_window_open &&
2287                                          vcpu->irq_summary == 0);
2288 }
2289
2290 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2291 {
2292         int r;
2293
2294         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
2295                 pr_debug("vcpu %d received sipi with vector # %x\n",
2296                        vcpu->vcpu_id, vcpu->sipi_vector);
2297                 kvm_lapic_reset(vcpu);
2298                 r = kvm_x86_ops->vcpu_reset(vcpu);
2299                 if (r)
2300                         return r;
2301                 vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
2302         }
2303
2304 preempted:
2305         if (vcpu->guest_debug.enabled)
2306                 kvm_x86_ops->guest_debug_pre(vcpu);
2307
2308 again:
2309         r = kvm_mmu_reload(vcpu);
2310         if (unlikely(r))
2311                 goto out;
2312
2313         kvm_inject_pending_timer_irqs(vcpu);
2314
2315         preempt_disable();
2316
2317         kvm_x86_ops->prepare_guest_switch(vcpu);
2318         kvm_load_guest_fpu(vcpu);
2319
2320         local_irq_disable();
2321
2322         if (signal_pending(current)) {
2323                 local_irq_enable();
2324                 preempt_enable();
2325                 r = -EINTR;
2326                 kvm_run->exit_reason = KVM_EXIT_INTR;
2327                 ++vcpu->stat.signal_exits;
2328                 goto out;
2329         }
2330
2331         if (irqchip_in_kernel(vcpu->kvm))
2332                 kvm_x86_ops->inject_pending_irq(vcpu);
2333         else if (!vcpu->mmio_read_completed)
2334                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
2335
2336         vcpu->guest_mode = 1;
2337         kvm_guest_enter();
2338
2339         if (vcpu->requests)
2340                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2341                         kvm_x86_ops->tlb_flush(vcpu);
2342
2343         kvm_x86_ops->run(vcpu, kvm_run);
2344
2345         vcpu->guest_mode = 0;
2346         local_irq_enable();
2347
2348         ++vcpu->stat.exits;
2349
2350         /*
2351          * We must have an instruction between local_irq_enable() and
2352          * kvm_guest_exit(), so the timer interrupt isn't delayed by
2353          * the interrupt shadow.  The stat.exits increment will do nicely.
2354          * But we need to prevent reordering, hence this barrier():
2355          */
2356         barrier();
2357
2358         kvm_guest_exit();
2359
2360         preempt_enable();
2361
2362         /*
2363          * Profile KVM exit RIPs:
2364          */
2365         if (unlikely(prof_on == KVM_PROFILING)) {
2366                 kvm_x86_ops->cache_regs(vcpu);
2367                 profile_hit(KVM_PROFILING, (void *)vcpu->rip);
2368         }
2369
2370         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2371
2372         if (r > 0) {
2373                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2374                         r = -EINTR;
2375                         kvm_run->exit_reason = KVM_EXIT_INTR;
2376                         ++vcpu->stat.request_irq_exits;
2377                         goto out;
2378                 }
2379                 if (!need_resched())
2380                         goto again;
2381         }
2382
2383 out:
2384         if (r > 0) {
2385                 kvm_resched(vcpu);
2386                 goto preempted;
2387         }
2388
2389         post_kvm_run_save(vcpu, kvm_run);
2390
2391         return r;
2392 }
2393
2394 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2395 {
2396         int r;
2397         sigset_t sigsaved;
2398
2399         vcpu_load(vcpu);
2400
2401         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
2402                 kvm_vcpu_block(vcpu);
2403                 vcpu_put(vcpu);
2404                 return -EAGAIN;
2405         }
2406
2407         if (vcpu->sigset_active)
2408                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2409
2410         /* re-sync apic's tpr */
2411         if (!irqchip_in_kernel(vcpu->kvm))
2412                 set_cr8(vcpu, kvm_run->cr8);
2413
2414         if (vcpu->pio.cur_count) {
2415                 r = complete_pio(vcpu);
2416                 if (r)
2417                         goto out;
2418         }
2419 #if CONFIG_HAS_IOMEM
2420         if (vcpu->mmio_needed) {
2421                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2422                 vcpu->mmio_read_completed = 1;
2423                 vcpu->mmio_needed = 0;
2424                 r = emulate_instruction(vcpu, kvm_run,
2425                                         vcpu->mmio_fault_cr2, 0, 1);
2426                 if (r == EMULATE_DO_MMIO) {
2427                         /*
2428                          * Read-modify-write.  Back to userspace.
2429                          */
2430                         r = 0;
2431                         goto out;
2432                 }
2433         }
2434 #endif
2435         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2436                 kvm_x86_ops->cache_regs(vcpu);
2437                 vcpu->regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2438                 kvm_x86_ops->decache_regs(vcpu);
2439         }
2440
2441         r = __vcpu_run(vcpu, kvm_run);
2442
2443 out:
2444         if (vcpu->sigset_active)
2445                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2446
2447         vcpu_put(vcpu);
2448         return r;
2449 }
2450
2451 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2452 {
2453         vcpu_load(vcpu);
2454
2455         kvm_x86_ops->cache_regs(vcpu);
2456
2457         regs->rax = vcpu->regs[VCPU_REGS_RAX];
2458         regs->rbx = vcpu->regs[VCPU_REGS_RBX];
2459         regs->rcx = vcpu->regs[VCPU_REGS_RCX];
2460         regs->rdx = vcpu->regs[VCPU_REGS_RDX];
2461         regs->rsi = vcpu->regs[VCPU_REGS_RSI];
2462         regs->rdi = vcpu->regs[VCPU_REGS_RDI];
2463         regs->rsp = vcpu->regs[VCPU_REGS_RSP];
2464         regs->rbp = vcpu->regs[VCPU_REGS_RBP];
2465 #ifdef CONFIG_X86_64
2466         regs->r8 = vcpu->regs[VCPU_REGS_R8];
2467         regs->r9 = vcpu->regs[VCPU_REGS_R9];
2468         regs->r10 = vcpu->regs[VCPU_REGS_R10];
2469         regs->r11 = vcpu->regs[VCPU_REGS_R11];
2470         regs->r12 = vcpu->regs[VCPU_REGS_R12];
2471         regs->r13 = vcpu->regs[VCPU_REGS_R13];
2472         regs->r14 = vcpu->regs[VCPU_REGS_R14];
2473         regs->r15 = vcpu->regs[VCPU_REGS_R15];
2474 #endif
2475
2476         regs->rip = vcpu->rip;
2477         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2478
2479         /*
2480          * Don't leak debug flags in case they were set for guest debugging
2481          */
2482         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2483                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2484
2485         vcpu_put(vcpu);
2486
2487         return 0;
2488 }
2489
2490 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2491 {
2492         vcpu_load(vcpu);
2493
2494         vcpu->regs[VCPU_REGS_RAX] = regs->rax;
2495         vcpu->regs[VCPU_REGS_RBX] = regs->rbx;
2496         vcpu->regs[VCPU_REGS_RCX] = regs->rcx;
2497         vcpu->regs[VCPU_REGS_RDX] = regs->rdx;
2498         vcpu->regs[VCPU_REGS_RSI] = regs->rsi;
2499         vcpu->regs[VCPU_REGS_RDI] = regs->rdi;
2500         vcpu->regs[VCPU_REGS_RSP] = regs->rsp;
2501         vcpu->regs[VCPU_REGS_RBP] = regs->rbp;
2502 #ifdef CONFIG_X86_64
2503         vcpu->regs[VCPU_REGS_R8] = regs->r8;
2504         vcpu->regs[VCPU_REGS_R9] = regs->r9;
2505         vcpu->regs[VCPU_REGS_R10] = regs->r10;
2506         vcpu->regs[VCPU_REGS_R11] = regs->r11;
2507         vcpu->regs[VCPU_REGS_R12] = regs->r12;
2508         vcpu->regs[VCPU_REGS_R13] = regs->r13;
2509         vcpu->regs[VCPU_REGS_R14] = regs->r14;
2510         vcpu->regs[VCPU_REGS_R15] = regs->r15;
2511 #endif
2512
2513         vcpu->rip = regs->rip;
2514         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
2515
2516         kvm_x86_ops->decache_regs(vcpu);
2517
2518         vcpu_put(vcpu);
2519
2520         return 0;
2521 }
2522
2523 static void get_segment(struct kvm_vcpu *vcpu,
2524                         struct kvm_segment *var, int seg)
2525 {
2526         return kvm_x86_ops->get_segment(vcpu, var, seg);
2527 }
2528
2529 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2530 {
2531         struct kvm_segment cs;
2532
2533         get_segment(vcpu, &cs, VCPU_SREG_CS);
2534         *db = cs.db;
2535         *l = cs.l;
2536 }
2537 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
2538
2539 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
2540                                   struct kvm_sregs *sregs)
2541 {
2542         struct descriptor_table dt;
2543         int pending_vec;
2544
2545         vcpu_load(vcpu);
2546
2547         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2548         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2549         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2550         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2551         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2552         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2553
2554         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2555         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2556
2557         kvm_x86_ops->get_idt(vcpu, &dt);
2558         sregs->idt.limit = dt.limit;
2559         sregs->idt.base = dt.base;
2560         kvm_x86_ops->get_gdt(vcpu, &dt);
2561         sregs->gdt.limit = dt.limit;
2562         sregs->gdt.base = dt.base;
2563
2564         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2565         sregs->cr0 = vcpu->cr0;
2566         sregs->cr2 = vcpu->cr2;
2567         sregs->cr3 = vcpu->cr3;
2568         sregs->cr4 = vcpu->cr4;
2569         sregs->cr8 = get_cr8(vcpu);
2570         sregs->efer = vcpu->shadow_efer;
2571         sregs->apic_base = kvm_get_apic_base(vcpu);
2572
2573         if (irqchip_in_kernel(vcpu->kvm)) {
2574                 memset(sregs->interrupt_bitmap, 0,
2575                        sizeof sregs->interrupt_bitmap);
2576                 pending_vec = kvm_x86_ops->get_irq(vcpu);
2577                 if (pending_vec >= 0)
2578                         set_bit(pending_vec,
2579                                 (unsigned long *)sregs->interrupt_bitmap);
2580         } else
2581                 memcpy(sregs->interrupt_bitmap, vcpu->irq_pending,
2582                        sizeof sregs->interrupt_bitmap);
2583
2584         vcpu_put(vcpu);
2585
2586         return 0;
2587 }
2588
2589 static void set_segment(struct kvm_vcpu *vcpu,
2590                         struct kvm_segment *var, int seg)
2591 {
2592         return kvm_x86_ops->set_segment(vcpu, var, seg);
2593 }
2594
2595 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2596                                   struct kvm_sregs *sregs)
2597 {
2598         int mmu_reset_needed = 0;
2599         int i, pending_vec, max_bits;
2600         struct descriptor_table dt;
2601
2602         vcpu_load(vcpu);
2603
2604         dt.limit = sregs->idt.limit;
2605         dt.base = sregs->idt.base;
2606         kvm_x86_ops->set_idt(vcpu, &dt);
2607         dt.limit = sregs->gdt.limit;
2608         dt.base = sregs->gdt.base;
2609         kvm_x86_ops->set_gdt(vcpu, &dt);
2610
2611         vcpu->cr2 = sregs->cr2;
2612         mmu_reset_needed |= vcpu->cr3 != sregs->cr3;
2613         vcpu->cr3 = sregs->cr3;
2614
2615         set_cr8(vcpu, sregs->cr8);
2616
2617         mmu_reset_needed |= vcpu->shadow_efer != sregs->efer;
2618 #ifdef CONFIG_X86_64
2619         kvm_x86_ops->set_efer(vcpu, sregs->efer);
2620 #endif
2621         kvm_set_apic_base(vcpu, sregs->apic_base);
2622
2623         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2624
2625         mmu_reset_needed |= vcpu->cr0 != sregs->cr0;
2626         vcpu->cr0 = sregs->cr0;
2627         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
2628
2629         mmu_reset_needed |= vcpu->cr4 != sregs->cr4;
2630         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
2631         if (!is_long_mode(vcpu) && is_pae(vcpu))
2632                 load_pdptrs(vcpu, vcpu->cr3);
2633
2634         if (mmu_reset_needed)
2635                 kvm_mmu_reset_context(vcpu);
2636
2637         if (!irqchip_in_kernel(vcpu->kvm)) {
2638                 memcpy(vcpu->irq_pending, sregs->interrupt_bitmap,
2639                        sizeof vcpu->irq_pending);
2640                 vcpu->irq_summary = 0;
2641                 for (i = 0; i < ARRAY_SIZE(vcpu->irq_pending); ++i)
2642                         if (vcpu->irq_pending[i])
2643                                 __set_bit(i, &vcpu->irq_summary);
2644         } else {
2645                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
2646                 pending_vec = find_first_bit(
2647                         (const unsigned long *)sregs->interrupt_bitmap,
2648                         max_bits);
2649                 /* Only pending external irq is handled here */
2650                 if (pending_vec < max_bits) {
2651                         kvm_x86_ops->set_irq(vcpu, pending_vec);
2652                         pr_debug("Set back pending irq %d\n",
2653                                  pending_vec);
2654                 }
2655         }
2656
2657         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2658         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2659         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2660         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2661         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2662         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2663
2664         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2665         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2666
2667         vcpu_put(vcpu);
2668
2669         return 0;
2670 }
2671
2672 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2673                                     struct kvm_debug_guest *dbg)
2674 {
2675         int r;
2676
2677         vcpu_load(vcpu);
2678
2679         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
2680
2681         vcpu_put(vcpu);
2682
2683         return r;
2684 }
2685
2686 /*
2687  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2688  * we have asm/x86/processor.h
2689  */
2690 struct fxsave {
2691         u16     cwd;
2692         u16     swd;
2693         u16     twd;
2694         u16     fop;
2695         u64     rip;
2696         u64     rdp;
2697         u32     mxcsr;
2698         u32     mxcsr_mask;
2699         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2700 #ifdef CONFIG_X86_64
2701         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2702 #else
2703         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2704 #endif
2705 };
2706
2707 /*
2708  * Translate a guest virtual address to a guest physical address.
2709  */
2710 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2711                                     struct kvm_translation *tr)
2712 {
2713         unsigned long vaddr = tr->linear_address;
2714         gpa_t gpa;
2715
2716         vcpu_load(vcpu);
2717         mutex_lock(&vcpu->kvm->lock);
2718         gpa = vcpu->mmu.gva_to_gpa(vcpu, vaddr);
2719         tr->physical_address = gpa;
2720         tr->valid = gpa != UNMAPPED_GVA;
2721         tr->writeable = 1;
2722         tr->usermode = 0;
2723         mutex_unlock(&vcpu->kvm->lock);
2724         vcpu_put(vcpu);
2725
2726         return 0;
2727 }
2728
2729 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2730 {
2731         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2732
2733         vcpu_load(vcpu);
2734
2735         memcpy(fpu->fpr, fxsave->st_space, 128);
2736         fpu->fcw = fxsave->cwd;
2737         fpu->fsw = fxsave->swd;
2738         fpu->ftwx = fxsave->twd;
2739         fpu->last_opcode = fxsave->fop;
2740         fpu->last_ip = fxsave->rip;
2741         fpu->last_dp = fxsave->rdp;
2742         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2743
2744         vcpu_put(vcpu);
2745
2746         return 0;
2747 }
2748
2749 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2750 {
2751         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2752
2753         vcpu_load(vcpu);
2754
2755         memcpy(fxsave->st_space, fpu->fpr, 128);
2756         fxsave->cwd = fpu->fcw;
2757         fxsave->swd = fpu->fsw;
2758         fxsave->twd = fpu->ftwx;
2759         fxsave->fop = fpu->last_opcode;
2760         fxsave->rip = fpu->last_ip;
2761         fxsave->rdp = fpu->last_dp;
2762         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2763
2764         vcpu_put(vcpu);
2765
2766         return 0;
2767 }
2768
2769 void fx_init(struct kvm_vcpu *vcpu)
2770 {
2771         unsigned after_mxcsr_mask;
2772
2773         /* Initialize guest FPU by resetting ours and saving into guest's */
2774         preempt_disable();
2775         fx_save(&vcpu->host_fx_image);
2776         fpu_init();
2777         fx_save(&vcpu->guest_fx_image);
2778         fx_restore(&vcpu->host_fx_image);
2779         preempt_enable();
2780
2781         vcpu->cr0 |= X86_CR0_ET;
2782         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
2783         vcpu->guest_fx_image.mxcsr = 0x1f80;
2784         memset((void *)&vcpu->guest_fx_image + after_mxcsr_mask,
2785                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
2786 }
2787 EXPORT_SYMBOL_GPL(fx_init);
2788
2789 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
2790 {
2791         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
2792                 return;
2793
2794         vcpu->guest_fpu_loaded = 1;
2795         fx_save(&vcpu->host_fx_image);
2796         fx_restore(&vcpu->guest_fx_image);
2797 }
2798 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
2799
2800 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
2801 {
2802         if (!vcpu->guest_fpu_loaded)
2803                 return;
2804
2805         vcpu->guest_fpu_loaded = 0;
2806         fx_save(&vcpu->guest_fx_image);
2807         fx_restore(&vcpu->host_fx_image);
2808         ++vcpu->stat.fpu_reload;
2809 }
2810 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
2811
2812 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
2813 {
2814         kvm_x86_ops->vcpu_free(vcpu);
2815 }
2816
2817 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
2818                                                 unsigned int id)
2819 {
2820         return kvm_x86_ops->vcpu_create(kvm, id);
2821 }
2822
2823 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
2824 {
2825         int r;
2826
2827         /* We do fxsave: this must be aligned. */
2828         BUG_ON((unsigned long)&vcpu->host_fx_image & 0xF);
2829
2830         vcpu_load(vcpu);
2831         r = kvm_arch_vcpu_reset(vcpu);
2832         if (r == 0)
2833                 r = kvm_mmu_setup(vcpu);
2834         vcpu_put(vcpu);
2835         if (r < 0)
2836                 goto free_vcpu;
2837
2838         return 0;
2839 free_vcpu:
2840         kvm_x86_ops->vcpu_free(vcpu);
2841         return r;
2842 }
2843
2844 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
2845 {
2846         vcpu_load(vcpu);
2847         kvm_mmu_unload(vcpu);
2848         vcpu_put(vcpu);
2849
2850         kvm_x86_ops->vcpu_free(vcpu);
2851 }
2852
2853 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
2854 {
2855         return kvm_x86_ops->vcpu_reset(vcpu);
2856 }
2857
2858 void kvm_arch_hardware_enable(void *garbage)
2859 {
2860         kvm_x86_ops->hardware_enable(garbage);
2861 }
2862
2863 void kvm_arch_hardware_disable(void *garbage)
2864 {
2865         kvm_x86_ops->hardware_disable(garbage);
2866 }
2867
2868 int kvm_arch_hardware_setup(void)
2869 {
2870         return kvm_x86_ops->hardware_setup();
2871 }
2872
2873 void kvm_arch_hardware_unsetup(void)
2874 {
2875         kvm_x86_ops->hardware_unsetup();
2876 }
2877
2878 void kvm_arch_check_processor_compat(void *rtn)
2879 {
2880         kvm_x86_ops->check_processor_compatibility(rtn);
2881 }
2882
2883 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
2884 {
2885         struct page *page;
2886         struct kvm *kvm;
2887         int r;
2888
2889         BUG_ON(vcpu->kvm == NULL);
2890         kvm = vcpu->kvm;
2891
2892         vcpu->mmu.root_hpa = INVALID_PAGE;
2893         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
2894                 vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
2895         else
2896                 vcpu->mp_state = VCPU_MP_STATE_UNINITIALIZED;
2897
2898         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2899         if (!page) {
2900                 r = -ENOMEM;
2901                 goto fail;
2902         }
2903         vcpu->pio_data = page_address(page);
2904
2905         r = kvm_mmu_create(vcpu);
2906         if (r < 0)
2907                 goto fail_free_pio_data;
2908
2909         if (irqchip_in_kernel(kvm)) {
2910                 r = kvm_create_lapic(vcpu);
2911                 if (r < 0)
2912                         goto fail_mmu_destroy;
2913         }
2914
2915         return 0;
2916
2917 fail_mmu_destroy:
2918         kvm_mmu_destroy(vcpu);
2919 fail_free_pio_data:
2920         free_page((unsigned long)vcpu->pio_data);
2921 fail:
2922         return r;
2923 }
2924
2925 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
2926 {
2927         kvm_free_lapic(vcpu);
2928         kvm_mmu_destroy(vcpu);
2929         free_page((unsigned long)vcpu->pio_data);
2930 }
2931
2932 struct  kvm *kvm_arch_create_vm(void)
2933 {
2934         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
2935
2936         if (!kvm)
2937                 return ERR_PTR(-ENOMEM);
2938
2939         INIT_LIST_HEAD(&kvm->active_mmu_pages);
2940
2941         return kvm;
2942 }
2943
2944 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
2945 {
2946         vcpu_load(vcpu);
2947         kvm_mmu_unload(vcpu);
2948         vcpu_put(vcpu);
2949 }
2950
2951 static void kvm_free_vcpus(struct kvm *kvm)
2952 {
2953         unsigned int i;
2954
2955         /*
2956          * Unpin any mmu pages first.
2957          */
2958         for (i = 0; i < KVM_MAX_VCPUS; ++i)
2959                 if (kvm->vcpus[i])
2960                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
2961         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
2962                 if (kvm->vcpus[i]) {
2963                         kvm_arch_vcpu_free(kvm->vcpus[i]);
2964                         kvm->vcpus[i] = NULL;
2965                 }
2966         }
2967
2968 }
2969
2970 void kvm_arch_destroy_vm(struct kvm *kvm)
2971 {
2972         kfree(kvm->vpic);
2973         kfree(kvm->vioapic);
2974         kvm_free_vcpus(kvm);
2975         kvm_free_physmem(kvm);
2976         kfree(kvm);
2977 }
2978
2979 int kvm_arch_set_memory_region(struct kvm *kvm,
2980                                 struct kvm_userspace_memory_region *mem,
2981                                 struct kvm_memory_slot old,
2982                                 int user_alloc)
2983 {
2984         int npages = mem->memory_size >> PAGE_SHIFT;
2985         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
2986
2987         /*To keep backward compatibility with older userspace,
2988          *x86 needs to hanlde !user_alloc case.
2989          */
2990         if (!user_alloc) {
2991                 if (npages && !old.rmap) {
2992                         down_write(&current->mm->mmap_sem);
2993                         memslot->userspace_addr = do_mmap(NULL, 0,
2994                                                      npages * PAGE_SIZE,
2995                                                      PROT_READ | PROT_WRITE,
2996                                                      MAP_SHARED | MAP_ANONYMOUS,
2997                                                      0);
2998                         up_write(&current->mm->mmap_sem);
2999
3000                         if (IS_ERR((void *)memslot->userspace_addr))
3001                                 return PTR_ERR((void *)memslot->userspace_addr);
3002                 } else {
3003                         if (!old.user_alloc && old.rmap) {
3004                                 int ret;
3005
3006                                 down_write(&current->mm->mmap_sem);
3007                                 ret = do_munmap(current->mm, old.userspace_addr,
3008                                                 old.npages * PAGE_SIZE);
3009                                 up_write(&current->mm->mmap_sem);
3010                                 if (ret < 0)
3011                                         printk(KERN_WARNING
3012                                        "kvm_vm_ioctl_set_memory_region: "
3013                                        "failed to munmap memory\n");
3014                         }
3015                 }
3016         }
3017
3018         if (!kvm->n_requested_mmu_pages) {
3019                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
3020                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
3021         }
3022
3023         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
3024         kvm_flush_remote_tlbs(kvm);
3025
3026         return 0;
3027 }