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