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