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