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