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