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