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