50bac2e50ae3e66fda334fd3fd8bc59e524a565b
[pandora-kernel.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2008 Qumranet, Inc.
8  * Copyright IBM Corporation, 2008
9  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10  *
11  * Authors:
12  *   Avi Kivity   <avi@qumranet.com>
13  *   Yaniv Kamay  <yaniv@qumranet.com>
14  *   Amit Shah    <amit.shah@qumranet.com>
15  *   Ben-Ami Yassour <benami@il.ibm.com>
16  *
17  * This work is licensed under the terms of the GNU GPL, version 2.  See
18  * the COPYING file in the top-level directory.
19  *
20  */
21
22 #include <linux/kvm_host.h>
23 #include "irq.h"
24 #include "mmu.h"
25 #include "i8254.h"
26 #include "tss.h"
27 #include "kvm_cache_regs.h"
28 #include "x86.h"
29
30 #include <linux/clocksource.h>
31 #include <linux/interrupt.h>
32 #include <linux/kvm.h>
33 #include <linux/fs.h>
34 #include <linux/vmalloc.h>
35 #include <linux/module.h>
36 #include <linux/mman.h>
37 #include <linux/highmem.h>
38 #include <linux/iommu.h>
39 #include <linux/intel-iommu.h>
40 #include <linux/cpufreq.h>
41 #include <linux/user-return-notifier.h>
42 #include <linux/srcu.h>
43 #include <linux/slab.h>
44 #include <linux/perf_event.h>
45 #include <linux/uaccess.h>
46 #include <linux/hash.h>
47 #include <linux/pci.h>
48 #include <trace/events/kvm.h>
49
50 #define CREATE_TRACE_POINTS
51 #include "trace.h"
52
53 #include <asm/debugreg.h>
54 #include <asm/msr.h>
55 #include <asm/desc.h>
56 #include <asm/mtrr.h>
57 #include <asm/mce.h>
58 #include <asm/i387.h>
59 #include <asm/xcr.h>
60 #include <asm/pvclock.h>
61 #include <asm/div64.h>
62
63 #define MAX_IO_MSRS 256
64 #define KVM_MAX_MCE_BANKS 32
65 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
66
67 #define emul_to_vcpu(ctxt) \
68         container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
69
70 /* EFER defaults:
71  * - enable syscall per default because its emulated by KVM
72  * - enable LME and LMA per default on 64 bit KVM
73  */
74 #ifdef CONFIG_X86_64
75 static
76 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
77 #else
78 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
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 static void process_nmi(struct kvm_vcpu *vcpu);
88
89 struct kvm_x86_ops *kvm_x86_ops;
90 EXPORT_SYMBOL_GPL(kvm_x86_ops);
91
92 int ignore_msrs = 0;
93 module_param_named(ignore_msrs, ignore_msrs, bool, S_IRUGO | S_IWUSR);
94
95 bool kvm_has_tsc_control;
96 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
97 u32  kvm_max_guest_tsc_khz;
98 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
99
100 #define KVM_NR_SHARED_MSRS 16
101
102 struct kvm_shared_msrs_global {
103         int nr;
104         u32 msrs[KVM_NR_SHARED_MSRS];
105 };
106
107 struct kvm_shared_msrs {
108         struct user_return_notifier urn;
109         bool registered;
110         struct kvm_shared_msr_values {
111                 u64 host;
112                 u64 curr;
113         } values[KVM_NR_SHARED_MSRS];
114 };
115
116 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
117 static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
118
119 struct kvm_stats_debugfs_item debugfs_entries[] = {
120         { "pf_fixed", VCPU_STAT(pf_fixed) },
121         { "pf_guest", VCPU_STAT(pf_guest) },
122         { "tlb_flush", VCPU_STAT(tlb_flush) },
123         { "invlpg", VCPU_STAT(invlpg) },
124         { "exits", VCPU_STAT(exits) },
125         { "io_exits", VCPU_STAT(io_exits) },
126         { "mmio_exits", VCPU_STAT(mmio_exits) },
127         { "signal_exits", VCPU_STAT(signal_exits) },
128         { "irq_window", VCPU_STAT(irq_window_exits) },
129         { "nmi_window", VCPU_STAT(nmi_window_exits) },
130         { "halt_exits", VCPU_STAT(halt_exits) },
131         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
132         { "hypercalls", VCPU_STAT(hypercalls) },
133         { "request_irq", VCPU_STAT(request_irq_exits) },
134         { "irq_exits", VCPU_STAT(irq_exits) },
135         { "host_state_reload", VCPU_STAT(host_state_reload) },
136         { "efer_reload", VCPU_STAT(efer_reload) },
137         { "fpu_reload", VCPU_STAT(fpu_reload) },
138         { "insn_emulation", VCPU_STAT(insn_emulation) },
139         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
140         { "irq_injections", VCPU_STAT(irq_injections) },
141         { "nmi_injections", VCPU_STAT(nmi_injections) },
142         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
143         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
144         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
145         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
146         { "mmu_flooded", VM_STAT(mmu_flooded) },
147         { "mmu_recycled", VM_STAT(mmu_recycled) },
148         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
149         { "mmu_unsync", VM_STAT(mmu_unsync) },
150         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
151         { "largepages", VM_STAT(lpages) },
152         { NULL }
153 };
154
155 u64 __read_mostly host_xcr0;
156
157 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
158
159 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
160 {
161         int i;
162         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
163                 vcpu->arch.apf.gfns[i] = ~0;
164 }
165
166 static void kvm_on_user_return(struct user_return_notifier *urn)
167 {
168         unsigned slot;
169         struct kvm_shared_msrs *locals
170                 = container_of(urn, struct kvm_shared_msrs, urn);
171         struct kvm_shared_msr_values *values;
172
173         for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
174                 values = &locals->values[slot];
175                 if (values->host != values->curr) {
176                         wrmsrl(shared_msrs_global.msrs[slot], values->host);
177                         values->curr = values->host;
178                 }
179         }
180         locals->registered = false;
181         user_return_notifier_unregister(urn);
182 }
183
184 static void shared_msr_update(unsigned slot, u32 msr)
185 {
186         struct kvm_shared_msrs *smsr;
187         u64 value;
188
189         smsr = &__get_cpu_var(shared_msrs);
190         /* only read, and nobody should modify it at this time,
191          * so don't need lock */
192         if (slot >= shared_msrs_global.nr) {
193                 printk(KERN_ERR "kvm: invalid MSR slot!");
194                 return;
195         }
196         rdmsrl_safe(msr, &value);
197         smsr->values[slot].host = value;
198         smsr->values[slot].curr = value;
199 }
200
201 void kvm_define_shared_msr(unsigned slot, u32 msr)
202 {
203         if (slot >= shared_msrs_global.nr)
204                 shared_msrs_global.nr = slot + 1;
205         shared_msrs_global.msrs[slot] = msr;
206         /* we need ensured the shared_msr_global have been updated */
207         smp_wmb();
208 }
209 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
210
211 static void kvm_shared_msr_cpu_online(void)
212 {
213         unsigned i;
214
215         for (i = 0; i < shared_msrs_global.nr; ++i)
216                 shared_msr_update(i, shared_msrs_global.msrs[i]);
217 }
218
219 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
220 {
221         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
222
223         if (((value ^ smsr->values[slot].curr) & mask) == 0)
224                 return;
225         smsr->values[slot].curr = value;
226         wrmsrl(shared_msrs_global.msrs[slot], value);
227         if (!smsr->registered) {
228                 smsr->urn.on_user_return = kvm_on_user_return;
229                 user_return_notifier_register(&smsr->urn);
230                 smsr->registered = true;
231         }
232 }
233 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
234
235 static void drop_user_return_notifiers(void *ignore)
236 {
237         struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
238
239         if (smsr->registered)
240                 kvm_on_user_return(&smsr->urn);
241 }
242
243 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
244 {
245         if (irqchip_in_kernel(vcpu->kvm))
246                 return vcpu->arch.apic_base;
247         else
248                 return vcpu->arch.apic_base;
249 }
250 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
251
252 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
253 {
254         /* TODO: reserve bits check */
255         if (irqchip_in_kernel(vcpu->kvm))
256                 kvm_lapic_set_base(vcpu, data);
257         else
258                 vcpu->arch.apic_base = data;
259 }
260 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
261
262 #define EXCPT_BENIGN            0
263 #define EXCPT_CONTRIBUTORY      1
264 #define EXCPT_PF                2
265
266 static int exception_class(int vector)
267 {
268         switch (vector) {
269         case PF_VECTOR:
270                 return EXCPT_PF;
271         case DE_VECTOR:
272         case TS_VECTOR:
273         case NP_VECTOR:
274         case SS_VECTOR:
275         case GP_VECTOR:
276                 return EXCPT_CONTRIBUTORY;
277         default:
278                 break;
279         }
280         return EXCPT_BENIGN;
281 }
282
283 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
284                 unsigned nr, bool has_error, u32 error_code,
285                 bool reinject)
286 {
287         u32 prev_nr;
288         int class1, class2;
289
290         kvm_make_request(KVM_REQ_EVENT, vcpu);
291
292         if (!vcpu->arch.exception.pending) {
293         queue:
294                 vcpu->arch.exception.pending = true;
295                 vcpu->arch.exception.has_error_code = has_error;
296                 vcpu->arch.exception.nr = nr;
297                 vcpu->arch.exception.error_code = error_code;
298                 vcpu->arch.exception.reinject = reinject;
299                 return;
300         }
301
302         /* to check exception */
303         prev_nr = vcpu->arch.exception.nr;
304         if (prev_nr == DF_VECTOR) {
305                 /* triple fault -> shutdown */
306                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
307                 return;
308         }
309         class1 = exception_class(prev_nr);
310         class2 = exception_class(nr);
311         if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
312                 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
313                 /* generate double fault per SDM Table 5-5 */
314                 vcpu->arch.exception.pending = true;
315                 vcpu->arch.exception.has_error_code = true;
316                 vcpu->arch.exception.nr = DF_VECTOR;
317                 vcpu->arch.exception.error_code = 0;
318         } else
319                 /* replace previous exception with a new one in a hope
320                    that instruction re-execution will regenerate lost
321                    exception */
322                 goto queue;
323 }
324
325 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
326 {
327         kvm_multiple_exception(vcpu, nr, false, 0, false);
328 }
329 EXPORT_SYMBOL_GPL(kvm_queue_exception);
330
331 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
332 {
333         kvm_multiple_exception(vcpu, nr, false, 0, true);
334 }
335 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
336
337 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
338 {
339         if (err)
340                 kvm_inject_gp(vcpu, 0);
341         else
342                 kvm_x86_ops->skip_emulated_instruction(vcpu);
343 }
344 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
345
346 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
347 {
348         ++vcpu->stat.pf_guest;
349         vcpu->arch.cr2 = fault->address;
350         kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
351 }
352 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
353
354 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
355 {
356         if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
357                 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
358         else
359                 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
360 }
361
362 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
363 {
364         atomic_inc(&vcpu->arch.nmi_queued);
365         kvm_make_request(KVM_REQ_NMI, vcpu);
366 }
367 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
368
369 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
370 {
371         kvm_multiple_exception(vcpu, nr, true, error_code, false);
372 }
373 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
374
375 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
376 {
377         kvm_multiple_exception(vcpu, nr, true, error_code, true);
378 }
379 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
380
381 /*
382  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
383  * a #GP and return false.
384  */
385 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
386 {
387         if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
388                 return true;
389         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
390         return false;
391 }
392 EXPORT_SYMBOL_GPL(kvm_require_cpl);
393
394 /*
395  * This function will be used to read from the physical memory of the currently
396  * running guest. The difference to kvm_read_guest_page is that this function
397  * can read from guest physical or from the guest's guest physical memory.
398  */
399 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
400                             gfn_t ngfn, void *data, int offset, int len,
401                             u32 access)
402 {
403         gfn_t real_gfn;
404         gpa_t ngpa;
405
406         ngpa     = gfn_to_gpa(ngfn);
407         real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
408         if (real_gfn == UNMAPPED_GVA)
409                 return -EFAULT;
410
411         real_gfn = gpa_to_gfn(real_gfn);
412
413         return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
414 }
415 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
416
417 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
418                                void *data, int offset, int len, u32 access)
419 {
420         return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
421                                        data, offset, len, access);
422 }
423
424 /*
425  * Load the pae pdptrs.  Return true is they are all valid.
426  */
427 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
428 {
429         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
430         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
431         int i;
432         int ret;
433         u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
434
435         ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
436                                       offset * sizeof(u64), sizeof(pdpte),
437                                       PFERR_USER_MASK|PFERR_WRITE_MASK);
438         if (ret < 0) {
439                 ret = 0;
440                 goto out;
441         }
442         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
443                 if (is_present_gpte(pdpte[i]) &&
444                     (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
445                         ret = 0;
446                         goto out;
447                 }
448         }
449         ret = 1;
450
451         memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
452         __set_bit(VCPU_EXREG_PDPTR,
453                   (unsigned long *)&vcpu->arch.regs_avail);
454         __set_bit(VCPU_EXREG_PDPTR,
455                   (unsigned long *)&vcpu->arch.regs_dirty);
456 out:
457
458         return ret;
459 }
460 EXPORT_SYMBOL_GPL(load_pdptrs);
461
462 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
463 {
464         u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
465         bool changed = true;
466         int offset;
467         gfn_t gfn;
468         int r;
469
470         if (is_long_mode(vcpu) || !is_pae(vcpu))
471                 return false;
472
473         if (!test_bit(VCPU_EXREG_PDPTR,
474                       (unsigned long *)&vcpu->arch.regs_avail))
475                 return true;
476
477         gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
478         offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
479         r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
480                                        PFERR_USER_MASK | PFERR_WRITE_MASK);
481         if (r < 0)
482                 goto out;
483         changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
484 out:
485
486         return changed;
487 }
488
489 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
490 {
491         unsigned long old_cr0 = kvm_read_cr0(vcpu);
492         unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
493                                     X86_CR0_CD | X86_CR0_NW;
494
495         cr0 |= X86_CR0_ET;
496
497 #ifdef CONFIG_X86_64
498         if (cr0 & 0xffffffff00000000UL)
499                 return 1;
500 #endif
501
502         cr0 &= ~CR0_RESERVED_BITS;
503
504         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
505                 return 1;
506
507         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
508                 return 1;
509
510         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
511 #ifdef CONFIG_X86_64
512                 if ((vcpu->arch.efer & EFER_LME)) {
513                         int cs_db, cs_l;
514
515                         if (!is_pae(vcpu))
516                                 return 1;
517                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
518                         if (cs_l)
519                                 return 1;
520                 } else
521 #endif
522                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
523                                                  kvm_read_cr3(vcpu)))
524                         return 1;
525         }
526
527         kvm_x86_ops->set_cr0(vcpu, cr0);
528
529         if ((cr0 ^ old_cr0) & X86_CR0_PG) {
530                 kvm_clear_async_pf_completion_queue(vcpu);
531                 kvm_async_pf_hash_reset(vcpu);
532         }
533
534         if ((cr0 ^ old_cr0) & update_bits)
535                 kvm_mmu_reset_context(vcpu);
536         return 0;
537 }
538 EXPORT_SYMBOL_GPL(kvm_set_cr0);
539
540 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
541 {
542         (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
543 }
544 EXPORT_SYMBOL_GPL(kvm_lmsw);
545
546 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
547 {
548         u64 xcr0;
549
550         /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
551         if (index != XCR_XFEATURE_ENABLED_MASK)
552                 return 1;
553         xcr0 = xcr;
554         if (kvm_x86_ops->get_cpl(vcpu) != 0)
555                 return 1;
556         if (!(xcr0 & XSTATE_FP))
557                 return 1;
558         if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
559                 return 1;
560         if (xcr0 & ~host_xcr0)
561                 return 1;
562         vcpu->arch.xcr0 = xcr0;
563         vcpu->guest_xcr0_loaded = 0;
564         return 0;
565 }
566
567 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
568 {
569         if (__kvm_set_xcr(vcpu, index, xcr)) {
570                 kvm_inject_gp(vcpu, 0);
571                 return 1;
572         }
573         return 0;
574 }
575 EXPORT_SYMBOL_GPL(kvm_set_xcr);
576
577 static bool guest_cpuid_has_xsave(struct kvm_vcpu *vcpu)
578 {
579         struct kvm_cpuid_entry2 *best;
580
581         if (!static_cpu_has(X86_FEATURE_XSAVE))
582                 return 0;
583
584         best = kvm_find_cpuid_entry(vcpu, 1, 0);
585         return best && (best->ecx & bit(X86_FEATURE_XSAVE));
586 }
587
588 static bool guest_cpuid_has_smep(struct kvm_vcpu *vcpu)
589 {
590         struct kvm_cpuid_entry2 *best;
591
592         best = kvm_find_cpuid_entry(vcpu, 7, 0);
593         return best && (best->ebx & bit(X86_FEATURE_SMEP));
594 }
595
596 static bool guest_cpuid_has_fsgsbase(struct kvm_vcpu *vcpu)
597 {
598         struct kvm_cpuid_entry2 *best;
599
600         best = kvm_find_cpuid_entry(vcpu, 7, 0);
601         return best && (best->ebx & bit(X86_FEATURE_FSGSBASE));
602 }
603
604 static void update_cpuid(struct kvm_vcpu *vcpu)
605 {
606         struct kvm_cpuid_entry2 *best;
607         struct kvm_lapic *apic = vcpu->arch.apic;
608
609         best = kvm_find_cpuid_entry(vcpu, 1, 0);
610         if (!best)
611                 return;
612
613         /* Update OSXSAVE bit */
614         if (cpu_has_xsave && best->function == 0x1) {
615                 best->ecx &= ~(bit(X86_FEATURE_OSXSAVE));
616                 if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE))
617                         best->ecx |= bit(X86_FEATURE_OSXSAVE);
618         }
619
620         if (apic) {
621                 if (best->ecx & bit(X86_FEATURE_TSC_DEADLINE_TIMER))
622                         apic->lapic_timer.timer_mode_mask = 3 << 17;
623                 else
624                         apic->lapic_timer.timer_mode_mask = 1 << 17;
625         }
626 }
627
628 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
629 {
630         unsigned long old_cr4 = kvm_read_cr4(vcpu);
631         unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
632                                    X86_CR4_PAE | X86_CR4_SMEP;
633         if (cr4 & CR4_RESERVED_BITS)
634                 return 1;
635
636         if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
637                 return 1;
638
639         if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
640                 return 1;
641
642         if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
643                 return 1;
644
645         if (is_long_mode(vcpu)) {
646                 if (!(cr4 & X86_CR4_PAE))
647                         return 1;
648         } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
649                    && ((cr4 ^ old_cr4) & pdptr_bits)
650                    && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
651                                    kvm_read_cr3(vcpu)))
652                 return 1;
653
654         if (kvm_x86_ops->set_cr4(vcpu, cr4))
655                 return 1;
656
657         if ((cr4 ^ old_cr4) & pdptr_bits)
658                 kvm_mmu_reset_context(vcpu);
659
660         if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
661                 update_cpuid(vcpu);
662
663         return 0;
664 }
665 EXPORT_SYMBOL_GPL(kvm_set_cr4);
666
667 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
668 {
669         if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
670                 kvm_mmu_sync_roots(vcpu);
671                 kvm_mmu_flush_tlb(vcpu);
672                 return 0;
673         }
674
675         if (is_long_mode(vcpu)) {
676                 if (cr3 & CR3_L_MODE_RESERVED_BITS)
677                         return 1;
678         } else {
679                 if (is_pae(vcpu)) {
680                         if (cr3 & CR3_PAE_RESERVED_BITS)
681                                 return 1;
682                         if (is_paging(vcpu) &&
683                             !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
684                                 return 1;
685                 }
686                 /*
687                  * We don't check reserved bits in nonpae mode, because
688                  * this isn't enforced, and VMware depends on this.
689                  */
690         }
691
692         /*
693          * Does the new cr3 value map to physical memory? (Note, we
694          * catch an invalid cr3 even in real-mode, because it would
695          * cause trouble later on when we turn on paging anyway.)
696          *
697          * A real CPU would silently accept an invalid cr3 and would
698          * attempt to use it - with largely undefined (and often hard
699          * to debug) behavior on the guest side.
700          */
701         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
702                 return 1;
703         vcpu->arch.cr3 = cr3;
704         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
705         vcpu->arch.mmu.new_cr3(vcpu);
706         return 0;
707 }
708 EXPORT_SYMBOL_GPL(kvm_set_cr3);
709
710 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
711 {
712         if (cr8 & CR8_RESERVED_BITS)
713                 return 1;
714         if (irqchip_in_kernel(vcpu->kvm))
715                 kvm_lapic_set_tpr(vcpu, cr8);
716         else
717                 vcpu->arch.cr8 = cr8;
718         return 0;
719 }
720 EXPORT_SYMBOL_GPL(kvm_set_cr8);
721
722 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
723 {
724         if (irqchip_in_kernel(vcpu->kvm))
725                 return kvm_lapic_get_cr8(vcpu);
726         else
727                 return vcpu->arch.cr8;
728 }
729 EXPORT_SYMBOL_GPL(kvm_get_cr8);
730
731 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
732 {
733         switch (dr) {
734         case 0 ... 3:
735                 vcpu->arch.db[dr] = val;
736                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
737                         vcpu->arch.eff_db[dr] = val;
738                 break;
739         case 4:
740                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
741                         return 1; /* #UD */
742                 /* fall through */
743         case 6:
744                 if (val & 0xffffffff00000000ULL)
745                         return -1; /* #GP */
746                 vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
747                 break;
748         case 5:
749                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
750                         return 1; /* #UD */
751                 /* fall through */
752         default: /* 7 */
753                 if (val & 0xffffffff00000000ULL)
754                         return -1; /* #GP */
755                 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
756                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
757                         kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
758                         vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
759                 }
760                 break;
761         }
762
763         return 0;
764 }
765
766 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
767 {
768         int res;
769
770         res = __kvm_set_dr(vcpu, dr, val);
771         if (res > 0)
772                 kvm_queue_exception(vcpu, UD_VECTOR);
773         else if (res < 0)
774                 kvm_inject_gp(vcpu, 0);
775
776         return res;
777 }
778 EXPORT_SYMBOL_GPL(kvm_set_dr);
779
780 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
781 {
782         switch (dr) {
783         case 0 ... 3:
784                 *val = vcpu->arch.db[dr];
785                 break;
786         case 4:
787                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
788                         return 1;
789                 /* fall through */
790         case 6:
791                 *val = vcpu->arch.dr6;
792                 break;
793         case 5:
794                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
795                         return 1;
796                 /* fall through */
797         default: /* 7 */
798                 *val = vcpu->arch.dr7;
799                 break;
800         }
801
802         return 0;
803 }
804
805 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
806 {
807         if (_kvm_get_dr(vcpu, dr, val)) {
808                 kvm_queue_exception(vcpu, UD_VECTOR);
809                 return 1;
810         }
811         return 0;
812 }
813 EXPORT_SYMBOL_GPL(kvm_get_dr);
814
815 /*
816  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
817  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
818  *
819  * This list is modified at module load time to reflect the
820  * capabilities of the host cpu. This capabilities test skips MSRs that are
821  * kvm-specific. Those are put in the beginning of the list.
822  */
823
824 #define KVM_SAVE_MSRS_BEGIN     9
825 static u32 msrs_to_save[] = {
826         MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
827         MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
828         HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
829         HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
830         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
831         MSR_STAR,
832 #ifdef CONFIG_X86_64
833         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
834 #endif
835         MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
836 };
837
838 static unsigned num_msrs_to_save;
839
840 static u32 emulated_msrs[] = {
841         MSR_IA32_TSCDEADLINE,
842         MSR_IA32_MISC_ENABLE,
843         MSR_IA32_MCG_STATUS,
844         MSR_IA32_MCG_CTL,
845 };
846
847 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
848 {
849         u64 old_efer = vcpu->arch.efer;
850
851         if (efer & efer_reserved_bits)
852                 return 1;
853
854         if (is_paging(vcpu)
855             && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
856                 return 1;
857
858         if (efer & EFER_FFXSR) {
859                 struct kvm_cpuid_entry2 *feat;
860
861                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
862                 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
863                         return 1;
864         }
865
866         if (efer & EFER_SVME) {
867                 struct kvm_cpuid_entry2 *feat;
868
869                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
870                 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
871                         return 1;
872         }
873
874         efer &= ~EFER_LMA;
875         efer |= vcpu->arch.efer & EFER_LMA;
876
877         kvm_x86_ops->set_efer(vcpu, efer);
878
879         vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
880
881         /* Update reserved bits */
882         if ((efer ^ old_efer) & EFER_NX)
883                 kvm_mmu_reset_context(vcpu);
884
885         return 0;
886 }
887
888 void kvm_enable_efer_bits(u64 mask)
889 {
890        efer_reserved_bits &= ~mask;
891 }
892 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
893
894
895 /*
896  * Writes msr value into into the appropriate "register".
897  * Returns 0 on success, non-0 otherwise.
898  * Assumes vcpu_load() was already called.
899  */
900 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
901 {
902         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
903 }
904
905 /*
906  * Adapt set_msr() to msr_io()'s calling convention
907  */
908 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
909 {
910         return kvm_set_msr(vcpu, index, *data);
911 }
912
913 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
914 {
915         int version;
916         int r;
917         struct pvclock_wall_clock wc;
918         struct timespec boot;
919
920         if (!wall_clock)
921                 return;
922
923         r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
924         if (r)
925                 return;
926
927         if (version & 1)
928                 ++version;  /* first time write, random junk */
929
930         ++version;
931
932         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
933
934         /*
935          * The guest calculates current wall clock time by adding
936          * system time (updated by kvm_guest_time_update below) to the
937          * wall clock specified here.  guest system time equals host
938          * system time for us, thus we must fill in host boot time here.
939          */
940         getboottime(&boot);
941
942         wc.sec = boot.tv_sec;
943         wc.nsec = boot.tv_nsec;
944         wc.version = version;
945
946         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
947
948         version++;
949         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
950 }
951
952 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
953 {
954         uint32_t quotient, remainder;
955
956         /* Don't try to replace with do_div(), this one calculates
957          * "(dividend << 32) / divisor" */
958         __asm__ ( "divl %4"
959                   : "=a" (quotient), "=d" (remainder)
960                   : "0" (0), "1" (dividend), "r" (divisor) );
961         return quotient;
962 }
963
964 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
965                                s8 *pshift, u32 *pmultiplier)
966 {
967         uint64_t scaled64;
968         int32_t  shift = 0;
969         uint64_t tps64;
970         uint32_t tps32;
971
972         tps64 = base_khz * 1000LL;
973         scaled64 = scaled_khz * 1000LL;
974         while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
975                 tps64 >>= 1;
976                 shift--;
977         }
978
979         tps32 = (uint32_t)tps64;
980         while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
981                 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
982                         scaled64 >>= 1;
983                 else
984                         tps32 <<= 1;
985                 shift++;
986         }
987
988         *pshift = shift;
989         *pmultiplier = div_frac(scaled64, tps32);
990
991         pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
992                  __func__, base_khz, scaled_khz, shift, *pmultiplier);
993 }
994
995 static inline u64 get_kernel_ns(void)
996 {
997         struct timespec ts;
998
999         WARN_ON(preemptible());
1000         ktime_get_ts(&ts);
1001         monotonic_to_bootbased(&ts);
1002         return timespec_to_ns(&ts);
1003 }
1004
1005 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1006 unsigned long max_tsc_khz;
1007
1008 static inline int kvm_tsc_changes_freq(void)
1009 {
1010         int cpu = get_cpu();
1011         int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
1012                   cpufreq_quick_get(cpu) != 0;
1013         put_cpu();
1014         return ret;
1015 }
1016
1017 u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
1018 {
1019         if (vcpu->arch.virtual_tsc_khz)
1020                 return vcpu->arch.virtual_tsc_khz;
1021         else
1022                 return __this_cpu_read(cpu_tsc_khz);
1023 }
1024
1025 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1026 {
1027         u64 ret;
1028
1029         WARN_ON(preemptible());
1030         if (kvm_tsc_changes_freq())
1031                 printk_once(KERN_WARNING
1032                  "kvm: unreliable cycle conversion on adjustable rate TSC\n");
1033         ret = nsec * vcpu_tsc_khz(vcpu);
1034         do_div(ret, USEC_PER_SEC);
1035         return ret;
1036 }
1037
1038 static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1039 {
1040         /* Compute a scale to convert nanoseconds in TSC cycles */
1041         kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1042                            &vcpu->arch.tsc_catchup_shift,
1043                            &vcpu->arch.tsc_catchup_mult);
1044 }
1045
1046 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1047 {
1048         u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1049                                       vcpu->arch.tsc_catchup_mult,
1050                                       vcpu->arch.tsc_catchup_shift);
1051         tsc += vcpu->arch.last_tsc_write;
1052         return tsc;
1053 }
1054
1055 void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
1056 {
1057         struct kvm *kvm = vcpu->kvm;
1058         u64 offset, ns, elapsed;
1059         unsigned long flags;
1060         s64 sdiff;
1061
1062         raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1063         offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1064         ns = get_kernel_ns();
1065         elapsed = ns - kvm->arch.last_tsc_nsec;
1066         sdiff = data - kvm->arch.last_tsc_write;
1067         if (sdiff < 0)
1068                 sdiff = -sdiff;
1069
1070         /*
1071          * Special case: close write to TSC within 5 seconds of
1072          * another CPU is interpreted as an attempt to synchronize
1073          * The 5 seconds is to accommodate host load / swapping as
1074          * well as any reset of TSC during the boot process.
1075          *
1076          * In that case, for a reliable TSC, we can match TSC offsets,
1077          * or make a best guest using elapsed value.
1078          */
1079         if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
1080             elapsed < 5ULL * NSEC_PER_SEC) {
1081                 if (!check_tsc_unstable()) {
1082                         offset = kvm->arch.last_tsc_offset;
1083                         pr_debug("kvm: matched tsc offset for %llu\n", data);
1084                 } else {
1085                         u64 delta = nsec_to_cycles(vcpu, elapsed);
1086                         offset += delta;
1087                         pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1088                 }
1089                 ns = kvm->arch.last_tsc_nsec;
1090         }
1091         kvm->arch.last_tsc_nsec = ns;
1092         kvm->arch.last_tsc_write = data;
1093         kvm->arch.last_tsc_offset = offset;
1094         kvm_x86_ops->write_tsc_offset(vcpu, offset);
1095         raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1096
1097         /* Reset of TSC must disable overshoot protection below */
1098         vcpu->arch.hv_clock.tsc_timestamp = 0;
1099         vcpu->arch.last_tsc_write = data;
1100         vcpu->arch.last_tsc_nsec = ns;
1101 }
1102 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1103
1104 static int kvm_guest_time_update(struct kvm_vcpu *v)
1105 {
1106         unsigned long flags;
1107         struct kvm_vcpu_arch *vcpu = &v->arch;
1108         void *shared_kaddr;
1109         unsigned long this_tsc_khz;
1110         s64 kernel_ns, max_kernel_ns;
1111         u64 tsc_timestamp;
1112
1113         /* Keep irq disabled to prevent changes to the clock */
1114         local_irq_save(flags);
1115         tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
1116         kernel_ns = get_kernel_ns();
1117         this_tsc_khz = vcpu_tsc_khz(v);
1118         if (unlikely(this_tsc_khz == 0)) {
1119                 local_irq_restore(flags);
1120                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1121                 return 1;
1122         }
1123
1124         /*
1125          * We may have to catch up the TSC to match elapsed wall clock
1126          * time for two reasons, even if kvmclock is used.
1127          *   1) CPU could have been running below the maximum TSC rate
1128          *   2) Broken TSC compensation resets the base at each VCPU
1129          *      entry to avoid unknown leaps of TSC even when running
1130          *      again on the same CPU.  This may cause apparent elapsed
1131          *      time to disappear, and the guest to stand still or run
1132          *      very slowly.
1133          */
1134         if (vcpu->tsc_catchup) {
1135                 u64 tsc = compute_guest_tsc(v, kernel_ns);
1136                 if (tsc > tsc_timestamp) {
1137                         kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
1138                         tsc_timestamp = tsc;
1139                 }
1140         }
1141
1142         local_irq_restore(flags);
1143
1144         if (!vcpu->time_page)
1145                 return 0;
1146
1147         /*
1148          * Time as measured by the TSC may go backwards when resetting the base
1149          * tsc_timestamp.  The reason for this is that the TSC resolution is
1150          * higher than the resolution of the other clock scales.  Thus, many
1151          * possible measurments of the TSC correspond to one measurement of any
1152          * other clock, and so a spread of values is possible.  This is not a
1153          * problem for the computation of the nanosecond clock; with TSC rates
1154          * around 1GHZ, there can only be a few cycles which correspond to one
1155          * nanosecond value, and any path through this code will inevitably
1156          * take longer than that.  However, with the kernel_ns value itself,
1157          * the precision may be much lower, down to HZ granularity.  If the
1158          * first sampling of TSC against kernel_ns ends in the low part of the
1159          * range, and the second in the high end of the range, we can get:
1160          *
1161          * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
1162          *
1163          * As the sampling errors potentially range in the thousands of cycles,
1164          * it is possible such a time value has already been observed by the
1165          * guest.  To protect against this, we must compute the system time as
1166          * observed by the guest and ensure the new system time is greater.
1167          */
1168         max_kernel_ns = 0;
1169         if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
1170                 max_kernel_ns = vcpu->last_guest_tsc -
1171                                 vcpu->hv_clock.tsc_timestamp;
1172                 max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
1173                                     vcpu->hv_clock.tsc_to_system_mul,
1174                                     vcpu->hv_clock.tsc_shift);
1175                 max_kernel_ns += vcpu->last_kernel_ns;
1176         }
1177
1178         if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1179                 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1180                                    &vcpu->hv_clock.tsc_shift,
1181                                    &vcpu->hv_clock.tsc_to_system_mul);
1182                 vcpu->hw_tsc_khz = this_tsc_khz;
1183         }
1184
1185         if (max_kernel_ns > kernel_ns)
1186                 kernel_ns = max_kernel_ns;
1187
1188         /* With all the info we got, fill in the values */
1189         vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1190         vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1191         vcpu->last_kernel_ns = kernel_ns;
1192         vcpu->last_guest_tsc = tsc_timestamp;
1193         vcpu->hv_clock.flags = 0;
1194
1195         /*
1196          * The interface expects us to write an even number signaling that the
1197          * update is finished. Since the guest won't see the intermediate
1198          * state, we just increase by 2 at the end.
1199          */
1200         vcpu->hv_clock.version += 2;
1201
1202         shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
1203
1204         memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
1205                sizeof(vcpu->hv_clock));
1206
1207         kunmap_atomic(shared_kaddr, KM_USER0);
1208
1209         mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
1210         return 0;
1211 }
1212
1213 static bool msr_mtrr_valid(unsigned msr)
1214 {
1215         switch (msr) {
1216         case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1217         case MSR_MTRRfix64K_00000:
1218         case MSR_MTRRfix16K_80000:
1219         case MSR_MTRRfix16K_A0000:
1220         case MSR_MTRRfix4K_C0000:
1221         case MSR_MTRRfix4K_C8000:
1222         case MSR_MTRRfix4K_D0000:
1223         case MSR_MTRRfix4K_D8000:
1224         case MSR_MTRRfix4K_E0000:
1225         case MSR_MTRRfix4K_E8000:
1226         case MSR_MTRRfix4K_F0000:
1227         case MSR_MTRRfix4K_F8000:
1228         case MSR_MTRRdefType:
1229         case MSR_IA32_CR_PAT:
1230                 return true;
1231         case 0x2f8:
1232                 return true;
1233         }
1234         return false;
1235 }
1236
1237 static bool valid_pat_type(unsigned t)
1238 {
1239         return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1240 }
1241
1242 static bool valid_mtrr_type(unsigned t)
1243 {
1244         return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1245 }
1246
1247 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1248 {
1249         int i;
1250
1251         if (!msr_mtrr_valid(msr))
1252                 return false;
1253
1254         if (msr == MSR_IA32_CR_PAT) {
1255                 for (i = 0; i < 8; i++)
1256                         if (!valid_pat_type((data >> (i * 8)) & 0xff))
1257                                 return false;
1258                 return true;
1259         } else if (msr == MSR_MTRRdefType) {
1260                 if (data & ~0xcff)
1261                         return false;
1262                 return valid_mtrr_type(data & 0xff);
1263         } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1264                 for (i = 0; i < 8 ; i++)
1265                         if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1266                                 return false;
1267                 return true;
1268         }
1269
1270         /* variable MTRRs */
1271         return valid_mtrr_type(data & 0xff);
1272 }
1273
1274 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1275 {
1276         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1277
1278         if (!mtrr_valid(vcpu, msr, data))
1279                 return 1;
1280
1281         if (msr == MSR_MTRRdefType) {
1282                 vcpu->arch.mtrr_state.def_type = data;
1283                 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1284         } else if (msr == MSR_MTRRfix64K_00000)
1285                 p[0] = data;
1286         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1287                 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1288         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1289                 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1290         else if (msr == MSR_IA32_CR_PAT)
1291                 vcpu->arch.pat = data;
1292         else {  /* Variable MTRRs */
1293                 int idx, is_mtrr_mask;
1294                 u64 *pt;
1295
1296                 idx = (msr - 0x200) / 2;
1297                 is_mtrr_mask = msr - 0x200 - 2 * idx;
1298                 if (!is_mtrr_mask)
1299                         pt =
1300                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1301                 else
1302                         pt =
1303                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1304                 *pt = data;
1305         }
1306
1307         kvm_mmu_reset_context(vcpu);
1308         return 0;
1309 }
1310
1311 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1312 {
1313         u64 mcg_cap = vcpu->arch.mcg_cap;
1314         unsigned bank_num = mcg_cap & 0xff;
1315
1316         switch (msr) {
1317         case MSR_IA32_MCG_STATUS:
1318                 vcpu->arch.mcg_status = data;
1319                 break;
1320         case MSR_IA32_MCG_CTL:
1321                 if (!(mcg_cap & MCG_CTL_P))
1322                         return 1;
1323                 if (data != 0 && data != ~(u64)0)
1324                         return -1;
1325                 vcpu->arch.mcg_ctl = data;
1326                 break;
1327         default:
1328                 if (msr >= MSR_IA32_MC0_CTL &&
1329                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1330                         u32 offset = msr - MSR_IA32_MC0_CTL;
1331                         /* only 0 or all 1s can be written to IA32_MCi_CTL
1332                          * some Linux kernels though clear bit 10 in bank 4 to
1333                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1334                          * this to avoid an uncatched #GP in the guest
1335                          */
1336                         if ((offset & 0x3) == 0 &&
1337                             data != 0 && (data | (1 << 10)) != ~(u64)0)
1338                                 return -1;
1339                         vcpu->arch.mce_banks[offset] = data;
1340                         break;
1341                 }
1342                 return 1;
1343         }
1344         return 0;
1345 }
1346
1347 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1348 {
1349         struct kvm *kvm = vcpu->kvm;
1350         int lm = is_long_mode(vcpu);
1351         u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1352                 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1353         u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1354                 : kvm->arch.xen_hvm_config.blob_size_32;
1355         u32 page_num = data & ~PAGE_MASK;
1356         u64 page_addr = data & PAGE_MASK;
1357         u8 *page;
1358         int r;
1359
1360         r = -E2BIG;
1361         if (page_num >= blob_size)
1362                 goto out;
1363         r = -ENOMEM;
1364         page = kzalloc(PAGE_SIZE, GFP_KERNEL);
1365         if (!page)
1366                 goto out;
1367         r = -EFAULT;
1368         if (copy_from_user(page, blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE))
1369                 goto out_free;
1370         if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1371                 goto out_free;
1372         r = 0;
1373 out_free:
1374         kfree(page);
1375 out:
1376         return r;
1377 }
1378
1379 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1380 {
1381         return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1382 }
1383
1384 static bool kvm_hv_msr_partition_wide(u32 msr)
1385 {
1386         bool r = false;
1387         switch (msr) {
1388         case HV_X64_MSR_GUEST_OS_ID:
1389         case HV_X64_MSR_HYPERCALL:
1390                 r = true;
1391                 break;
1392         }
1393
1394         return r;
1395 }
1396
1397 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1398 {
1399         struct kvm *kvm = vcpu->kvm;
1400
1401         switch (msr) {
1402         case HV_X64_MSR_GUEST_OS_ID:
1403                 kvm->arch.hv_guest_os_id = data;
1404                 /* setting guest os id to zero disables hypercall page */
1405                 if (!kvm->arch.hv_guest_os_id)
1406                         kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1407                 break;
1408         case HV_X64_MSR_HYPERCALL: {
1409                 u64 gfn;
1410                 unsigned long addr;
1411                 u8 instructions[4];
1412
1413                 /* if guest os id is not set hypercall should remain disabled */
1414                 if (!kvm->arch.hv_guest_os_id)
1415                         break;
1416                 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1417                         kvm->arch.hv_hypercall = data;
1418                         break;
1419                 }
1420                 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1421                 addr = gfn_to_hva(kvm, gfn);
1422                 if (kvm_is_error_hva(addr))
1423                         return 1;
1424                 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1425                 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1426                 if (__copy_to_user((void __user *)addr, instructions, 4))
1427                         return 1;
1428                 kvm->arch.hv_hypercall = data;
1429                 break;
1430         }
1431         default:
1432                 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1433                           "data 0x%llx\n", msr, data);
1434                 return 1;
1435         }
1436         return 0;
1437 }
1438
1439 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1440 {
1441         switch (msr) {
1442         case HV_X64_MSR_APIC_ASSIST_PAGE: {
1443                 unsigned long addr;
1444
1445                 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1446                         vcpu->arch.hv_vapic = data;
1447                         break;
1448                 }
1449                 addr = gfn_to_hva(vcpu->kvm, data >>
1450                                   HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
1451                 if (kvm_is_error_hva(addr))
1452                         return 1;
1453                 if (__clear_user((void __user *)addr, PAGE_SIZE))
1454                         return 1;
1455                 vcpu->arch.hv_vapic = data;
1456                 break;
1457         }
1458         case HV_X64_MSR_EOI:
1459                 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1460         case HV_X64_MSR_ICR:
1461                 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1462         case HV_X64_MSR_TPR:
1463                 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1464         default:
1465                 pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1466                           "data 0x%llx\n", msr, data);
1467                 return 1;
1468         }
1469
1470         return 0;
1471 }
1472
1473 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1474 {
1475         gpa_t gpa = data & ~0x3f;
1476
1477         /* Bits 2:5 are resrved, Should be zero */
1478         if (data & 0x3c)
1479                 return 1;
1480
1481         vcpu->arch.apf.msr_val = data;
1482
1483         if (!(data & KVM_ASYNC_PF_ENABLED)) {
1484                 kvm_clear_async_pf_completion_queue(vcpu);
1485                 kvm_async_pf_hash_reset(vcpu);
1486                 return 0;
1487         }
1488
1489         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
1490                 return 1;
1491
1492         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1493         kvm_async_pf_wakeup_all(vcpu);
1494         return 0;
1495 }
1496
1497 static void kvmclock_reset(struct kvm_vcpu *vcpu)
1498 {
1499         if (vcpu->arch.time_page) {
1500                 kvm_release_page_dirty(vcpu->arch.time_page);
1501                 vcpu->arch.time_page = NULL;
1502         }
1503 }
1504
1505 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
1506 {
1507         u64 delta;
1508
1509         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1510                 return;
1511
1512         delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
1513         vcpu->arch.st.last_steal = current->sched_info.run_delay;
1514         vcpu->arch.st.accum_steal = delta;
1515 }
1516
1517 static void record_steal_time(struct kvm_vcpu *vcpu)
1518 {
1519         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
1520                 return;
1521
1522         if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1523                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
1524                 return;
1525
1526         vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
1527         vcpu->arch.st.steal.version += 2;
1528         vcpu->arch.st.accum_steal = 0;
1529
1530         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
1531                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
1532 }
1533
1534 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1535 {
1536         switch (msr) {
1537         case MSR_EFER:
1538                 return set_efer(vcpu, data);
1539         case MSR_K7_HWCR:
1540                 data &= ~(u64)0x40;     /* ignore flush filter disable */
1541                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
1542                 if (data != 0) {
1543                         pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
1544                                 data);
1545                         return 1;
1546                 }
1547                 break;
1548         case MSR_FAM10H_MMIO_CONF_BASE:
1549                 if (data != 0) {
1550                         pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
1551                                 "0x%llx\n", data);
1552                         return 1;
1553                 }
1554                 break;
1555         case MSR_AMD64_NB_CFG:
1556                 break;
1557         case MSR_IA32_DEBUGCTLMSR:
1558                 if (!data) {
1559                         /* We support the non-activated case already */
1560                         break;
1561                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
1562                         /* Values other than LBR and BTF are vendor-specific,
1563                            thus reserved and should throw a #GP */
1564                         return 1;
1565                 }
1566                 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
1567                         __func__, data);
1568                 break;
1569         case MSR_IA32_UCODE_REV:
1570         case MSR_IA32_UCODE_WRITE:
1571         case MSR_VM_HSAVE_PA:
1572         case MSR_AMD64_PATCH_LOADER:
1573                 break;
1574         case 0x200 ... 0x2ff:
1575                 return set_msr_mtrr(vcpu, msr, data);
1576         case MSR_IA32_APICBASE:
1577                 kvm_set_apic_base(vcpu, data);
1578                 break;
1579         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1580                 return kvm_x2apic_msr_write(vcpu, msr, data);
1581         case MSR_IA32_TSCDEADLINE:
1582                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
1583                 break;
1584         case MSR_IA32_MISC_ENABLE:
1585                 vcpu->arch.ia32_misc_enable_msr = data;
1586                 break;
1587         case MSR_KVM_WALL_CLOCK_NEW:
1588         case MSR_KVM_WALL_CLOCK:
1589                 vcpu->kvm->arch.wall_clock = data;
1590                 kvm_write_wall_clock(vcpu->kvm, data);
1591                 break;
1592         case MSR_KVM_SYSTEM_TIME_NEW:
1593         case MSR_KVM_SYSTEM_TIME: {
1594                 kvmclock_reset(vcpu);
1595
1596                 vcpu->arch.time = data;
1597                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1598
1599                 /* we verify if the enable bit is set... */
1600                 if (!(data & 1))
1601                         break;
1602
1603                 /* ...but clean it before doing the actual write */
1604                 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
1605
1606                 /* Check that the address is 32-byte aligned. */
1607                 if (vcpu->arch.time_offset &
1608                                 (sizeof(struct pvclock_vcpu_time_info) - 1))
1609                         break;
1610
1611                 vcpu->arch.time_page =
1612                                 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
1613
1614                 if (is_error_page(vcpu->arch.time_page)) {
1615                         kvm_release_page_clean(vcpu->arch.time_page);
1616                         vcpu->arch.time_page = NULL;
1617                 }
1618                 break;
1619         }
1620         case MSR_KVM_ASYNC_PF_EN:
1621                 if (kvm_pv_enable_async_pf(vcpu, data))
1622                         return 1;
1623                 break;
1624         case MSR_KVM_STEAL_TIME:
1625
1626                 if (unlikely(!sched_info_on()))
1627                         return 1;
1628
1629                 if (data & KVM_STEAL_RESERVED_MASK)
1630                         return 1;
1631
1632                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
1633                                                         data & KVM_STEAL_VALID_BITS))
1634                         return 1;
1635
1636                 vcpu->arch.st.msr_val = data;
1637
1638                 if (!(data & KVM_MSR_ENABLED))
1639                         break;
1640
1641                 vcpu->arch.st.last_steal = current->sched_info.run_delay;
1642
1643                 preempt_disable();
1644                 accumulate_steal_time(vcpu);
1645                 preempt_enable();
1646
1647                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
1648
1649                 break;
1650
1651         case MSR_IA32_MCG_CTL:
1652         case MSR_IA32_MCG_STATUS:
1653         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1654                 return set_msr_mce(vcpu, msr, data);
1655
1656         /* Performance counters are not protected by a CPUID bit,
1657          * so we should check all of them in the generic path for the sake of
1658          * cross vendor migration.
1659          * Writing a zero into the event select MSRs disables them,
1660          * which we perfectly emulate ;-). Any other value should be at least
1661          * reported, some guests depend on them.
1662          */
1663         case MSR_P6_EVNTSEL0:
1664         case MSR_P6_EVNTSEL1:
1665         case MSR_K7_EVNTSEL0:
1666         case MSR_K7_EVNTSEL1:
1667         case MSR_K7_EVNTSEL2:
1668         case MSR_K7_EVNTSEL3:
1669                 if (data != 0)
1670                         pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1671                                 "0x%x data 0x%llx\n", msr, data);
1672                 break;
1673         /* at least RHEL 4 unconditionally writes to the perfctr registers,
1674          * so we ignore writes to make it happy.
1675          */
1676         case MSR_P6_PERFCTR0:
1677         case MSR_P6_PERFCTR1:
1678         case MSR_K7_PERFCTR0:
1679         case MSR_K7_PERFCTR1:
1680         case MSR_K7_PERFCTR2:
1681         case MSR_K7_PERFCTR3:
1682                 pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
1683                         "0x%x data 0x%llx\n", msr, data);
1684                 break;
1685         case MSR_K7_CLK_CTL:
1686                 /*
1687                  * Ignore all writes to this no longer documented MSR.
1688                  * Writes are only relevant for old K7 processors,
1689                  * all pre-dating SVM, but a recommended workaround from
1690                  * AMD for these chips. It is possible to speicify the
1691                  * affected processor models on the command line, hence
1692                  * the need to ignore the workaround.
1693                  */
1694                 break;
1695         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1696                 if (kvm_hv_msr_partition_wide(msr)) {
1697                         int r;
1698                         mutex_lock(&vcpu->kvm->lock);
1699                         r = set_msr_hyperv_pw(vcpu, msr, data);
1700                         mutex_unlock(&vcpu->kvm->lock);
1701                         return r;
1702                 } else
1703                         return set_msr_hyperv(vcpu, msr, data);
1704                 break;
1705         case MSR_IA32_BBL_CR_CTL3:
1706                 /* Drop writes to this legacy MSR -- see rdmsr
1707                  * counterpart for further detail.
1708                  */
1709                 pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
1710                 break;
1711         default:
1712                 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
1713                         return xen_hvm_config(vcpu, data);
1714                 if (!ignore_msrs) {
1715                         pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
1716                                 msr, data);
1717                         return 1;
1718                 } else {
1719                         pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
1720                                 msr, data);
1721                         break;
1722                 }
1723         }
1724         return 0;
1725 }
1726 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
1727
1728
1729 /*
1730  * Reads an msr value (of 'msr_index') into 'pdata'.
1731  * Returns 0 on success, non-0 otherwise.
1732  * Assumes vcpu_load() was already called.
1733  */
1734 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1735 {
1736         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
1737 }
1738
1739 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1740 {
1741         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1742
1743         if (!msr_mtrr_valid(msr))
1744                 return 1;
1745
1746         if (msr == MSR_MTRRdefType)
1747                 *pdata = vcpu->arch.mtrr_state.def_type +
1748                          (vcpu->arch.mtrr_state.enabled << 10);
1749         else if (msr == MSR_MTRRfix64K_00000)
1750                 *pdata = p[0];
1751         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1752                 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
1753         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1754                 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
1755         else if (msr == MSR_IA32_CR_PAT)
1756                 *pdata = vcpu->arch.pat;
1757         else {  /* Variable MTRRs */
1758                 int idx, is_mtrr_mask;
1759                 u64 *pt;
1760
1761                 idx = (msr - 0x200) / 2;
1762                 is_mtrr_mask = msr - 0x200 - 2 * idx;
1763                 if (!is_mtrr_mask)
1764                         pt =
1765                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1766                 else
1767                         pt =
1768                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1769                 *pdata = *pt;
1770         }
1771
1772         return 0;
1773 }
1774
1775 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1776 {
1777         u64 data;
1778         u64 mcg_cap = vcpu->arch.mcg_cap;
1779         unsigned bank_num = mcg_cap & 0xff;
1780
1781         switch (msr) {
1782         case MSR_IA32_P5_MC_ADDR:
1783         case MSR_IA32_P5_MC_TYPE:
1784                 data = 0;
1785                 break;
1786         case MSR_IA32_MCG_CAP:
1787                 data = vcpu->arch.mcg_cap;
1788                 break;
1789         case MSR_IA32_MCG_CTL:
1790                 if (!(mcg_cap & MCG_CTL_P))
1791                         return 1;
1792                 data = vcpu->arch.mcg_ctl;
1793                 break;
1794         case MSR_IA32_MCG_STATUS:
1795                 data = vcpu->arch.mcg_status;
1796                 break;
1797         default:
1798                 if (msr >= MSR_IA32_MC0_CTL &&
1799                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1800                         u32 offset = msr - MSR_IA32_MC0_CTL;
1801                         data = vcpu->arch.mce_banks[offset];
1802                         break;
1803                 }
1804                 return 1;
1805         }
1806         *pdata = data;
1807         return 0;
1808 }
1809
1810 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1811 {
1812         u64 data = 0;
1813         struct kvm *kvm = vcpu->kvm;
1814
1815         switch (msr) {
1816         case HV_X64_MSR_GUEST_OS_ID:
1817                 data = kvm->arch.hv_guest_os_id;
1818                 break;
1819         case HV_X64_MSR_HYPERCALL:
1820                 data = kvm->arch.hv_hypercall;
1821                 break;
1822         default:
1823                 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1824                 return 1;
1825         }
1826
1827         *pdata = data;
1828         return 0;
1829 }
1830
1831 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1832 {
1833         u64 data = 0;
1834
1835         switch (msr) {
1836         case HV_X64_MSR_VP_INDEX: {
1837                 int r;
1838                 struct kvm_vcpu *v;
1839                 kvm_for_each_vcpu(r, v, vcpu->kvm)
1840                         if (v == vcpu)
1841                                 data = r;
1842                 break;
1843         }
1844         case HV_X64_MSR_EOI:
1845                 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1846         case HV_X64_MSR_ICR:
1847                 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1848         case HV_X64_MSR_TPR:
1849                 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1850         case HV_X64_MSR_APIC_ASSIST_PAGE:
1851                 data = vcpu->arch.hv_vapic;
1852                 break;
1853         default:
1854                 pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1855                 return 1;
1856         }
1857         *pdata = data;
1858         return 0;
1859 }
1860
1861 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1862 {
1863         u64 data;
1864
1865         switch (msr) {
1866         case MSR_IA32_PLATFORM_ID:
1867         case MSR_IA32_EBL_CR_POWERON:
1868         case MSR_IA32_DEBUGCTLMSR:
1869         case MSR_IA32_LASTBRANCHFROMIP:
1870         case MSR_IA32_LASTBRANCHTOIP:
1871         case MSR_IA32_LASTINTFROMIP:
1872         case MSR_IA32_LASTINTTOIP:
1873         case MSR_K8_SYSCFG:
1874         case MSR_K7_HWCR:
1875         case MSR_VM_HSAVE_PA:
1876         case MSR_P6_PERFCTR0:
1877         case MSR_P6_PERFCTR1:
1878         case MSR_P6_EVNTSEL0:
1879         case MSR_P6_EVNTSEL1:
1880         case MSR_K7_EVNTSEL0:
1881         case MSR_K7_PERFCTR0:
1882         case MSR_K8_INT_PENDING_MSG:
1883         case MSR_AMD64_NB_CFG:
1884         case MSR_FAM10H_MMIO_CONF_BASE:
1885                 data = 0;
1886                 break;
1887         case MSR_IA32_UCODE_REV:
1888                 data = 0x100000000ULL;
1889                 break;
1890         case MSR_MTRRcap:
1891                 data = 0x500 | KVM_NR_VAR_MTRR;
1892                 break;
1893         case 0x200 ... 0x2ff:
1894                 return get_msr_mtrr(vcpu, msr, pdata);
1895         case 0xcd: /* fsb frequency */
1896                 data = 3;
1897                 break;
1898                 /*
1899                  * MSR_EBC_FREQUENCY_ID
1900                  * Conservative value valid for even the basic CPU models.
1901                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
1902                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
1903                  * and 266MHz for model 3, or 4. Set Core Clock
1904                  * Frequency to System Bus Frequency Ratio to 1 (bits
1905                  * 31:24) even though these are only valid for CPU
1906                  * models > 2, however guests may end up dividing or
1907                  * multiplying by zero otherwise.
1908                  */
1909         case MSR_EBC_FREQUENCY_ID:
1910                 data = 1 << 24;
1911                 break;
1912         case MSR_IA32_APICBASE:
1913                 data = kvm_get_apic_base(vcpu);
1914                 break;
1915         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
1916                 return kvm_x2apic_msr_read(vcpu, msr, pdata);
1917                 break;
1918         case MSR_IA32_TSCDEADLINE:
1919                 data = kvm_get_lapic_tscdeadline_msr(vcpu);
1920                 break;
1921         case MSR_IA32_MISC_ENABLE:
1922                 data = vcpu->arch.ia32_misc_enable_msr;
1923                 break;
1924         case MSR_IA32_PERF_STATUS:
1925                 /* TSC increment by tick */
1926                 data = 1000ULL;
1927                 /* CPU multiplier */
1928                 data |= (((uint64_t)4ULL) << 40);
1929                 break;
1930         case MSR_EFER:
1931                 data = vcpu->arch.efer;
1932                 break;
1933         case MSR_KVM_WALL_CLOCK:
1934         case MSR_KVM_WALL_CLOCK_NEW:
1935                 data = vcpu->kvm->arch.wall_clock;
1936                 break;
1937         case MSR_KVM_SYSTEM_TIME:
1938         case MSR_KVM_SYSTEM_TIME_NEW:
1939                 data = vcpu->arch.time;
1940                 break;
1941         case MSR_KVM_ASYNC_PF_EN:
1942                 data = vcpu->arch.apf.msr_val;
1943                 break;
1944         case MSR_KVM_STEAL_TIME:
1945                 data = vcpu->arch.st.msr_val;
1946                 break;
1947         case MSR_IA32_P5_MC_ADDR:
1948         case MSR_IA32_P5_MC_TYPE:
1949         case MSR_IA32_MCG_CAP:
1950         case MSR_IA32_MCG_CTL:
1951         case MSR_IA32_MCG_STATUS:
1952         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
1953                 return get_msr_mce(vcpu, msr, pdata);
1954         case MSR_K7_CLK_CTL:
1955                 /*
1956                  * Provide expected ramp-up count for K7. All other
1957                  * are set to zero, indicating minimum divisors for
1958                  * every field.
1959                  *
1960                  * This prevents guest kernels on AMD host with CPU
1961                  * type 6, model 8 and higher from exploding due to
1962                  * the rdmsr failing.
1963                  */
1964                 data = 0x20000000;
1965                 break;
1966         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
1967                 if (kvm_hv_msr_partition_wide(msr)) {
1968                         int r;
1969                         mutex_lock(&vcpu->kvm->lock);
1970                         r = get_msr_hyperv_pw(vcpu, msr, pdata);
1971                         mutex_unlock(&vcpu->kvm->lock);
1972                         return r;
1973                 } else
1974                         return get_msr_hyperv(vcpu, msr, pdata);
1975                 break;
1976         case MSR_IA32_BBL_CR_CTL3:
1977                 /* This legacy MSR exists but isn't fully documented in current
1978                  * silicon.  It is however accessed by winxp in very narrow
1979                  * scenarios where it sets bit #19, itself documented as
1980                  * a "reserved" bit.  Best effort attempt to source coherent
1981                  * read data here should the balance of the register be
1982                  * interpreted by the guest:
1983                  *
1984                  * L2 cache control register 3: 64GB range, 256KB size,
1985                  * enabled, latency 0x1, configured
1986                  */
1987                 data = 0xbe702111;
1988                 break;
1989         default:
1990                 if (!ignore_msrs) {
1991                         pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
1992                         return 1;
1993                 } else {
1994                         pr_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
1995                         data = 0;
1996                 }
1997                 break;
1998         }
1999         *pdata = data;
2000         return 0;
2001 }
2002 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2003
2004 /*
2005  * Read or write a bunch of msrs. All parameters are kernel addresses.
2006  *
2007  * @return number of msrs set successfully.
2008  */
2009 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2010                     struct kvm_msr_entry *entries,
2011                     int (*do_msr)(struct kvm_vcpu *vcpu,
2012                                   unsigned index, u64 *data))
2013 {
2014         int i, idx;
2015
2016         idx = srcu_read_lock(&vcpu->kvm->srcu);
2017         for (i = 0; i < msrs->nmsrs; ++i)
2018                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2019                         break;
2020         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2021
2022         return i;
2023 }
2024
2025 /*
2026  * Read or write a bunch of msrs. Parameters are user addresses.
2027  *
2028  * @return number of msrs set successfully.
2029  */
2030 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2031                   int (*do_msr)(struct kvm_vcpu *vcpu,
2032                                 unsigned index, u64 *data),
2033                   int writeback)
2034 {
2035         struct kvm_msrs msrs;
2036         struct kvm_msr_entry *entries;
2037         int r, n;
2038         unsigned size;
2039
2040         r = -EFAULT;
2041         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2042                 goto out;
2043
2044         r = -E2BIG;
2045         if (msrs.nmsrs >= MAX_IO_MSRS)
2046                 goto out;
2047
2048         r = -ENOMEM;
2049         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2050         entries = kmalloc(size, GFP_KERNEL);
2051         if (!entries)
2052                 goto out;
2053
2054         r = -EFAULT;
2055         if (copy_from_user(entries, user_msrs->entries, size))
2056                 goto out_free;
2057
2058         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2059         if (r < 0)
2060                 goto out_free;
2061
2062         r = -EFAULT;
2063         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2064                 goto out_free;
2065
2066         r = n;
2067
2068 out_free:
2069         kfree(entries);
2070 out:
2071         return r;
2072 }
2073
2074 int kvm_dev_ioctl_check_extension(long ext)
2075 {
2076         int r;
2077
2078         switch (ext) {
2079         case KVM_CAP_IRQCHIP:
2080         case KVM_CAP_HLT:
2081         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2082         case KVM_CAP_SET_TSS_ADDR:
2083         case KVM_CAP_EXT_CPUID:
2084         case KVM_CAP_CLOCKSOURCE:
2085         case KVM_CAP_PIT:
2086         case KVM_CAP_NOP_IO_DELAY:
2087         case KVM_CAP_MP_STATE:
2088         case KVM_CAP_SYNC_MMU:
2089         case KVM_CAP_USER_NMI:
2090         case KVM_CAP_REINJECT_CONTROL:
2091         case KVM_CAP_IRQ_INJECT_STATUS:
2092         case KVM_CAP_ASSIGN_DEV_IRQ:
2093         case KVM_CAP_IRQFD:
2094         case KVM_CAP_IOEVENTFD:
2095         case KVM_CAP_PIT2:
2096         case KVM_CAP_PIT_STATE2:
2097         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2098         case KVM_CAP_XEN_HVM:
2099         case KVM_CAP_ADJUST_CLOCK:
2100         case KVM_CAP_VCPU_EVENTS:
2101         case KVM_CAP_HYPERV:
2102         case KVM_CAP_HYPERV_VAPIC:
2103         case KVM_CAP_HYPERV_SPIN:
2104         case KVM_CAP_PCI_SEGMENT:
2105         case KVM_CAP_DEBUGREGS:
2106         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2107         case KVM_CAP_XSAVE:
2108         case KVM_CAP_ASYNC_PF:
2109         case KVM_CAP_GET_TSC_KHZ:
2110                 r = 1;
2111                 break;
2112         case KVM_CAP_COALESCED_MMIO:
2113                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2114                 break;
2115         case KVM_CAP_VAPIC:
2116                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2117                 break;
2118         case KVM_CAP_NR_VCPUS:
2119                 r = KVM_SOFT_MAX_VCPUS;
2120                 break;
2121         case KVM_CAP_MAX_VCPUS:
2122                 r = KVM_MAX_VCPUS;
2123                 break;
2124         case KVM_CAP_NR_MEMSLOTS:
2125                 r = KVM_MEMORY_SLOTS;
2126                 break;
2127         case KVM_CAP_PV_MMU:    /* obsolete */
2128                 r = 0;
2129                 break;
2130         case KVM_CAP_IOMMU:
2131                 r = iommu_present(&pci_bus_type);
2132                 break;
2133         case KVM_CAP_MCE:
2134                 r = KVM_MAX_MCE_BANKS;
2135                 break;
2136         case KVM_CAP_XCRS:
2137                 r = cpu_has_xsave;
2138                 break;
2139         case KVM_CAP_TSC_CONTROL:
2140                 r = kvm_has_tsc_control;
2141                 break;
2142         case KVM_CAP_TSC_DEADLINE_TIMER:
2143                 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2144                 break;
2145         default:
2146                 r = 0;
2147                 break;
2148         }
2149         return r;
2150
2151 }
2152
2153 long kvm_arch_dev_ioctl(struct file *filp,
2154                         unsigned int ioctl, unsigned long arg)
2155 {
2156         void __user *argp = (void __user *)arg;
2157         long r;
2158
2159         switch (ioctl) {
2160         case KVM_GET_MSR_INDEX_LIST: {
2161                 struct kvm_msr_list __user *user_msr_list = argp;
2162                 struct kvm_msr_list msr_list;
2163                 unsigned n;
2164
2165                 r = -EFAULT;
2166                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2167                         goto out;
2168                 n = msr_list.nmsrs;
2169                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2170                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2171                         goto out;
2172                 r = -E2BIG;
2173                 if (n < msr_list.nmsrs)
2174                         goto out;
2175                 r = -EFAULT;
2176                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2177                                  num_msrs_to_save * sizeof(u32)))
2178                         goto out;
2179                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2180                                  &emulated_msrs,
2181                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2182                         goto out;
2183                 r = 0;
2184                 break;
2185         }
2186         case KVM_GET_SUPPORTED_CPUID: {
2187                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2188                 struct kvm_cpuid2 cpuid;
2189
2190                 r = -EFAULT;
2191                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2192                         goto out;
2193                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
2194                                                       cpuid_arg->entries);
2195                 if (r)
2196                         goto out;
2197
2198                 r = -EFAULT;
2199                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2200                         goto out;
2201                 r = 0;
2202                 break;
2203         }
2204         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2205                 u64 mce_cap;
2206
2207                 mce_cap = KVM_MCE_CAP_SUPPORTED;
2208                 r = -EFAULT;
2209                 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2210                         goto out;
2211                 r = 0;
2212                 break;
2213         }
2214         default:
2215                 r = -EINVAL;
2216         }
2217 out:
2218         return r;
2219 }
2220
2221 static void wbinvd_ipi(void *garbage)
2222 {
2223         wbinvd();
2224 }
2225
2226 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2227 {
2228         return vcpu->kvm->arch.iommu_domain &&
2229                 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
2230 }
2231
2232 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2233 {
2234         /* Address WBINVD may be executed by guest */
2235         if (need_emulate_wbinvd(vcpu)) {
2236                 if (kvm_x86_ops->has_wbinvd_exit())
2237                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2238                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2239                         smp_call_function_single(vcpu->cpu,
2240                                         wbinvd_ipi, NULL, 1);
2241         }
2242
2243         kvm_x86_ops->vcpu_load(vcpu, cpu);
2244         if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2245                 /* Make sure TSC doesn't go backwards */
2246                 s64 tsc_delta;
2247                 u64 tsc;
2248
2249                 tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2250                 tsc_delta = !vcpu->arch.last_guest_tsc ? 0 :
2251                              tsc - vcpu->arch.last_guest_tsc;
2252
2253                 if (tsc_delta < 0)
2254                         mark_tsc_unstable("KVM discovered backwards TSC");
2255                 if (check_tsc_unstable()) {
2256                         kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
2257                         vcpu->arch.tsc_catchup = 1;
2258                 }
2259                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2260                 if (vcpu->cpu != cpu)
2261                         kvm_migrate_timers(vcpu);
2262                 vcpu->cpu = cpu;
2263         }
2264
2265         accumulate_steal_time(vcpu);
2266         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2267 }
2268
2269 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2270 {
2271         kvm_x86_ops->vcpu_put(vcpu);
2272         kvm_put_guest_fpu(vcpu);
2273         vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
2274 }
2275
2276 static int is_efer_nx(void)
2277 {
2278         unsigned long long efer = 0;
2279
2280         rdmsrl_safe(MSR_EFER, &efer);
2281         return efer & EFER_NX;
2282 }
2283
2284 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
2285 {
2286         int i;
2287         struct kvm_cpuid_entry2 *e, *entry;
2288
2289         entry = NULL;
2290         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2291                 e = &vcpu->arch.cpuid_entries[i];
2292                 if (e->function == 0x80000001) {
2293                         entry = e;
2294                         break;
2295                 }
2296         }
2297         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
2298                 entry->edx &= ~(1 << 20);
2299                 printk(KERN_INFO "kvm: guest NX capability removed\n");
2300         }
2301 }
2302
2303 /* when an old userspace process fills a new kernel module */
2304 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
2305                                     struct kvm_cpuid *cpuid,
2306                                     struct kvm_cpuid_entry __user *entries)
2307 {
2308         int r, i;
2309         struct kvm_cpuid_entry *cpuid_entries;
2310
2311         r = -E2BIG;
2312         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2313                 goto out;
2314         r = -ENOMEM;
2315         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
2316         if (!cpuid_entries)
2317                 goto out;
2318         r = -EFAULT;
2319         if (copy_from_user(cpuid_entries, entries,
2320                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
2321                 goto out_free;
2322         for (i = 0; i < cpuid->nent; i++) {
2323                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
2324                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
2325                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
2326                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
2327                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
2328                 vcpu->arch.cpuid_entries[i].index = 0;
2329                 vcpu->arch.cpuid_entries[i].flags = 0;
2330                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
2331                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
2332                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
2333         }
2334         vcpu->arch.cpuid_nent = cpuid->nent;
2335         cpuid_fix_nx_cap(vcpu);
2336         r = 0;
2337         kvm_apic_set_version(vcpu);
2338         kvm_x86_ops->cpuid_update(vcpu);
2339         update_cpuid(vcpu);
2340
2341 out_free:
2342         vfree(cpuid_entries);
2343 out:
2344         return r;
2345 }
2346
2347 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
2348                                      struct kvm_cpuid2 *cpuid,
2349                                      struct kvm_cpuid_entry2 __user *entries)
2350 {
2351         int r;
2352
2353         r = -E2BIG;
2354         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2355                 goto out;
2356         r = -EFAULT;
2357         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
2358                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
2359                 goto out;
2360         vcpu->arch.cpuid_nent = cpuid->nent;
2361         kvm_apic_set_version(vcpu);
2362         kvm_x86_ops->cpuid_update(vcpu);
2363         update_cpuid(vcpu);
2364         return 0;
2365
2366 out:
2367         return r;
2368 }
2369
2370 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
2371                                      struct kvm_cpuid2 *cpuid,
2372                                      struct kvm_cpuid_entry2 __user *entries)
2373 {
2374         int r;
2375
2376         r = -E2BIG;
2377         if (cpuid->nent < vcpu->arch.cpuid_nent)
2378                 goto out;
2379         r = -EFAULT;
2380         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
2381                          vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
2382                 goto out;
2383         return 0;
2384
2385 out:
2386         cpuid->nent = vcpu->arch.cpuid_nent;
2387         return r;
2388 }
2389
2390 static void cpuid_mask(u32 *word, int wordnum)
2391 {
2392         *word &= boot_cpu_data.x86_capability[wordnum];
2393 }
2394
2395 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2396                            u32 index)
2397 {
2398         entry->function = function;
2399         entry->index = index;
2400         cpuid_count(entry->function, entry->index,
2401                     &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
2402         entry->flags = 0;
2403 }
2404
2405 static bool supported_xcr0_bit(unsigned bit)
2406 {
2407         u64 mask = ((u64)1 << bit);
2408
2409         return mask & (XSTATE_FP | XSTATE_SSE | XSTATE_YMM) & host_xcr0;
2410 }
2411
2412 #define F(x) bit(X86_FEATURE_##x)
2413
2414 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
2415                          u32 index, int *nent, int maxnent)
2416 {
2417         unsigned f_nx = is_efer_nx() ? F(NX) : 0;
2418 #ifdef CONFIG_X86_64
2419         unsigned f_gbpages = (kvm_x86_ops->get_lpage_level() == PT_PDPE_LEVEL)
2420                                 ? F(GBPAGES) : 0;
2421         unsigned f_lm = F(LM);
2422 #else
2423         unsigned f_gbpages = 0;
2424         unsigned f_lm = 0;
2425 #endif
2426         unsigned f_rdtscp = kvm_x86_ops->rdtscp_supported() ? F(RDTSCP) : 0;
2427
2428         /* cpuid 1.edx */
2429         const u32 kvm_supported_word0_x86_features =
2430                 F(FPU) | F(VME) | F(DE) | F(PSE) |
2431                 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2432                 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
2433                 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2434                 F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLSH) |
2435                 0 /* Reserved, DS, ACPI */ | F(MMX) |
2436                 F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
2437                 0 /* HTT, TM, Reserved, PBE */;
2438         /* cpuid 0x80000001.edx */
2439         const u32 kvm_supported_word1_x86_features =
2440                 F(FPU) | F(VME) | F(DE) | F(PSE) |
2441                 F(TSC) | F(MSR) | F(PAE) | F(MCE) |
2442                 F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
2443                 F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
2444                 F(PAT) | F(PSE36) | 0 /* Reserved */ |
2445                 f_nx | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
2446                 F(FXSR) | F(FXSR_OPT) | f_gbpages | f_rdtscp |
2447                 0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW);
2448         /* cpuid 1.ecx */
2449         const u32 kvm_supported_word4_x86_features =
2450                 F(XMM3) | F(PCLMULQDQ) | 0 /* DTES64, MONITOR */ |
2451                 0 /* DS-CPL, VMX, SMX, EST */ |
2452                 0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
2453                 0 /* Reserved */ | F(CX16) | 0 /* xTPR Update, PDCM */ |
2454                 0 /* Reserved, DCA */ | F(XMM4_1) |
2455                 F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
2456                 0 /* Reserved*/ | F(AES) | F(XSAVE) | 0 /* OSXSAVE */ | F(AVX) |
2457                 F(F16C) | F(RDRAND);
2458         /* cpuid 0x80000001.ecx */
2459         const u32 kvm_supported_word6_x86_features =
2460                 F(LAHF_LM) | F(CMP_LEGACY) | 0 /*SVM*/ | 0 /* ExtApicSpace */ |
2461                 F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
2462                 F(3DNOWPREFETCH) | 0 /* OSVW */ | 0 /* IBS */ | F(XOP) |
2463                 0 /* SKINIT, WDT, LWP */ | F(FMA4) | F(TBM);
2464
2465         /* cpuid 0xC0000001.edx */
2466         const u32 kvm_supported_word5_x86_features =
2467                 F(XSTORE) | F(XSTORE_EN) | F(XCRYPT) | F(XCRYPT_EN) |
2468                 F(ACE2) | F(ACE2_EN) | F(PHE) | F(PHE_EN) |
2469                 F(PMM) | F(PMM_EN);
2470
2471         /* cpuid 7.0.ebx */
2472         const u32 kvm_supported_word9_x86_features =
2473                 F(SMEP) | F(FSGSBASE) | F(ERMS);
2474
2475         /* all calls to cpuid_count() should be made on the same cpu */
2476         get_cpu();
2477         do_cpuid_1_ent(entry, function, index);
2478         ++*nent;
2479
2480         switch (function) {
2481         case 0:
2482                 entry->eax = min(entry->eax, (u32)0xd);
2483                 break;
2484         case 1:
2485                 entry->edx &= kvm_supported_word0_x86_features;
2486                 cpuid_mask(&entry->edx, 0);
2487                 entry->ecx &= kvm_supported_word4_x86_features;
2488                 cpuid_mask(&entry->ecx, 4);
2489                 /* we support x2apic emulation even if host does not support
2490                  * it since we emulate x2apic in software */
2491                 entry->ecx |= F(X2APIC);
2492                 break;
2493         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
2494          * may return different values. This forces us to get_cpu() before
2495          * issuing the first command, and also to emulate this annoying behavior
2496          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
2497         case 2: {
2498                 int t, times = entry->eax & 0xff;
2499
2500                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2501                 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2502                 for (t = 1; t < times && *nent < maxnent; ++t) {
2503                         do_cpuid_1_ent(&entry[t], function, 0);
2504                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
2505                         ++*nent;
2506                 }
2507                 break;
2508         }
2509         /* function 4 has additional index. */
2510         case 4: {
2511                 int i, cache_type;
2512
2513                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2514                 /* read more entries until cache_type is zero */
2515                 for (i = 1; *nent < maxnent; ++i) {
2516                         cache_type = entry[i - 1].eax & 0x1f;
2517                         if (!cache_type)
2518                                 break;
2519                         do_cpuid_1_ent(&entry[i], function, i);
2520                         entry[i].flags |=
2521                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2522                         ++*nent;
2523                 }
2524                 break;
2525         }
2526         case 7: {
2527                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2528                 /* Mask ebx against host capbability word 9 */
2529                 if (index == 0) {
2530                         entry->ebx &= kvm_supported_word9_x86_features;
2531                         cpuid_mask(&entry->ebx, 9);
2532                 } else
2533                         entry->ebx = 0;
2534                 entry->eax = 0;
2535                 entry->ecx = 0;
2536                 entry->edx = 0;
2537                 break;
2538         }
2539         case 9:
2540                 break;
2541         /* function 0xb has additional index. */
2542         case 0xb: {
2543                 int i, level_type;
2544
2545                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2546                 /* read more entries until level_type is zero */
2547                 for (i = 1; *nent < maxnent; ++i) {
2548                         level_type = entry[i - 1].ecx & 0xff00;
2549                         if (!level_type)
2550                                 break;
2551                         do_cpuid_1_ent(&entry[i], function, i);
2552                         entry[i].flags |=
2553                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2554                         ++*nent;
2555                 }
2556                 break;
2557         }
2558         case 0xd: {
2559                 int idx, i;
2560
2561                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2562                 for (idx = 1, i = 1; *nent < maxnent && idx < 64; ++idx) {
2563                         do_cpuid_1_ent(&entry[i], function, idx);
2564                         if (entry[i].eax == 0 || !supported_xcr0_bit(idx))
2565                                 continue;
2566                         entry[i].flags |=
2567                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2568                         ++*nent;
2569                         ++i;
2570                 }
2571                 break;
2572         }
2573         case KVM_CPUID_SIGNATURE: {
2574                 char signature[12] = "KVMKVMKVM\0\0";
2575                 u32 *sigptr = (u32 *)signature;
2576                 entry->eax = 0;
2577                 entry->ebx = sigptr[0];
2578                 entry->ecx = sigptr[1];
2579                 entry->edx = sigptr[2];
2580                 break;
2581         }
2582         case KVM_CPUID_FEATURES:
2583                 entry->eax = (1 << KVM_FEATURE_CLOCKSOURCE) |
2584                              (1 << KVM_FEATURE_NOP_IO_DELAY) |
2585                              (1 << KVM_FEATURE_CLOCKSOURCE2) |
2586                              (1 << KVM_FEATURE_ASYNC_PF) |
2587                              (1 << KVM_FEATURE_CLOCKSOURCE_STABLE_BIT);
2588
2589                 if (sched_info_on())
2590                         entry->eax |= (1 << KVM_FEATURE_STEAL_TIME);
2591
2592                 entry->ebx = 0;
2593                 entry->ecx = 0;
2594                 entry->edx = 0;
2595                 break;
2596         case 0x80000000:
2597                 entry->eax = min(entry->eax, 0x8000001a);
2598                 break;
2599         case 0x80000001:
2600                 entry->edx &= kvm_supported_word1_x86_features;
2601                 cpuid_mask(&entry->edx, 1);
2602                 entry->ecx &= kvm_supported_word6_x86_features;
2603                 cpuid_mask(&entry->ecx, 6);
2604                 break;
2605         case 0x80000008: {
2606                 unsigned g_phys_as = (entry->eax >> 16) & 0xff;
2607                 unsigned virt_as = max((entry->eax >> 8) & 0xff, 48U);
2608                 unsigned phys_as = entry->eax & 0xff;
2609
2610                 if (!g_phys_as)
2611                         g_phys_as = phys_as;
2612                 entry->eax = g_phys_as | (virt_as << 8);
2613                 entry->ebx = entry->edx = 0;
2614                 break;
2615         }
2616         case 0x80000019:
2617                 entry->ecx = entry->edx = 0;
2618                 break;
2619         case 0x8000001a:
2620                 break;
2621         case 0x8000001d:
2622                 break;
2623         /*Add support for Centaur's CPUID instruction*/
2624         case 0xC0000000:
2625                 /*Just support up to 0xC0000004 now*/
2626                 entry->eax = min(entry->eax, 0xC0000004);
2627                 break;
2628         case 0xC0000001:
2629                 entry->edx &= kvm_supported_word5_x86_features;
2630                 cpuid_mask(&entry->edx, 5);
2631                 break;
2632         case 3: /* Processor serial number */
2633         case 5: /* MONITOR/MWAIT */
2634         case 6: /* Thermal management */
2635         case 0xA: /* Architectural Performance Monitoring */
2636         case 0x80000007: /* Advanced power management */
2637         case 0xC0000002:
2638         case 0xC0000003:
2639         case 0xC0000004:
2640         default:
2641                 entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
2642                 break;
2643         }
2644
2645         kvm_x86_ops->set_supported_cpuid(function, entry);
2646
2647         put_cpu();
2648 }
2649
2650 #undef F
2651
2652 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
2653                                      struct kvm_cpuid_entry2 __user *entries)
2654 {
2655         struct kvm_cpuid_entry2 *cpuid_entries;
2656         int limit, nent = 0, r = -E2BIG;
2657         u32 func;
2658
2659         if (cpuid->nent < 1)
2660                 goto out;
2661         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2662                 cpuid->nent = KVM_MAX_CPUID_ENTRIES;
2663         r = -ENOMEM;
2664         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
2665         if (!cpuid_entries)
2666                 goto out;
2667
2668         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
2669         limit = cpuid_entries[0].eax;
2670         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
2671                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2672                              &nent, cpuid->nent);
2673         r = -E2BIG;
2674         if (nent >= cpuid->nent)
2675                 goto out_free;
2676
2677         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
2678         limit = cpuid_entries[nent - 1].eax;
2679         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
2680                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
2681                              &nent, cpuid->nent);
2682
2683
2684
2685         r = -E2BIG;
2686         if (nent >= cpuid->nent)
2687                 goto out_free;
2688
2689         /* Add support for Centaur's CPUID instruction. */
2690         if (boot_cpu_data.x86_vendor == X86_VENDOR_CENTAUR) {
2691                 do_cpuid_ent(&cpuid_entries[nent], 0xC0000000, 0,
2692                                 &nent, cpuid->nent);
2693
2694                 r = -E2BIG;
2695                 if (nent >= cpuid->nent)
2696                         goto out_free;
2697
2698                 limit = cpuid_entries[nent - 1].eax;
2699                 for (func = 0xC0000001;
2700                         func <= limit && nent < cpuid->nent; ++func)
2701                         do_cpuid_ent(&cpuid_entries[nent], func, 0,
2702                                         &nent, cpuid->nent);
2703
2704                 r = -E2BIG;
2705                 if (nent >= cpuid->nent)
2706                         goto out_free;
2707         }
2708
2709         do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_SIGNATURE, 0, &nent,
2710                      cpuid->nent);
2711
2712         r = -E2BIG;
2713         if (nent >= cpuid->nent)
2714                 goto out_free;
2715
2716         do_cpuid_ent(&cpuid_entries[nent], KVM_CPUID_FEATURES, 0, &nent,
2717                      cpuid->nent);
2718
2719         r = -E2BIG;
2720         if (nent >= cpuid->nent)
2721                 goto out_free;
2722
2723         r = -EFAULT;
2724         if (copy_to_user(entries, cpuid_entries,
2725                          nent * sizeof(struct kvm_cpuid_entry2)))
2726                 goto out_free;
2727         cpuid->nent = nent;
2728         r = 0;
2729
2730 out_free:
2731         vfree(cpuid_entries);
2732 out:
2733         return r;
2734 }
2735
2736 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2737                                     struct kvm_lapic_state *s)
2738 {
2739         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2740
2741         return 0;
2742 }
2743
2744 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2745                                     struct kvm_lapic_state *s)
2746 {
2747         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2748         kvm_apic_post_state_restore(vcpu);
2749         update_cr8_intercept(vcpu);
2750
2751         return 0;
2752 }
2753
2754 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2755                                     struct kvm_interrupt *irq)
2756 {
2757         if (irq->irq < 0 || irq->irq >= 256)
2758                 return -EINVAL;
2759         if (irqchip_in_kernel(vcpu->kvm))
2760                 return -ENXIO;
2761
2762         kvm_queue_interrupt(vcpu, irq->irq, false);
2763         kvm_make_request(KVM_REQ_EVENT, vcpu);
2764
2765         return 0;
2766 }
2767
2768 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2769 {
2770         kvm_inject_nmi(vcpu);
2771
2772         return 0;
2773 }
2774
2775 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2776                                            struct kvm_tpr_access_ctl *tac)
2777 {
2778         if (tac->flags)
2779                 return -EINVAL;
2780         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2781         return 0;
2782 }
2783
2784 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2785                                         u64 mcg_cap)
2786 {
2787         int r;
2788         unsigned bank_num = mcg_cap & 0xff, bank;
2789
2790         r = -EINVAL;
2791         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2792                 goto out;
2793         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2794                 goto out;
2795         r = 0;
2796         vcpu->arch.mcg_cap = mcg_cap;
2797         /* Init IA32_MCG_CTL to all 1s */
2798         if (mcg_cap & MCG_CTL_P)
2799                 vcpu->arch.mcg_ctl = ~(u64)0;
2800         /* Init IA32_MCi_CTL to all 1s */
2801         for (bank = 0; bank < bank_num; bank++)
2802                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2803 out:
2804         return r;
2805 }
2806
2807 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2808                                       struct kvm_x86_mce *mce)
2809 {
2810         u64 mcg_cap = vcpu->arch.mcg_cap;
2811         unsigned bank_num = mcg_cap & 0xff;
2812         u64 *banks = vcpu->arch.mce_banks;
2813
2814         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2815                 return -EINVAL;
2816         /*
2817          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2818          * reporting is disabled
2819          */
2820         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2821             vcpu->arch.mcg_ctl != ~(u64)0)
2822                 return 0;
2823         banks += 4 * mce->bank;
2824         /*
2825          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2826          * reporting is disabled for the bank
2827          */
2828         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2829                 return 0;
2830         if (mce->status & MCI_STATUS_UC) {
2831                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2832                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2833                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2834                         return 0;
2835                 }
2836                 if (banks[1] & MCI_STATUS_VAL)
2837                         mce->status |= MCI_STATUS_OVER;
2838                 banks[2] = mce->addr;
2839                 banks[3] = mce->misc;
2840                 vcpu->arch.mcg_status = mce->mcg_status;
2841                 banks[1] = mce->status;
2842                 kvm_queue_exception(vcpu, MC_VECTOR);
2843         } else if (!(banks[1] & MCI_STATUS_VAL)
2844                    || !(banks[1] & MCI_STATUS_UC)) {
2845                 if (banks[1] & MCI_STATUS_VAL)
2846                         mce->status |= MCI_STATUS_OVER;
2847                 banks[2] = mce->addr;
2848                 banks[3] = mce->misc;
2849                 banks[1] = mce->status;
2850         } else
2851                 banks[1] |= MCI_STATUS_OVER;
2852         return 0;
2853 }
2854
2855 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2856                                                struct kvm_vcpu_events *events)
2857 {
2858         process_nmi(vcpu);
2859         events->exception.injected =
2860                 vcpu->arch.exception.pending &&
2861                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2862         events->exception.nr = vcpu->arch.exception.nr;
2863         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2864         events->exception.pad = 0;
2865         events->exception.error_code = vcpu->arch.exception.error_code;
2866
2867         events->interrupt.injected =
2868                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2869         events->interrupt.nr = vcpu->arch.interrupt.nr;
2870         events->interrupt.soft = 0;
2871         events->interrupt.shadow =
2872                 kvm_x86_ops->get_interrupt_shadow(vcpu,
2873                         KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
2874
2875         events->nmi.injected = vcpu->arch.nmi_injected;
2876         events->nmi.pending = vcpu->arch.nmi_pending != 0;
2877         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
2878         events->nmi.pad = 0;
2879
2880         events->sipi_vector = vcpu->arch.sipi_vector;
2881
2882         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
2883                          | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2884                          | KVM_VCPUEVENT_VALID_SHADOW);
2885         memset(&events->reserved, 0, sizeof(events->reserved));
2886 }
2887
2888 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
2889                                               struct kvm_vcpu_events *events)
2890 {
2891         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
2892                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
2893                               | KVM_VCPUEVENT_VALID_SHADOW))
2894                 return -EINVAL;
2895
2896         process_nmi(vcpu);
2897         vcpu->arch.exception.pending = events->exception.injected;
2898         vcpu->arch.exception.nr = events->exception.nr;
2899         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
2900         vcpu->arch.exception.error_code = events->exception.error_code;
2901
2902         vcpu->arch.interrupt.pending = events->interrupt.injected;
2903         vcpu->arch.interrupt.nr = events->interrupt.nr;
2904         vcpu->arch.interrupt.soft = events->interrupt.soft;
2905         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
2906                 kvm_x86_ops->set_interrupt_shadow(vcpu,
2907                                                   events->interrupt.shadow);
2908
2909         vcpu->arch.nmi_injected = events->nmi.injected;
2910         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
2911                 vcpu->arch.nmi_pending = events->nmi.pending;
2912         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
2913
2914         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
2915                 vcpu->arch.sipi_vector = events->sipi_vector;
2916
2917         kvm_make_request(KVM_REQ_EVENT, vcpu);
2918
2919         return 0;
2920 }
2921
2922 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
2923                                              struct kvm_debugregs *dbgregs)
2924 {
2925         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
2926         dbgregs->dr6 = vcpu->arch.dr6;
2927         dbgregs->dr7 = vcpu->arch.dr7;
2928         dbgregs->flags = 0;
2929         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
2930 }
2931
2932 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
2933                                             struct kvm_debugregs *dbgregs)
2934 {
2935         if (dbgregs->flags)
2936                 return -EINVAL;
2937
2938         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
2939         vcpu->arch.dr6 = dbgregs->dr6;
2940         vcpu->arch.dr7 = dbgregs->dr7;
2941
2942         return 0;
2943 }
2944
2945 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
2946                                          struct kvm_xsave *guest_xsave)
2947 {
2948         if (cpu_has_xsave)
2949                 memcpy(guest_xsave->region,
2950                         &vcpu->arch.guest_fpu.state->xsave,
2951                         xstate_size);
2952         else {
2953                 memcpy(guest_xsave->region,
2954                         &vcpu->arch.guest_fpu.state->fxsave,
2955                         sizeof(struct i387_fxsave_struct));
2956                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
2957                         XSTATE_FPSSE;
2958         }
2959 }
2960
2961 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
2962                                         struct kvm_xsave *guest_xsave)
2963 {
2964         u64 xstate_bv =
2965                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
2966
2967         if (cpu_has_xsave)
2968                 memcpy(&vcpu->arch.guest_fpu.state->xsave,
2969                         guest_xsave->region, xstate_size);
2970         else {
2971                 if (xstate_bv & ~XSTATE_FPSSE)
2972                         return -EINVAL;
2973                 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
2974                         guest_xsave->region, sizeof(struct i387_fxsave_struct));
2975         }
2976         return 0;
2977 }
2978
2979 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
2980                                         struct kvm_xcrs *guest_xcrs)
2981 {
2982         if (!cpu_has_xsave) {
2983                 guest_xcrs->nr_xcrs = 0;
2984                 return;
2985         }
2986
2987         guest_xcrs->nr_xcrs = 1;
2988         guest_xcrs->flags = 0;
2989         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
2990         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
2991 }
2992
2993 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
2994                                        struct kvm_xcrs *guest_xcrs)
2995 {
2996         int i, r = 0;
2997
2998         if (!cpu_has_xsave)
2999                 return -EINVAL;
3000
3001         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3002                 return -EINVAL;
3003
3004         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3005                 /* Only support XCR0 currently */
3006                 if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
3007                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3008                                 guest_xcrs->xcrs[0].value);
3009                         break;
3010                 }
3011         if (r)
3012                 r = -EINVAL;
3013         return r;
3014 }
3015
3016 long kvm_arch_vcpu_ioctl(struct file *filp,
3017                          unsigned int ioctl, unsigned long arg)
3018 {
3019         struct kvm_vcpu *vcpu = filp->private_data;
3020         void __user *argp = (void __user *)arg;
3021         int r;
3022         union {
3023                 struct kvm_lapic_state *lapic;
3024                 struct kvm_xsave *xsave;
3025                 struct kvm_xcrs *xcrs;
3026                 void *buffer;
3027         } u;
3028
3029         u.buffer = NULL;
3030         switch (ioctl) {
3031         case KVM_GET_LAPIC: {
3032                 r = -EINVAL;
3033                 if (!vcpu->arch.apic)
3034                         goto out;
3035                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3036
3037                 r = -ENOMEM;
3038                 if (!u.lapic)
3039                         goto out;
3040                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3041                 if (r)
3042                         goto out;
3043                 r = -EFAULT;
3044                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3045                         goto out;
3046                 r = 0;
3047                 break;
3048         }
3049         case KVM_SET_LAPIC: {
3050                 r = -EINVAL;
3051                 if (!vcpu->arch.apic)
3052                         goto out;
3053                 u.lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3054                 r = -ENOMEM;
3055                 if (!u.lapic)
3056                         goto out;
3057                 r = -EFAULT;
3058                 if (copy_from_user(u.lapic, argp, sizeof(struct kvm_lapic_state)))
3059                         goto out;
3060                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3061                 if (r)
3062                         goto out;
3063                 r = 0;
3064                 break;
3065         }
3066         case KVM_INTERRUPT: {
3067                 struct kvm_interrupt irq;
3068
3069                 r = -EFAULT;
3070                 if (copy_from_user(&irq, argp, sizeof irq))
3071                         goto out;
3072                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3073                 if (r)
3074                         goto out;
3075                 r = 0;
3076                 break;
3077         }
3078         case KVM_NMI: {
3079                 r = kvm_vcpu_ioctl_nmi(vcpu);
3080                 if (r)
3081                         goto out;
3082                 r = 0;
3083                 break;
3084         }
3085         case KVM_SET_CPUID: {
3086                 struct kvm_cpuid __user *cpuid_arg = argp;
3087                 struct kvm_cpuid cpuid;
3088
3089                 r = -EFAULT;
3090                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3091                         goto out;
3092                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3093                 if (r)
3094                         goto out;
3095                 break;
3096         }
3097         case KVM_SET_CPUID2: {
3098                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3099                 struct kvm_cpuid2 cpuid;
3100
3101                 r = -EFAULT;
3102                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3103                         goto out;
3104                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3105                                               cpuid_arg->entries);
3106                 if (r)
3107                         goto out;
3108                 break;
3109         }
3110         case KVM_GET_CPUID2: {
3111                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3112                 struct kvm_cpuid2 cpuid;
3113
3114                 r = -EFAULT;
3115                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3116                         goto out;
3117                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3118                                               cpuid_arg->entries);
3119                 if (r)
3120                         goto out;
3121                 r = -EFAULT;
3122                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3123                         goto out;
3124                 r = 0;
3125                 break;
3126         }
3127         case KVM_GET_MSRS:
3128                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3129                 break;
3130         case KVM_SET_MSRS:
3131                 r = msr_io(vcpu, argp, do_set_msr, 0);
3132                 break;
3133         case KVM_TPR_ACCESS_REPORTING: {
3134                 struct kvm_tpr_access_ctl tac;
3135
3136                 r = -EFAULT;
3137                 if (copy_from_user(&tac, argp, sizeof tac))
3138                         goto out;
3139                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3140                 if (r)
3141                         goto out;
3142                 r = -EFAULT;
3143                 if (copy_to_user(argp, &tac, sizeof tac))
3144                         goto out;
3145                 r = 0;
3146                 break;
3147         };
3148         case KVM_SET_VAPIC_ADDR: {
3149                 struct kvm_vapic_addr va;
3150
3151                 r = -EINVAL;
3152                 if (!irqchip_in_kernel(vcpu->kvm))
3153                         goto out;
3154                 r = -EFAULT;
3155                 if (copy_from_user(&va, argp, sizeof va))
3156                         goto out;
3157                 r = 0;
3158                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3159                 break;
3160         }
3161         case KVM_X86_SETUP_MCE: {
3162                 u64 mcg_cap;
3163
3164                 r = -EFAULT;
3165                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3166                         goto out;
3167                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3168                 break;
3169         }
3170         case KVM_X86_SET_MCE: {
3171                 struct kvm_x86_mce mce;
3172
3173                 r = -EFAULT;
3174                 if (copy_from_user(&mce, argp, sizeof mce))
3175                         goto out;
3176                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3177                 break;
3178         }
3179         case KVM_GET_VCPU_EVENTS: {
3180                 struct kvm_vcpu_events events;
3181
3182                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3183
3184                 r = -EFAULT;
3185                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3186                         break;
3187                 r = 0;
3188                 break;
3189         }
3190         case KVM_SET_VCPU_EVENTS: {
3191                 struct kvm_vcpu_events events;
3192
3193                 r = -EFAULT;
3194                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3195                         break;
3196
3197                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3198                 break;
3199         }
3200         case KVM_GET_DEBUGREGS: {
3201                 struct kvm_debugregs dbgregs;
3202
3203                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3204
3205                 r = -EFAULT;
3206                 if (copy_to_user(argp, &dbgregs,
3207                                  sizeof(struct kvm_debugregs)))
3208                         break;
3209                 r = 0;
3210                 break;
3211         }
3212         case KVM_SET_DEBUGREGS: {
3213                 struct kvm_debugregs dbgregs;
3214
3215                 r = -EFAULT;
3216                 if (copy_from_user(&dbgregs, argp,
3217                                    sizeof(struct kvm_debugregs)))
3218                         break;
3219
3220                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3221                 break;
3222         }
3223         case KVM_GET_XSAVE: {
3224                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3225                 r = -ENOMEM;
3226                 if (!u.xsave)
3227                         break;
3228
3229                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3230
3231                 r = -EFAULT;
3232                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3233                         break;
3234                 r = 0;
3235                 break;
3236         }
3237         case KVM_SET_XSAVE: {
3238                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3239                 r = -ENOMEM;
3240                 if (!u.xsave)
3241                         break;
3242
3243                 r = -EFAULT;
3244                 if (copy_from_user(u.xsave, argp, sizeof(struct kvm_xsave)))
3245                         break;
3246
3247                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3248                 break;
3249         }
3250         case KVM_GET_XCRS: {
3251                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3252                 r = -ENOMEM;
3253                 if (!u.xcrs)
3254                         break;
3255
3256                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3257
3258                 r = -EFAULT;
3259                 if (copy_to_user(argp, u.xcrs,
3260                                  sizeof(struct kvm_xcrs)))
3261                         break;
3262                 r = 0;
3263                 break;
3264         }
3265         case KVM_SET_XCRS: {
3266                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3267                 r = -ENOMEM;
3268                 if (!u.xcrs)
3269                         break;
3270
3271                 r = -EFAULT;
3272                 if (copy_from_user(u.xcrs, argp,
3273                                    sizeof(struct kvm_xcrs)))
3274                         break;
3275
3276                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3277                 break;
3278         }
3279         case KVM_SET_TSC_KHZ: {
3280                 u32 user_tsc_khz;
3281
3282                 r = -EINVAL;
3283                 if (!kvm_has_tsc_control)
3284                         break;
3285
3286                 user_tsc_khz = (u32)arg;
3287
3288                 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3289                         goto out;
3290
3291                 kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
3292
3293                 r = 0;
3294                 goto out;
3295         }
3296         case KVM_GET_TSC_KHZ: {
3297                 r = -EIO;
3298                 if (check_tsc_unstable())
3299                         goto out;
3300
3301                 r = vcpu_tsc_khz(vcpu);
3302
3303                 goto out;
3304         }
3305         default:
3306                 r = -EINVAL;
3307         }
3308 out:
3309         kfree(u.buffer);
3310         return r;
3311 }
3312
3313 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3314 {
3315         int ret;
3316
3317         if (addr > (unsigned int)(-3 * PAGE_SIZE))
3318                 return -1;
3319         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3320         return ret;
3321 }
3322
3323 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3324                                               u64 ident_addr)
3325 {
3326         kvm->arch.ept_identity_map_addr = ident_addr;
3327         return 0;
3328 }
3329
3330 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3331                                           u32 kvm_nr_mmu_pages)
3332 {
3333         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3334                 return -EINVAL;
3335
3336         mutex_lock(&kvm->slots_lock);
3337         spin_lock(&kvm->mmu_lock);
3338
3339         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3340         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3341
3342         spin_unlock(&kvm->mmu_lock);
3343         mutex_unlock(&kvm->slots_lock);
3344         return 0;
3345 }
3346
3347 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3348 {
3349         return kvm->arch.n_max_mmu_pages;
3350 }
3351
3352 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3353 {
3354         int r;
3355
3356         r = 0;
3357         switch (chip->chip_id) {
3358         case KVM_IRQCHIP_PIC_MASTER:
3359                 memcpy(&chip->chip.pic,
3360                         &pic_irqchip(kvm)->pics[0],
3361                         sizeof(struct kvm_pic_state));
3362                 break;
3363         case KVM_IRQCHIP_PIC_SLAVE:
3364                 memcpy(&chip->chip.pic,
3365                         &pic_irqchip(kvm)->pics[1],
3366                         sizeof(struct kvm_pic_state));
3367                 break;
3368         case KVM_IRQCHIP_IOAPIC:
3369                 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3370                 break;
3371         default:
3372                 r = -EINVAL;
3373                 break;
3374         }
3375         return r;
3376 }
3377
3378 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3379 {
3380         int r;
3381
3382         r = 0;
3383         switch (chip->chip_id) {
3384         case KVM_IRQCHIP_PIC_MASTER:
3385                 spin_lock(&pic_irqchip(kvm)->lock);
3386                 memcpy(&pic_irqchip(kvm)->pics[0],
3387                         &chip->chip.pic,
3388                         sizeof(struct kvm_pic_state));
3389                 spin_unlock(&pic_irqchip(kvm)->lock);
3390                 break;
3391         case KVM_IRQCHIP_PIC_SLAVE:
3392                 spin_lock(&pic_irqchip(kvm)->lock);
3393                 memcpy(&pic_irqchip(kvm)->pics[1],
3394                         &chip->chip.pic,
3395                         sizeof(struct kvm_pic_state));
3396                 spin_unlock(&pic_irqchip(kvm)->lock);
3397                 break;
3398         case KVM_IRQCHIP_IOAPIC:
3399                 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3400                 break;
3401         default:
3402                 r = -EINVAL;
3403                 break;
3404         }
3405         kvm_pic_update_irq(pic_irqchip(kvm));
3406         return r;
3407 }
3408
3409 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3410 {
3411         int r = 0;
3412
3413         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3414         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3415         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3416         return r;
3417 }
3418
3419 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3420 {
3421         int r = 0;
3422
3423         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3424         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3425         kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
3426         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3427         return r;
3428 }
3429
3430 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3431 {
3432         int r = 0;
3433
3434         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3435         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3436                 sizeof(ps->channels));
3437         ps->flags = kvm->arch.vpit->pit_state.flags;
3438         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3439         memset(&ps->reserved, 0, sizeof(ps->reserved));
3440         return r;
3441 }
3442
3443 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3444 {
3445         int r = 0, start = 0;
3446         u32 prev_legacy, cur_legacy;
3447         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3448         prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3449         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3450         if (!prev_legacy && cur_legacy)
3451                 start = 1;
3452         memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3453                sizeof(kvm->arch.vpit->pit_state.channels));
3454         kvm->arch.vpit->pit_state.flags = ps->flags;
3455         kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
3456         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3457         return r;
3458 }
3459
3460 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3461                                  struct kvm_reinject_control *control)
3462 {
3463         if (!kvm->arch.vpit)
3464                 return -ENXIO;
3465         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3466         kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
3467         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3468         return 0;
3469 }
3470
3471 /*
3472  * Get (and clear) the dirty memory log for a memory slot.
3473  */
3474 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
3475                                       struct kvm_dirty_log *log)
3476 {
3477         int r, i;
3478         struct kvm_memory_slot *memslot;
3479         unsigned long n;
3480         unsigned long is_dirty = 0;
3481
3482         mutex_lock(&kvm->slots_lock);
3483
3484         r = -EINVAL;
3485         if (log->slot >= KVM_MEMORY_SLOTS)
3486                 goto out;
3487
3488         memslot = &kvm->memslots->memslots[log->slot];
3489         r = -ENOENT;
3490         if (!memslot->dirty_bitmap)
3491                 goto out;
3492
3493         n = kvm_dirty_bitmap_bytes(memslot);
3494
3495         for (i = 0; !is_dirty && i < n/sizeof(long); i++)
3496                 is_dirty = memslot->dirty_bitmap[i];
3497
3498         /* If nothing is dirty, don't bother messing with page tables. */
3499         if (is_dirty) {
3500                 struct kvm_memslots *slots, *old_slots;
3501                 unsigned long *dirty_bitmap;
3502
3503                 dirty_bitmap = memslot->dirty_bitmap_head;
3504                 if (memslot->dirty_bitmap == dirty_bitmap)
3505                         dirty_bitmap += n / sizeof(long);
3506                 memset(dirty_bitmap, 0, n);
3507
3508                 r = -ENOMEM;
3509                 slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
3510                 if (!slots)
3511                         goto out;
3512                 memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
3513                 slots->memslots[log->slot].dirty_bitmap = dirty_bitmap;
3514                 slots->generation++;
3515
3516                 old_slots = kvm->memslots;
3517                 rcu_assign_pointer(kvm->memslots, slots);
3518                 synchronize_srcu_expedited(&kvm->srcu);
3519                 dirty_bitmap = old_slots->memslots[log->slot].dirty_bitmap;
3520                 kfree(old_slots);
3521
3522                 spin_lock(&kvm->mmu_lock);
3523                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
3524                 spin_unlock(&kvm->mmu_lock);
3525
3526                 r = -EFAULT;
3527                 if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
3528                         goto out;
3529         } else {
3530                 r = -EFAULT;
3531                 if (clear_user(log->dirty_bitmap, n))
3532                         goto out;
3533         }
3534
3535         r = 0;
3536 out:
3537         mutex_unlock(&kvm->slots_lock);
3538         return r;
3539 }
3540
3541 long kvm_arch_vm_ioctl(struct file *filp,
3542                        unsigned int ioctl, unsigned long arg)
3543 {
3544         struct kvm *kvm = filp->private_data;
3545         void __user *argp = (void __user *)arg;
3546         int r = -ENOTTY;
3547         /*
3548          * This union makes it completely explicit to gcc-3.x
3549          * that these two variables' stack usage should be
3550          * combined, not added together.
3551          */
3552         union {
3553                 struct kvm_pit_state ps;
3554                 struct kvm_pit_state2 ps2;
3555                 struct kvm_pit_config pit_config;
3556         } u;
3557
3558         switch (ioctl) {
3559         case KVM_SET_TSS_ADDR:
3560                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3561                 if (r < 0)
3562                         goto out;
3563                 break;
3564         case KVM_SET_IDENTITY_MAP_ADDR: {
3565                 u64 ident_addr;
3566
3567                 r = -EFAULT;
3568                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3569                         goto out;
3570                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3571                 if (r < 0)
3572                         goto out;
3573                 break;
3574         }
3575         case KVM_SET_NR_MMU_PAGES:
3576                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3577                 if (r)
3578                         goto out;
3579                 break;
3580         case KVM_GET_NR_MMU_PAGES:
3581                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3582                 break;
3583         case KVM_CREATE_IRQCHIP: {
3584                 struct kvm_pic *vpic;
3585
3586                 mutex_lock(&kvm->lock);
3587                 r = -EEXIST;
3588                 if (kvm->arch.vpic)
3589                         goto create_irqchip_unlock;
3590                 r = -EINVAL;
3591                 if (atomic_read(&kvm->online_vcpus))
3592                         goto create_irqchip_unlock;
3593                 r = -ENOMEM;
3594                 vpic = kvm_create_pic(kvm);
3595                 if (vpic) {
3596                         r = kvm_ioapic_init(kvm);
3597                         if (r) {
3598                                 mutex_lock(&kvm->slots_lock);
3599                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3600                                                           &vpic->dev_master);
3601                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3602                                                           &vpic->dev_slave);
3603                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3604                                                           &vpic->dev_eclr);
3605                                 mutex_unlock(&kvm->slots_lock);
3606                                 kfree(vpic);
3607                                 goto create_irqchip_unlock;
3608                         }
3609                 } else
3610                         goto create_irqchip_unlock;
3611                 smp_wmb();
3612                 kvm->arch.vpic = vpic;
3613                 smp_wmb();
3614                 r = kvm_setup_default_irq_routing(kvm);
3615                 if (r) {
3616                         mutex_lock(&kvm->slots_lock);
3617                         mutex_lock(&kvm->irq_lock);
3618                         kvm_ioapic_destroy(kvm);
3619                         kvm_destroy_pic(kvm);
3620                         mutex_unlock(&kvm->irq_lock);
3621                         mutex_unlock(&kvm->slots_lock);
3622                 }
3623         create_irqchip_unlock:
3624                 mutex_unlock(&kvm->lock);
3625                 break;
3626         }
3627         case KVM_CREATE_PIT:
3628                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3629                 goto create_pit;
3630         case KVM_CREATE_PIT2:
3631                 r = -EFAULT;
3632                 if (copy_from_user(&u.pit_config, argp,
3633                                    sizeof(struct kvm_pit_config)))
3634                         goto out;
3635         create_pit:
3636                 mutex_lock(&kvm->slots_lock);
3637                 r = -EEXIST;
3638                 if (kvm->arch.vpit)
3639                         goto create_pit_unlock;
3640                 r = -ENOMEM;
3641                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3642                 if (kvm->arch.vpit)
3643                         r = 0;
3644         create_pit_unlock:
3645                 mutex_unlock(&kvm->slots_lock);
3646                 break;
3647         case KVM_IRQ_LINE_STATUS:
3648         case KVM_IRQ_LINE: {
3649                 struct kvm_irq_level irq_event;
3650
3651                 r = -EFAULT;
3652                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
3653                         goto out;
3654                 r = -ENXIO;
3655                 if (irqchip_in_kernel(kvm)) {
3656                         __s32 status;
3657                         status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3658                                         irq_event.irq, irq_event.level);
3659                         if (ioctl == KVM_IRQ_LINE_STATUS) {
3660                                 r = -EFAULT;
3661                                 irq_event.status = status;
3662                                 if (copy_to_user(argp, &irq_event,
3663                                                         sizeof irq_event))
3664                                         goto out;
3665                         }
3666                         r = 0;
3667                 }
3668                 break;
3669         }
3670         case KVM_GET_IRQCHIP: {
3671                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3672                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3673
3674                 r = -ENOMEM;
3675                 if (!chip)
3676                         goto out;
3677                 r = -EFAULT;
3678                 if (copy_from_user(chip, argp, sizeof *chip))
3679                         goto get_irqchip_out;
3680                 r = -ENXIO;
3681                 if (!irqchip_in_kernel(kvm))
3682                         goto get_irqchip_out;
3683                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3684                 if (r)
3685                         goto get_irqchip_out;
3686                 r = -EFAULT;
3687                 if (copy_to_user(argp, chip, sizeof *chip))
3688                         goto get_irqchip_out;
3689                 r = 0;
3690         get_irqchip_out:
3691                 kfree(chip);
3692                 if (r)
3693                         goto out;
3694                 break;
3695         }
3696         case KVM_SET_IRQCHIP: {
3697                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3698                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
3699
3700                 r = -ENOMEM;
3701                 if (!chip)
3702                         goto out;
3703                 r = -EFAULT;
3704                 if (copy_from_user(chip, argp, sizeof *chip))
3705                         goto set_irqchip_out;
3706                 r = -ENXIO;
3707                 if (!irqchip_in_kernel(kvm))
3708                         goto set_irqchip_out;
3709                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3710                 if (r)
3711                         goto set_irqchip_out;
3712                 r = 0;
3713         set_irqchip_out:
3714                 kfree(chip);
3715                 if (r)
3716                         goto out;
3717                 break;
3718         }
3719         case KVM_GET_PIT: {
3720                 r = -EFAULT;
3721                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3722                         goto out;
3723                 r = -ENXIO;
3724                 if (!kvm->arch.vpit)
3725                         goto out;
3726                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
3727                 if (r)
3728                         goto out;
3729                 r = -EFAULT;
3730                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
3731                         goto out;
3732                 r = 0;
3733                 break;
3734         }
3735         case KVM_SET_PIT: {
3736                 r = -EFAULT;
3737                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
3738                         goto out;
3739                 r = -ENXIO;
3740                 if (!kvm->arch.vpit)
3741                         goto out;
3742                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
3743                 if (r)
3744                         goto out;
3745                 r = 0;
3746                 break;
3747         }
3748         case KVM_GET_PIT2: {
3749                 r = -ENXIO;
3750                 if (!kvm->arch.vpit)
3751                         goto out;
3752                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
3753                 if (r)
3754                         goto out;
3755                 r = -EFAULT;
3756                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
3757                         goto out;
3758                 r = 0;
3759                 break;
3760         }
3761         case KVM_SET_PIT2: {
3762                 r = -EFAULT;
3763                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
3764                         goto out;
3765                 r = -ENXIO;
3766                 if (!kvm->arch.vpit)
3767                         goto out;
3768                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
3769                 if (r)
3770                         goto out;
3771                 r = 0;
3772                 break;
3773         }
3774         case KVM_REINJECT_CONTROL: {
3775                 struct kvm_reinject_control control;
3776                 r =  -EFAULT;
3777                 if (copy_from_user(&control, argp, sizeof(control)))
3778                         goto out;
3779                 r = kvm_vm_ioctl_reinject(kvm, &control);
3780                 if (r)
3781                         goto out;
3782                 r = 0;
3783                 break;
3784         }
3785         case KVM_XEN_HVM_CONFIG: {
3786                 r = -EFAULT;
3787                 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
3788                                    sizeof(struct kvm_xen_hvm_config)))
3789                         goto out;
3790                 r = -EINVAL;
3791                 if (kvm->arch.xen_hvm_config.flags)
3792                         goto out;
3793                 r = 0;
3794                 break;
3795         }
3796         case KVM_SET_CLOCK: {
3797                 struct kvm_clock_data user_ns;
3798                 u64 now_ns;
3799                 s64 delta;
3800
3801                 r = -EFAULT;
3802                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
3803                         goto out;
3804
3805                 r = -EINVAL;
3806                 if (user_ns.flags)
3807                         goto out;
3808
3809                 r = 0;
3810                 local_irq_disable();
3811                 now_ns = get_kernel_ns();
3812                 delta = user_ns.clock - now_ns;
3813                 local_irq_enable();
3814                 kvm->arch.kvmclock_offset = delta;
3815                 break;
3816         }
3817         case KVM_GET_CLOCK: {
3818                 struct kvm_clock_data user_ns;
3819                 u64 now_ns;
3820
3821                 local_irq_disable();
3822                 now_ns = get_kernel_ns();
3823                 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
3824                 local_irq_enable();
3825                 user_ns.flags = 0;
3826                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
3827
3828                 r = -EFAULT;
3829                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
3830                         goto out;
3831                 r = 0;
3832                 break;
3833         }
3834
3835         default:
3836                 ;
3837         }
3838 out:
3839         return r;
3840 }
3841
3842 static void kvm_init_msr_list(void)
3843 {
3844         u32 dummy[2];
3845         unsigned i, j;
3846
3847         /* skip the first msrs in the list. KVM-specific */
3848         for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
3849                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
3850                         continue;
3851                 if (j < i)
3852                         msrs_to_save[j] = msrs_to_save[i];
3853                 j++;
3854         }
3855         num_msrs_to_save = j;
3856 }
3857
3858 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
3859                            const void *v)
3860 {
3861         int handled = 0;
3862         int n;
3863
3864         do {
3865                 n = min(len, 8);
3866                 if (!(vcpu->arch.apic &&
3867                       !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
3868                     && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3869                         break;
3870                 handled += n;
3871                 addr += n;
3872                 len -= n;
3873                 v += n;
3874         } while (len);
3875
3876         return handled;
3877 }
3878
3879 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
3880 {
3881         int handled = 0;
3882         int n;
3883
3884         do {
3885                 n = min(len, 8);
3886                 if (!(vcpu->arch.apic &&
3887                       !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
3888                     && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
3889                         break;
3890                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
3891                 handled += n;
3892                 addr += n;
3893                 len -= n;
3894                 v += n;
3895         } while (len);
3896
3897         return handled;
3898 }
3899
3900 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3901                         struct kvm_segment *var, int seg)
3902 {
3903         kvm_x86_ops->set_segment(vcpu, var, seg);
3904 }
3905
3906 void kvm_get_segment(struct kvm_vcpu *vcpu,
3907                      struct kvm_segment *var, int seg)
3908 {
3909         kvm_x86_ops->get_segment(vcpu, var, seg);
3910 }
3911
3912 static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3913 {
3914         return gpa;
3915 }
3916
3917 static gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
3918 {
3919         gpa_t t_gpa;
3920         struct x86_exception exception;
3921
3922         BUG_ON(!mmu_is_nested(vcpu));
3923
3924         /* NPT walks are always user-walks */
3925         access |= PFERR_USER_MASK;
3926         t_gpa  = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
3927
3928         return t_gpa;
3929 }
3930
3931 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
3932                               struct x86_exception *exception)
3933 {
3934         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3935         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3936 }
3937
3938  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
3939                                 struct x86_exception *exception)
3940 {
3941         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3942         access |= PFERR_FETCH_MASK;
3943         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3944 }
3945
3946 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
3947                                struct x86_exception *exception)
3948 {
3949         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3950         access |= PFERR_WRITE_MASK;
3951         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
3952 }
3953
3954 /* uses this to access any guest's mapped memory without checking CPL */
3955 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
3956                                 struct x86_exception *exception)
3957 {
3958         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
3959 }
3960
3961 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
3962                                       struct kvm_vcpu *vcpu, u32 access,
3963                                       struct x86_exception *exception)
3964 {
3965         void *data = val;
3966         int r = X86EMUL_CONTINUE;
3967
3968         while (bytes) {
3969                 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
3970                                                             exception);
3971                 unsigned offset = addr & (PAGE_SIZE-1);
3972                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
3973                 int ret;
3974
3975                 if (gpa == UNMAPPED_GVA)
3976                         return X86EMUL_PROPAGATE_FAULT;
3977                 ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
3978                 if (ret < 0) {
3979                         r = X86EMUL_IO_NEEDED;
3980                         goto out;
3981                 }
3982
3983                 bytes -= toread;
3984                 data += toread;
3985                 addr += toread;
3986         }
3987 out:
3988         return r;
3989 }
3990
3991 /* used for instruction fetching */
3992 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
3993                                 gva_t addr, void *val, unsigned int bytes,
3994                                 struct x86_exception *exception)
3995 {
3996         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
3997         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
3998
3999         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
4000                                           access | PFERR_FETCH_MASK,
4001                                           exception);
4002 }
4003
4004 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4005                                gva_t addr, void *val, unsigned int bytes,
4006                                struct x86_exception *exception)
4007 {
4008         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4009         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4010
4011         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4012                                           exception);
4013 }
4014 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4015
4016 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4017                                       gva_t addr, void *val, unsigned int bytes,
4018                                       struct x86_exception *exception)
4019 {
4020         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4021         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4022 }
4023
4024 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4025                                        gva_t addr, void *val,
4026                                        unsigned int bytes,
4027                                        struct x86_exception *exception)
4028 {
4029         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4030         void *data = val;
4031         int r = X86EMUL_CONTINUE;
4032
4033         while (bytes) {
4034                 gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4035                                                              PFERR_WRITE_MASK,
4036                                                              exception);
4037                 unsigned offset = addr & (PAGE_SIZE-1);
4038                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4039                 int ret;
4040
4041                 if (gpa == UNMAPPED_GVA)
4042                         return X86EMUL_PROPAGATE_FAULT;
4043                 ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
4044                 if (ret < 0) {
4045                         r = X86EMUL_IO_NEEDED;
4046                         goto out;
4047                 }
4048
4049                 bytes -= towrite;
4050                 data += towrite;
4051                 addr += towrite;
4052         }
4053 out:
4054         return r;
4055 }
4056 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4057
4058 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4059                                 gpa_t *gpa, struct x86_exception *exception,
4060                                 bool write)
4061 {
4062         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4063
4064         if (vcpu_match_mmio_gva(vcpu, gva) &&
4065                   check_write_user_access(vcpu, write, access,
4066                   vcpu->arch.access)) {
4067                 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4068                                         (gva & (PAGE_SIZE - 1));
4069                 trace_vcpu_match_mmio(gva, *gpa, write, false);
4070                 return 1;
4071         }
4072
4073         if (write)
4074                 access |= PFERR_WRITE_MASK;
4075
4076         *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4077
4078         if (*gpa == UNMAPPED_GVA)
4079                 return -1;
4080
4081         /* For APIC access vmexit */
4082         if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4083                 return 1;
4084
4085         if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4086                 trace_vcpu_match_mmio(gva, *gpa, write, true);
4087                 return 1;
4088         }
4089
4090         return 0;
4091 }
4092
4093 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4094                         const void *val, int bytes)
4095 {
4096         int ret;
4097
4098         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
4099         if (ret < 0)
4100                 return 0;
4101         kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
4102         return 1;
4103 }
4104
4105 struct read_write_emulator_ops {
4106         int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4107                                   int bytes);
4108         int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4109                                   void *val, int bytes);
4110         int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4111                                int bytes, void *val);
4112         int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4113                                     void *val, int bytes);
4114         bool write;
4115 };
4116
4117 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4118 {
4119         if (vcpu->mmio_read_completed) {
4120                 memcpy(val, vcpu->mmio_data, bytes);
4121                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4122                                vcpu->mmio_phys_addr, *(u64 *)val);
4123                 vcpu->mmio_read_completed = 0;
4124                 return 1;
4125         }
4126
4127         return 0;
4128 }
4129
4130 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4131                         void *val, int bytes)
4132 {
4133         return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
4134 }
4135
4136 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4137                          void *val, int bytes)
4138 {
4139         return emulator_write_phys(vcpu, gpa, val, bytes);
4140 }
4141
4142 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4143 {
4144         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
4145         return vcpu_mmio_write(vcpu, gpa, bytes, val);
4146 }
4147
4148 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4149                           void *val, int bytes)
4150 {
4151         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
4152         return X86EMUL_IO_NEEDED;
4153 }
4154
4155 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4156                            void *val, int bytes)
4157 {
4158         memcpy(vcpu->mmio_data, val, bytes);
4159         memcpy(vcpu->run->mmio.data, vcpu->mmio_data, 8);
4160         return X86EMUL_CONTINUE;
4161 }
4162
4163 static struct read_write_emulator_ops read_emultor = {
4164         .read_write_prepare = read_prepare,
4165         .read_write_emulate = read_emulate,
4166         .read_write_mmio = vcpu_mmio_read,
4167         .read_write_exit_mmio = read_exit_mmio,
4168 };
4169
4170 static struct read_write_emulator_ops write_emultor = {
4171         .read_write_emulate = write_emulate,
4172         .read_write_mmio = write_mmio,
4173         .read_write_exit_mmio = write_exit_mmio,
4174         .write = true,
4175 };
4176
4177 static int emulator_read_write_onepage(unsigned long addr, void *val,
4178                                        unsigned int bytes,
4179                                        struct x86_exception *exception,
4180                                        struct kvm_vcpu *vcpu,
4181                                        struct read_write_emulator_ops *ops)
4182 {
4183         gpa_t gpa;
4184         int handled, ret;
4185         bool write = ops->write;
4186
4187         if (ops->read_write_prepare &&
4188                   ops->read_write_prepare(vcpu, val, bytes))
4189                 return X86EMUL_CONTINUE;
4190
4191         ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4192
4193         if (ret < 0)
4194                 return X86EMUL_PROPAGATE_FAULT;
4195
4196         /* For APIC access vmexit */
4197         if (ret)
4198                 goto mmio;
4199
4200         if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4201                 return X86EMUL_CONTINUE;
4202
4203 mmio:
4204         /*
4205          * Is this MMIO handled locally?
4206          */
4207         handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4208         if (handled == bytes)
4209                 return X86EMUL_CONTINUE;
4210
4211         gpa += handled;
4212         bytes -= handled;
4213         val += handled;
4214
4215         vcpu->mmio_needed = 1;
4216         vcpu->run->exit_reason = KVM_EXIT_MMIO;
4217         vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
4218         vcpu->mmio_size = bytes;
4219         vcpu->run->mmio.len = min(vcpu->mmio_size, 8);
4220         vcpu->run->mmio.is_write = vcpu->mmio_is_write = write;
4221         vcpu->mmio_index = 0;
4222
4223         return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4224 }
4225
4226 int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
4227                         void *val, unsigned int bytes,
4228                         struct x86_exception *exception,
4229                         struct read_write_emulator_ops *ops)
4230 {
4231         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4232
4233         /* Crossing a page boundary? */
4234         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4235                 int rc, now;
4236
4237                 now = -addr & ~PAGE_MASK;
4238                 rc = emulator_read_write_onepage(addr, val, now, exception,
4239                                                  vcpu, ops);
4240
4241                 if (rc != X86EMUL_CONTINUE)
4242                         return rc;
4243                 addr += now;
4244                 val += now;
4245                 bytes -= now;
4246         }
4247
4248         return emulator_read_write_onepage(addr, val, bytes, exception,
4249                                            vcpu, ops);
4250 }
4251
4252 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4253                                   unsigned long addr,
4254                                   void *val,
4255                                   unsigned int bytes,
4256                                   struct x86_exception *exception)
4257 {
4258         return emulator_read_write(ctxt, addr, val, bytes,
4259                                    exception, &read_emultor);
4260 }
4261
4262 int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4263                             unsigned long addr,
4264                             const void *val,
4265                             unsigned int bytes,
4266                             struct x86_exception *exception)
4267 {
4268         return emulator_read_write(ctxt, addr, (void *)val, bytes,
4269                                    exception, &write_emultor);
4270 }
4271
4272 #define CMPXCHG_TYPE(t, ptr, old, new) \
4273         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4274
4275 #ifdef CONFIG_X86_64
4276 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4277 #else
4278 #  define CMPXCHG64(ptr, old, new) \
4279         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4280 #endif
4281
4282 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4283                                      unsigned long addr,
4284                                      const void *old,
4285                                      const void *new,
4286                                      unsigned int bytes,
4287                                      struct x86_exception *exception)
4288 {
4289         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4290         gpa_t gpa;
4291         struct page *page;
4292         char *kaddr;
4293         bool exchanged;
4294
4295         /* guests cmpxchg8b have to be emulated atomically */
4296         if (bytes > 8 || (bytes & (bytes - 1)))
4297                 goto emul_write;
4298
4299         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4300
4301         if (gpa == UNMAPPED_GVA ||
4302             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4303                 goto emul_write;
4304
4305         if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4306                 goto emul_write;
4307
4308         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4309         if (is_error_page(page)) {
4310                 kvm_release_page_clean(page);
4311                 goto emul_write;
4312         }
4313
4314         kaddr = kmap_atomic(page, KM_USER0);
4315         kaddr += offset_in_page(gpa);
4316         switch (bytes) {
4317         case 1:
4318                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4319                 break;
4320         case 2:
4321                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4322                 break;
4323         case 4:
4324                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4325                 break;
4326         case 8:
4327                 exchanged = CMPXCHG64(kaddr, old, new);
4328                 break;
4329         default:
4330                 BUG();
4331         }
4332         kunmap_atomic(kaddr, KM_USER0);
4333         kvm_release_page_dirty(page);
4334
4335         if (!exchanged)
4336                 return X86EMUL_CMPXCHG_FAILED;
4337
4338         kvm_mmu_pte_write(vcpu, gpa, new, bytes, 1);
4339
4340         return X86EMUL_CONTINUE;
4341
4342 emul_write:
4343         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4344
4345         return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4346 }
4347
4348 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4349 {
4350         /* TODO: String I/O for in kernel device */
4351         int r;
4352
4353         if (vcpu->arch.pio.in)
4354                 r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
4355                                     vcpu->arch.pio.size, pd);
4356         else
4357                 r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
4358                                      vcpu->arch.pio.port, vcpu->arch.pio.size,
4359                                      pd);
4360         return r;
4361 }
4362
4363
4364 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4365                                     int size, unsigned short port, void *val,
4366                                     unsigned int count)
4367 {
4368         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4369
4370         if (vcpu->arch.pio.count)
4371                 goto data_avail;
4372
4373         trace_kvm_pio(0, port, size, count);
4374
4375         vcpu->arch.pio.port = port;
4376         vcpu->arch.pio.in = 1;
4377         vcpu->arch.pio.count  = count;
4378         vcpu->arch.pio.size = size;
4379
4380         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4381         data_avail:
4382                 memcpy(val, vcpu->arch.pio_data, size * count);
4383                 vcpu->arch.pio.count = 0;
4384                 return 1;
4385         }
4386
4387         vcpu->run->exit_reason = KVM_EXIT_IO;
4388         vcpu->run->io.direction = KVM_EXIT_IO_IN;
4389         vcpu->run->io.size = size;
4390         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4391         vcpu->run->io.count = count;
4392         vcpu->run->io.port = port;
4393
4394         return 0;
4395 }
4396
4397 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4398                                      int size, unsigned short port,
4399                                      const void *val, unsigned int count)
4400 {
4401         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4402
4403         trace_kvm_pio(1, port, size, count);
4404
4405         vcpu->arch.pio.port = port;
4406         vcpu->arch.pio.in = 0;
4407         vcpu->arch.pio.count = count;
4408         vcpu->arch.pio.size = size;
4409
4410         memcpy(vcpu->arch.pio_data, val, size * count);
4411
4412         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4413                 vcpu->arch.pio.count = 0;
4414                 return 1;
4415         }
4416
4417         vcpu->run->exit_reason = KVM_EXIT_IO;
4418         vcpu->run->io.direction = KVM_EXIT_IO_OUT;
4419         vcpu->run->io.size = size;
4420         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4421         vcpu->run->io.count = count;
4422         vcpu->run->io.port = port;
4423
4424         return 0;
4425 }
4426
4427 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4428 {
4429         return kvm_x86_ops->get_segment_base(vcpu, seg);
4430 }
4431
4432 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4433 {
4434         kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4435 }
4436
4437 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4438 {
4439         if (!need_emulate_wbinvd(vcpu))
4440                 return X86EMUL_CONTINUE;
4441
4442         if (kvm_x86_ops->has_wbinvd_exit()) {
4443                 int cpu = get_cpu();
4444
4445                 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4446                 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4447                                 wbinvd_ipi, NULL, 1);
4448                 put_cpu();
4449                 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4450         } else
4451                 wbinvd();
4452         return X86EMUL_CONTINUE;
4453 }
4454 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4455
4456 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4457 {
4458         kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
4459 }
4460
4461 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
4462 {
4463         return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4464 }
4465
4466 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
4467 {
4468
4469         return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4470 }
4471
4472 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4473 {
4474         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4475 }
4476
4477 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4478 {
4479         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4480         unsigned long value;
4481
4482         switch (cr) {
4483         case 0:
4484                 value = kvm_read_cr0(vcpu);
4485                 break;
4486         case 2:
4487                 value = vcpu->arch.cr2;
4488                 break;
4489         case 3:
4490                 value = kvm_read_cr3(vcpu);
4491                 break;
4492         case 4:
4493                 value = kvm_read_cr4(vcpu);
4494                 break;
4495         case 8:
4496                 value = kvm_get_cr8(vcpu);
4497                 break;
4498         default:
4499                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4500                 return 0;
4501         }
4502
4503         return value;
4504 }
4505
4506 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4507 {
4508         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4509         int res = 0;
4510
4511         switch (cr) {
4512         case 0:
4513                 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4514                 break;
4515         case 2:
4516                 vcpu->arch.cr2 = val;
4517                 break;
4518         case 3:
4519                 res = kvm_set_cr3(vcpu, val);
4520                 break;
4521         case 4:
4522                 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4523                 break;
4524         case 8:
4525                 res = kvm_set_cr8(vcpu, val);
4526                 break;
4527         default:
4528                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
4529                 res = -1;
4530         }
4531
4532         return res;
4533 }
4534
4535 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4536 {
4537         return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4538 }
4539
4540 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4541 {
4542         kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4543 }
4544
4545 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4546 {
4547         kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4548 }
4549
4550 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4551 {
4552         kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4553 }
4554
4555 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4556 {
4557         kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4558 }
4559
4560 static unsigned long emulator_get_cached_segment_base(
4561         struct x86_emulate_ctxt *ctxt, int seg)
4562 {
4563         return get_segment_base(emul_to_vcpu(ctxt), seg);
4564 }
4565
4566 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4567                                  struct desc_struct *desc, u32 *base3,
4568                                  int seg)
4569 {
4570         struct kvm_segment var;
4571
4572         kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4573         *selector = var.selector;
4574
4575         if (var.unusable)
4576                 return false;
4577
4578         if (var.g)
4579                 var.limit >>= 12;
4580         set_desc_limit(desc, var.limit);
4581         set_desc_base(desc, (unsigned long)var.base);
4582 #ifdef CONFIG_X86_64
4583         if (base3)
4584                 *base3 = var.base >> 32;
4585 #endif
4586         desc->type = var.type;
4587         desc->s = var.s;
4588         desc->dpl = var.dpl;
4589         desc->p = var.present;
4590         desc->avl = var.avl;
4591         desc->l = var.l;
4592         desc->d = var.db;
4593         desc->g = var.g;
4594
4595         return true;
4596 }
4597
4598 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
4599                                  struct desc_struct *desc, u32 base3,
4600                                  int seg)
4601 {
4602         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4603         struct kvm_segment var;
4604
4605         var.selector = selector;
4606         var.base = get_desc_base(desc);
4607 #ifdef CONFIG_X86_64
4608         var.base |= ((u64)base3) << 32;
4609 #endif
4610         var.limit = get_desc_limit(desc);
4611         if (desc->g)
4612                 var.limit = (var.limit << 12) | 0xfff;
4613         var.type = desc->type;
4614         var.present = desc->p;
4615         var.dpl = desc->dpl;
4616         var.db = desc->d;
4617         var.s = desc->s;
4618         var.l = desc->l;
4619         var.g = desc->g;
4620         var.avl = desc->avl;
4621         var.present = desc->p;
4622         var.unusable = !var.present;
4623         var.padding = 0;
4624
4625         kvm_set_segment(vcpu, &var, seg);
4626         return;
4627 }
4628
4629 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
4630                             u32 msr_index, u64 *pdata)
4631 {
4632         return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
4633 }
4634
4635 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
4636                             u32 msr_index, u64 data)
4637 {
4638         return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
4639 }
4640
4641 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
4642 {
4643         emul_to_vcpu(ctxt)->arch.halt_request = 1;
4644 }
4645
4646 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
4647 {
4648         preempt_disable();
4649         kvm_load_guest_fpu(emul_to_vcpu(ctxt));
4650         /*
4651          * CR0.TS may reference the host fpu state, not the guest fpu state,
4652          * so it may be clear at this point.
4653          */
4654         clts();
4655 }
4656
4657 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
4658 {
4659         preempt_enable();
4660 }
4661
4662 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
4663                               struct x86_instruction_info *info,
4664                               enum x86_intercept_stage stage)
4665 {
4666         return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
4667 }
4668
4669 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
4670                                u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
4671 {
4672         struct kvm_cpuid_entry2 *cpuid = NULL;
4673
4674         if (eax && ecx)
4675                 cpuid = kvm_find_cpuid_entry(emul_to_vcpu(ctxt),
4676                                             *eax, *ecx);
4677
4678         if (cpuid) {
4679                 *eax = cpuid->eax;
4680                 *ecx = cpuid->ecx;
4681                 if (ebx)
4682                         *ebx = cpuid->ebx;
4683                 if (edx)
4684                         *edx = cpuid->edx;
4685                 return true;
4686         }
4687
4688         return false;
4689 }
4690
4691 static struct x86_emulate_ops emulate_ops = {
4692         .read_std            = kvm_read_guest_virt_system,
4693         .write_std           = kvm_write_guest_virt_system,
4694         .fetch               = kvm_fetch_guest_virt,
4695         .read_emulated       = emulator_read_emulated,
4696         .write_emulated      = emulator_write_emulated,
4697         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
4698         .invlpg              = emulator_invlpg,
4699         .pio_in_emulated     = emulator_pio_in_emulated,
4700         .pio_out_emulated    = emulator_pio_out_emulated,
4701         .get_segment         = emulator_get_segment,
4702         .set_segment         = emulator_set_segment,
4703         .get_cached_segment_base = emulator_get_cached_segment_base,
4704         .get_gdt             = emulator_get_gdt,
4705         .get_idt             = emulator_get_idt,
4706         .set_gdt             = emulator_set_gdt,
4707         .set_idt             = emulator_set_idt,
4708         .get_cr              = emulator_get_cr,
4709         .set_cr              = emulator_set_cr,
4710         .cpl                 = emulator_get_cpl,
4711         .get_dr              = emulator_get_dr,
4712         .set_dr              = emulator_set_dr,
4713         .set_msr             = emulator_set_msr,
4714         .get_msr             = emulator_get_msr,
4715         .halt                = emulator_halt,
4716         .wbinvd              = emulator_wbinvd,
4717         .fix_hypercall       = emulator_fix_hypercall,
4718         .get_fpu             = emulator_get_fpu,
4719         .put_fpu             = emulator_put_fpu,
4720         .intercept           = emulator_intercept,
4721         .get_cpuid           = emulator_get_cpuid,
4722 };
4723
4724 static void cache_all_regs(struct kvm_vcpu *vcpu)
4725 {
4726         kvm_register_read(vcpu, VCPU_REGS_RAX);
4727         kvm_register_read(vcpu, VCPU_REGS_RSP);
4728         kvm_register_read(vcpu, VCPU_REGS_RIP);
4729         vcpu->arch.regs_dirty = ~0;
4730 }
4731
4732 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
4733 {
4734         u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
4735         /*
4736          * an sti; sti; sequence only disable interrupts for the first
4737          * instruction. So, if the last instruction, be it emulated or
4738          * not, left the system with the INT_STI flag enabled, it
4739          * means that the last instruction is an sti. We should not
4740          * leave the flag on in this case. The same goes for mov ss
4741          */
4742         if (!(int_shadow & mask))
4743                 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
4744 }
4745
4746 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
4747 {
4748         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4749         if (ctxt->exception.vector == PF_VECTOR)
4750                 kvm_propagate_fault(vcpu, &ctxt->exception);
4751         else if (ctxt->exception.error_code_valid)
4752                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
4753                                       ctxt->exception.error_code);
4754         else
4755                 kvm_queue_exception(vcpu, ctxt->exception.vector);
4756 }
4757
4758 static void init_decode_cache(struct x86_emulate_ctxt *ctxt,
4759                               const unsigned long *regs)
4760 {
4761         memset(&ctxt->twobyte, 0,
4762                (void *)&ctxt->regs - (void *)&ctxt->twobyte);
4763         memcpy(ctxt->regs, regs, sizeof(ctxt->regs));
4764
4765         ctxt->fetch.start = 0;
4766         ctxt->fetch.end = 0;
4767         ctxt->io_read.pos = 0;
4768         ctxt->io_read.end = 0;
4769         ctxt->mem_read.pos = 0;
4770         ctxt->mem_read.end = 0;
4771 }
4772
4773 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
4774 {
4775         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4776         int cs_db, cs_l;
4777
4778         /*
4779          * TODO: fix emulate.c to use guest_read/write_register
4780          * instead of direct ->regs accesses, can save hundred cycles
4781          * on Intel for instructions that don't read/change RSP, for
4782          * for example.
4783          */
4784         cache_all_regs(vcpu);
4785
4786         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
4787
4788         ctxt->eflags = kvm_get_rflags(vcpu);
4789         ctxt->eip = kvm_rip_read(vcpu);
4790         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
4791                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
4792                      cs_l                               ? X86EMUL_MODE_PROT64 :
4793                      cs_db                              ? X86EMUL_MODE_PROT32 :
4794                                                           X86EMUL_MODE_PROT16;
4795         ctxt->guest_mode = is_guest_mode(vcpu);
4796
4797         init_decode_cache(ctxt, vcpu->arch.regs);
4798         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4799 }
4800
4801 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
4802 {
4803         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4804         int ret;
4805
4806         init_emulate_ctxt(vcpu);
4807
4808         ctxt->op_bytes = 2;
4809         ctxt->ad_bytes = 2;
4810         ctxt->_eip = ctxt->eip + inc_eip;
4811         ret = emulate_int_real(ctxt, irq);
4812
4813         if (ret != X86EMUL_CONTINUE)
4814                 return EMULATE_FAIL;
4815
4816         ctxt->eip = ctxt->_eip;
4817         memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4818         kvm_rip_write(vcpu, ctxt->eip);
4819         kvm_set_rflags(vcpu, ctxt->eflags);
4820
4821         if (irq == NMI_VECTOR)
4822                 vcpu->arch.nmi_pending = 0;
4823         else
4824                 vcpu->arch.interrupt.pending = false;
4825
4826         return EMULATE_DONE;
4827 }
4828 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
4829
4830 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
4831 {
4832         int r = EMULATE_DONE;
4833
4834         ++vcpu->stat.insn_emulation_fail;
4835         trace_kvm_emulate_insn_failed(vcpu);
4836         if (!is_guest_mode(vcpu)) {
4837                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4838                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4839                 vcpu->run->internal.ndata = 0;
4840                 r = EMULATE_FAIL;
4841         }
4842         kvm_queue_exception(vcpu, UD_VECTOR);
4843
4844         return r;
4845 }
4846
4847 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
4848 {
4849         gpa_t gpa;
4850
4851         if (tdp_enabled)
4852                 return false;
4853
4854         /*
4855          * if emulation was due to access to shadowed page table
4856          * and it failed try to unshadow page and re-entetr the
4857          * guest to let CPU execute the instruction.
4858          */
4859         if (kvm_mmu_unprotect_page_virt(vcpu, gva))
4860                 return true;
4861
4862         gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
4863
4864         if (gpa == UNMAPPED_GVA)
4865                 return true; /* let cpu generate fault */
4866
4867         if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
4868                 return true;
4869
4870         return false;
4871 }
4872
4873 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
4874                             unsigned long cr2,
4875                             int emulation_type,
4876                             void *insn,
4877                             int insn_len)
4878 {
4879         int r;
4880         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4881         bool writeback = true;
4882
4883         kvm_clear_exception_queue(vcpu);
4884
4885         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
4886                 init_emulate_ctxt(vcpu);
4887                 ctxt->interruptibility = 0;
4888                 ctxt->have_exception = false;
4889                 ctxt->perm_ok = false;
4890
4891                 ctxt->only_vendor_specific_insn
4892                         = emulation_type & EMULTYPE_TRAP_UD;
4893
4894                 r = x86_decode_insn(ctxt, insn, insn_len);
4895
4896                 trace_kvm_emulate_insn_start(vcpu);
4897                 ++vcpu->stat.insn_emulation;
4898                 if (r != EMULATION_OK)  {
4899                         if (emulation_type & EMULTYPE_TRAP_UD)
4900                                 return EMULATE_FAIL;
4901                         if (reexecute_instruction(vcpu, cr2))
4902                                 return EMULATE_DONE;
4903                         if (emulation_type & EMULTYPE_SKIP)
4904                                 return EMULATE_FAIL;
4905                         return handle_emulation_failure(vcpu);
4906                 }
4907         }
4908
4909         if (emulation_type & EMULTYPE_SKIP) {
4910                 kvm_rip_write(vcpu, ctxt->_eip);
4911                 return EMULATE_DONE;
4912         }
4913
4914         /* this is needed for vmware backdoor interface to work since it
4915            changes registers values  during IO operation */
4916         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
4917                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
4918                 memcpy(ctxt->regs, vcpu->arch.regs, sizeof ctxt->regs);
4919         }
4920
4921 restart:
4922         r = x86_emulate_insn(ctxt);
4923
4924         if (r == EMULATION_INTERCEPTED)
4925                 return EMULATE_DONE;
4926
4927         if (r == EMULATION_FAILED) {
4928                 if (reexecute_instruction(vcpu, cr2))
4929                         return EMULATE_DONE;
4930
4931                 return handle_emulation_failure(vcpu);
4932         }
4933
4934         if (ctxt->have_exception) {
4935                 inject_emulated_exception(vcpu);
4936                 r = EMULATE_DONE;
4937         } else if (vcpu->arch.pio.count) {
4938                 if (!vcpu->arch.pio.in)
4939                         vcpu->arch.pio.count = 0;
4940                 else
4941                         writeback = false;
4942                 r = EMULATE_DO_MMIO;
4943         } else if (vcpu->mmio_needed) {
4944                 if (!vcpu->mmio_is_write)
4945                         writeback = false;
4946                 r = EMULATE_DO_MMIO;
4947         } else if (r == EMULATION_RESTART)
4948                 goto restart;
4949         else
4950                 r = EMULATE_DONE;
4951
4952         if (writeback) {
4953                 toggle_interruptibility(vcpu, ctxt->interruptibility);
4954                 kvm_set_rflags(vcpu, ctxt->eflags);
4955                 kvm_make_request(KVM_REQ_EVENT, vcpu);
4956                 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
4957                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
4958                 kvm_rip_write(vcpu, ctxt->eip);
4959         } else
4960                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
4961
4962         return r;
4963 }
4964 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
4965
4966 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
4967 {
4968         unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
4969         int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
4970                                             size, port, &val, 1);
4971         /* do not return to emulator after return from userspace */
4972         vcpu->arch.pio.count = 0;
4973         return ret;
4974 }
4975 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
4976
4977 static void tsc_bad(void *info)
4978 {
4979         __this_cpu_write(cpu_tsc_khz, 0);
4980 }
4981
4982 static void tsc_khz_changed(void *data)
4983 {
4984         struct cpufreq_freqs *freq = data;
4985         unsigned long khz = 0;
4986
4987         if (data)
4988                 khz = freq->new;
4989         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
4990                 khz = cpufreq_quick_get(raw_smp_processor_id());
4991         if (!khz)
4992                 khz = tsc_khz;
4993         __this_cpu_write(cpu_tsc_khz, khz);
4994 }
4995
4996 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
4997                                      void *data)
4998 {
4999         struct cpufreq_freqs *freq = data;
5000         struct kvm *kvm;
5001         struct kvm_vcpu *vcpu;
5002         int i, send_ipi = 0;
5003
5004         /*
5005          * We allow guests to temporarily run on slowing clocks,
5006          * provided we notify them after, or to run on accelerating
5007          * clocks, provided we notify them before.  Thus time never
5008          * goes backwards.
5009          *
5010          * However, we have a problem.  We can't atomically update
5011          * the frequency of a given CPU from this function; it is
5012          * merely a notifier, which can be called from any CPU.
5013          * Changing the TSC frequency at arbitrary points in time
5014          * requires a recomputation of local variables related to
5015          * the TSC for each VCPU.  We must flag these local variables
5016          * to be updated and be sure the update takes place with the
5017          * new frequency before any guests proceed.
5018          *
5019          * Unfortunately, the combination of hotplug CPU and frequency
5020          * change creates an intractable locking scenario; the order
5021          * of when these callouts happen is undefined with respect to
5022          * CPU hotplug, and they can race with each other.  As such,
5023          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5024          * undefined; you can actually have a CPU frequency change take
5025          * place in between the computation of X and the setting of the
5026          * variable.  To protect against this problem, all updates of
5027          * the per_cpu tsc_khz variable are done in an interrupt
5028          * protected IPI, and all callers wishing to update the value
5029          * must wait for a synchronous IPI to complete (which is trivial
5030          * if the caller is on the CPU already).  This establishes the
5031          * necessary total order on variable updates.
5032          *
5033          * Note that because a guest time update may take place
5034          * anytime after the setting of the VCPU's request bit, the
5035          * correct TSC value must be set before the request.  However,
5036          * to ensure the update actually makes it to any guest which
5037          * starts running in hardware virtualization between the set
5038          * and the acquisition of the spinlock, we must also ping the
5039          * CPU after setting the request bit.
5040          *
5041          */
5042
5043         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5044                 return 0;
5045         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5046                 return 0;
5047
5048         smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5049
5050         raw_spin_lock(&kvm_lock);
5051         list_for_each_entry(kvm, &vm_list, vm_list) {
5052                 kvm_for_each_vcpu(i, vcpu, kvm) {
5053                         if (vcpu->cpu != freq->cpu)
5054                                 continue;
5055                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5056                         if (vcpu->cpu != smp_processor_id())
5057                                 send_ipi = 1;
5058                 }
5059         }
5060         raw_spin_unlock(&kvm_lock);
5061
5062         if (freq->old < freq->new && send_ipi) {
5063                 /*
5064                  * We upscale the frequency.  Must make the guest
5065                  * doesn't see old kvmclock values while running with
5066                  * the new frequency, otherwise we risk the guest sees
5067                  * time go backwards.
5068                  *
5069                  * In case we update the frequency for another cpu
5070                  * (which might be in guest context) send an interrupt
5071                  * to kick the cpu out of guest context.  Next time
5072                  * guest context is entered kvmclock will be updated,
5073                  * so the guest will not see stale values.
5074                  */
5075                 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5076         }
5077         return 0;
5078 }
5079
5080 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5081         .notifier_call  = kvmclock_cpufreq_notifier
5082 };
5083
5084 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5085                                         unsigned long action, void *hcpu)
5086 {
5087         unsigned int cpu = (unsigned long)hcpu;
5088
5089         switch (action) {
5090                 case CPU_ONLINE:
5091                 case CPU_DOWN_FAILED:
5092                         smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5093                         break;
5094                 case CPU_DOWN_PREPARE:
5095                         smp_call_function_single(cpu, tsc_bad, NULL, 1);
5096                         break;
5097         }
5098         return NOTIFY_OK;
5099 }
5100
5101 static struct notifier_block kvmclock_cpu_notifier_block = {
5102         .notifier_call  = kvmclock_cpu_notifier,
5103         .priority = -INT_MAX
5104 };
5105
5106 static void kvm_timer_init(void)
5107 {
5108         int cpu;
5109
5110         max_tsc_khz = tsc_khz;
5111         register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5112         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5113 #ifdef CONFIG_CPU_FREQ
5114                 struct cpufreq_policy policy;
5115                 memset(&policy, 0, sizeof(policy));
5116                 cpu = get_cpu();
5117                 cpufreq_get_policy(&policy, cpu);
5118                 if (policy.cpuinfo.max_freq)
5119                         max_tsc_khz = policy.cpuinfo.max_freq;
5120                 put_cpu();
5121 #endif
5122                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5123                                           CPUFREQ_TRANSITION_NOTIFIER);
5124         }
5125         pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5126         for_each_online_cpu(cpu)
5127                 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5128 }
5129
5130 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5131
5132 static int kvm_is_in_guest(void)
5133 {
5134         return percpu_read(current_vcpu) != NULL;
5135 }
5136
5137 static int kvm_is_user_mode(void)
5138 {
5139         int user_mode = 3;
5140
5141         if (percpu_read(current_vcpu))
5142                 user_mode = kvm_x86_ops->get_cpl(percpu_read(current_vcpu));
5143
5144         return user_mode != 0;
5145 }
5146
5147 static unsigned long kvm_get_guest_ip(void)
5148 {
5149         unsigned long ip = 0;
5150
5151         if (percpu_read(current_vcpu))
5152                 ip = kvm_rip_read(percpu_read(current_vcpu));
5153
5154         return ip;
5155 }
5156
5157 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5158         .is_in_guest            = kvm_is_in_guest,
5159         .is_user_mode           = kvm_is_user_mode,
5160         .get_guest_ip           = kvm_get_guest_ip,
5161 };
5162
5163 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5164 {
5165         percpu_write(current_vcpu, vcpu);
5166 }
5167 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5168
5169 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5170 {
5171         percpu_write(current_vcpu, NULL);
5172 }
5173 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5174
5175 static void kvm_set_mmio_spte_mask(void)
5176 {
5177         u64 mask;
5178         int maxphyaddr = boot_cpu_data.x86_phys_bits;
5179
5180         /*
5181          * Set the reserved bits and the present bit of an paging-structure
5182          * entry to generate page fault with PFER.RSV = 1.
5183          */
5184         mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
5185         mask |= 1ull;
5186
5187 #ifdef CONFIG_X86_64
5188         /*
5189          * If reserved bit is not supported, clear the present bit to disable
5190          * mmio page fault.
5191          */
5192         if (maxphyaddr == 52)
5193                 mask &= ~1ull;
5194 #endif
5195
5196         kvm_mmu_set_mmio_spte_mask(mask);
5197 }
5198
5199 int kvm_arch_init(void *opaque)
5200 {
5201         int r;
5202         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
5203
5204         if (kvm_x86_ops) {
5205                 printk(KERN_ERR "kvm: already loaded the other module\n");
5206                 r = -EEXIST;
5207                 goto out;
5208         }
5209
5210         if (!ops->cpu_has_kvm_support()) {
5211                 printk(KERN_ERR "kvm: no hardware support\n");
5212                 r = -EOPNOTSUPP;
5213                 goto out;
5214         }
5215         if (ops->disabled_by_bios()) {
5216                 printk(KERN_ERR "kvm: disabled by bios\n");
5217                 r = -EOPNOTSUPP;
5218                 goto out;
5219         }
5220
5221         r = kvm_mmu_module_init();
5222         if (r)
5223                 goto out;
5224
5225         kvm_set_mmio_spte_mask();
5226         kvm_init_msr_list();
5227
5228         kvm_x86_ops = ops;
5229         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5230                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
5231
5232         kvm_timer_init();
5233
5234         perf_register_guest_info_callbacks(&kvm_guest_cbs);
5235
5236         if (cpu_has_xsave)
5237                 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5238
5239         return 0;
5240
5241 out:
5242         return r;
5243 }
5244
5245 void kvm_arch_exit(void)
5246 {
5247         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
5248
5249         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5250                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
5251                                             CPUFREQ_TRANSITION_NOTIFIER);
5252         unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5253         kvm_x86_ops = NULL;
5254         kvm_mmu_module_exit();
5255 }
5256
5257 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
5258 {
5259         ++vcpu->stat.halt_exits;
5260         if (irqchip_in_kernel(vcpu->kvm)) {
5261                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
5262                 return 1;
5263         } else {
5264                 vcpu->run->exit_reason = KVM_EXIT_HLT;
5265                 return 0;
5266         }
5267 }
5268 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
5269
5270 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
5271                            unsigned long a1)
5272 {
5273         if (is_long_mode(vcpu))
5274                 return a0;
5275         else
5276                 return a0 | ((gpa_t)a1 << 32);
5277 }
5278
5279 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
5280 {
5281         u64 param, ingpa, outgpa, ret;
5282         uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
5283         bool fast, longmode;
5284         int cs_db, cs_l;
5285
5286         /*
5287          * hypercall generates UD from non zero cpl and real mode
5288          * per HYPER-V spec
5289          */
5290         if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
5291                 kvm_queue_exception(vcpu, UD_VECTOR);
5292                 return 0;
5293         }
5294
5295         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5296         longmode = is_long_mode(vcpu) && cs_l == 1;
5297
5298         if (!longmode) {
5299                 param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
5300                         (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
5301                 ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
5302                         (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
5303                 outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
5304                         (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
5305         }
5306 #ifdef CONFIG_X86_64
5307         else {
5308                 param = kvm_register_read(vcpu, VCPU_REGS_RCX);
5309                 ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
5310                 outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
5311         }
5312 #endif
5313
5314         code = param & 0xffff;
5315         fast = (param >> 16) & 0x1;
5316         rep_cnt = (param >> 32) & 0xfff;
5317         rep_idx = (param >> 48) & 0xfff;
5318
5319         trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
5320
5321         switch (code) {
5322         case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
5323                 kvm_vcpu_on_spin(vcpu);
5324                 break;
5325         default:
5326                 res = HV_STATUS_INVALID_HYPERCALL_CODE;
5327                 break;
5328         }
5329
5330         ret = res | (((u64)rep_done & 0xfff) << 32);
5331         if (longmode) {
5332                 kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5333         } else {
5334                 kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
5335                 kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
5336         }
5337
5338         return 1;
5339 }
5340
5341 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
5342 {
5343         unsigned long nr, a0, a1, a2, a3, ret;
5344         int r = 1;
5345
5346         if (kvm_hv_hypercall_enabled(vcpu->kvm))
5347                 return kvm_hv_hypercall(vcpu);
5348
5349         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
5350         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
5351         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
5352         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
5353         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
5354
5355         trace_kvm_hypercall(nr, a0, a1, a2, a3);
5356
5357         if (!is_long_mode(vcpu)) {
5358                 nr &= 0xFFFFFFFF;
5359                 a0 &= 0xFFFFFFFF;
5360                 a1 &= 0xFFFFFFFF;
5361                 a2 &= 0xFFFFFFFF;
5362                 a3 &= 0xFFFFFFFF;
5363         }
5364
5365         if (kvm_x86_ops->get_cpl(vcpu) != 0) {
5366                 ret = -KVM_EPERM;
5367                 goto out;
5368         }
5369
5370         switch (nr) {
5371         case KVM_HC_VAPIC_POLL_IRQ:
5372                 ret = 0;
5373                 break;
5374         case KVM_HC_MMU_OP:
5375                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
5376                 break;
5377         default:
5378                 ret = -KVM_ENOSYS;
5379                 break;
5380         }
5381 out:
5382         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
5383         ++vcpu->stat.hypercalls;
5384         return r;
5385 }
5386 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
5387
5388 int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
5389 {
5390         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5391         char instruction[3];
5392         unsigned long rip = kvm_rip_read(vcpu);
5393
5394         /*
5395          * Blow out the MMU to ensure that no other VCPU has an active mapping
5396          * to ensure that the updated hypercall appears atomically across all
5397          * VCPUs.
5398          */
5399         kvm_mmu_zap_all(vcpu->kvm);
5400
5401         kvm_x86_ops->patch_hypercall(vcpu, instruction);
5402
5403         return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
5404 }
5405
5406 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
5407 {
5408         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
5409         int j, nent = vcpu->arch.cpuid_nent;
5410
5411         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
5412         /* when no next entry is found, the current entry[i] is reselected */
5413         for (j = i + 1; ; j = (j + 1) % nent) {
5414                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
5415                 if (ej->function == e->function) {
5416                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
5417                         return j;
5418                 }
5419         }
5420         return 0; /* silence gcc, even though control never reaches here */
5421 }
5422
5423 /* find an entry with matching function, matching index (if needed), and that
5424  * should be read next (if it's stateful) */
5425 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
5426         u32 function, u32 index)
5427 {
5428         if (e->function != function)
5429                 return 0;
5430         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
5431                 return 0;
5432         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
5433             !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
5434                 return 0;
5435         return 1;
5436 }
5437
5438 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
5439                                               u32 function, u32 index)
5440 {
5441         int i;
5442         struct kvm_cpuid_entry2 *best = NULL;
5443
5444         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
5445                 struct kvm_cpuid_entry2 *e;
5446
5447                 e = &vcpu->arch.cpuid_entries[i];
5448                 if (is_matching_cpuid_entry(e, function, index)) {
5449                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
5450                                 move_to_next_stateful_cpuid_entry(vcpu, i);
5451                         best = e;
5452                         break;
5453                 }
5454         }
5455         return best;
5456 }
5457 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
5458
5459 int cpuid_maxphyaddr(struct kvm_vcpu *vcpu)
5460 {
5461         struct kvm_cpuid_entry2 *best;
5462
5463         best = kvm_find_cpuid_entry(vcpu, 0x80000000, 0);
5464         if (!best || best->eax < 0x80000008)
5465                 goto not_found;
5466         best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
5467         if (best)
5468                 return best->eax & 0xff;
5469 not_found:
5470         return 36;
5471 }
5472
5473 /*
5474  * If no match is found, check whether we exceed the vCPU's limit
5475  * and return the content of the highest valid _standard_ leaf instead.
5476  * This is to satisfy the CPUID specification.
5477  */
5478 static struct kvm_cpuid_entry2* check_cpuid_limit(struct kvm_vcpu *vcpu,
5479                                                   u32 function, u32 index)
5480 {
5481         struct kvm_cpuid_entry2 *maxlevel;
5482
5483         maxlevel = kvm_find_cpuid_entry(vcpu, function & 0x80000000, 0);
5484         if (!maxlevel || maxlevel->eax >= function)
5485                 return NULL;
5486         if (function & 0x80000000) {
5487                 maxlevel = kvm_find_cpuid_entry(vcpu, 0, 0);
5488                 if (!maxlevel)
5489                         return NULL;
5490         }
5491         return kvm_find_cpuid_entry(vcpu, maxlevel->eax, index);
5492 }
5493
5494 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
5495 {
5496         u32 function, index;
5497         struct kvm_cpuid_entry2 *best;
5498
5499         function = kvm_register_read(vcpu, VCPU_REGS_RAX);
5500         index = kvm_register_read(vcpu, VCPU_REGS_RCX);
5501         kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
5502         kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
5503         kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
5504         kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
5505         best = kvm_find_cpuid_entry(vcpu, function, index);
5506
5507         if (!best)
5508                 best = check_cpuid_limit(vcpu, function, index);
5509
5510         if (best) {
5511                 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
5512                 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
5513                 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
5514                 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
5515         }
5516         kvm_x86_ops->skip_emulated_instruction(vcpu);
5517         trace_kvm_cpuid(function,
5518                         kvm_register_read(vcpu, VCPU_REGS_RAX),
5519                         kvm_register_read(vcpu, VCPU_REGS_RBX),
5520                         kvm_register_read(vcpu, VCPU_REGS_RCX),
5521                         kvm_register_read(vcpu, VCPU_REGS_RDX));
5522 }
5523 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
5524
5525 /*
5526  * Check if userspace requested an interrupt window, and that the
5527  * interrupt window is open.
5528  *
5529  * No need to exit to userspace if we already have an interrupt queued.
5530  */
5531 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
5532 {
5533         return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
5534                 vcpu->run->request_interrupt_window &&
5535                 kvm_arch_interrupt_allowed(vcpu));
5536 }
5537
5538 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
5539 {
5540         struct kvm_run *kvm_run = vcpu->run;
5541
5542         kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
5543         kvm_run->cr8 = kvm_get_cr8(vcpu);
5544         kvm_run->apic_base = kvm_get_apic_base(vcpu);
5545         if (irqchip_in_kernel(vcpu->kvm))
5546                 kvm_run->ready_for_interrupt_injection = 1;
5547         else
5548                 kvm_run->ready_for_interrupt_injection =
5549                         kvm_arch_interrupt_allowed(vcpu) &&
5550                         !kvm_cpu_has_interrupt(vcpu) &&
5551                         !kvm_event_needs_reinjection(vcpu);
5552 }
5553
5554 static void vapic_enter(struct kvm_vcpu *vcpu)
5555 {
5556         struct kvm_lapic *apic = vcpu->arch.apic;
5557         struct page *page;
5558
5559         if (!apic || !apic->vapic_addr)
5560                 return;
5561
5562         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5563
5564         vcpu->arch.apic->vapic_page = page;
5565 }
5566
5567 static void vapic_exit(struct kvm_vcpu *vcpu)
5568 {
5569         struct kvm_lapic *apic = vcpu->arch.apic;
5570         int idx;
5571
5572         if (!apic || !apic->vapic_addr)
5573                 return;
5574
5575         idx = srcu_read_lock(&vcpu->kvm->srcu);
5576         kvm_release_page_dirty(apic->vapic_page);
5577         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
5578         srcu_read_unlock(&vcpu->kvm->srcu, idx);
5579 }
5580
5581 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
5582 {
5583         int max_irr, tpr;
5584
5585         if (!kvm_x86_ops->update_cr8_intercept)
5586                 return;
5587
5588         if (!vcpu->arch.apic)
5589                 return;
5590
5591         if (!vcpu->arch.apic->vapic_addr)
5592                 max_irr = kvm_lapic_find_highest_irr(vcpu);
5593         else
5594                 max_irr = -1;
5595
5596         if (max_irr != -1)
5597                 max_irr >>= 4;
5598
5599         tpr = kvm_lapic_get_cr8(vcpu);
5600
5601         kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
5602 }
5603
5604 static void inject_pending_event(struct kvm_vcpu *vcpu)
5605 {
5606         /* try to reinject previous events if any */
5607         if (vcpu->arch.exception.pending) {
5608                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
5609                                         vcpu->arch.exception.has_error_code,
5610                                         vcpu->arch.exception.error_code);
5611                 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
5612                                           vcpu->arch.exception.has_error_code,
5613                                           vcpu->arch.exception.error_code,
5614                                           vcpu->arch.exception.reinject);
5615                 return;
5616         }
5617
5618         if (vcpu->arch.nmi_injected) {
5619                 kvm_x86_ops->set_nmi(vcpu);
5620                 return;
5621         }
5622
5623         if (vcpu->arch.interrupt.pending) {
5624                 kvm_x86_ops->set_irq(vcpu);
5625                 return;
5626         }
5627
5628         /* try to inject new event if pending */
5629         if (vcpu->arch.nmi_pending) {
5630                 if (kvm_x86_ops->nmi_allowed(vcpu)) {
5631                         --vcpu->arch.nmi_pending;
5632                         vcpu->arch.nmi_injected = true;
5633                         kvm_x86_ops->set_nmi(vcpu);
5634                 }
5635         } else if (kvm_cpu_has_interrupt(vcpu)) {
5636                 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
5637                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
5638                                             false);
5639                         kvm_x86_ops->set_irq(vcpu);
5640                 }
5641         }
5642 }
5643
5644 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
5645 {
5646         if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
5647                         !vcpu->guest_xcr0_loaded) {
5648                 /* kvm_set_xcr() also depends on this */
5649                 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
5650                 vcpu->guest_xcr0_loaded = 1;
5651         }
5652 }
5653
5654 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
5655 {
5656         if (vcpu->guest_xcr0_loaded) {
5657                 if (vcpu->arch.xcr0 != host_xcr0)
5658                         xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
5659                 vcpu->guest_xcr0_loaded = 0;
5660         }
5661 }
5662
5663 static void process_nmi(struct kvm_vcpu *vcpu)
5664 {
5665         unsigned limit = 2;
5666
5667         /*
5668          * x86 is limited to one NMI running, and one NMI pending after it.
5669          * If an NMI is already in progress, limit further NMIs to just one.
5670          * Otherwise, allow two (and we'll inject the first one immediately).
5671          */
5672         if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
5673                 limit = 1;
5674
5675         vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
5676         vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
5677         kvm_make_request(KVM_REQ_EVENT, vcpu);
5678 }
5679
5680 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
5681 {
5682         int r;
5683         bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
5684                 vcpu->run->request_interrupt_window;
5685
5686         if (vcpu->requests) {
5687                 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
5688                         kvm_mmu_unload(vcpu);
5689                 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
5690                         __kvm_migrate_timers(vcpu);
5691                 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
5692                         r = kvm_guest_time_update(vcpu);
5693                         if (unlikely(r))
5694                                 goto out;
5695                 }
5696                 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
5697                         kvm_mmu_sync_roots(vcpu);
5698                 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
5699                         kvm_x86_ops->tlb_flush(vcpu);
5700                 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
5701                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
5702                         r = 0;
5703                         goto out;
5704                 }
5705                 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
5706                         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5707                         r = 0;
5708                         goto out;
5709                 }
5710                 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
5711                         vcpu->fpu_active = 0;
5712                         kvm_x86_ops->fpu_deactivate(vcpu);
5713                 }
5714                 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
5715                         /* Page is swapped out. Do synthetic halt */
5716                         vcpu->arch.apf.halted = true;
5717                         r = 1;
5718                         goto out;
5719                 }
5720                 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
5721                         record_steal_time(vcpu);
5722                 if (kvm_check_request(KVM_REQ_NMI, vcpu))
5723                         process_nmi(vcpu);
5724
5725         }
5726
5727         r = kvm_mmu_reload(vcpu);
5728         if (unlikely(r))
5729                 goto out;
5730
5731         if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
5732                 inject_pending_event(vcpu);
5733
5734                 /* enable NMI/IRQ window open exits if needed */
5735                 if (vcpu->arch.nmi_pending)
5736                         kvm_x86_ops->enable_nmi_window(vcpu);
5737                 else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
5738                         kvm_x86_ops->enable_irq_window(vcpu);
5739
5740                 if (kvm_lapic_enabled(vcpu)) {
5741                         update_cr8_intercept(vcpu);
5742                         kvm_lapic_sync_to_vapic(vcpu);
5743                 }
5744         }
5745
5746         preempt_disable();
5747
5748         kvm_x86_ops->prepare_guest_switch(vcpu);
5749         if (vcpu->fpu_active)
5750                 kvm_load_guest_fpu(vcpu);
5751         kvm_load_guest_xcr0(vcpu);
5752
5753         vcpu->mode = IN_GUEST_MODE;
5754
5755         /* We should set ->mode before check ->requests,
5756          * see the comment in make_all_cpus_request.
5757          */
5758         smp_mb();
5759
5760         local_irq_disable();
5761
5762         if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
5763             || need_resched() || signal_pending(current)) {
5764                 vcpu->mode = OUTSIDE_GUEST_MODE;
5765                 smp_wmb();
5766                 local_irq_enable();
5767                 preempt_enable();
5768                 kvm_x86_ops->cancel_injection(vcpu);
5769                 r = 1;
5770                 goto out;
5771         }
5772
5773         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5774
5775         kvm_guest_enter();
5776
5777         if (unlikely(vcpu->arch.switch_db_regs)) {
5778                 set_debugreg(0, 7);
5779                 set_debugreg(vcpu->arch.eff_db[0], 0);
5780                 set_debugreg(vcpu->arch.eff_db[1], 1);
5781                 set_debugreg(vcpu->arch.eff_db[2], 2);
5782                 set_debugreg(vcpu->arch.eff_db[3], 3);
5783         }
5784
5785         trace_kvm_entry(vcpu->vcpu_id);
5786         kvm_x86_ops->run(vcpu);
5787
5788         /*
5789          * If the guest has used debug registers, at least dr7
5790          * will be disabled while returning to the host.
5791          * If we don't have active breakpoints in the host, we don't
5792          * care about the messed up debug address registers. But if
5793          * we have some of them active, restore the old state.
5794          */
5795         if (hw_breakpoint_active())
5796                 hw_breakpoint_restore();
5797
5798         vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
5799
5800         vcpu->mode = OUTSIDE_GUEST_MODE;
5801         smp_wmb();
5802         local_irq_enable();
5803
5804         ++vcpu->stat.exits;
5805
5806         /*
5807          * We must have an instruction between local_irq_enable() and
5808          * kvm_guest_exit(), so the timer interrupt isn't delayed by
5809          * the interrupt shadow.  The stat.exits increment will do nicely.
5810          * But we need to prevent reordering, hence this barrier():
5811          */
5812         barrier();
5813
5814         kvm_guest_exit();
5815
5816         preempt_enable();
5817
5818         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5819
5820         /*
5821          * Profile KVM exit RIPs:
5822          */
5823         if (unlikely(prof_on == KVM_PROFILING)) {
5824                 unsigned long rip = kvm_rip_read(vcpu);
5825                 profile_hit(KVM_PROFILING, (void *)rip);
5826         }
5827
5828
5829         kvm_lapic_sync_from_vapic(vcpu);
5830
5831         r = kvm_x86_ops->handle_exit(vcpu);
5832 out:
5833         return r;
5834 }
5835
5836
5837 static int __vcpu_run(struct kvm_vcpu *vcpu)
5838 {
5839         int r;
5840         struct kvm *kvm = vcpu->kvm;
5841
5842         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
5843                 pr_debug("vcpu %d received sipi with vector # %x\n",
5844                          vcpu->vcpu_id, vcpu->arch.sipi_vector);
5845                 kvm_lapic_reset(vcpu);
5846                 r = kvm_arch_vcpu_reset(vcpu);
5847                 if (r)
5848                         return r;
5849                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
5850         }
5851
5852         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5853         vapic_enter(vcpu);
5854
5855         r = 1;
5856         while (r > 0) {
5857                 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
5858                     !vcpu->arch.apf.halted)
5859                         r = vcpu_enter_guest(vcpu);
5860                 else {
5861                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5862                         kvm_vcpu_block(vcpu);
5863                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5864                         if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
5865                         {
5866                                 switch(vcpu->arch.mp_state) {
5867                                 case KVM_MP_STATE_HALTED:
5868                                         vcpu->arch.mp_state =
5869                                                 KVM_MP_STATE_RUNNABLE;
5870                                 case KVM_MP_STATE_RUNNABLE:
5871                                         vcpu->arch.apf.halted = false;
5872                                         break;
5873                                 case KVM_MP_STATE_SIPI_RECEIVED:
5874                                 default:
5875                                         r = -EINTR;
5876                                         break;
5877                                 }
5878                         }
5879                 }
5880
5881                 if (r <= 0)
5882                         break;
5883
5884                 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
5885                 if (kvm_cpu_has_pending_timer(vcpu))
5886                         kvm_inject_pending_timer_irqs(vcpu);
5887
5888                 if (dm_request_for_irq_injection(vcpu)) {
5889                         r = -EINTR;
5890                         vcpu->run->exit_reason = KVM_EXIT_INTR;
5891                         ++vcpu->stat.request_irq_exits;
5892                 }
5893
5894                 kvm_check_async_pf_completion(vcpu);
5895
5896                 if (signal_pending(current)) {
5897                         r = -EINTR;
5898                         vcpu->run->exit_reason = KVM_EXIT_INTR;
5899                         ++vcpu->stat.signal_exits;
5900                 }
5901                 if (need_resched()) {
5902                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5903                         kvm_resched(vcpu);
5904                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
5905                 }
5906         }
5907
5908         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
5909
5910         vapic_exit(vcpu);
5911
5912         return r;
5913 }
5914
5915 static int complete_mmio(struct kvm_vcpu *vcpu)
5916 {
5917         struct kvm_run *run = vcpu->run;
5918         int r;
5919
5920         if (!(vcpu->arch.pio.count || vcpu->mmio_needed))
5921                 return 1;
5922
5923         if (vcpu->mmio_needed) {
5924                 vcpu->mmio_needed = 0;
5925                 if (!vcpu->mmio_is_write)
5926                         memcpy(vcpu->mmio_data + vcpu->mmio_index,
5927                                run->mmio.data, 8);
5928                 vcpu->mmio_index += 8;
5929                 if (vcpu->mmio_index < vcpu->mmio_size) {
5930                         run->exit_reason = KVM_EXIT_MMIO;
5931                         run->mmio.phys_addr = vcpu->mmio_phys_addr + vcpu->mmio_index;
5932                         memcpy(run->mmio.data, vcpu->mmio_data + vcpu->mmio_index, 8);
5933                         run->mmio.len = min(vcpu->mmio_size - vcpu->mmio_index, 8);
5934                         run->mmio.is_write = vcpu->mmio_is_write;
5935                         vcpu->mmio_needed = 1;
5936                         return 0;
5937                 }
5938                 if (vcpu->mmio_is_write)
5939                         return 1;
5940                 vcpu->mmio_read_completed = 1;
5941         }
5942         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5943         r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
5944         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5945         if (r != EMULATE_DONE)
5946                 return 0;
5947         return 1;
5948 }
5949
5950 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
5951 {
5952         int r;
5953         sigset_t sigsaved;
5954
5955         if (!tsk_used_math(current) && init_fpu(current))
5956                 return -ENOMEM;
5957
5958         if (vcpu->sigset_active)
5959                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
5960
5961         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
5962                 kvm_vcpu_block(vcpu);
5963                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
5964                 r = -EAGAIN;
5965                 goto out;
5966         }
5967
5968         /* re-sync apic's tpr */
5969         if (!irqchip_in_kernel(vcpu->kvm)) {
5970                 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
5971                         r = -EINVAL;
5972                         goto out;
5973                 }
5974         }
5975
5976         r = complete_mmio(vcpu);
5977         if (r <= 0)
5978                 goto out;
5979
5980         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
5981                 kvm_register_write(vcpu, VCPU_REGS_RAX,
5982                                      kvm_run->hypercall.ret);
5983
5984         r = __vcpu_run(vcpu);
5985
5986 out:
5987         post_kvm_run_save(vcpu);
5988         if (vcpu->sigset_active)
5989                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
5990
5991         return r;
5992 }
5993
5994 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
5995 {
5996         if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
5997                 /*
5998                  * We are here if userspace calls get_regs() in the middle of
5999                  * instruction emulation. Registers state needs to be copied
6000                  * back from emulation context to vcpu. Usrapace shouldn't do
6001                  * that usually, but some bad designed PV devices (vmware
6002                  * backdoor interface) need this to work
6003                  */
6004                 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6005                 memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
6006                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6007         }
6008         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
6009         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
6010         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
6011         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
6012         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
6013         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
6014         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6015         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
6016 #ifdef CONFIG_X86_64
6017         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
6018         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
6019         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
6020         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
6021         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
6022         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
6023         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
6024         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
6025 #endif
6026
6027         regs->rip = kvm_rip_read(vcpu);
6028         regs->rflags = kvm_get_rflags(vcpu);
6029
6030         return 0;
6031 }
6032
6033 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
6034 {
6035         vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
6036         vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
6037
6038         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
6039         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
6040         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
6041         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
6042         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
6043         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
6044         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
6045         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
6046 #ifdef CONFIG_X86_64
6047         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
6048         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
6049         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
6050         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
6051         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
6052         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
6053         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
6054         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
6055 #endif
6056
6057         kvm_rip_write(vcpu, regs->rip);
6058         kvm_set_rflags(vcpu, regs->rflags);
6059
6060         vcpu->arch.exception.pending = false;
6061
6062         kvm_make_request(KVM_REQ_EVENT, vcpu);
6063
6064         return 0;
6065 }
6066
6067 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
6068 {
6069         struct kvm_segment cs;
6070
6071         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
6072         *db = cs.db;
6073         *l = cs.l;
6074 }
6075 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
6076
6077 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
6078                                   struct kvm_sregs *sregs)
6079 {
6080         struct desc_ptr dt;
6081
6082         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6083         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6084         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6085         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6086         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6087         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6088
6089         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6090         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6091
6092         kvm_x86_ops->get_idt(vcpu, &dt);
6093         sregs->idt.limit = dt.size;
6094         sregs->idt.base = dt.address;
6095         kvm_x86_ops->get_gdt(vcpu, &dt);
6096         sregs->gdt.limit = dt.size;
6097         sregs->gdt.base = dt.address;
6098
6099         sregs->cr0 = kvm_read_cr0(vcpu);
6100         sregs->cr2 = vcpu->arch.cr2;
6101         sregs->cr3 = kvm_read_cr3(vcpu);
6102         sregs->cr4 = kvm_read_cr4(vcpu);
6103         sregs->cr8 = kvm_get_cr8(vcpu);
6104         sregs->efer = vcpu->arch.efer;
6105         sregs->apic_base = kvm_get_apic_base(vcpu);
6106
6107         memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
6108
6109         if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
6110                 set_bit(vcpu->arch.interrupt.nr,
6111                         (unsigned long *)sregs->interrupt_bitmap);
6112
6113         return 0;
6114 }
6115
6116 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
6117                                     struct kvm_mp_state *mp_state)
6118 {
6119         mp_state->mp_state = vcpu->arch.mp_state;
6120         return 0;
6121 }
6122
6123 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
6124                                     struct kvm_mp_state *mp_state)
6125 {
6126         vcpu->arch.mp_state = mp_state->mp_state;
6127         kvm_make_request(KVM_REQ_EVENT, vcpu);
6128         return 0;
6129 }
6130
6131 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
6132                     bool has_error_code, u32 error_code)
6133 {
6134         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6135         int ret;
6136
6137         init_emulate_ctxt(vcpu);
6138
6139         ret = emulator_task_switch(ctxt, tss_selector, reason,
6140                                    has_error_code, error_code);
6141
6142         if (ret)
6143                 return EMULATE_FAIL;
6144
6145         memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
6146         kvm_rip_write(vcpu, ctxt->eip);
6147         kvm_set_rflags(vcpu, ctxt->eflags);
6148         kvm_make_request(KVM_REQ_EVENT, vcpu);
6149         return EMULATE_DONE;
6150 }
6151 EXPORT_SYMBOL_GPL(kvm_task_switch);
6152
6153 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
6154                                   struct kvm_sregs *sregs)
6155 {
6156         int mmu_reset_needed = 0;
6157         int pending_vec, max_bits, idx;
6158         struct desc_ptr dt;
6159
6160         if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
6161                 return -EINVAL;
6162
6163         dt.size = sregs->idt.limit;
6164         dt.address = sregs->idt.base;
6165         kvm_x86_ops->set_idt(vcpu, &dt);
6166         dt.size = sregs->gdt.limit;
6167         dt.address = sregs->gdt.base;
6168         kvm_x86_ops->set_gdt(vcpu, &dt);
6169
6170         vcpu->arch.cr2 = sregs->cr2;
6171         mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
6172         vcpu->arch.cr3 = sregs->cr3;
6173         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
6174
6175         kvm_set_cr8(vcpu, sregs->cr8);
6176
6177         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
6178         kvm_x86_ops->set_efer(vcpu, sregs->efer);
6179         kvm_set_apic_base(vcpu, sregs->apic_base);
6180
6181         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
6182         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
6183         vcpu->arch.cr0 = sregs->cr0;
6184
6185         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
6186         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
6187         if (sregs->cr4 & X86_CR4_OSXSAVE)
6188                 update_cpuid(vcpu);
6189
6190         idx = srcu_read_lock(&vcpu->kvm->srcu);
6191         if (!is_long_mode(vcpu) && is_pae(vcpu)) {
6192                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
6193                 mmu_reset_needed = 1;
6194         }
6195         srcu_read_unlock(&vcpu->kvm->srcu, idx);
6196
6197         if (mmu_reset_needed)
6198                 kvm_mmu_reset_context(vcpu);
6199
6200         max_bits = (sizeof sregs->interrupt_bitmap) << 3;
6201         pending_vec = find_first_bit(
6202                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
6203         if (pending_vec < max_bits) {
6204                 kvm_queue_interrupt(vcpu, pending_vec, false);
6205                 pr_debug("Set back pending irq %d\n", pending_vec);
6206         }
6207
6208         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
6209         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
6210         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
6211         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
6212         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
6213         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
6214
6215         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
6216         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
6217
6218         update_cr8_intercept(vcpu);
6219
6220         /* Older userspace won't unhalt the vcpu on reset. */
6221         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
6222             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
6223             !is_protmode(vcpu))
6224                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6225
6226         kvm_make_request(KVM_REQ_EVENT, vcpu);
6227
6228         return 0;
6229 }
6230
6231 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
6232                                         struct kvm_guest_debug *dbg)
6233 {
6234         unsigned long rflags;
6235         int i, r;
6236
6237         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
6238                 r = -EBUSY;
6239                 if (vcpu->arch.exception.pending)
6240                         goto out;
6241                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
6242                         kvm_queue_exception(vcpu, DB_VECTOR);
6243                 else
6244                         kvm_queue_exception(vcpu, BP_VECTOR);
6245         }
6246
6247         /*
6248          * Read rflags as long as potentially injected trace flags are still
6249          * filtered out.
6250          */
6251         rflags = kvm_get_rflags(vcpu);
6252
6253         vcpu->guest_debug = dbg->control;
6254         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
6255                 vcpu->guest_debug = 0;
6256
6257         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6258                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
6259                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
6260                 vcpu->arch.switch_db_regs =
6261                         (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
6262         } else {
6263                 for (i = 0; i < KVM_NR_DB_REGS; i++)
6264                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
6265                 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
6266         }
6267
6268         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6269                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
6270                         get_segment_base(vcpu, VCPU_SREG_CS);
6271
6272         /*
6273          * Trigger an rflags update that will inject or remove the trace
6274          * flags.
6275          */
6276         kvm_set_rflags(vcpu, rflags);
6277
6278         kvm_x86_ops->set_guest_debug(vcpu, dbg);
6279
6280         r = 0;
6281
6282 out:
6283
6284         return r;
6285 }
6286
6287 /*
6288  * Translate a guest virtual address to a guest physical address.
6289  */
6290 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
6291                                     struct kvm_translation *tr)
6292 {
6293         unsigned long vaddr = tr->linear_address;
6294         gpa_t gpa;
6295         int idx;
6296
6297         idx = srcu_read_lock(&vcpu->kvm->srcu);
6298         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
6299         srcu_read_unlock(&vcpu->kvm->srcu, idx);
6300         tr->physical_address = gpa;
6301         tr->valid = gpa != UNMAPPED_GVA;
6302         tr->writeable = 1;
6303         tr->usermode = 0;
6304
6305         return 0;
6306 }
6307
6308 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6309 {
6310         struct i387_fxsave_struct *fxsave =
6311                         &vcpu->arch.guest_fpu.state->fxsave;
6312
6313         memcpy(fpu->fpr, fxsave->st_space, 128);
6314         fpu->fcw = fxsave->cwd;
6315         fpu->fsw = fxsave->swd;
6316         fpu->ftwx = fxsave->twd;
6317         fpu->last_opcode = fxsave->fop;
6318         fpu->last_ip = fxsave->rip;
6319         fpu->last_dp = fxsave->rdp;
6320         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
6321
6322         return 0;
6323 }
6324
6325 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
6326 {
6327         struct i387_fxsave_struct *fxsave =
6328                         &vcpu->arch.guest_fpu.state->fxsave;
6329
6330         memcpy(fxsave->st_space, fpu->fpr, 128);
6331         fxsave->cwd = fpu->fcw;
6332         fxsave->swd = fpu->fsw;
6333         fxsave->twd = fpu->ftwx;
6334         fxsave->fop = fpu->last_opcode;
6335         fxsave->rip = fpu->last_ip;
6336         fxsave->rdp = fpu->last_dp;
6337         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
6338
6339         return 0;
6340 }
6341
6342 int fx_init(struct kvm_vcpu *vcpu)
6343 {
6344         int err;
6345
6346         err = fpu_alloc(&vcpu->arch.guest_fpu);
6347         if (err)
6348                 return err;
6349
6350         fpu_finit(&vcpu->arch.guest_fpu);
6351
6352         /*
6353          * Ensure guest xcr0 is valid for loading
6354          */
6355         vcpu->arch.xcr0 = XSTATE_FP;
6356
6357         vcpu->arch.cr0 |= X86_CR0_ET;
6358
6359         return 0;
6360 }
6361 EXPORT_SYMBOL_GPL(fx_init);
6362
6363 static void fx_free(struct kvm_vcpu *vcpu)
6364 {
6365         fpu_free(&vcpu->arch.guest_fpu);
6366 }
6367
6368 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
6369 {
6370         if (vcpu->guest_fpu_loaded)
6371                 return;
6372
6373         /*
6374          * Restore all possible states in the guest,
6375          * and assume host would use all available bits.
6376          * Guest xcr0 would be loaded later.
6377          */
6378         kvm_put_guest_xcr0(vcpu);
6379         vcpu->guest_fpu_loaded = 1;
6380         unlazy_fpu(current);
6381         fpu_restore_checking(&vcpu->arch.guest_fpu);
6382         trace_kvm_fpu(1);
6383 }
6384
6385 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
6386 {
6387         kvm_put_guest_xcr0(vcpu);
6388
6389         if (!vcpu->guest_fpu_loaded)
6390                 return;
6391
6392         vcpu->guest_fpu_loaded = 0;
6393         fpu_save_init(&vcpu->arch.guest_fpu);
6394         ++vcpu->stat.fpu_reload;
6395         kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
6396         trace_kvm_fpu(0);
6397 }
6398
6399 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
6400 {
6401         kvmclock_reset(vcpu);
6402
6403         free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
6404         fx_free(vcpu);
6405         kvm_x86_ops->vcpu_free(vcpu);
6406 }
6407
6408 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
6409                                                 unsigned int id)
6410 {
6411         if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
6412                 printk_once(KERN_WARNING
6413                 "kvm: SMP vm created on host with unstable TSC; "
6414                 "guest TSC will not be reliable\n");
6415         return kvm_x86_ops->vcpu_create(kvm, id);
6416 }
6417
6418 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
6419 {
6420         int r;
6421
6422         vcpu->arch.mtrr_state.have_fixed = 1;
6423         vcpu_load(vcpu);
6424         r = kvm_arch_vcpu_reset(vcpu);
6425         if (r == 0)
6426                 r = kvm_mmu_setup(vcpu);
6427         vcpu_put(vcpu);
6428
6429         return r;
6430 }
6431
6432 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
6433 {
6434         vcpu->arch.apf.msr_val = 0;
6435
6436         vcpu_load(vcpu);
6437         kvm_mmu_unload(vcpu);
6438         vcpu_put(vcpu);
6439
6440         fx_free(vcpu);
6441         kvm_x86_ops->vcpu_free(vcpu);
6442 }
6443
6444 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
6445 {
6446         atomic_set(&vcpu->arch.nmi_queued, 0);
6447         vcpu->arch.nmi_pending = 0;
6448         vcpu->arch.nmi_injected = false;
6449
6450         vcpu->arch.switch_db_regs = 0;
6451         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
6452         vcpu->arch.dr6 = DR6_FIXED_1;
6453         vcpu->arch.dr7 = DR7_FIXED_1;
6454
6455         kvm_make_request(KVM_REQ_EVENT, vcpu);
6456         vcpu->arch.apf.msr_val = 0;
6457         vcpu->arch.st.msr_val = 0;
6458
6459         kvmclock_reset(vcpu);
6460
6461         kvm_clear_async_pf_completion_queue(vcpu);
6462         kvm_async_pf_hash_reset(vcpu);
6463         vcpu->arch.apf.halted = false;
6464
6465         return kvm_x86_ops->vcpu_reset(vcpu);
6466 }
6467
6468 int kvm_arch_hardware_enable(void *garbage)
6469 {
6470         struct kvm *kvm;
6471         struct kvm_vcpu *vcpu;
6472         int i;
6473
6474         kvm_shared_msr_cpu_online();
6475         list_for_each_entry(kvm, &vm_list, vm_list)
6476                 kvm_for_each_vcpu(i, vcpu, kvm)
6477                         if (vcpu->cpu == smp_processor_id())
6478                                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6479         return kvm_x86_ops->hardware_enable(garbage);
6480 }
6481
6482 void kvm_arch_hardware_disable(void *garbage)
6483 {
6484         kvm_x86_ops->hardware_disable(garbage);
6485         drop_user_return_notifiers(garbage);
6486 }
6487
6488 int kvm_arch_hardware_setup(void)
6489 {
6490         return kvm_x86_ops->hardware_setup();
6491 }
6492
6493 void kvm_arch_hardware_unsetup(void)
6494 {
6495         kvm_x86_ops->hardware_unsetup();
6496 }
6497
6498 void kvm_arch_check_processor_compat(void *rtn)
6499 {
6500         kvm_x86_ops->check_processor_compatibility(rtn);
6501 }
6502
6503 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
6504 {
6505         return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
6506 }
6507
6508 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
6509 {
6510         struct page *page;
6511         struct kvm *kvm;
6512         int r;
6513
6514         BUG_ON(vcpu->kvm == NULL);
6515         kvm = vcpu->kvm;
6516
6517         vcpu->arch.emulate_ctxt.ops = &emulate_ops;
6518         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
6519         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
6520         vcpu->arch.mmu.translate_gpa = translate_gpa;
6521         vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
6522         if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
6523                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
6524         else
6525                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
6526
6527         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
6528         if (!page) {
6529                 r = -ENOMEM;
6530                 goto fail;
6531         }
6532         vcpu->arch.pio_data = page_address(page);
6533
6534         kvm_init_tsc_catchup(vcpu, max_tsc_khz);
6535
6536         r = kvm_mmu_create(vcpu);
6537         if (r < 0)
6538                 goto fail_free_pio_data;
6539
6540         if (irqchip_in_kernel(kvm)) {
6541                 r = kvm_create_lapic(vcpu);
6542                 if (r < 0)
6543                         goto fail_mmu_destroy;
6544         }
6545
6546         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
6547                                        GFP_KERNEL);
6548         if (!vcpu->arch.mce_banks) {
6549                 r = -ENOMEM;
6550                 goto fail_free_lapic;
6551         }
6552         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
6553
6554         if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
6555                 goto fail_free_mce_banks;
6556
6557         kvm_async_pf_hash_reset(vcpu);
6558
6559         return 0;
6560 fail_free_mce_banks:
6561         kfree(vcpu->arch.mce_banks);
6562 fail_free_lapic:
6563         kvm_free_lapic(vcpu);
6564 fail_mmu_destroy:
6565         kvm_mmu_destroy(vcpu);
6566 fail_free_pio_data:
6567         free_page((unsigned long)vcpu->arch.pio_data);
6568 fail:
6569         return r;
6570 }
6571
6572 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
6573 {
6574         int idx;
6575
6576         kfree(vcpu->arch.mce_banks);
6577         kvm_free_lapic(vcpu);
6578         idx = srcu_read_lock(&vcpu->kvm->srcu);
6579         kvm_mmu_destroy(vcpu);
6580         srcu_read_unlock(&vcpu->kvm->srcu, idx);
6581         free_page((unsigned long)vcpu->arch.pio_data);
6582 }
6583
6584 int kvm_arch_init_vm(struct kvm *kvm)
6585 {
6586         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6587         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
6588
6589         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
6590         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
6591
6592         raw_spin_lock_init(&kvm->arch.tsc_write_lock);
6593
6594         return 0;
6595 }
6596
6597 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
6598 {
6599         vcpu_load(vcpu);
6600         kvm_mmu_unload(vcpu);
6601         vcpu_put(vcpu);
6602 }
6603
6604 static void kvm_free_vcpus(struct kvm *kvm)
6605 {
6606         unsigned int i;
6607         struct kvm_vcpu *vcpu;
6608
6609         /*
6610          * Unpin any mmu pages first.
6611          */
6612         kvm_for_each_vcpu(i, vcpu, kvm) {
6613                 kvm_clear_async_pf_completion_queue(vcpu);
6614                 kvm_unload_vcpu_mmu(vcpu);
6615         }
6616         kvm_for_each_vcpu(i, vcpu, kvm)
6617                 kvm_arch_vcpu_free(vcpu);
6618
6619         mutex_lock(&kvm->lock);
6620         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
6621                 kvm->vcpus[i] = NULL;
6622
6623         atomic_set(&kvm->online_vcpus, 0);
6624         mutex_unlock(&kvm->lock);
6625 }
6626
6627 void kvm_arch_sync_events(struct kvm *kvm)
6628 {
6629         kvm_free_all_assigned_devices(kvm);
6630         kvm_free_pit(kvm);
6631 }
6632
6633 void kvm_arch_destroy_vm(struct kvm *kvm)
6634 {
6635         kvm_iommu_unmap_guest(kvm);
6636         kfree(kvm->arch.vpic);
6637         kfree(kvm->arch.vioapic);
6638         kvm_free_vcpus(kvm);
6639         if (kvm->arch.apic_access_page)
6640                 put_page(kvm->arch.apic_access_page);
6641         if (kvm->arch.ept_identity_pagetable)
6642                 put_page(kvm->arch.ept_identity_pagetable);
6643 }
6644
6645 int kvm_arch_prepare_memory_region(struct kvm *kvm,
6646                                 struct kvm_memory_slot *memslot,
6647                                 struct kvm_memory_slot old,
6648                                 struct kvm_userspace_memory_region *mem,
6649                                 int user_alloc)
6650 {
6651         int npages = memslot->npages;
6652         int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
6653
6654         /* Prevent internal slot pages from being moved by fork()/COW. */
6655         if (memslot->id >= KVM_MEMORY_SLOTS)
6656                 map_flags = MAP_SHARED | MAP_ANONYMOUS;
6657
6658         /*To keep backward compatibility with older userspace,
6659          *x86 needs to hanlde !user_alloc case.
6660          */
6661         if (!user_alloc) {
6662                 if (npages && !old.rmap) {
6663                         unsigned long userspace_addr;
6664
6665                         down_write(&current->mm->mmap_sem);
6666                         userspace_addr = do_mmap(NULL, 0,
6667                                                  npages * PAGE_SIZE,
6668                                                  PROT_READ | PROT_WRITE,
6669                                                  map_flags,
6670                                                  0);
6671                         up_write(&current->mm->mmap_sem);
6672
6673                         if (IS_ERR((void *)userspace_addr))
6674                                 return PTR_ERR((void *)userspace_addr);
6675
6676                         memslot->userspace_addr = userspace_addr;
6677                 }
6678         }
6679
6680
6681         return 0;
6682 }
6683
6684 void kvm_arch_commit_memory_region(struct kvm *kvm,
6685                                 struct kvm_userspace_memory_region *mem,
6686                                 struct kvm_memory_slot old,
6687                                 int user_alloc)
6688 {
6689
6690         int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
6691
6692         if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
6693                 int ret;
6694
6695                 down_write(&current->mm->mmap_sem);
6696                 ret = do_munmap(current->mm, old.userspace_addr,
6697                                 old.npages * PAGE_SIZE);
6698                 up_write(&current->mm->mmap_sem);
6699                 if (ret < 0)
6700                         printk(KERN_WARNING
6701                                "kvm_vm_ioctl_set_memory_region: "
6702                                "failed to munmap memory\n");
6703         }
6704
6705         if (!kvm->arch.n_requested_mmu_pages)
6706                 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
6707
6708         spin_lock(&kvm->mmu_lock);
6709         if (nr_mmu_pages)
6710                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
6711         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
6712         spin_unlock(&kvm->mmu_lock);
6713 }
6714
6715 void kvm_arch_flush_shadow(struct kvm *kvm)
6716 {
6717         kvm_mmu_zap_all(kvm);
6718         kvm_reload_remote_mmus(kvm);
6719 }
6720
6721 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
6722 {
6723         return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6724                 !vcpu->arch.apf.halted)
6725                 || !list_empty_careful(&vcpu->async_pf.done)
6726                 || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
6727                 || atomic_read(&vcpu->arch.nmi_queued) ||
6728                 (kvm_arch_interrupt_allowed(vcpu) &&
6729                  kvm_cpu_has_interrupt(vcpu));
6730 }
6731
6732 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
6733 {
6734         int me;
6735         int cpu = vcpu->cpu;
6736
6737         if (waitqueue_active(&vcpu->wq)) {
6738                 wake_up_interruptible(&vcpu->wq);
6739                 ++vcpu->stat.halt_wakeup;
6740         }
6741
6742         me = get_cpu();
6743         if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
6744                 if (kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE)
6745                         smp_send_reschedule(cpu);
6746         put_cpu();
6747 }
6748
6749 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
6750 {
6751         return kvm_x86_ops->interrupt_allowed(vcpu);
6752 }
6753
6754 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
6755 {
6756         unsigned long current_rip = kvm_rip_read(vcpu) +
6757                 get_segment_base(vcpu, VCPU_SREG_CS);
6758
6759         return current_rip == linear_rip;
6760 }
6761 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
6762
6763 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
6764 {
6765         unsigned long rflags;
6766
6767         rflags = kvm_x86_ops->get_rflags(vcpu);
6768         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6769                 rflags &= ~X86_EFLAGS_TF;
6770         return rflags;
6771 }
6772 EXPORT_SYMBOL_GPL(kvm_get_rflags);
6773
6774 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
6775 {
6776         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
6777             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
6778                 rflags |= X86_EFLAGS_TF;
6779         kvm_x86_ops->set_rflags(vcpu, rflags);
6780         kvm_make_request(KVM_REQ_EVENT, vcpu);
6781 }
6782 EXPORT_SYMBOL_GPL(kvm_set_rflags);
6783
6784 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
6785 {
6786         int r;
6787
6788         if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
6789               is_error_page(work->page))
6790                 return;
6791
6792         r = kvm_mmu_reload(vcpu);
6793         if (unlikely(r))
6794                 return;
6795
6796         if (!vcpu->arch.mmu.direct_map &&
6797               work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
6798                 return;
6799
6800         vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
6801 }
6802
6803 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
6804 {
6805         return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
6806 }
6807
6808 static inline u32 kvm_async_pf_next_probe(u32 key)
6809 {
6810         return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
6811 }
6812
6813 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6814 {
6815         u32 key = kvm_async_pf_hash_fn(gfn);
6816
6817         while (vcpu->arch.apf.gfns[key] != ~0)
6818                 key = kvm_async_pf_next_probe(key);
6819
6820         vcpu->arch.apf.gfns[key] = gfn;
6821 }
6822
6823 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
6824 {
6825         int i;
6826         u32 key = kvm_async_pf_hash_fn(gfn);
6827
6828         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
6829                      (vcpu->arch.apf.gfns[key] != gfn &&
6830                       vcpu->arch.apf.gfns[key] != ~0); i++)
6831                 key = kvm_async_pf_next_probe(key);
6832
6833         return key;
6834 }
6835
6836 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6837 {
6838         return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
6839 }
6840
6841 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
6842 {
6843         u32 i, j, k;
6844
6845         i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
6846         while (true) {
6847                 vcpu->arch.apf.gfns[i] = ~0;
6848                 do {
6849                         j = kvm_async_pf_next_probe(j);
6850                         if (vcpu->arch.apf.gfns[j] == ~0)
6851                                 return;
6852                         k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
6853                         /*
6854                          * k lies cyclically in ]i,j]
6855                          * |    i.k.j |
6856                          * |....j i.k.| or  |.k..j i...|
6857                          */
6858                 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
6859                 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
6860                 i = j;
6861         }
6862 }
6863
6864 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
6865 {
6866
6867         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
6868                                       sizeof(val));
6869 }
6870
6871 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
6872                                      struct kvm_async_pf *work)
6873 {
6874         struct x86_exception fault;
6875
6876         trace_kvm_async_pf_not_present(work->arch.token, work->gva);
6877         kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
6878
6879         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
6880             (vcpu->arch.apf.send_user_only &&
6881              kvm_x86_ops->get_cpl(vcpu) == 0))
6882                 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
6883         else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
6884                 fault.vector = PF_VECTOR;
6885                 fault.error_code_valid = true;
6886                 fault.error_code = 0;
6887                 fault.nested_page_fault = false;
6888                 fault.address = work->arch.token;
6889                 kvm_inject_page_fault(vcpu, &fault);
6890         }
6891 }
6892
6893 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
6894                                  struct kvm_async_pf *work)
6895 {
6896         struct x86_exception fault;
6897
6898         trace_kvm_async_pf_ready(work->arch.token, work->gva);
6899         if (is_error_page(work->page))
6900                 work->arch.token = ~0; /* broadcast wakeup */
6901         else
6902                 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
6903
6904         if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
6905             !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
6906                 fault.vector = PF_VECTOR;
6907                 fault.error_code_valid = true;
6908                 fault.error_code = 0;
6909                 fault.nested_page_fault = false;
6910                 fault.address = work->arch.token;
6911                 kvm_inject_page_fault(vcpu, &fault);
6912         }
6913         vcpu->arch.apf.halted = false;
6914 }
6915
6916 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
6917 {
6918         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
6919                 return true;
6920         else
6921                 return !kvm_event_needs_reinjection(vcpu) &&
6922                         kvm_x86_ops->interrupt_allowed(vcpu);
6923 }
6924
6925 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
6926 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
6927 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
6928 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
6929 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
6930 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
6931 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
6932 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
6933 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
6934 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
6935 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
6936 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);