]> err.no Git - linux-2.6/blob - arch/x86/kvm/x86.c
KVM: MMU: hypercall based pte updates and TLB flushes
[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         case KVM_CAP_PV_MMU:
836                 r = !tdp_enabled;
837                 break;
838         default:
839                 r = 0;
840                 break;
841         }
842         return r;
843
844 }
845
846 long kvm_arch_dev_ioctl(struct file *filp,
847                         unsigned int ioctl, unsigned long arg)
848 {
849         void __user *argp = (void __user *)arg;
850         long r;
851
852         switch (ioctl) {
853         case KVM_GET_MSR_INDEX_LIST: {
854                 struct kvm_msr_list __user *user_msr_list = argp;
855                 struct kvm_msr_list msr_list;
856                 unsigned n;
857
858                 r = -EFAULT;
859                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
860                         goto out;
861                 n = msr_list.nmsrs;
862                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
863                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
864                         goto out;
865                 r = -E2BIG;
866                 if (n < num_msrs_to_save)
867                         goto out;
868                 r = -EFAULT;
869                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
870                                  num_msrs_to_save * sizeof(u32)))
871                         goto out;
872                 if (copy_to_user(user_msr_list->indices
873                                  + num_msrs_to_save * sizeof(u32),
874                                  &emulated_msrs,
875                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
876                         goto out;
877                 r = 0;
878                 break;
879         }
880         case KVM_GET_SUPPORTED_CPUID: {
881                 struct kvm_cpuid2 __user *cpuid_arg = argp;
882                 struct kvm_cpuid2 cpuid;
883
884                 r = -EFAULT;
885                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
886                         goto out;
887                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
888                         cpuid_arg->entries);
889                 if (r)
890                         goto out;
891
892                 r = -EFAULT;
893                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
894                         goto out;
895                 r = 0;
896                 break;
897         }
898         default:
899                 r = -EINVAL;
900         }
901 out:
902         return r;
903 }
904
905 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
906 {
907         kvm_x86_ops->vcpu_load(vcpu, cpu);
908         kvm_write_guest_time(vcpu);
909 }
910
911 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
912 {
913         kvm_x86_ops->vcpu_put(vcpu);
914         kvm_put_guest_fpu(vcpu);
915 }
916
917 static int is_efer_nx(void)
918 {
919         u64 efer;
920
921         rdmsrl(MSR_EFER, efer);
922         return efer & EFER_NX;
923 }
924
925 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
926 {
927         int i;
928         struct kvm_cpuid_entry2 *e, *entry;
929
930         entry = NULL;
931         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
932                 e = &vcpu->arch.cpuid_entries[i];
933                 if (e->function == 0x80000001) {
934                         entry = e;
935                         break;
936                 }
937         }
938         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
939                 entry->edx &= ~(1 << 20);
940                 printk(KERN_INFO "kvm: guest NX capability removed\n");
941         }
942 }
943
944 /* when an old userspace process fills a new kernel module */
945 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
946                                     struct kvm_cpuid *cpuid,
947                                     struct kvm_cpuid_entry __user *entries)
948 {
949         int r, i;
950         struct kvm_cpuid_entry *cpuid_entries;
951
952         r = -E2BIG;
953         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
954                 goto out;
955         r = -ENOMEM;
956         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
957         if (!cpuid_entries)
958                 goto out;
959         r = -EFAULT;
960         if (copy_from_user(cpuid_entries, entries,
961                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
962                 goto out_free;
963         for (i = 0; i < cpuid->nent; i++) {
964                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
965                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
966                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
967                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
968                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
969                 vcpu->arch.cpuid_entries[i].index = 0;
970                 vcpu->arch.cpuid_entries[i].flags = 0;
971                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
972                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
973                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
974         }
975         vcpu->arch.cpuid_nent = cpuid->nent;
976         cpuid_fix_nx_cap(vcpu);
977         r = 0;
978
979 out_free:
980         vfree(cpuid_entries);
981 out:
982         return r;
983 }
984
985 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
986                                     struct kvm_cpuid2 *cpuid,
987                                     struct kvm_cpuid_entry2 __user *entries)
988 {
989         int r;
990
991         r = -E2BIG;
992         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
993                 goto out;
994         r = -EFAULT;
995         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
996                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
997                 goto out;
998         vcpu->arch.cpuid_nent = cpuid->nent;
999         return 0;
1000
1001 out:
1002         return r;
1003 }
1004
1005 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1006                                     struct kvm_cpuid2 *cpuid,
1007                                     struct kvm_cpuid_entry2 __user *entries)
1008 {
1009         int r;
1010
1011         r = -E2BIG;
1012         if (cpuid->nent < vcpu->arch.cpuid_nent)
1013                 goto out;
1014         r = -EFAULT;
1015         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1016                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1017                 goto out;
1018         return 0;
1019
1020 out:
1021         cpuid->nent = vcpu->arch.cpuid_nent;
1022         return r;
1023 }
1024
1025 static inline u32 bit(int bitno)
1026 {
1027         return 1 << (bitno & 31);
1028 }
1029
1030 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1031                           u32 index)
1032 {
1033         entry->function = function;
1034         entry->index = index;
1035         cpuid_count(entry->function, entry->index,
1036                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1037         entry->flags = 0;
1038 }
1039
1040 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1041                          u32 index, int *nent, int maxnent)
1042 {
1043         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
1044                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1045                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1046                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1047                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1048                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
1049                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1050                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
1051                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
1052                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
1053         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
1054                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1055                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1056                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1057                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1058                 bit(X86_FEATURE_PGE) |
1059                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1060                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
1061                 bit(X86_FEATURE_SYSCALL) |
1062                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
1063 #ifdef CONFIG_X86_64
1064                 bit(X86_FEATURE_LM) |
1065 #endif
1066                 bit(X86_FEATURE_MMXEXT) |
1067                 bit(X86_FEATURE_3DNOWEXT) |
1068                 bit(X86_FEATURE_3DNOW);
1069         const u32 kvm_supported_word3_x86_features =
1070                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
1071         const u32 kvm_supported_word6_x86_features =
1072                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
1073
1074         /* all func 2 cpuid_count() should be called on the same cpu */
1075         get_cpu();
1076         do_cpuid_1_ent(entry, function, index);
1077         ++*nent;
1078
1079         switch (function) {
1080         case 0:
1081                 entry->eax = min(entry->eax, (u32)0xb);
1082                 break;
1083         case 1:
1084                 entry->edx &= kvm_supported_word0_x86_features;
1085                 entry->ecx &= kvm_supported_word3_x86_features;
1086                 break;
1087         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1088          * may return different values. This forces us to get_cpu() before
1089          * issuing the first command, and also to emulate this annoying behavior
1090          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1091         case 2: {
1092                 int t, times = entry->eax & 0xff;
1093
1094                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1095                 for (t = 1; t < times && *nent < maxnent; ++t) {
1096                         do_cpuid_1_ent(&entry[t], function, 0);
1097                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1098                         ++*nent;
1099                 }
1100                 break;
1101         }
1102         /* function 4 and 0xb have additional index. */
1103         case 4: {
1104                 int i, cache_type;
1105
1106                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1107                 /* read more entries until cache_type is zero */
1108                 for (i = 1; *nent < maxnent; ++i) {
1109                         cache_type = entry[i - 1].eax & 0x1f;
1110                         if (!cache_type)
1111                                 break;
1112                         do_cpuid_1_ent(&entry[i], function, i);
1113                         entry[i].flags |=
1114                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1115                         ++*nent;
1116                 }
1117                 break;
1118         }
1119         case 0xb: {
1120                 int i, level_type;
1121
1122                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1123                 /* read more entries until level_type is zero */
1124                 for (i = 1; *nent < maxnent; ++i) {
1125                         level_type = entry[i - 1].ecx & 0xff;
1126                         if (!level_type)
1127                                 break;
1128                         do_cpuid_1_ent(&entry[i], function, i);
1129                         entry[i].flags |=
1130                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1131                         ++*nent;
1132                 }
1133                 break;
1134         }
1135         case 0x80000000:
1136                 entry->eax = min(entry->eax, 0x8000001a);
1137                 break;
1138         case 0x80000001:
1139                 entry->edx &= kvm_supported_word1_x86_features;
1140                 entry->ecx &= kvm_supported_word6_x86_features;
1141                 break;
1142         }
1143         put_cpu();
1144 }
1145
1146 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1147                                     struct kvm_cpuid_entry2 __user *entries)
1148 {
1149         struct kvm_cpuid_entry2 *cpuid_entries;
1150         int limit, nent = 0, r = -E2BIG;
1151         u32 func;
1152
1153         if (cpuid->nent < 1)
1154                 goto out;
1155         r = -ENOMEM;
1156         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1157         if (!cpuid_entries)
1158                 goto out;
1159
1160         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1161         limit = cpuid_entries[0].eax;
1162         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1163                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1164                                 &nent, cpuid->nent);
1165         r = -E2BIG;
1166         if (nent >= cpuid->nent)
1167                 goto out_free;
1168
1169         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1170         limit = cpuid_entries[nent - 1].eax;
1171         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1172                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1173                                &nent, cpuid->nent);
1174         r = -EFAULT;
1175         if (copy_to_user(entries, cpuid_entries,
1176                         nent * sizeof(struct kvm_cpuid_entry2)))
1177                 goto out_free;
1178         cpuid->nent = nent;
1179         r = 0;
1180
1181 out_free:
1182         vfree(cpuid_entries);
1183 out:
1184         return r;
1185 }
1186
1187 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1188                                     struct kvm_lapic_state *s)
1189 {
1190         vcpu_load(vcpu);
1191         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1192         vcpu_put(vcpu);
1193
1194         return 0;
1195 }
1196
1197 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1198                                     struct kvm_lapic_state *s)
1199 {
1200         vcpu_load(vcpu);
1201         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1202         kvm_apic_post_state_restore(vcpu);
1203         vcpu_put(vcpu);
1204
1205         return 0;
1206 }
1207
1208 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1209                                     struct kvm_interrupt *irq)
1210 {
1211         if (irq->irq < 0 || irq->irq >= 256)
1212                 return -EINVAL;
1213         if (irqchip_in_kernel(vcpu->kvm))
1214                 return -ENXIO;
1215         vcpu_load(vcpu);
1216
1217         set_bit(irq->irq, vcpu->arch.irq_pending);
1218         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1219
1220         vcpu_put(vcpu);
1221
1222         return 0;
1223 }
1224
1225 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1226                                            struct kvm_tpr_access_ctl *tac)
1227 {
1228         if (tac->flags)
1229                 return -EINVAL;
1230         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1231         return 0;
1232 }
1233
1234 long kvm_arch_vcpu_ioctl(struct file *filp,
1235                          unsigned int ioctl, unsigned long arg)
1236 {
1237         struct kvm_vcpu *vcpu = filp->private_data;
1238         void __user *argp = (void __user *)arg;
1239         int r;
1240
1241         switch (ioctl) {
1242         case KVM_GET_LAPIC: {
1243                 struct kvm_lapic_state lapic;
1244
1245                 memset(&lapic, 0, sizeof lapic);
1246                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1247                 if (r)
1248                         goto out;
1249                 r = -EFAULT;
1250                 if (copy_to_user(argp, &lapic, sizeof lapic))
1251                         goto out;
1252                 r = 0;
1253                 break;
1254         }
1255         case KVM_SET_LAPIC: {
1256                 struct kvm_lapic_state lapic;
1257
1258                 r = -EFAULT;
1259                 if (copy_from_user(&lapic, argp, sizeof lapic))
1260                         goto out;
1261                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1262                 if (r)
1263                         goto out;
1264                 r = 0;
1265                 break;
1266         }
1267         case KVM_INTERRUPT: {
1268                 struct kvm_interrupt irq;
1269
1270                 r = -EFAULT;
1271                 if (copy_from_user(&irq, argp, sizeof irq))
1272                         goto out;
1273                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1274                 if (r)
1275                         goto out;
1276                 r = 0;
1277                 break;
1278         }
1279         case KVM_SET_CPUID: {
1280                 struct kvm_cpuid __user *cpuid_arg = argp;
1281                 struct kvm_cpuid cpuid;
1282
1283                 r = -EFAULT;
1284                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1285                         goto out;
1286                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1287                 if (r)
1288                         goto out;
1289                 break;
1290         }
1291         case KVM_SET_CPUID2: {
1292                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1293                 struct kvm_cpuid2 cpuid;
1294
1295                 r = -EFAULT;
1296                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1297                         goto out;
1298                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1299                                 cpuid_arg->entries);
1300                 if (r)
1301                         goto out;
1302                 break;
1303         }
1304         case KVM_GET_CPUID2: {
1305                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1306                 struct kvm_cpuid2 cpuid;
1307
1308                 r = -EFAULT;
1309                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1310                         goto out;
1311                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1312                                 cpuid_arg->entries);
1313                 if (r)
1314                         goto out;
1315                 r = -EFAULT;
1316                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1317                         goto out;
1318                 r = 0;
1319                 break;
1320         }
1321         case KVM_GET_MSRS:
1322                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1323                 break;
1324         case KVM_SET_MSRS:
1325                 r = msr_io(vcpu, argp, do_set_msr, 0);
1326                 break;
1327         case KVM_TPR_ACCESS_REPORTING: {
1328                 struct kvm_tpr_access_ctl tac;
1329
1330                 r = -EFAULT;
1331                 if (copy_from_user(&tac, argp, sizeof tac))
1332                         goto out;
1333                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1334                 if (r)
1335                         goto out;
1336                 r = -EFAULT;
1337                 if (copy_to_user(argp, &tac, sizeof tac))
1338                         goto out;
1339                 r = 0;
1340                 break;
1341         };
1342         case KVM_SET_VAPIC_ADDR: {
1343                 struct kvm_vapic_addr va;
1344
1345                 r = -EINVAL;
1346                 if (!irqchip_in_kernel(vcpu->kvm))
1347                         goto out;
1348                 r = -EFAULT;
1349                 if (copy_from_user(&va, argp, sizeof va))
1350                         goto out;
1351                 r = 0;
1352                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1353                 break;
1354         }
1355         default:
1356                 r = -EINVAL;
1357         }
1358 out:
1359         return r;
1360 }
1361
1362 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1363 {
1364         int ret;
1365
1366         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1367                 return -1;
1368         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1369         return ret;
1370 }
1371
1372 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1373                                           u32 kvm_nr_mmu_pages)
1374 {
1375         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1376                 return -EINVAL;
1377
1378         down_write(&kvm->slots_lock);
1379
1380         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1381         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1382
1383         up_write(&kvm->slots_lock);
1384         return 0;
1385 }
1386
1387 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1388 {
1389         return kvm->arch.n_alloc_mmu_pages;
1390 }
1391
1392 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1393 {
1394         int i;
1395         struct kvm_mem_alias *alias;
1396
1397         for (i = 0; i < kvm->arch.naliases; ++i) {
1398                 alias = &kvm->arch.aliases[i];
1399                 if (gfn >= alias->base_gfn
1400                     && gfn < alias->base_gfn + alias->npages)
1401                         return alias->target_gfn + gfn - alias->base_gfn;
1402         }
1403         return gfn;
1404 }
1405
1406 /*
1407  * Set a new alias region.  Aliases map a portion of physical memory into
1408  * another portion.  This is useful for memory windows, for example the PC
1409  * VGA region.
1410  */
1411 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1412                                          struct kvm_memory_alias *alias)
1413 {
1414         int r, n;
1415         struct kvm_mem_alias *p;
1416
1417         r = -EINVAL;
1418         /* General sanity checks */
1419         if (alias->memory_size & (PAGE_SIZE - 1))
1420                 goto out;
1421         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1422                 goto out;
1423         if (alias->slot >= KVM_ALIAS_SLOTS)
1424                 goto out;
1425         if (alias->guest_phys_addr + alias->memory_size
1426             < alias->guest_phys_addr)
1427                 goto out;
1428         if (alias->target_phys_addr + alias->memory_size
1429             < alias->target_phys_addr)
1430                 goto out;
1431
1432         down_write(&kvm->slots_lock);
1433
1434         p = &kvm->arch.aliases[alias->slot];
1435         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1436         p->npages = alias->memory_size >> PAGE_SHIFT;
1437         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1438
1439         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1440                 if (kvm->arch.aliases[n - 1].npages)
1441                         break;
1442         kvm->arch.naliases = n;
1443
1444         kvm_mmu_zap_all(kvm);
1445
1446         up_write(&kvm->slots_lock);
1447
1448         return 0;
1449
1450 out:
1451         return r;
1452 }
1453
1454 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1455 {
1456         int r;
1457
1458         r = 0;
1459         switch (chip->chip_id) {
1460         case KVM_IRQCHIP_PIC_MASTER:
1461                 memcpy(&chip->chip.pic,
1462                         &pic_irqchip(kvm)->pics[0],
1463                         sizeof(struct kvm_pic_state));
1464                 break;
1465         case KVM_IRQCHIP_PIC_SLAVE:
1466                 memcpy(&chip->chip.pic,
1467                         &pic_irqchip(kvm)->pics[1],
1468                         sizeof(struct kvm_pic_state));
1469                 break;
1470         case KVM_IRQCHIP_IOAPIC:
1471                 memcpy(&chip->chip.ioapic,
1472                         ioapic_irqchip(kvm),
1473                         sizeof(struct kvm_ioapic_state));
1474                 break;
1475         default:
1476                 r = -EINVAL;
1477                 break;
1478         }
1479         return r;
1480 }
1481
1482 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1483 {
1484         int r;
1485
1486         r = 0;
1487         switch (chip->chip_id) {
1488         case KVM_IRQCHIP_PIC_MASTER:
1489                 memcpy(&pic_irqchip(kvm)->pics[0],
1490                         &chip->chip.pic,
1491                         sizeof(struct kvm_pic_state));
1492                 break;
1493         case KVM_IRQCHIP_PIC_SLAVE:
1494                 memcpy(&pic_irqchip(kvm)->pics[1],
1495                         &chip->chip.pic,
1496                         sizeof(struct kvm_pic_state));
1497                 break;
1498         case KVM_IRQCHIP_IOAPIC:
1499                 memcpy(ioapic_irqchip(kvm),
1500                         &chip->chip.ioapic,
1501                         sizeof(struct kvm_ioapic_state));
1502                 break;
1503         default:
1504                 r = -EINVAL;
1505                 break;
1506         }
1507         kvm_pic_update_irq(pic_irqchip(kvm));
1508         return r;
1509 }
1510
1511 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1512 {
1513         int r = 0;
1514
1515         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
1516         return r;
1517 }
1518
1519 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1520 {
1521         int r = 0;
1522
1523         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
1524         kvm_pit_load_count(kvm, 0, ps->channels[0].count);
1525         return r;
1526 }
1527
1528 /*
1529  * Get (and clear) the dirty memory log for a memory slot.
1530  */
1531 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1532                                       struct kvm_dirty_log *log)
1533 {
1534         int r;
1535         int n;
1536         struct kvm_memory_slot *memslot;
1537         int is_dirty = 0;
1538
1539         down_write(&kvm->slots_lock);
1540
1541         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1542         if (r)
1543                 goto out;
1544
1545         /* If nothing is dirty, don't bother messing with page tables. */
1546         if (is_dirty) {
1547                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1548                 kvm_flush_remote_tlbs(kvm);
1549                 memslot = &kvm->memslots[log->slot];
1550                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1551                 memset(memslot->dirty_bitmap, 0, n);
1552         }
1553         r = 0;
1554 out:
1555         up_write(&kvm->slots_lock);
1556         return r;
1557 }
1558
1559 long kvm_arch_vm_ioctl(struct file *filp,
1560                        unsigned int ioctl, unsigned long arg)
1561 {
1562         struct kvm *kvm = filp->private_data;
1563         void __user *argp = (void __user *)arg;
1564         int r = -EINVAL;
1565
1566         switch (ioctl) {
1567         case KVM_SET_TSS_ADDR:
1568                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1569                 if (r < 0)
1570                         goto out;
1571                 break;
1572         case KVM_SET_MEMORY_REGION: {
1573                 struct kvm_memory_region kvm_mem;
1574                 struct kvm_userspace_memory_region kvm_userspace_mem;
1575
1576                 r = -EFAULT;
1577                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1578                         goto out;
1579                 kvm_userspace_mem.slot = kvm_mem.slot;
1580                 kvm_userspace_mem.flags = kvm_mem.flags;
1581                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1582                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1583                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1584                 if (r)
1585                         goto out;
1586                 break;
1587         }
1588         case KVM_SET_NR_MMU_PAGES:
1589                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1590                 if (r)
1591                         goto out;
1592                 break;
1593         case KVM_GET_NR_MMU_PAGES:
1594                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1595                 break;
1596         case KVM_SET_MEMORY_ALIAS: {
1597                 struct kvm_memory_alias alias;
1598
1599                 r = -EFAULT;
1600                 if (copy_from_user(&alias, argp, sizeof alias))
1601                         goto out;
1602                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
1603                 if (r)
1604                         goto out;
1605                 break;
1606         }
1607         case KVM_CREATE_IRQCHIP:
1608                 r = -ENOMEM;
1609                 kvm->arch.vpic = kvm_create_pic(kvm);
1610                 if (kvm->arch.vpic) {
1611                         r = kvm_ioapic_init(kvm);
1612                         if (r) {
1613                                 kfree(kvm->arch.vpic);
1614                                 kvm->arch.vpic = NULL;
1615                                 goto out;
1616                         }
1617                 } else
1618                         goto out;
1619                 break;
1620         case KVM_CREATE_PIT:
1621                 r = -ENOMEM;
1622                 kvm->arch.vpit = kvm_create_pit(kvm);
1623                 if (kvm->arch.vpit)
1624                         r = 0;
1625                 break;
1626         case KVM_IRQ_LINE: {
1627                 struct kvm_irq_level irq_event;
1628
1629                 r = -EFAULT;
1630                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1631                         goto out;
1632                 if (irqchip_in_kernel(kvm)) {
1633                         mutex_lock(&kvm->lock);
1634                         if (irq_event.irq < 16)
1635                                 kvm_pic_set_irq(pic_irqchip(kvm),
1636                                         irq_event.irq,
1637                                         irq_event.level);
1638                         kvm_ioapic_set_irq(kvm->arch.vioapic,
1639                                         irq_event.irq,
1640                                         irq_event.level);
1641                         mutex_unlock(&kvm->lock);
1642                         r = 0;
1643                 }
1644                 break;
1645         }
1646         case KVM_GET_IRQCHIP: {
1647                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1648                 struct kvm_irqchip chip;
1649
1650                 r = -EFAULT;
1651                 if (copy_from_user(&chip, argp, sizeof chip))
1652                         goto out;
1653                 r = -ENXIO;
1654                 if (!irqchip_in_kernel(kvm))
1655                         goto out;
1656                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1657                 if (r)
1658                         goto out;
1659                 r = -EFAULT;
1660                 if (copy_to_user(argp, &chip, sizeof chip))
1661                         goto out;
1662                 r = 0;
1663                 break;
1664         }
1665         case KVM_SET_IRQCHIP: {
1666                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1667                 struct kvm_irqchip chip;
1668
1669                 r = -EFAULT;
1670                 if (copy_from_user(&chip, argp, sizeof chip))
1671                         goto out;
1672                 r = -ENXIO;
1673                 if (!irqchip_in_kernel(kvm))
1674                         goto out;
1675                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1676                 if (r)
1677                         goto out;
1678                 r = 0;
1679                 break;
1680         }
1681         case KVM_GET_PIT: {
1682                 struct kvm_pit_state ps;
1683                 r = -EFAULT;
1684                 if (copy_from_user(&ps, argp, sizeof ps))
1685                         goto out;
1686                 r = -ENXIO;
1687                 if (!kvm->arch.vpit)
1688                         goto out;
1689                 r = kvm_vm_ioctl_get_pit(kvm, &ps);
1690                 if (r)
1691                         goto out;
1692                 r = -EFAULT;
1693                 if (copy_to_user(argp, &ps, sizeof ps))
1694                         goto out;
1695                 r = 0;
1696                 break;
1697         }
1698         case KVM_SET_PIT: {
1699                 struct kvm_pit_state ps;
1700                 r = -EFAULT;
1701                 if (copy_from_user(&ps, argp, sizeof ps))
1702                         goto out;
1703                 r = -ENXIO;
1704                 if (!kvm->arch.vpit)
1705                         goto out;
1706                 r = kvm_vm_ioctl_set_pit(kvm, &ps);
1707                 if (r)
1708                         goto out;
1709                 r = 0;
1710                 break;
1711         }
1712         default:
1713                 ;
1714         }
1715 out:
1716         return r;
1717 }
1718
1719 static void kvm_init_msr_list(void)
1720 {
1721         u32 dummy[2];
1722         unsigned i, j;
1723
1724         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1725                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1726                         continue;
1727                 if (j < i)
1728                         msrs_to_save[j] = msrs_to_save[i];
1729                 j++;
1730         }
1731         num_msrs_to_save = j;
1732 }
1733
1734 /*
1735  * Only apic need an MMIO device hook, so shortcut now..
1736  */
1737 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1738                                                 gpa_t addr)
1739 {
1740         struct kvm_io_device *dev;
1741
1742         if (vcpu->arch.apic) {
1743                 dev = &vcpu->arch.apic->dev;
1744                 if (dev->in_range(dev, addr))
1745                         return dev;
1746         }
1747         return NULL;
1748 }
1749
1750
1751 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1752                                                 gpa_t addr)
1753 {
1754         struct kvm_io_device *dev;
1755
1756         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1757         if (dev == NULL)
1758                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1759         return dev;
1760 }
1761
1762 int emulator_read_std(unsigned long addr,
1763                              void *val,
1764                              unsigned int bytes,
1765                              struct kvm_vcpu *vcpu)
1766 {
1767         void *data = val;
1768         int r = X86EMUL_CONTINUE;
1769
1770         down_read(&vcpu->kvm->slots_lock);
1771         while (bytes) {
1772                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1773                 unsigned offset = addr & (PAGE_SIZE-1);
1774                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1775                 int ret;
1776
1777                 if (gpa == UNMAPPED_GVA) {
1778                         r = X86EMUL_PROPAGATE_FAULT;
1779                         goto out;
1780                 }
1781                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1782                 if (ret < 0) {
1783                         r = X86EMUL_UNHANDLEABLE;
1784                         goto out;
1785                 }
1786
1787                 bytes -= tocopy;
1788                 data += tocopy;
1789                 addr += tocopy;
1790         }
1791 out:
1792         up_read(&vcpu->kvm->slots_lock);
1793         return r;
1794 }
1795 EXPORT_SYMBOL_GPL(emulator_read_std);
1796
1797 static int emulator_read_emulated(unsigned long addr,
1798                                   void *val,
1799                                   unsigned int bytes,
1800                                   struct kvm_vcpu *vcpu)
1801 {
1802         struct kvm_io_device *mmio_dev;
1803         gpa_t                 gpa;
1804
1805         if (vcpu->mmio_read_completed) {
1806                 memcpy(val, vcpu->mmio_data, bytes);
1807                 vcpu->mmio_read_completed = 0;
1808                 return X86EMUL_CONTINUE;
1809         }
1810
1811         down_read(&vcpu->kvm->slots_lock);
1812         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1813         up_read(&vcpu->kvm->slots_lock);
1814
1815         /* For APIC access vmexit */
1816         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1817                 goto mmio;
1818
1819         if (emulator_read_std(addr, val, bytes, vcpu)
1820                         == X86EMUL_CONTINUE)
1821                 return X86EMUL_CONTINUE;
1822         if (gpa == UNMAPPED_GVA)
1823                 return X86EMUL_PROPAGATE_FAULT;
1824
1825 mmio:
1826         /*
1827          * Is this MMIO handled locally?
1828          */
1829         mutex_lock(&vcpu->kvm->lock);
1830         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1831         if (mmio_dev) {
1832                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1833                 mutex_unlock(&vcpu->kvm->lock);
1834                 return X86EMUL_CONTINUE;
1835         }
1836         mutex_unlock(&vcpu->kvm->lock);
1837
1838         vcpu->mmio_needed = 1;
1839         vcpu->mmio_phys_addr = gpa;
1840         vcpu->mmio_size = bytes;
1841         vcpu->mmio_is_write = 0;
1842
1843         return X86EMUL_UNHANDLEABLE;
1844 }
1845
1846 int __emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1847                           const void *val, int bytes)
1848 {
1849         int ret;
1850
1851         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1852         if (ret < 0)
1853                 return 0;
1854         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1855         return 1;
1856 }
1857
1858 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1859                         const void *val, int bytes)
1860 {
1861         int ret;
1862
1863         down_read(&vcpu->kvm->slots_lock);
1864         ret =__emulator_write_phys(vcpu, gpa, val, bytes);
1865         up_read(&vcpu->kvm->slots_lock);
1866         return ret;
1867 }
1868
1869 static int emulator_write_emulated_onepage(unsigned long addr,
1870                                            const void *val,
1871                                            unsigned int bytes,
1872                                            struct kvm_vcpu *vcpu)
1873 {
1874         struct kvm_io_device *mmio_dev;
1875         gpa_t                 gpa;
1876
1877         down_read(&vcpu->kvm->slots_lock);
1878         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1879         up_read(&vcpu->kvm->slots_lock);
1880
1881         if (gpa == UNMAPPED_GVA) {
1882                 kvm_inject_page_fault(vcpu, addr, 2);
1883                 return X86EMUL_PROPAGATE_FAULT;
1884         }
1885
1886         /* For APIC access vmexit */
1887         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1888                 goto mmio;
1889
1890         if (emulator_write_phys(vcpu, gpa, val, bytes))
1891                 return X86EMUL_CONTINUE;
1892
1893 mmio:
1894         /*
1895          * Is this MMIO handled locally?
1896          */
1897         mutex_lock(&vcpu->kvm->lock);
1898         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1899         if (mmio_dev) {
1900                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1901                 mutex_unlock(&vcpu->kvm->lock);
1902                 return X86EMUL_CONTINUE;
1903         }
1904         mutex_unlock(&vcpu->kvm->lock);
1905
1906         vcpu->mmio_needed = 1;
1907         vcpu->mmio_phys_addr = gpa;
1908         vcpu->mmio_size = bytes;
1909         vcpu->mmio_is_write = 1;
1910         memcpy(vcpu->mmio_data, val, bytes);
1911
1912         return X86EMUL_CONTINUE;
1913 }
1914
1915 int emulator_write_emulated(unsigned long addr,
1916                                    const void *val,
1917                                    unsigned int bytes,
1918                                    struct kvm_vcpu *vcpu)
1919 {
1920         /* Crossing a page boundary? */
1921         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1922                 int rc, now;
1923
1924                 now = -addr & ~PAGE_MASK;
1925                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1926                 if (rc != X86EMUL_CONTINUE)
1927                         return rc;
1928                 addr += now;
1929                 val += now;
1930                 bytes -= now;
1931         }
1932         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1933 }
1934 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1935
1936 static int emulator_cmpxchg_emulated(unsigned long addr,
1937                                      const void *old,
1938                                      const void *new,
1939                                      unsigned int bytes,
1940                                      struct kvm_vcpu *vcpu)
1941 {
1942         static int reported;
1943
1944         if (!reported) {
1945                 reported = 1;
1946                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1947         }
1948 #ifndef CONFIG_X86_64
1949         /* guests cmpxchg8b have to be emulated atomically */
1950         if (bytes == 8) {
1951                 gpa_t gpa;
1952                 struct page *page;
1953                 char *kaddr;
1954                 u64 val;
1955
1956                 down_read(&vcpu->kvm->slots_lock);
1957                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1958
1959                 if (gpa == UNMAPPED_GVA ||
1960                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1961                         goto emul_write;
1962
1963                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
1964                         goto emul_write;
1965
1966                 val = *(u64 *)new;
1967
1968                 down_read(&current->mm->mmap_sem);
1969                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1970                 up_read(&current->mm->mmap_sem);
1971
1972                 kaddr = kmap_atomic(page, KM_USER0);
1973                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
1974                 kunmap_atomic(kaddr, KM_USER0);
1975                 kvm_release_page_dirty(page);
1976         emul_write:
1977                 up_read(&vcpu->kvm->slots_lock);
1978         }
1979 #endif
1980
1981         return emulator_write_emulated(addr, new, bytes, vcpu);
1982 }
1983
1984 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1985 {
1986         return kvm_x86_ops->get_segment_base(vcpu, seg);
1987 }
1988
1989 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1990 {
1991         return X86EMUL_CONTINUE;
1992 }
1993
1994 int emulate_clts(struct kvm_vcpu *vcpu)
1995 {
1996         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
1997         return X86EMUL_CONTINUE;
1998 }
1999
2000 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2001 {
2002         struct kvm_vcpu *vcpu = ctxt->vcpu;
2003
2004         switch (dr) {
2005         case 0 ... 3:
2006                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2007                 return X86EMUL_CONTINUE;
2008         default:
2009                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2010                 return X86EMUL_UNHANDLEABLE;
2011         }
2012 }
2013
2014 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2015 {
2016         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2017         int exception;
2018
2019         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2020         if (exception) {
2021                 /* FIXME: better handling */
2022                 return X86EMUL_UNHANDLEABLE;
2023         }
2024         return X86EMUL_CONTINUE;
2025 }
2026
2027 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2028 {
2029         static int reported;
2030         u8 opcodes[4];
2031         unsigned long rip = vcpu->arch.rip;
2032         unsigned long rip_linear;
2033
2034         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2035
2036         if (reported)
2037                 return;
2038
2039         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
2040
2041         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2042                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2043         reported = 1;
2044 }
2045 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2046
2047 static struct x86_emulate_ops emulate_ops = {
2048         .read_std            = emulator_read_std,
2049         .read_emulated       = emulator_read_emulated,
2050         .write_emulated      = emulator_write_emulated,
2051         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
2052 };
2053
2054 int emulate_instruction(struct kvm_vcpu *vcpu,
2055                         struct kvm_run *run,
2056                         unsigned long cr2,
2057                         u16 error_code,
2058                         int emulation_type)
2059 {
2060         int r;
2061         struct decode_cache *c;
2062
2063         vcpu->arch.mmio_fault_cr2 = cr2;
2064         kvm_x86_ops->cache_regs(vcpu);
2065
2066         vcpu->mmio_is_write = 0;
2067         vcpu->arch.pio.string = 0;
2068
2069         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2070                 int cs_db, cs_l;
2071                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2072
2073                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2074                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
2075                 vcpu->arch.emulate_ctxt.mode =
2076                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2077                         ? X86EMUL_MODE_REAL : cs_l
2078                         ? X86EMUL_MODE_PROT64 : cs_db
2079                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2080
2081                 if (vcpu->arch.emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
2082                         vcpu->arch.emulate_ctxt.cs_base = 0;
2083                         vcpu->arch.emulate_ctxt.ds_base = 0;
2084                         vcpu->arch.emulate_ctxt.es_base = 0;
2085                         vcpu->arch.emulate_ctxt.ss_base = 0;
2086                 } else {
2087                         vcpu->arch.emulate_ctxt.cs_base =
2088                                         get_segment_base(vcpu, VCPU_SREG_CS);
2089                         vcpu->arch.emulate_ctxt.ds_base =
2090                                         get_segment_base(vcpu, VCPU_SREG_DS);
2091                         vcpu->arch.emulate_ctxt.es_base =
2092                                         get_segment_base(vcpu, VCPU_SREG_ES);
2093                         vcpu->arch.emulate_ctxt.ss_base =
2094                                         get_segment_base(vcpu, VCPU_SREG_SS);
2095                 }
2096
2097                 vcpu->arch.emulate_ctxt.gs_base =
2098                                         get_segment_base(vcpu, VCPU_SREG_GS);
2099                 vcpu->arch.emulate_ctxt.fs_base =
2100                                         get_segment_base(vcpu, VCPU_SREG_FS);
2101
2102                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2103
2104                 /* Reject the instructions other than VMCALL/VMMCALL when
2105                  * try to emulate invalid opcode */
2106                 c = &vcpu->arch.emulate_ctxt.decode;
2107                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
2108                     (!(c->twobyte && c->b == 0x01 &&
2109                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
2110                        c->modrm_mod == 3 && c->modrm_rm == 1)))
2111                         return EMULATE_FAIL;
2112
2113                 ++vcpu->stat.insn_emulation;
2114                 if (r)  {
2115                         ++vcpu->stat.insn_emulation_fail;
2116                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2117                                 return EMULATE_DONE;
2118                         return EMULATE_FAIL;
2119                 }
2120         }
2121
2122         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2123
2124         if (vcpu->arch.pio.string)
2125                 return EMULATE_DO_MMIO;
2126
2127         if ((r || vcpu->mmio_is_write) && run) {
2128                 run->exit_reason = KVM_EXIT_MMIO;
2129                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2130                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2131                 run->mmio.len = vcpu->mmio_size;
2132                 run->mmio.is_write = vcpu->mmio_is_write;
2133         }
2134
2135         if (r) {
2136                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2137                         return EMULATE_DONE;
2138                 if (!vcpu->mmio_needed) {
2139                         kvm_report_emulation_failure(vcpu, "mmio");
2140                         return EMULATE_FAIL;
2141                 }
2142                 return EMULATE_DO_MMIO;
2143         }
2144
2145         kvm_x86_ops->decache_regs(vcpu);
2146         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2147
2148         if (vcpu->mmio_is_write) {
2149                 vcpu->mmio_needed = 0;
2150                 return EMULATE_DO_MMIO;
2151         }
2152
2153         return EMULATE_DONE;
2154 }
2155 EXPORT_SYMBOL_GPL(emulate_instruction);
2156
2157 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
2158 {
2159         int i;
2160
2161         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
2162                 if (vcpu->arch.pio.guest_pages[i]) {
2163                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
2164                         vcpu->arch.pio.guest_pages[i] = NULL;
2165                 }
2166 }
2167
2168 static int pio_copy_data(struct kvm_vcpu *vcpu)
2169 {
2170         void *p = vcpu->arch.pio_data;
2171         void *q;
2172         unsigned bytes;
2173         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
2174
2175         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
2176                  PAGE_KERNEL);
2177         if (!q) {
2178                 free_pio_guest_pages(vcpu);
2179                 return -ENOMEM;
2180         }
2181         q += vcpu->arch.pio.guest_page_offset;
2182         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2183         if (vcpu->arch.pio.in)
2184                 memcpy(q, p, bytes);
2185         else
2186                 memcpy(p, q, bytes);
2187         q -= vcpu->arch.pio.guest_page_offset;
2188         vunmap(q);
2189         free_pio_guest_pages(vcpu);
2190         return 0;
2191 }
2192
2193 int complete_pio(struct kvm_vcpu *vcpu)
2194 {
2195         struct kvm_pio_request *io = &vcpu->arch.pio;
2196         long delta;
2197         int r;
2198
2199         kvm_x86_ops->cache_regs(vcpu);
2200
2201         if (!io->string) {
2202                 if (io->in)
2203                         memcpy(&vcpu->arch.regs[VCPU_REGS_RAX], vcpu->arch.pio_data,
2204                                io->size);
2205         } else {
2206                 if (io->in) {
2207                         r = pio_copy_data(vcpu);
2208                         if (r) {
2209                                 kvm_x86_ops->cache_regs(vcpu);
2210                                 return r;
2211                         }
2212                 }
2213
2214                 delta = 1;
2215                 if (io->rep) {
2216                         delta *= io->cur_count;
2217                         /*
2218                          * The size of the register should really depend on
2219                          * current address size.
2220                          */
2221                         vcpu->arch.regs[VCPU_REGS_RCX] -= delta;
2222                 }
2223                 if (io->down)
2224                         delta = -delta;
2225                 delta *= io->size;
2226                 if (io->in)
2227                         vcpu->arch.regs[VCPU_REGS_RDI] += delta;
2228                 else
2229                         vcpu->arch.regs[VCPU_REGS_RSI] += delta;
2230         }
2231
2232         kvm_x86_ops->decache_regs(vcpu);
2233
2234         io->count -= io->cur_count;
2235         io->cur_count = 0;
2236
2237         return 0;
2238 }
2239
2240 static void kernel_pio(struct kvm_io_device *pio_dev,
2241                        struct kvm_vcpu *vcpu,
2242                        void *pd)
2243 {
2244         /* TODO: String I/O for in kernel device */
2245
2246         mutex_lock(&vcpu->kvm->lock);
2247         if (vcpu->arch.pio.in)
2248                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2249                                   vcpu->arch.pio.size,
2250                                   pd);
2251         else
2252                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2253                                    vcpu->arch.pio.size,
2254                                    pd);
2255         mutex_unlock(&vcpu->kvm->lock);
2256 }
2257
2258 static void pio_string_write(struct kvm_io_device *pio_dev,
2259                              struct kvm_vcpu *vcpu)
2260 {
2261         struct kvm_pio_request *io = &vcpu->arch.pio;
2262         void *pd = vcpu->arch.pio_data;
2263         int i;
2264
2265         mutex_lock(&vcpu->kvm->lock);
2266         for (i = 0; i < io->cur_count; i++) {
2267                 kvm_iodevice_write(pio_dev, io->port,
2268                                    io->size,
2269                                    pd);
2270                 pd += io->size;
2271         }
2272         mutex_unlock(&vcpu->kvm->lock);
2273 }
2274
2275 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2276                                                gpa_t addr)
2277 {
2278         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
2279 }
2280
2281 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2282                   int size, unsigned port)
2283 {
2284         struct kvm_io_device *pio_dev;
2285
2286         vcpu->run->exit_reason = KVM_EXIT_IO;
2287         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2288         vcpu->run->io.size = vcpu->arch.pio.size = size;
2289         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2290         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2291         vcpu->run->io.port = vcpu->arch.pio.port = port;
2292         vcpu->arch.pio.in = in;
2293         vcpu->arch.pio.string = 0;
2294         vcpu->arch.pio.down = 0;
2295         vcpu->arch.pio.guest_page_offset = 0;
2296         vcpu->arch.pio.rep = 0;
2297
2298         kvm_x86_ops->cache_regs(vcpu);
2299         memcpy(vcpu->arch.pio_data, &vcpu->arch.regs[VCPU_REGS_RAX], 4);
2300         kvm_x86_ops->decache_regs(vcpu);
2301
2302         kvm_x86_ops->skip_emulated_instruction(vcpu);
2303
2304         pio_dev = vcpu_find_pio_dev(vcpu, port);
2305         if (pio_dev) {
2306                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2307                 complete_pio(vcpu);
2308                 return 1;
2309         }
2310         return 0;
2311 }
2312 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2313
2314 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2315                   int size, unsigned long count, int down,
2316                   gva_t address, int rep, unsigned port)
2317 {
2318         unsigned now, in_page;
2319         int i, ret = 0;
2320         int nr_pages = 1;
2321         struct page *page;
2322         struct kvm_io_device *pio_dev;
2323
2324         vcpu->run->exit_reason = KVM_EXIT_IO;
2325         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2326         vcpu->run->io.size = vcpu->arch.pio.size = size;
2327         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2328         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2329         vcpu->run->io.port = vcpu->arch.pio.port = port;
2330         vcpu->arch.pio.in = in;
2331         vcpu->arch.pio.string = 1;
2332         vcpu->arch.pio.down = down;
2333         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2334         vcpu->arch.pio.rep = rep;
2335
2336         if (!count) {
2337                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2338                 return 1;
2339         }
2340
2341         if (!down)
2342                 in_page = PAGE_SIZE - offset_in_page(address);
2343         else
2344                 in_page = offset_in_page(address) + size;
2345         now = min(count, (unsigned long)in_page / size);
2346         if (!now) {
2347                 /*
2348                  * String I/O straddles page boundary.  Pin two guest pages
2349                  * so that we satisfy atomicity constraints.  Do just one
2350                  * transaction to avoid complexity.
2351                  */
2352                 nr_pages = 2;
2353                 now = 1;
2354         }
2355         if (down) {
2356                 /*
2357                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2358                  */
2359                 pr_unimpl(vcpu, "guest string pio down\n");
2360                 kvm_inject_gp(vcpu, 0);
2361                 return 1;
2362         }
2363         vcpu->run->io.count = now;
2364         vcpu->arch.pio.cur_count = now;
2365
2366         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2367                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2368
2369         for (i = 0; i < nr_pages; ++i) {
2370                 down_read(&vcpu->kvm->slots_lock);
2371                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2372                 vcpu->arch.pio.guest_pages[i] = page;
2373                 up_read(&vcpu->kvm->slots_lock);
2374                 if (!page) {
2375                         kvm_inject_gp(vcpu, 0);
2376                         free_pio_guest_pages(vcpu);
2377                         return 1;
2378                 }
2379         }
2380
2381         pio_dev = vcpu_find_pio_dev(vcpu, port);
2382         if (!vcpu->arch.pio.in) {
2383                 /* string PIO write */
2384                 ret = pio_copy_data(vcpu);
2385                 if (ret >= 0 && pio_dev) {
2386                         pio_string_write(pio_dev, vcpu);
2387                         complete_pio(vcpu);
2388                         if (vcpu->arch.pio.count == 0)
2389                                 ret = 1;
2390                 }
2391         } else if (pio_dev)
2392                 pr_unimpl(vcpu, "no string pio read support yet, "
2393                        "port %x size %d count %ld\n",
2394                         port, size, count);
2395
2396         return ret;
2397 }
2398 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2399
2400 int kvm_arch_init(void *opaque)
2401 {
2402         int r;
2403         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2404
2405         if (kvm_x86_ops) {
2406                 printk(KERN_ERR "kvm: already loaded the other module\n");
2407                 r = -EEXIST;
2408                 goto out;
2409         }
2410
2411         if (!ops->cpu_has_kvm_support()) {
2412                 printk(KERN_ERR "kvm: no hardware support\n");
2413                 r = -EOPNOTSUPP;
2414                 goto out;
2415         }
2416         if (ops->disabled_by_bios()) {
2417                 printk(KERN_ERR "kvm: disabled by bios\n");
2418                 r = -EOPNOTSUPP;
2419                 goto out;
2420         }
2421
2422         r = kvm_mmu_module_init();
2423         if (r)
2424                 goto out;
2425
2426         kvm_init_msr_list();
2427
2428         kvm_x86_ops = ops;
2429         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2430         return 0;
2431
2432 out:
2433         return r;
2434 }
2435
2436 void kvm_arch_exit(void)
2437 {
2438         kvm_x86_ops = NULL;
2439         kvm_mmu_module_exit();
2440 }
2441
2442 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2443 {
2444         ++vcpu->stat.halt_exits;
2445         if (irqchip_in_kernel(vcpu->kvm)) {
2446                 vcpu->arch.mp_state = VCPU_MP_STATE_HALTED;
2447                 kvm_vcpu_block(vcpu);
2448                 if (vcpu->arch.mp_state != VCPU_MP_STATE_RUNNABLE)
2449                         return -EINTR;
2450                 return 1;
2451         } else {
2452                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2453                 return 0;
2454         }
2455 }
2456 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2457
2458 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2459                            unsigned long a1)
2460 {
2461         if (is_long_mode(vcpu))
2462                 return a0;
2463         else
2464                 return a0 | ((gpa_t)a1 << 32);
2465 }
2466
2467 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2468 {
2469         unsigned long nr, a0, a1, a2, a3, ret;
2470         int r = 1;
2471
2472         kvm_x86_ops->cache_regs(vcpu);
2473
2474         nr = vcpu->arch.regs[VCPU_REGS_RAX];
2475         a0 = vcpu->arch.regs[VCPU_REGS_RBX];
2476         a1 = vcpu->arch.regs[VCPU_REGS_RCX];
2477         a2 = vcpu->arch.regs[VCPU_REGS_RDX];
2478         a3 = vcpu->arch.regs[VCPU_REGS_RSI];
2479
2480         if (!is_long_mode(vcpu)) {
2481                 nr &= 0xFFFFFFFF;
2482                 a0 &= 0xFFFFFFFF;
2483                 a1 &= 0xFFFFFFFF;
2484                 a2 &= 0xFFFFFFFF;
2485                 a3 &= 0xFFFFFFFF;
2486         }
2487
2488         switch (nr) {
2489         case KVM_HC_VAPIC_POLL_IRQ:
2490                 ret = 0;
2491                 break;
2492         case KVM_HC_MMU_OP:
2493                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2494                 break;
2495         default:
2496                 ret = -KVM_ENOSYS;
2497                 break;
2498         }
2499         vcpu->arch.regs[VCPU_REGS_RAX] = ret;
2500         kvm_x86_ops->decache_regs(vcpu);
2501         ++vcpu->stat.hypercalls;
2502         return r;
2503 }
2504 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2505
2506 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2507 {
2508         char instruction[3];
2509         int ret = 0;
2510
2511
2512         /*
2513          * Blow out the MMU to ensure that no other VCPU has an active mapping
2514          * to ensure that the updated hypercall appears atomically across all
2515          * VCPUs.
2516          */
2517         kvm_mmu_zap_all(vcpu->kvm);
2518
2519         kvm_x86_ops->cache_regs(vcpu);
2520         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2521         if (emulator_write_emulated(vcpu->arch.rip, instruction, 3, vcpu)
2522             != X86EMUL_CONTINUE)
2523                 ret = -EFAULT;
2524
2525         return ret;
2526 }
2527
2528 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2529 {
2530         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2531 }
2532
2533 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2534 {
2535         struct descriptor_table dt = { limit, base };
2536
2537         kvm_x86_ops->set_gdt(vcpu, &dt);
2538 }
2539
2540 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2541 {
2542         struct descriptor_table dt = { limit, base };
2543
2544         kvm_x86_ops->set_idt(vcpu, &dt);
2545 }
2546
2547 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2548                    unsigned long *rflags)
2549 {
2550         kvm_lmsw(vcpu, msw);
2551         *rflags = kvm_x86_ops->get_rflags(vcpu);
2552 }
2553
2554 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2555 {
2556         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2557         switch (cr) {
2558         case 0:
2559                 return vcpu->arch.cr0;
2560         case 2:
2561                 return vcpu->arch.cr2;
2562         case 3:
2563                 return vcpu->arch.cr3;
2564         case 4:
2565                 return vcpu->arch.cr4;
2566         case 8:
2567                 return kvm_get_cr8(vcpu);
2568         default:
2569                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2570                 return 0;
2571         }
2572 }
2573
2574 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2575                      unsigned long *rflags)
2576 {
2577         switch (cr) {
2578         case 0:
2579                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2580                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2581                 break;
2582         case 2:
2583                 vcpu->arch.cr2 = val;
2584                 break;
2585         case 3:
2586                 kvm_set_cr3(vcpu, val);
2587                 break;
2588         case 4:
2589                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2590                 break;
2591         case 8:
2592                 kvm_set_cr8(vcpu, val & 0xfUL);
2593                 break;
2594         default:
2595                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2596         }
2597 }
2598
2599 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2600 {
2601         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2602         int j, nent = vcpu->arch.cpuid_nent;
2603
2604         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2605         /* when no next entry is found, the current entry[i] is reselected */
2606         for (j = i + 1; j == i; j = (j + 1) % nent) {
2607                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2608                 if (ej->function == e->function) {
2609                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2610                         return j;
2611                 }
2612         }
2613         return 0; /* silence gcc, even though control never reaches here */
2614 }
2615
2616 /* find an entry with matching function, matching index (if needed), and that
2617  * should be read next (if it's stateful) */
2618 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2619         u32 function, u32 index)
2620 {
2621         if (e->function != function)
2622                 return 0;
2623         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2624                 return 0;
2625         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2626                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2627                 return 0;
2628         return 1;
2629 }
2630
2631 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2632 {
2633         int i;
2634         u32 function, index;
2635         struct kvm_cpuid_entry2 *e, *best;
2636
2637         kvm_x86_ops->cache_regs(vcpu);
2638         function = vcpu->arch.regs[VCPU_REGS_RAX];
2639         index = vcpu->arch.regs[VCPU_REGS_RCX];
2640         vcpu->arch.regs[VCPU_REGS_RAX] = 0;
2641         vcpu->arch.regs[VCPU_REGS_RBX] = 0;
2642         vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2643         vcpu->arch.regs[VCPU_REGS_RDX] = 0;
2644         best = NULL;
2645         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2646                 e = &vcpu->arch.cpuid_entries[i];
2647                 if (is_matching_cpuid_entry(e, function, index)) {
2648                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2649                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2650                         best = e;
2651                         break;
2652                 }
2653                 /*
2654                  * Both basic or both extended?
2655                  */
2656                 if (((e->function ^ function) & 0x80000000) == 0)
2657                         if (!best || e->function > best->function)
2658                                 best = e;
2659         }
2660         if (best) {
2661                 vcpu->arch.regs[VCPU_REGS_RAX] = best->eax;
2662                 vcpu->arch.regs[VCPU_REGS_RBX] = best->ebx;
2663                 vcpu->arch.regs[VCPU_REGS_RCX] = best->ecx;
2664                 vcpu->arch.regs[VCPU_REGS_RDX] = best->edx;
2665         }
2666         kvm_x86_ops->decache_regs(vcpu);
2667         kvm_x86_ops->skip_emulated_instruction(vcpu);
2668 }
2669 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2670
2671 /*
2672  * Check if userspace requested an interrupt window, and that the
2673  * interrupt window is open.
2674  *
2675  * No need to exit to userspace if we already have an interrupt queued.
2676  */
2677 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2678                                           struct kvm_run *kvm_run)
2679 {
2680         return (!vcpu->arch.irq_summary &&
2681                 kvm_run->request_interrupt_window &&
2682                 vcpu->arch.interrupt_window_open &&
2683                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2684 }
2685
2686 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2687                               struct kvm_run *kvm_run)
2688 {
2689         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2690         kvm_run->cr8 = kvm_get_cr8(vcpu);
2691         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2692         if (irqchip_in_kernel(vcpu->kvm))
2693                 kvm_run->ready_for_interrupt_injection = 1;
2694         else
2695                 kvm_run->ready_for_interrupt_injection =
2696                                         (vcpu->arch.interrupt_window_open &&
2697                                          vcpu->arch.irq_summary == 0);
2698 }
2699
2700 static void vapic_enter(struct kvm_vcpu *vcpu)
2701 {
2702         struct kvm_lapic *apic = vcpu->arch.apic;
2703         struct page *page;
2704
2705         if (!apic || !apic->vapic_addr)
2706                 return;
2707
2708         down_read(&current->mm->mmap_sem);
2709         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2710         up_read(&current->mm->mmap_sem);
2711
2712         vcpu->arch.apic->vapic_page = page;
2713 }
2714
2715 static void vapic_exit(struct kvm_vcpu *vcpu)
2716 {
2717         struct kvm_lapic *apic = vcpu->arch.apic;
2718
2719         if (!apic || !apic->vapic_addr)
2720                 return;
2721
2722         kvm_release_page_dirty(apic->vapic_page);
2723         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2724 }
2725
2726 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2727 {
2728         int r;
2729
2730         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
2731                 pr_debug("vcpu %d received sipi with vector # %x\n",
2732                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
2733                 kvm_lapic_reset(vcpu);
2734                 r = kvm_x86_ops->vcpu_reset(vcpu);
2735                 if (r)
2736                         return r;
2737                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
2738         }
2739
2740         vapic_enter(vcpu);
2741
2742 preempted:
2743         if (vcpu->guest_debug.enabled)
2744                 kvm_x86_ops->guest_debug_pre(vcpu);
2745
2746 again:
2747         if (vcpu->requests)
2748                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
2749                         kvm_mmu_unload(vcpu);
2750
2751         r = kvm_mmu_reload(vcpu);
2752         if (unlikely(r))
2753                 goto out;
2754
2755         if (vcpu->requests) {
2756                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
2757                         __kvm_migrate_apic_timer(vcpu);
2758                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
2759                                        &vcpu->requests)) {
2760                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
2761                         r = 0;
2762                         goto out;
2763                 }
2764                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
2765                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2766                         r = 0;
2767                         goto out;
2768                 }
2769         }
2770
2771         kvm_inject_pending_timer_irqs(vcpu);
2772
2773         preempt_disable();
2774
2775         kvm_x86_ops->prepare_guest_switch(vcpu);
2776         kvm_load_guest_fpu(vcpu);
2777
2778         local_irq_disable();
2779
2780         if (need_resched()) {
2781                 local_irq_enable();
2782                 preempt_enable();
2783                 r = 1;
2784                 goto out;
2785         }
2786
2787         if (vcpu->requests)
2788                 if (test_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests)) {
2789                         local_irq_enable();
2790                         preempt_enable();
2791                         r = 1;
2792                         goto out;
2793                 }
2794
2795         if (signal_pending(current)) {
2796                 local_irq_enable();
2797                 preempt_enable();
2798                 r = -EINTR;
2799                 kvm_run->exit_reason = KVM_EXIT_INTR;
2800                 ++vcpu->stat.signal_exits;
2801                 goto out;
2802         }
2803
2804         if (vcpu->arch.exception.pending)
2805                 __queue_exception(vcpu);
2806         else if (irqchip_in_kernel(vcpu->kvm))
2807                 kvm_x86_ops->inject_pending_irq(vcpu);
2808         else
2809                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
2810
2811         kvm_lapic_sync_to_vapic(vcpu);
2812
2813         vcpu->guest_mode = 1;
2814         kvm_guest_enter();
2815
2816         if (vcpu->requests)
2817                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2818                         kvm_x86_ops->tlb_flush(vcpu);
2819
2820         kvm_x86_ops->run(vcpu, kvm_run);
2821
2822         vcpu->guest_mode = 0;
2823         local_irq_enable();
2824
2825         ++vcpu->stat.exits;
2826
2827         /*
2828          * We must have an instruction between local_irq_enable() and
2829          * kvm_guest_exit(), so the timer interrupt isn't delayed by
2830          * the interrupt shadow.  The stat.exits increment will do nicely.
2831          * But we need to prevent reordering, hence this barrier():
2832          */
2833         barrier();
2834
2835         kvm_guest_exit();
2836
2837         preempt_enable();
2838
2839         /*
2840          * Profile KVM exit RIPs:
2841          */
2842         if (unlikely(prof_on == KVM_PROFILING)) {
2843                 kvm_x86_ops->cache_regs(vcpu);
2844                 profile_hit(KVM_PROFILING, (void *)vcpu->arch.rip);
2845         }
2846
2847         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
2848                 vcpu->arch.exception.pending = false;
2849
2850         kvm_lapic_sync_from_vapic(vcpu);
2851
2852         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2853
2854         if (r > 0) {
2855                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2856                         r = -EINTR;
2857                         kvm_run->exit_reason = KVM_EXIT_INTR;
2858                         ++vcpu->stat.request_irq_exits;
2859                         goto out;
2860                 }
2861                 if (!need_resched())
2862                         goto again;
2863         }
2864
2865 out:
2866         if (r > 0) {
2867                 kvm_resched(vcpu);
2868                 goto preempted;
2869         }
2870
2871         post_kvm_run_save(vcpu, kvm_run);
2872
2873         vapic_exit(vcpu);
2874
2875         return r;
2876 }
2877
2878 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2879 {
2880         int r;
2881         sigset_t sigsaved;
2882
2883         vcpu_load(vcpu);
2884
2885         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
2886                 kvm_vcpu_block(vcpu);
2887                 vcpu_put(vcpu);
2888                 return -EAGAIN;
2889         }
2890
2891         if (vcpu->sigset_active)
2892                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2893
2894         /* re-sync apic's tpr */
2895         if (!irqchip_in_kernel(vcpu->kvm))
2896                 kvm_set_cr8(vcpu, kvm_run->cr8);
2897
2898         if (vcpu->arch.pio.cur_count) {
2899                 r = complete_pio(vcpu);
2900                 if (r)
2901                         goto out;
2902         }
2903 #if CONFIG_HAS_IOMEM
2904         if (vcpu->mmio_needed) {
2905                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2906                 vcpu->mmio_read_completed = 1;
2907                 vcpu->mmio_needed = 0;
2908                 r = emulate_instruction(vcpu, kvm_run,
2909                                         vcpu->arch.mmio_fault_cr2, 0,
2910                                         EMULTYPE_NO_DECODE);
2911                 if (r == EMULATE_DO_MMIO) {
2912                         /*
2913                          * Read-modify-write.  Back to userspace.
2914                          */
2915                         r = 0;
2916                         goto out;
2917                 }
2918         }
2919 #endif
2920         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2921                 kvm_x86_ops->cache_regs(vcpu);
2922                 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2923                 kvm_x86_ops->decache_regs(vcpu);
2924         }
2925
2926         r = __vcpu_run(vcpu, kvm_run);
2927
2928 out:
2929         if (vcpu->sigset_active)
2930                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2931
2932         vcpu_put(vcpu);
2933         return r;
2934 }
2935
2936 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2937 {
2938         vcpu_load(vcpu);
2939
2940         kvm_x86_ops->cache_regs(vcpu);
2941
2942         regs->rax = vcpu->arch.regs[VCPU_REGS_RAX];
2943         regs->rbx = vcpu->arch.regs[VCPU_REGS_RBX];
2944         regs->rcx = vcpu->arch.regs[VCPU_REGS_RCX];
2945         regs->rdx = vcpu->arch.regs[VCPU_REGS_RDX];
2946         regs->rsi = vcpu->arch.regs[VCPU_REGS_RSI];
2947         regs->rdi = vcpu->arch.regs[VCPU_REGS_RDI];
2948         regs->rsp = vcpu->arch.regs[VCPU_REGS_RSP];
2949         regs->rbp = vcpu->arch.regs[VCPU_REGS_RBP];
2950 #ifdef CONFIG_X86_64
2951         regs->r8 = vcpu->arch.regs[VCPU_REGS_R8];
2952         regs->r9 = vcpu->arch.regs[VCPU_REGS_R9];
2953         regs->r10 = vcpu->arch.regs[VCPU_REGS_R10];
2954         regs->r11 = vcpu->arch.regs[VCPU_REGS_R11];
2955         regs->r12 = vcpu->arch.regs[VCPU_REGS_R12];
2956         regs->r13 = vcpu->arch.regs[VCPU_REGS_R13];
2957         regs->r14 = vcpu->arch.regs[VCPU_REGS_R14];
2958         regs->r15 = vcpu->arch.regs[VCPU_REGS_R15];
2959 #endif
2960
2961         regs->rip = vcpu->arch.rip;
2962         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2963
2964         /*
2965          * Don't leak debug flags in case they were set for guest debugging
2966          */
2967         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2968                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2969
2970         vcpu_put(vcpu);
2971
2972         return 0;
2973 }
2974
2975 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2976 {
2977         vcpu_load(vcpu);
2978
2979         vcpu->arch.regs[VCPU_REGS_RAX] = regs->rax;
2980         vcpu->arch.regs[VCPU_REGS_RBX] = regs->rbx;
2981         vcpu->arch.regs[VCPU_REGS_RCX] = regs->rcx;
2982         vcpu->arch.regs[VCPU_REGS_RDX] = regs->rdx;
2983         vcpu->arch.regs[VCPU_REGS_RSI] = regs->rsi;
2984         vcpu->arch.regs[VCPU_REGS_RDI] = regs->rdi;
2985         vcpu->arch.regs[VCPU_REGS_RSP] = regs->rsp;
2986         vcpu->arch.regs[VCPU_REGS_RBP] = regs->rbp;
2987 #ifdef CONFIG_X86_64
2988         vcpu->arch.regs[VCPU_REGS_R8] = regs->r8;
2989         vcpu->arch.regs[VCPU_REGS_R9] = regs->r9;
2990         vcpu->arch.regs[VCPU_REGS_R10] = regs->r10;
2991         vcpu->arch.regs[VCPU_REGS_R11] = regs->r11;
2992         vcpu->arch.regs[VCPU_REGS_R12] = regs->r12;
2993         vcpu->arch.regs[VCPU_REGS_R13] = regs->r13;
2994         vcpu->arch.regs[VCPU_REGS_R14] = regs->r14;
2995         vcpu->arch.regs[VCPU_REGS_R15] = regs->r15;
2996 #endif
2997
2998         vcpu->arch.rip = regs->rip;
2999         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
3000
3001         kvm_x86_ops->decache_regs(vcpu);
3002
3003         vcpu_put(vcpu);
3004
3005         return 0;
3006 }
3007
3008 static void get_segment(struct kvm_vcpu *vcpu,
3009                         struct kvm_segment *var, int seg)
3010 {
3011         kvm_x86_ops->get_segment(vcpu, var, seg);
3012 }
3013
3014 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3015 {
3016         struct kvm_segment cs;
3017
3018         get_segment(vcpu, &cs, VCPU_SREG_CS);
3019         *db = cs.db;
3020         *l = cs.l;
3021 }
3022 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3023
3024 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3025                                   struct kvm_sregs *sregs)
3026 {
3027         struct descriptor_table dt;
3028         int pending_vec;
3029
3030         vcpu_load(vcpu);
3031
3032         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3033         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3034         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3035         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3036         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3037         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3038
3039         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3040         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3041
3042         kvm_x86_ops->get_idt(vcpu, &dt);
3043         sregs->idt.limit = dt.limit;
3044         sregs->idt.base = dt.base;
3045         kvm_x86_ops->get_gdt(vcpu, &dt);
3046         sregs->gdt.limit = dt.limit;
3047         sregs->gdt.base = dt.base;
3048
3049         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3050         sregs->cr0 = vcpu->arch.cr0;
3051         sregs->cr2 = vcpu->arch.cr2;
3052         sregs->cr3 = vcpu->arch.cr3;
3053         sregs->cr4 = vcpu->arch.cr4;
3054         sregs->cr8 = kvm_get_cr8(vcpu);
3055         sregs->efer = vcpu->arch.shadow_efer;
3056         sregs->apic_base = kvm_get_apic_base(vcpu);
3057
3058         if (irqchip_in_kernel(vcpu->kvm)) {
3059                 memset(sregs->interrupt_bitmap, 0,
3060                        sizeof sregs->interrupt_bitmap);
3061                 pending_vec = kvm_x86_ops->get_irq(vcpu);
3062                 if (pending_vec >= 0)
3063                         set_bit(pending_vec,
3064                                 (unsigned long *)sregs->interrupt_bitmap);
3065         } else
3066                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
3067                        sizeof sregs->interrupt_bitmap);
3068
3069         vcpu_put(vcpu);
3070
3071         return 0;
3072 }
3073
3074 static void set_segment(struct kvm_vcpu *vcpu,
3075                         struct kvm_segment *var, int seg)
3076 {
3077         kvm_x86_ops->set_segment(vcpu, var, seg);
3078 }
3079
3080 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
3081                                   struct kvm_sregs *sregs)
3082 {
3083         int mmu_reset_needed = 0;
3084         int i, pending_vec, max_bits;
3085         struct descriptor_table dt;
3086
3087         vcpu_load(vcpu);
3088
3089         dt.limit = sregs->idt.limit;
3090         dt.base = sregs->idt.base;
3091         kvm_x86_ops->set_idt(vcpu, &dt);
3092         dt.limit = sregs->gdt.limit;
3093         dt.base = sregs->gdt.base;
3094         kvm_x86_ops->set_gdt(vcpu, &dt);
3095
3096         vcpu->arch.cr2 = sregs->cr2;
3097         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
3098         vcpu->arch.cr3 = sregs->cr3;
3099
3100         kvm_set_cr8(vcpu, sregs->cr8);
3101
3102         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
3103         kvm_x86_ops->set_efer(vcpu, sregs->efer);
3104         kvm_set_apic_base(vcpu, sregs->apic_base);
3105
3106         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3107
3108         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
3109         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
3110         vcpu->arch.cr0 = sregs->cr0;
3111
3112         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
3113         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3114         if (!is_long_mode(vcpu) && is_pae(vcpu))
3115                 load_pdptrs(vcpu, vcpu->arch.cr3);
3116
3117         if (mmu_reset_needed)
3118                 kvm_mmu_reset_context(vcpu);
3119
3120         if (!irqchip_in_kernel(vcpu->kvm)) {
3121                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
3122                        sizeof vcpu->arch.irq_pending);
3123                 vcpu->arch.irq_summary = 0;
3124                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
3125                         if (vcpu->arch.irq_pending[i])
3126                                 __set_bit(i, &vcpu->arch.irq_summary);
3127         } else {
3128                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
3129                 pending_vec = find_first_bit(
3130                         (const unsigned long *)sregs->interrupt_bitmap,
3131                         max_bits);
3132                 /* Only pending external irq is handled here */
3133                 if (pending_vec < max_bits) {
3134                         kvm_x86_ops->set_irq(vcpu, pending_vec);
3135                         pr_debug("Set back pending irq %d\n",
3136                                  pending_vec);
3137                 }
3138         }
3139
3140         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3141         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3142         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3143         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3144         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3145         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3146
3147         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3148         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3149
3150         vcpu_put(vcpu);
3151
3152         return 0;
3153 }
3154
3155 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
3156                                     struct kvm_debug_guest *dbg)
3157 {
3158         int r;
3159
3160         vcpu_load(vcpu);
3161
3162         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
3163
3164         vcpu_put(vcpu);
3165
3166         return r;
3167 }
3168
3169 /*
3170  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
3171  * we have asm/x86/processor.h
3172  */
3173 struct fxsave {
3174         u16     cwd;
3175         u16     swd;
3176         u16     twd;
3177         u16     fop;
3178         u64     rip;
3179         u64     rdp;
3180         u32     mxcsr;
3181         u32     mxcsr_mask;
3182         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
3183 #ifdef CONFIG_X86_64
3184         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
3185 #else
3186         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
3187 #endif
3188 };
3189
3190 /*
3191  * Translate a guest virtual address to a guest physical address.
3192  */
3193 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
3194                                     struct kvm_translation *tr)
3195 {
3196         unsigned long vaddr = tr->linear_address;
3197         gpa_t gpa;
3198
3199         vcpu_load(vcpu);
3200         down_read(&vcpu->kvm->slots_lock);
3201         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
3202         up_read(&vcpu->kvm->slots_lock);
3203         tr->physical_address = gpa;
3204         tr->valid = gpa != UNMAPPED_GVA;
3205         tr->writeable = 1;
3206         tr->usermode = 0;
3207         vcpu_put(vcpu);
3208
3209         return 0;
3210 }
3211
3212 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3213 {
3214         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3215
3216         vcpu_load(vcpu);
3217
3218         memcpy(fpu->fpr, fxsave->st_space, 128);
3219         fpu->fcw = fxsave->cwd;
3220         fpu->fsw = fxsave->swd;
3221         fpu->ftwx = fxsave->twd;
3222         fpu->last_opcode = fxsave->fop;
3223         fpu->last_ip = fxsave->rip;
3224         fpu->last_dp = fxsave->rdp;
3225         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
3226
3227         vcpu_put(vcpu);
3228
3229         return 0;
3230 }
3231
3232 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3233 {
3234         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3235
3236         vcpu_load(vcpu);
3237
3238         memcpy(fxsave->st_space, fpu->fpr, 128);
3239         fxsave->cwd = fpu->fcw;
3240         fxsave->swd = fpu->fsw;
3241         fxsave->twd = fpu->ftwx;
3242         fxsave->fop = fpu->last_opcode;
3243         fxsave->rip = fpu->last_ip;
3244         fxsave->rdp = fpu->last_dp;
3245         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
3246
3247         vcpu_put(vcpu);
3248
3249         return 0;
3250 }
3251
3252 void fx_init(struct kvm_vcpu *vcpu)
3253 {
3254         unsigned after_mxcsr_mask;
3255
3256         /* Initialize guest FPU by resetting ours and saving into guest's */
3257         preempt_disable();
3258         fx_save(&vcpu->arch.host_fx_image);
3259         fpu_init();
3260         fx_save(&vcpu->arch.guest_fx_image);
3261         fx_restore(&vcpu->arch.host_fx_image);
3262         preempt_enable();
3263
3264         vcpu->arch.cr0 |= X86_CR0_ET;
3265         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
3266         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
3267         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
3268                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
3269 }
3270 EXPORT_SYMBOL_GPL(fx_init);
3271
3272 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
3273 {
3274         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
3275                 return;
3276
3277         vcpu->guest_fpu_loaded = 1;
3278         fx_save(&vcpu->arch.host_fx_image);
3279         fx_restore(&vcpu->arch.guest_fx_image);
3280 }
3281 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
3282
3283 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
3284 {
3285         if (!vcpu->guest_fpu_loaded)
3286                 return;
3287
3288         vcpu->guest_fpu_loaded = 0;
3289         fx_save(&vcpu->arch.guest_fx_image);
3290         fx_restore(&vcpu->arch.host_fx_image);
3291         ++vcpu->stat.fpu_reload;
3292 }
3293 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
3294
3295 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
3296 {
3297         kvm_x86_ops->vcpu_free(vcpu);
3298 }
3299
3300 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
3301                                                 unsigned int id)
3302 {
3303         return kvm_x86_ops->vcpu_create(kvm, id);
3304 }
3305
3306 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
3307 {
3308         int r;
3309
3310         /* We do fxsave: this must be aligned. */
3311         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
3312
3313         vcpu_load(vcpu);
3314         r = kvm_arch_vcpu_reset(vcpu);
3315         if (r == 0)
3316                 r = kvm_mmu_setup(vcpu);
3317         vcpu_put(vcpu);
3318         if (r < 0)
3319                 goto free_vcpu;
3320
3321         return 0;
3322 free_vcpu:
3323         kvm_x86_ops->vcpu_free(vcpu);
3324         return r;
3325 }
3326
3327 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
3328 {
3329         vcpu_load(vcpu);
3330         kvm_mmu_unload(vcpu);
3331         vcpu_put(vcpu);
3332
3333         kvm_x86_ops->vcpu_free(vcpu);
3334 }
3335
3336 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
3337 {
3338         return kvm_x86_ops->vcpu_reset(vcpu);
3339 }
3340
3341 void kvm_arch_hardware_enable(void *garbage)
3342 {
3343         kvm_x86_ops->hardware_enable(garbage);
3344 }
3345
3346 void kvm_arch_hardware_disable(void *garbage)
3347 {
3348         kvm_x86_ops->hardware_disable(garbage);
3349 }
3350
3351 int kvm_arch_hardware_setup(void)
3352 {
3353         return kvm_x86_ops->hardware_setup();
3354 }
3355
3356 void kvm_arch_hardware_unsetup(void)
3357 {
3358         kvm_x86_ops->hardware_unsetup();
3359 }
3360
3361 void kvm_arch_check_processor_compat(void *rtn)
3362 {
3363         kvm_x86_ops->check_processor_compatibility(rtn);
3364 }
3365
3366 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
3367 {
3368         struct page *page;
3369         struct kvm *kvm;
3370         int r;
3371
3372         BUG_ON(vcpu->kvm == NULL);
3373         kvm = vcpu->kvm;
3374
3375         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3376         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
3377                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
3378         else
3379                 vcpu->arch.mp_state = VCPU_MP_STATE_UNINITIALIZED;
3380
3381         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3382         if (!page) {
3383                 r = -ENOMEM;
3384                 goto fail;
3385         }
3386         vcpu->arch.pio_data = page_address(page);
3387
3388         r = kvm_mmu_create(vcpu);
3389         if (r < 0)
3390                 goto fail_free_pio_data;
3391
3392         if (irqchip_in_kernel(kvm)) {
3393                 r = kvm_create_lapic(vcpu);
3394                 if (r < 0)
3395                         goto fail_mmu_destroy;
3396         }
3397
3398         return 0;
3399
3400 fail_mmu_destroy:
3401         kvm_mmu_destroy(vcpu);
3402 fail_free_pio_data:
3403         free_page((unsigned long)vcpu->arch.pio_data);
3404 fail:
3405         return r;
3406 }
3407
3408 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
3409 {
3410         kvm_free_lapic(vcpu);
3411         kvm_mmu_destroy(vcpu);
3412         free_page((unsigned long)vcpu->arch.pio_data);
3413 }
3414
3415 struct  kvm *kvm_arch_create_vm(void)
3416 {
3417         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
3418
3419         if (!kvm)
3420                 return ERR_PTR(-ENOMEM);
3421
3422         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
3423
3424         return kvm;
3425 }
3426
3427 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
3428 {
3429         vcpu_load(vcpu);
3430         kvm_mmu_unload(vcpu);
3431         vcpu_put(vcpu);
3432 }
3433
3434 static void kvm_free_vcpus(struct kvm *kvm)
3435 {
3436         unsigned int i;
3437
3438         /*
3439          * Unpin any mmu pages first.
3440          */
3441         for (i = 0; i < KVM_MAX_VCPUS; ++i)
3442                 if (kvm->vcpus[i])
3443                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
3444         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3445                 if (kvm->vcpus[i]) {
3446                         kvm_arch_vcpu_free(kvm->vcpus[i]);
3447                         kvm->vcpus[i] = NULL;
3448                 }
3449         }
3450
3451 }
3452
3453 void kvm_arch_destroy_vm(struct kvm *kvm)
3454 {
3455         kvm_free_pit(kvm);
3456         kfree(kvm->arch.vpic);
3457         kfree(kvm->arch.vioapic);
3458         kvm_free_vcpus(kvm);
3459         kvm_free_physmem(kvm);
3460         kfree(kvm);
3461 }
3462
3463 int kvm_arch_set_memory_region(struct kvm *kvm,
3464                                 struct kvm_userspace_memory_region *mem,
3465                                 struct kvm_memory_slot old,
3466                                 int user_alloc)
3467 {
3468         int npages = mem->memory_size >> PAGE_SHIFT;
3469         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
3470
3471         /*To keep backward compatibility with older userspace,
3472          *x86 needs to hanlde !user_alloc case.
3473          */
3474         if (!user_alloc) {
3475                 if (npages && !old.rmap) {
3476                         down_write(&current->mm->mmap_sem);
3477                         memslot->userspace_addr = do_mmap(NULL, 0,
3478                                                      npages * PAGE_SIZE,
3479                                                      PROT_READ | PROT_WRITE,
3480                                                      MAP_SHARED | MAP_ANONYMOUS,
3481                                                      0);
3482                         up_write(&current->mm->mmap_sem);
3483
3484                         if (IS_ERR((void *)memslot->userspace_addr))
3485                                 return PTR_ERR((void *)memslot->userspace_addr);
3486                 } else {
3487                         if (!old.user_alloc && old.rmap) {
3488                                 int ret;
3489
3490                                 down_write(&current->mm->mmap_sem);
3491                                 ret = do_munmap(current->mm, old.userspace_addr,
3492                                                 old.npages * PAGE_SIZE);
3493                                 up_write(&current->mm->mmap_sem);
3494                                 if (ret < 0)
3495                                         printk(KERN_WARNING
3496                                        "kvm_vm_ioctl_set_memory_region: "
3497                                        "failed to munmap memory\n");
3498                         }
3499                 }
3500         }
3501
3502         if (!kvm->arch.n_requested_mmu_pages) {
3503                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
3504                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
3505         }
3506
3507         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
3508         kvm_flush_remote_tlbs(kvm);
3509
3510         return 0;
3511 }
3512
3513 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
3514 {
3515         return vcpu->arch.mp_state == VCPU_MP_STATE_RUNNABLE
3516                || vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED;
3517 }
3518
3519 static void vcpu_kick_intr(void *info)
3520 {
3521 #ifdef DEBUG
3522         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
3523         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
3524 #endif
3525 }
3526
3527 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3528 {
3529         int ipi_pcpu = vcpu->cpu;
3530
3531         if (waitqueue_active(&vcpu->wq)) {
3532                 wake_up_interruptible(&vcpu->wq);
3533                 ++vcpu->stat.halt_wakeup;
3534         }
3535         if (vcpu->guest_mode)
3536                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0, 0);
3537 }