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