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