]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - arch/x86/kvm/x86.c
KVM: Reduce kvm stack usage in kvm_arch_vm_ioctl()
[karo-tx-linux.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         case KVM_CAP_SYNC_MMU:
887                 r = 1;
888                 break;
889         case KVM_CAP_COALESCED_MMIO:
890                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
891                 break;
892         case KVM_CAP_VAPIC:
893                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
894                 break;
895         case KVM_CAP_NR_VCPUS:
896                 r = KVM_MAX_VCPUS;
897                 break;
898         case KVM_CAP_NR_MEMSLOTS:
899                 r = KVM_MEMORY_SLOTS;
900                 break;
901         case KVM_CAP_PV_MMU:
902                 r = !tdp_enabled;
903                 break;
904         default:
905                 r = 0;
906                 break;
907         }
908         return r;
909
910 }
911
912 long kvm_arch_dev_ioctl(struct file *filp,
913                         unsigned int ioctl, unsigned long arg)
914 {
915         void __user *argp = (void __user *)arg;
916         long r;
917
918         switch (ioctl) {
919         case KVM_GET_MSR_INDEX_LIST: {
920                 struct kvm_msr_list __user *user_msr_list = argp;
921                 struct kvm_msr_list msr_list;
922                 unsigned n;
923
924                 r = -EFAULT;
925                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
926                         goto out;
927                 n = msr_list.nmsrs;
928                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
929                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
930                         goto out;
931                 r = -E2BIG;
932                 if (n < num_msrs_to_save)
933                         goto out;
934                 r = -EFAULT;
935                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
936                                  num_msrs_to_save * sizeof(u32)))
937                         goto out;
938                 if (copy_to_user(user_msr_list->indices
939                                  + num_msrs_to_save * sizeof(u32),
940                                  &emulated_msrs,
941                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
942                         goto out;
943                 r = 0;
944                 break;
945         }
946         case KVM_GET_SUPPORTED_CPUID: {
947                 struct kvm_cpuid2 __user *cpuid_arg = argp;
948                 struct kvm_cpuid2 cpuid;
949
950                 r = -EFAULT;
951                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
952                         goto out;
953                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
954                         cpuid_arg->entries);
955                 if (r)
956                         goto out;
957
958                 r = -EFAULT;
959                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
960                         goto out;
961                 r = 0;
962                 break;
963         }
964         default:
965                 r = -EINVAL;
966         }
967 out:
968         return r;
969 }
970
971 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
972 {
973         kvm_x86_ops->vcpu_load(vcpu, cpu);
974         kvm_write_guest_time(vcpu);
975 }
976
977 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
978 {
979         kvm_x86_ops->vcpu_put(vcpu);
980         kvm_put_guest_fpu(vcpu);
981 }
982
983 static int is_efer_nx(void)
984 {
985         u64 efer;
986
987         rdmsrl(MSR_EFER, efer);
988         return efer & EFER_NX;
989 }
990
991 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
992 {
993         int i;
994         struct kvm_cpuid_entry2 *e, *entry;
995
996         entry = NULL;
997         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
998                 e = &vcpu->arch.cpuid_entries[i];
999                 if (e->function == 0x80000001) {
1000                         entry = e;
1001                         break;
1002                 }
1003         }
1004         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1005                 entry->edx &= ~(1 << 20);
1006                 printk(KERN_INFO "kvm: guest NX capability removed\n");
1007         }
1008 }
1009
1010 /* when an old userspace process fills a new kernel module */
1011 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1012                                     struct kvm_cpuid *cpuid,
1013                                     struct kvm_cpuid_entry __user *entries)
1014 {
1015         int r, i;
1016         struct kvm_cpuid_entry *cpuid_entries;
1017
1018         r = -E2BIG;
1019         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1020                 goto out;
1021         r = -ENOMEM;
1022         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1023         if (!cpuid_entries)
1024                 goto out;
1025         r = -EFAULT;
1026         if (copy_from_user(cpuid_entries, entries,
1027                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1028                 goto out_free;
1029         for (i = 0; i < cpuid->nent; i++) {
1030                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1031                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1032                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1033                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1034                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1035                 vcpu->arch.cpuid_entries[i].index = 0;
1036                 vcpu->arch.cpuid_entries[i].flags = 0;
1037                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1038                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1039                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1040         }
1041         vcpu->arch.cpuid_nent = cpuid->nent;
1042         cpuid_fix_nx_cap(vcpu);
1043         r = 0;
1044
1045 out_free:
1046         vfree(cpuid_entries);
1047 out:
1048         return r;
1049 }
1050
1051 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1052                                     struct kvm_cpuid2 *cpuid,
1053                                     struct kvm_cpuid_entry2 __user *entries)
1054 {
1055         int r;
1056
1057         r = -E2BIG;
1058         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1059                 goto out;
1060         r = -EFAULT;
1061         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1062                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1063                 goto out;
1064         vcpu->arch.cpuid_nent = cpuid->nent;
1065         return 0;
1066
1067 out:
1068         return r;
1069 }
1070
1071 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1072                                     struct kvm_cpuid2 *cpuid,
1073                                     struct kvm_cpuid_entry2 __user *entries)
1074 {
1075         int r;
1076
1077         r = -E2BIG;
1078         if (cpuid->nent < vcpu->arch.cpuid_nent)
1079                 goto out;
1080         r = -EFAULT;
1081         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1082                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1083                 goto out;
1084         return 0;
1085
1086 out:
1087         cpuid->nent = vcpu->arch.cpuid_nent;
1088         return r;
1089 }
1090
1091 static inline u32 bit(int bitno)
1092 {
1093         return 1 << (bitno & 31);
1094 }
1095
1096 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1097                           u32 index)
1098 {
1099         entry->function = function;
1100         entry->index = index;
1101         cpuid_count(entry->function, entry->index,
1102                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1103         entry->flags = 0;
1104 }
1105
1106 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1107                          u32 index, int *nent, int maxnent)
1108 {
1109         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
1110                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1111                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1112                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1113                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1114                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
1115                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1116                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
1117                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
1118                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
1119         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
1120                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1121                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1122                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1123                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1124                 bit(X86_FEATURE_PGE) |
1125                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1126                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
1127                 bit(X86_FEATURE_SYSCALL) |
1128                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
1129 #ifdef CONFIG_X86_64
1130                 bit(X86_FEATURE_LM) |
1131 #endif
1132                 bit(X86_FEATURE_MMXEXT) |
1133                 bit(X86_FEATURE_3DNOWEXT) |
1134                 bit(X86_FEATURE_3DNOW);
1135         const u32 kvm_supported_word3_x86_features =
1136                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
1137         const u32 kvm_supported_word6_x86_features =
1138                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
1139
1140         /* all func 2 cpuid_count() should be called on the same cpu */
1141         get_cpu();
1142         do_cpuid_1_ent(entry, function, index);
1143         ++*nent;
1144
1145         switch (function) {
1146         case 0:
1147                 entry->eax = min(entry->eax, (u32)0xb);
1148                 break;
1149         case 1:
1150                 entry->edx &= kvm_supported_word0_x86_features;
1151                 entry->ecx &= kvm_supported_word3_x86_features;
1152                 break;
1153         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1154          * may return different values. This forces us to get_cpu() before
1155          * issuing the first command, and also to emulate this annoying behavior
1156          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1157         case 2: {
1158                 int t, times = entry->eax & 0xff;
1159
1160                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1161                 for (t = 1; t < times && *nent < maxnent; ++t) {
1162                         do_cpuid_1_ent(&entry[t], function, 0);
1163                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1164                         ++*nent;
1165                 }
1166                 break;
1167         }
1168         /* function 4 and 0xb have additional index. */
1169         case 4: {
1170                 int i, cache_type;
1171
1172                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1173                 /* read more entries until cache_type is zero */
1174                 for (i = 1; *nent < maxnent; ++i) {
1175                         cache_type = entry[i - 1].eax & 0x1f;
1176                         if (!cache_type)
1177                                 break;
1178                         do_cpuid_1_ent(&entry[i], function, i);
1179                         entry[i].flags |=
1180                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1181                         ++*nent;
1182                 }
1183                 break;
1184         }
1185         case 0xb: {
1186                 int i, level_type;
1187
1188                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1189                 /* read more entries until level_type is zero */
1190                 for (i = 1; *nent < maxnent; ++i) {
1191                         level_type = entry[i - 1].ecx & 0xff;
1192                         if (!level_type)
1193                                 break;
1194                         do_cpuid_1_ent(&entry[i], function, i);
1195                         entry[i].flags |=
1196                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1197                         ++*nent;
1198                 }
1199                 break;
1200         }
1201         case 0x80000000:
1202                 entry->eax = min(entry->eax, 0x8000001a);
1203                 break;
1204         case 0x80000001:
1205                 entry->edx &= kvm_supported_word1_x86_features;
1206                 entry->ecx &= kvm_supported_word6_x86_features;
1207                 break;
1208         }
1209         put_cpu();
1210 }
1211
1212 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1213                                     struct kvm_cpuid_entry2 __user *entries)
1214 {
1215         struct kvm_cpuid_entry2 *cpuid_entries;
1216         int limit, nent = 0, r = -E2BIG;
1217         u32 func;
1218
1219         if (cpuid->nent < 1)
1220                 goto out;
1221         r = -ENOMEM;
1222         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1223         if (!cpuid_entries)
1224                 goto out;
1225
1226         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1227         limit = cpuid_entries[0].eax;
1228         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1229                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1230                                 &nent, cpuid->nent);
1231         r = -E2BIG;
1232         if (nent >= cpuid->nent)
1233                 goto out_free;
1234
1235         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1236         limit = cpuid_entries[nent - 1].eax;
1237         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1238                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1239                                &nent, cpuid->nent);
1240         r = -EFAULT;
1241         if (copy_to_user(entries, cpuid_entries,
1242                         nent * sizeof(struct kvm_cpuid_entry2)))
1243                 goto out_free;
1244         cpuid->nent = nent;
1245         r = 0;
1246
1247 out_free:
1248         vfree(cpuid_entries);
1249 out:
1250         return r;
1251 }
1252
1253 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1254                                     struct kvm_lapic_state *s)
1255 {
1256         vcpu_load(vcpu);
1257         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1258         vcpu_put(vcpu);
1259
1260         return 0;
1261 }
1262
1263 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1264                                     struct kvm_lapic_state *s)
1265 {
1266         vcpu_load(vcpu);
1267         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1268         kvm_apic_post_state_restore(vcpu);
1269         vcpu_put(vcpu);
1270
1271         return 0;
1272 }
1273
1274 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1275                                     struct kvm_interrupt *irq)
1276 {
1277         if (irq->irq < 0 || irq->irq >= 256)
1278                 return -EINVAL;
1279         if (irqchip_in_kernel(vcpu->kvm))
1280                 return -ENXIO;
1281         vcpu_load(vcpu);
1282
1283         set_bit(irq->irq, vcpu->arch.irq_pending);
1284         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1285
1286         vcpu_put(vcpu);
1287
1288         return 0;
1289 }
1290
1291 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1292                                            struct kvm_tpr_access_ctl *tac)
1293 {
1294         if (tac->flags)
1295                 return -EINVAL;
1296         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1297         return 0;
1298 }
1299
1300 long kvm_arch_vcpu_ioctl(struct file *filp,
1301                          unsigned int ioctl, unsigned long arg)
1302 {
1303         struct kvm_vcpu *vcpu = filp->private_data;
1304         void __user *argp = (void __user *)arg;
1305         int r;
1306
1307         switch (ioctl) {
1308         case KVM_GET_LAPIC: {
1309                 struct kvm_lapic_state lapic;
1310
1311                 memset(&lapic, 0, sizeof lapic);
1312                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1313                 if (r)
1314                         goto out;
1315                 r = -EFAULT;
1316                 if (copy_to_user(argp, &lapic, sizeof lapic))
1317                         goto out;
1318                 r = 0;
1319                 break;
1320         }
1321         case KVM_SET_LAPIC: {
1322                 struct kvm_lapic_state lapic;
1323
1324                 r = -EFAULT;
1325                 if (copy_from_user(&lapic, argp, sizeof lapic))
1326                         goto out;
1327                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1328                 if (r)
1329                         goto out;
1330                 r = 0;
1331                 break;
1332         }
1333         case KVM_INTERRUPT: {
1334                 struct kvm_interrupt irq;
1335
1336                 r = -EFAULT;
1337                 if (copy_from_user(&irq, argp, sizeof irq))
1338                         goto out;
1339                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1340                 if (r)
1341                         goto out;
1342                 r = 0;
1343                 break;
1344         }
1345         case KVM_SET_CPUID: {
1346                 struct kvm_cpuid __user *cpuid_arg = argp;
1347                 struct kvm_cpuid cpuid;
1348
1349                 r = -EFAULT;
1350                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1351                         goto out;
1352                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1353                 if (r)
1354                         goto out;
1355                 break;
1356         }
1357         case KVM_SET_CPUID2: {
1358                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1359                 struct kvm_cpuid2 cpuid;
1360
1361                 r = -EFAULT;
1362                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1363                         goto out;
1364                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1365                                 cpuid_arg->entries);
1366                 if (r)
1367                         goto out;
1368                 break;
1369         }
1370         case KVM_GET_CPUID2: {
1371                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1372                 struct kvm_cpuid2 cpuid;
1373
1374                 r = -EFAULT;
1375                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1376                         goto out;
1377                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1378                                 cpuid_arg->entries);
1379                 if (r)
1380                         goto out;
1381                 r = -EFAULT;
1382                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1383                         goto out;
1384                 r = 0;
1385                 break;
1386         }
1387         case KVM_GET_MSRS:
1388                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1389                 break;
1390         case KVM_SET_MSRS:
1391                 r = msr_io(vcpu, argp, do_set_msr, 0);
1392                 break;
1393         case KVM_TPR_ACCESS_REPORTING: {
1394                 struct kvm_tpr_access_ctl tac;
1395
1396                 r = -EFAULT;
1397                 if (copy_from_user(&tac, argp, sizeof tac))
1398                         goto out;
1399                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1400                 if (r)
1401                         goto out;
1402                 r = -EFAULT;
1403                 if (copy_to_user(argp, &tac, sizeof tac))
1404                         goto out;
1405                 r = 0;
1406                 break;
1407         };
1408         case KVM_SET_VAPIC_ADDR: {
1409                 struct kvm_vapic_addr va;
1410
1411                 r = -EINVAL;
1412                 if (!irqchip_in_kernel(vcpu->kvm))
1413                         goto out;
1414                 r = -EFAULT;
1415                 if (copy_from_user(&va, argp, sizeof va))
1416                         goto out;
1417                 r = 0;
1418                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1419                 break;
1420         }
1421         default:
1422                 r = -EINVAL;
1423         }
1424 out:
1425         return r;
1426 }
1427
1428 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1429 {
1430         int ret;
1431
1432         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1433                 return -1;
1434         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1435         return ret;
1436 }
1437
1438 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1439                                           u32 kvm_nr_mmu_pages)
1440 {
1441         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1442                 return -EINVAL;
1443
1444         down_write(&kvm->slots_lock);
1445
1446         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1447         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1448
1449         up_write(&kvm->slots_lock);
1450         return 0;
1451 }
1452
1453 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1454 {
1455         return kvm->arch.n_alloc_mmu_pages;
1456 }
1457
1458 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1459 {
1460         int i;
1461         struct kvm_mem_alias *alias;
1462
1463         for (i = 0; i < kvm->arch.naliases; ++i) {
1464                 alias = &kvm->arch.aliases[i];
1465                 if (gfn >= alias->base_gfn
1466                     && gfn < alias->base_gfn + alias->npages)
1467                         return alias->target_gfn + gfn - alias->base_gfn;
1468         }
1469         return gfn;
1470 }
1471
1472 /*
1473  * Set a new alias region.  Aliases map a portion of physical memory into
1474  * another portion.  This is useful for memory windows, for example the PC
1475  * VGA region.
1476  */
1477 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1478                                          struct kvm_memory_alias *alias)
1479 {
1480         int r, n;
1481         struct kvm_mem_alias *p;
1482
1483         r = -EINVAL;
1484         /* General sanity checks */
1485         if (alias->memory_size & (PAGE_SIZE - 1))
1486                 goto out;
1487         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1488                 goto out;
1489         if (alias->slot >= KVM_ALIAS_SLOTS)
1490                 goto out;
1491         if (alias->guest_phys_addr + alias->memory_size
1492             < alias->guest_phys_addr)
1493                 goto out;
1494         if (alias->target_phys_addr + alias->memory_size
1495             < alias->target_phys_addr)
1496                 goto out;
1497
1498         down_write(&kvm->slots_lock);
1499         spin_lock(&kvm->mmu_lock);
1500
1501         p = &kvm->arch.aliases[alias->slot];
1502         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1503         p->npages = alias->memory_size >> PAGE_SHIFT;
1504         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1505
1506         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1507                 if (kvm->arch.aliases[n - 1].npages)
1508                         break;
1509         kvm->arch.naliases = n;
1510
1511         spin_unlock(&kvm->mmu_lock);
1512         kvm_mmu_zap_all(kvm);
1513
1514         up_write(&kvm->slots_lock);
1515
1516         return 0;
1517
1518 out:
1519         return r;
1520 }
1521
1522 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1523 {
1524         int r;
1525
1526         r = 0;
1527         switch (chip->chip_id) {
1528         case KVM_IRQCHIP_PIC_MASTER:
1529                 memcpy(&chip->chip.pic,
1530                         &pic_irqchip(kvm)->pics[0],
1531                         sizeof(struct kvm_pic_state));
1532                 break;
1533         case KVM_IRQCHIP_PIC_SLAVE:
1534                 memcpy(&chip->chip.pic,
1535                         &pic_irqchip(kvm)->pics[1],
1536                         sizeof(struct kvm_pic_state));
1537                 break;
1538         case KVM_IRQCHIP_IOAPIC:
1539                 memcpy(&chip->chip.ioapic,
1540                         ioapic_irqchip(kvm),
1541                         sizeof(struct kvm_ioapic_state));
1542                 break;
1543         default:
1544                 r = -EINVAL;
1545                 break;
1546         }
1547         return r;
1548 }
1549
1550 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1551 {
1552         int r;
1553
1554         r = 0;
1555         switch (chip->chip_id) {
1556         case KVM_IRQCHIP_PIC_MASTER:
1557                 memcpy(&pic_irqchip(kvm)->pics[0],
1558                         &chip->chip.pic,
1559                         sizeof(struct kvm_pic_state));
1560                 break;
1561         case KVM_IRQCHIP_PIC_SLAVE:
1562                 memcpy(&pic_irqchip(kvm)->pics[1],
1563                         &chip->chip.pic,
1564                         sizeof(struct kvm_pic_state));
1565                 break;
1566         case KVM_IRQCHIP_IOAPIC:
1567                 memcpy(ioapic_irqchip(kvm),
1568                         &chip->chip.ioapic,
1569                         sizeof(struct kvm_ioapic_state));
1570                 break;
1571         default:
1572                 r = -EINVAL;
1573                 break;
1574         }
1575         kvm_pic_update_irq(pic_irqchip(kvm));
1576         return r;
1577 }
1578
1579 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1580 {
1581         int r = 0;
1582
1583         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
1584         return r;
1585 }
1586
1587 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1588 {
1589         int r = 0;
1590
1591         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
1592         kvm_pit_load_count(kvm, 0, ps->channels[0].count);
1593         return r;
1594 }
1595
1596 /*
1597  * Get (and clear) the dirty memory log for a memory slot.
1598  */
1599 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1600                                       struct kvm_dirty_log *log)
1601 {
1602         int r;
1603         int n;
1604         struct kvm_memory_slot *memslot;
1605         int is_dirty = 0;
1606
1607         down_write(&kvm->slots_lock);
1608
1609         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1610         if (r)
1611                 goto out;
1612
1613         /* If nothing is dirty, don't bother messing with page tables. */
1614         if (is_dirty) {
1615                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1616                 kvm_flush_remote_tlbs(kvm);
1617                 memslot = &kvm->memslots[log->slot];
1618                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1619                 memset(memslot->dirty_bitmap, 0, n);
1620         }
1621         r = 0;
1622 out:
1623         up_write(&kvm->slots_lock);
1624         return r;
1625 }
1626
1627 long kvm_arch_vm_ioctl(struct file *filp,
1628                        unsigned int ioctl, unsigned long arg)
1629 {
1630         struct kvm *kvm = filp->private_data;
1631         void __user *argp = (void __user *)arg;
1632         int r = -EINVAL;
1633         /*
1634          * This union makes it completely explicit to gcc-3.x
1635          * that these two variables' stack usage should be
1636          * combined, not added together.
1637          */
1638         union {
1639                 struct kvm_pit_state ps;
1640                 struct kvm_memory_alias alias;
1641         } u;
1642
1643         switch (ioctl) {
1644         case KVM_SET_TSS_ADDR:
1645                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1646                 if (r < 0)
1647                         goto out;
1648                 break;
1649         case KVM_SET_MEMORY_REGION: {
1650                 struct kvm_memory_region kvm_mem;
1651                 struct kvm_userspace_memory_region kvm_userspace_mem;
1652
1653                 r = -EFAULT;
1654                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1655                         goto out;
1656                 kvm_userspace_mem.slot = kvm_mem.slot;
1657                 kvm_userspace_mem.flags = kvm_mem.flags;
1658                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1659                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1660                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1661                 if (r)
1662                         goto out;
1663                 break;
1664         }
1665         case KVM_SET_NR_MMU_PAGES:
1666                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1667                 if (r)
1668                         goto out;
1669                 break;
1670         case KVM_GET_NR_MMU_PAGES:
1671                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1672                 break;
1673         case KVM_SET_MEMORY_ALIAS:
1674                 r = -EFAULT;
1675                 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
1676                         goto out;
1677                 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
1678                 if (r)
1679                         goto out;
1680                 break;
1681         case KVM_CREATE_IRQCHIP:
1682                 r = -ENOMEM;
1683                 kvm->arch.vpic = kvm_create_pic(kvm);
1684                 if (kvm->arch.vpic) {
1685                         r = kvm_ioapic_init(kvm);
1686                         if (r) {
1687                                 kfree(kvm->arch.vpic);
1688                                 kvm->arch.vpic = NULL;
1689                                 goto out;
1690                         }
1691                 } else
1692                         goto out;
1693                 break;
1694         case KVM_CREATE_PIT:
1695                 r = -ENOMEM;
1696                 kvm->arch.vpit = kvm_create_pit(kvm);
1697                 if (kvm->arch.vpit)
1698                         r = 0;
1699                 break;
1700         case KVM_IRQ_LINE: {
1701                 struct kvm_irq_level irq_event;
1702
1703                 r = -EFAULT;
1704                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1705                         goto out;
1706                 if (irqchip_in_kernel(kvm)) {
1707                         mutex_lock(&kvm->lock);
1708                         if (irq_event.irq < 16)
1709                                 kvm_pic_set_irq(pic_irqchip(kvm),
1710                                         irq_event.irq,
1711                                         irq_event.level);
1712                         kvm_ioapic_set_irq(kvm->arch.vioapic,
1713                                         irq_event.irq,
1714                                         irq_event.level);
1715                         mutex_unlock(&kvm->lock);
1716                         r = 0;
1717                 }
1718                 break;
1719         }
1720         case KVM_GET_IRQCHIP: {
1721                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1722                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
1723
1724                 r = -ENOMEM;
1725                 if (!chip)
1726                         goto out;
1727                 r = -EFAULT;
1728                 if (copy_from_user(chip, argp, sizeof *chip))
1729                         goto get_irqchip_out;
1730                 r = -ENXIO;
1731                 if (!irqchip_in_kernel(kvm))
1732                         goto get_irqchip_out;
1733                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1734                 if (r)
1735                         goto get_irqchip_out;
1736                 r = -EFAULT;
1737                 if (copy_to_user(argp, chip, sizeof *chip))
1738                         goto get_irqchip_out;
1739                 r = 0;
1740         get_irqchip_out:
1741                 kfree(chip);
1742                 if (r)
1743                         goto out;
1744                 break;
1745         }
1746         case KVM_SET_IRQCHIP: {
1747                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1748                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
1749
1750                 r = -ENOMEM;
1751                 if (!chip)
1752                         goto out;
1753                 r = -EFAULT;
1754                 if (copy_from_user(chip, argp, sizeof *chip))
1755                         goto set_irqchip_out;
1756                 r = -ENXIO;
1757                 if (!irqchip_in_kernel(kvm))
1758                         goto set_irqchip_out;
1759                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
1760                 if (r)
1761                         goto set_irqchip_out;
1762                 r = 0;
1763         set_irqchip_out:
1764                 kfree(chip);
1765                 if (r)
1766                         goto out;
1767                 break;
1768         }
1769         case KVM_GET_PIT: {
1770                 r = -EFAULT;
1771                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
1772                         goto out;
1773                 r = -ENXIO;
1774                 if (!kvm->arch.vpit)
1775                         goto out;
1776                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
1777                 if (r)
1778                         goto out;
1779                 r = -EFAULT;
1780                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
1781                         goto out;
1782                 r = 0;
1783                 break;
1784         }
1785         case KVM_SET_PIT: {
1786                 r = -EFAULT;
1787                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
1788                         goto out;
1789                 r = -ENXIO;
1790                 if (!kvm->arch.vpit)
1791                         goto out;
1792                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
1793                 if (r)
1794                         goto out;
1795                 r = 0;
1796                 break;
1797         }
1798         default:
1799                 ;
1800         }
1801 out:
1802         return r;
1803 }
1804
1805 static void kvm_init_msr_list(void)
1806 {
1807         u32 dummy[2];
1808         unsigned i, j;
1809
1810         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1811                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1812                         continue;
1813                 if (j < i)
1814                         msrs_to_save[j] = msrs_to_save[i];
1815                 j++;
1816         }
1817         num_msrs_to_save = j;
1818 }
1819
1820 /*
1821  * Only apic need an MMIO device hook, so shortcut now..
1822  */
1823 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1824                                                 gpa_t addr, int len,
1825                                                 int is_write)
1826 {
1827         struct kvm_io_device *dev;
1828
1829         if (vcpu->arch.apic) {
1830                 dev = &vcpu->arch.apic->dev;
1831                 if (dev->in_range(dev, addr, len, is_write))
1832                         return dev;
1833         }
1834         return NULL;
1835 }
1836
1837
1838 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1839                                                 gpa_t addr, int len,
1840                                                 int is_write)
1841 {
1842         struct kvm_io_device *dev;
1843
1844         dev = vcpu_find_pervcpu_dev(vcpu, addr, len, is_write);
1845         if (dev == NULL)
1846                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr, len,
1847                                           is_write);
1848         return dev;
1849 }
1850
1851 int emulator_read_std(unsigned long addr,
1852                              void *val,
1853                              unsigned int bytes,
1854                              struct kvm_vcpu *vcpu)
1855 {
1856         void *data = val;
1857         int r = X86EMUL_CONTINUE;
1858
1859         while (bytes) {
1860                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1861                 unsigned offset = addr & (PAGE_SIZE-1);
1862                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1863                 int ret;
1864
1865                 if (gpa == UNMAPPED_GVA) {
1866                         r = X86EMUL_PROPAGATE_FAULT;
1867                         goto out;
1868                 }
1869                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1870                 if (ret < 0) {
1871                         r = X86EMUL_UNHANDLEABLE;
1872                         goto out;
1873                 }
1874
1875                 bytes -= tocopy;
1876                 data += tocopy;
1877                 addr += tocopy;
1878         }
1879 out:
1880         return r;
1881 }
1882 EXPORT_SYMBOL_GPL(emulator_read_std);
1883
1884 static int emulator_read_emulated(unsigned long addr,
1885                                   void *val,
1886                                   unsigned int bytes,
1887                                   struct kvm_vcpu *vcpu)
1888 {
1889         struct kvm_io_device *mmio_dev;
1890         gpa_t                 gpa;
1891
1892         if (vcpu->mmio_read_completed) {
1893                 memcpy(val, vcpu->mmio_data, bytes);
1894                 vcpu->mmio_read_completed = 0;
1895                 return X86EMUL_CONTINUE;
1896         }
1897
1898         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1899
1900         /* For APIC access vmexit */
1901         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1902                 goto mmio;
1903
1904         if (emulator_read_std(addr, val, bytes, vcpu)
1905                         == X86EMUL_CONTINUE)
1906                 return X86EMUL_CONTINUE;
1907         if (gpa == UNMAPPED_GVA)
1908                 return X86EMUL_PROPAGATE_FAULT;
1909
1910 mmio:
1911         /*
1912          * Is this MMIO handled locally?
1913          */
1914         mutex_lock(&vcpu->kvm->lock);
1915         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 0);
1916         if (mmio_dev) {
1917                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1918                 mutex_unlock(&vcpu->kvm->lock);
1919                 return X86EMUL_CONTINUE;
1920         }
1921         mutex_unlock(&vcpu->kvm->lock);
1922
1923         vcpu->mmio_needed = 1;
1924         vcpu->mmio_phys_addr = gpa;
1925         vcpu->mmio_size = bytes;
1926         vcpu->mmio_is_write = 0;
1927
1928         return X86EMUL_UNHANDLEABLE;
1929 }
1930
1931 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1932                           const void *val, int bytes)
1933 {
1934         int ret;
1935
1936         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1937         if (ret < 0)
1938                 return 0;
1939         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1940         return 1;
1941 }
1942
1943 static int emulator_write_emulated_onepage(unsigned long addr,
1944                                            const void *val,
1945                                            unsigned int bytes,
1946                                            struct kvm_vcpu *vcpu)
1947 {
1948         struct kvm_io_device *mmio_dev;
1949         gpa_t                 gpa;
1950
1951         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1952
1953         if (gpa == UNMAPPED_GVA) {
1954                 kvm_inject_page_fault(vcpu, addr, 2);
1955                 return X86EMUL_PROPAGATE_FAULT;
1956         }
1957
1958         /* For APIC access vmexit */
1959         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1960                 goto mmio;
1961
1962         if (emulator_write_phys(vcpu, gpa, val, bytes))
1963                 return X86EMUL_CONTINUE;
1964
1965 mmio:
1966         /*
1967          * Is this MMIO handled locally?
1968          */
1969         mutex_lock(&vcpu->kvm->lock);
1970         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 1);
1971         if (mmio_dev) {
1972                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1973                 mutex_unlock(&vcpu->kvm->lock);
1974                 return X86EMUL_CONTINUE;
1975         }
1976         mutex_unlock(&vcpu->kvm->lock);
1977
1978         vcpu->mmio_needed = 1;
1979         vcpu->mmio_phys_addr = gpa;
1980         vcpu->mmio_size = bytes;
1981         vcpu->mmio_is_write = 1;
1982         memcpy(vcpu->mmio_data, val, bytes);
1983
1984         return X86EMUL_CONTINUE;
1985 }
1986
1987 int emulator_write_emulated(unsigned long addr,
1988                                    const void *val,
1989                                    unsigned int bytes,
1990                                    struct kvm_vcpu *vcpu)
1991 {
1992         /* Crossing a page boundary? */
1993         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1994                 int rc, now;
1995
1996                 now = -addr & ~PAGE_MASK;
1997                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1998                 if (rc != X86EMUL_CONTINUE)
1999                         return rc;
2000                 addr += now;
2001                 val += now;
2002                 bytes -= now;
2003         }
2004         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
2005 }
2006 EXPORT_SYMBOL_GPL(emulator_write_emulated);
2007
2008 static int emulator_cmpxchg_emulated(unsigned long addr,
2009                                      const void *old,
2010                                      const void *new,
2011                                      unsigned int bytes,
2012                                      struct kvm_vcpu *vcpu)
2013 {
2014         static int reported;
2015
2016         if (!reported) {
2017                 reported = 1;
2018                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
2019         }
2020 #ifndef CONFIG_X86_64
2021         /* guests cmpxchg8b have to be emulated atomically */
2022         if (bytes == 8) {
2023                 gpa_t gpa;
2024                 struct page *page;
2025                 char *kaddr;
2026                 u64 val;
2027
2028                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2029
2030                 if (gpa == UNMAPPED_GVA ||
2031                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2032                         goto emul_write;
2033
2034                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
2035                         goto emul_write;
2036
2037                 val = *(u64 *)new;
2038
2039                 down_read(&current->mm->mmap_sem);
2040                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2041                 up_read(&current->mm->mmap_sem);
2042
2043                 kaddr = kmap_atomic(page, KM_USER0);
2044                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
2045                 kunmap_atomic(kaddr, KM_USER0);
2046                 kvm_release_page_dirty(page);
2047         }
2048 emul_write:
2049 #endif
2050
2051         return emulator_write_emulated(addr, new, bytes, vcpu);
2052 }
2053
2054 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
2055 {
2056         return kvm_x86_ops->get_segment_base(vcpu, seg);
2057 }
2058
2059 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
2060 {
2061         return X86EMUL_CONTINUE;
2062 }
2063
2064 int emulate_clts(struct kvm_vcpu *vcpu)
2065 {
2066         KVMTRACE_0D(CLTS, vcpu, handler);
2067         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
2068         return X86EMUL_CONTINUE;
2069 }
2070
2071 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2072 {
2073         struct kvm_vcpu *vcpu = ctxt->vcpu;
2074
2075         switch (dr) {
2076         case 0 ... 3:
2077                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2078                 return X86EMUL_CONTINUE;
2079         default:
2080                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2081                 return X86EMUL_UNHANDLEABLE;
2082         }
2083 }
2084
2085 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2086 {
2087         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2088         int exception;
2089
2090         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2091         if (exception) {
2092                 /* FIXME: better handling */
2093                 return X86EMUL_UNHANDLEABLE;
2094         }
2095         return X86EMUL_CONTINUE;
2096 }
2097
2098 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2099 {
2100         u8 opcodes[4];
2101         unsigned long rip = vcpu->arch.rip;
2102         unsigned long rip_linear;
2103
2104         if (!printk_ratelimit())
2105                 return;
2106
2107         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2108
2109         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
2110
2111         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2112                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2113 }
2114 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2115
2116 static struct x86_emulate_ops emulate_ops = {
2117         .read_std            = emulator_read_std,
2118         .read_emulated       = emulator_read_emulated,
2119         .write_emulated      = emulator_write_emulated,
2120         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
2121 };
2122
2123 int emulate_instruction(struct kvm_vcpu *vcpu,
2124                         struct kvm_run *run,
2125                         unsigned long cr2,
2126                         u16 error_code,
2127                         int emulation_type)
2128 {
2129         int r;
2130         struct decode_cache *c;
2131
2132         vcpu->arch.mmio_fault_cr2 = cr2;
2133         kvm_x86_ops->cache_regs(vcpu);
2134
2135         vcpu->mmio_is_write = 0;
2136         vcpu->arch.pio.string = 0;
2137
2138         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2139                 int cs_db, cs_l;
2140                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2141
2142                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2143                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
2144                 vcpu->arch.emulate_ctxt.mode =
2145                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2146                         ? X86EMUL_MODE_REAL : cs_l
2147                         ? X86EMUL_MODE_PROT64 : cs_db
2148                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2149
2150                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2151
2152                 /* Reject the instructions other than VMCALL/VMMCALL when
2153                  * try to emulate invalid opcode */
2154                 c = &vcpu->arch.emulate_ctxt.decode;
2155                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
2156                     (!(c->twobyte && c->b == 0x01 &&
2157                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
2158                        c->modrm_mod == 3 && c->modrm_rm == 1)))
2159                         return EMULATE_FAIL;
2160
2161                 ++vcpu->stat.insn_emulation;
2162                 if (r)  {
2163                         ++vcpu->stat.insn_emulation_fail;
2164                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2165                                 return EMULATE_DONE;
2166                         return EMULATE_FAIL;
2167                 }
2168         }
2169
2170         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2171
2172         if (vcpu->arch.pio.string)
2173                 return EMULATE_DO_MMIO;
2174
2175         if ((r || vcpu->mmio_is_write) && run) {
2176                 run->exit_reason = KVM_EXIT_MMIO;
2177                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2178                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2179                 run->mmio.len = vcpu->mmio_size;
2180                 run->mmio.is_write = vcpu->mmio_is_write;
2181         }
2182
2183         if (r) {
2184                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2185                         return EMULATE_DONE;
2186                 if (!vcpu->mmio_needed) {
2187                         kvm_report_emulation_failure(vcpu, "mmio");
2188                         return EMULATE_FAIL;
2189                 }
2190                 return EMULATE_DO_MMIO;
2191         }
2192
2193         kvm_x86_ops->decache_regs(vcpu);
2194         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2195
2196         if (vcpu->mmio_is_write) {
2197                 vcpu->mmio_needed = 0;
2198                 return EMULATE_DO_MMIO;
2199         }
2200
2201         return EMULATE_DONE;
2202 }
2203 EXPORT_SYMBOL_GPL(emulate_instruction);
2204
2205 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
2206 {
2207         int i;
2208
2209         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
2210                 if (vcpu->arch.pio.guest_pages[i]) {
2211                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
2212                         vcpu->arch.pio.guest_pages[i] = NULL;
2213                 }
2214 }
2215
2216 static int pio_copy_data(struct kvm_vcpu *vcpu)
2217 {
2218         void *p = vcpu->arch.pio_data;
2219         void *q;
2220         unsigned bytes;
2221         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
2222
2223         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
2224                  PAGE_KERNEL);
2225         if (!q) {
2226                 free_pio_guest_pages(vcpu);
2227                 return -ENOMEM;
2228         }
2229         q += vcpu->arch.pio.guest_page_offset;
2230         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2231         if (vcpu->arch.pio.in)
2232                 memcpy(q, p, bytes);
2233         else
2234                 memcpy(p, q, bytes);
2235         q -= vcpu->arch.pio.guest_page_offset;
2236         vunmap(q);
2237         free_pio_guest_pages(vcpu);
2238         return 0;
2239 }
2240
2241 int complete_pio(struct kvm_vcpu *vcpu)
2242 {
2243         struct kvm_pio_request *io = &vcpu->arch.pio;
2244         long delta;
2245         int r;
2246
2247         kvm_x86_ops->cache_regs(vcpu);
2248
2249         if (!io->string) {
2250                 if (io->in)
2251                         memcpy(&vcpu->arch.regs[VCPU_REGS_RAX], vcpu->arch.pio_data,
2252                                io->size);
2253         } else {
2254                 if (io->in) {
2255                         r = pio_copy_data(vcpu);
2256                         if (r) {
2257                                 kvm_x86_ops->cache_regs(vcpu);
2258                                 return r;
2259                         }
2260                 }
2261
2262                 delta = 1;
2263                 if (io->rep) {
2264                         delta *= io->cur_count;
2265                         /*
2266                          * The size of the register should really depend on
2267                          * current address size.
2268                          */
2269                         vcpu->arch.regs[VCPU_REGS_RCX] -= delta;
2270                 }
2271                 if (io->down)
2272                         delta = -delta;
2273                 delta *= io->size;
2274                 if (io->in)
2275                         vcpu->arch.regs[VCPU_REGS_RDI] += delta;
2276                 else
2277                         vcpu->arch.regs[VCPU_REGS_RSI] += delta;
2278         }
2279
2280         kvm_x86_ops->decache_regs(vcpu);
2281
2282         io->count -= io->cur_count;
2283         io->cur_count = 0;
2284
2285         return 0;
2286 }
2287
2288 static void kernel_pio(struct kvm_io_device *pio_dev,
2289                        struct kvm_vcpu *vcpu,
2290                        void *pd)
2291 {
2292         /* TODO: String I/O for in kernel device */
2293
2294         mutex_lock(&vcpu->kvm->lock);
2295         if (vcpu->arch.pio.in)
2296                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2297                                   vcpu->arch.pio.size,
2298                                   pd);
2299         else
2300                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2301                                    vcpu->arch.pio.size,
2302                                    pd);
2303         mutex_unlock(&vcpu->kvm->lock);
2304 }
2305
2306 static void pio_string_write(struct kvm_io_device *pio_dev,
2307                              struct kvm_vcpu *vcpu)
2308 {
2309         struct kvm_pio_request *io = &vcpu->arch.pio;
2310         void *pd = vcpu->arch.pio_data;
2311         int i;
2312
2313         mutex_lock(&vcpu->kvm->lock);
2314         for (i = 0; i < io->cur_count; i++) {
2315                 kvm_iodevice_write(pio_dev, io->port,
2316                                    io->size,
2317                                    pd);
2318                 pd += io->size;
2319         }
2320         mutex_unlock(&vcpu->kvm->lock);
2321 }
2322
2323 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2324                                                gpa_t addr, int len,
2325                                                int is_write)
2326 {
2327         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr, len, is_write);
2328 }
2329
2330 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2331                   int size, unsigned port)
2332 {
2333         struct kvm_io_device *pio_dev;
2334
2335         vcpu->run->exit_reason = KVM_EXIT_IO;
2336         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2337         vcpu->run->io.size = vcpu->arch.pio.size = size;
2338         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2339         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2340         vcpu->run->io.port = vcpu->arch.pio.port = port;
2341         vcpu->arch.pio.in = in;
2342         vcpu->arch.pio.string = 0;
2343         vcpu->arch.pio.down = 0;
2344         vcpu->arch.pio.guest_page_offset = 0;
2345         vcpu->arch.pio.rep = 0;
2346
2347         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2348                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2349                             handler);
2350         else
2351                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2352                             handler);
2353
2354         kvm_x86_ops->cache_regs(vcpu);
2355         memcpy(vcpu->arch.pio_data, &vcpu->arch.regs[VCPU_REGS_RAX], 4);
2356
2357         kvm_x86_ops->skip_emulated_instruction(vcpu);
2358
2359         pio_dev = vcpu_find_pio_dev(vcpu, port, size, !in);
2360         if (pio_dev) {
2361                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2362                 complete_pio(vcpu);
2363                 return 1;
2364         }
2365         return 0;
2366 }
2367 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2368
2369 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2370                   int size, unsigned long count, int down,
2371                   gva_t address, int rep, unsigned port)
2372 {
2373         unsigned now, in_page;
2374         int i, ret = 0;
2375         int nr_pages = 1;
2376         struct page *page;
2377         struct kvm_io_device *pio_dev;
2378
2379         vcpu->run->exit_reason = KVM_EXIT_IO;
2380         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2381         vcpu->run->io.size = vcpu->arch.pio.size = size;
2382         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2383         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2384         vcpu->run->io.port = vcpu->arch.pio.port = port;
2385         vcpu->arch.pio.in = in;
2386         vcpu->arch.pio.string = 1;
2387         vcpu->arch.pio.down = down;
2388         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2389         vcpu->arch.pio.rep = rep;
2390
2391         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2392                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2393                             handler);
2394         else
2395                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2396                             handler);
2397
2398         if (!count) {
2399                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2400                 return 1;
2401         }
2402
2403         if (!down)
2404                 in_page = PAGE_SIZE - offset_in_page(address);
2405         else
2406                 in_page = offset_in_page(address) + size;
2407         now = min(count, (unsigned long)in_page / size);
2408         if (!now) {
2409                 /*
2410                  * String I/O straddles page boundary.  Pin two guest pages
2411                  * so that we satisfy atomicity constraints.  Do just one
2412                  * transaction to avoid complexity.
2413                  */
2414                 nr_pages = 2;
2415                 now = 1;
2416         }
2417         if (down) {
2418                 /*
2419                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2420                  */
2421                 pr_unimpl(vcpu, "guest string pio down\n");
2422                 kvm_inject_gp(vcpu, 0);
2423                 return 1;
2424         }
2425         vcpu->run->io.count = now;
2426         vcpu->arch.pio.cur_count = now;
2427
2428         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2429                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2430
2431         for (i = 0; i < nr_pages; ++i) {
2432                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2433                 vcpu->arch.pio.guest_pages[i] = page;
2434                 if (!page) {
2435                         kvm_inject_gp(vcpu, 0);
2436                         free_pio_guest_pages(vcpu);
2437                         return 1;
2438                 }
2439         }
2440
2441         pio_dev = vcpu_find_pio_dev(vcpu, port,
2442                                     vcpu->arch.pio.cur_count,
2443                                     !vcpu->arch.pio.in);
2444         if (!vcpu->arch.pio.in) {
2445                 /* string PIO write */
2446                 ret = pio_copy_data(vcpu);
2447                 if (ret >= 0 && pio_dev) {
2448                         pio_string_write(pio_dev, vcpu);
2449                         complete_pio(vcpu);
2450                         if (vcpu->arch.pio.count == 0)
2451                                 ret = 1;
2452                 }
2453         } else if (pio_dev)
2454                 pr_unimpl(vcpu, "no string pio read support yet, "
2455                        "port %x size %d count %ld\n",
2456                         port, size, count);
2457
2458         return ret;
2459 }
2460 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2461
2462 int kvm_arch_init(void *opaque)
2463 {
2464         int r;
2465         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2466
2467         if (kvm_x86_ops) {
2468                 printk(KERN_ERR "kvm: already loaded the other module\n");
2469                 r = -EEXIST;
2470                 goto out;
2471         }
2472
2473         if (!ops->cpu_has_kvm_support()) {
2474                 printk(KERN_ERR "kvm: no hardware support\n");
2475                 r = -EOPNOTSUPP;
2476                 goto out;
2477         }
2478         if (ops->disabled_by_bios()) {
2479                 printk(KERN_ERR "kvm: disabled by bios\n");
2480                 r = -EOPNOTSUPP;
2481                 goto out;
2482         }
2483
2484         r = kvm_mmu_module_init();
2485         if (r)
2486                 goto out;
2487
2488         kvm_init_msr_list();
2489
2490         kvm_x86_ops = ops;
2491         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2492         kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
2493         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
2494                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
2495         return 0;
2496
2497 out:
2498         return r;
2499 }
2500
2501 void kvm_arch_exit(void)
2502 {
2503         kvm_x86_ops = NULL;
2504         kvm_mmu_module_exit();
2505 }
2506
2507 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2508 {
2509         ++vcpu->stat.halt_exits;
2510         KVMTRACE_0D(HLT, vcpu, handler);
2511         if (irqchip_in_kernel(vcpu->kvm)) {
2512                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
2513                 up_read(&vcpu->kvm->slots_lock);
2514                 kvm_vcpu_block(vcpu);
2515                 down_read(&vcpu->kvm->slots_lock);
2516                 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
2517                         return -EINTR;
2518                 return 1;
2519         } else {
2520                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2521                 return 0;
2522         }
2523 }
2524 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2525
2526 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2527                            unsigned long a1)
2528 {
2529         if (is_long_mode(vcpu))
2530                 return a0;
2531         else
2532                 return a0 | ((gpa_t)a1 << 32);
2533 }
2534
2535 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2536 {
2537         unsigned long nr, a0, a1, a2, a3, ret;
2538         int r = 1;
2539
2540         kvm_x86_ops->cache_regs(vcpu);
2541
2542         nr = vcpu->arch.regs[VCPU_REGS_RAX];
2543         a0 = vcpu->arch.regs[VCPU_REGS_RBX];
2544         a1 = vcpu->arch.regs[VCPU_REGS_RCX];
2545         a2 = vcpu->arch.regs[VCPU_REGS_RDX];
2546         a3 = vcpu->arch.regs[VCPU_REGS_RSI];
2547
2548         KVMTRACE_1D(VMMCALL, vcpu, (u32)nr, handler);
2549
2550         if (!is_long_mode(vcpu)) {
2551                 nr &= 0xFFFFFFFF;
2552                 a0 &= 0xFFFFFFFF;
2553                 a1 &= 0xFFFFFFFF;
2554                 a2 &= 0xFFFFFFFF;
2555                 a3 &= 0xFFFFFFFF;
2556         }
2557
2558         switch (nr) {
2559         case KVM_HC_VAPIC_POLL_IRQ:
2560                 ret = 0;
2561                 break;
2562         case KVM_HC_MMU_OP:
2563                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2564                 break;
2565         default:
2566                 ret = -KVM_ENOSYS;
2567                 break;
2568         }
2569         vcpu->arch.regs[VCPU_REGS_RAX] = ret;
2570         kvm_x86_ops->decache_regs(vcpu);
2571         ++vcpu->stat.hypercalls;
2572         return r;
2573 }
2574 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2575
2576 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2577 {
2578         char instruction[3];
2579         int ret = 0;
2580
2581
2582         /*
2583          * Blow out the MMU to ensure that no other VCPU has an active mapping
2584          * to ensure that the updated hypercall appears atomically across all
2585          * VCPUs.
2586          */
2587         kvm_mmu_zap_all(vcpu->kvm);
2588
2589         kvm_x86_ops->cache_regs(vcpu);
2590         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2591         if (emulator_write_emulated(vcpu->arch.rip, instruction, 3, vcpu)
2592             != X86EMUL_CONTINUE)
2593                 ret = -EFAULT;
2594
2595         return ret;
2596 }
2597
2598 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2599 {
2600         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2601 }
2602
2603 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2604 {
2605         struct descriptor_table dt = { limit, base };
2606
2607         kvm_x86_ops->set_gdt(vcpu, &dt);
2608 }
2609
2610 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2611 {
2612         struct descriptor_table dt = { limit, base };
2613
2614         kvm_x86_ops->set_idt(vcpu, &dt);
2615 }
2616
2617 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2618                    unsigned long *rflags)
2619 {
2620         kvm_lmsw(vcpu, msw);
2621         *rflags = kvm_x86_ops->get_rflags(vcpu);
2622 }
2623
2624 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2625 {
2626         unsigned long value;
2627
2628         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2629         switch (cr) {
2630         case 0:
2631                 value = vcpu->arch.cr0;
2632                 break;
2633         case 2:
2634                 value = vcpu->arch.cr2;
2635                 break;
2636         case 3:
2637                 value = vcpu->arch.cr3;
2638                 break;
2639         case 4:
2640                 value = vcpu->arch.cr4;
2641                 break;
2642         case 8:
2643                 value = kvm_get_cr8(vcpu);
2644                 break;
2645         default:
2646                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2647                 return 0;
2648         }
2649         KVMTRACE_3D(CR_READ, vcpu, (u32)cr, (u32)value,
2650                     (u32)((u64)value >> 32), handler);
2651
2652         return value;
2653 }
2654
2655 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2656                      unsigned long *rflags)
2657 {
2658         KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)val,
2659                     (u32)((u64)val >> 32), handler);
2660
2661         switch (cr) {
2662         case 0:
2663                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2664                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2665                 break;
2666         case 2:
2667                 vcpu->arch.cr2 = val;
2668                 break;
2669         case 3:
2670                 kvm_set_cr3(vcpu, val);
2671                 break;
2672         case 4:
2673                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2674                 break;
2675         case 8:
2676                 kvm_set_cr8(vcpu, val & 0xfUL);
2677                 break;
2678         default:
2679                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2680         }
2681 }
2682
2683 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2684 {
2685         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2686         int j, nent = vcpu->arch.cpuid_nent;
2687
2688         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2689         /* when no next entry is found, the current entry[i] is reselected */
2690         for (j = i + 1; j == i; j = (j + 1) % nent) {
2691                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2692                 if (ej->function == e->function) {
2693                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2694                         return j;
2695                 }
2696         }
2697         return 0; /* silence gcc, even though control never reaches here */
2698 }
2699
2700 /* find an entry with matching function, matching index (if needed), and that
2701  * should be read next (if it's stateful) */
2702 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2703         u32 function, u32 index)
2704 {
2705         if (e->function != function)
2706                 return 0;
2707         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2708                 return 0;
2709         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2710                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2711                 return 0;
2712         return 1;
2713 }
2714
2715 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2716 {
2717         int i;
2718         u32 function, index;
2719         struct kvm_cpuid_entry2 *e, *best;
2720
2721         kvm_x86_ops->cache_regs(vcpu);
2722         function = vcpu->arch.regs[VCPU_REGS_RAX];
2723         index = vcpu->arch.regs[VCPU_REGS_RCX];
2724         vcpu->arch.regs[VCPU_REGS_RAX] = 0;
2725         vcpu->arch.regs[VCPU_REGS_RBX] = 0;
2726         vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2727         vcpu->arch.regs[VCPU_REGS_RDX] = 0;
2728         best = NULL;
2729         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2730                 e = &vcpu->arch.cpuid_entries[i];
2731                 if (is_matching_cpuid_entry(e, function, index)) {
2732                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2733                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2734                         best = e;
2735                         break;
2736                 }
2737                 /*
2738                  * Both basic or both extended?
2739                  */
2740                 if (((e->function ^ function) & 0x80000000) == 0)
2741                         if (!best || e->function > best->function)
2742                                 best = e;
2743         }
2744         if (best) {
2745                 vcpu->arch.regs[VCPU_REGS_RAX] = best->eax;
2746                 vcpu->arch.regs[VCPU_REGS_RBX] = best->ebx;
2747                 vcpu->arch.regs[VCPU_REGS_RCX] = best->ecx;
2748                 vcpu->arch.regs[VCPU_REGS_RDX] = best->edx;
2749         }
2750         kvm_x86_ops->decache_regs(vcpu);
2751         kvm_x86_ops->skip_emulated_instruction(vcpu);
2752         KVMTRACE_5D(CPUID, vcpu, function,
2753                     (u32)vcpu->arch.regs[VCPU_REGS_RAX],
2754                     (u32)vcpu->arch.regs[VCPU_REGS_RBX],
2755                     (u32)vcpu->arch.regs[VCPU_REGS_RCX],
2756                     (u32)vcpu->arch.regs[VCPU_REGS_RDX], handler);
2757 }
2758 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2759
2760 /*
2761  * Check if userspace requested an interrupt window, and that the
2762  * interrupt window is open.
2763  *
2764  * No need to exit to userspace if we already have an interrupt queued.
2765  */
2766 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2767                                           struct kvm_run *kvm_run)
2768 {
2769         return (!vcpu->arch.irq_summary &&
2770                 kvm_run->request_interrupt_window &&
2771                 vcpu->arch.interrupt_window_open &&
2772                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2773 }
2774
2775 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2776                               struct kvm_run *kvm_run)
2777 {
2778         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2779         kvm_run->cr8 = kvm_get_cr8(vcpu);
2780         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2781         if (irqchip_in_kernel(vcpu->kvm))
2782                 kvm_run->ready_for_interrupt_injection = 1;
2783         else
2784                 kvm_run->ready_for_interrupt_injection =
2785                                         (vcpu->arch.interrupt_window_open &&
2786                                          vcpu->arch.irq_summary == 0);
2787 }
2788
2789 static void vapic_enter(struct kvm_vcpu *vcpu)
2790 {
2791         struct kvm_lapic *apic = vcpu->arch.apic;
2792         struct page *page;
2793
2794         if (!apic || !apic->vapic_addr)
2795                 return;
2796
2797         down_read(&current->mm->mmap_sem);
2798         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2799         up_read(&current->mm->mmap_sem);
2800
2801         vcpu->arch.apic->vapic_page = page;
2802 }
2803
2804 static void vapic_exit(struct kvm_vcpu *vcpu)
2805 {
2806         struct kvm_lapic *apic = vcpu->arch.apic;
2807
2808         if (!apic || !apic->vapic_addr)
2809                 return;
2810
2811         down_read(&vcpu->kvm->slots_lock);
2812         kvm_release_page_dirty(apic->vapic_page);
2813         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2814         up_read(&vcpu->kvm->slots_lock);
2815 }
2816
2817 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2818 {
2819         int r;
2820
2821         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
2822                 pr_debug("vcpu %d received sipi with vector # %x\n",
2823                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
2824                 kvm_lapic_reset(vcpu);
2825                 r = kvm_x86_ops->vcpu_reset(vcpu);
2826                 if (r)
2827                         return r;
2828                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2829         }
2830
2831         down_read(&vcpu->kvm->slots_lock);
2832         vapic_enter(vcpu);
2833
2834 preempted:
2835         if (vcpu->guest_debug.enabled)
2836                 kvm_x86_ops->guest_debug_pre(vcpu);
2837
2838 again:
2839         if (vcpu->requests)
2840                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
2841                         kvm_mmu_unload(vcpu);
2842
2843         r = kvm_mmu_reload(vcpu);
2844         if (unlikely(r))
2845                 goto out;
2846
2847         if (vcpu->requests) {
2848                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
2849                         __kvm_migrate_timers(vcpu);
2850                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2851                         kvm_x86_ops->tlb_flush(vcpu);
2852                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
2853                                        &vcpu->requests)) {
2854                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
2855                         r = 0;
2856                         goto out;
2857                 }
2858                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
2859                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2860                         r = 0;
2861                         goto out;
2862                 }
2863         }
2864
2865         clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
2866         kvm_inject_pending_timer_irqs(vcpu);
2867
2868         preempt_disable();
2869
2870         kvm_x86_ops->prepare_guest_switch(vcpu);
2871         kvm_load_guest_fpu(vcpu);
2872
2873         local_irq_disable();
2874
2875         if (vcpu->requests || need_resched()) {
2876                 local_irq_enable();
2877                 preempt_enable();
2878                 r = 1;
2879                 goto out;
2880         }
2881
2882         if (signal_pending(current)) {
2883                 local_irq_enable();
2884                 preempt_enable();
2885                 r = -EINTR;
2886                 kvm_run->exit_reason = KVM_EXIT_INTR;
2887                 ++vcpu->stat.signal_exits;
2888                 goto out;
2889         }
2890
2891         vcpu->guest_mode = 1;
2892         /*
2893          * Make sure that guest_mode assignment won't happen after
2894          * testing the pending IRQ vector bitmap.
2895          */
2896         smp_wmb();
2897
2898         if (vcpu->arch.exception.pending)
2899                 __queue_exception(vcpu);
2900         else if (irqchip_in_kernel(vcpu->kvm))
2901                 kvm_x86_ops->inject_pending_irq(vcpu);
2902         else
2903                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
2904
2905         kvm_lapic_sync_to_vapic(vcpu);
2906
2907         up_read(&vcpu->kvm->slots_lock);
2908
2909         kvm_guest_enter();
2910
2911
2912         KVMTRACE_0D(VMENTRY, vcpu, entryexit);
2913         kvm_x86_ops->run(vcpu, kvm_run);
2914
2915         vcpu->guest_mode = 0;
2916         local_irq_enable();
2917
2918         ++vcpu->stat.exits;
2919
2920         /*
2921          * We must have an instruction between local_irq_enable() and
2922          * kvm_guest_exit(), so the timer interrupt isn't delayed by
2923          * the interrupt shadow.  The stat.exits increment will do nicely.
2924          * But we need to prevent reordering, hence this barrier():
2925          */
2926         barrier();
2927
2928         kvm_guest_exit();
2929
2930         preempt_enable();
2931
2932         down_read(&vcpu->kvm->slots_lock);
2933
2934         /*
2935          * Profile KVM exit RIPs:
2936          */
2937         if (unlikely(prof_on == KVM_PROFILING)) {
2938                 kvm_x86_ops->cache_regs(vcpu);
2939                 profile_hit(KVM_PROFILING, (void *)vcpu->arch.rip);
2940         }
2941
2942         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
2943                 vcpu->arch.exception.pending = false;
2944
2945         kvm_lapic_sync_from_vapic(vcpu);
2946
2947         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2948
2949         if (r > 0) {
2950                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2951                         r = -EINTR;
2952                         kvm_run->exit_reason = KVM_EXIT_INTR;
2953                         ++vcpu->stat.request_irq_exits;
2954                         goto out;
2955                 }
2956                 if (!need_resched())
2957                         goto again;
2958         }
2959
2960 out:
2961         up_read(&vcpu->kvm->slots_lock);
2962         if (r > 0) {
2963                 kvm_resched(vcpu);
2964                 down_read(&vcpu->kvm->slots_lock);
2965                 goto preempted;
2966         }
2967
2968         post_kvm_run_save(vcpu, kvm_run);
2969
2970         vapic_exit(vcpu);
2971
2972         return r;
2973 }
2974
2975 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2976 {
2977         int r;
2978         sigset_t sigsaved;
2979
2980         vcpu_load(vcpu);
2981
2982         if (vcpu->sigset_active)
2983                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2984
2985         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
2986                 kvm_vcpu_block(vcpu);
2987                 r = -EAGAIN;
2988                 goto out;
2989         }
2990
2991         /* re-sync apic's tpr */
2992         if (!irqchip_in_kernel(vcpu->kvm))
2993                 kvm_set_cr8(vcpu, kvm_run->cr8);
2994
2995         if (vcpu->arch.pio.cur_count) {
2996                 r = complete_pio(vcpu);
2997                 if (r)
2998                         goto out;
2999         }
3000 #if CONFIG_HAS_IOMEM
3001         if (vcpu->mmio_needed) {
3002                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
3003                 vcpu->mmio_read_completed = 1;
3004                 vcpu->mmio_needed = 0;
3005
3006                 down_read(&vcpu->kvm->slots_lock);
3007                 r = emulate_instruction(vcpu, kvm_run,
3008                                         vcpu->arch.mmio_fault_cr2, 0,
3009                                         EMULTYPE_NO_DECODE);
3010                 up_read(&vcpu->kvm->slots_lock);
3011                 if (r == EMULATE_DO_MMIO) {
3012                         /*
3013                          * Read-modify-write.  Back to userspace.
3014                          */
3015                         r = 0;
3016                         goto out;
3017                 }
3018         }
3019 #endif
3020         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
3021                 kvm_x86_ops->cache_regs(vcpu);
3022                 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
3023                 kvm_x86_ops->decache_regs(vcpu);
3024         }
3025
3026         r = __vcpu_run(vcpu, kvm_run);
3027
3028 out:
3029         if (vcpu->sigset_active)
3030                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
3031
3032         vcpu_put(vcpu);
3033         return r;
3034 }
3035
3036 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3037 {
3038         vcpu_load(vcpu);
3039
3040         kvm_x86_ops->cache_regs(vcpu);
3041
3042         regs->rax = vcpu->arch.regs[VCPU_REGS_RAX];
3043         regs->rbx = vcpu->arch.regs[VCPU_REGS_RBX];
3044         regs->rcx = vcpu->arch.regs[VCPU_REGS_RCX];
3045         regs->rdx = vcpu->arch.regs[VCPU_REGS_RDX];
3046         regs->rsi = vcpu->arch.regs[VCPU_REGS_RSI];
3047         regs->rdi = vcpu->arch.regs[VCPU_REGS_RDI];
3048         regs->rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3049         regs->rbp = vcpu->arch.regs[VCPU_REGS_RBP];
3050 #ifdef CONFIG_X86_64
3051         regs->r8 = vcpu->arch.regs[VCPU_REGS_R8];
3052         regs->r9 = vcpu->arch.regs[VCPU_REGS_R9];
3053         regs->r10 = vcpu->arch.regs[VCPU_REGS_R10];
3054         regs->r11 = vcpu->arch.regs[VCPU_REGS_R11];
3055         regs->r12 = vcpu->arch.regs[VCPU_REGS_R12];
3056         regs->r13 = vcpu->arch.regs[VCPU_REGS_R13];
3057         regs->r14 = vcpu->arch.regs[VCPU_REGS_R14];
3058         regs->r15 = vcpu->arch.regs[VCPU_REGS_R15];
3059 #endif
3060
3061         regs->rip = vcpu->arch.rip;
3062         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
3063
3064         /*
3065          * Don't leak debug flags in case they were set for guest debugging
3066          */
3067         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
3068                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
3069
3070         vcpu_put(vcpu);
3071
3072         return 0;
3073 }
3074
3075 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3076 {
3077         vcpu_load(vcpu);
3078
3079         vcpu->arch.regs[VCPU_REGS_RAX] = regs->rax;
3080         vcpu->arch.regs[VCPU_REGS_RBX] = regs->rbx;
3081         vcpu->arch.regs[VCPU_REGS_RCX] = regs->rcx;
3082         vcpu->arch.regs[VCPU_REGS_RDX] = regs->rdx;
3083         vcpu->arch.regs[VCPU_REGS_RSI] = regs->rsi;
3084         vcpu->arch.regs[VCPU_REGS_RDI] = regs->rdi;
3085         vcpu->arch.regs[VCPU_REGS_RSP] = regs->rsp;
3086         vcpu->arch.regs[VCPU_REGS_RBP] = regs->rbp;
3087 #ifdef CONFIG_X86_64
3088         vcpu->arch.regs[VCPU_REGS_R8] = regs->r8;
3089         vcpu->arch.regs[VCPU_REGS_R9] = regs->r9;
3090         vcpu->arch.regs[VCPU_REGS_R10] = regs->r10;
3091         vcpu->arch.regs[VCPU_REGS_R11] = regs->r11;
3092         vcpu->arch.regs[VCPU_REGS_R12] = regs->r12;
3093         vcpu->arch.regs[VCPU_REGS_R13] = regs->r13;
3094         vcpu->arch.regs[VCPU_REGS_R14] = regs->r14;
3095         vcpu->arch.regs[VCPU_REGS_R15] = regs->r15;
3096 #endif
3097
3098         vcpu->arch.rip = regs->rip;
3099         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
3100
3101         kvm_x86_ops->decache_regs(vcpu);
3102
3103         vcpu->arch.exception.pending = false;
3104
3105         vcpu_put(vcpu);
3106
3107         return 0;
3108 }
3109
3110 void kvm_get_segment(struct kvm_vcpu *vcpu,
3111                      struct kvm_segment *var, int seg)
3112 {
3113         kvm_x86_ops->get_segment(vcpu, var, seg);
3114 }
3115
3116 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3117 {
3118         struct kvm_segment cs;
3119
3120         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
3121         *db = cs.db;
3122         *l = cs.l;
3123 }
3124 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3125
3126 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3127                                   struct kvm_sregs *sregs)
3128 {
3129         struct descriptor_table dt;
3130         int pending_vec;
3131
3132         vcpu_load(vcpu);
3133
3134         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3135         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3136         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3137         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3138         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3139         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3140
3141         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3142         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3143
3144         kvm_x86_ops->get_idt(vcpu, &dt);
3145         sregs->idt.limit = dt.limit;
3146         sregs->idt.base = dt.base;
3147         kvm_x86_ops->get_gdt(vcpu, &dt);
3148         sregs->gdt.limit = dt.limit;
3149         sregs->gdt.base = dt.base;
3150
3151         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3152         sregs->cr0 = vcpu->arch.cr0;
3153         sregs->cr2 = vcpu->arch.cr2;
3154         sregs->cr3 = vcpu->arch.cr3;
3155         sregs->cr4 = vcpu->arch.cr4;
3156         sregs->cr8 = kvm_get_cr8(vcpu);
3157         sregs->efer = vcpu->arch.shadow_efer;
3158         sregs->apic_base = kvm_get_apic_base(vcpu);
3159
3160         if (irqchip_in_kernel(vcpu->kvm)) {
3161                 memset(sregs->interrupt_bitmap, 0,
3162                        sizeof sregs->interrupt_bitmap);
3163                 pending_vec = kvm_x86_ops->get_irq(vcpu);
3164                 if (pending_vec >= 0)
3165                         set_bit(pending_vec,
3166                                 (unsigned long *)sregs->interrupt_bitmap);
3167         } else
3168                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
3169                        sizeof sregs->interrupt_bitmap);
3170
3171         vcpu_put(vcpu);
3172
3173         return 0;
3174 }
3175
3176 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
3177                                     struct kvm_mp_state *mp_state)
3178 {
3179         vcpu_load(vcpu);
3180         mp_state->mp_state = vcpu->arch.mp_state;
3181         vcpu_put(vcpu);
3182         return 0;
3183 }
3184
3185 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
3186                                     struct kvm_mp_state *mp_state)
3187 {
3188         vcpu_load(vcpu);
3189         vcpu->arch.mp_state = mp_state->mp_state;
3190         vcpu_put(vcpu);
3191         return 0;
3192 }
3193
3194 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3195                         struct kvm_segment *var, int seg)
3196 {
3197         kvm_x86_ops->set_segment(vcpu, var, seg);
3198 }
3199
3200 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
3201                                    struct kvm_segment *kvm_desct)
3202 {
3203         kvm_desct->base = seg_desc->base0;
3204         kvm_desct->base |= seg_desc->base1 << 16;
3205         kvm_desct->base |= seg_desc->base2 << 24;
3206         kvm_desct->limit = seg_desc->limit0;
3207         kvm_desct->limit |= seg_desc->limit << 16;
3208         if (seg_desc->g) {
3209                 kvm_desct->limit <<= 12;
3210                 kvm_desct->limit |= 0xfff;
3211         }
3212         kvm_desct->selector = selector;
3213         kvm_desct->type = seg_desc->type;
3214         kvm_desct->present = seg_desc->p;
3215         kvm_desct->dpl = seg_desc->dpl;
3216         kvm_desct->db = seg_desc->d;
3217         kvm_desct->s = seg_desc->s;
3218         kvm_desct->l = seg_desc->l;
3219         kvm_desct->g = seg_desc->g;
3220         kvm_desct->avl = seg_desc->avl;
3221         if (!selector)
3222                 kvm_desct->unusable = 1;
3223         else
3224                 kvm_desct->unusable = 0;
3225         kvm_desct->padding = 0;
3226 }
3227
3228 static void get_segment_descritptor_dtable(struct kvm_vcpu *vcpu,
3229                                            u16 selector,
3230                                            struct descriptor_table *dtable)
3231 {
3232         if (selector & 1 << 2) {
3233                 struct kvm_segment kvm_seg;
3234
3235                 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
3236
3237                 if (kvm_seg.unusable)
3238                         dtable->limit = 0;
3239                 else
3240                         dtable->limit = kvm_seg.limit;
3241                 dtable->base = kvm_seg.base;
3242         }
3243         else
3244                 kvm_x86_ops->get_gdt(vcpu, dtable);
3245 }
3246
3247 /* allowed just for 8 bytes segments */
3248 static int load_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                 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
3259                 return 1;
3260         }
3261         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3262         gpa += index * 8;
3263         return kvm_read_guest(vcpu->kvm, gpa, seg_desc, 8);
3264 }
3265
3266 /* allowed just for 8 bytes segments */
3267 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3268                                          struct desc_struct *seg_desc)
3269 {
3270         gpa_t gpa;
3271         struct descriptor_table dtable;
3272         u16 index = selector >> 3;
3273
3274         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3275
3276         if (dtable.limit < index * 8 + 7)
3277                 return 1;
3278         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3279         gpa += index * 8;
3280         return kvm_write_guest(vcpu->kvm, gpa, seg_desc, 8);
3281 }
3282
3283 static u32 get_tss_base_addr(struct kvm_vcpu *vcpu,
3284                              struct desc_struct *seg_desc)
3285 {
3286         u32 base_addr;
3287
3288         base_addr = seg_desc->base0;
3289         base_addr |= (seg_desc->base1 << 16);
3290         base_addr |= (seg_desc->base2 << 24);
3291
3292         return vcpu->arch.mmu.gva_to_gpa(vcpu, base_addr);
3293 }
3294
3295 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
3296 {
3297         struct kvm_segment kvm_seg;
3298
3299         kvm_get_segment(vcpu, &kvm_seg, seg);
3300         return kvm_seg.selector;
3301 }
3302
3303 static int load_segment_descriptor_to_kvm_desct(struct kvm_vcpu *vcpu,
3304                                                 u16 selector,
3305                                                 struct kvm_segment *kvm_seg)
3306 {
3307         struct desc_struct seg_desc;
3308
3309         if (load_guest_segment_descriptor(vcpu, selector, &seg_desc))
3310                 return 1;
3311         seg_desct_to_kvm_desct(&seg_desc, selector, kvm_seg);
3312         return 0;
3313 }
3314
3315 int kvm_load_realmode_segment(struct kvm_vcpu *vcpu, u16 selector, int seg)
3316 {
3317         struct kvm_segment segvar = {
3318                 .base = selector << 4,
3319                 .limit = 0xffff,
3320                 .selector = selector,
3321                 .type = 3,
3322                 .present = 1,
3323                 .dpl = 3,
3324                 .db = 0,
3325                 .s = 1,
3326                 .l = 0,
3327                 .g = 0,
3328                 .avl = 0,
3329                 .unusable = 0,
3330         };
3331         kvm_x86_ops->set_segment(vcpu, &segvar, seg);
3332         return 0;
3333 }
3334
3335 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3336                                 int type_bits, int seg)
3337 {
3338         struct kvm_segment kvm_seg;
3339
3340         if (!(vcpu->arch.cr0 & X86_CR0_PE))
3341                 return kvm_load_realmode_segment(vcpu, selector, seg);
3342         if (load_segment_descriptor_to_kvm_desct(vcpu, selector, &kvm_seg))
3343                 return 1;
3344         kvm_seg.type |= type_bits;
3345
3346         if (seg != VCPU_SREG_SS && seg != VCPU_SREG_CS &&
3347             seg != VCPU_SREG_LDTR)
3348                 if (!kvm_seg.s)
3349                         kvm_seg.unusable = 1;
3350
3351         kvm_set_segment(vcpu, &kvm_seg, seg);
3352         return 0;
3353 }
3354
3355 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
3356                                 struct tss_segment_32 *tss)
3357 {
3358         tss->cr3 = vcpu->arch.cr3;
3359         tss->eip = vcpu->arch.rip;
3360         tss->eflags = kvm_x86_ops->get_rflags(vcpu);
3361         tss->eax = vcpu->arch.regs[VCPU_REGS_RAX];
3362         tss->ecx = vcpu->arch.regs[VCPU_REGS_RCX];
3363         tss->edx = vcpu->arch.regs[VCPU_REGS_RDX];
3364         tss->ebx = vcpu->arch.regs[VCPU_REGS_RBX];
3365         tss->esp = vcpu->arch.regs[VCPU_REGS_RSP];
3366         tss->ebp = vcpu->arch.regs[VCPU_REGS_RBP];
3367         tss->esi = vcpu->arch.regs[VCPU_REGS_RSI];
3368         tss->edi = vcpu->arch.regs[VCPU_REGS_RDI];
3369
3370         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3371         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3372         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3373         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3374         tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
3375         tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
3376         tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3377         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3378 }
3379
3380 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
3381                                   struct tss_segment_32 *tss)
3382 {
3383         kvm_set_cr3(vcpu, tss->cr3);
3384
3385         vcpu->arch.rip = tss->eip;
3386         kvm_x86_ops->set_rflags(vcpu, tss->eflags | 2);
3387
3388         vcpu->arch.regs[VCPU_REGS_RAX] = tss->eax;
3389         vcpu->arch.regs[VCPU_REGS_RCX] = tss->ecx;
3390         vcpu->arch.regs[VCPU_REGS_RDX] = tss->edx;
3391         vcpu->arch.regs[VCPU_REGS_RBX] = tss->ebx;
3392         vcpu->arch.regs[VCPU_REGS_RSP] = tss->esp;
3393         vcpu->arch.regs[VCPU_REGS_RBP] = tss->ebp;
3394         vcpu->arch.regs[VCPU_REGS_RSI] = tss->esi;
3395         vcpu->arch.regs[VCPU_REGS_RDI] = tss->edi;
3396
3397         if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, 0, VCPU_SREG_LDTR))
3398                 return 1;
3399
3400         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3401                 return 1;
3402
3403         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3404                 return 1;
3405
3406         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3407                 return 1;
3408
3409         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3410                 return 1;
3411
3412         if (kvm_load_segment_descriptor(vcpu, tss->fs, 1, VCPU_SREG_FS))
3413                 return 1;
3414
3415         if (kvm_load_segment_descriptor(vcpu, tss->gs, 1, VCPU_SREG_GS))
3416                 return 1;
3417         return 0;
3418 }
3419
3420 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
3421                                 struct tss_segment_16 *tss)
3422 {
3423         tss->ip = vcpu->arch.rip;
3424         tss->flag = kvm_x86_ops->get_rflags(vcpu);
3425         tss->ax = vcpu->arch.regs[VCPU_REGS_RAX];
3426         tss->cx = vcpu->arch.regs[VCPU_REGS_RCX];
3427         tss->dx = vcpu->arch.regs[VCPU_REGS_RDX];
3428         tss->bx = vcpu->arch.regs[VCPU_REGS_RBX];
3429         tss->sp = vcpu->arch.regs[VCPU_REGS_RSP];
3430         tss->bp = vcpu->arch.regs[VCPU_REGS_RBP];
3431         tss->si = vcpu->arch.regs[VCPU_REGS_RSI];
3432         tss->di = vcpu->arch.regs[VCPU_REGS_RDI];
3433
3434         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3435         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3436         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3437         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3438         tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3439         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3440 }
3441
3442 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
3443                                  struct tss_segment_16 *tss)
3444 {
3445         vcpu->arch.rip = tss->ip;
3446         kvm_x86_ops->set_rflags(vcpu, tss->flag | 2);
3447         vcpu->arch.regs[VCPU_REGS_RAX] = tss->ax;
3448         vcpu->arch.regs[VCPU_REGS_RCX] = tss->cx;
3449         vcpu->arch.regs[VCPU_REGS_RDX] = tss->dx;
3450         vcpu->arch.regs[VCPU_REGS_RBX] = tss->bx;
3451         vcpu->arch.regs[VCPU_REGS_RSP] = tss->sp;
3452         vcpu->arch.regs[VCPU_REGS_RBP] = tss->bp;
3453         vcpu->arch.regs[VCPU_REGS_RSI] = tss->si;
3454         vcpu->arch.regs[VCPU_REGS_RDI] = tss->di;
3455
3456         if (kvm_load_segment_descriptor(vcpu, tss->ldt, 0, VCPU_SREG_LDTR))
3457                 return 1;
3458
3459         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3460                 return 1;
3461
3462         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3463                 return 1;
3464
3465         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3466                 return 1;
3467
3468         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3469                 return 1;
3470         return 0;
3471 }
3472
3473 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
3474                        u32 old_tss_base,
3475                        struct desc_struct *nseg_desc)
3476 {
3477         struct tss_segment_16 tss_segment_16;
3478         int ret = 0;
3479
3480         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3481                            sizeof tss_segment_16))
3482                 goto out;
3483
3484         save_state_to_tss16(vcpu, &tss_segment_16);
3485
3486         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3487                             sizeof tss_segment_16))
3488                 goto out;
3489
3490         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3491                            &tss_segment_16, sizeof tss_segment_16))
3492                 goto out;
3493
3494         if (load_state_from_tss16(vcpu, &tss_segment_16))
3495                 goto out;
3496
3497         ret = 1;
3498 out:
3499         return ret;
3500 }
3501
3502 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
3503                        u32 old_tss_base,
3504                        struct desc_struct *nseg_desc)
3505 {
3506         struct tss_segment_32 tss_segment_32;
3507         int ret = 0;
3508
3509         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3510                            sizeof tss_segment_32))
3511                 goto out;
3512
3513         save_state_to_tss32(vcpu, &tss_segment_32);
3514
3515         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3516                             sizeof tss_segment_32))
3517                 goto out;
3518
3519         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3520                            &tss_segment_32, sizeof tss_segment_32))
3521                 goto out;
3522
3523         if (load_state_from_tss32(vcpu, &tss_segment_32))
3524                 goto out;
3525
3526         ret = 1;
3527 out:
3528         return ret;
3529 }
3530
3531 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
3532 {
3533         struct kvm_segment tr_seg;
3534         struct desc_struct cseg_desc;
3535         struct desc_struct nseg_desc;
3536         int ret = 0;
3537         u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
3538         u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
3539
3540         old_tss_base = vcpu->arch.mmu.gva_to_gpa(vcpu, old_tss_base);
3541
3542         /* FIXME: Handle errors. Failure to read either TSS or their
3543          * descriptors should generate a pagefault.
3544          */
3545         if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
3546                 goto out;
3547
3548         if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
3549                 goto out;
3550
3551         if (reason != TASK_SWITCH_IRET) {
3552                 int cpl;
3553
3554                 cpl = kvm_x86_ops->get_cpl(vcpu);
3555                 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
3556                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
3557                         return 1;
3558                 }
3559         }
3560
3561         if (!nseg_desc.p || (nseg_desc.limit0 | nseg_desc.limit << 16) < 0x67) {
3562                 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
3563                 return 1;
3564         }
3565
3566         if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
3567                 cseg_desc.type &= ~(1 << 1); //clear the B flag
3568                 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
3569         }
3570
3571         if (reason == TASK_SWITCH_IRET) {
3572                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3573                 kvm_x86_ops->set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
3574         }
3575
3576         kvm_x86_ops->skip_emulated_instruction(vcpu);
3577         kvm_x86_ops->cache_regs(vcpu);
3578
3579         if (nseg_desc.type & 8)
3580                 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_base,
3581                                          &nseg_desc);
3582         else
3583                 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_base,
3584                                          &nseg_desc);
3585
3586         if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
3587                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3588                 kvm_x86_ops->set_rflags(vcpu, eflags | X86_EFLAGS_NT);
3589         }
3590
3591         if (reason != TASK_SWITCH_IRET) {
3592                 nseg_desc.type |= (1 << 1);
3593                 save_guest_segment_descriptor(vcpu, tss_selector,
3594                                               &nseg_desc);
3595         }
3596
3597         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_TS);
3598         seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
3599         tr_seg.type = 11;
3600         kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
3601 out:
3602         kvm_x86_ops->decache_regs(vcpu);
3603         return ret;
3604 }
3605 EXPORT_SYMBOL_GPL(kvm_task_switch);
3606
3607 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
3608                                   struct kvm_sregs *sregs)
3609 {
3610         int mmu_reset_needed = 0;
3611         int i, pending_vec, max_bits;
3612         struct descriptor_table dt;
3613
3614         vcpu_load(vcpu);
3615
3616         dt.limit = sregs->idt.limit;
3617         dt.base = sregs->idt.base;
3618         kvm_x86_ops->set_idt(vcpu, &dt);
3619         dt.limit = sregs->gdt.limit;
3620         dt.base = sregs->gdt.base;
3621         kvm_x86_ops->set_gdt(vcpu, &dt);
3622
3623         vcpu->arch.cr2 = sregs->cr2;
3624         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
3625         vcpu->arch.cr3 = sregs->cr3;
3626
3627         kvm_set_cr8(vcpu, sregs->cr8);
3628
3629         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
3630         kvm_x86_ops->set_efer(vcpu, sregs->efer);
3631         kvm_set_apic_base(vcpu, sregs->apic_base);
3632
3633         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3634
3635         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
3636         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
3637         vcpu->arch.cr0 = sregs->cr0;
3638
3639         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
3640         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3641         if (!is_long_mode(vcpu) && is_pae(vcpu))
3642                 load_pdptrs(vcpu, vcpu->arch.cr3);
3643
3644         if (mmu_reset_needed)
3645                 kvm_mmu_reset_context(vcpu);
3646
3647         if (!irqchip_in_kernel(vcpu->kvm)) {
3648                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
3649                        sizeof vcpu->arch.irq_pending);
3650                 vcpu->arch.irq_summary = 0;
3651                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
3652                         if (vcpu->arch.irq_pending[i])
3653                                 __set_bit(i, &vcpu->arch.irq_summary);
3654         } else {
3655                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
3656                 pending_vec = find_first_bit(
3657                         (const unsigned long *)sregs->interrupt_bitmap,
3658                         max_bits);
3659                 /* Only pending external irq is handled here */
3660                 if (pending_vec < max_bits) {
3661                         kvm_x86_ops->set_irq(vcpu, pending_vec);
3662                         pr_debug("Set back pending irq %d\n",
3663                                  pending_vec);
3664                 }
3665         }
3666
3667         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3668         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3669         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3670         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3671         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3672         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3673
3674         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3675         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3676
3677         vcpu_put(vcpu);
3678
3679         return 0;
3680 }
3681
3682 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
3683                                     struct kvm_debug_guest *dbg)
3684 {
3685         int r;
3686
3687         vcpu_load(vcpu);
3688
3689         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
3690
3691         vcpu_put(vcpu);
3692
3693         return r;
3694 }
3695
3696 /*
3697  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
3698  * we have asm/x86/processor.h
3699  */
3700 struct fxsave {
3701         u16     cwd;
3702         u16     swd;
3703         u16     twd;
3704         u16     fop;
3705         u64     rip;
3706         u64     rdp;
3707         u32     mxcsr;
3708         u32     mxcsr_mask;
3709         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
3710 #ifdef CONFIG_X86_64
3711         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
3712 #else
3713         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
3714 #endif
3715 };
3716
3717 /*
3718  * Translate a guest virtual address to a guest physical address.
3719  */
3720 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
3721                                     struct kvm_translation *tr)
3722 {
3723         unsigned long vaddr = tr->linear_address;
3724         gpa_t gpa;
3725
3726         vcpu_load(vcpu);
3727         down_read(&vcpu->kvm->slots_lock);
3728         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
3729         up_read(&vcpu->kvm->slots_lock);
3730         tr->physical_address = gpa;
3731         tr->valid = gpa != UNMAPPED_GVA;
3732         tr->writeable = 1;
3733         tr->usermode = 0;
3734         vcpu_put(vcpu);
3735
3736         return 0;
3737 }
3738
3739 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3740 {
3741         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3742
3743         vcpu_load(vcpu);
3744
3745         memcpy(fpu->fpr, fxsave->st_space, 128);
3746         fpu->fcw = fxsave->cwd;
3747         fpu->fsw = fxsave->swd;
3748         fpu->ftwx = fxsave->twd;
3749         fpu->last_opcode = fxsave->fop;
3750         fpu->last_ip = fxsave->rip;
3751         fpu->last_dp = fxsave->rdp;
3752         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
3753
3754         vcpu_put(vcpu);
3755
3756         return 0;
3757 }
3758
3759 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3760 {
3761         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3762
3763         vcpu_load(vcpu);
3764
3765         memcpy(fxsave->st_space, fpu->fpr, 128);
3766         fxsave->cwd = fpu->fcw;
3767         fxsave->swd = fpu->fsw;
3768         fxsave->twd = fpu->ftwx;
3769         fxsave->fop = fpu->last_opcode;
3770         fxsave->rip = fpu->last_ip;
3771         fxsave->rdp = fpu->last_dp;
3772         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
3773
3774         vcpu_put(vcpu);
3775
3776         return 0;
3777 }
3778
3779 void fx_init(struct kvm_vcpu *vcpu)
3780 {
3781         unsigned after_mxcsr_mask;
3782
3783         /*
3784          * Touch the fpu the first time in non atomic context as if
3785          * this is the first fpu instruction the exception handler
3786          * will fire before the instruction returns and it'll have to
3787          * allocate ram with GFP_KERNEL.
3788          */
3789         if (!used_math())
3790                 kvm_fx_save(&vcpu->arch.host_fx_image);
3791
3792         /* Initialize guest FPU by resetting ours and saving into guest's */
3793         preempt_disable();
3794         kvm_fx_save(&vcpu->arch.host_fx_image);
3795         kvm_fx_finit();
3796         kvm_fx_save(&vcpu->arch.guest_fx_image);
3797         kvm_fx_restore(&vcpu->arch.host_fx_image);
3798         preempt_enable();
3799
3800         vcpu->arch.cr0 |= X86_CR0_ET;
3801         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
3802         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
3803         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
3804                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
3805 }
3806 EXPORT_SYMBOL_GPL(fx_init);
3807
3808 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
3809 {
3810         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
3811                 return;
3812
3813         vcpu->guest_fpu_loaded = 1;
3814         kvm_fx_save(&vcpu->arch.host_fx_image);
3815         kvm_fx_restore(&vcpu->arch.guest_fx_image);
3816 }
3817 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
3818
3819 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
3820 {
3821         if (!vcpu->guest_fpu_loaded)
3822                 return;
3823
3824         vcpu->guest_fpu_loaded = 0;
3825         kvm_fx_save(&vcpu->arch.guest_fx_image);
3826         kvm_fx_restore(&vcpu->arch.host_fx_image);
3827         ++vcpu->stat.fpu_reload;
3828 }
3829 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
3830
3831 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
3832 {
3833         kvm_x86_ops->vcpu_free(vcpu);
3834 }
3835
3836 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
3837                                                 unsigned int id)
3838 {
3839         return kvm_x86_ops->vcpu_create(kvm, id);
3840 }
3841
3842 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
3843 {
3844         int r;
3845
3846         /* We do fxsave: this must be aligned. */
3847         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
3848
3849         vcpu_load(vcpu);
3850         r = kvm_arch_vcpu_reset(vcpu);
3851         if (r == 0)
3852                 r = kvm_mmu_setup(vcpu);
3853         vcpu_put(vcpu);
3854         if (r < 0)
3855                 goto free_vcpu;
3856
3857         return 0;
3858 free_vcpu:
3859         kvm_x86_ops->vcpu_free(vcpu);
3860         return r;
3861 }
3862
3863 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
3864 {
3865         vcpu_load(vcpu);
3866         kvm_mmu_unload(vcpu);
3867         vcpu_put(vcpu);
3868
3869         kvm_x86_ops->vcpu_free(vcpu);
3870 }
3871
3872 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
3873 {
3874         return kvm_x86_ops->vcpu_reset(vcpu);
3875 }
3876
3877 void kvm_arch_hardware_enable(void *garbage)
3878 {
3879         kvm_x86_ops->hardware_enable(garbage);
3880 }
3881
3882 void kvm_arch_hardware_disable(void *garbage)
3883 {
3884         kvm_x86_ops->hardware_disable(garbage);
3885 }
3886
3887 int kvm_arch_hardware_setup(void)
3888 {
3889         return kvm_x86_ops->hardware_setup();
3890 }
3891
3892 void kvm_arch_hardware_unsetup(void)
3893 {
3894         kvm_x86_ops->hardware_unsetup();
3895 }
3896
3897 void kvm_arch_check_processor_compat(void *rtn)
3898 {
3899         kvm_x86_ops->check_processor_compatibility(rtn);
3900 }
3901
3902 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
3903 {
3904         struct page *page;
3905         struct kvm *kvm;
3906         int r;
3907
3908         BUG_ON(vcpu->kvm == NULL);
3909         kvm = vcpu->kvm;
3910
3911         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3912         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
3913                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3914         else
3915                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
3916
3917         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3918         if (!page) {
3919                 r = -ENOMEM;
3920                 goto fail;
3921         }
3922         vcpu->arch.pio_data = page_address(page);
3923
3924         r = kvm_mmu_create(vcpu);
3925         if (r < 0)
3926                 goto fail_free_pio_data;
3927
3928         if (irqchip_in_kernel(kvm)) {
3929                 r = kvm_create_lapic(vcpu);
3930                 if (r < 0)
3931                         goto fail_mmu_destroy;
3932         }
3933
3934         return 0;
3935
3936 fail_mmu_destroy:
3937         kvm_mmu_destroy(vcpu);
3938 fail_free_pio_data:
3939         free_page((unsigned long)vcpu->arch.pio_data);
3940 fail:
3941         return r;
3942 }
3943
3944 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
3945 {
3946         kvm_free_lapic(vcpu);
3947         down_read(&vcpu->kvm->slots_lock);
3948         kvm_mmu_destroy(vcpu);
3949         up_read(&vcpu->kvm->slots_lock);
3950         free_page((unsigned long)vcpu->arch.pio_data);
3951 }
3952
3953 struct  kvm *kvm_arch_create_vm(void)
3954 {
3955         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
3956
3957         if (!kvm)
3958                 return ERR_PTR(-ENOMEM);
3959
3960         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
3961
3962         return kvm;
3963 }
3964
3965 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
3966 {
3967         vcpu_load(vcpu);
3968         kvm_mmu_unload(vcpu);
3969         vcpu_put(vcpu);
3970 }
3971
3972 static void kvm_free_vcpus(struct kvm *kvm)
3973 {
3974         unsigned int i;
3975
3976         /*
3977          * Unpin any mmu pages first.
3978          */
3979         for (i = 0; i < KVM_MAX_VCPUS; ++i)
3980                 if (kvm->vcpus[i])
3981                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
3982         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3983                 if (kvm->vcpus[i]) {
3984                         kvm_arch_vcpu_free(kvm->vcpus[i]);
3985                         kvm->vcpus[i] = NULL;
3986                 }
3987         }
3988
3989 }
3990
3991 void kvm_arch_destroy_vm(struct kvm *kvm)
3992 {
3993         kvm_free_pit(kvm);
3994         kfree(kvm->arch.vpic);
3995         kfree(kvm->arch.vioapic);
3996         kvm_free_vcpus(kvm);
3997         kvm_free_physmem(kvm);
3998         if (kvm->arch.apic_access_page)
3999                 put_page(kvm->arch.apic_access_page);
4000         if (kvm->arch.ept_identity_pagetable)
4001                 put_page(kvm->arch.ept_identity_pagetable);
4002         kfree(kvm);
4003 }
4004
4005 int kvm_arch_set_memory_region(struct kvm *kvm,
4006                                 struct kvm_userspace_memory_region *mem,
4007                                 struct kvm_memory_slot old,
4008                                 int user_alloc)
4009 {
4010         int npages = mem->memory_size >> PAGE_SHIFT;
4011         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
4012
4013         /*To keep backward compatibility with older userspace,
4014          *x86 needs to hanlde !user_alloc case.
4015          */
4016         if (!user_alloc) {
4017                 if (npages && !old.rmap) {
4018                         unsigned long userspace_addr;
4019
4020                         down_write(&current->mm->mmap_sem);
4021                         userspace_addr = do_mmap(NULL, 0,
4022                                                  npages * PAGE_SIZE,
4023                                                  PROT_READ | PROT_WRITE,
4024                                                  MAP_PRIVATE | MAP_ANONYMOUS,
4025                                                  0);
4026                         up_write(&current->mm->mmap_sem);
4027
4028                         if (IS_ERR((void *)userspace_addr))
4029                                 return PTR_ERR((void *)userspace_addr);
4030
4031                         /* set userspace_addr atomically for kvm_hva_to_rmapp */
4032                         spin_lock(&kvm->mmu_lock);
4033                         memslot->userspace_addr = userspace_addr;
4034                         spin_unlock(&kvm->mmu_lock);
4035                 } else {
4036                         if (!old.user_alloc && old.rmap) {
4037                                 int ret;
4038
4039                                 down_write(&current->mm->mmap_sem);
4040                                 ret = do_munmap(current->mm, old.userspace_addr,
4041                                                 old.npages * PAGE_SIZE);
4042                                 up_write(&current->mm->mmap_sem);
4043                                 if (ret < 0)
4044                                         printk(KERN_WARNING
4045                                        "kvm_vm_ioctl_set_memory_region: "
4046                                        "failed to munmap memory\n");
4047                         }
4048                 }
4049         }
4050
4051         if (!kvm->arch.n_requested_mmu_pages) {
4052                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
4053                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
4054         }
4055
4056         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
4057         kvm_flush_remote_tlbs(kvm);
4058
4059         return 0;
4060 }
4061
4062 void kvm_arch_flush_shadow(struct kvm *kvm)
4063 {
4064         kvm_mmu_zap_all(kvm);
4065 }
4066
4067 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
4068 {
4069         return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
4070                || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED;
4071 }
4072
4073 static void vcpu_kick_intr(void *info)
4074 {
4075 #ifdef DEBUG
4076         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
4077         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
4078 #endif
4079 }
4080
4081 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
4082 {
4083         int ipi_pcpu = vcpu->cpu;
4084         int cpu = get_cpu();
4085
4086         if (waitqueue_active(&vcpu->wq)) {
4087                 wake_up_interruptible(&vcpu->wq);
4088                 ++vcpu->stat.halt_wakeup;
4089         }
4090         /*
4091          * We may be called synchronously with irqs disabled in guest mode,
4092          * So need not to call smp_call_function_single() in that case.
4093          */
4094         if (vcpu->guest_mode && vcpu->cpu != cpu)
4095                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0);
4096         put_cpu();
4097 }