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