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